Merge master.kernel.org:/pub/scm/linux/kernel/git/jejb/scsi-for-linus-2.6
[pandora-kernel.git] / sound / oss / nm256_audio.c
1 /* 
2  * Audio driver for the NeoMagic 256AV and 256ZX chipsets in native
3  * mode, with AC97 mixer support.
4  *
5  * Overall design and parts of this code stolen from vidc_*.c and
6  * skeleton.c.
7  *
8  * Yeah, there are a lot of magic constants in here.  You tell ME what
9  * they are.  I just get this stuff psychically, remember? 
10  *
11  * This driver was written by someone who wishes to remain anonymous. 
12  * It is in the public domain, so share and enjoy.  Try to make a profit
13  * off of it; go on, I dare you.  
14  *
15  * Changes:
16  * 11-10-2000   Bartlomiej Zolnierkiewicz <bkz@linux-ide.org>
17  *              Added some __init
18  * 19-04-2001   Marcus Meissner <mm@caldera.de>
19  *              Ported to 2.4 PCI API.
20  */
21
22 #include <linux/pci.h>
23 #include <linux/init.h>
24 #include <linux/interrupt.h>
25 #include <linux/kernel.h>
26 #include <linux/module.h>
27 #include <linux/pm.h>
28 #include <linux/delay.h>
29 #include <linux/spinlock.h>
30 #include "sound_config.h"
31
32 static int nm256_debug;
33 static int force_load;
34
35 #include "nm256.h"
36 #include "nm256_coeff.h"
37
38 /* 
39  * The size of the playback reserve.  When the playback buffer has less
40  * than NM256_PLAY_WMARK_SIZE bytes to output, we request a new
41  * buffer.
42  */
43 #define NM256_PLAY_WMARK_SIZE 512
44
45 static struct audio_driver nm256_audio_driver;
46
47 static int nm256_grabInterrupt (struct nm256_info *card);
48 static int nm256_releaseInterrupt (struct nm256_info *card);
49 static irqreturn_t nm256_interrupt (int irq, void *dev_id, struct pt_regs *dummy);
50 static irqreturn_t nm256_interrupt_zx (int irq, void *dev_id, struct pt_regs *dummy);
51 static int handle_pm_event (struct pm_dev *dev, pm_request_t rqst, void *data);
52
53 /* These belong in linux/pci.h. */
54 #define PCI_DEVICE_ID_NEOMAGIC_NM256AV_AUDIO 0x8005
55 #define PCI_DEVICE_ID_NEOMAGIC_NM256ZX_AUDIO 0x8006
56 #define PCI_DEVICE_ID_NEOMAGIC_NM256XL_PLUS_AUDIO 0x8016
57
58 /* List of cards.  */
59 static struct nm256_info *nmcard_list;
60
61 /* Release the mapped-in memory for CARD.  */
62 static void
63 nm256_release_ports (struct nm256_info *card)
64 {
65     int x;
66
67     for (x = 0; x < 2; x++) {
68         if (card->port[x].ptr != NULL) {
69             iounmap (card->port[x].ptr);
70             card->port[x].ptr = NULL;
71         }
72     }
73 }
74
75 /* 
76  * Map in the memory ports for CARD, if they aren't already mapped in
77  * and have been configured.  If successful, a zero value is returned;
78  * otherwise any previously mapped-in areas are released and a non-zero
79  * value is returned.
80  *
81  * This is invoked twice, once for each port.  Ideally it would only be
82  * called once, but we now need to map in the second port in order to
83  * check how much memory the card has on the 256ZX.
84  */
85 static int
86 nm256_remap_ports (struct nm256_info *card)
87 {
88     int x;
89
90     for (x = 0; x < 2; x++) {
91         if (card->port[x].ptr == NULL && card->port[x].end_offset > 0) {
92             u32 physaddr 
93                 = card->port[x].physaddr + card->port[x].start_offset;
94             u32 size 
95                 = card->port[x].end_offset - card->port[x].start_offset;
96
97             card->port[x].ptr = ioremap_nocache (physaddr, size);
98                                                   
99             if (card->port[x].ptr == NULL) {
100                 printk (KERN_ERR "NM256: Unable to remap port %d\n", x + 1);
101                 nm256_release_ports (card);
102                 return -1;
103             }
104         }
105     }
106     return 0;
107 }
108
109 /* Locate the card in our list. */
110 static struct nm256_info *
111 nm256_find_card (int dev)
112 {
113     struct nm256_info *card;
114
115     for (card = nmcard_list; card != NULL; card = card->next_card)
116         if (card->dev[0] == dev || card->dev[1] == dev)
117             return card;
118
119     return NULL;
120 }
121
122 /*
123  * Ditto, but find the card struct corresponding to the mixer device DEV 
124  * instead. 
125  */
126 static struct nm256_info *
127 nm256_find_card_for_mixer (int dev)
128 {
129     struct nm256_info *card;
130
131     for (card = nmcard_list; card != NULL; card = card->next_card)
132         if (card->mixer_oss_dev == dev)
133             return card;
134
135     return NULL;
136 }
137
138 static int usecache;
139 static int buffertop;
140
141 /* Check to see if we're using the bank of cached coefficients. */
142 static int
143 nm256_cachedCoefficients (struct nm256_info *card)
144 {
145     return usecache;
146 }
147
148 /* The actual rates supported by the card. */
149 static int samplerates[9] = {
150     8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 99999999
151 };
152
153 /*
154  * Set the card samplerate, word size and stereo mode to correspond to
155  * the settings in the CARD struct for the specified device in DEV.
156  * We keep two separate sets of information, one for each device; the
157  * hardware is not actually configured until a read or write is
158  * attempted.
159  */
160
161 static int
162 nm256_setInfo (int dev, struct nm256_info *card)
163 {
164     int x;
165     int w;
166     int targetrate;
167
168     if (card->dev[0] == dev)
169         w = 0;
170     else if (card->dev[1] == dev)
171         w = 1;
172     else
173         return -ENODEV;
174
175     targetrate = card->sinfo[w].samplerate;
176
177     if ((card->sinfo[w].bits != 8 && card->sinfo[w].bits != 16)
178         || targetrate < samplerates[0]
179         || targetrate > samplerates[7])
180         return -EINVAL;
181
182     for (x = 0; x < 8; x++)
183         if (targetrate < ((samplerates[x] + samplerates[x + 1]) / 2))
184             break;
185
186     if (x < 8) {
187         u8 ratebits = ((x << 4) & NM_RATE_MASK);
188         if (card->sinfo[w].bits == 16)
189             ratebits |= NM_RATE_BITS_16;
190         if (card->sinfo[w].stereo)
191             ratebits |= NM_RATE_STEREO;
192
193         card->sinfo[w].samplerate = samplerates[x];
194
195
196         if (card->dev_for_play == dev && card->playing) {
197             if (nm256_debug)
198                 printk (KERN_DEBUG "Setting play ratebits to 0x%x\n",
199                         ratebits);
200             nm256_loadCoefficient (card, 0, x);
201             nm256_writePort8 (card, 2,
202                               NM_PLAYBACK_REG_OFFSET + NM_RATE_REG_OFFSET,
203                               ratebits);
204         }
205
206         if (card->dev_for_record == dev && card->recording) {
207             if (nm256_debug)
208                 printk (KERN_DEBUG "Setting record ratebits to 0x%x\n",
209                         ratebits);
210             nm256_loadCoefficient (card, 1, x);
211             nm256_writePort8 (card, 2,
212                               NM_RECORD_REG_OFFSET + NM_RATE_REG_OFFSET,
213                               ratebits);
214         }
215         return 0;
216     }
217     else
218         return -EINVAL;
219 }
220
221 /* Start the play process going. */
222 static void
223 startPlay (struct nm256_info *card)
224 {
225     if (! card->playing) {
226         card->playing = 1;
227         if (nm256_grabInterrupt (card) == 0) {
228             nm256_setInfo (card->dev_for_play, card);
229
230             /* Enable playback engine and interrupts. */
231             nm256_writePort8 (card, 2, NM_PLAYBACK_ENABLE_REG,
232                               NM_PLAYBACK_ENABLE_FLAG | NM_PLAYBACK_FREERUN);
233
234             /* Enable both channels. */
235             nm256_writePort16 (card, 2, NM_AUDIO_MUTE_REG, 0x0);
236         }
237     }
238 }
239
240 /* 
241  * Request one chunk of AMT bytes from the recording device.  When the
242  * operation is complete, the data will be copied into BUFFER and the
243  * function DMAbuf_inputintr will be invoked.
244  */
245
246 static void
247 nm256_startRecording (struct nm256_info *card, char *buffer, u32 amt)
248 {
249     u32 endpos;
250     int enableEngine = 0;
251     u32 ringsize = card->recordBufferSize;
252     unsigned long flags;
253
254     if (amt > (ringsize / 2)) {
255         /*
256          * Of course this won't actually work right, because the
257          * caller is going to assume we will give what we got asked
258          * for.
259          */
260         printk (KERN_ERR "NM256: Read request too large: %d\n", amt);
261         amt = ringsize / 2;
262     }
263
264     if (amt < 8) {
265         printk (KERN_ERR "NM256: Read request too small; %d\n", amt);
266         return;
267     }
268
269     spin_lock_irqsave(&card->lock,flags);
270     /*
271      * If we're not currently recording, set up the start and end registers
272      * for the recording engine.
273      */
274     if (! card->recording) {
275         card->recording = 1;
276         if (nm256_grabInterrupt (card) == 0) {
277             card->curRecPos = 0;
278             nm256_setInfo (card->dev_for_record, card);
279             nm256_writePort32 (card, 2, NM_RBUFFER_START, card->abuf2);
280             nm256_writePort32 (card, 2, NM_RBUFFER_END,
281                                  card->abuf2 + ringsize);
282
283             nm256_writePort32 (card, 2, NM_RBUFFER_CURRP,
284                                  card->abuf2 + card->curRecPos);
285             enableEngine = 1;
286         }
287         else {
288             /* Not sure what else to do here.  */
289             spin_unlock_irqrestore(&card->lock,flags);
290             return;
291         }
292     }
293
294     /* 
295      * If we happen to go past the end of the buffer a bit (due to a
296      * delayed interrupt) it's OK.  So might as well set the watermark
297      * right at the end of the data we want.
298      */
299     endpos = card->abuf2 + ((card->curRecPos + amt) % ringsize);
300
301     card->recBuf = buffer;
302     card->requestedRecAmt = amt;
303     nm256_writePort32 (card, 2, NM_RBUFFER_WMARK, endpos);
304     /* Enable recording engine and interrupts. */
305     if (enableEngine)
306         nm256_writePort8 (card, 2, NM_RECORD_ENABLE_REG,
307                             NM_RECORD_ENABLE_FLAG | NM_RECORD_FREERUN);
308
309     spin_unlock_irqrestore(&card->lock,flags);
310 }
311
312 /* Stop the play engine. */
313 static void
314 stopPlay (struct nm256_info *card)
315 {
316     /* Shut off sound from both channels. */
317     nm256_writePort16 (card, 2, NM_AUDIO_MUTE_REG,
318                        NM_AUDIO_MUTE_LEFT | NM_AUDIO_MUTE_RIGHT);
319     /* Disable play engine. */
320     nm256_writePort8 (card, 2, NM_PLAYBACK_ENABLE_REG, 0);
321     if (card->playing) {
322         nm256_releaseInterrupt (card);
323
324         /* Reset the relevant state bits. */
325         card->playing = 0;
326         card->curPlayPos = 0;
327     }
328 }
329
330 /* Stop recording. */
331 static void
332 stopRecord (struct nm256_info *card)
333 {
334     /* Disable recording engine. */
335     nm256_writePort8 (card, 2, NM_RECORD_ENABLE_REG, 0);
336
337     if (card->recording) {
338         nm256_releaseInterrupt (card);
339
340         card->recording = 0;
341         card->curRecPos = 0;
342     }
343 }
344
345 /*
346  * Ring buffers, man.  That's where the hip-hop, wild-n-wooly action's at.
347  * 1972?  (Well, I suppose it was cheep-n-easy to implement.)
348  *
349  * Write AMT bytes of BUFFER to the playback ring buffer, and start the
350  * playback engine running.  It will only accept up to 1/2 of the total
351  * size of the ring buffer.  No check is made that we're about to overwrite
352  * the currently-playing sample.
353  */
354
355 static void
356 nm256_write_block (struct nm256_info *card, char *buffer, u32 amt)
357 {
358     u32 ringsize = card->playbackBufferSize;
359     u32 endstop;
360     unsigned long flags;
361
362     if (amt > (ringsize / 2)) {
363         printk (KERN_ERR "NM256: Write request too large: %d\n", amt);
364         amt = (ringsize / 2);
365     }
366
367     if (amt < NM256_PLAY_WMARK_SIZE) {
368         printk (KERN_ERR "NM256: Write request too small: %d\n", amt);
369         return;
370     }
371
372     card->curPlayPos %= ringsize;
373
374     card->requested_amt = amt;
375
376     spin_lock_irqsave(&card->lock,flags);
377
378     if ((card->curPlayPos + amt) >= ringsize) {
379         u32 rem = ringsize - card->curPlayPos;
380
381         nm256_writeBuffer8 (card, buffer, 1,
382                               card->abuf1 + card->curPlayPos,
383                               rem);
384         if (amt > rem)
385             nm256_writeBuffer8 (card, buffer + rem, 1, card->abuf1,
386                                   amt - rem);
387     } 
388     else
389         nm256_writeBuffer8 (card, buffer, 1,
390                               card->abuf1 + card->curPlayPos,
391                               amt);
392
393     /*
394      * Setup the start-n-stop-n-limit registers, and start that engine
395      * goin'. 
396      *
397      * Normally we just let it wrap around to avoid the click-click
398      * action scene.
399      */
400     if (! card->playing) {
401         /* The PBUFFER_END register in this case points to one sample
402            before the end of the buffer. */
403         int w = (card->dev_for_play == card->dev[0] ? 0 : 1);
404         int sampsize = (card->sinfo[w].bits == 16 ? 2 : 1);
405
406         if (card->sinfo[w].stereo)
407             sampsize *= 2;
408
409         /* Need to set the not-normally-changing-registers up. */
410         nm256_writePort32 (card, 2, NM_PBUFFER_START,
411                              card->abuf1 + card->curPlayPos);
412         nm256_writePort32 (card, 2, NM_PBUFFER_END,
413                              card->abuf1 + ringsize - sampsize);
414         nm256_writePort32 (card, 2, NM_PBUFFER_CURRP,
415                              card->abuf1 + card->curPlayPos);
416     }
417     endstop = (card->curPlayPos + amt - NM256_PLAY_WMARK_SIZE) % ringsize;
418     nm256_writePort32 (card, 2, NM_PBUFFER_WMARK, card->abuf1 + endstop);
419
420     if (! card->playing)
421         startPlay (card);
422
423     spin_unlock_irqrestore(&card->lock,flags);
424 }
425
426 /*  We just got a card playback interrupt; process it.  */
427 static void
428 nm256_get_new_block (struct nm256_info *card)
429 {
430     /* Check to see how much got played so far. */
431     u32 amt = nm256_readPort32 (card, 2, NM_PBUFFER_CURRP) - card->abuf1;
432
433     if (amt >= card->playbackBufferSize) {
434         printk (KERN_ERR "NM256: Sound playback pointer invalid!\n");
435         amt = 0;
436     }
437
438     if (amt < card->curPlayPos)
439         amt = (card->playbackBufferSize - card->curPlayPos) + amt;
440     else
441         amt -= card->curPlayPos;
442
443     if (card->requested_amt > (amt + NM256_PLAY_WMARK_SIZE)) {
444         u32 endstop =
445             card->curPlayPos + card->requested_amt - NM256_PLAY_WMARK_SIZE;
446         nm256_writePort32 (card, 2, NM_PBUFFER_WMARK, card->abuf1 + endstop);
447     } 
448     else {
449         card->curPlayPos += card->requested_amt;
450         /* Get a new block to write.  This will eventually invoke
451            nm256_write_block () or stopPlay ().  */
452         DMAbuf_outputintr (card->dev_for_play, 1);
453     }
454 }
455
456 /* 
457  * Read the last-recorded block from the ring buffer, copy it into the
458  * saved buffer pointer, and invoke DMAuf_inputintr() with the recording
459  * device. 
460  */
461
462 static void
463 nm256_read_block (struct nm256_info *card)
464 {
465     /* Grab the current position of the recording pointer. */
466     u32 currptr = nm256_readPort32 (card, 2, NM_RBUFFER_CURRP) - card->abuf2;
467     u32 amtToRead = card->requestedRecAmt;
468     u32 ringsize = card->recordBufferSize;
469
470     if (currptr >= card->recordBufferSize) {
471         printk (KERN_ERR "NM256: Sound buffer record pointer invalid!\n");
472         currptr = 0;
473     }
474
475     /*
476      * This test is probably redundant; we shouldn't be here unless
477      * it's true.
478      */
479     if (card->recording) {
480         /* If we wrapped around, copy everything from the start of our
481            recording buffer to the end of the buffer. */
482         if (currptr < card->curRecPos) {
483             u32 amt = min (ringsize - card->curRecPos, amtToRead);
484
485             nm256_readBuffer8 (card, card->recBuf, 1,
486                                  card->abuf2 + card->curRecPos,
487                                  amt);
488             amtToRead -= amt;
489             card->curRecPos += amt;
490             card->recBuf += amt;
491             if (card->curRecPos == ringsize)
492                 card->curRecPos = 0;
493         }
494
495         if ((card->curRecPos < currptr) && (amtToRead > 0)) {
496             u32 amt = min (currptr - card->curRecPos, amtToRead);
497             nm256_readBuffer8 (card, card->recBuf, 1,
498                                  card->abuf2 + card->curRecPos, amt);
499             card->curRecPos = ((card->curRecPos + amt) % ringsize);
500         }
501         card->recBuf = NULL;
502         card->requestedRecAmt = 0;
503         DMAbuf_inputintr (card->dev_for_record);
504     }
505 }
506
507 /*
508  * Initialize the hardware. 
509  */
510 static void
511 nm256_initHw (struct nm256_info *card)
512 {
513     /* Reset everything. */
514     nm256_writePort8 (card, 2, 0x0, 0x11);
515     nm256_writePort16 (card, 2, 0x214, 0);
516
517     stopRecord (card);
518     stopPlay (card);
519 }
520
521 /* 
522  * Handle a potential interrupt for the device referred to by DEV_ID. 
523  *
524  * I don't like the cut-n-paste job here either between the two routines,
525  * but there are sufficient differences between the two interrupt handlers
526  * that parameterizing it isn't all that great either.  (Could use a macro,
527  * I suppose...yucky bleah.)
528  */
529
530 static irqreturn_t
531 nm256_interrupt (int irq, void *dev_id, struct pt_regs *dummy)
532 {
533     struct nm256_info *card = (struct nm256_info *)dev_id;
534     u16 status;
535     static int badintrcount;
536     int handled = 0;
537
538     if ((card == NULL) || (card->magsig != NM_MAGIC_SIG)) {
539         printk (KERN_ERR "NM256: Bad card pointer\n");
540         return IRQ_NONE;
541     }
542
543     status = nm256_readPort16 (card, 2, NM_INT_REG);
544
545     /* Not ours. */
546     if (status == 0) {
547         if (badintrcount++ > 1000) {
548             /*
549              * I'm not sure if the best thing is to stop the card from
550              * playing or just release the interrupt (after all, we're in
551              * a bad situation, so doing fancy stuff may not be such a good
552              * idea).
553              *
554              * I worry about the card engine continuing to play noise
555              * over and over, however--that could become a very
556              * obnoxious problem.  And we know that when this usually
557              * happens things are fairly safe, it just means the user's
558              * inserted a PCMCIA card and someone's spamming us with IRQ 9s.
559              */
560
561             handled = 1;
562             if (card->playing)
563                 stopPlay (card);
564             if (card->recording)
565                 stopRecord (card);
566             badintrcount = 0;
567         }
568         return IRQ_RETVAL(handled);
569     }
570
571     badintrcount = 0;
572
573     /* Rather boring; check for individual interrupts and process them. */
574
575     if (status & NM_PLAYBACK_INT) {
576         handled = 1;
577         status &= ~NM_PLAYBACK_INT;
578         NM_ACK_INT (card, NM_PLAYBACK_INT);
579
580         if (card->playing)
581             nm256_get_new_block (card);
582     }
583
584     if (status & NM_RECORD_INT) {
585         handled = 1;
586         status &= ~NM_RECORD_INT;
587         NM_ACK_INT (card, NM_RECORD_INT);
588
589         if (card->recording)
590             nm256_read_block (card);
591     }
592
593     if (status & NM_MISC_INT_1) {
594         u8 cbyte;
595
596         handled = 1;
597         status &= ~NM_MISC_INT_1;
598         printk (KERN_ERR "NM256: Got misc interrupt #1\n");
599         NM_ACK_INT (card, NM_MISC_INT_1);
600         nm256_writePort16 (card, 2, NM_INT_REG, 0x8000);
601         cbyte = nm256_readPort8 (card, 2, 0x400);
602         nm256_writePort8 (card, 2, 0x400, cbyte | 2);
603     }
604
605     if (status & NM_MISC_INT_2) {
606         u8 cbyte;
607
608         handled = 1;
609         status &= ~NM_MISC_INT_2;
610         printk (KERN_ERR "NM256: Got misc interrupt #2\n");
611         NM_ACK_INT (card, NM_MISC_INT_2);
612         cbyte = nm256_readPort8 (card, 2, 0x400);
613         nm256_writePort8 (card, 2, 0x400, cbyte & ~2);
614     }
615
616     /* Unknown interrupt. */
617     if (status) {
618         handled = 1;
619         printk (KERN_ERR "NM256: Fire in the hole! Unknown status 0x%x\n",
620                 status);
621         /* Pray. */
622         NM_ACK_INT (card, status);
623     }
624     return IRQ_RETVAL(handled);
625 }
626
627 /*
628  * Handle a potential interrupt for the device referred to by DEV_ID.
629  * This handler is for the 256ZX, and is very similar to the non-ZX
630  * routine.
631  */
632
633 static irqreturn_t
634 nm256_interrupt_zx (int irq, void *dev_id, struct pt_regs *dummy)
635 {
636     struct nm256_info *card = (struct nm256_info *)dev_id;
637     u32 status;
638     static int badintrcount;
639     int handled = 0;
640
641     if ((card == NULL) || (card->magsig != NM_MAGIC_SIG)) {
642         printk (KERN_ERR "NM256: Bad card pointer\n");
643         return IRQ_NONE;
644     }
645
646     status = nm256_readPort32 (card, 2, NM_INT_REG);
647
648     /* Not ours. */
649     if (status == 0) {
650         if (badintrcount++ > 1000) {
651             printk (KERN_ERR "NM256: Releasing interrupt, over 1000 invalid interrupts\n");
652             /*
653              * I'm not sure if the best thing is to stop the card from
654              * playing or just release the interrupt (after all, we're in
655              * a bad situation, so doing fancy stuff may not be such a good
656              * idea).
657              *
658              * I worry about the card engine continuing to play noise
659              * over and over, however--that could become a very
660              * obnoxious problem.  And we know that when this usually
661              * happens things are fairly safe, it just means the user's
662              * inserted a PCMCIA card and someone's spamming us with 
663              * IRQ 9s.
664              */
665
666             handled = 1;
667             if (card->playing)
668                 stopPlay (card);
669             if (card->recording)
670                 stopRecord (card);
671             badintrcount = 0;
672         }
673         return IRQ_RETVAL(handled);
674     }
675
676     badintrcount = 0;
677
678     /* Rather boring; check for individual interrupts and process them. */
679
680     if (status & NM2_PLAYBACK_INT) {
681         handled = 1;
682         status &= ~NM2_PLAYBACK_INT;
683         NM2_ACK_INT (card, NM2_PLAYBACK_INT);
684
685         if (card->playing)
686             nm256_get_new_block (card);
687     }
688
689     if (status & NM2_RECORD_INT) {
690         handled = 1;
691         status &= ~NM2_RECORD_INT;
692         NM2_ACK_INT (card, NM2_RECORD_INT);
693
694         if (card->recording)
695             nm256_read_block (card);
696     }
697
698     if (status & NM2_MISC_INT_1) {
699         u8 cbyte;
700
701         handled = 1;
702         status &= ~NM2_MISC_INT_1;
703         printk (KERN_ERR "NM256: Got misc interrupt #1\n");
704         NM2_ACK_INT (card, NM2_MISC_INT_1);
705         cbyte = nm256_readPort8 (card, 2, 0x400);
706         nm256_writePort8 (card, 2, 0x400, cbyte | 2);
707     }
708
709     if (status & NM2_MISC_INT_2) {
710         u8 cbyte;
711
712         handled = 1;
713         status &= ~NM2_MISC_INT_2;
714         printk (KERN_ERR "NM256: Got misc interrupt #2\n");
715         NM2_ACK_INT (card, NM2_MISC_INT_2);
716         cbyte = nm256_readPort8 (card, 2, 0x400);
717         nm256_writePort8 (card, 2, 0x400, cbyte & ~2);
718     }
719
720     /* Unknown interrupt. */
721     if (status) {
722         handled = 1;
723         printk (KERN_ERR "NM256: Fire in the hole! Unknown status 0x%x\n",
724                 status);
725         /* Pray. */
726         NM2_ACK_INT (card, status);
727     }
728     return IRQ_RETVAL(handled);
729 }
730
731 /* 
732  * Request our interrupt.
733  */
734 static int
735 nm256_grabInterrupt (struct nm256_info *card)
736 {
737     if (card->has_irq++ == 0) {
738         if (request_irq (card->irq, card->introutine, SA_SHIRQ,
739                          "NM256_audio", card) < 0) {
740             printk (KERN_ERR "NM256: can't obtain IRQ %d\n", card->irq);
741             return -1;
742         }
743     }
744     return 0;
745 }
746
747 /* 
748  * Release our interrupt. 
749  */
750 static int
751 nm256_releaseInterrupt (struct nm256_info *card)
752 {
753     if (card->has_irq <= 0) {
754         printk (KERN_ERR "nm256: too many calls to releaseInterrupt\n");
755         return -1;
756     }
757     card->has_irq--;
758     if (card->has_irq == 0) {
759         free_irq (card->irq, card);
760     }
761     return 0;
762 }
763
764 /*
765  * Waits for the mixer to become ready to be written; returns a zero value
766  * if it timed out.
767  */
768
769 static int
770 nm256_isReady (struct ac97_hwint *dev)
771 {
772     struct nm256_info *card = (struct nm256_info *)dev->driver_private;
773     int t2 = 10;
774     u32 testaddr;
775     u16 testb;
776     int done = 0;
777
778     if (card->magsig != NM_MAGIC_SIG) {
779         printk (KERN_ERR "NM256: Bad magic signature in isReady!\n");
780         return 0;
781     }
782
783     testaddr = card->mixer_status_offset;
784     testb = card->mixer_status_mask;
785
786     /* 
787      * Loop around waiting for the mixer to become ready. 
788      */
789     while (! done && t2-- > 0) {
790         if ((nm256_readPort16 (card, 2, testaddr) & testb) == 0)
791             done = 1;
792         else
793             udelay (100);
794     }
795     return done;
796 }
797
798 /*
799  * Return the contents of the AC97 mixer register REG.  Returns a positive
800  * value if successful, or a negative error code.
801  */
802 static int
803 nm256_readAC97Reg (struct ac97_hwint *dev, u8 reg)
804 {
805     struct nm256_info *card = (struct nm256_info *)dev->driver_private;
806
807     if (card->magsig != NM_MAGIC_SIG) {
808         printk (KERN_ERR "NM256: Bad magic signature in readAC97Reg!\n");
809         return -EINVAL;
810     }
811
812     if (reg < 128) {
813         int res;
814
815         nm256_isReady (dev);
816         res = nm256_readPort16 (card, 2, card->mixer + reg);
817         /* Magic delay.  Bleah yucky.  */
818         udelay (1000);
819         return res;
820     }
821     else
822         return -EINVAL;
823 }
824
825 /* 
826  * Writes VALUE to AC97 mixer register REG.  Returns 0 if successful, or
827  * a negative error code. 
828  */
829 static int
830 nm256_writeAC97Reg (struct ac97_hwint *dev, u8 reg, u16 value)
831 {
832     unsigned long flags;
833     int tries = 2;
834     int done = 0;
835     u32 base;
836
837     struct nm256_info *card = (struct nm256_info *)dev->driver_private;
838
839     if (card->magsig != NM_MAGIC_SIG) {
840         printk (KERN_ERR "NM256: Bad magic signature in writeAC97Reg!\n");
841         return -EINVAL;
842     }
843
844     base = card->mixer;
845
846     spin_lock_irqsave(&card->lock,flags);
847
848     nm256_isReady (dev);
849
850     /* Wait for the write to take, too. */
851     while ((tries-- > 0) && !done) {
852         nm256_writePort16 (card, 2, base + reg, value);
853         if (nm256_isReady (dev)) {
854             done = 1;
855             break;
856         }
857
858     }
859
860     spin_unlock_irqrestore(&card->lock,flags);
861     udelay (1000);
862
863     return ! done;
864 }
865
866 /* 
867  * Initial register values to be written to the AC97 mixer.
868  * While most of these are identical to the reset values, we do this
869  * so that we have most of the register contents cached--this avoids
870  * reading from the mixer directly (which seems to be problematic,
871  * probably due to ignorance).
872  */
873 struct initialValues 
874 {
875     unsigned short port;
876     unsigned short value;
877 };
878
879 static struct initialValues nm256_ac97_initial_values[] = 
880 {
881     { AC97_MASTER_VOL_STEREO, 0x8000 },
882     { AC97_HEADPHONE_VOL,     0x8000 },
883     { AC97_MASTER_VOL_MONO,   0x0000 },
884     { AC97_PCBEEP_VOL,        0x0000 },
885     { AC97_PHONE_VOL,         0x0008 },
886     { AC97_MIC_VOL,           0x8000 },
887     { AC97_LINEIN_VOL,        0x8808 },
888     { AC97_CD_VOL,            0x8808 },
889     { AC97_VIDEO_VOL,         0x8808 },
890     { AC97_AUX_VOL,           0x8808 },
891     { AC97_PCMOUT_VOL,        0x0808 },
892     { AC97_RECORD_SELECT,     0x0000 },
893     { AC97_RECORD_GAIN,       0x0B0B },
894     { AC97_GENERAL_PURPOSE,   0x0000 },
895     { 0xffff, 0xffff }
896 };
897
898 /* Initialize the AC97 into a known state.  */
899 static int
900 nm256_resetAC97 (struct ac97_hwint *dev)
901 {
902     struct nm256_info *card = (struct nm256_info *)dev->driver_private;
903     int x;
904
905     if (card->magsig != NM_MAGIC_SIG) {
906         printk (KERN_ERR "NM256: Bad magic signature in resetAC97!\n");
907         return -EINVAL;
908     }
909
910     /* Reset the mixer.  'Tis magic!  */
911     nm256_writePort8 (card, 2, 0x6c0, 1);
912 //  nm256_writePort8 (card, 2, 0x6cc, 0x87);    /* This crashes Dell latitudes */
913     nm256_writePort8 (card, 2, 0x6cc, 0x80);
914     nm256_writePort8 (card, 2, 0x6cc, 0x0);
915
916     if (! card->mixer_values_init) {
917         for (x = 0; nm256_ac97_initial_values[x].port != 0xffff; x++) {
918             ac97_put_register (dev,
919                                nm256_ac97_initial_values[x].port,
920                                nm256_ac97_initial_values[x].value);
921             card->mixer_values_init = 1;
922         }
923     }
924
925     return 0;
926 }
927
928 /*
929  * We don't do anything particularly special here; it just passes the
930  * mixer ioctl to the AC97 driver.
931  */
932 static int
933 nm256_default_mixer_ioctl (int dev, unsigned int cmd, void __user *arg)
934 {
935     struct nm256_info *card = nm256_find_card_for_mixer (dev);
936     if (card != NULL)
937         return ac97_mixer_ioctl (&(card->mdev), cmd, arg);
938     else
939         return -ENODEV;
940 }
941
942 static struct mixer_operations nm256_mixer_operations = {
943         .owner  = THIS_MODULE,
944         .id     = "NeoMagic",
945         .name   = "NM256AC97Mixer",
946         .ioctl  = nm256_default_mixer_ioctl
947 };
948
949 /*
950  * Default settings for the OSS mixer.  These are set last, after the
951  * mixer is initialized.
952  *
953  * I "love" C sometimes.  Got braces?
954  */
955 static struct ac97_mixer_value_list mixer_defaults[] = {
956     { SOUND_MIXER_VOLUME,  { { 85, 85 } } },
957     { SOUND_MIXER_SPEAKER, { { 100 } } },
958     { SOUND_MIXER_PCM,     { { 65, 65 } } },
959     { SOUND_MIXER_CD,      { { 65, 65 } } },
960     { -1,                  {  { 0,  0 } } }
961 };
962
963
964 /* Installs the AC97 mixer into CARD.  */
965 static int __init
966 nm256_install_mixer (struct nm256_info *card)
967 {
968     int mixer;
969
970     card->mdev.reset_device = nm256_resetAC97;
971     card->mdev.read_reg = nm256_readAC97Reg;
972     card->mdev.write_reg = nm256_writeAC97Reg;
973     card->mdev.driver_private = (void *)card;
974
975     if (ac97_init (&(card->mdev)))
976         return -1;
977
978     mixer = sound_alloc_mixerdev();
979     if (num_mixers >= MAX_MIXER_DEV) {
980         printk ("NM256 mixer: Unable to alloc mixerdev\n");
981         return -1;
982     }
983
984     mixer_devs[mixer] = &nm256_mixer_operations;
985     card->mixer_oss_dev = mixer;
986
987     /* Some reasonable default values.  */
988     ac97_set_values (&(card->mdev), mixer_defaults);
989
990     printk(KERN_INFO "Initialized AC97 mixer\n");
991     return 0;
992 }
993
994 /* Perform a full reset on the hardware; this is invoked when an APM
995    resume event occurs.  */
996 static void
997 nm256_full_reset (struct nm256_info *card)
998 {
999     nm256_initHw (card);
1000     ac97_reset (&(card->mdev));
1001 }
1002
1003 /* 
1004  * See if the signature left by the NM256 BIOS is intact; if so, we use
1005  * the associated address as the end of our audio buffer in the video
1006  * RAM.
1007  */
1008
1009 static void __init
1010 nm256_peek_for_sig (struct nm256_info *card)
1011 {
1012     u32 port1offset 
1013         = card->port[0].physaddr + card->port[0].end_offset - 0x0400;
1014     /* The signature is located 1K below the end of video RAM.  */
1015     char __iomem *temp = ioremap_nocache (port1offset, 16);
1016     /* Default buffer end is 5120 bytes below the top of RAM.  */
1017     u32 default_value = card->port[0].end_offset - 0x1400;
1018     u32 sig;
1019
1020     /* Install the default value first, so we don't have to repeatedly
1021        do it if there is a problem.  */
1022     card->port[0].end_offset = default_value;
1023
1024     if (temp == NULL) {
1025         printk (KERN_ERR "NM256: Unable to scan for card signature in video RAM\n");
1026         return;
1027     }
1028     sig = readl (temp);
1029     if ((sig & NM_SIG_MASK) == NM_SIGNATURE) {
1030         u32 pointer = readl (temp + 4);
1031
1032         /*
1033          * If it's obviously invalid, don't use it (the port already has a
1034          * suitable default value set).
1035          */
1036         if (pointer != 0xffffffff)
1037             card->port[0].end_offset = pointer;
1038
1039         printk (KERN_INFO "NM256: Found card signature in video RAM: 0x%x\n",
1040                 pointer);
1041     }
1042
1043     iounmap (temp);
1044 }
1045
1046 /* 
1047  * Install a driver for the PCI device referenced by PCIDEV.
1048  * VERSTR is a human-readable version string.
1049  */
1050
1051 static int __devinit
1052 nm256_install(struct pci_dev *pcidev, enum nm256rev rev, char *verstr)
1053 {
1054     struct nm256_info *card;
1055     struct pm_dev *pmdev;
1056     int x;
1057
1058     if (pci_enable_device(pcidev))
1059             return 0;
1060
1061     card = kmalloc (sizeof (struct nm256_info), GFP_KERNEL);
1062     if (card == NULL) {
1063         printk (KERN_ERR "NM256: out of memory!\n");
1064         return 0;
1065     }
1066
1067     card->magsig = NM_MAGIC_SIG;
1068     card->playing  = 0;
1069     card->recording = 0;
1070     card->rev = rev;
1071         spin_lock_init(&card->lock);
1072
1073     /* Init the memory port info.  */
1074     for (x = 0; x < 2; x++) {
1075         card->port[x].physaddr = pci_resource_start (pcidev, x);
1076         card->port[x].ptr = NULL;
1077         card->port[x].start_offset = 0;
1078         card->port[x].end_offset = 0;
1079     }
1080
1081     /* Port 2 is easy.  */
1082     card->port[1].start_offset = 0;
1083     card->port[1].end_offset = NM_PORT2_SIZE;
1084
1085     /* Yuck.  But we have to map in port 2 so we can check how much RAM the
1086        card has.  */
1087     if (nm256_remap_ports (card)) {
1088         kfree (card);
1089         return 0;
1090     }
1091
1092     /* 
1093      * The NM256 has two memory ports.  The first port is nothing
1094      * more than a chunk of video RAM, which is used as the I/O ring
1095      * buffer.  The second port has the actual juicy stuff (like the
1096      * mixer and the playback engine control registers).
1097      */
1098
1099     if (card->rev == REV_NM256AV) {
1100         /* Ok, try to see if this is a non-AC97 version of the hardware. */
1101         int pval = nm256_readPort16 (card, 2, NM_MIXER_PRESENCE);
1102         if ((pval & NM_PRESENCE_MASK) != NM_PRESENCE_VALUE) {
1103             if (! force_load) {
1104                 printk (KERN_ERR "NM256: This doesn't look to me like the AC97-compatible version.\n");
1105                 printk (KERN_ERR "       You can force the driver to load by passing in the module\n");
1106                 printk (KERN_ERR "       parameter:\n");
1107                 printk (KERN_ERR "              force_load = 1\n");
1108                 printk (KERN_ERR "\n");
1109                 printk (KERN_ERR "       More likely, you should be using the appropriate SB-16 or\n");
1110                 printk (KERN_ERR "       CS4232 driver instead.  (If your BIOS has settings for\n");
1111                 printk (KERN_ERR "       IRQ and/or DMA for the sound card, this is *not* the correct\n");
1112                 printk (KERN_ERR "       driver to use.)\n");
1113                 nm256_release_ports (card);
1114                 kfree (card);
1115                 return 0;
1116             }
1117             else {
1118                 printk (KERN_INFO "NM256: Forcing driver load as per user request.\n");
1119             }
1120         }
1121         else {
1122          /*   printk (KERN_INFO "NM256: Congratulations. You're not running Eunice.\n")*/;
1123         }
1124         card->port[0].end_offset = 2560 * 1024;
1125         card->introutine = nm256_interrupt;
1126         card->mixer_status_offset = NM_MIXER_STATUS_OFFSET;
1127         card->mixer_status_mask = NM_MIXER_READY_MASK;
1128     } 
1129     else {
1130         /* Not sure if there is any relevant detect for the ZX or not.  */
1131         if (nm256_readPort8 (card, 2, 0xa0b) != 0)
1132             card->port[0].end_offset = 6144 * 1024;
1133         else
1134             card->port[0].end_offset = 4096 * 1024;
1135
1136         card->introutine = nm256_interrupt_zx;
1137         card->mixer_status_offset = NM2_MIXER_STATUS_OFFSET;
1138         card->mixer_status_mask = NM2_MIXER_READY_MASK;
1139     }
1140
1141     if (buffertop >= 98304 && buffertop < card->port[0].end_offset)
1142         card->port[0].end_offset = buffertop;
1143     else
1144         nm256_peek_for_sig (card);
1145
1146     card->port[0].start_offset = card->port[0].end_offset - 98304;
1147
1148     printk (KERN_INFO "NM256: Mapping port 1 from 0x%x - 0x%x\n",
1149             card->port[0].start_offset, card->port[0].end_offset);
1150
1151     if (nm256_remap_ports (card)) {
1152         kfree (card);
1153         return 0;
1154     }
1155
1156     /* See if we can get the interrupt. */
1157
1158     card->irq = pcidev->irq;
1159     card->has_irq = 0;
1160
1161     if (nm256_grabInterrupt (card) != 0) {
1162         nm256_release_ports (card);
1163         kfree (card);
1164         return 0;
1165     }
1166
1167     nm256_releaseInterrupt (card);
1168
1169     /*
1170      *  Init the board.
1171      */
1172
1173     card->playbackBufferSize = 16384;
1174     card->recordBufferSize = 16384;
1175
1176     card->coeffBuf = card->port[0].end_offset - NM_MAX_COEFFICIENT;
1177     card->abuf2 = card->coeffBuf - card->recordBufferSize;
1178     card->abuf1 = card->abuf2 - card->playbackBufferSize;
1179     card->allCoeffBuf = card->abuf2 - (NM_TOTAL_COEFF_COUNT * 4);
1180
1181     /* Fixed setting. */
1182     card->mixer = NM_MIXER_OFFSET;
1183     card->mixer_values_init = 0;
1184
1185     card->is_open_play = 0;
1186     card->is_open_record = 0;
1187
1188     card->coeffsCurrent = 0;
1189
1190     card->opencnt[0] = 0; card->opencnt[1] = 0;
1191
1192     /* Reasonable default settings, but largely unnecessary. */
1193     for (x = 0; x < 2; x++) {
1194         card->sinfo[x].bits = 8;
1195         card->sinfo[x].stereo = 0;
1196         card->sinfo[x].samplerate = 8000;
1197     }
1198
1199     nm256_initHw (card);
1200
1201     for (x = 0; x < 2; x++) {
1202         if ((card->dev[x] =
1203              sound_install_audiodrv(AUDIO_DRIVER_VERSION,
1204                                     "NM256", &nm256_audio_driver,
1205                                     sizeof(struct audio_driver),
1206                                     DMA_NODMA, AFMT_U8 | AFMT_S16_LE,
1207                                     NULL, -1, -1)) >= 0) {
1208             /* 1K minimum buffer size. */
1209             audio_devs[card->dev[x]]->min_fragment = 10;
1210             /* Maximum of 8K buffer size. */
1211             audio_devs[card->dev[x]]->max_fragment = 13;
1212         }
1213         else {
1214             printk(KERN_ERR "NM256: Too many PCM devices available\n");
1215             nm256_release_ports (card);
1216             kfree (card);
1217             return 0;
1218         }
1219     }
1220
1221     pci_set_drvdata(pcidev,card);
1222
1223     /* Insert the card in the list.  */
1224     card->next_card = nmcard_list;
1225     nmcard_list = card;
1226
1227     printk(KERN_INFO "Initialized NeoMagic %s audio in PCI native mode\n",
1228            verstr);
1229
1230     /* 
1231      * And our mixer.  (We should allow support for other mixers, maybe.)
1232      */
1233
1234     nm256_install_mixer (card);
1235
1236     pmdev = pm_register(PM_PCI_DEV, PM_PCI_ID(pcidev), handle_pm_event);
1237     if (pmdev)
1238         pmdev->data = card;
1239
1240     return 1;
1241 }
1242
1243
1244 /*
1245  * PM event handler, so the card is properly reinitialized after a power
1246  * event.
1247  */
1248 static int
1249 handle_pm_event (struct pm_dev *dev, pm_request_t rqst, void *data)
1250 {
1251     struct nm256_info *crd = (struct nm256_info*) dev->data;
1252     if (crd) {
1253         switch (rqst) {
1254         case PM_SUSPEND:
1255             break;
1256         case PM_RESUME:
1257             {
1258                 int playing = crd->playing;
1259                 nm256_full_reset (crd);
1260                 /*
1261                  * A little ugly, but that's ok; pretend the
1262                  * block we were playing is done. 
1263                  */
1264                 if (playing)
1265                     DMAbuf_outputintr (crd->dev_for_play, 1);
1266             }
1267             break;
1268         }
1269     }
1270     return 0;
1271 }
1272
1273 static int __devinit
1274 nm256_probe(struct pci_dev *pcidev,const struct pci_device_id *pciid)
1275 {
1276     if (pcidev->device == PCI_DEVICE_ID_NEOMAGIC_NM256AV_AUDIO)
1277         return nm256_install(pcidev, REV_NM256AV, "256AV");
1278     if (pcidev->device == PCI_DEVICE_ID_NEOMAGIC_NM256ZX_AUDIO)
1279         return nm256_install(pcidev, REV_NM256ZX, "256ZX");
1280     if (pcidev->device == PCI_DEVICE_ID_NEOMAGIC_NM256XL_PLUS_AUDIO)
1281         return nm256_install(pcidev, REV_NM256ZX, "256XL+");
1282     return -1; /* should not come here ... */
1283 }
1284
1285 static void __devinit
1286 nm256_remove(struct pci_dev *pcidev) {
1287     struct nm256_info *xcard = pci_get_drvdata(pcidev);
1288     struct nm256_info *card,*next_card = NULL;
1289
1290     for (card = nmcard_list; card != NULL; card = next_card) {
1291         next_card = card->next_card;
1292         if (card == xcard) {
1293             stopPlay (card);
1294             stopRecord (card);
1295             if (card->has_irq)
1296                 free_irq (card->irq, card);
1297             nm256_release_ports (card);
1298             sound_unload_mixerdev (card->mixer_oss_dev);
1299             sound_unload_audiodev (card->dev[0]);
1300             sound_unload_audiodev (card->dev[1]);
1301             kfree (card);
1302             break;
1303         }
1304     }
1305     if (nmcard_list == card)
1306         nmcard_list = next_card;
1307 }
1308
1309 /*
1310  * Open the device
1311  *
1312  * DEV  - device
1313  * MODE - mode to open device (logical OR of OPEN_READ and OPEN_WRITE)
1314  *
1315  * Called when opening the DMAbuf               (dmabuf.c:259)
1316  */
1317 static int
1318 nm256_audio_open(int dev, int mode)
1319 {
1320     struct nm256_info *card = nm256_find_card (dev);
1321     int w;
1322         
1323     if (card == NULL)
1324         return -ENODEV;
1325
1326     if (card->dev[0] == dev)
1327         w = 0;
1328     else if (card->dev[1] == dev)
1329         w = 1;
1330     else
1331         return -ENODEV;
1332
1333     if (card->opencnt[w] > 0)
1334         return -EBUSY;
1335
1336     /* No bits set? Huh? */
1337     if (! ((mode & OPEN_READ) || (mode & OPEN_WRITE)))
1338         return -EIO;
1339
1340     /*
1341      * If it's open for both read and write, and the card's currently
1342      * being read or written to, then do the opposite of what has
1343      * already been done.  Otherwise, don't specify any mode until the
1344      * user actually tries to do I/O.  (Some programs open the device
1345      * for both read and write, but only actually do reading or writing.)
1346      */
1347
1348     if ((mode & OPEN_WRITE) && (mode & OPEN_READ)) {
1349         if (card->is_open_play)
1350             mode = OPEN_WRITE;
1351         else if (card->is_open_record)
1352             mode = OPEN_READ;
1353         else mode = 0;
1354     }
1355         
1356     if (mode & OPEN_WRITE) {
1357         if (card->is_open_play == 0) {
1358             card->dev_for_play = dev;
1359             card->is_open_play = 1;
1360         }
1361         else
1362             return -EBUSY;
1363     }
1364
1365     if (mode & OPEN_READ) {
1366         if (card->is_open_record == 0) {
1367             card->dev_for_record = dev;
1368             card->is_open_record = 1;
1369         }
1370         else
1371             return -EBUSY;
1372     }
1373
1374     card->opencnt[w]++;
1375     return 0;
1376 }
1377
1378 /*
1379  * Close the device
1380  *
1381  * DEV  - device
1382  *
1383  * Called when closing the DMAbuf               (dmabuf.c:477)
1384  *      after halt_xfer
1385  */
1386 static void
1387 nm256_audio_close(int dev)
1388 {
1389     struct nm256_info *card = nm256_find_card (dev);
1390         
1391     if (card != NULL) {
1392         int w;
1393
1394         if (card->dev[0] == dev)
1395             w = 0;
1396         else if (card->dev[1] == dev)
1397             w = 1;
1398         else
1399             return;
1400
1401         card->opencnt[w]--;
1402         if (card->opencnt[w] <= 0) {
1403             card->opencnt[w] = 0;
1404
1405             if (card->dev_for_play == dev) {
1406                 stopPlay (card);
1407                 card->is_open_play = 0;
1408                 card->dev_for_play = -1;
1409             }
1410
1411             if (card->dev_for_record == dev) {
1412                 stopRecord (card);
1413                 card->is_open_record = 0;
1414                 card->dev_for_record = -1;
1415             }
1416         }
1417     }
1418 }
1419
1420 /* Standard ioctl handler. */
1421 static int
1422 nm256_audio_ioctl(int dev, unsigned int cmd, void __user *arg)
1423 {
1424     int ret;
1425     u32 oldinfo;
1426     int w;
1427
1428     struct nm256_info *card = nm256_find_card (dev);
1429
1430     if (card == NULL)
1431         return -ENODEV;
1432
1433     if (dev == card->dev[0])
1434         w = 0;
1435     else
1436         w = 1;
1437
1438     /* 
1439      * The code here is messy.  There are probably better ways to do
1440      * it.  (It should be possible to handle it the same way the AC97 mixer 
1441      * is done.)
1442      */
1443     switch (cmd)
1444         {
1445         case SOUND_PCM_WRITE_RATE:
1446             if (get_user(ret, (int __user *) arg))
1447                 return -EFAULT;
1448
1449             if (ret != 0) {
1450                 oldinfo = card->sinfo[w].samplerate;
1451                 card->sinfo[w].samplerate = ret;
1452                 ret = nm256_setInfo(dev, card);
1453                 if (ret != 0)
1454                     card->sinfo[w].samplerate = oldinfo;
1455             }
1456             if (ret == 0)
1457                 ret = card->sinfo[w].samplerate;
1458             break;
1459
1460         case SOUND_PCM_READ_RATE:
1461             ret = card->sinfo[w].samplerate;
1462             break;
1463
1464         case SNDCTL_DSP_STEREO:
1465             if (get_user(ret, (int __user *) arg))
1466                 return -EFAULT;
1467
1468             card->sinfo[w].stereo = ret ? 1 : 0;
1469             ret = nm256_setInfo (dev, card);
1470             if (ret == 0)
1471                 ret = card->sinfo[w].stereo;
1472
1473             break;
1474
1475         case SOUND_PCM_WRITE_CHANNELS:
1476             if (get_user(ret, (int __user *) arg))
1477                 return -EFAULT;
1478
1479             if (ret < 1 || ret > 3)
1480                 ret = card->sinfo[w].stereo + 1;
1481             else {
1482                 card->sinfo[w].stereo = ret - 1;
1483                 ret = nm256_setInfo (dev, card);
1484                 if (ret == 0)
1485                     ret = card->sinfo[w].stereo + 1;
1486             }
1487             break;
1488
1489         case SOUND_PCM_READ_CHANNELS:
1490             ret = card->sinfo[w].stereo + 1;
1491             break;
1492
1493         case SNDCTL_DSP_SETFMT:
1494             if (get_user(ret, (int __user *) arg))
1495                 return -EFAULT;
1496
1497             if (ret != 0) {
1498                 oldinfo = card->sinfo[w].bits;
1499                 card->sinfo[w].bits = ret;
1500                 ret = nm256_setInfo (dev, card);
1501                 if (ret != 0)
1502                     card->sinfo[w].bits = oldinfo;
1503             }
1504             if (ret == 0)
1505                 ret = card->sinfo[w].bits;
1506             break;
1507
1508         case SOUND_PCM_READ_BITS:
1509             ret = card->sinfo[w].bits;
1510             break;
1511
1512         default:
1513             return -EINVAL;
1514         }
1515     return put_user(ret, (int __user *) arg);
1516 }
1517
1518 /*
1519  * Given the sound device DEV and an associated physical buffer PHYSBUF, 
1520  * return a pointer to the actual buffer in kernel space. 
1521  *
1522  * This routine should exist as part of the soundcore routines.
1523  */
1524
1525 static char *
1526 nm256_getDMAbuffer (int dev, unsigned long physbuf)
1527 {
1528     struct audio_operations *adev = audio_devs[dev];
1529     struct dma_buffparms *dmap = adev->dmap_out;
1530     char *dma_start =
1531         (char *)(physbuf - (unsigned long)dmap->raw_buf_phys 
1532                  + (unsigned long)dmap->raw_buf);
1533
1534     return dma_start;
1535 }
1536
1537
1538 /*
1539  * Output a block to sound device
1540  *
1541  * dev          - device number
1542  * buf          - physical address of buffer
1543  * total_count  - total byte count in buffer
1544  * intrflag     - set if this has been called from an interrupt 
1545  *                                (via DMAbuf_outputintr)
1546  * restart_dma  - set if engine needs to be re-initialised
1547  *
1548  * Called when:
1549  *  1. Starting output                                  (dmabuf.c:1327)
1550  *  2.                                                  (dmabuf.c:1504)
1551  *  3. A new buffer needs to be sent to the device      (dmabuf.c:1579)
1552  */
1553 static void
1554 nm256_audio_output_block(int dev, unsigned long physbuf,
1555                                        int total_count, int intrflag)
1556 {
1557     struct nm256_info *card = nm256_find_card (dev);
1558
1559     if (card != NULL) {
1560         char *dma_buf = nm256_getDMAbuffer (dev, physbuf);
1561         card->is_open_play = 1;
1562         card->dev_for_play = dev;
1563         nm256_write_block (card, dma_buf, total_count);
1564     }
1565 }
1566
1567 /* Ditto, but do recording instead.  */
1568 static void
1569 nm256_audio_start_input(int dev, unsigned long physbuf, int count,
1570                         int intrflag)
1571 {
1572     struct nm256_info *card = nm256_find_card (dev);
1573
1574     if (card != NULL) {
1575         char *dma_buf = nm256_getDMAbuffer (dev, physbuf);
1576         card->is_open_record = 1;
1577         card->dev_for_record = dev;
1578         nm256_startRecording (card, dma_buf, count);
1579     }
1580 }
1581
1582 /* 
1583  * Prepare for inputting samples to DEV. 
1584  * Each requested buffer will be BSIZE byes long, with a total of
1585  * BCOUNT buffers. 
1586  */
1587
1588 static int
1589 nm256_audio_prepare_for_input(int dev, int bsize, int bcount)
1590 {
1591     struct nm256_info *card = nm256_find_card (dev);
1592
1593     if (card == NULL) 
1594         return -ENODEV;
1595
1596     if (card->is_open_record && card->dev_for_record != dev)
1597         return -EBUSY;
1598
1599     audio_devs[dev]->dmap_in->flags |= DMA_NODMA;
1600     return 0;
1601 }
1602
1603 /*
1604  * Prepare for outputting samples to `dev'
1605  *
1606  * Each buffer that will be passed will be `bsize' bytes long,
1607  * with a total of `bcount' buffers.
1608  *
1609  * Called when:
1610  *  1. A trigger enables audio output                   (dmabuf.c:978)
1611  *  2. We get a write buffer without dma_mode setup     (dmabuf.c:1152)
1612  *  3. We restart a transfer                            (dmabuf.c:1324)
1613  */
1614
1615 static int
1616 nm256_audio_prepare_for_output(int dev, int bsize, int bcount)
1617 {
1618     struct nm256_info *card = nm256_find_card (dev);
1619
1620     if (card == NULL)
1621         return -ENODEV;
1622
1623     if (card->is_open_play && card->dev_for_play != dev)
1624         return -EBUSY;
1625
1626     audio_devs[dev]->dmap_out->flags |= DMA_NODMA;
1627     return 0;
1628 }
1629
1630 /* Stop the current operations associated with DEV.  */
1631 static void
1632 nm256_audio_reset(int dev)
1633 {
1634     struct nm256_info *card = nm256_find_card (dev);
1635
1636     if (card != NULL) {
1637         if (card->dev_for_play == dev)
1638             stopPlay (card);
1639         if (card->dev_for_record == dev)
1640             stopRecord (card);
1641     }
1642 }
1643
1644 static int
1645 nm256_audio_local_qlen(int dev)
1646 {
1647     return 0;
1648 }
1649
1650 static struct audio_driver nm256_audio_driver =
1651 {
1652         .owner                  = THIS_MODULE,
1653         .open                   = nm256_audio_open,
1654         .close                  = nm256_audio_close,
1655         .output_block           = nm256_audio_output_block,
1656         .start_input            = nm256_audio_start_input,
1657         .ioctl                  = nm256_audio_ioctl,
1658         .prepare_for_input      = nm256_audio_prepare_for_input,
1659         .prepare_for_output     = nm256_audio_prepare_for_output,
1660         .halt_io                = nm256_audio_reset,
1661         .local_qlen             = nm256_audio_local_qlen,
1662 };
1663
1664 static struct pci_device_id nm256_pci_tbl[] = {
1665         {PCI_VENDOR_ID_NEOMAGIC, PCI_DEVICE_ID_NEOMAGIC_NM256AV_AUDIO,
1666         PCI_ANY_ID, PCI_ANY_ID, 0, 0},
1667         {PCI_VENDOR_ID_NEOMAGIC, PCI_DEVICE_ID_NEOMAGIC_NM256ZX_AUDIO,
1668         PCI_ANY_ID, PCI_ANY_ID, 0, 0},
1669         {PCI_VENDOR_ID_NEOMAGIC, PCI_DEVICE_ID_NEOMAGIC_NM256XL_PLUS_AUDIO,
1670         PCI_ANY_ID, PCI_ANY_ID, 0, 0},
1671         {0,}
1672 };
1673 MODULE_DEVICE_TABLE(pci, nm256_pci_tbl);
1674 MODULE_LICENSE("GPL");
1675
1676
1677 static struct pci_driver nm256_pci_driver = {
1678         .name           = "nm256_audio",
1679         .id_table       = nm256_pci_tbl,
1680         .probe          = nm256_probe,
1681         .remove         = nm256_remove,
1682 };
1683
1684 module_param(usecache, bool, 0);
1685 module_param(buffertop, int, 0);
1686 module_param(nm256_debug, bool, 0644);
1687 module_param(force_load, bool, 0);
1688
1689 static int __init do_init_nm256(void)
1690 {
1691     printk (KERN_INFO "NeoMagic 256AV/256ZX audio driver, version 1.1p\n");
1692     return pci_module_init(&nm256_pci_driver);
1693 }
1694
1695 static void __exit cleanup_nm256 (void)
1696 {
1697     pci_unregister_driver(&nm256_pci_driver);
1698     pm_unregister_all (&handle_pm_event);
1699 }
1700
1701 module_init(do_init_nm256);
1702 module_exit(cleanup_nm256);
1703
1704 /*
1705  * Local variables:
1706  *  c-basic-offset: 4
1707  * End:
1708  */