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