ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / sound / oss / maestro.c
1 /*****************************************************************************
2  *
3  *      ESS Maestro/Maestro-2/Maestro-2E driver for Linux 2.[23].x
4  *
5  *      This program is free software; you can redistribute it and/or modify
6  *      it under the terms of the GNU General Public License as published by
7  *      the Free Software Foundation; either version 2 of the License, or
8  *      (at your option) any later version.
9  *
10  *      This program is distributed in the hope that it will be useful,
11  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *      GNU General Public License for more details.
14  *
15  *      You should have received a copy of the GNU General Public License
16  *      along with this program; if not, write to the Free Software
17  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  *      (c) Copyright 1999       Alan Cox <alan.cox@linux.org>
20  *
21  *      Based heavily on SonicVibes.c:
22  *      Copyright (C) 1998-1999  Thomas Sailer (sailer@ife.ee.ethz.ch)
23  *
24  *      Heavily modified by Zach Brown <zab@zabbo.net> based on lunch
25  *      with ESS engineers.  Many thanks to Howard Kim for providing 
26  *      contacts and hardware.  Honorable mention goes to Eric 
27  *      Brombaugh for all sorts of things.  Best regards to the 
28  *      proprietors of Hack Central for fine lodging.
29  *
30  *  Supported devices:
31  *  /dev/dsp0-3    standard /dev/dsp device, (mostly) OSS compatible
32  *  /dev/mixer  standard /dev/mixer device, (mostly) OSS compatible
33  *
34  *  Hardware Description
35  *
36  *      A working Maestro setup contains the Maestro chip wired to a 
37  *      codec or 2.  In the Maestro we have the APUs, the ASSP, and the
38  *      Wavecache.  The APUs can be though of as virtual audio routing
39  *      channels.  They can take data from a number of sources and perform
40  *      basic encodings of the data.  The wavecache is a storehouse for
41  *      PCM data.  Typically it deals with PCI and interracts with the
42  *      APUs.  The ASSP is a wacky DSP like device that ESS is loth
43  *      to release docs on.  Thankfully it isn't required on the Maestro
44  *      until you start doing insane things like FM emulation and surround
45  *      encoding.  The codecs are almost always AC-97 compliant codecs, 
46  *      but it appears that early Maestros may have had PT101 (an ESS
47  *      part?) wired to them.  The only real difference in the Maestro
48  *      families is external goop like docking capability, memory for
49  *      the ASSP, and initialization differences.
50  *
51  *  Driver Operation
52  *
53  *      We only drive the APU/Wavecache as typical DACs and drive the
54  *      mixers in the codecs.  There are 64 APUs.  We assign 6 to each
55  *      /dev/dsp? device.  2 channels for output, and 4 channels for
56  *      input.
57  *
58  *      Each APU can do a number of things, but we only really use
59  *      3 basic functions.  For playback we use them to convert PCM
60  *      data fetched over PCI by the wavecahche into analog data that
61  *      is handed to the codec.  One APU for mono, and a pair for stereo.
62  *      When in stereo, the combination of smarts in the APU and Wavecache
63  *      decide which wavecache gets the left or right channel.
64  *
65  *      For record we still use the old overly mono system.  For each in
66  *      coming channel the data comes in from the codec, through a 'input'
67  *      APU, through another rate converter APU, and then into memory via
68  *      the wavecache and PCI.  If its stereo, we mash it back into LRLR in
69  *      software.  The pass between the 2 APUs is supposedly what requires us
70  *      to have a 512 byte buffer sitting around in wavecache/memory.
71  *
72  *      The wavecache makes our life even more fun.  First off, it can
73  *      only address the first 28 bits of PCI address space, making it
74  *      useless on quite a few architectures.  Secondly, its insane.
75  *      It claims to fetch from 4 regions of PCI space, each 4 meg in length.
76  *      But that doesn't really work.  You can only use 1 region.  So all our
77  *      allocations have to be in 4meg of each other.  Booo.  Hiss.
78  *      So we have a module parameter, dsps_order, that is the order of
79  *      the number of dsps to provide.  All their buffer space is allocated
80  *      on open time.  The sonicvibes OSS routines we inherited really want
81  *      power of 2 buffers, so we have all those next to each other, then
82  *      512 byte regions for the recording wavecaches.  This ends up
83  *      wasting quite a bit of memory.  The only fixes I can see would be 
84  *      getting a kernel allocator that could work in zones, or figuring out
85  *      just how to coerce the WP into doing what we want.
86  *
87  *      The indirection of the various registers means we have to spinlock
88  *      nearly all register accesses.  We have the main register indirection
89  *      like the wave cache, maestro registers, etc.  Then we have beasts
90  *      like the APU interface that is indirect registers gotten at through
91  *      the main maestro indirection.  Ouch.  We spinlock around the actual
92  *      ports on a per card basis.  This means spinlock activity at each IO
93  *      operation, but the only IO operation clusters are in non critical 
94  *      paths and it makes the code far easier to follow.  Interrupts are
95  *      blocked while holding the locks because the int handler has to
96  *      get at some of them :(.  The mixer interface doesn't, however.
97  *      We also have an OSS state lock that is thrown around in a few
98  *      places.
99  *
100  *      This driver has brute force APM suspend support.  We catch suspend
101  *      notifications and stop all work being done on the chip.  Any people
102  *      that try between this shutdown and the real suspend operation will
103  *      be put to sleep.  When we resume we restore our software state on
104  *      the chip and wake up the people that were using it.  The code thats
105  *      being used now is quite dirty and assumes we're on a uni-processor
106  *      machine.  Much of it will need to be cleaned up for SMP ACPI or 
107  *      similar.
108  *
109  *      We also pay attention to PCI power management now.  The driver
110  *      will power down units of the chip that it knows aren't needed.
111  *      The WaveProcessor and company are only powered on when people
112  *      have /dev/dsp*s open.  On removal the driver will
113  *      power down the maestro entirely.  There could still be
114  *      trouble with BIOSen that magically change power states 
115  *      themselves, but we'll see.  
116  *      
117  * History
118  *  v0.15 - May 21 2001 - Marcus Meissner <mm@caldera.de>
119  *      Ported to Linux 2.4 PCI API. Some clean ups, global devs list
120  *      removed (now using pci device driver data).
121  *      PM needs to be polished still. Bumped version.
122  *  (still kind of v0.14) May 13 2001 - Ben Pfaff <pfaffben@msu.edu>
123  *      Add support for 978 docking and basic hardware volume control
124  *  (still kind of v0.14) Nov 23 - Alan Cox <alan@redhat.com>
125  *      Add clocking= for people with seriously warped hardware
126  *  (still v0.14) Nov 10 2000 - Bartlomiej Zolnierkiewicz <bkz@linux-ide.org>
127  *      add __init to maestro_ac97_init() and maestro_install()
128  *  (still based on v0.14) Mar 29 2000 - Zach Brown <zab@redhat.com>
129  *      move to 2.3 power management interface, which
130  *              required hacking some suspend/resume/check paths 
131  *      make static compilation work
132  *  v0.14 - Jan 28 2000 - Zach Brown <zab@redhat.com>
133  *      add PCI power management through ACPI regs.
134  *      we now shut down on machine reboot/halt
135  *      leave scary PCI config items alone (isa stuff, mostly)
136  *      enable 1921s, it seems only mine was broke.
137  *      fix swapped left/right pcm dac.  har har.
138  *      up bob freq, increase buffers, fix pointers at underflow
139  *      silly compilation problems
140  *  v0.13 - Nov 18 1999 - Zach Brown <zab@redhat.com>
141  *      fix nec Versas?  man would that be cool.
142  *  v0.12 - Nov 12 1999 - Zach Brown <zab@redhat.com>
143  *      brown bag volume max fix..
144  *  v0.11 - Nov 11 1999 - Zach Brown <zab@redhat.com>
145  *      use proper stereo apu decoding, mmap/write should work.
146  *      make volume sliders more useful, tweak rate calculation.
147  *      fix lame 8bit format reporting bug.  duh. apm apu saving buglet also
148  *      fix maestro 1 clock freq "bug", remove pt101 support
149  *  v0.10 - Oct 28 1999 - Zach Brown <zab@redhat.com>
150  *      aha, so, sometimes the WP writes a status word to offset 0
151  *        from one of the PCMBARs.  rearrange allocation accordingly..
152  *        cheers again to Eric for being a good hacker in investigating this.
153  *      Jeroen Hoogervorst submits 7500 fix out of nowhere.  yay.  :)
154  *  v0.09 - Oct 23 1999 - Zach Brown <zab@redhat.com>
155  *      added APM support.
156  *      re-order something such that some 2Es now work.  Magic!
157  *      new codec reset routine.  made some codecs come to life.
158  *      fix clear_advance, sync some control with ESS.
159  *      now write to all base regs to be paranoid.
160  *  v0.08 - Oct 20 1999 - Zach Brown <zab@redhat.com>
161  *      Fix initial buflen bug.  I am so smart.  also smp compiling..
162  *      I owe Eric yet another beer: fixed recmask, igain, 
163  *        muting, and adc sync consistency.  Go Team.
164  *  v0.07 - Oct 4 1999 - Zach Brown <zab@redhat.com>
165  *      tweak adc/dac, formating, and stuff to allow full duplex
166  *      allocate dsps memory at open() so we can fit in the wavecache window
167  *      fix wavecache braindamage.  again.  no more scribbling?
168  *      fix ess 1921 codec bug on some laptops.
169  *      fix dumb pci scanning bug
170  *      started 2.3 cleanup, redid spinlocks, little cleanups
171  *  v0.06 - Sep 20 1999 - Zach Brown <zab@redhat.com>
172  *      fix wavecache thinkos.  limit to 1 /dev/dsp.
173  *      eric is wearing his thinking toque this week.
174  *              spotted apu mode bugs and gain ramping problem
175  *      don't touch weird mixer regs, make recmask optional
176  *      fixed igain inversion, defaults for mixers, clean up rec_start
177  *      make mono recording work.
178  *      report subsystem stuff, please send reports.
179  *      littles: parallel out, amp now
180  *  v0.05 - Sep 17 1999 - Zach Brown <zab@redhat.com>
181  *      merged and fixed up Eric's initial recording code
182  *      munged format handling to catch misuse, needs rewrite.
183  *      revert ring bus init, fixup shared int, add pci busmaster setting
184  *      fix mixer oss interface, fix mic mute and recmask
185  *      mask off unsupported mixers, reset with all 1s, modularize defaults
186  *      make sure bob is running while we need it
187  *      got rid of device limit, initial minimal apm hooks
188  *      pull out dead code/includes, only allow multimedia/audio maestros
189  *  v0.04 - Sep 01 1999 - Zach Brown <zab@redhat.com>
190  *      copied memory leak fix from sonicvibes driver
191  *      different ac97 reset, play with 2.0 ac97, simplify ring bus setup
192  *      bob freq code, region sanity, jitter sync fix; all from Eric 
193  *
194  * TODO
195  *      fix bob frequency
196  *      endianness
197  *      do smart things with ac97 2.0 bits.
198  *      dual codecs
199  *      leave 54->61 open
200  *
201  *      it also would be fun to have a mode that would not use pci dma at all
202  *      but would copy into the wavecache on board memory and use that 
203  *      on architectures that don't like the maestro's pci dma ickiness.
204  */
205
206 /*****************************************************************************/
207
208 #include <linux/module.h>
209 #include <linux/sched.h>
210 #include <linux/smp_lock.h>
211 #include <linux/string.h>
212 #include <linux/ctype.h>
213 #include <linux/ioport.h>
214 #include <linux/delay.h>
215 #include <linux/sound.h>
216 #include <linux/slab.h>
217 #include <linux/soundcard.h>
218 #include <linux/pci.h>
219 #include <linux/spinlock.h>
220 #include <linux/init.h>
221 #include <linux/interrupt.h>
222 #include <linux/poll.h>
223 #include <linux/reboot.h>
224 #include <linux/bitops.h>
225 #include <linux/wait.h>
226
227 #include <asm/current.h>
228 #include <asm/dma.h>
229 #include <asm/io.h>
230 #include <asm/page.h>
231 #include <asm/uaccess.h>
232
233 #include <linux/pm.h>
234 static int maestro_pm_callback(struct pm_dev *dev, pm_request_t rqst, void *d);
235
236 #include "maestro.h"
237
238 static struct pci_driver maestro_pci_driver;
239
240 /* --------------------------------------------------------------------- */
241
242 #define M_DEBUG 1
243
244 #ifdef M_DEBUG
245 static int debug;
246 #define M_printk(args...) {if (debug) printk(args);}
247 #else
248 #define M_printk(x)
249 #endif
250
251 /* we try to setup 2^(dsps_order) /dev/dsp devices */
252 static int dsps_order;
253 /* whether or not we mess around with power management */
254 static int use_pm=2; /* set to 1 for force */
255 /* clocking for broken hardware - a few laptops seem to use a 50Khz clock
256         ie insmod with clocking=50000 or so */
257         
258 static int clocking=48000;
259
260 MODULE_AUTHOR("Zach Brown <zab@zabbo.net>, Alan Cox <alan@redhat.com>");
261 MODULE_DESCRIPTION("ESS Maestro Driver");
262 MODULE_LICENSE("GPL");
263
264 #ifdef M_DEBUG
265 MODULE_PARM(debug,"i");
266 #endif
267 MODULE_PARM(dsps_order,"i");
268 MODULE_PARM(use_pm,"i");
269 MODULE_PARM(clocking, "i");
270
271 /* --------------------------------------------------------------------- */
272 #define DRIVER_VERSION "0.15"
273
274 #ifndef PCI_VENDOR_ESS
275 #define PCI_VENDOR_ESS                  0x125D
276 #define PCI_DEVICE_ID_ESS_ESS1968       0x1968          /* Maestro 2    */
277 #define PCI_DEVICE_ID_ESS_ESS1978       0x1978          /* Maestro 2E   */
278
279 #define PCI_VENDOR_ESS_OLD              0x1285          /* Platform Tech, 
280                                                 the people the maestro 
281                                                 was bought from */
282 #define PCI_DEVICE_ID_ESS_ESS0100       0x0100          /* maestro 1 */
283 #endif /* PCI_VENDOR_ESS */
284
285 #define ESS_CHAN_HARD           0x100
286
287 /* NEC Versas ? */
288 #define NEC_VERSA_SUBID1        0x80581033
289 #define NEC_VERSA_SUBID2        0x803c1033
290
291
292 /* changed so that I could actually find all the
293         references and fix them up.  it's a little more readable now. */
294 #define ESS_FMT_STEREO  0x01
295 #define ESS_FMT_16BIT   0x02
296 #define ESS_FMT_MASK    0x03
297 #define ESS_DAC_SHIFT   0   
298 #define ESS_ADC_SHIFT   4
299
300 #define ESS_STATE_MAGIC         0x125D1968
301 #define ESS_CARD_MAGIC          0x19283746
302
303 #define DAC_RUNNING             1
304 #define ADC_RUNNING             2
305
306 #define MAX_DSP_ORDER   2
307 #define MAX_DSPS        (1<<MAX_DSP_ORDER)
308 #define NR_DSPS         (1<<dsps_order)
309 #define NR_IDRS         32
310
311 #define NR_APUS         64
312 #define NR_APU_REGS     16
313
314 /* acpi states */
315 enum {
316         ACPI_D0=0,
317         ACPI_D1,
318         ACPI_D2,
319         ACPI_D3
320 };
321
322 /* bits in the acpi masks */
323 #define ACPI_12MHZ      ( 1 << 15)
324 #define ACPI_24MHZ      ( 1 << 14)
325 #define ACPI_978        ( 1 << 13)
326 #define ACPI_SPDIF      ( 1 << 12)
327 #define ACPI_GLUE       ( 1 << 11)
328 #define ACPI__10        ( 1 << 10) /* reserved */
329 #define ACPI_PCIINT     ( 1 << 9)
330 #define ACPI_HV         ( 1 << 8) /* hardware volume */
331 #define ACPI_GPIO       ( 1 << 7)
332 #define ACPI_ASSP       ( 1 << 6)
333 #define ACPI_SB         ( 1 << 5) /* sb emul */
334 #define ACPI_FM         ( 1 << 4) /* fm emul */
335 #define ACPI_RB         ( 1 << 3) /* ringbus / aclink */
336 #define ACPI_MIDI       ( 1 << 2) 
337 #define ACPI_GP         ( 1 << 1) /* game port */
338 #define ACPI_WP         ( 1 << 0) /* wave processor */
339
340 #define ACPI_ALL        (0xffff)
341 #define ACPI_SLEEP      (~(ACPI_SPDIF|ACPI_ASSP|ACPI_SB|ACPI_FM| \
342                         ACPI_MIDI|ACPI_GP|ACPI_WP))
343 #define ACPI_NONE       (ACPI__10)
344
345 /* these masks indicate which units we care about at
346         which states */
347 u16 acpi_state_mask[] = {
348         [ACPI_D0] = ACPI_ALL,
349         [ACPI_D1] = ACPI_SLEEP,
350         [ACPI_D2] = ACPI_SLEEP,
351         [ACPI_D3] = ACPI_NONE
352 };
353
354 static char version[] __devinitdata =
355 KERN_INFO "maestro: version " DRIVER_VERSION " time " __TIME__ " " __DATE__ "\n";
356
357
358
359 static const unsigned sample_size[] = { 1, 2, 2, 4 };
360 static const unsigned sample_shift[] = { 0, 1, 1, 2 };
361
362 enum card_types_t {
363         TYPE_MAESTRO,
364         TYPE_MAESTRO2,
365         TYPE_MAESTRO2E
366 };
367
368 static const char *card_names[]={
369         [TYPE_MAESTRO] = "ESS Maestro",
370         [TYPE_MAESTRO2] = "ESS Maestro 2",
371         [TYPE_MAESTRO2E] = "ESS Maestro 2E"
372 };
373
374 static int clock_freq[]={
375         [TYPE_MAESTRO] = (49152000L / 1024L),
376         [TYPE_MAESTRO2] = (50000000L / 1024L),
377         [TYPE_MAESTRO2E] = (50000000L / 1024L)
378 };
379
380 static int maestro_notifier(struct notifier_block *nb, unsigned long event, void *buf);
381
382 static struct notifier_block maestro_nb = {maestro_notifier, NULL, 0};
383
384 /* --------------------------------------------------------------------- */
385
386 struct ess_state {
387         unsigned int magic;
388         /* FIXME: we probably want submixers in here, but only one record pair */
389         u8 apu[6];              /* l/r output, l/r intput converters, l/r input apus */
390         u8 apu_mode[6];         /* Running mode for this APU */
391         u8 apu_pan[6];          /* Panning setup for this APU */
392         u32 apu_base[6];        /* base address for this apu */
393         struct ess_card *card;  /* Card info */
394         /* wave stuff */
395         unsigned int rateadc, ratedac;
396         unsigned char fmt, enable;
397
398         int index;
399
400         /* this locks around the oss state in the driver */
401         spinlock_t lock;
402         /* only let 1 be opening at a time */
403         struct semaphore open_sem;
404         wait_queue_head_t open_wait;
405         mode_t open_mode;
406
407         /* soundcore stuff */
408         int dev_audio;
409
410         struct dmabuf {
411                 void *rawbuf;
412                 unsigned buforder;
413                 unsigned numfrag;
414                 unsigned fragshift;
415                 /* XXX zab - swptr only in here so that it can be referenced by
416                         clear_advance, as far as I can tell :( */
417                 unsigned hwptr, swptr;
418                 unsigned total_bytes;
419                 int count;
420                 unsigned error; /* over/underrun */
421                 wait_queue_head_t wait;
422                 /* redundant, but makes calculations easier */
423                 unsigned fragsize;
424                 unsigned dmasize;
425                 unsigned fragsamples;
426                 /* OSS stuff */
427                 unsigned mapped:1;
428                 unsigned ready:1;       /* our oss buffers are ready to go */
429                 unsigned endcleared:1;
430                 unsigned ossfragshift;
431                 int ossmaxfrags;
432                 unsigned subdivision;
433                 u16 base;               /* Offset for ptr */
434         } dma_dac, dma_adc;
435
436         /* pointer to each dsp?s piece of the apu->src buffer page */
437         void *mixbuf;
438
439 };
440         
441 struct ess_card {
442         unsigned int magic;
443
444         /* We keep maestro cards in a linked list */
445         struct ess_card *next;
446
447         int dev_mixer;
448
449         int card_type;
450
451         /* as most of this is static,
452                 perhaps it should be a pointer to a global struct */
453         struct mixer_goo {
454                 int modcnt;
455                 int supported_mixers;
456                 int stereo_mixers;
457                 int record_sources;
458                 /* the caller must guarantee arg sanity before calling these */
459 /*              int (*read_mixer)(struct ess_card *card, int index);*/
460                 void (*write_mixer)(struct ess_card *card,int mixer, unsigned int left,unsigned int right);
461                 int (*recmask_io)(struct ess_card *card,int rw,int mask);
462                 unsigned int mixer_state[SOUND_MIXER_NRDEVICES];
463         } mix;
464         
465         int power_regs;
466                 
467         int in_suspend;
468         wait_queue_head_t suspend_queue;
469
470         struct ess_state channels[MAX_DSPS];
471         u16 maestro_map[NR_IDRS];       /* Register map */
472         /* we have to store this junk so that we can come back from a
473                 suspend */
474         u16 apu_map[NR_APUS][NR_APU_REGS];      /* contents of apu regs */
475
476         /* this locks around the physical registers on the card */
477         spinlock_t lock;
478
479         /* memory for this card.. wavecache limited :(*/
480         void *dmapages;
481         int dmaorder;
482
483         /* hardware resources */
484         struct pci_dev *pcidev;
485         u32 iobase;
486         u32 irq;
487
488         int bob_freq;
489         char dsps_open;
490
491         int dock_mute_vol;
492 };
493
494 static void set_mixer(struct ess_card *card,unsigned int mixer, unsigned int val );
495
496 static unsigned 
497 ld2(unsigned int x)
498 {
499         unsigned r = 0;
500         
501         if (x >= 0x10000) {
502                 x >>= 16;
503                 r += 16;
504         }
505         if (x >= 0x100) {
506                 x >>= 8;
507                 r += 8;
508         }
509         if (x >= 0x10) {
510                 x >>= 4;
511                 r += 4;
512         }
513         if (x >= 4) {
514                 x >>= 2;
515                 r += 2;
516         }
517         if (x >= 2)
518                 r++;
519         return r;
520 }
521
522
523 /* --------------------------------------------------------------------- */
524
525 static void check_suspend(struct ess_card *card);
526
527 /* --------------------------------------------------------------------- */
528
529
530 /*
531  *      ESS Maestro AC97 codec programming interface.
532  */
533          
534 static void maestro_ac97_set(struct ess_card *card, u8 cmd, u16 val)
535 {
536         int io = card->iobase;
537         int i;
538         /*
539          *      Wait for the codec bus to be free 
540          */
541
542         check_suspend(card);
543          
544         for(i=0;i<10000;i++)
545         {
546                 if(!(inb(io+ESS_AC97_INDEX)&1)) 
547                         break;
548         }
549         /*
550          *      Write the bus
551          */ 
552         outw(val, io+ESS_AC97_DATA);
553         mdelay(1);
554         outb(cmd, io+ESS_AC97_INDEX);
555         mdelay(1);
556 }
557
558 static u16 maestro_ac97_get(struct ess_card *card, u8 cmd)
559 {
560         int io = card->iobase;
561         int sanity=10000;
562         u16 data;
563         int i;
564         
565         check_suspend(card);
566         /*
567          *      Wait for the codec bus to be free 
568          */
569          
570         for(i=0;i<10000;i++)
571         {
572                 if(!(inb(io+ESS_AC97_INDEX)&1))
573                         break;
574         }
575
576         outb(cmd|0x80, io+ESS_AC97_INDEX);
577         mdelay(1);
578         
579         while(inb(io+ESS_AC97_INDEX)&1)
580         {
581                 sanity--;
582                 if(!sanity)
583                 {
584                         printk(KERN_ERR "maestro: ac97 codec timeout reading 0x%x.\n",cmd);
585                         return 0;
586                 }
587         }
588         data=inw(io+ESS_AC97_DATA);
589         mdelay(1);
590         return data;
591 }
592
593 /* OSS interface to the ac97s.. */
594
595 #define AC97_STEREO_MASK (SOUND_MASK_VOLUME|\
596         SOUND_MASK_PCM|SOUND_MASK_LINE|SOUND_MASK_CD|\
597         SOUND_MASK_VIDEO|SOUND_MASK_LINE1|SOUND_MASK_IGAIN)
598
599 #define AC97_SUPPORTED_MASK (AC97_STEREO_MASK | \
600         SOUND_MASK_BASS|SOUND_MASK_TREBLE|SOUND_MASK_MIC|\
601         SOUND_MASK_SPEAKER)
602
603 #define AC97_RECORD_MASK (SOUND_MASK_MIC|\
604         SOUND_MASK_CD| SOUND_MASK_VIDEO| SOUND_MASK_LINE1| SOUND_MASK_LINE|\
605         SOUND_MASK_PHONEIN)
606
607 #define supported_mixer(CARD,FOO) ( CARD->mix.supported_mixers & (1<<FOO) )
608
609 /* this table has default mixer values for all OSS mixers.
610         be sure to fill it in if you add oss mixers
611         to anyone's supported mixer defines */
612
613  unsigned int mixer_defaults[SOUND_MIXER_NRDEVICES] = {
614         [SOUND_MIXER_VOLUME] =          0x3232,
615         [SOUND_MIXER_BASS] =            0x3232,
616         [SOUND_MIXER_TREBLE] =          0x3232,
617         [SOUND_MIXER_SPEAKER] =         0x3232,
618         [SOUND_MIXER_MIC] =     0x8000, /* annoying */
619         [SOUND_MIXER_LINE] =    0x3232,
620         [SOUND_MIXER_CD] =      0x3232,
621         [SOUND_MIXER_VIDEO] =   0x3232,
622         [SOUND_MIXER_LINE1] =   0x3232,
623         [SOUND_MIXER_PCM] =             0x3232,
624         [SOUND_MIXER_IGAIN] =           0x3232
625 };
626         
627 static struct ac97_mixer_hw {
628         unsigned char offset;
629         int scale;
630 } ac97_hw[SOUND_MIXER_NRDEVICES]= {
631         [SOUND_MIXER_VOLUME]    =       {0x02,63},
632         [SOUND_MIXER_BASS]      =       {0x08,15},
633         [SOUND_MIXER_TREBLE]    =       {0x08,15},
634         [SOUND_MIXER_SPEAKER]   =       {0x0a,15},
635         [SOUND_MIXER_MIC]       =       {0x0e,31},
636         [SOUND_MIXER_LINE]      =       {0x10,31},
637         [SOUND_MIXER_CD]        =       {0x12,31},
638         [SOUND_MIXER_VIDEO]     =       {0x14,31},
639         [SOUND_MIXER_LINE1]     =       {0x16,31},
640         [SOUND_MIXER_PCM]       =       {0x18,31},
641         [SOUND_MIXER_IGAIN]     =       {0x1c,15}
642 };
643
644 #if 0 /* *shrug* removed simply because we never used it.
645                 feel free to implement again if needed */
646
647 /* reads the given OSS mixer from the ac97
648         the caller must have insured that the ac97 knows
649         about that given mixer, and should be holding a
650         spinlock for the card */
651 static int ac97_read_mixer(struct ess_card *card, int mixer) 
652 {
653         u16 val;
654         int ret=0;
655         struct ac97_mixer_hw *mh = &ac97_hw[mixer];
656
657         val = maestro_ac97_get(card, mh->offset);
658
659         if(AC97_STEREO_MASK & (1<<mixer)) {
660                 /* nice stereo mixers .. */
661                 int left,right;
662
663                 left = (val >> 8)  & 0x7f;
664                 right = val  & 0x7f;
665
666                 if (mixer == SOUND_MIXER_IGAIN) {
667                         right = (right * 100) / mh->scale;
668                         left = (left * 100) / mh->scale;
669                 } else {
670                         right = 100 - ((right * 100) / mh->scale);
671                         left = 100 - ((left * 100) / mh->scale);
672                 }
673
674                 ret = left | (right << 8);
675         } else if (mixer == SOUND_MIXER_SPEAKER) {
676                 ret = 100 - ((((val & 0x1e)>>1) * 100) / mh->scale);
677         } else if (mixer == SOUND_MIXER_MIC) {
678                 ret = 100 - (((val & 0x1f) * 100) / mh->scale);
679         /*  the low bit is optional in the tone sliders and masking
680                 it lets is avoid the 0xf 'bypass'.. */
681         } else if (mixer == SOUND_MIXER_BASS) {
682                 ret = 100 - ((((val >> 8) & 0xe) * 100) / mh->scale);
683         } else if (mixer == SOUND_MIXER_TREBLE) {
684                 ret = 100 - (((val & 0xe) * 100) / mh->scale);
685         }
686
687         M_printk("read mixer %d (0x%x) %x -> %x\n",mixer,mh->offset,val,ret);
688
689         return ret;
690 }
691 #endif
692
693 /* write the OSS encoded volume to the given OSS encoded mixer,
694         again caller's job to make sure all is well in arg land,
695         call with spinlock held */
696         
697 /* linear scale -> log */
698 static unsigned char lin2log[101] = 
699 {
700 0, 0 , 15 , 23 , 30 , 34 , 38 , 42 , 45 , 47 ,
701 50 , 52 , 53 , 55 , 57 , 58 , 60 , 61 , 62 ,
702 63 , 65 , 66 , 67 , 68 , 69 , 69 , 70 , 71 ,
703 72 , 73 , 73 , 74 , 75 , 75 , 76 , 77 , 77 ,
704 78 , 78 , 79 , 80 , 80 , 81 , 81 , 82 , 82 ,
705 83 , 83 , 84 , 84 , 84 , 85 , 85 , 86 , 86 ,
706 87 , 87 , 87 , 88 , 88 , 88 , 89 , 89 , 89 ,
707 90 , 90 , 90 , 91 , 91 , 91 , 92 , 92 , 92 ,
708 93 , 93 , 93 , 94 , 94 , 94 , 94 , 95 , 95 ,
709 95 , 95 , 96 , 96 , 96 , 96 , 97 , 97 , 97 ,
710 97 , 98 , 98 , 98 , 98 , 99 , 99 , 99 , 99 , 99 
711 };
712
713 static void ac97_write_mixer(struct ess_card *card,int mixer, unsigned int left, unsigned int right)
714 {
715         u16 val=0;
716         struct ac97_mixer_hw *mh = &ac97_hw[mixer];
717
718         M_printk("wrote mixer %d (0x%x) %d,%d",mixer,mh->offset,left,right);
719
720         if(AC97_STEREO_MASK & (1<<mixer)) {
721                 /* stereo mixers, mute them if we can */
722
723                 if (mixer == SOUND_MIXER_IGAIN) {
724                         /* igain's slider is reversed.. */
725                         right = (right * mh->scale) / 100;
726                         left = (left * mh->scale) / 100;
727                         if ((left == 0) && (right == 0))
728                                 val |= 0x8000;
729                 } else if (mixer == SOUND_MIXER_PCM || mixer == SOUND_MIXER_CD) {
730                         /* log conversion seems bad for them */
731                         if ((left == 0) && (right == 0))
732                                 val = 0x8000;
733                         right = ((100 - right) * mh->scale) / 100;
734                         left = ((100 - left) * mh->scale) / 100;
735                 } else {
736                         /* log conversion for the stereo controls */
737                         if((left == 0) && (right == 0))
738                                 val = 0x8000;
739                         right = ((100 - lin2log[right]) * mh->scale) / 100;
740                         left = ((100 - lin2log[left]) * mh->scale) / 100;
741                 }
742
743                 val |= (left << 8) | right;
744
745         } else if (mixer == SOUND_MIXER_SPEAKER) {
746                 val = (((100 - left) * mh->scale) / 100) << 1;
747         } else if (mixer == SOUND_MIXER_MIC) {
748                 val = maestro_ac97_get(card, mh->offset) & ~0x801f;
749                 val |= (((100 - left) * mh->scale) / 100);
750         /*  the low bit is optional in the tone sliders and masking
751                 it lets is avoid the 0xf 'bypass'.. */
752         } else if (mixer == SOUND_MIXER_BASS) {
753                 val = maestro_ac97_get(card , mh->offset) & ~0x0f00;
754                 val |= ((((100 - left) * mh->scale) / 100) << 8) & 0x0e00;
755         } else if (mixer == SOUND_MIXER_TREBLE)  {
756                 val = maestro_ac97_get(card , mh->offset) & ~0x000f;
757                 val |= (((100 - left) * mh->scale) / 100) & 0x000e;
758         }
759
760         maestro_ac97_set(card , mh->offset, val);
761         
762         M_printk(" -> %x\n",val);
763 }
764
765 /* the following tables allow us to go from 
766         OSS <-> ac97 quickly. */
767
768 enum ac97_recsettings {
769         AC97_REC_MIC=0,
770         AC97_REC_CD,
771         AC97_REC_VIDEO,
772         AC97_REC_AUX,
773         AC97_REC_LINE,
774         AC97_REC_STEREO, /* combination of all enabled outputs..  */
775         AC97_REC_MONO,        /*.. or the mono equivalent */
776         AC97_REC_PHONE        
777 };
778
779 static unsigned int ac97_oss_mask[] = {
780         [AC97_REC_MIC] = SOUND_MASK_MIC, 
781         [AC97_REC_CD] = SOUND_MASK_CD, 
782         [AC97_REC_VIDEO] = SOUND_MASK_VIDEO, 
783         [AC97_REC_AUX] = SOUND_MASK_LINE1, 
784         [AC97_REC_LINE] = SOUND_MASK_LINE, 
785         [AC97_REC_PHONE] = SOUND_MASK_PHONEIN
786 };
787
788 /* indexed by bit position */
789 static unsigned int ac97_oss_rm[] = {
790         [SOUND_MIXER_MIC] = AC97_REC_MIC,
791         [SOUND_MIXER_CD] = AC97_REC_CD,
792         [SOUND_MIXER_VIDEO] = AC97_REC_VIDEO,
793         [SOUND_MIXER_LINE1] = AC97_REC_AUX,
794         [SOUND_MIXER_LINE] = AC97_REC_LINE,
795         [SOUND_MIXER_PHONEIN] = AC97_REC_PHONE
796 };
797         
798 /* read or write the recmask 
799         the ac97 can really have left and right recording
800         inputs independently set, but OSS doesn't seem to 
801         want us to express that to the user. 
802         the caller guarantees that we have a supported bit set,
803         and they must be holding the card's spinlock */
804 static int 
805 ac97_recmask_io(struct ess_card *card, int read, int mask) 
806 {
807         unsigned int val = ac97_oss_mask[ maestro_ac97_get(card, 0x1a) & 0x7 ];
808
809         if (read) return val;
810
811         /* oss can have many inputs, maestro can't.  try
812                 to pick the 'new' one */
813
814         if (mask != val) mask &= ~val;
815
816         val = ffs(mask) - 1; 
817         val = ac97_oss_rm[val];
818         val |= val << 8;  /* set both channels */
819
820         M_printk("maestro: setting ac97 recmask to 0x%x\n",val);
821
822         maestro_ac97_set(card,0x1a,val);
823
824         return 0;
825 };
826
827 /*
828  *      The Maestro can be wired to a standard AC97 compliant codec
829  *      (see www.intel.com for the pdf's on this), or to a PT101 codec
830  *      which appears to be the ES1918 (data sheet on the esstech.com.tw site)
831  *
832  *      The PT101 setup is untested.
833  */
834  
835 static u16 __init maestro_ac97_init(struct ess_card *card)
836 {
837         u16 vend1, vend2, caps;
838
839         card->mix.supported_mixers = AC97_SUPPORTED_MASK;
840         card->mix.stereo_mixers = AC97_STEREO_MASK;
841         card->mix.record_sources = AC97_RECORD_MASK;
842 /*      card->mix.read_mixer = ac97_read_mixer;*/
843         card->mix.write_mixer = ac97_write_mixer;
844         card->mix.recmask_io = ac97_recmask_io;
845
846         vend1 = maestro_ac97_get(card, 0x7c);
847         vend2 = maestro_ac97_get(card, 0x7e);
848
849         caps = maestro_ac97_get(card, 0x00);
850
851         printk(KERN_INFO "maestro: AC97 Codec detected: v: 0x%2x%2x caps: 0x%x pwr: 0x%x\n",
852                 vend1,vend2,caps,maestro_ac97_get(card,0x26) & 0xf);
853
854         if (! (caps & 0x4) ) {
855                 /* no bass/treble nobs */
856                 card->mix.supported_mixers &= ~(SOUND_MASK_BASS|SOUND_MASK_TREBLE);
857         }
858
859         /* XXX endianness, dork head. */
860         /* vendor specifc bits.. */
861         switch ((long)(vend1 << 16) | vend2) {
862         case 0x545200ff:        /* TriTech */
863                 /* no idea what this does */
864                 maestro_ac97_set(card,0x2a,0x0001);
865                 maestro_ac97_set(card,0x2c,0x0000);
866                 maestro_ac97_set(card,0x2c,0xffff);
867                 break;
868 #if 0   /* i thought the problems I was seeing were with
869         the 1921, but apparently they were with the pci board
870         it was on, so this code is commented out.
871          lets see if this holds true. */
872         case 0x83847609:        /* ESS 1921 */
873                 /* writing to 0xe (mic) or 0x1a (recmask) seems
874                         to hang this codec */
875                 card->mix.supported_mixers &= ~(SOUND_MASK_MIC);
876                 card->mix.record_sources = 0;
877                 card->mix.recmask_io = NULL;
878 #if 0   /* don't ask.  I have yet to see what these actually do. */
879                 maestro_ac97_set(card,0x76,0xABBA); /* o/~ Take a chance on me o/~ */
880                 udelay(20);
881                 maestro_ac97_set(card,0x78,0x3002);
882                 udelay(20);
883                 maestro_ac97_set(card,0x78,0x3802);
884                 udelay(20);
885 #endif
886                 break;
887 #endif
888         default: break;
889         }
890
891         maestro_ac97_set(card, 0x1E, 0x0404);
892         /* null misc stuff */
893         maestro_ac97_set(card, 0x20, 0x0000);
894
895         return 0;
896 }
897
898 #if 0  /* there has been 1 person on the planet with a pt101 that we
899         know of.  If they care, they can put this back in :) */
900 static u16 maestro_pt101_init(struct ess_card *card,int iobase)
901 {
902         printk(KERN_INFO "maestro: PT101 Codec detected, initializing but _not_ installing mixer device.\n");
903         /* who knows.. */
904         maestro_ac97_set(iobase, 0x2A, 0x0001);
905         maestro_ac97_set(iobase, 0x2C, 0x0000);
906         maestro_ac97_set(iobase, 0x2C, 0xFFFF);
907         maestro_ac97_set(iobase, 0x10, 0x9F1F);
908         maestro_ac97_set(iobase, 0x12, 0x0808);
909         maestro_ac97_set(iobase, 0x14, 0x9F1F);
910         maestro_ac97_set(iobase, 0x16, 0x9F1F);
911         maestro_ac97_set(iobase, 0x18, 0x0404);
912         maestro_ac97_set(iobase, 0x1A, 0x0000);
913         maestro_ac97_set(iobase, 0x1C, 0x0000);
914         maestro_ac97_set(iobase, 0x02, 0x0404);
915         maestro_ac97_set(iobase, 0x04, 0x0808);
916         maestro_ac97_set(iobase, 0x0C, 0x801F);
917         maestro_ac97_set(iobase, 0x0E, 0x801F);
918         return 0;
919 }
920 #endif
921
922 /* this is very magic, and very slow.. */
923 static void 
924 maestro_ac97_reset(int ioaddr, struct pci_dev *pcidev)
925 {
926         u16 save_68;
927         u16 w;
928         u32 vend;
929
930         outw( inw(ioaddr + 0x38) & 0xfffc, ioaddr + 0x38);
931         outw( inw(ioaddr + 0x3a) & 0xfffc, ioaddr + 0x3a);
932         outw( inw(ioaddr + 0x3c) & 0xfffc, ioaddr + 0x3c);
933
934         /* reset the first codec */
935         outw(0x0000,  ioaddr+0x36);
936         save_68 = inw(ioaddr+0x68);
937         pci_read_config_word(pcidev, 0x58, &w); /* something magical with gpio and bus arb. */
938         pci_read_config_dword(pcidev, PCI_SUBSYSTEM_VENDOR_ID, &vend);
939         if( w & 0x1)
940                 save_68 |= 0x10;
941         outw(0xfffe, ioaddr + 0x64);    /* tickly gpio 0.. */
942         outw(0x0001, ioaddr + 0x68);
943         outw(0x0000, ioaddr + 0x60);
944         udelay(20);
945         outw(0x0001, ioaddr + 0x60);
946         mdelay(20);
947
948         outw(save_68 | 0x1, ioaddr + 0x68);     /* now restore .. */
949         outw( (inw(ioaddr + 0x38) & 0xfffc)|0x1, ioaddr + 0x38);
950         outw( (inw(ioaddr + 0x3a) & 0xfffc)|0x1, ioaddr + 0x3a);
951         outw( (inw(ioaddr + 0x3c) & 0xfffc)|0x1, ioaddr + 0x3c);
952
953         /* now the second codec */
954         outw(0x0000,  ioaddr+0x36);
955         outw(0xfff7, ioaddr + 0x64);
956         save_68 = inw(ioaddr+0x68);
957         outw(0x0009, ioaddr + 0x68);
958         outw(0x0001, ioaddr + 0x60);
959         udelay(20);
960         outw(0x0009, ioaddr + 0x60);
961         mdelay(500);    /* .. ouch.. */
962         outw( inw(ioaddr + 0x38) & 0xfffc, ioaddr + 0x38);
963         outw( inw(ioaddr + 0x3a) & 0xfffc, ioaddr + 0x3a);
964         outw( inw(ioaddr + 0x3c) & 0xfffc, ioaddr + 0x3c);
965
966 #if 0 /* the loop here needs to be much better if we want it.. */
967         M_printk("trying software reset\n");
968         /* try and do a software reset */
969         outb(0x80|0x7c, ioaddr + 0x30);
970         for (w=0; ; w++) {
971                 if ((inw(ioaddr+ 0x30) & 1) == 0) {
972                         if(inb(ioaddr + 0x32) !=0) break;
973
974                         outb(0x80|0x7d, ioaddr + 0x30);
975                         if (((inw(ioaddr+ 0x30) & 1) == 0) && (inb(ioaddr + 0x32) !=0)) break;
976                         outb(0x80|0x7f, ioaddr + 0x30);
977                         if (((inw(ioaddr+ 0x30) & 1) == 0) && (inb(ioaddr + 0x32) !=0)) break;
978                 }
979
980                 if( w > 10000) {
981                         outb( inb(ioaddr + 0x37) | 0x08, ioaddr + 0x37);  /* do a software reset */
982                         mdelay(500); /* oh my.. */
983                         outb( inb(ioaddr + 0x37) & ~0x08, ioaddr + 0x37);  
984                         udelay(1);
985                         outw( 0x80, ioaddr+0x30);
986                         for(w = 0 ; w < 10000; w++) {
987                                 if((inw(ioaddr + 0x30) & 1) ==0) break;
988                         }
989                 }
990         }
991 #endif
992         if ( vend == NEC_VERSA_SUBID1 || vend == NEC_VERSA_SUBID2) {
993                 /* turn on external amp? */
994                 outw(0xf9ff, ioaddr + 0x64);
995                 outw(inw(ioaddr+0x68) | 0x600, ioaddr + 0x68);
996                 outw(0x0209, ioaddr + 0x60);
997         }
998
999         /* Turn on the 978 docking chip.
1000            First frob the "master output enable" bit,
1001            then set most of the playback volume control registers to max. */
1002         outb(inb(ioaddr+0xc0)|(1<<5), ioaddr+0xc0);
1003         outb(0xff, ioaddr+0xc3);
1004         outb(0xff, ioaddr+0xc4);
1005         outb(0xff, ioaddr+0xc6);
1006         outb(0xff, ioaddr+0xc8);
1007         outb(0x3f, ioaddr+0xcf);
1008         outb(0x3f, ioaddr+0xd0);
1009 }
1010 /*
1011  *      Indirect register access. Not all registers are readable so we
1012  *      need to keep register state ourselves
1013  */
1014  
1015 #define WRITEABLE_MAP   0xEFFFFF
1016 #define READABLE_MAP    0x64003F
1017
1018 /*
1019  *      The Maestro engineers were a little indirection happy. These indirected
1020  *      registers themselves include indirect registers at another layer
1021  */
1022
1023 static void __maestro_write(struct ess_card *card, u16 reg, u16 data)
1024 {
1025         long ioaddr = card->iobase;
1026
1027         outw(reg, ioaddr+0x02);
1028         outw(data, ioaddr+0x00);
1029         if( reg >= NR_IDRS) printk("maestro: IDR %d out of bounds!\n",reg);
1030         else card->maestro_map[reg]=data;
1031
1032 }
1033  
1034 static void maestro_write(struct ess_state *s, u16 reg, u16 data)
1035 {
1036         unsigned long flags;
1037
1038         check_suspend(s->card);
1039         spin_lock_irqsave(&s->card->lock,flags);
1040
1041         __maestro_write(s->card,reg,data);
1042
1043         spin_unlock_irqrestore(&s->card->lock,flags);
1044 }
1045
1046 static u16 __maestro_read(struct ess_card *card, u16 reg)
1047 {
1048         long ioaddr = card->iobase;
1049
1050         outw(reg, ioaddr+0x02);
1051         return card->maestro_map[reg]=inw(ioaddr+0x00);
1052 }
1053
1054 static u16 maestro_read(struct ess_state *s, u16 reg)
1055 {
1056         if(READABLE_MAP & (1<<reg))
1057         {
1058                 unsigned long flags;
1059                 check_suspend(s->card);
1060                 spin_lock_irqsave(&s->card->lock,flags);
1061
1062                 __maestro_read(s->card,reg);
1063
1064                 spin_unlock_irqrestore(&s->card->lock,flags);
1065         }
1066         return s->card->maestro_map[reg];
1067 }
1068
1069 /*
1070  *      These routines handle accessing the second level indirections to the
1071  *      wave ram.
1072  */
1073
1074 /*
1075  *      The register names are the ones ESS uses (see 104T31.ZIP)
1076  */
1077  
1078 #define IDR0_DATA_PORT          0x00
1079 #define IDR1_CRAM_POINTER       0x01
1080 #define IDR2_CRAM_DATA          0x02
1081 #define IDR3_WAVE_DATA          0x03
1082 #define IDR4_WAVE_PTR_LOW       0x04
1083 #define IDR5_WAVE_PTR_HI        0x05
1084 #define IDR6_TIMER_CTRL         0x06
1085 #define IDR7_WAVE_ROMRAM        0x07
1086
1087 static void apu_index_set(struct ess_card *card, u16 index)
1088 {
1089         int i;
1090         __maestro_write(card, IDR1_CRAM_POINTER, index);
1091         for(i=0;i<1000;i++)
1092                 if(__maestro_read(card, IDR1_CRAM_POINTER)==index)
1093                         return;
1094         printk(KERN_WARNING "maestro: APU register select failed.\n");
1095 }
1096
1097 static void apu_data_set(struct ess_card *card, u16 data)
1098 {
1099         int i;
1100         for(i=0;i<1000;i++)
1101         {
1102                 if(__maestro_read(card, IDR0_DATA_PORT)==data)
1103                         return;
1104                 __maestro_write(card, IDR0_DATA_PORT, data);
1105         }
1106 }
1107
1108 /*
1109  *      This is the public interface for APU manipulation. It handles the
1110  *      interlock to avoid two APU writes in parallel etc. Don't diddle
1111  *      directly with the stuff above.
1112  */
1113
1114 static void apu_set_register(struct ess_state *s, u16 channel, u8 reg, u16 data)
1115 {
1116         unsigned long flags;
1117         
1118         check_suspend(s->card);
1119
1120         if(channel&ESS_CHAN_HARD)
1121                 channel&=~ESS_CHAN_HARD;
1122         else
1123         {
1124                 if(channel>5)
1125                         printk("BAD CHANNEL %d.\n",channel);
1126                 else
1127                         channel = s->apu[channel];
1128                 /* store based on real hardware apu/reg */
1129                 s->card->apu_map[channel][reg]=data;
1130         }
1131         reg|=(channel<<4);
1132         
1133         /* hooray for double indirection!! */
1134         spin_lock_irqsave(&s->card->lock,flags);
1135
1136         apu_index_set(s->card, reg);
1137         apu_data_set(s->card, data);
1138
1139         spin_unlock_irqrestore(&s->card->lock,flags);
1140 }
1141
1142 static u16 apu_get_register(struct ess_state *s, u16 channel, u8 reg)
1143 {
1144         unsigned long flags;
1145         u16 v;
1146         
1147         check_suspend(s->card);
1148
1149         if(channel&ESS_CHAN_HARD)
1150                 channel&=~ESS_CHAN_HARD;
1151         else
1152                 channel = s->apu[channel];
1153
1154         reg|=(channel<<4);
1155         
1156         spin_lock_irqsave(&s->card->lock,flags);
1157
1158         apu_index_set(s->card, reg);
1159         v=__maestro_read(s->card, IDR0_DATA_PORT);
1160
1161         spin_unlock_irqrestore(&s->card->lock,flags);
1162         return v;
1163 }
1164
1165
1166 /*
1167  *      The wavecache buffers between the APUs and
1168  *      pci bus mastering
1169  */
1170  
1171 static void wave_set_register(struct ess_state *s, u16 reg, u16 value)
1172 {
1173         long ioaddr = s->card->iobase;
1174         unsigned long flags;
1175         check_suspend(s->card);
1176         
1177         spin_lock_irqsave(&s->card->lock,flags);
1178
1179         outw(reg, ioaddr+0x10);
1180         outw(value, ioaddr+0x12);
1181
1182         spin_unlock_irqrestore(&s->card->lock,flags);
1183 }
1184
1185 static u16 wave_get_register(struct ess_state *s, u16 reg)
1186 {
1187         long ioaddr = s->card->iobase;
1188         unsigned long flags;
1189         u16 value;
1190         check_suspend(s->card);
1191         
1192         spin_lock_irqsave(&s->card->lock,flags);
1193         outw(reg, ioaddr+0x10);
1194         value=inw(ioaddr+0x12);
1195         spin_unlock_irqrestore(&s->card->lock,flags);
1196         
1197         return value;
1198 }
1199
1200 static void sound_reset(int ioaddr)
1201 {
1202         outw(0x2000, 0x18+ioaddr);
1203         udelay(1);
1204         outw(0x0000, 0x18+ioaddr);
1205         udelay(1);
1206 }
1207
1208 /* sets the play formats of these apus, should be passed the already shifted format */
1209 static void set_apu_fmt(struct ess_state *s, int apu, int mode)
1210 {
1211         int apu_fmt = 0x10;
1212
1213         if(!(mode&ESS_FMT_16BIT)) apu_fmt+=0x20; 
1214         if((mode&ESS_FMT_STEREO)) apu_fmt+=0x10; 
1215         s->apu_mode[apu]   = apu_fmt;
1216         s->apu_mode[apu+1] = apu_fmt;
1217 }
1218
1219 /* this only fixes the output apu mode to be later set by start_dac and
1220         company.  output apu modes are set in ess_rec_setup */
1221 static void set_fmt(struct ess_state *s, unsigned char mask, unsigned char data)
1222 {
1223         s->fmt = (s->fmt & mask) | data;
1224         set_apu_fmt(s, 0, (s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK);
1225 }
1226
1227 /* this is off by a little bit.. */
1228 static u32 compute_rate(struct ess_state *s, u32 freq)
1229 {
1230         u32 clock = clock_freq[s->card->card_type];     
1231
1232         freq = (freq * clocking)/48000;
1233         
1234         if (freq == 48000) 
1235                 return 0x10000;
1236
1237         return ((freq / clock) <<16 )+  
1238                 (((freq % clock) << 16) / clock);
1239 }
1240
1241 static void set_dac_rate(struct ess_state *s, unsigned int rate)
1242 {
1243         u32 freq;
1244         int fmt = (s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK;
1245
1246         if (rate > 48000)
1247                 rate = 48000;
1248         if (rate < 4000)
1249                 rate = 4000;
1250
1251         s->ratedac = rate;
1252
1253         if(! (fmt & ESS_FMT_16BIT) && !(fmt & ESS_FMT_STEREO))
1254                 rate >>= 1;
1255
1256 /*      M_printk("computing dac rate %d with mode %d\n",rate,s->fmt);*/
1257
1258         freq = compute_rate(s, rate);
1259         
1260         /* Load the frequency, turn on 6dB */
1261         apu_set_register(s, 0, 2,(apu_get_register(s, 0, 2)&0x00FF)|
1262                 ( ((freq&0xFF)<<8)|0x10 ));
1263         apu_set_register(s, 0, 3, freq>>8);
1264         apu_set_register(s, 1, 2,(apu_get_register(s, 1, 2)&0x00FF)|
1265                 ( ((freq&0xFF)<<8)|0x10 ));
1266         apu_set_register(s, 1, 3, freq>>8);
1267 }
1268
1269 static void set_adc_rate(struct ess_state *s, unsigned rate)
1270 {
1271         u32 freq;
1272
1273         /* Sample Rate conversion APUs don't like 0x10000 for their rate */
1274         if (rate > 47999)
1275                 rate = 47999;
1276         if (rate < 4000)
1277                 rate = 4000;
1278
1279         s->rateadc = rate;
1280
1281         freq = compute_rate(s, rate);
1282         
1283         /* Load the frequency, turn on 6dB */
1284         apu_set_register(s, 2, 2,(apu_get_register(s, 2, 2)&0x00FF)|
1285                 ( ((freq&0xFF)<<8)|0x10 ));
1286         apu_set_register(s, 2, 3, freq>>8);
1287         apu_set_register(s, 3, 2,(apu_get_register(s, 3, 2)&0x00FF)|
1288                 ( ((freq&0xFF)<<8)|0x10 ));
1289         apu_set_register(s, 3, 3, freq>>8);
1290
1291         /* fix mixer rate at 48khz.  and its _must_ be 0x10000. */
1292         freq = 0x10000;
1293
1294         apu_set_register(s, 4, 2,(apu_get_register(s, 4, 2)&0x00FF)|
1295                 ( ((freq&0xFF)<<8)|0x10 ));
1296         apu_set_register(s, 4, 3, freq>>8);
1297         apu_set_register(s, 5, 2,(apu_get_register(s, 5, 2)&0x00FF)|
1298                 ( ((freq&0xFF)<<8)|0x10 ));
1299         apu_set_register(s, 5, 3, freq>>8);
1300 }
1301
1302 /* Stop our host of recording apus */
1303 static inline void stop_adc(struct ess_state *s)
1304 {
1305         /* XXX lets hope we don't have to lock around this */
1306         if (! (s->enable & ADC_RUNNING)) return;
1307
1308         s->enable &= ~ADC_RUNNING;
1309         apu_set_register(s, 2, 0, apu_get_register(s, 2, 0)&0xFF0F);
1310         apu_set_register(s, 3, 0, apu_get_register(s, 3, 0)&0xFF0F);
1311         apu_set_register(s, 4, 0, apu_get_register(s, 2, 0)&0xFF0F);
1312         apu_set_register(s, 5, 0, apu_get_register(s, 3, 0)&0xFF0F);
1313 }       
1314
1315 /* stop output apus */
1316 static void stop_dac(struct ess_state *s)
1317 {
1318         /* XXX have to lock around this? */
1319         if (! (s->enable & DAC_RUNNING)) return;
1320
1321         s->enable &= ~DAC_RUNNING;
1322         apu_set_register(s, 0, 0, apu_get_register(s, 0, 0)&0xFF0F);
1323         apu_set_register(s, 1, 0, apu_get_register(s, 1, 0)&0xFF0F);
1324 }       
1325
1326 static void start_dac(struct ess_state *s)
1327 {
1328         /* XXX locks? */
1329         if (    (s->dma_dac.mapped || s->dma_dac.count > 0) && 
1330                 s->dma_dac.ready &&
1331                 (! (s->enable & DAC_RUNNING)) ) {
1332
1333                 s->enable |= DAC_RUNNING;
1334
1335                 apu_set_register(s, 0, 0, 
1336                         (apu_get_register(s, 0, 0)&0xFF0F)|s->apu_mode[0]);
1337
1338                 if((s->fmt >> ESS_DAC_SHIFT)  & ESS_FMT_STEREO) 
1339                         apu_set_register(s, 1, 0, 
1340                                 (apu_get_register(s, 1, 0)&0xFF0F)|s->apu_mode[1]);
1341         }
1342 }       
1343
1344 static void start_adc(struct ess_state *s)
1345 {
1346         /* XXX locks? */
1347         if ((s->dma_adc.mapped || s->dma_adc.count < (signed)(s->dma_adc.dmasize - 2*s->dma_adc.fragsize)) 
1348             && s->dma_adc.ready && (! (s->enable & ADC_RUNNING)) ) {
1349
1350                 s->enable |= ADC_RUNNING;
1351                 apu_set_register(s, 2, 0, 
1352                         (apu_get_register(s, 2, 0)&0xFF0F)|s->apu_mode[2]);
1353                 apu_set_register(s, 4, 0, 
1354                         (apu_get_register(s, 4, 0)&0xFF0F)|s->apu_mode[4]);
1355
1356                 if( s->fmt & (ESS_FMT_STEREO << ESS_ADC_SHIFT)) {
1357                         apu_set_register(s, 3, 0, 
1358                                 (apu_get_register(s, 3, 0)&0xFF0F)|s->apu_mode[3]);
1359                         apu_set_register(s, 5, 0, 
1360                                 (apu_get_register(s, 5, 0)&0xFF0F)|s->apu_mode[5]);
1361                 }
1362                         
1363         }
1364 }       
1365
1366
1367 /*
1368  *      Native play back driver 
1369  */
1370
1371 /* the mode passed should be already shifted and masked */
1372 static void 
1373 ess_play_setup(struct ess_state *ess, int mode, u32 rate, void *buffer, int size)
1374 {
1375         u32 pa;
1376         u32 tmpval;
1377         int high_apu = 0;
1378         int channel;
1379
1380         M_printk("mode=%d rate=%d buf=%p len=%d.\n",
1381                 mode, rate, buffer, size);
1382                 
1383         /* all maestro sizes are in 16bit words */
1384         size >>=1;
1385
1386         if(mode&ESS_FMT_STEREO) {
1387                 high_apu++;
1388                 /* only 16/stereo gets size divided */
1389                 if(mode&ESS_FMT_16BIT)
1390                         size>>=1;
1391         }
1392         
1393         for(channel=0; channel <= high_apu; channel++)
1394         {
1395                 pa = virt_to_bus(buffer);
1396
1397                 /* set the wavecache control reg */
1398                 tmpval = (pa - 0x10) & 0xFFF8;
1399                 if(!(mode & ESS_FMT_16BIT)) tmpval |= 4;
1400                 if(mode & ESS_FMT_STEREO) tmpval |= 2;
1401                 ess->apu_base[channel]=tmpval;
1402                 wave_set_register(ess, ess->apu[channel]<<3, tmpval);
1403                 
1404                 pa -= virt_to_bus(ess->card->dmapages);
1405                 pa>>=1; /* words */
1406                 
1407                 /* base offset of dma calcs when reading the pointer
1408                         on the left one */
1409                 if(!channel) ess->dma_dac.base = pa&0xFFFF;
1410                 
1411                 pa|=0x00400000;                 /* System RAM */
1412
1413                 /* XXX the 16bit here might not be needed.. */
1414                 if((mode & ESS_FMT_STEREO) && (mode & ESS_FMT_16BIT)) {
1415                         if(channel) 
1416                                 pa|=0x00800000;                 /* Stereo */
1417                         pa>>=1;
1418                 }
1419                         
1420 /* XXX think about endianess when writing these registers */
1421                 M_printk("maestro: ess_play_setup: APU[%d] pa = 0x%x\n", ess->apu[channel], pa);
1422                 /* start of sample */
1423                 apu_set_register(ess, channel, 4, ((pa>>16)&0xFF)<<8);
1424                 apu_set_register(ess, channel, 5, pa&0xFFFF);
1425                 /* sample end */
1426                 apu_set_register(ess, channel, 6, (pa+size)&0xFFFF);
1427                 /* setting loop len == sample len */
1428                 apu_set_register(ess, channel, 7, size);
1429                 
1430                 /* clear effects/env.. */
1431                 apu_set_register(ess, channel, 8, 0x0000);
1432                 /* set amp now to 0xd0 (?), low byte is 'amplitude dest'? */
1433                 apu_set_register(ess, channel, 9, 0xD000);
1434
1435                 /* clear routing stuff */
1436                 apu_set_register(ess, channel, 11, 0x0000);
1437                 /* dma on, no envelopes, filter to all 1s) */
1438                 apu_set_register(ess, channel, 0, 0x400F);
1439                 
1440                 if(mode&ESS_FMT_16BIT)
1441                         ess->apu_mode[channel]=0x10;
1442                 else
1443                         ess->apu_mode[channel]=0x30;
1444
1445                 if(mode&ESS_FMT_STEREO) {
1446                         /* set panning: left or right */
1447                         apu_set_register(ess, channel, 10, 0x8F00 | (channel ? 0 : 0x10));
1448                         ess->apu_mode[channel] += 0x10;
1449                 } else
1450                         apu_set_register(ess, channel, 10, 0x8F08);
1451         }
1452         
1453         /* clear WP interrupts */
1454         outw(1, ess->card->iobase+0x04);
1455         /* enable WP ints */
1456         outw(inw(ess->card->iobase+0x18)|4, ess->card->iobase+0x18);
1457
1458         /* go team! */
1459         set_dac_rate(ess,rate);
1460         start_dac(ess);
1461 }
1462
1463 /*
1464  *      Native record driver 
1465  */
1466
1467 /* again, passed mode is alrady shifted/masked */
1468 static void 
1469 ess_rec_setup(struct ess_state *ess, int mode, u32 rate, void *buffer, int size)
1470 {
1471         int apu_step = 2;
1472         int channel;
1473
1474         M_printk("maestro: ess_rec_setup: mode=%d rate=%d buf=0x%p len=%d.\n",
1475                 mode, rate, buffer, size);
1476                 
1477         /* all maestro sizes are in 16bit words */
1478         size >>=1;
1479
1480         /* we're given the full size of the buffer, but
1481         in stereo each channel will only use its half */
1482         if(mode&ESS_FMT_STEREO) {
1483                 size >>=1; 
1484                 apu_step = 1;
1485         }
1486         
1487         /* APU assignments: 2 = mono/left SRC
1488                             3 = right SRC
1489                             4 = mono/left Input Mixer
1490                             5 = right Input Mixer */
1491         for(channel=2;channel<6;channel+=apu_step)
1492         {
1493                 int i;
1494                 int bsize, route;
1495                 u32 pa;
1496                 u32 tmpval;
1497
1498                 /* data seems to flow from the codec, through an apu into
1499                         the 'mixbuf' bit of page, then through the SRC apu
1500                         and out to the real 'buffer'.  ok.  sure.  */
1501                 
1502                 if(channel & 0x04) {
1503                         /* ok, we're an input mixer going from adc
1504                                 through the mixbuf to the other apus */
1505
1506                         if(!(channel & 0x01)) { 
1507                                 pa = virt_to_bus(ess->mixbuf);
1508                         } else {
1509                                 pa = virt_to_bus(ess->mixbuf + (PAGE_SIZE >> 4));
1510                         }
1511
1512                         /* we source from a 'magic' apu */
1513                         bsize = PAGE_SIZE >> 5; /* half of this channels alloc, in words */
1514                         route = 0x14 + (channel - 4); /* parallel in crap, see maestro reg 0xC [8-11] */
1515                         ess->apu_mode[channel] = 0x90;  /* Input Mixer */
1516
1517                 } else {  
1518                         /* we're a rate converter taking
1519                                 input from the input apus and outputing it to
1520                                 system memory */
1521                         if(!(channel & 0x01))  {
1522                                 pa = virt_to_bus(buffer);
1523                         } else {
1524                                 /* right channel records its split half.
1525                                 *2 accommodates for rampant shifting earlier */
1526                                 pa = virt_to_bus(buffer + size*2);
1527                         }
1528
1529                         ess->apu_mode[channel] = 0xB0;  /* Sample Rate Converter */
1530
1531                         bsize = size; 
1532                         /* get input from inputing apu */
1533                         route = channel + 2;
1534                 }
1535
1536                 M_printk("maestro: ess_rec_setup: getting pa 0x%x from %d\n",pa,channel);
1537                 
1538                 /* set the wavecache control reg */
1539                 tmpval = (pa - 0x10) & 0xFFF8;
1540                 ess->apu_base[channel]=tmpval;
1541                 wave_set_register(ess, ess->apu[channel]<<3, tmpval);
1542                 
1543                 pa -= virt_to_bus(ess->card->dmapages);
1544                 pa>>=1; /* words */
1545                 
1546                 /* base offset of dma calcs when reading the pointer
1547                         on this left one */
1548                 if(channel==2) ess->dma_adc.base = pa&0xFFFF;
1549
1550                 pa|=0x00400000;                 /* bit 22 -> System RAM */
1551
1552                 M_printk("maestro: ess_rec_setup: APU[%d] pa = 0x%x size = 0x%x route = 0x%x\n", 
1553                         ess->apu[channel], pa, bsize, route);
1554                 
1555                 /* Begin loading the APU */             
1556                 for(i=0;i<15;i++)               /* clear all PBRs */
1557                         apu_set_register(ess, channel, i, 0x0000);
1558                         
1559                 apu_set_register(ess, channel, 0, 0x400F);
1560
1561                 /* need to enable subgroups.. and we should probably
1562                         have different groups for different /dev/dsps..  */
1563                 apu_set_register(ess, channel, 2, 0x8);
1564                                 
1565                 /* Load the buffer into the wave engine */
1566                 apu_set_register(ess, channel, 4, ((pa>>16)&0xFF)<<8);
1567                 /* XXX reg is little endian.. */
1568                 apu_set_register(ess, channel, 5, pa&0xFFFF);
1569                 apu_set_register(ess, channel, 6, (pa+bsize)&0xFFFF);
1570                 apu_set_register(ess, channel, 7, bsize);
1571                                 
1572                 /* clear effects/env.. */
1573                 apu_set_register(ess, channel, 8, 0x00F0);
1574                 
1575                 /* amplitude now?  sure.  why not.  */
1576                 apu_set_register(ess, channel, 9, 0x0000);
1577
1578                 /* set filter tune, radius, polar pan */
1579                 apu_set_register(ess, channel, 10, 0x8F08);
1580
1581                 /* route input */
1582                 apu_set_register(ess, channel, 11, route);
1583         }
1584         
1585         /* clear WP interrupts */
1586         outw(1, ess->card->iobase+0x04);
1587         /* enable WP ints */
1588         outw(inw(ess->card->iobase+0x18)|4, ess->card->iobase+0x18);
1589
1590         /* let 'er rip */
1591         set_adc_rate(ess,rate);
1592         start_adc(ess);
1593 }
1594 /* --------------------------------------------------------------------- */
1595
1596 static void set_dmaa(struct ess_state *s, unsigned int addr, unsigned int count)
1597 {
1598         M_printk("set_dmaa??\n");
1599 }
1600
1601 static void set_dmac(struct ess_state *s, unsigned int addr, unsigned int count)
1602 {
1603         M_printk("set_dmac??\n");
1604 }
1605
1606 /* Playback pointer */
1607 static inline unsigned get_dmaa(struct ess_state *s)
1608 {
1609         int offset;
1610
1611         offset = apu_get_register(s,0,5);
1612
1613 /*      M_printk("dmaa: offset: %d, base: %d\n",offset,s->dma_dac.base); */
1614         
1615         offset-=s->dma_dac.base;
1616
1617         return (offset&0xFFFE)<<1; /* hardware is in words */
1618 }
1619
1620 /* Record pointer */
1621 static inline unsigned get_dmac(struct ess_state *s)
1622 {
1623         int offset;
1624
1625         offset = apu_get_register(s,2,5);
1626
1627 /*      M_printk("dmac: offset: %d, base: %d\n",offset,s->dma_adc.base); */
1628         
1629         /* The offset is an address not a position relative to base */
1630         offset-=s->dma_adc.base;
1631         
1632         return (offset&0xFFFE)<<1; /* hardware is in words */
1633 }
1634
1635 /*
1636  *      Meet Bob, the timer...
1637  */
1638
1639 static irqreturn_t ess_interrupt(int irq, void *dev_id, struct pt_regs *regs);
1640
1641 static void stop_bob(struct ess_state *s)
1642 {
1643         /* Mask IDR 11,17 */
1644         maestro_write(s,  0x11, maestro_read(s, 0x11)&~1);
1645         maestro_write(s,  0x17, maestro_read(s, 0x17)&~1);
1646 }
1647
1648 /* eventually we could be clever and limit bob ints
1649         to the frequency at which our smallest duration
1650         chunks may expire */
1651 #define ESS_SYSCLK      50000000
1652 static void start_bob(struct ess_state *s)
1653 {
1654         int prescale;
1655         int divide;
1656         
1657         /* XXX make freq selector much smarter, see calc_bob_rate */
1658         int freq = 200; 
1659         
1660         /* compute ideal interrupt frequency for buffer size & play rate */
1661         /* first, find best prescaler value to match freq */
1662         for(prescale=5;prescale<12;prescale++)
1663                 if(freq > (ESS_SYSCLK>>(prescale+9)))
1664                         break;
1665                         
1666         /* next, back off prescaler whilst getting divider into optimum range */
1667         divide=1;
1668         while((prescale > 5) && (divide<32))
1669         {
1670                 prescale--;
1671                 divide <<=1;
1672         }
1673         divide>>=1;
1674         
1675         /* now fine-tune the divider for best match */
1676         for(;divide<31;divide++)
1677                 if(freq >= ((ESS_SYSCLK>>(prescale+9))/(divide+1)))
1678                         break;
1679         
1680         /* divide = 0 is illegal, but don't let prescale = 4! */
1681         if(divide == 0)
1682         {
1683                 divide++;
1684                 if(prescale>5)
1685                         prescale--;
1686         }
1687
1688         maestro_write(s, 6, 0x9000 | (prescale<<5) | divide); /* set reg */
1689         
1690         /* Now set IDR 11/17 */
1691         maestro_write(s, 0x11, maestro_read(s, 0x11)|1);
1692         maestro_write(s, 0x17, maestro_read(s, 0x17)|1);
1693 }
1694 /* --------------------------------------------------------------------- */
1695
1696 /* this quickly calculates the frequency needed for bob
1697         and sets it if its different than what bob is
1698         currently running at.  its called often so 
1699         needs to be fairly quick. */
1700 #define BOB_MIN 50
1701 #define BOB_MAX 400
1702 static void calc_bob_rate(struct ess_state *s) {
1703 #if 0 /* this thing tries to set the frequency of bob such that
1704         there are 2 interrupts / buffer walked by the dac/adc.  That
1705         is probably very wrong for people who actually care about 
1706         mid buffer positioning.  it should be calculated as bytes/interrupt
1707         and that needs to be decided :)  so for now just use the static 150
1708         in start_bob.*/
1709
1710         unsigned int dac_rate=2,adc_rate=1,newrate;
1711         static int israte=-1;
1712
1713         if (s->dma_dac.fragsize == 0) dac_rate = BOB_MIN;
1714         else  {
1715                 dac_rate =      (2 * s->ratedac * sample_size[(s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK]) /
1716                                 (s->dma_dac.fragsize) ;
1717         }
1718                 
1719         if (s->dma_adc.fragsize == 0) adc_rate = BOB_MIN;
1720         else {
1721                 adc_rate =      (2 * s->rateadc * sample_size[(s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK]) /
1722                                 (s->dma_adc.fragsize) ;
1723         }
1724
1725         if(dac_rate > adc_rate) newrate = adc_rate;
1726         else newrate=dac_rate;
1727
1728         if(newrate > BOB_MAX) newrate = BOB_MAX;
1729         else {
1730                 if(newrate < BOB_MIN) 
1731                         newrate = BOB_MIN;
1732         }
1733
1734         if( israte != newrate) {
1735                 printk("dac: %d  adc: %d rate: %d\n",dac_rate,adc_rate,israte);
1736                 israte=newrate;
1737         }
1738 #endif
1739
1740 }
1741
1742 static int 
1743 prog_dmabuf(struct ess_state *s, unsigned rec)
1744 {
1745         struct dmabuf *db = rec ? &s->dma_adc : &s->dma_dac;
1746         unsigned rate = rec ? s->rateadc : s->ratedac;
1747         unsigned bytepersec;
1748         unsigned bufs;
1749         unsigned char fmt;
1750         unsigned long flags;
1751
1752         spin_lock_irqsave(&s->lock, flags);
1753         fmt = s->fmt;
1754         if (rec) {
1755                 stop_adc(s);
1756                 fmt >>= ESS_ADC_SHIFT;
1757         } else {
1758                 stop_dac(s);
1759                 fmt >>= ESS_DAC_SHIFT;
1760         }
1761         spin_unlock_irqrestore(&s->lock, flags);
1762         fmt &= ESS_FMT_MASK;
1763
1764         db->hwptr = db->swptr = db->total_bytes = db->count = db->error = db->endcleared = 0;
1765
1766         /* this algorithm is a little nuts.. where did /1000 come from? */
1767         bytepersec = rate << sample_shift[fmt];
1768         bufs = PAGE_SIZE << db->buforder;
1769         if (db->ossfragshift) {
1770                 if ((1000 << db->ossfragshift) < bytepersec)
1771                         db->fragshift = ld2(bytepersec/1000);
1772                 else
1773                         db->fragshift = db->ossfragshift;
1774         } else {
1775                 db->fragshift = ld2(bytepersec/100/(db->subdivision ? db->subdivision : 1));
1776                 if (db->fragshift < 3)
1777                         db->fragshift = 3; 
1778         }
1779         db->numfrag = bufs >> db->fragshift;
1780         while (db->numfrag < 4 && db->fragshift > 3) {
1781                 db->fragshift--;
1782                 db->numfrag = bufs >> db->fragshift;
1783         }
1784         db->fragsize = 1 << db->fragshift;
1785         if (db->ossmaxfrags >= 4 && db->ossmaxfrags < db->numfrag)
1786                 db->numfrag = db->ossmaxfrags;
1787         db->fragsamples = db->fragsize >> sample_shift[fmt];
1788         db->dmasize = db->numfrag << db->fragshift;
1789
1790         M_printk("maestro: setup oss: numfrag: %d fragsize: %d dmasize: %d\n",db->numfrag,db->fragsize,db->dmasize);
1791
1792         memset(db->rawbuf, (fmt & ESS_FMT_16BIT) ? 0 : 0x80, db->dmasize);
1793
1794         spin_lock_irqsave(&s->lock, flags);
1795         if (rec) 
1796                 ess_rec_setup(s, fmt, s->rateadc, db->rawbuf, db->dmasize);
1797         else 
1798                 ess_play_setup(s, fmt, s->ratedac, db->rawbuf, db->dmasize);
1799
1800         spin_unlock_irqrestore(&s->lock, flags);
1801         db->ready = 1;
1802
1803         return 0;
1804 }
1805
1806 static __inline__ void 
1807 clear_advance(struct ess_state *s)
1808 {
1809         unsigned char c = ((s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_16BIT) ? 0 : 0x80;
1810         
1811         unsigned char *buf = s->dma_dac.rawbuf;
1812         unsigned bsize = s->dma_dac.dmasize;
1813         unsigned bptr = s->dma_dac.swptr;
1814         unsigned len = s->dma_dac.fragsize;
1815         
1816         if (bptr + len > bsize) {
1817                 unsigned x = bsize - bptr;
1818                 memset(buf + bptr, c, x);
1819                 /* account for wrapping? */
1820                 bptr = 0;
1821                 len -= x;
1822         }
1823         memset(buf + bptr, c, len);
1824 }
1825
1826 /* call with spinlock held! */
1827 static void 
1828 ess_update_ptr(struct ess_state *s)
1829 {
1830         unsigned hwptr;
1831         int diff;
1832
1833         /* update ADC pointer */
1834         if (s->dma_adc.ready) {
1835                 /* oh boy should this all be re-written.  everything in the current code paths think
1836                 that the various counters/pointers are expressed in bytes to the user but we have
1837                 two apus doing stereo stuff so we fix it up here.. it propagates to all the various
1838                 counters from here.  */
1839                 if ( s->fmt & (ESS_FMT_STEREO << ESS_ADC_SHIFT)) {
1840                         hwptr = (get_dmac(s)*2) % s->dma_adc.dmasize;
1841                 } else {
1842                         hwptr = get_dmac(s) % s->dma_adc.dmasize;
1843                 }
1844                 diff = (s->dma_adc.dmasize + hwptr - s->dma_adc.hwptr) % s->dma_adc.dmasize;
1845                 s->dma_adc.hwptr = hwptr;
1846                 s->dma_adc.total_bytes += diff;
1847                 s->dma_adc.count += diff;
1848                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize) 
1849                         wake_up(&s->dma_adc.wait);
1850                 if (!s->dma_adc.mapped) {
1851                         if (s->dma_adc.count > (signed)(s->dma_adc.dmasize - ((3 * s->dma_adc.fragsize) >> 1))) {
1852                                 /* FILL ME 
1853                                 wrindir(s, SV_CIENABLE, s->enable); */
1854                                 stop_adc(s); 
1855                                 /* brute force everyone back in sync, sigh */
1856                                 s->dma_adc.count = 0;
1857                                 s->dma_adc.swptr = 0;
1858                                 s->dma_adc.hwptr = 0;
1859                                 s->dma_adc.error++;
1860                         }
1861                 }
1862         }
1863         /* update DAC pointer */
1864         if (s->dma_dac.ready) {
1865                 hwptr = get_dmaa(s) % s->dma_dac.dmasize; 
1866                 /* the apu only reports the length it has seen, not the
1867                         length of the memory that has been used (the WP
1868                         knows that) */
1869                 if ( ((s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK) == (ESS_FMT_STEREO|ESS_FMT_16BIT))
1870                         hwptr<<=1;
1871
1872                 diff = (s->dma_dac.dmasize + hwptr - s->dma_dac.hwptr) % s->dma_dac.dmasize;
1873 /*              M_printk("updating dac: hwptr: %d diff: %d\n",hwptr,diff);*/
1874                 s->dma_dac.hwptr = hwptr;
1875                 s->dma_dac.total_bytes += diff;
1876                 if (s->dma_dac.mapped) {
1877                         s->dma_dac.count += diff;
1878                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize) {
1879                                 wake_up(&s->dma_dac.wait);
1880                         }
1881                 } else {
1882                         s->dma_dac.count -= diff;
1883 /*                      M_printk("maestro: ess_update_ptr: diff: %d, count: %d\n", diff, s->dma_dac.count); */
1884                         if (s->dma_dac.count <= 0) {
1885                                 M_printk("underflow! diff: %d count: %d hw: %d sw: %d\n", diff, s->dma_dac.count, 
1886                                         hwptr, s->dma_dac.swptr);
1887                                 /* FILL ME 
1888                                 wrindir(s, SV_CIENABLE, s->enable); */
1889                                 /* XXX how on earth can calling this with the lock held work.. */
1890                                 stop_dac(s);
1891                                 /* brute force everyone back in sync, sigh */
1892                                 s->dma_dac.count = 0; 
1893                                 s->dma_dac.swptr = hwptr; 
1894                                 s->dma_dac.error++;
1895                         } else if (s->dma_dac.count <= (signed)s->dma_dac.fragsize && !s->dma_dac.endcleared) {
1896                                 clear_advance(s);
1897                                 s->dma_dac.endcleared = 1;
1898                         }
1899                         if (s->dma_dac.count + (signed)s->dma_dac.fragsize <= (signed)s->dma_dac.dmasize) {
1900                                 wake_up(&s->dma_dac.wait);
1901 /*                              printk("waking up DAC count: %d sw: %d hw: %d\n",s->dma_dac.count, s->dma_dac.swptr, 
1902                                         hwptr);*/
1903                         }
1904                 }
1905         }
1906 }
1907
1908 static irqreturn_t
1909 ess_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1910 {
1911         struct ess_state *s;
1912         struct ess_card *c = (struct ess_card *)dev_id;
1913         int i;
1914         u32 event;
1915
1916         if ( ! (event = inb(c->iobase+0x1A)) )
1917                 return IRQ_NONE;
1918
1919         outw(inw(c->iobase+4)&1, c->iobase+4);
1920
1921 /*      M_printk("maestro int: %x\n",event);*/
1922         if(event&(1<<6))
1923         {
1924                 int x;
1925                 enum {UP_EVT, DOWN_EVT, MUTE_EVT} vol_evt;
1926                 int volume;
1927
1928                 /* Figure out which volume control button was pushed,
1929                    based on differences from the default register
1930                    values. */
1931                 x = inb(c->iobase+0x1c);
1932                 if (x&1) vol_evt = MUTE_EVT;
1933                 else if (((x>>1)&7) > 4) vol_evt = UP_EVT;
1934                 else vol_evt = DOWN_EVT;
1935
1936                 /* Reset the volume control registers. */
1937                 outb(0x88, c->iobase+0x1c);
1938                 outb(0x88, c->iobase+0x1d);
1939                 outb(0x88, c->iobase+0x1e);
1940                 outb(0x88, c->iobase+0x1f);
1941
1942                 /* Deal with the button press in a hammer-handed
1943                    manner by adjusting the master mixer volume. */
1944                 volume = c->mix.mixer_state[0] & 0xff;
1945                 if (vol_evt == UP_EVT) {
1946                         volume += 5;
1947                         if (volume > 100)
1948                                 volume = 100;
1949                 }
1950                 else if (vol_evt == DOWN_EVT) {
1951                         volume -= 5;
1952                         if (volume < 0)
1953                                 volume = 0;
1954                 } else {
1955                         /* vol_evt == MUTE_EVT */
1956                         if (volume == 0)
1957                                 volume = c->dock_mute_vol;
1958                         else {
1959                                 c->dock_mute_vol = volume;
1960                                 volume = 0;
1961                         }
1962                 }
1963                 set_mixer (c, 0, (volume << 8) | volume);
1964         }
1965
1966         /* Ack all the interrupts. */
1967         outb(0xFF, c->iobase+0x1A);
1968                 
1969         /*
1970          *      Update the pointers for all APU's we are running.
1971          */
1972         for(i=0;i<NR_DSPS;i++)
1973         {
1974                 s=&c->channels[i];
1975                 if(s->dev_audio == -1)
1976                         break;
1977                 spin_lock(&s->lock);
1978                 ess_update_ptr(s);
1979                 spin_unlock(&s->lock);
1980         }
1981         return IRQ_HANDLED;
1982 }
1983
1984
1985 /* --------------------------------------------------------------------- */
1986
1987 static const char invalid_magic[] = KERN_CRIT "maestro: invalid magic value in %s\n";
1988
1989 #define VALIDATE_MAGIC(FOO,MAG)                         \
1990 ({                                                \
1991         if (!(FOO) || (FOO)->magic != MAG) { \
1992                 printk(invalid_magic,__FUNCTION__);            \
1993                 return -ENXIO;                    \
1994         }                                         \
1995 })
1996
1997 #define VALIDATE_STATE(a) VALIDATE_MAGIC(a,ESS_STATE_MAGIC)
1998 #define VALIDATE_CARD(a) VALIDATE_MAGIC(a,ESS_CARD_MAGIC)
1999
2000 static void set_mixer(struct ess_card *card,unsigned int mixer, unsigned int val ) 
2001 {
2002         unsigned int left,right;
2003         /* cleanse input a little */
2004         right = ((val >> 8)  & 0xff) ;
2005         left = (val  & 0xff) ;
2006
2007         if(right > 100) right = 100;
2008         if(left > 100) left = 100;
2009
2010         card->mix.mixer_state[mixer]=(right << 8) | left;
2011         card->mix.write_mixer(card,mixer,left,right);
2012 }
2013
2014 static void
2015 mixer_push_state(struct ess_card *card)
2016 {
2017         int i;
2018         for(i = 0 ; i < SOUND_MIXER_NRDEVICES ; i++) {
2019                 if( ! supported_mixer(card,i)) continue;
2020
2021                 set_mixer(card,i,card->mix.mixer_state[i]);
2022         }
2023 }
2024
2025 static int mixer_ioctl(struct ess_card *card, unsigned int cmd, unsigned long arg)
2026 {
2027         int i, val=0;
2028        unsigned long flags;
2029
2030         VALIDATE_CARD(card);
2031         if (cmd == SOUND_MIXER_INFO) {
2032                 mixer_info info;
2033                 memset(&info, 0, sizeof(info));
2034                 strlcpy(info.id, card_names[card->card_type], sizeof(info.id));
2035                 strlcpy(info.name, card_names[card->card_type], sizeof(info.name));
2036                 info.modify_counter = card->mix.modcnt;
2037                 if (copy_to_user((void *)arg, &info, sizeof(info)))
2038                         return -EFAULT;
2039                 return 0;
2040         }
2041         if (cmd == SOUND_OLD_MIXER_INFO) {
2042                 _old_mixer_info info;
2043                 memset(&info, 0, sizeof(info));
2044                 strlcpy(info.id, card_names[card->card_type], sizeof(info.id));
2045                 strlcpy(info.name, card_names[card->card_type], sizeof(info.name));
2046                 if (copy_to_user((void *)arg, &info, sizeof(info)))
2047                         return -EFAULT;
2048                 return 0;
2049         }
2050         if (cmd == OSS_GETVERSION)
2051                 return put_user(SOUND_VERSION, (int *)arg);
2052
2053         if (_IOC_TYPE(cmd) != 'M' || _IOC_SIZE(cmd) != sizeof(int))
2054                 return -EINVAL;
2055
2056         if (_IOC_DIR(cmd) == _IOC_READ) {
2057                 switch (_IOC_NR(cmd)) {
2058                 case SOUND_MIXER_RECSRC: /* give them the current record source */
2059
2060                         if(!card->mix.recmask_io) {
2061                                 val = 0;
2062                         } else {
2063                                spin_lock_irqsave(&card->lock, flags);
2064                                 val = card->mix.recmask_io(card,1,0);
2065                                spin_unlock_irqrestore(&card->lock, flags);
2066                         }
2067                         break;
2068                         
2069                 case SOUND_MIXER_DEVMASK: /* give them the supported mixers */
2070                         val = card->mix.supported_mixers;
2071                         break;
2072
2073                 case SOUND_MIXER_RECMASK: /* Arg contains a bit for each supported recording source */
2074                         val = card->mix.record_sources;
2075                         break;
2076                         
2077                 case SOUND_MIXER_STEREODEVS: /* Mixer channels supporting stereo */
2078                         val = card->mix.stereo_mixers;
2079                         break;
2080                         
2081                 case SOUND_MIXER_CAPS:
2082                         val = SOUND_CAP_EXCL_INPUT;
2083                         break;
2084
2085                 default: /* read a specific mixer */
2086                         i = _IOC_NR(cmd);
2087
2088                         if ( ! supported_mixer(card,i)) 
2089                                 return -EINVAL;
2090
2091                         /* do we ever want to touch the hardware? */
2092 /*                     spin_lock_irqsave(&card->lock, flags);
2093                         val = card->mix.read_mixer(card,i);
2094                        spin_unlock_irqrestore(&card->lock, flags);*/
2095
2096                         val = card->mix.mixer_state[i];
2097 /*                      M_printk("returned 0x%x for mixer %d\n",val,i);*/
2098
2099                         break;
2100                 }
2101                 return put_user(val,(int *)arg);
2102         }
2103         
2104         if (_IOC_DIR(cmd) != (_IOC_WRITE|_IOC_READ))
2105                 return -EINVAL;
2106         
2107         card->mix.modcnt++;
2108
2109         if (get_user(val, (int *)arg))
2110                 return -EFAULT;
2111
2112         switch (_IOC_NR(cmd)) {
2113         case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
2114
2115                 if (!card->mix.recmask_io) return -EINVAL;
2116                 if(!val) return 0;
2117                 if(! (val &= card->mix.record_sources)) return -EINVAL;
2118
2119                spin_lock_irqsave(&card->lock, flags);
2120                 card->mix.recmask_io(card,0,val);
2121                spin_unlock_irqrestore(&card->lock, flags);
2122                 return 0;
2123
2124         default:
2125                 i = _IOC_NR(cmd);
2126
2127                 if ( ! supported_mixer(card,i)) 
2128                         return -EINVAL;
2129
2130                spin_lock_irqsave(&card->lock, flags);
2131                 set_mixer(card,i,val);
2132                spin_unlock_irqrestore(&card->lock, flags);
2133
2134                 return 0;
2135         }
2136 }
2137
2138 /* --------------------------------------------------------------------- */
2139 static int ess_open_mixdev(struct inode *inode, struct file *file)
2140 {
2141         unsigned int minor = iminor(inode);
2142         struct ess_card *card = NULL;
2143         struct pci_dev *pdev = NULL;
2144         struct pci_driver *drvr;
2145
2146         while ((pdev = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, pdev)) != NULL) {
2147                 drvr = pci_dev_driver (pdev);
2148                 if (drvr == &maestro_pci_driver) {
2149                         card = (struct ess_card*)pci_get_drvdata (pdev);
2150                         if (!card)
2151                                 continue;
2152                         if (card->dev_mixer == minor)
2153                                 break;
2154                 }
2155         }
2156         if (!card)
2157                 return -ENODEV;
2158         file->private_data = card;
2159         return 0;
2160 }
2161
2162 static int ess_release_mixdev(struct inode *inode, struct file *file)
2163 {
2164         struct ess_card *card = (struct ess_card *)file->private_data;
2165
2166         VALIDATE_CARD(card);
2167         
2168         return 0;
2169 }
2170
2171 static int ess_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2172 {
2173         struct ess_card *card = (struct ess_card *)file->private_data;
2174
2175         VALIDATE_CARD(card);
2176
2177         return mixer_ioctl(card, cmd, arg);
2178 }
2179
2180 static /*const*/ struct file_operations ess_mixer_fops = {
2181         .owner          = THIS_MODULE,
2182         .llseek         = no_llseek,
2183         .ioctl          = ess_ioctl_mixdev,
2184         .open           = ess_open_mixdev,
2185         .release        = ess_release_mixdev,
2186 };
2187
2188 /* --------------------------------------------------------------------- */
2189
2190 static int drain_dac(struct ess_state *s, int nonblock)
2191 {
2192         DECLARE_WAITQUEUE(wait,current);
2193         unsigned long flags;
2194         int count;
2195         signed long tmo;
2196
2197         if (s->dma_dac.mapped || !s->dma_dac.ready)
2198                 return 0;
2199         current->state = TASK_INTERRUPTIBLE;
2200         add_wait_queue(&s->dma_dac.wait, &wait);
2201         for (;;) {
2202                 /* XXX uhm.. questionable locking*/
2203                 spin_lock_irqsave(&s->lock, flags);
2204                 count = s->dma_dac.count;
2205                 spin_unlock_irqrestore(&s->lock, flags);
2206                 if (count <= 0)
2207                         break;
2208                 if (signal_pending(current))
2209                         break;
2210                 if (nonblock) {
2211                         remove_wait_queue(&s->dma_dac.wait, &wait);
2212                         current->state = TASK_RUNNING;
2213                         return -EBUSY;
2214                 }
2215                 tmo = (count * HZ) / s->ratedac;
2216                 tmo >>= sample_shift[(s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK];
2217                 /* XXX this is just broken.  someone is waking us up alot, or schedule_timeout is broken.
2218                         or something.  who cares. - zach */
2219                 if (!schedule_timeout(tmo ? tmo : 1) && tmo)
2220                         M_printk(KERN_DEBUG "maestro: dma timed out?? %ld\n",jiffies);
2221         }
2222         remove_wait_queue(&s->dma_dac.wait, &wait);
2223         current->state = TASK_RUNNING;
2224         if (signal_pending(current))
2225                 return -ERESTARTSYS;
2226         return 0;
2227 }
2228
2229 /* --------------------------------------------------------------------- */
2230 /* Zach sez: "god this is gross.." */
2231 static int 
2232 comb_stereo(unsigned char *real_buffer,unsigned char  *tmp_buffer, int offset, 
2233         int count, int bufsize)
2234 {  
2235         /* No such thing as stereo recording, so we
2236         use dual input mixers.  which means we have to 
2237         combine mono to stereo buffer.  yuck. 
2238
2239         but we don't have to be able to work a byte at a time..*/
2240
2241         unsigned char *so,*left,*right;
2242         int i;
2243
2244         so = tmp_buffer;
2245         left = real_buffer + offset;
2246         right = real_buffer + bufsize/2 + offset;
2247
2248 /*      M_printk("comb_stereo writing %d to %p from %p and %p, offset: %d size: %d\n",count/2, tmp_buffer,left,right,offset,bufsize);*/
2249
2250         for(i=count/4; i ; i--) {
2251                 (*(so+2)) = *(right++);
2252                 (*(so+3)) = *(right++);
2253                 (*so) = *(left++);
2254                 (*(so+1)) = *(left++);
2255                 so+=4;
2256         }
2257
2258         return 0;
2259 }
2260
2261 /* in this loop, dma_adc.count signifies the amount of data thats waiting
2262         to be copied to the user's buffer.  it is filled by the interrupt
2263         handler and drained by this loop. */
2264 static ssize_t 
2265 ess_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
2266 {
2267         struct ess_state *s = (struct ess_state *)file->private_data;
2268         ssize_t ret;
2269         unsigned long flags;
2270         unsigned swptr;
2271         int cnt;
2272         unsigned char *combbuf = NULL;
2273         
2274         VALIDATE_STATE(s);
2275         if (ppos != &file->f_pos)
2276                 return -ESPIPE;
2277         if (s->dma_adc.mapped)
2278                 return -ENXIO;
2279         if (!s->dma_adc.ready && (ret = prog_dmabuf(s, 1)))
2280                 return ret;
2281         if (!access_ok(VERIFY_WRITE, buffer, count))
2282                 return -EFAULT;
2283         if(!(combbuf = kmalloc(count,GFP_KERNEL)))
2284                 return -ENOMEM;
2285         ret = 0;
2286
2287         calc_bob_rate(s);
2288
2289         while (count > 0) {
2290                 spin_lock_irqsave(&s->lock, flags);
2291                 /* remember, all these things are expressed in bytes to be
2292                         sent to the user.. hence the evil / 2 down below */
2293                 swptr = s->dma_adc.swptr;
2294                 cnt = s->dma_adc.dmasize-swptr;
2295                 if (s->dma_adc.count < cnt)
2296                         cnt = s->dma_adc.count;
2297                 spin_unlock_irqrestore(&s->lock, flags);
2298
2299                 if (cnt > count)
2300                         cnt = count;
2301
2302                 if ( cnt > 0 ) cnt &= ~3;
2303
2304                 if (cnt <= 0) {
2305                         start_adc(s);
2306                         if (file->f_flags & O_NONBLOCK) 
2307                         {
2308                                 ret = ret ? ret : -EAGAIN;
2309                                 goto rec_return_free;
2310                         }
2311                         if (!interruptible_sleep_on_timeout(&s->dma_adc.wait, HZ)) {
2312                                 if(! s->card->in_suspend) printk(KERN_DEBUG "maestro: read: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
2313                                        s->dma_adc.dmasize, s->dma_adc.fragsize, s->dma_adc.count, 
2314                                        s->dma_adc.hwptr, s->dma_adc.swptr);
2315                                 stop_adc(s);
2316                                 spin_lock_irqsave(&s->lock, flags);
2317                                 set_dmac(s, virt_to_bus(s->dma_adc.rawbuf), s->dma_adc.numfrag << s->dma_adc.fragshift);
2318                                 /* program enhanced mode registers */
2319                                 /* FILL ME */
2320 /*                              wrindir(s, SV_CIDMACBASECOUNT1, (s->dma_adc.fragsamples-1) >> 8);
2321                                 wrindir(s, SV_CIDMACBASECOUNT0, s->dma_adc.fragsamples-1); */
2322                                 s->dma_adc.count = s->dma_adc.hwptr = s->dma_adc.swptr = 0;
2323                                 spin_unlock_irqrestore(&s->lock, flags);
2324                         }
2325                         if (signal_pending(current)) 
2326                         {
2327                                 ret = ret ? ret : -ERESTARTSYS;
2328                                 goto rec_return_free;
2329                         }
2330                         continue;
2331                 }
2332         
2333                 if(s->fmt & (ESS_FMT_STEREO << ESS_ADC_SHIFT)) {
2334                         /* swptr/2 so that we know the real offset in each apu's buffer */
2335                         comb_stereo(s->dma_adc.rawbuf,combbuf,swptr/2,cnt,s->dma_adc.dmasize);
2336                         if (copy_to_user(buffer, combbuf, cnt)) {
2337                                 ret = ret ? ret : -EFAULT;
2338                                 goto rec_return_free;
2339                         }
2340                 } else  {
2341                         if (copy_to_user(buffer, s->dma_adc.rawbuf + swptr, cnt)) {
2342                                 ret = ret ? ret : -EFAULT;
2343                                 goto rec_return_free;
2344                         }
2345                 }
2346
2347                 swptr = (swptr + cnt) % s->dma_adc.dmasize;
2348                 spin_lock_irqsave(&s->lock, flags);
2349                 s->dma_adc.swptr = swptr;
2350                 s->dma_adc.count -= cnt;
2351                 spin_unlock_irqrestore(&s->lock, flags);
2352                 count -= cnt;
2353                 buffer += cnt;
2354                 ret += cnt;
2355                 start_adc(s);
2356         }
2357
2358 rec_return_free:
2359         if(combbuf) kfree(combbuf);
2360         return ret;
2361 }
2362
2363 static ssize_t 
2364 ess_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
2365 {
2366         struct ess_state *s = (struct ess_state *)file->private_data;
2367         ssize_t ret;
2368         unsigned long flags;
2369         unsigned swptr;
2370         int cnt;
2371         
2372         VALIDATE_STATE(s);
2373         if (ppos != &file->f_pos)
2374                 return -ESPIPE;
2375         if (s->dma_dac.mapped)
2376                 return -ENXIO;
2377         if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2378                 return ret;
2379         if (!access_ok(VERIFY_READ, buffer, count))
2380                 return -EFAULT;
2381         ret = 0;
2382
2383         calc_bob_rate(s);
2384
2385         while (count > 0) {
2386                 spin_lock_irqsave(&s->lock, flags);
2387
2388                 if (s->dma_dac.count < 0) {
2389                         s->dma_dac.count = 0;
2390                         s->dma_dac.swptr = s->dma_dac.hwptr;
2391                 }
2392                 swptr = s->dma_dac.swptr;
2393
2394                 cnt = s->dma_dac.dmasize-swptr;
2395
2396                 if (s->dma_dac.count + cnt > s->dma_dac.dmasize)
2397                         cnt = s->dma_dac.dmasize - s->dma_dac.count;
2398
2399                 spin_unlock_irqrestore(&s->lock, flags);
2400
2401                 if (cnt > count)
2402                         cnt = count;
2403
2404                 if (cnt <= 0) {
2405                         start_dac(s);
2406                         if (file->f_flags & O_NONBLOCK) {
2407                                 if(!ret) ret = -EAGAIN;
2408                                 goto return_free;
2409                         }
2410                         if (!interruptible_sleep_on_timeout(&s->dma_dac.wait, HZ)) {
2411                                 if(! s->card->in_suspend) printk(KERN_DEBUG "maestro: write: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
2412                                        s->dma_dac.dmasize, s->dma_dac.fragsize, s->dma_dac.count, 
2413                                        s->dma_dac.hwptr, s->dma_dac.swptr);
2414                                 stop_dac(s);
2415                                 spin_lock_irqsave(&s->lock, flags);
2416                                 set_dmaa(s, virt_to_bus(s->dma_dac.rawbuf), s->dma_dac.numfrag << s->dma_dac.fragshift);
2417                                 /* program enhanced mode registers */
2418 /*                              wrindir(s, SV_CIDMAABASECOUNT1, (s->dma_dac.fragsamples-1) >> 8);
2419                                 wrindir(s, SV_CIDMAABASECOUNT0, s->dma_dac.fragsamples-1); */
2420                                 /* FILL ME */
2421                                 s->dma_dac.count = s->dma_dac.hwptr = s->dma_dac.swptr = 0;
2422                                 spin_unlock_irqrestore(&s->lock, flags);
2423                         }
2424                         if (signal_pending(current)) {
2425                                 if (!ret) ret = -ERESTARTSYS;
2426                                 goto return_free;
2427                         }
2428                         continue;
2429                 }
2430                 if (copy_from_user(s->dma_dac.rawbuf + swptr, buffer, cnt)) {
2431                         if (!ret) ret = -EFAULT;
2432                         goto return_free;
2433                 }
2434 /*              printk("wrote %d bytes at sw: %d cnt: %d while hw: %d\n",cnt, swptr, s->dma_dac.count, s->dma_dac.hwptr);*/
2435
2436                 swptr = (swptr + cnt) % s->dma_dac.dmasize;
2437
2438                 spin_lock_irqsave(&s->lock, flags);
2439                 s->dma_dac.swptr = swptr;
2440                 s->dma_dac.count += cnt;
2441                 s->dma_dac.endcleared = 0;
2442                 spin_unlock_irqrestore(&s->lock, flags);
2443                 count -= cnt;
2444                 buffer += cnt;
2445                 ret += cnt;
2446                 start_dac(s);
2447         }
2448 return_free:
2449         return ret;
2450 }
2451
2452 /* No kernel lock - we have our own spinlock */
2453 static unsigned int ess_poll(struct file *file, struct poll_table_struct *wait)
2454 {
2455         struct ess_state *s = (struct ess_state *)file->private_data;
2456         unsigned long flags;
2457         unsigned int mask = 0;
2458
2459         VALIDATE_STATE(s);
2460
2461 /* In 0.14 prog_dmabuf always returns success anyway ... */
2462         if (file->f_mode & FMODE_WRITE) {
2463                 if (!s->dma_dac.ready && prog_dmabuf(s, 0)) 
2464                         return 0;
2465         }
2466         if (file->f_mode & FMODE_READ) {
2467                 if (!s->dma_adc.ready && prog_dmabuf(s, 1))
2468                         return 0;
2469         }
2470
2471         if (file->f_mode & FMODE_WRITE)
2472                 poll_wait(file, &s->dma_dac.wait, wait);
2473         if (file->f_mode & FMODE_READ)
2474                 poll_wait(file, &s->dma_adc.wait, wait);
2475         spin_lock_irqsave(&s->lock, flags);
2476         ess_update_ptr(s);
2477         if (file->f_mode & FMODE_READ) {
2478                 if (s->dma_adc.count >= (signed)s->dma_adc.fragsize)
2479                         mask |= POLLIN | POLLRDNORM;
2480         }
2481         if (file->f_mode & FMODE_WRITE) {
2482                 if (s->dma_dac.mapped) {
2483                         if (s->dma_dac.count >= (signed)s->dma_dac.fragsize) 
2484                                 mask |= POLLOUT | POLLWRNORM;
2485                 } else {
2486                         if ((signed)s->dma_dac.dmasize >= s->dma_dac.count + (signed)s->dma_dac.fragsize)
2487                                 mask |= POLLOUT | POLLWRNORM;
2488                 }
2489         }
2490         spin_unlock_irqrestore(&s->lock, flags);
2491         return mask;
2492 }
2493
2494 static int ess_mmap(struct file *file, struct vm_area_struct *vma)
2495 {
2496         struct ess_state *s = (struct ess_state *)file->private_data;
2497         struct dmabuf *db;
2498         int ret = -EINVAL;
2499         unsigned long size;
2500
2501         VALIDATE_STATE(s);
2502         lock_kernel();
2503         if (vma->vm_flags & VM_WRITE) {
2504                 if ((ret = prog_dmabuf(s, 1)) != 0)
2505                         goto out;
2506                 db = &s->dma_dac;
2507         } else 
2508 #if 0
2509         /* if we can have the wp/wc do the combining
2510                 we can turn this back on.  */
2511               if (vma->vm_flags & VM_READ) {
2512                 if ((ret = prog_dmabuf(s, 0)) != 0)
2513                         goto out;
2514                 db = &s->dma_adc;
2515         } else  
2516 #endif
2517                 goto out;
2518         ret = -EINVAL;
2519         if (vma->vm_pgoff != 0)
2520                 goto out;
2521         size = vma->vm_end - vma->vm_start;
2522         if (size > (PAGE_SIZE << db->buforder))
2523                 goto out;
2524         ret = -EAGAIN;
2525         if (remap_page_range(vma, vma->vm_start, virt_to_phys(db->rawbuf), size, vma->vm_page_prot))
2526                 goto out;
2527         db->mapped = 1;
2528         ret = 0;
2529 out:
2530         unlock_kernel();
2531         return ret;
2532 }
2533
2534 static int ess_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2535 {
2536         struct ess_state *s = (struct ess_state *)file->private_data;
2537         unsigned long flags;
2538         audio_buf_info abinfo;
2539         count_info cinfo;
2540         int val, mapped, ret;
2541         unsigned char fmtm, fmtd;
2542
2543 /*      printk("maestro: ess_ioctl: cmd %d\n", cmd);*/
2544         
2545         VALIDATE_STATE(s);
2546         mapped = ((file->f_mode & FMODE_WRITE) && s->dma_dac.mapped) ||
2547                 ((file->f_mode & FMODE_READ) && s->dma_adc.mapped);
2548         switch (cmd) {
2549         case OSS_GETVERSION:
2550                 return put_user(SOUND_VERSION, (int *)arg);
2551
2552         case SNDCTL_DSP_SYNC:
2553                 if (file->f_mode & FMODE_WRITE)
2554                         return drain_dac(s, file->f_flags & O_NONBLOCK);
2555                 return 0;
2556                 
2557         case SNDCTL_DSP_SETDUPLEX:
2558                 /* XXX fix */
2559                 return 0;
2560
2561         case SNDCTL_DSP_GETCAPS:
2562                 return put_user(DSP_CAP_DUPLEX | DSP_CAP_REALTIME | DSP_CAP_TRIGGER | DSP_CAP_MMAP, (int *)arg);
2563                 
2564         case SNDCTL_DSP_RESET:
2565                 if (file->f_mode & FMODE_WRITE) {
2566                         stop_dac(s);
2567                         synchronize_irq(s->card->pcidev->irq);
2568                         s->dma_dac.swptr = s->dma_dac.hwptr = s->dma_dac.count = s->dma_dac.total_bytes = 0;
2569                 }
2570                 if (file->f_mode & FMODE_READ) {
2571                         stop_adc(s);
2572                         synchronize_irq(s->card->pcidev->irq);
2573                         s->dma_adc.swptr = s->dma_adc.hwptr = s->dma_adc.count = s->dma_adc.total_bytes = 0;
2574                 }
2575                 return 0;
2576
2577         case SNDCTL_DSP_SPEED:
2578                 if (get_user(val, (int *)arg))
2579                         return -EFAULT;
2580                 if (val >= 0) {
2581                         if (file->f_mode & FMODE_READ) {
2582                                 stop_adc(s);
2583                                 s->dma_adc.ready = 0;
2584                                 set_adc_rate(s, val);
2585                         }
2586                         if (file->f_mode & FMODE_WRITE) {
2587                                 stop_dac(s);
2588                                 s->dma_dac.ready = 0;
2589                                 set_dac_rate(s, val);
2590                         }
2591                 }
2592                 return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, (int *)arg);
2593                 
2594         case SNDCTL_DSP_STEREO:
2595                 if (get_user(val, (int *)arg))
2596                         return -EFAULT;
2597                 fmtd = 0;
2598                 fmtm = ~0;
2599                 if (file->f_mode & FMODE_READ) {
2600                         stop_adc(s);
2601                         s->dma_adc.ready = 0;
2602                         if (val)
2603                                 fmtd |= ESS_FMT_STEREO << ESS_ADC_SHIFT;
2604                         else
2605                                 fmtm &= ~(ESS_FMT_STEREO << ESS_ADC_SHIFT);
2606                 }
2607                 if (file->f_mode & FMODE_WRITE) {
2608                         stop_dac(s);
2609                         s->dma_dac.ready = 0;
2610                         if (val)
2611                                 fmtd |= ESS_FMT_STEREO << ESS_DAC_SHIFT;
2612                         else
2613                                 fmtm &= ~(ESS_FMT_STEREO << ESS_DAC_SHIFT);
2614                 }
2615                 set_fmt(s, fmtm, fmtd);
2616                 return 0;
2617
2618         case SNDCTL_DSP_CHANNELS:
2619                 if (get_user(val, (int *)arg))
2620                         return -EFAULT;
2621                 if (val != 0) {
2622                         fmtd = 0;
2623                         fmtm = ~0;
2624                         if (file->f_mode & FMODE_READ) {
2625                                 stop_adc(s);
2626                                 s->dma_adc.ready = 0;
2627                                 if (val >= 2)
2628                                         fmtd |= ESS_FMT_STEREO << ESS_ADC_SHIFT;
2629                                 else
2630                                         fmtm &= ~(ESS_FMT_STEREO << ESS_ADC_SHIFT);
2631                         }
2632                         if (file->f_mode & FMODE_WRITE) {
2633                                 stop_dac(s);
2634                                 s->dma_dac.ready = 0;
2635                                 if (val >= 2)
2636                                         fmtd |= ESS_FMT_STEREO << ESS_DAC_SHIFT;
2637                                 else
2638                                         fmtm &= ~(ESS_FMT_STEREO << ESS_DAC_SHIFT);
2639                         }
2640                         set_fmt(s, fmtm, fmtd);
2641                 }
2642                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (ESS_FMT_STEREO << ESS_ADC_SHIFT) 
2643                                            : (ESS_FMT_STEREO << ESS_DAC_SHIFT))) ? 2 : 1, (int *)arg);
2644                 
2645         case SNDCTL_DSP_GETFMTS: /* Returns a mask */
2646                 return put_user(AFMT_U8|AFMT_S16_LE, (int *)arg);
2647                 
2648         case SNDCTL_DSP_SETFMT: /* Selects ONE fmt*/
2649                 if (get_user(val, (int *)arg))
2650                         return -EFAULT;
2651                 if (val != AFMT_QUERY) {
2652                         fmtd = 0;
2653                         fmtm = ~0;
2654                         if (file->f_mode & FMODE_READ) {
2655                                 stop_adc(s);
2656                                 s->dma_adc.ready = 0;
2657         /* fixed at 16bit for now */
2658                                 fmtd |= ESS_FMT_16BIT << ESS_ADC_SHIFT;
2659 #if 0
2660                                 if (val == AFMT_S16_LE)
2661                                         fmtd |= ESS_FMT_16BIT << ESS_ADC_SHIFT;
2662                                 else
2663                                         fmtm &= ~(ESS_FMT_16BIT << ESS_ADC_SHIFT);
2664 #endif
2665                         }
2666                         if (file->f_mode & FMODE_WRITE) {
2667                                 stop_dac(s);
2668                                 s->dma_dac.ready = 0;
2669                                 if (val == AFMT_S16_LE)
2670                                         fmtd |= ESS_FMT_16BIT << ESS_DAC_SHIFT;
2671                                 else
2672                                         fmtm &= ~(ESS_FMT_16BIT << ESS_DAC_SHIFT);
2673                         }
2674                         set_fmt(s, fmtm, fmtd);
2675                 }
2676                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? 
2677                         (ESS_FMT_16BIT << ESS_ADC_SHIFT) 
2678                         : (ESS_FMT_16BIT << ESS_DAC_SHIFT))) ? 
2679                                 AFMT_S16_LE : 
2680                                 AFMT_U8, 
2681                         (int *)arg);
2682                 
2683         case SNDCTL_DSP_POST:
2684                 return 0;
2685
2686         case SNDCTL_DSP_GETTRIGGER:
2687                 val = 0;
2688                 if ((file->f_mode & FMODE_READ) && (s->enable & ADC_RUNNING))
2689                         val |= PCM_ENABLE_INPUT;
2690                 if ((file->f_mode & FMODE_WRITE) && (s->enable & DAC_RUNNING)) 
2691                         val |= PCM_ENABLE_OUTPUT;
2692                 return put_user(val, (int *)arg);
2693                 
2694         case SNDCTL_DSP_SETTRIGGER:
2695                 if (get_user(val, (int *)arg))
2696                         return -EFAULT;
2697                 if (file->f_mode & FMODE_READ) {
2698                         if (val & PCM_ENABLE_INPUT) {
2699                                 if (!s->dma_adc.ready && (ret =  prog_dmabuf(s, 1)))
2700                                         return ret;
2701                                 start_adc(s);
2702                         } else
2703                                 stop_adc(s);
2704                 }
2705                 if (file->f_mode & FMODE_WRITE) {
2706                         if (val & PCM_ENABLE_OUTPUT) {
2707                                 if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2708                                         return ret;
2709                                 start_dac(s);
2710                         } else
2711                                 stop_dac(s);
2712                 }
2713                 return 0;
2714
2715         case SNDCTL_DSP_GETOSPACE:
2716                 if (!(file->f_mode & FMODE_WRITE))
2717                         return -EINVAL;
2718                 if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2719                         return ret;
2720                 spin_lock_irqsave(&s->lock, flags);
2721                 ess_update_ptr(s);
2722                 abinfo.fragsize = s->dma_dac.fragsize;
2723                 abinfo.bytes = s->dma_dac.dmasize - s->dma_dac.count;
2724                 abinfo.fragstotal = s->dma_dac.numfrag;
2725                 abinfo.fragments = abinfo.bytes >> s->dma_dac.fragshift;      
2726                 spin_unlock_irqrestore(&s->lock, flags);
2727                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2728
2729         case SNDCTL_DSP_GETISPACE:
2730                 if (!(file->f_mode & FMODE_READ))
2731                         return -EINVAL;
2732                 if (!s->dma_adc.ready && (ret =  prog_dmabuf(s, 1)))
2733                         return ret;
2734                 spin_lock_irqsave(&s->lock, flags);
2735                 ess_update_ptr(s);
2736                 abinfo.fragsize = s->dma_adc.fragsize;
2737                 abinfo.bytes = s->dma_adc.count;
2738                 abinfo.fragstotal = s->dma_adc.numfrag;
2739                 abinfo.fragments = abinfo.bytes >> s->dma_adc.fragshift;      
2740                 spin_unlock_irqrestore(&s->lock, flags);
2741                 return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2742                 
2743         case SNDCTL_DSP_NONBLOCK:
2744                 file->f_flags |= O_NONBLOCK;
2745                 return 0;
2746
2747         case SNDCTL_DSP_GETODELAY:
2748                 if (!(file->f_mode & FMODE_WRITE))
2749                         return -EINVAL;
2750                 if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2751                         return ret;
2752                 spin_lock_irqsave(&s->lock, flags);
2753                 ess_update_ptr(s);
2754                 val = s->dma_dac.count;
2755                 spin_unlock_irqrestore(&s->lock, flags);
2756                 return put_user(val, (int *)arg);
2757
2758         case SNDCTL_DSP_GETIPTR:
2759                 if (!(file->f_mode & FMODE_READ))
2760                         return -EINVAL;
2761                 if (!s->dma_adc.ready && (ret =  prog_dmabuf(s, 1)))
2762                         return ret;
2763                 spin_lock_irqsave(&s->lock, flags);
2764                 ess_update_ptr(s);
2765                 cinfo.bytes = s->dma_adc.total_bytes;
2766                 cinfo.blocks = s->dma_adc.count >> s->dma_adc.fragshift;
2767                 cinfo.ptr = s->dma_adc.hwptr;
2768                 if (s->dma_adc.mapped)
2769                         s->dma_adc.count &= s->dma_adc.fragsize-1;
2770                 spin_unlock_irqrestore(&s->lock, flags);
2771                 if (copy_to_user((void *)arg, &cinfo, sizeof(cinfo)))
2772                         return -EFAULT;
2773                 return 0;
2774
2775         case SNDCTL_DSP_GETOPTR:
2776                 if (!(file->f_mode & FMODE_WRITE))
2777                         return -EINVAL;
2778                 if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2779                         return ret;
2780                 spin_lock_irqsave(&s->lock, flags);
2781                 ess_update_ptr(s);
2782                 cinfo.bytes = s->dma_dac.total_bytes;
2783                 cinfo.blocks = s->dma_dac.count >> s->dma_dac.fragshift;
2784                 cinfo.ptr = s->dma_dac.hwptr;
2785                 if (s->dma_dac.mapped)
2786                         s->dma_dac.count &= s->dma_dac.fragsize-1;
2787                 spin_unlock_irqrestore(&s->lock, flags);
2788                 if (copy_to_user((void *)arg, &cinfo, sizeof(cinfo)))
2789                         return -EFAULT;
2790                 return 0;
2791
2792         case SNDCTL_DSP_GETBLKSIZE:
2793                 if (file->f_mode & FMODE_WRITE) {
2794                         if ((val = prog_dmabuf(s, 0)))
2795                                 return val;
2796                         return put_user(s->dma_dac.fragsize, (int *)arg);
2797                 }
2798                 if ((val = prog_dmabuf(s, 1)))
2799                         return val;
2800                 return put_user(s->dma_adc.fragsize, (int *)arg);
2801
2802         case SNDCTL_DSP_SETFRAGMENT:
2803                 if (get_user(val, (int *)arg))
2804                         return -EFAULT;
2805                 M_printk("maestro: SETFRAGMENT: %0x\n",val);
2806                 if (file->f_mode & FMODE_READ) {
2807                         s->dma_adc.ossfragshift = val & 0xffff;
2808                         s->dma_adc.ossmaxfrags = (val >> 16) & 0xffff;
2809                         if (s->dma_adc.ossfragshift < 4)
2810                                 s->dma_adc.ossfragshift = 4;
2811                         if (s->dma_adc.ossfragshift > 15)
2812                                 s->dma_adc.ossfragshift = 15;
2813                         if (s->dma_adc.ossmaxfrags < 4)
2814                                 s->dma_adc.ossmaxfrags = 4;
2815                 }
2816                 if (file->f_mode & FMODE_WRITE) {
2817                         s->dma_dac.ossfragshift = val & 0xffff;
2818                         s->dma_dac.ossmaxfrags = (val >> 16) & 0xffff;
2819                         if (s->dma_dac.ossfragshift < 4)
2820                                 s->dma_dac.ossfragshift = 4;
2821                         if (s->dma_dac.ossfragshift > 15)
2822                                 s->dma_dac.ossfragshift = 15;
2823                         if (s->dma_dac.ossmaxfrags < 4)
2824                                 s->dma_dac.ossmaxfrags = 4;
2825                 }
2826                 return 0;
2827
2828         case SNDCTL_DSP_SUBDIVIDE:
2829                 if ((file->f_mode & FMODE_READ && s->dma_adc.subdivision) ||
2830                     (file->f_mode & FMODE_WRITE && s->dma_dac.subdivision))
2831                         return -EINVAL;
2832                 if (get_user(val, (int *)arg))
2833                         return -EFAULT;
2834                 if (val != 1 && val != 2 && val != 4)
2835                         return -EINVAL;
2836                 if (file->f_mode & FMODE_READ)
2837                         s->dma_adc.subdivision = val;
2838                 if (file->f_mode & FMODE_WRITE)
2839                         s->dma_dac.subdivision = val;
2840                 return 0;
2841
2842         case SOUND_PCM_READ_RATE:
2843                 return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, (int *)arg);
2844
2845         case SOUND_PCM_READ_CHANNELS:
2846                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (ESS_FMT_STEREO << ESS_ADC_SHIFT) 
2847                                            : (ESS_FMT_STEREO << ESS_DAC_SHIFT))) ? 2 : 1, (int *)arg);
2848
2849         case SOUND_PCM_READ_BITS:
2850                 return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (ESS_FMT_16BIT << ESS_ADC_SHIFT) 
2851                                            : (ESS_FMT_16BIT << ESS_DAC_SHIFT))) ? 16 : 8, (int *)arg);
2852
2853         case SOUND_PCM_WRITE_FILTER:
2854         case SNDCTL_DSP_SETSYNCRO:
2855         case SOUND_PCM_READ_FILTER:
2856                 return -EINVAL;
2857                 
2858         }
2859         return -EINVAL;
2860 }
2861
2862 static void
2863 set_base_registers(struct ess_state *s,void *vaddr)
2864 {
2865         unsigned long packed_phys = virt_to_bus(vaddr)>>12;
2866         wave_set_register(s, 0x01FC , packed_phys);
2867         wave_set_register(s, 0x01FD , packed_phys);
2868         wave_set_register(s, 0x01FE , packed_phys);
2869         wave_set_register(s, 0x01FF , packed_phys);
2870 }
2871
2872 /* 
2873  * this guy makes sure we're in the right power
2874  * state for what we want to be doing 
2875  */
2876 static void maestro_power(struct ess_card *card, int tostate)
2877 {
2878         u16 active_mask = acpi_state_mask[tostate];
2879         u8 state;
2880
2881         if(!use_pm) return;
2882
2883         pci_read_config_byte(card->pcidev, card->power_regs+0x4, &state);
2884         state&=3;
2885
2886         /* make sure we're in the right state */
2887         if(state != tostate) {
2888                 M_printk(KERN_WARNING "maestro: dev %02x:%02x.%x switching from D%d to D%d\n",
2889                         card->pcidev->bus->number, 
2890                         PCI_SLOT(card->pcidev->devfn),
2891                         PCI_FUNC(card->pcidev->devfn),
2892                         state,tostate);
2893                 pci_write_config_byte(card->pcidev, card->power_regs+0x4, tostate);
2894         }
2895
2896         /* and make sure the units we care about are on 
2897                 XXX we might want to do this before state flipping? */
2898         pci_write_config_word(card->pcidev, 0x54, ~ active_mask);
2899         pci_write_config_word(card->pcidev, 0x56, ~ active_mask);
2900 }
2901
2902 /* we allocate a large power of two for all our memory.
2903         this is cut up into (not to scale :):
2904         |silly fifo word        | 512byte mixbuf per adc        | dac/adc * channels |
2905 */
2906 static int
2907 allocate_buffers(struct ess_state *s)
2908 {
2909         void *rawbuf=NULL;
2910         int order,i;
2911         struct page *page, *pend;
2912
2913         /* alloc as big a chunk as we can */
2914         for (order = (dsps_order + (16-PAGE_SHIFT) + 1); order >= (dsps_order + 2 + 1); order--)
2915                 if((rawbuf = (void *)__get_free_pages(GFP_KERNEL|GFP_DMA, order)))
2916                         break;
2917
2918         if (!rawbuf)
2919                 return 1;
2920
2921         M_printk("maestro: allocated %ld (%d) bytes at %p\n",PAGE_SIZE<<order,order, rawbuf);
2922
2923         if ((virt_to_bus(rawbuf) + (PAGE_SIZE << order) - 1) & ~((1<<28)-1))  {
2924                 printk(KERN_ERR "maestro: DMA buffer beyond 256MB! busaddr 0x%lx  size %ld\n",
2925                         virt_to_bus(rawbuf), PAGE_SIZE << order);
2926                 kfree(rawbuf);
2927                 return 1;
2928         }
2929
2930         s->card->dmapages = rawbuf;
2931         s->card->dmaorder = order;
2932
2933         for(i=0;i<NR_DSPS;i++) {
2934                 struct ess_state *ess = &s->card->channels[i];
2935
2936                 if(ess->dev_audio == -1)
2937                         continue;
2938
2939                 ess->dma_dac.ready = s->dma_dac.mapped = 0;
2940                 ess->dma_adc.ready = s->dma_adc.mapped = 0;
2941                 ess->dma_adc.buforder = ess->dma_dac.buforder = order - 1 - dsps_order - 1;
2942
2943                 /* offset dac and adc buffers starting half way through and then at each [da][ad]c's
2944                         order's intervals.. */
2945                 ess->dma_dac.rawbuf = rawbuf + (PAGE_SIZE<<(order-1)) + (i * ( PAGE_SIZE << (ess->dma_dac.buforder + 1 )));
2946                 ess->dma_adc.rawbuf = ess->dma_dac.rawbuf + ( PAGE_SIZE << ess->dma_dac.buforder);
2947                 /* offset mixbuf by a mixbuf so that the lame status fifo can
2948                         happily scribble away.. */ 
2949                 ess->mixbuf = rawbuf + (512 * (i+1));
2950
2951                 M_printk("maestro: setup apu %d: dac: %p adc: %p mix: %p\n",i,ess->dma_dac.rawbuf,
2952                         ess->dma_adc.rawbuf, ess->mixbuf);
2953
2954         }
2955
2956         /* now mark the pages as reserved; otherwise remap_page_range doesn't do what we want */
2957         pend = virt_to_page(rawbuf + (PAGE_SIZE << order) - 1);
2958         for (page = virt_to_page(rawbuf); page <= pend; page++)
2959                 SetPageReserved(page);
2960
2961         return 0;
2962
2963 static void
2964 free_buffers(struct ess_state *s)
2965 {
2966         struct page *page, *pend;
2967
2968         s->dma_dac.rawbuf = s->dma_adc.rawbuf = NULL;
2969         s->dma_dac.mapped = s->dma_adc.mapped = 0;
2970         s->dma_dac.ready = s->dma_adc.ready = 0;
2971
2972         M_printk("maestro: freeing %p\n",s->card->dmapages);
2973         /* undo marking the pages as reserved */
2974
2975         pend = virt_to_page(s->card->dmapages + (PAGE_SIZE << s->card->dmaorder) - 1);
2976         for (page = virt_to_page(s->card->dmapages); page <= pend; page++)
2977                 ClearPageReserved(page);
2978
2979         free_pages((unsigned long)s->card->dmapages,s->card->dmaorder);
2980         s->card->dmapages = NULL;
2981 }
2982
2983 static int 
2984 ess_open(struct inode *inode, struct file *file)
2985 {
2986         unsigned int minor = iminor(inode);
2987         struct ess_state *s = NULL;
2988         unsigned char fmtm = ~0, fmts = 0;
2989         struct pci_dev *pdev = NULL;
2990         /*
2991          *      Scan the cards and find the channel. We only
2992          *      do this at open time so it is ok
2993          */
2994
2995         while ((pdev = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, pdev)) != NULL) {
2996                 struct ess_card *c;
2997                 struct pci_driver *drvr;
2998
2999                 drvr = pci_dev_driver (pdev);
3000                 if (drvr == &maestro_pci_driver) {
3001                         int i;
3002                         struct ess_state *sp;
3003
3004                         c = (struct ess_card*)pci_get_drvdata (pdev);
3005                         if (!c)
3006                                 continue;
3007                         for(i=0;i<NR_DSPS;i++)
3008                         {
3009                                 sp=&c->channels[i];
3010                                 if(sp->dev_audio < 0)
3011                                         continue;
3012                                 if((sp->dev_audio ^ minor) & ~0xf)
3013                                         continue;
3014                                 s=sp;
3015                         }
3016                 }
3017         }
3018         if (!s)
3019                 return -ENODEV;
3020
3021         VALIDATE_STATE(s);
3022         file->private_data = s;
3023         /* wait for device to become free */
3024         down(&s->open_sem);
3025         while (s->open_mode & file->f_mode) {
3026                 if (file->f_flags & O_NONBLOCK) {
3027                         up(&s->open_sem);
3028                         return -EWOULDBLOCK;
3029                 }
3030                 up(&s->open_sem);
3031                 interruptible_sleep_on(&s->open_wait);
3032                 if (signal_pending(current))
3033                         return -ERESTARTSYS;
3034                 down(&s->open_sem);
3035         }
3036
3037         /* under semaphore.. */
3038         if ((s->card->dmapages==NULL) && allocate_buffers(s)) {
3039                 up(&s->open_sem);
3040                 return -ENOMEM;
3041         }
3042
3043         /* we're covered by the open_sem */
3044         if( ! s->card->dsps_open )  {
3045                 maestro_power(s->card,ACPI_D0);
3046                 start_bob(s);
3047         }
3048         s->card->dsps_open++;
3049         M_printk("maestro: open, %d bobs now\n",s->card->dsps_open);
3050
3051         /* ok, lets write WC base regs now that we've 
3052                 powered up the chip */
3053         M_printk("maestro: writing 0x%lx (bus 0x%lx) to the wp\n",virt_to_bus(s->card->dmapages),
3054                 ((virt_to_bus(s->card->dmapages))&0xFFE00000)>>12);
3055         set_base_registers(s,s->card->dmapages);
3056
3057         if (file->f_mode & FMODE_READ) {
3058 /*
3059                 fmtm &= ~((ESS_FMT_STEREO | ESS_FMT_16BIT) << ESS_ADC_SHIFT);
3060                 if ((minor & 0xf) == SND_DEV_DSP16)
3061                         fmts |= ESS_FMT_16BIT << ESS_ADC_SHIFT; */
3062
3063                 fmtm &= ~((ESS_FMT_STEREO|ESS_FMT_16BIT) << ESS_ADC_SHIFT);
3064                 fmts = (ESS_FMT_STEREO|ESS_FMT_16BIT) << ESS_ADC_SHIFT;
3065
3066                 s->dma_adc.ossfragshift = s->dma_adc.ossmaxfrags = s->dma_adc.subdivision = 0;
3067                 set_adc_rate(s, 8000);
3068         }
3069         if (file->f_mode & FMODE_WRITE) {
3070                 fmtm &= ~((ESS_FMT_STEREO | ESS_FMT_16BIT) << ESS_DAC_SHIFT);
3071                 if ((minor & 0xf) == SND_DEV_DSP16)
3072                         fmts |= ESS_FMT_16BIT << ESS_DAC_SHIFT;
3073
3074                 s->dma_dac.ossfragshift = s->dma_dac.ossmaxfrags = s->dma_dac.subdivision = 0;
3075                 set_dac_rate(s, 8000);
3076         }
3077         set_fmt(s, fmtm, fmts);
3078         s->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
3079
3080         up(&s->open_sem);
3081         return 0;
3082 }
3083
3084 static int 
3085 ess_release(struct inode *inode, struct file *file)
3086 {
3087         struct ess_state *s = (struct ess_state *)file->private_data;
3088
3089         VALIDATE_STATE(s);
3090         lock_kernel();
3091         if (file->f_mode & FMODE_WRITE)
3092                 drain_dac(s, file->f_flags & O_NONBLOCK);
3093         down(&s->open_sem);
3094         if (file->f_mode & FMODE_WRITE) {
3095                 stop_dac(s);
3096         }
3097         if (file->f_mode & FMODE_READ) {
3098                 stop_adc(s);
3099         }
3100                 
3101         s->open_mode &= (~file->f_mode) & (FMODE_READ|FMODE_WRITE);
3102         /* we're covered by the open_sem */
3103         M_printk("maestro: %d dsps now alive\n",s->card->dsps_open-1);
3104         if( --s->card->dsps_open <= 0) {
3105                 s->card->dsps_open = 0;
3106                 stop_bob(s);
3107                 free_buffers(s);
3108                 maestro_power(s->card,ACPI_D2);
3109         }
3110         up(&s->open_sem);
3111         wake_up(&s->open_wait);
3112         unlock_kernel();
3113         return 0;
3114 }
3115
3116 static struct file_operations ess_audio_fops = {
3117         .owner          = THIS_MODULE,
3118         .llseek         = no_llseek,
3119         .read           = ess_read,
3120         .write          = ess_write,
3121         .poll           = ess_poll,
3122         .ioctl          = ess_ioctl,
3123         .mmap           = ess_mmap,
3124         .open           = ess_open,
3125         .release        = ess_release,
3126 };
3127
3128 static int
3129 maestro_config(struct ess_card *card) 
3130 {
3131         struct pci_dev *pcidev = card->pcidev;
3132         struct ess_state *ess = &card->channels[0];
3133         int apu,iobase  = card->iobase;
3134         u16 w;
3135         u32 n;
3136
3137         /* We used to muck around with pci config space that
3138          * we had no business messing with.  We don't know enough
3139          * about the machine to know which DMA mode is appropriate, 
3140          * etc.  We were guessing wrong on some machines and making
3141          * them unhappy.  We now trust in the BIOS to do things right,
3142          * which almost certainly means a new host of problems will
3143          * arise with broken BIOS implementations.  screw 'em. 
3144          * We're already intolerant of machines that don't assign
3145          * IRQs.
3146          */
3147         
3148         /* do config work at full power */
3149         maestro_power(card,ACPI_D0);
3150          
3151         pci_read_config_word(pcidev, 0x50, &w);
3152
3153         w&=~(1<<5);                     /* Don't swap left/right (undoc)*/
3154         
3155         pci_write_config_word(pcidev, 0x50, w);
3156         
3157         pci_read_config_word(pcidev, 0x52, &w);
3158         w&=~(1<<15);            /* Turn off internal clock multiplier */
3159         /* XXX how do we know which to use? */
3160         w&=~(1<<14);            /* External clock */
3161         
3162         w|= (1<<7);             /* Hardware volume control on */
3163         w|= (1<<6);             /* Debounce off: easier to push the HWV buttons. */
3164         w&=~(1<<5);             /* GPIO 4:5 */
3165         w|= (1<<4);             /* Disconnect from the CHI.  Enabling this made a dell 7500 work. */
3166         w&=~(1<<2);             /* MIDI fix off (undoc) */
3167         w&=~(1<<1);             /* reserved, always write 0 */
3168         pci_write_config_word(pcidev, 0x52, w);
3169         
3170         /*
3171          *      Legacy mode
3172          */
3173
3174         pci_read_config_word(pcidev, 0x40, &w);
3175         w|=(1<<15);     /* legacy decode off */
3176         w&=~(1<<14);    /* Disable SIRQ */
3177         w&=~(0x1f);     /* disable mpu irq/io, game port, fm, SB */
3178          
3179         pci_write_config_word(pcidev, 0x40, w);
3180
3181         /* Set up 978 docking control chip. */
3182         pci_read_config_word(pcidev, 0x58, &w);
3183         w|=1<<2;        /* Enable 978. */
3184         w|=1<<3;        /* Turn on 978 hardware volume control. */
3185         w&=~(1<<11);    /* Turn on 978 mixer volume control. */
3186         pci_write_config_word(pcidev, 0x58, w);
3187         
3188         sound_reset(iobase);
3189
3190         /*
3191          *      Ring Bus Setup
3192          */
3193
3194         /* setup usual 0x34 stuff.. 0x36 may be chip specific */
3195         outw(0xC090, iobase+0x34); /* direct sound, stereo */
3196         udelay(20);
3197         outw(0x3000, iobase+0x36); /* direct sound, stereo */
3198         udelay(20);
3199
3200
3201         /*
3202          *      Reset the CODEC
3203          */
3204          
3205         maestro_ac97_reset(iobase,pcidev);
3206         
3207         /*
3208          *      Ring Bus Setup
3209          */
3210                  
3211         n=inl(iobase+0x34);
3212         n&=~0xF000;
3213         n|=12<<12;              /* Direct Sound, Stereo */
3214         outl(n, iobase+0x34);
3215
3216         n=inl(iobase+0x34);
3217         n&=~0x0F00;             /* Modem off */
3218         outl(n, iobase+0x34);
3219
3220         n=inl(iobase+0x34);
3221         n&=~0x00F0;
3222         n|=9<<4;                /* DAC, Stereo */
3223         outl(n, iobase+0x34);
3224         
3225         n=inl(iobase+0x34);
3226         n&=~0x000F;             /* ASSP off */
3227         outl(n, iobase+0x34);
3228         
3229         n=inl(iobase+0x34);
3230         n|=(1<<29);             /* Enable ring bus */
3231         outl(n, iobase+0x34);
3232         
3233         n=inl(iobase+0x34);
3234         n|=(1<<28);             /* Enable serial bus */
3235         outl(n, iobase+0x34);
3236         
3237         n=inl(iobase+0x34);
3238         n&=~0x00F00000;         /* MIC off */
3239         outl(n, iobase+0x34);
3240         
3241         n=inl(iobase+0x34);
3242         n&=~0x000F0000;         /* I2S off */
3243         outl(n, iobase+0x34);
3244         
3245
3246         w=inw(iobase+0x18);
3247         w&=~(1<<7);             /* ClkRun off */
3248         outw(w, iobase+0x18);
3249
3250         w=inw(iobase+0x18);
3251         w&=~(1<<6);             /* Hardware volume control interrupt off... for now. */
3252         outw(w, iobase+0x18);
3253         
3254         w=inw(iobase+0x18);
3255         w&=~(1<<4);             /* ASSP irq off */
3256         outw(w, iobase+0x18);
3257         
3258         w=inw(iobase+0x18);
3259         w&=~(1<<3);             /* ISDN irq off */
3260         outw(w, iobase+0x18);
3261         
3262         w=inw(iobase+0x18);
3263         w|=(1<<2);              /* Direct Sound IRQ on */
3264         outw(w, iobase+0x18);
3265
3266         w=inw(iobase+0x18);
3267         w&=~(1<<1);             /* MPU401 IRQ off */
3268         outw(w, iobase+0x18);
3269
3270         w=inw(iobase+0x18);
3271         w|=(1<<0);              /* SB IRQ on */
3272         outw(w, iobase+0x18);
3273
3274         /* Set hardware volume control registers to midpoints.
3275            We can tell which button was pushed based on how they change. */
3276         outb(0x88, iobase+0x1c);
3277         outb(0x88, iobase+0x1d);
3278         outb(0x88, iobase+0x1e);
3279         outb(0x88, iobase+0x1f);
3280
3281         /* it appears some maestros (dell 7500) only work if these are set,
3282                 regardless of whether we use the assp or not. */
3283
3284         outb(0, iobase+0xA4); 
3285         outb(3, iobase+0xA2); 
3286         outb(0, iobase+0xA6);
3287         
3288         for(apu=0;apu<16;apu++)
3289         {
3290                 /* Write 0 into the buffer area 0x1E0->1EF */
3291                 outw(0x01E0+apu, 0x10+iobase);
3292                 outw(0x0000, 0x12+iobase);
3293         
3294                 /*
3295                  * The 1.10 test program seem to write 0 into the buffer area
3296                  * 0x1D0-0x1DF too.
3297                  */
3298                 outw(0x01D0+apu, 0x10+iobase);
3299                 outw(0x0000, 0x12+iobase);
3300         }
3301
3302 #if 1
3303         wave_set_register(ess, IDR7_WAVE_ROMRAM, 
3304                 (wave_get_register(ess, IDR7_WAVE_ROMRAM)&0xFF00));
3305         wave_set_register(ess, IDR7_WAVE_ROMRAM,
3306                 wave_get_register(ess, IDR7_WAVE_ROMRAM)|0x100);
3307         wave_set_register(ess, IDR7_WAVE_ROMRAM,
3308                 wave_get_register(ess, IDR7_WAVE_ROMRAM)&~0x200);
3309         wave_set_register(ess, IDR7_WAVE_ROMRAM,
3310                 wave_get_register(ess, IDR7_WAVE_ROMRAM)|~0x400);
3311 #else           
3312         maestro_write(ess, IDR7_WAVE_ROMRAM, 
3313                 (maestro_read(ess, IDR7_WAVE_ROMRAM)&0xFF00));
3314         maestro_write(ess, IDR7_WAVE_ROMRAM,
3315                 maestro_read(ess, IDR7_WAVE_ROMRAM)|0x100);
3316         maestro_write(ess, IDR7_WAVE_ROMRAM,
3317                 maestro_read(ess, IDR7_WAVE_ROMRAM)&~0x200);
3318         maestro_write(ess, IDR7_WAVE_ROMRAM,
3319                 maestro_read(ess, IDR7_WAVE_ROMRAM)|0x400);
3320 #endif
3321         
3322         maestro_write(ess, IDR2_CRAM_DATA, 0x0000);
3323         maestro_write(ess, 0x08, 0xB004);
3324         /* Now back to the DirectSound stuff */
3325         maestro_write(ess, 0x09, 0x001B);
3326         maestro_write(ess, 0x0A, 0x8000);
3327         maestro_write(ess, 0x0B, 0x3F37);
3328         maestro_write(ess, 0x0C, 0x0098);
3329         
3330         /* parallel out ?? */
3331         maestro_write(ess, 0x0C, 
3332                 (maestro_read(ess, 0x0C)&~0xF000)|0x8000); 
3333         /* parallel in, has something to do with recording :) */
3334         maestro_write(ess, 0x0C, 
3335                 (maestro_read(ess, 0x0C)&~0x0F00)|0x0500);
3336
3337         maestro_write(ess, 0x0D, 0x7632);
3338                         
3339         /* Wave cache control on - test off, sg off, 
3340                 enable, enable extra chans 1Mb */
3341
3342         outw(inw(0x14+iobase)|(1<<8),0x14+iobase);
3343         outw(inw(0x14+iobase)&0xFE03,0x14+iobase);
3344         outw((inw(0x14+iobase)&0xFFFC), 0x14+iobase);
3345         outw(inw(0x14+iobase)|(1<<7),0x14+iobase);
3346
3347         outw(0xA1A0, 0x14+iobase);      /* 0300 ? */
3348
3349         /* Now clear the APU control ram */     
3350         for(apu=0;apu<NR_APUS;apu++)
3351         {
3352                 for(w=0;w<NR_APU_REGS;w++)
3353                         apu_set_register(ess, apu|ESS_CHAN_HARD, w, 0);
3354                 
3355         }
3356
3357         return 0;
3358         
3359 }
3360
3361 /* this guy tries to find the pci power management
3362  * register bank.  this should really be in core
3363  * code somewhere.  1 on success. */
3364 int
3365 parse_power(struct ess_card *card, struct pci_dev *pcidev)
3366 {
3367         u32 n;
3368         u16 w;
3369         u8 next;
3370         int max = 64;  /* an a 8bit guy pointing to 32bit guys
3371                                 can only express so much. */
3372
3373         card->power_regs = 0;
3374
3375         /* check to see if we have a capabilities list in
3376                 the config register */
3377         pci_read_config_word(pcidev, PCI_STATUS, &w);
3378         if(!(w & PCI_STATUS_CAP_LIST)) return 0;
3379
3380         /* walk the list, starting at the head. */
3381         pci_read_config_byte(pcidev,PCI_CAPABILITY_LIST,&next);
3382
3383         while(next && max--) {
3384                 pci_read_config_dword(pcidev, next & ~3, &n);
3385                 if((n & 0xff) == PCI_CAP_ID_PM) {
3386                         card->power_regs = next;
3387                         break;
3388                 }
3389                 next = ((n>>8) & 0xff);
3390         }
3391
3392         return card->power_regs ? 1 : 0;
3393 }
3394
3395 static int __init
3396 maestro_probe(struct pci_dev *pcidev,const struct pci_device_id *pdid)
3397 {
3398         int card_type = pdid->driver_data;
3399         u32 n;
3400         int iobase;
3401         int i, ret;
3402         struct ess_card *card;
3403         struct ess_state *ess;
3404         struct pm_dev *pmdev;
3405         int num = 0;
3406
3407 /* when built into the kernel, we only print version if device is found */
3408 #ifndef MODULE
3409         static int printed_version;
3410         if (!printed_version++)
3411                 printk(version);
3412 #endif
3413
3414         /* don't pick up weird modem maestros */
3415         if(((pcidev->class >> 8) & 0xffff) != PCI_CLASS_MULTIMEDIA_AUDIO)
3416                 return -ENODEV;
3417
3418
3419         if ((ret=pci_enable_device(pcidev)))
3420                 return ret;
3421                         
3422         iobase = pci_resource_start(pcidev,0);
3423         if (!iobase || !(pci_resource_flags(pcidev, 0 ) & IORESOURCE_IO))
3424                 return -ENODEV;
3425
3426         if(pcidev->irq == 0)
3427                 return -ENODEV;
3428
3429         /* stake our claim on the iospace */
3430         if( request_region(iobase, 256, card_names[card_type]) == NULL )
3431         {
3432                 printk(KERN_WARNING "maestro: can't allocate 256 bytes I/O at 0x%4.4x\n", iobase);
3433                 return -EBUSY;
3434         }
3435
3436         /* just to be sure */
3437         pci_set_master(pcidev);
3438
3439         card = kmalloc(sizeof(struct ess_card), GFP_KERNEL);
3440         if(card == NULL)
3441         {
3442                 printk(KERN_WARNING "maestro: out of memory\n");
3443                 release_region(iobase, 256);
3444                 return -ENOMEM;
3445         }
3446         
3447         memset(card, 0, sizeof(*card));
3448         card->pcidev = pcidev;
3449
3450         pmdev = pm_register(PM_PCI_DEV, PM_PCI_ID(pcidev),
3451                         maestro_pm_callback);
3452         if (pmdev)
3453                 pmdev->data = card;
3454
3455         card->iobase = iobase;
3456         card->card_type = card_type;
3457         card->irq = pcidev->irq;
3458         card->magic = ESS_CARD_MAGIC;
3459         spin_lock_init(&card->lock);
3460         init_waitqueue_head(&card->suspend_queue);
3461
3462         card->dock_mute_vol = 50;
3463         
3464         /* init our groups of 6 apus */
3465         for(i=0;i<NR_DSPS;i++)
3466         {
3467                 struct ess_state *s=&card->channels[i];
3468
3469                 s->index = i;
3470
3471                 s->card = card;
3472                 init_waitqueue_head(&s->dma_adc.wait);
3473                 init_waitqueue_head(&s->dma_dac.wait);
3474                 init_waitqueue_head(&s->open_wait);
3475                 spin_lock_init(&s->lock);
3476                 init_MUTEX(&s->open_sem);
3477                 s->magic = ESS_STATE_MAGIC;
3478                 
3479                 s->apu[0] = 6*i;
3480                 s->apu[1] = (6*i)+1;
3481                 s->apu[2] = (6*i)+2;
3482                 s->apu[3] = (6*i)+3;
3483                 s->apu[4] = (6*i)+4;
3484                 s->apu[5] = (6*i)+5;
3485                 
3486                 if(s->dma_adc.ready || s->dma_dac.ready || s->dma_adc.rawbuf)
3487                         printk("maestro: BOTCH!\n");
3488                 /* register devices */
3489                 if ((s->dev_audio = register_sound_dsp(&ess_audio_fops, -1)) < 0)
3490                         break;
3491         }
3492         
3493         num = i;
3494         
3495         /* clear the rest if we ran out of slots to register */
3496         for(;i<NR_DSPS;i++)
3497         {
3498                 struct ess_state *s=&card->channels[i];
3499                 s->dev_audio = -1;
3500         }
3501         
3502         ess = &card->channels[0];
3503
3504         /*
3505          *      Ok card ready. Begin setup proper
3506          */
3507
3508         printk(KERN_INFO "maestro: Configuring %s found at IO 0x%04X IRQ %d\n", 
3509                 card_names[card_type],iobase,card->irq);
3510         pci_read_config_dword(pcidev, PCI_SUBSYSTEM_VENDOR_ID, &n);
3511         printk(KERN_INFO "maestro:  subvendor id: 0x%08x\n",n); 
3512
3513         /* turn off power management unless:
3514          *      - the user explicitly asks for it
3515          *              or
3516          *              - we're not a 2e, lesser chipps seem to have problems.
3517          *              - we're not on our _very_ small whitelist.  some implemenetations
3518          *                      really don't like the pm code, others require it.
3519          *                      feel free to expand this as required.
3520          */
3521 #define SUBSYSTEM_VENDOR(x) (x&0xffff)
3522         if(     (use_pm != 1) && 
3523                 ((card_type != TYPE_MAESTRO2E)  || (SUBSYSTEM_VENDOR(n) != 0x1028)))
3524                         use_pm = 0;
3525
3526         if(!use_pm) 
3527                 printk(KERN_INFO "maestro: not attempting power management.\n");
3528         else {
3529                 if(!parse_power(card,pcidev)) 
3530                         printk(KERN_INFO "maestro: no PCI power management interface found.\n");
3531                 else {
3532                         pci_read_config_dword(pcidev, card->power_regs, &n);
3533                         printk(KERN_INFO "maestro: PCI power management capability: 0x%x\n",n>>16);
3534                 }       
3535         }
3536
3537         maestro_config(card);
3538
3539         if(maestro_ac97_get(card, 0x00)==0x0080) {
3540                 printk(KERN_ERR "maestro: my goodness!  you seem to have a pt101 codec, which is quite rare.\n"
3541                                 "\tyou should tell someone about this.\n");
3542         } else {
3543                 maestro_ac97_init(card);
3544         }
3545
3546         if ((card->dev_mixer = register_sound_mixer(&ess_mixer_fops, -1)) < 0) {
3547                 printk("maestro: couldn't register mixer!\n");
3548         } else {
3549                 memcpy(card->mix.mixer_state,mixer_defaults,sizeof(card->mix.mixer_state));
3550                 mixer_push_state(card);
3551         }
3552         
3553         if((ret=request_irq(card->irq, ess_interrupt, SA_SHIRQ, card_names[card_type], card)))
3554         {
3555                 printk(KERN_ERR "maestro: unable to allocate irq %d,\n", card->irq);
3556                 unregister_sound_mixer(card->dev_mixer);
3557                 for(i=0;i<NR_DSPS;i++)
3558                 {
3559                         struct ess_state *s = &card->channels[i];
3560                         if(s->dev_audio != -1)
3561                                 unregister_sound_dsp(s->dev_audio);
3562                 }
3563                 release_region(card->iobase, 256);              
3564                 unregister_reboot_notifier(&maestro_nb);
3565                 kfree(card);
3566                 return ret;
3567         }
3568
3569         /* Turn on hardware volume control interrupt.
3570            This has to come after we grab the IRQ above,
3571            or a crash will result on installation if a button has been pressed,
3572            because in that case we'll get an immediate interrupt. */
3573         n = inw(iobase+0x18);
3574         n|=(1<<6);
3575         outw(n, iobase+0x18);
3576
3577         pci_set_drvdata(pcidev,card);
3578         /* now go to sleep 'till something interesting happens */
3579         maestro_power(card,ACPI_D2);
3580
3581         printk(KERN_INFO "maestro: %d channels configured.\n", num);
3582         return 0;
3583 }
3584
3585 static void maestro_remove(struct pci_dev *pcidev) {
3586         struct ess_card *card = pci_get_drvdata(pcidev);
3587         int i;
3588         u32 n;
3589         
3590         /* XXX maybe should force stop bob, but should be all 
3591                 stopped by _release by now */
3592
3593         /* Turn off hardware volume control interrupt.
3594            This has to come before we leave the IRQ below,
3595            or a crash results if a button is pressed ! */
3596         n = inw(card->iobase+0x18);
3597         n&=~(1<<6);
3598         outw(n, card->iobase+0x18);
3599
3600         free_irq(card->irq, card);
3601         unregister_sound_mixer(card->dev_mixer);
3602         for(i=0;i<NR_DSPS;i++)
3603         {
3604                 struct ess_state *ess = &card->channels[i];
3605                 if(ess->dev_audio != -1)
3606                         unregister_sound_dsp(ess->dev_audio);
3607         }
3608         /* Goodbye, Mr. Bond. */
3609         maestro_power(card,ACPI_D3);
3610         release_region(card->iobase, 256);
3611         kfree(card);
3612         pci_set_drvdata(pcidev,NULL);
3613 }
3614
3615 static struct pci_device_id maestro_pci_tbl[] = {
3616         {PCI_VENDOR_ESS, PCI_DEVICE_ID_ESS_ESS1968, PCI_ANY_ID, PCI_ANY_ID, 0, 0, TYPE_MAESTRO2},
3617         {PCI_VENDOR_ESS, PCI_DEVICE_ID_ESS_ESS1978, PCI_ANY_ID, PCI_ANY_ID, 0, 0, TYPE_MAESTRO2E},
3618         {PCI_VENDOR_ESS_OLD, PCI_DEVICE_ID_ESS_ESS0100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, TYPE_MAESTRO},
3619         {0,}
3620 };
3621 MODULE_DEVICE_TABLE(pci, maestro_pci_tbl);
3622
3623 static struct pci_driver maestro_pci_driver = {
3624         .name     = "maestro",
3625         .id_table = maestro_pci_tbl,
3626         .probe    = maestro_probe,
3627         .remove   = maestro_remove,
3628 };
3629
3630 int __init init_maestro(void)
3631 {
3632         int rc;
3633
3634         rc = pci_module_init(&maestro_pci_driver);
3635         if (rc < 0)
3636                 return rc;
3637
3638         if (register_reboot_notifier(&maestro_nb))
3639                 printk(KERN_WARNING "maestro: reboot notifier registration failed; may not reboot properly.\n");
3640 #ifdef MODULE
3641         printk(version);
3642 #endif
3643         if (dsps_order < 0)   {
3644                 dsps_order = 1;
3645                 printk(KERN_WARNING "maestro: clipping dsps_order to %d\n",dsps_order);
3646         }
3647         else if (dsps_order > MAX_DSP_ORDER)  {
3648                 dsps_order = MAX_DSP_ORDER;
3649                 printk(KERN_WARNING "maestro: clipping dsps_order to %d\n",dsps_order);
3650         }
3651         return 0;
3652 }
3653
3654 static int maestro_notifier(struct notifier_block *nb, unsigned long event, void *buf)
3655 {
3656         /* this notifier is called when the kernel is really shut down. */
3657         M_printk("maestro: shutting down\n");
3658         /* this will remove all card instances too */
3659         pci_unregister_driver(&maestro_pci_driver);
3660         /* XXX dunno about power management */
3661         return NOTIFY_OK;
3662 }
3663
3664 /* --------------------------------------------------------------------- */
3665
3666
3667 void cleanup_maestro(void) {
3668         M_printk("maestro: unloading\n");
3669         pci_unregister_driver(&maestro_pci_driver);
3670         pm_unregister_all(maestro_pm_callback);
3671         unregister_reboot_notifier(&maestro_nb);
3672 }
3673
3674 /* --------------------------------------------------------------------- */
3675
3676 void
3677 check_suspend(struct ess_card *card)
3678 {
3679         DECLARE_WAITQUEUE(wait, current);
3680
3681         if(!card->in_suspend) return;
3682
3683         card->in_suspend++;
3684         add_wait_queue(&(card->suspend_queue), &wait);
3685         current->state = TASK_UNINTERRUPTIBLE;
3686         schedule();
3687         remove_wait_queue(&(card->suspend_queue), &wait);
3688         current->state = TASK_RUNNING;
3689 }
3690
3691 static int 
3692 maestro_suspend(struct ess_card *card)
3693 {
3694         unsigned long flags;
3695         int i,j;
3696
3697         spin_lock_irqsave(&card->lock,flags); /* over-kill */
3698
3699         M_printk("maestro: apm in dev %p\n",card);
3700
3701         /* we have to read from the apu regs, need
3702                 to power it up */
3703         maestro_power(card,ACPI_D0);
3704
3705         for(i=0;i<NR_DSPS;i++) {
3706                 struct ess_state *s = &card->channels[i];
3707
3708                 if(s->dev_audio == -1)
3709                         continue;
3710
3711                 M_printk("maestro: stopping apus for device %d\n",i);
3712                 stop_dac(s);
3713                 stop_adc(s);
3714                 for(j=0;j<6;j++) 
3715                         card->apu_map[s->apu[j]][5]=apu_get_register(s,j,5);
3716
3717         }
3718
3719         /* get rid of interrupts? */
3720         if( card->dsps_open > 0)
3721                 stop_bob(&card->channels[0]);
3722
3723         card->in_suspend++;
3724
3725         spin_unlock_irqrestore(&card->lock,flags);
3726
3727         /* we trust in the bios to power down the chip on suspend.
3728          * XXX I'm also not sure that in_suspend will protect
3729          * against all reg accesses from here on out. 
3730          */
3731         return 0;
3732 }
3733 static int 
3734 maestro_resume(struct ess_card *card)
3735 {
3736         unsigned long flags;
3737         int i;
3738
3739         spin_lock_irqsave(&card->lock,flags); /* over-kill */
3740
3741         card->in_suspend = 0;
3742
3743         M_printk("maestro: resuming card at %p\n",card);
3744
3745         /* restore all our config */
3746         maestro_config(card);
3747         /* need to restore the base pointers.. */ 
3748         if(card->dmapages) 
3749                 set_base_registers(&card->channels[0],card->dmapages);
3750
3751         mixer_push_state(card);
3752
3753         /* set each channels' apu control registers before
3754          * restoring audio 
3755          */
3756         for(i=0;i<NR_DSPS;i++) {
3757                 struct ess_state *s = &card->channels[i];
3758                 int chan,reg;
3759
3760                 if(s->dev_audio == -1)
3761                         continue;
3762
3763                 for(chan = 0 ; chan < 6 ; chan++) {
3764                         wave_set_register(s,s->apu[chan]<<3,s->apu_base[chan]);
3765                         for(reg = 1 ; reg < NR_APU_REGS ; reg++)  
3766                                 apu_set_register(s,chan,reg,s->card->apu_map[s->apu[chan]][reg]);
3767                 }
3768                 for(chan = 0 ; chan < 6 ; chan++)  
3769                         apu_set_register(s,chan,0,s->card->apu_map[s->apu[chan]][0] & 0xFF0F);
3770         }
3771
3772         /* now we flip on the music */
3773
3774         if( card->dsps_open <= 0) {
3775                 /* this card's idle */
3776                 maestro_power(card,ACPI_D2);
3777         } else {
3778                 /* ok, we're actually playing things on
3779                         this card */
3780                 maestro_power(card,ACPI_D0);
3781                 start_bob(&card->channels[0]);
3782                 for(i=0;i<NR_DSPS;i++) {
3783                         struct ess_state *s = &card->channels[i];
3784
3785                         /* these use the apu_mode, and can handle
3786                                 spurious calls */
3787                         start_dac(s);   
3788                         start_adc(s);   
3789                 }
3790         }
3791
3792         spin_unlock_irqrestore(&card->lock,flags);
3793
3794         /* all right, we think things are ready, 
3795                 wake up people who were using the device
3796                 when we suspended */
3797         wake_up(&(card->suspend_queue));
3798
3799         return 0;
3800 }
3801
3802 int 
3803 maestro_pm_callback(struct pm_dev *dev, pm_request_t rqst, void *data) 
3804 {
3805         struct ess_card *card = (struct ess_card*) dev->data;
3806
3807         if ( ! card ) goto out;
3808
3809         M_printk("maestro: pm event 0x%x received for card %p\n", rqst, card);
3810         
3811         switch (rqst) {
3812                 case PM_SUSPEND: 
3813                         maestro_suspend(card);
3814                 break;
3815                 case PM_RESUME: 
3816                         maestro_resume(card);
3817                 break;
3818                 /*
3819                  * we'd also like to find out about
3820                  * power level changes because some biosen
3821                  * do mean things to the maestro when they
3822                  * change their power state.
3823                  */
3824         }
3825 out:
3826         return 0;
3827 }
3828
3829 module_init(init_maestro);
3830 module_exit(cleanup_maestro);