Remove all inclusions of <linux/config.h>
[linux-3.10.git] / sound / oss / ymfpci.c
1 /*
2  *  Copyright 1999 Jaroslav Kysela <perex@suse.cz>
3  *  Copyright 2000 Alan Cox <alan@redhat.com>
4  *  Copyright 2001 Kai Germaschewski <kai@tp1.ruhr-uni-bochum.de>
5  *  Copyright 2002 Pete Zaitcev <zaitcev@yahoo.com>
6  *
7  *  Yamaha YMF7xx driver.
8  *
9  *  This code is a result of high-speed collision
10  *  between ymfpci.c of ALSA and cs46xx.c of Linux.
11  *  -- Pete Zaitcev <zaitcev@yahoo.com>; 2000/09/18
12  *
13  *   This program is free software; you can redistribute it and/or modify
14  *   it under the terms of the GNU General Public License as published by
15  *   the Free Software Foundation; either version 2 of the License, or
16  *   (at your option) any later version.
17  *
18  *   This program is distributed in the hope that it will be useful,
19  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *   GNU General Public License for more details.
22  *
23  *   You should have received a copy of the GNU General Public License
24  *   along with this program; if not, write to the Free Software
25  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  * TODO:
28  *  - Use P44Slot for 44.1 playback (beware of idle buzzing in P44Slot).
29  *  - 96KHz playback for DVD - use pitch of 2.0.
30  *  - Retain DMA buffer on close, do not wait the end of frame.
31  *  - Resolve XXX tagged questions.
32  *  - Cannot play 5133Hz.
33  *  - 2001/01/07 Consider if we can remove voice_lock, like so:
34  *     : Allocate/deallocate voices in open/close under semafore.
35  *     : We access voices in interrupt, that only for pcms that open.
36  *    voice_lock around playback_prepare closes interrupts for insane duration.
37  *  - Revisit the way voice_alloc is done - too confusing, overcomplicated.
38  *    Should support various channel types, however.
39  *  - Remove prog_dmabuf from read/write, leave it in open.
40  *  - 2001/01/07 Replace the OPL3 part of CONFIG_SOUND_YMFPCI_LEGACY code with
41  *    native synthesizer through a playback slot.
42  *  - 2001/11/29 ac97_save_state
43  *    Talk to Kai to remove ac97_save_state before it's too late!
44  *  - Second AC97
45  *  - Restore S/PDIF - Toshibas have it.
46  *
47  * Kai used pci_alloc_consistent for DMA buffer, which sounds a little
48  * unconventional. However, given how small our fragments can be,
49  * a little uncached access is perhaps better than endless flushing.
50  * On i386 and other I/O-coherent architectures pci_alloc_consistent
51  * is entirely harmless.
52  */
53
54 #include <linux/module.h>
55 #include <linux/init.h>
56 #include <linux/interrupt.h>
57 #include <linux/ioport.h>
58 #include <linux/delay.h>
59 #include <linux/pci.h>
60 #include <linux/slab.h>
61 #include <linux/poll.h>
62 #include <linux/soundcard.h>
63 #include <linux/ac97_codec.h>
64 #include <linux/sound.h>
65
66 #include <asm/io.h>
67 #include <asm/dma.h>
68 #include <asm/uaccess.h>
69
70 #ifdef CONFIG_SOUND_YMFPCI_LEGACY
71 # include "sound_config.h"
72 # include "mpu401.h"
73 #endif
74 #include "ymfpci.h"
75
76 /*
77  * I do not believe in debug levels as I never can guess what
78  * part of the code is going to be problematic in the future.
79  * Don't forget to run your klogd with -c 8.
80  *
81  * Example (do not remove):
82  * #define YMFDBG(fmt, arg...)  do{ printk(KERN_DEBUG fmt, ##arg); }while(0)
83  */
84 #define YMFDBGW(fmt, arg...)  /* */     /* write counts */
85 #define YMFDBGI(fmt, arg...)  /* */     /* interrupts */
86 #define YMFDBGX(fmt, arg...)  /* */     /* ioctl */
87
88 static int ymf_playback_trigger(ymfpci_t *unit, struct ymf_pcm *ypcm, int cmd);
89 static void ymf_capture_trigger(ymfpci_t *unit, struct ymf_pcm *ypcm, int cmd);
90 static void ymfpci_voice_free(ymfpci_t *unit, ymfpci_voice_t *pvoice);
91 static int ymf_capture_alloc(struct ymf_unit *unit, int *pbank);
92 static int ymf_playback_prepare(struct ymf_state *state);
93 static int ymf_capture_prepare(struct ymf_state *state);
94 static struct ymf_state *ymf_state_alloc(ymfpci_t *unit);
95
96 static void ymfpci_aclink_reset(struct pci_dev * pci);
97 static void ymfpci_disable_dsp(ymfpci_t *unit);
98 static void ymfpci_download_image(ymfpci_t *codec);
99 static void ymf_memload(ymfpci_t *unit);
100
101 static DEFINE_SPINLOCK(ymf_devs_lock);
102 static LIST_HEAD(ymf_devs);
103
104 /*
105  *  constants
106  */
107
108 static struct pci_device_id ymf_id_tbl[] = {
109 #define DEV(dev, data) \
110         { PCI_VENDOR_ID_YAMAHA, dev, PCI_ANY_ID, PCI_ANY_ID, 0, 0, \
111                 (unsigned long)data }
112         DEV (PCI_DEVICE_ID_YAMAHA_724,  "YMF724"),
113         DEV (PCI_DEVICE_ID_YAMAHA_724F, "YMF724F"),
114         DEV (PCI_DEVICE_ID_YAMAHA_740,  "YMF740"),
115         DEV (PCI_DEVICE_ID_YAMAHA_740C, "YMF740C"),
116         DEV (PCI_DEVICE_ID_YAMAHA_744,  "YMF744"),
117         DEV (PCI_DEVICE_ID_YAMAHA_754,  "YMF754"),
118 #undef DEV
119         { }
120 };
121 MODULE_DEVICE_TABLE(pci, ymf_id_tbl);
122
123 /*
124  *  common I/O routines
125  */
126
127 static inline void ymfpci_writeb(ymfpci_t *codec, u32 offset, u8 val)
128 {
129         writeb(val, codec->reg_area_virt + offset);
130 }
131
132 static inline u16 ymfpci_readw(ymfpci_t *codec, u32 offset)
133 {
134         return readw(codec->reg_area_virt + offset);
135 }
136
137 static inline void ymfpci_writew(ymfpci_t *codec, u32 offset, u16 val)
138 {
139         writew(val, codec->reg_area_virt + offset);
140 }
141
142 static inline u32 ymfpci_readl(ymfpci_t *codec, u32 offset)
143 {
144         return readl(codec->reg_area_virt + offset);
145 }
146
147 static inline void ymfpci_writel(ymfpci_t *codec, u32 offset, u32 val)
148 {
149         writel(val, codec->reg_area_virt + offset);
150 }
151
152 static int ymfpci_codec_ready(ymfpci_t *codec, int secondary, int sched)
153 {
154         signed long end_time;
155         u32 reg = secondary ? YDSXGR_SECSTATUSADR : YDSXGR_PRISTATUSADR;
156         
157         end_time = jiffies + 3 * (HZ / 4);
158         do {
159                 if ((ymfpci_readw(codec, reg) & 0x8000) == 0)
160                         return 0;
161                 if (sched) {
162                         set_current_state(TASK_UNINTERRUPTIBLE);
163                         schedule_timeout(1);
164                 }
165         } while (end_time - (signed long)jiffies >= 0);
166         printk(KERN_ERR "ymfpci_codec_ready: codec %i is not ready [0x%x]\n",
167             secondary, ymfpci_readw(codec, reg));
168         return -EBUSY;
169 }
170
171 static void ymfpci_codec_write(struct ac97_codec *dev, u8 reg, u16 val)
172 {
173         ymfpci_t *codec = dev->private_data;
174         u32 cmd;
175
176         spin_lock(&codec->ac97_lock);
177         /* XXX Do make use of dev->id */
178         ymfpci_codec_ready(codec, 0, 0);
179         cmd = ((YDSXG_AC97WRITECMD | reg) << 16) | val;
180         ymfpci_writel(codec, YDSXGR_AC97CMDDATA, cmd);
181         spin_unlock(&codec->ac97_lock);
182 }
183
184 static u16 _ymfpci_codec_read(ymfpci_t *unit, u8 reg)
185 {
186         int i;
187
188         if (ymfpci_codec_ready(unit, 0, 0))
189                 return ~0;
190         ymfpci_writew(unit, YDSXGR_AC97CMDADR, YDSXG_AC97READCMD | reg);
191         if (ymfpci_codec_ready(unit, 0, 0))
192                 return ~0;
193         if (unit->pci->device == PCI_DEVICE_ID_YAMAHA_744 && unit->rev < 2) {
194                 for (i = 0; i < 600; i++)
195                         ymfpci_readw(unit, YDSXGR_PRISTATUSDATA);
196         }
197         return ymfpci_readw(unit, YDSXGR_PRISTATUSDATA);
198 }
199
200 static u16 ymfpci_codec_read(struct ac97_codec *dev, u8 reg)
201 {
202         ymfpci_t *unit = dev->private_data;
203         u16 ret;
204         
205         spin_lock(&unit->ac97_lock);
206         ret = _ymfpci_codec_read(unit, reg);
207         spin_unlock(&unit->ac97_lock);
208         
209         return ret;
210 }
211
212 /*
213  *  Misc routines
214  */
215
216 /*
217  * Calculate the actual sampling rate relatetively to the base clock (48kHz).
218  */
219 static u32 ymfpci_calc_delta(u32 rate)
220 {
221         switch (rate) {
222         case 8000:      return 0x02aaab00;
223         case 11025:     return 0x03accd00;
224         case 16000:     return 0x05555500;
225         case 22050:     return 0x07599a00;
226         case 32000:     return 0x0aaaab00;
227         case 44100:     return 0x0eb33300;
228         default:        return ((rate << 16) / 48000) << 12;
229         }
230 }
231
232 static u32 def_rate[8] = {
233         100, 2000, 8000, 11025, 16000, 22050, 32000, 48000
234 };
235
236 static u32 ymfpci_calc_lpfK(u32 rate)
237 {
238         u32 i;
239         static u32 val[8] = {
240                 0x00570000, 0x06AA0000, 0x18B20000, 0x20930000,
241                 0x2B9A0000, 0x35A10000, 0x3EAA0000, 0x40000000
242         };
243         
244         if (rate == 44100)
245                 return 0x40000000;      /* FIXME: What's the right value? */
246         for (i = 0; i < 8; i++)
247                 if (rate <= def_rate[i])
248                         return val[i];
249         return val[0];
250 }
251
252 static u32 ymfpci_calc_lpfQ(u32 rate)
253 {
254         u32 i;
255         static u32 val[8] = {
256                 0x35280000, 0x34A70000, 0x32020000, 0x31770000,
257                 0x31390000, 0x31C90000, 0x33D00000, 0x40000000
258         };
259         
260         if (rate == 44100)
261                 return 0x370A0000;
262         for (i = 0; i < 8; i++)
263                 if (rate <= def_rate[i])
264                         return val[i];
265         return val[0];
266 }
267
268 static u32 ymf_calc_lend(u32 rate)
269 {
270         return (rate * YMF_SAMPF) / 48000;
271 }
272
273 /*
274  * We ever allow only a few formats, but let's be generic, for smaller surprise.
275  */
276 static int ymf_pcm_format_width(int format)
277 {
278         static int mask16 = AFMT_S16_LE|AFMT_S16_BE|AFMT_U16_LE|AFMT_U16_BE;
279
280         if ((format & (format-1)) != 0) {
281                 printk(KERN_ERR "ymfpci: format 0x%x is not a power of 2\n", format);
282                 return 8;
283         }
284
285         if (format == AFMT_IMA_ADPCM) return 4;
286         if ((format & mask16) != 0) return 16;
287         return 8;
288 }
289
290 static void ymf_pcm_update_shift(struct ymf_pcm_format *f)
291 {
292         f->shift = 0;
293         if (f->voices == 2)
294                 f->shift++;
295         if (ymf_pcm_format_width(f->format) == 16)
296                 f->shift++;
297 }
298
299 /* Are you sure 32K is not too much? See if mpg123 skips on loaded systems. */
300 #define DMABUF_DEFAULTORDER (15-PAGE_SHIFT)
301 #define DMABUF_MINORDER 1
302
303 /*
304  * Allocate DMA buffer
305  */
306 static int alloc_dmabuf(ymfpci_t *unit, struct ymf_dmabuf *dmabuf)
307 {
308         void *rawbuf = NULL;
309         dma_addr_t dma_addr;
310         int order;
311         struct page *map, *mapend;
312
313         /* alloc as big a chunk as we can */
314         for (order = DMABUF_DEFAULTORDER; order >= DMABUF_MINORDER; order--) {
315                 rawbuf = pci_alloc_consistent(unit->pci, PAGE_SIZE << order, &dma_addr);
316                 if (rawbuf)
317                         break;
318         }
319         if (!rawbuf)
320                 return -ENOMEM;
321
322 #if 0
323         printk(KERN_DEBUG "ymfpci: allocated %ld (order = %d) bytes at %p\n",
324                PAGE_SIZE << order, order, rawbuf);
325 #endif
326
327         dmabuf->ready  = dmabuf->mapped = 0;
328         dmabuf->rawbuf = rawbuf;
329         dmabuf->dma_addr = dma_addr;
330         dmabuf->buforder = order;
331
332         /* now mark the pages as reserved; otherwise remap_pfn_range doesn't do what we want */
333         mapend = virt_to_page(rawbuf + (PAGE_SIZE << order) - 1);
334         for (map = virt_to_page(rawbuf); map <= mapend; map++)
335                 set_bit(PG_reserved, &map->flags);
336
337         return 0;
338 }
339
340 /*
341  * Free DMA buffer
342  */
343 static void dealloc_dmabuf(ymfpci_t *unit, struct ymf_dmabuf *dmabuf)
344 {
345         struct page *map, *mapend;
346
347         if (dmabuf->rawbuf) {
348                 /* undo marking the pages as reserved */
349                 mapend = virt_to_page(dmabuf->rawbuf + (PAGE_SIZE << dmabuf->buforder) - 1);
350                 for (map = virt_to_page(dmabuf->rawbuf); map <= mapend; map++)
351                         clear_bit(PG_reserved, &map->flags);
352
353                 pci_free_consistent(unit->pci, PAGE_SIZE << dmabuf->buforder,
354                     dmabuf->rawbuf, dmabuf->dma_addr);
355         }
356         dmabuf->rawbuf = NULL;
357         dmabuf->mapped = dmabuf->ready = 0;
358 }
359
360 static int prog_dmabuf(struct ymf_state *state, int rec)
361 {
362         struct ymf_dmabuf *dmabuf;
363         int w_16;
364         unsigned bufsize;
365         unsigned long flags;
366         int redzone, redfrags;
367         int ret;
368
369         w_16 = ymf_pcm_format_width(state->format.format) == 16;
370         dmabuf = rec ? &state->rpcm.dmabuf : &state->wpcm.dmabuf;
371
372         spin_lock_irqsave(&state->unit->reg_lock, flags);
373         dmabuf->hwptr = dmabuf->swptr = 0;
374         dmabuf->total_bytes = 0;
375         dmabuf->count = 0;
376         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
377
378         /* allocate DMA buffer if not allocated yet */
379         if (!dmabuf->rawbuf)
380                 if ((ret = alloc_dmabuf(state->unit, dmabuf)))
381                         return ret;
382
383         /*
384          * Create fake fragment sizes and numbers for OSS ioctls.
385          * Import what Doom might have set with SNDCTL_DSP_SETFRAGMENT.
386          */
387         bufsize = PAGE_SIZE << dmabuf->buforder;
388         /* By default we give 4 big buffers. */
389         dmabuf->fragshift = (dmabuf->buforder + PAGE_SHIFT - 2);
390         if (dmabuf->ossfragshift > 3 &&
391             dmabuf->ossfragshift < dmabuf->fragshift) {
392                 /* If OSS set smaller fragments, give more smaller buffers. */
393                 dmabuf->fragshift = dmabuf->ossfragshift;
394         }
395         dmabuf->fragsize = 1 << dmabuf->fragshift;
396
397         dmabuf->numfrag = bufsize >> dmabuf->fragshift;
398         dmabuf->dmasize = dmabuf->numfrag << dmabuf->fragshift;
399
400         if (dmabuf->ossmaxfrags >= 2) {
401                 redzone = ymf_calc_lend(state->format.rate);
402                 redzone <<= state->format.shift;
403                 redzone *= 3;
404                 redfrags = (redzone + dmabuf->fragsize-1) >> dmabuf->fragshift;
405
406                 if (dmabuf->ossmaxfrags + redfrags < dmabuf->numfrag) {
407                         dmabuf->numfrag = dmabuf->ossmaxfrags + redfrags;
408                         dmabuf->dmasize = dmabuf->numfrag << dmabuf->fragshift;
409                 }
410         }
411
412         memset(dmabuf->rawbuf, w_16 ? 0 : 0x80, dmabuf->dmasize);
413
414         /*
415          *      Now set up the ring 
416          */
417
418         /* XXX   ret = rec? cap_pre(): pbk_pre();  */
419         spin_lock_irqsave(&state->unit->voice_lock, flags);
420         if (rec) {
421                 if ((ret = ymf_capture_prepare(state)) != 0) {
422                         spin_unlock_irqrestore(&state->unit->voice_lock, flags);
423                         return ret;
424                 }
425         } else {
426                 if ((ret = ymf_playback_prepare(state)) != 0) {
427                         spin_unlock_irqrestore(&state->unit->voice_lock, flags);
428                         return ret;
429                 }
430         }
431         spin_unlock_irqrestore(&state->unit->voice_lock, flags);
432
433         /* set the ready flag for the dma buffer (this comment is not stupid) */
434         dmabuf->ready = 1;
435
436 #if 0
437         printk(KERN_DEBUG "prog_dmabuf: rate %d format 0x%x,"
438             " numfrag %d fragsize %d dmasize %d\n",
439                state->format.rate, state->format.format, dmabuf->numfrag,
440                dmabuf->fragsize, dmabuf->dmasize);
441 #endif
442
443         return 0;
444 }
445
446 static void ymf_start_dac(struct ymf_state *state)
447 {
448         ymf_playback_trigger(state->unit, &state->wpcm, 1);
449 }
450
451 // static void ymf_start_adc(struct ymf_state *state)
452 // {
453 //      ymf_capture_trigger(state->unit, &state->rpcm, 1);
454 // }
455
456 /*
457  * Wait until output is drained.
458  * This does not kill the hardware for the sake of ioctls.
459  */
460 static void ymf_wait_dac(struct ymf_state *state)
461 {
462         struct ymf_unit *unit = state->unit;
463         struct ymf_pcm *ypcm = &state->wpcm;
464         DECLARE_WAITQUEUE(waita, current);
465         unsigned long flags;
466
467         add_wait_queue(&ypcm->dmabuf.wait, &waita);
468
469         spin_lock_irqsave(&unit->reg_lock, flags);
470         if (ypcm->dmabuf.count != 0 && !ypcm->running) {
471                 ymf_playback_trigger(unit, ypcm, 1);
472         }
473
474 #if 0
475         if (file->f_flags & O_NONBLOCK) {
476                 /*
477                  * XXX Our  mistake is to attach DMA buffer to state
478                  * rather than to some per-device structure.
479                  * Cannot skip waiting, can only make it shorter.
480                  */
481         }
482 #endif
483
484         set_current_state(TASK_UNINTERRUPTIBLE);
485         while (ypcm->running) {
486                 spin_unlock_irqrestore(&unit->reg_lock, flags);
487                 schedule();
488                 spin_lock_irqsave(&unit->reg_lock, flags);
489                 set_current_state(TASK_UNINTERRUPTIBLE);
490         }
491         spin_unlock_irqrestore(&unit->reg_lock, flags);
492
493         set_current_state(TASK_RUNNING);
494         remove_wait_queue(&ypcm->dmabuf.wait, &waita);
495
496         /*
497          * This function may take up to 4 seconds to reach this point
498          * (32K circular buffer, 8000 Hz). User notices.
499          */
500 }
501
502 /* Can just stop, without wait. Or can we? */
503 static void ymf_stop_adc(struct ymf_state *state)
504 {
505         struct ymf_unit *unit = state->unit;
506         unsigned long flags;
507
508         spin_lock_irqsave(&unit->reg_lock, flags);
509         ymf_capture_trigger(unit, &state->rpcm, 0);
510         spin_unlock_irqrestore(&unit->reg_lock, flags);
511 }
512
513 /*
514  *  Hardware start management
515  */
516
517 static void ymfpci_hw_start(ymfpci_t *unit)
518 {
519         unsigned long flags;
520
521         spin_lock_irqsave(&unit->reg_lock, flags);
522         if (unit->start_count++ == 0) {
523                 ymfpci_writel(unit, YDSXGR_MODE,
524                     ymfpci_readl(unit, YDSXGR_MODE) | 3);
525                 unit->active_bank = ymfpci_readl(unit, YDSXGR_CTRLSELECT) & 1;
526         }
527         spin_unlock_irqrestore(&unit->reg_lock, flags);
528 }
529
530 static void ymfpci_hw_stop(ymfpci_t *unit)
531 {
532         unsigned long flags;
533         long timeout = 1000;
534
535         spin_lock_irqsave(&unit->reg_lock, flags);
536         if (--unit->start_count == 0) {
537                 ymfpci_writel(unit, YDSXGR_MODE,
538                     ymfpci_readl(unit, YDSXGR_MODE) & ~3);
539                 while (timeout-- > 0) {
540                         if ((ymfpci_readl(unit, YDSXGR_STATUS) & 2) == 0)
541                                 break;
542                 }
543         }
544         spin_unlock_irqrestore(&unit->reg_lock, flags);
545 }
546
547 /*
548  *  Playback voice management
549  */
550
551 static int voice_alloc(ymfpci_t *codec, ymfpci_voice_type_t type, int pair, ymfpci_voice_t *rvoice[])
552 {
553         ymfpci_voice_t *voice, *voice2;
554         int idx;
555
556         for (idx = 0; idx < YDSXG_PLAYBACK_VOICES; idx += pair ? 2 : 1) {
557                 voice = &codec->voices[idx];
558                 voice2 = pair ? &codec->voices[idx+1] : NULL;
559                 if (voice->use || (voice2 && voice2->use))
560                         continue;
561                 voice->use = 1;
562                 if (voice2)
563                         voice2->use = 1;
564                 switch (type) {
565                 case YMFPCI_PCM:
566                         voice->pcm = 1;
567                         if (voice2)
568                                 voice2->pcm = 1;
569                         break;
570                 case YMFPCI_SYNTH:
571                         voice->synth = 1;
572                         break;
573                 case YMFPCI_MIDI:
574                         voice->midi = 1;
575                         break;
576                 }
577                 ymfpci_hw_start(codec);
578                 rvoice[0] = voice;
579                 if (voice2) {
580                         ymfpci_hw_start(codec);
581                         rvoice[1] = voice2;
582                 }
583                 return 0;
584         }
585         return -EBUSY;  /* Your audio channel is open by someone else. */
586 }
587
588 static void ymfpci_voice_free(ymfpci_t *unit, ymfpci_voice_t *pvoice)
589 {
590         ymfpci_hw_stop(unit);
591         pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = 0;
592         pvoice->ypcm = NULL;
593 }
594
595 /*
596  */
597
598 static void ymf_pcm_interrupt(ymfpci_t *codec, ymfpci_voice_t *voice)
599 {
600         struct ymf_pcm *ypcm;
601         int redzone;
602         int pos, delta, swptr;
603         int played, distance;
604         struct ymf_state *state;
605         struct ymf_dmabuf *dmabuf;
606         char silence;
607
608         if ((ypcm = voice->ypcm) == NULL) {
609                 return;
610         }
611         if ((state = ypcm->state) == NULL) {
612                 ypcm->running = 0;      // lock it
613                 return;
614         }
615         dmabuf = &ypcm->dmabuf;
616         spin_lock(&codec->reg_lock);
617         if (ypcm->running) {
618                 YMFDBGI("ymfpci: %d, intr bank %d count %d start 0x%x:%x\n",
619                    voice->number, codec->active_bank, dmabuf->count,
620                    le32_to_cpu(voice->bank[0].start),
621                    le32_to_cpu(voice->bank[1].start));
622                 silence = (ymf_pcm_format_width(state->format.format) == 16) ?
623                     0 : 0x80;
624                 /* We need actual left-hand-side redzone size here. */
625                 redzone = ymf_calc_lend(state->format.rate);
626                 redzone <<= (state->format.shift + 1);
627                 swptr = dmabuf->swptr;
628
629                 pos = le32_to_cpu(voice->bank[codec->active_bank].start);
630                 pos <<= state->format.shift;
631                 if (pos < 0 || pos >= dmabuf->dmasize) {        /* ucode bug */
632                         printk(KERN_ERR "ymfpci%d: runaway voice %d: hwptr %d=>%d dmasize %d\n",
633                             codec->dev_audio, voice->number,
634                             dmabuf->hwptr, pos, dmabuf->dmasize);
635                         pos = 0;
636                 }
637                 if (pos < dmabuf->hwptr) {
638                         delta = dmabuf->dmasize - dmabuf->hwptr;
639                         memset(dmabuf->rawbuf + dmabuf->hwptr, silence, delta);
640                         delta += pos;
641                         memset(dmabuf->rawbuf, silence, pos);
642                 } else {
643                         delta = pos - dmabuf->hwptr;
644                         memset(dmabuf->rawbuf + dmabuf->hwptr, silence, delta);
645                 }
646                 dmabuf->hwptr = pos;
647
648                 if (dmabuf->count == 0) {
649                         printk(KERN_ERR "ymfpci%d: %d: strain: hwptr %d\n",
650                             codec->dev_audio, voice->number, dmabuf->hwptr);
651                         ymf_playback_trigger(codec, ypcm, 0);
652                 }
653
654                 if (swptr <= pos) {
655                         distance = pos - swptr;
656                 } else {
657                         distance = dmabuf->dmasize - (swptr - pos);
658                 }
659                 if (distance < redzone) {
660                         /*
661                          * hwptr inside redzone => DMA ran out of samples.
662                          */
663                         if (delta < dmabuf->count) {
664                                 /*
665                                  * Lost interrupt or other screwage.
666                                  */
667                                 printk(KERN_ERR "ymfpci%d: %d: lost: delta %d"
668                                     " hwptr %d swptr %d distance %d count %d\n",
669                                     codec->dev_audio, voice->number, delta,
670                                     dmabuf->hwptr, swptr, distance, dmabuf->count);
671                         } else {
672                                 /*
673                                  * Normal end of DMA.
674                                  */
675                                 YMFDBGI("ymfpci%d: %d: done: delta %d"
676                                     " hwptr %d swptr %d distance %d count %d\n",
677                                     codec->dev_audio, voice->number, delta,
678                                     dmabuf->hwptr, swptr, distance, dmabuf->count);
679                         }
680                         played = dmabuf->count;
681                         if (ypcm->running) {
682                                 ymf_playback_trigger(codec, ypcm, 0);
683                         }
684                 } else {
685                         /*
686                          * hwptr is chipping away towards a remote swptr.
687                          * Calculate other distance and apply it to count.
688                          */
689                         if (swptr >= pos) {
690                                 distance = swptr - pos;
691                         } else {
692                                 distance = dmabuf->dmasize - (pos - swptr);
693                         }
694                         if (distance < dmabuf->count) {
695                                 played = dmabuf->count - distance;
696                         } else {
697                                 played = 0;
698                         }
699                 }
700
701                 dmabuf->total_bytes += played;
702                 dmabuf->count -= played;
703                 if (dmabuf->count < dmabuf->dmasize / 2) {
704                         wake_up(&dmabuf->wait);
705                 }
706         }
707         spin_unlock(&codec->reg_lock);
708 }
709
710 static void ymf_cap_interrupt(ymfpci_t *unit, struct ymf_capture *cap)
711 {
712         struct ymf_pcm *ypcm;
713         int redzone;
714         struct ymf_state *state;
715         struct ymf_dmabuf *dmabuf;
716         int pos, delta;
717         int cnt;
718
719         if ((ypcm = cap->ypcm) == NULL) {
720                 return;
721         }
722         if ((state = ypcm->state) == NULL) {
723                 ypcm->running = 0;      // lock it
724                 return;
725         }
726         dmabuf = &ypcm->dmabuf;
727         spin_lock(&unit->reg_lock);
728         if (ypcm->running) {
729                 redzone = ymf_calc_lend(state->format.rate);
730                 redzone <<= (state->format.shift + 1);
731
732                 pos = le32_to_cpu(cap->bank[unit->active_bank].start);
733                 // pos <<= state->format.shift;
734                 if (pos < 0 || pos >= dmabuf->dmasize) {        /* ucode bug */
735                         printk(KERN_ERR "ymfpci%d: runaway capture %d: hwptr %d=>%d dmasize %d\n",
736                             unit->dev_audio, ypcm->capture_bank_number,
737                             dmabuf->hwptr, pos, dmabuf->dmasize);
738                         pos = 0;
739                 }
740                 if (pos < dmabuf->hwptr) {
741                         delta = dmabuf->dmasize - dmabuf->hwptr;
742                         delta += pos;
743                 } else {
744                         delta = pos - dmabuf->hwptr;
745                 }
746                 dmabuf->hwptr = pos;
747
748                 cnt = dmabuf->count;
749                 cnt += delta;
750                 if (cnt + redzone > dmabuf->dmasize) {
751                         /* Overflow - bump swptr */
752                         dmabuf->count = dmabuf->dmasize - redzone;
753                         dmabuf->swptr = dmabuf->hwptr + redzone;
754                         if (dmabuf->swptr >= dmabuf->dmasize) {
755                                 dmabuf->swptr -= dmabuf->dmasize;
756                         }
757                 } else {
758                         dmabuf->count = cnt;
759                 }
760
761                 dmabuf->total_bytes += delta;
762                 if (dmabuf->count) {            /* && is_sleeping  XXX */
763                         wake_up(&dmabuf->wait);
764                 }
765         }
766         spin_unlock(&unit->reg_lock);
767 }
768
769 static int ymf_playback_trigger(ymfpci_t *codec, struct ymf_pcm *ypcm, int cmd)
770 {
771
772         if (ypcm->voices[0] == NULL) {
773                 return -EINVAL;
774         }
775         if (cmd != 0) {
776                 codec->ctrl_playback[ypcm->voices[0]->number + 1] =
777                     cpu_to_le32(ypcm->voices[0]->bank_ba);
778                 if (ypcm->voices[1] != NULL)
779                         codec->ctrl_playback[ypcm->voices[1]->number + 1] =
780                             cpu_to_le32(ypcm->voices[1]->bank_ba);
781                 ypcm->running = 1;
782         } else {
783                 codec->ctrl_playback[ypcm->voices[0]->number + 1] = 0;
784                 if (ypcm->voices[1] != NULL)
785                         codec->ctrl_playback[ypcm->voices[1]->number + 1] = 0;
786                 ypcm->running = 0;
787         }
788         return 0;
789 }
790
791 static void ymf_capture_trigger(ymfpci_t *codec, struct ymf_pcm *ypcm, int cmd)
792 {
793         u32 tmp;
794
795         if (cmd != 0) {
796                 tmp = ymfpci_readl(codec, YDSXGR_MAPOFREC) | (1 << ypcm->capture_bank_number);
797                 ymfpci_writel(codec, YDSXGR_MAPOFREC, tmp);
798                 ypcm->running = 1;
799         } else {
800                 tmp = ymfpci_readl(codec, YDSXGR_MAPOFREC) & ~(1 << ypcm->capture_bank_number);
801                 ymfpci_writel(codec, YDSXGR_MAPOFREC, tmp);
802                 ypcm->running = 0;
803         }
804 }
805
806 static int ymfpci_pcm_voice_alloc(struct ymf_pcm *ypcm, int voices)
807 {
808         struct ymf_unit *unit;
809         int err;
810
811         unit = ypcm->state->unit;
812         if (ypcm->voices[1] != NULL && voices < 2) {
813                 ymfpci_voice_free(unit, ypcm->voices[1]);
814                 ypcm->voices[1] = NULL;
815         }
816         if (voices == 1 && ypcm->voices[0] != NULL)
817                 return 0;               /* already allocated */
818         if (voices == 2 && ypcm->voices[0] != NULL && ypcm->voices[1] != NULL)
819                 return 0;               /* already allocated */
820         if (voices > 1) {
821                 if (ypcm->voices[0] != NULL && ypcm->voices[1] == NULL) {
822                         ymfpci_voice_free(unit, ypcm->voices[0]);
823                         ypcm->voices[0] = NULL;
824                 }               
825                 if ((err = voice_alloc(unit, YMFPCI_PCM, 1, ypcm->voices)) < 0)
826                         return err;
827                 ypcm->voices[0]->ypcm = ypcm;
828                 ypcm->voices[1]->ypcm = ypcm;
829         } else {
830                 if ((err = voice_alloc(unit, YMFPCI_PCM, 0, ypcm->voices)) < 0)
831                         return err;
832                 ypcm->voices[0]->ypcm = ypcm;
833         }
834         return 0;
835 }
836
837 static void ymf_pcm_init_voice(ymfpci_voice_t *voice, int stereo,
838     int rate, int w_16, unsigned long addr, unsigned int end, int spdif)
839 {
840         u32 format;
841         u32 delta = ymfpci_calc_delta(rate);
842         u32 lpfQ = ymfpci_calc_lpfQ(rate);
843         u32 lpfK = ymfpci_calc_lpfK(rate);
844         ymfpci_playback_bank_t *bank;
845         int nbank;
846
847         /*
848          * The gain is a floating point number. According to the manual,
849          * bit 31 indicates a sign bit, bit 30 indicates an integer part,
850          * and bits [29:15] indicate a decimal fraction part. Thus,
851          * for a gain of 1.0 the constant of 0x40000000 is loaded.
852          */
853         unsigned default_gain = cpu_to_le32(0x40000000);
854
855         format = (stereo ? 0x00010000 : 0) | (w_16 ? 0 : 0x80000000);
856         if (stereo)
857                 end >>= 1;
858         if (w_16)
859                 end >>= 1;
860         for (nbank = 0; nbank < 2; nbank++) {
861                 bank = &voice->bank[nbank];
862                 bank->format = cpu_to_le32(format);
863                 bank->loop_default = 0; /* 0-loops forever, otherwise count */
864                 bank->base = cpu_to_le32(addr);
865                 bank->loop_start = 0;
866                 bank->loop_end = cpu_to_le32(end);
867                 bank->loop_frac = 0;
868                 bank->eg_gain_end = default_gain;
869                 bank->lpfQ = cpu_to_le32(lpfQ);
870                 bank->status = 0;
871                 bank->num_of_frames = 0;
872                 bank->loop_count = 0;
873                 bank->start = 0;
874                 bank->start_frac = 0;
875                 bank->delta =
876                 bank->delta_end = cpu_to_le32(delta);
877                 bank->lpfK =
878                 bank->lpfK_end = cpu_to_le32(lpfK);
879                 bank->eg_gain = default_gain;
880                 bank->lpfD1 =
881                 bank->lpfD2 = 0;
882
883                 bank->left_gain = 
884                 bank->right_gain =
885                 bank->left_gain_end =
886                 bank->right_gain_end =
887                 bank->eff1_gain =
888                 bank->eff2_gain =
889                 bank->eff3_gain =
890                 bank->eff1_gain_end =
891                 bank->eff2_gain_end =
892                 bank->eff3_gain_end = 0;
893
894                 if (!stereo) {
895                         if (!spdif) {
896                                 bank->left_gain = 
897                                 bank->right_gain =
898                                 bank->left_gain_end =
899                                 bank->right_gain_end = default_gain;
900                         } else {
901                                 bank->eff2_gain =
902                                 bank->eff2_gain_end =
903                                 bank->eff3_gain =
904                                 bank->eff3_gain_end = default_gain;
905                         }
906                 } else {
907                         if (!spdif) {
908                                 if ((voice->number & 1) == 0) {
909                                         bank->left_gain =
910                                         bank->left_gain_end = default_gain;
911                                 } else {
912                                         bank->format |= cpu_to_le32(1);
913                                         bank->right_gain =
914                                         bank->right_gain_end = default_gain;
915                                 }
916                         } else {
917                                 if ((voice->number & 1) == 0) {
918                                         bank->eff2_gain =
919                                         bank->eff2_gain_end = default_gain;
920                                 } else {
921                                         bank->format |= cpu_to_le32(1);
922                                         bank->eff3_gain =
923                                         bank->eff3_gain_end = default_gain;
924                                 }
925                         }
926                 }
927         }
928 }
929
930 /*
931  * XXX Capture channel allocation is entirely fake at the moment.
932  * We use only one channel and mark it busy as required.
933  */
934 static int ymf_capture_alloc(struct ymf_unit *unit, int *pbank)
935 {
936         struct ymf_capture *cap;
937         int cbank;
938
939         cbank = 1;              /* Only ADC slot is used for now. */
940         cap = &unit->capture[cbank];
941         if (cap->use)
942                 return -EBUSY;
943         cap->use = 1;
944         *pbank = cbank;
945         return 0;
946 }
947
948 static int ymf_playback_prepare(struct ymf_state *state)
949 {
950         struct ymf_pcm *ypcm = &state->wpcm;
951         int err, nvoice;
952
953         if ((err = ymfpci_pcm_voice_alloc(ypcm, state->format.voices)) < 0) {
954                 /* Somebody started 32 mpg123's in parallel? */
955                 printk(KERN_INFO "ymfpci%d: cannot allocate voice\n",
956                     state->unit->dev_audio);
957                 return err;
958         }
959
960         for (nvoice = 0; nvoice < state->format.voices; nvoice++) {
961                 ymf_pcm_init_voice(ypcm->voices[nvoice],
962                     state->format.voices == 2, state->format.rate,
963                     ymf_pcm_format_width(state->format.format) == 16,
964                     ypcm->dmabuf.dma_addr, ypcm->dmabuf.dmasize,
965                     ypcm->spdif);
966         }
967         return 0;
968 }
969
970 static int ymf_capture_prepare(struct ymf_state *state)
971 {
972         ymfpci_t *unit = state->unit;
973         struct ymf_pcm *ypcm = &state->rpcm;
974         ymfpci_capture_bank_t * bank;
975         /* XXX This is confusing, gotta rename one of them banks... */
976         int nbank;              /* flip-flop bank */
977         int cbank;              /* input [super-]bank */
978         struct ymf_capture *cap;
979         u32 rate, format;
980
981         if (ypcm->capture_bank_number == -1) {
982                 if (ymf_capture_alloc(unit, &cbank) != 0)
983                         return -EBUSY;
984
985                 ypcm->capture_bank_number = cbank;
986
987                 cap = &unit->capture[cbank];
988                 cap->bank = unit->bank_capture[cbank][0];
989                 cap->ypcm = ypcm;
990                 ymfpci_hw_start(unit);
991         }
992
993         // ypcm->frag_size = snd_pcm_lib_transfer_fragment(substream);
994         // frag_size is replaced with nonfragged byte-aligned rolling buffer
995         rate = ((48000 * 4096) / state->format.rate) - 1;
996         format = 0;
997         if (state->format.voices == 2)
998                 format |= 2;
999         if (ymf_pcm_format_width(state->format.format) == 8)
1000                 format |= 1;
1001         switch (ypcm->capture_bank_number) {
1002         case 0:
1003                 ymfpci_writel(unit, YDSXGR_RECFORMAT, format);
1004                 ymfpci_writel(unit, YDSXGR_RECSLOTSR, rate);
1005                 break;
1006         case 1:
1007                 ymfpci_writel(unit, YDSXGR_ADCFORMAT, format);
1008                 ymfpci_writel(unit, YDSXGR_ADCSLOTSR, rate);
1009                 break;
1010         }
1011         for (nbank = 0; nbank < 2; nbank++) {
1012                 bank = unit->bank_capture[ypcm->capture_bank_number][nbank];
1013                 bank->base = cpu_to_le32(ypcm->dmabuf.dma_addr);
1014                 // bank->loop_end = ypcm->dmabuf.dmasize >> state->format.shift;
1015                 bank->loop_end = cpu_to_le32(ypcm->dmabuf.dmasize);
1016                 bank->start = 0;
1017                 bank->num_of_loops = 0;
1018         }
1019 #if 0 /* s/pdif */
1020         if (state->digital.dig_valid)
1021                 /*state->digital.type == SND_PCM_DIG_AES_IEC958*/
1022                 ymfpci_writew(codec, YDSXGR_SPDIFOUTSTATUS,
1023                     state->digital.dig_status[0] | (state->digital.dig_status[1] << 8));
1024 #endif
1025         return 0;
1026 }
1027
1028 static irqreturn_t ymf_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1029 {
1030         ymfpci_t *codec = dev_id;
1031         u32 status, nvoice, mode;
1032         struct ymf_voice *voice;
1033         struct ymf_capture *cap;
1034
1035         status = ymfpci_readl(codec, YDSXGR_STATUS);
1036         if (status & 0x80000000) {
1037                 codec->active_bank = ymfpci_readl(codec, YDSXGR_CTRLSELECT) & 1;
1038                 spin_lock(&codec->voice_lock);
1039                 for (nvoice = 0; nvoice < YDSXG_PLAYBACK_VOICES; nvoice++) {
1040                         voice = &codec->voices[nvoice];
1041                         if (voice->use)
1042                                 ymf_pcm_interrupt(codec, voice);
1043                 }
1044                 for (nvoice = 0; nvoice < YDSXG_CAPTURE_VOICES; nvoice++) {
1045                         cap = &codec->capture[nvoice];
1046                         if (cap->use)
1047                                 ymf_cap_interrupt(codec, cap);
1048                 }
1049                 spin_unlock(&codec->voice_lock);
1050                 spin_lock(&codec->reg_lock);
1051                 ymfpci_writel(codec, YDSXGR_STATUS, 0x80000000);
1052                 mode = ymfpci_readl(codec, YDSXGR_MODE) | 2;
1053                 ymfpci_writel(codec, YDSXGR_MODE, mode);
1054                 spin_unlock(&codec->reg_lock);
1055         }
1056
1057         status = ymfpci_readl(codec, YDSXGR_INTFLAG);
1058         if (status & 1) {
1059                 /* timer handler */
1060                 ymfpci_writel(codec, YDSXGR_INTFLAG, ~0);
1061         }
1062         return IRQ_HANDLED;
1063 }
1064
1065 static void ymf_pcm_free_substream(struct ymf_pcm *ypcm)
1066 {
1067         unsigned long flags;
1068         struct ymf_unit *unit;
1069
1070         unit = ypcm->state->unit;
1071
1072         if (ypcm->type == PLAYBACK_VOICE) {
1073                 spin_lock_irqsave(&unit->voice_lock, flags);
1074                 if (ypcm->voices[1])
1075                         ymfpci_voice_free(unit, ypcm->voices[1]);
1076                 if (ypcm->voices[0])
1077                         ymfpci_voice_free(unit, ypcm->voices[0]);
1078                 spin_unlock_irqrestore(&unit->voice_lock, flags);
1079         } else {
1080                 if (ypcm->capture_bank_number != -1) {
1081                         unit->capture[ypcm->capture_bank_number].use = 0;
1082                         ypcm->capture_bank_number = -1;
1083                         ymfpci_hw_stop(unit);
1084                 }
1085         }
1086 }
1087
1088 static struct ymf_state *ymf_state_alloc(ymfpci_t *unit)
1089 {
1090         struct ymf_pcm *ypcm;
1091         struct ymf_state *state;
1092
1093         if ((state = kmalloc(sizeof(struct ymf_state), GFP_KERNEL)) == NULL) {
1094                 goto out0;
1095         }
1096         memset(state, 0, sizeof(struct ymf_state));
1097
1098         ypcm = &state->wpcm;
1099         ypcm->state = state;
1100         ypcm->type = PLAYBACK_VOICE;
1101         ypcm->capture_bank_number = -1;
1102         init_waitqueue_head(&ypcm->dmabuf.wait);
1103
1104         ypcm = &state->rpcm;
1105         ypcm->state = state;
1106         ypcm->type = CAPTURE_AC97;
1107         ypcm->capture_bank_number = -1;
1108         init_waitqueue_head(&ypcm->dmabuf.wait);
1109
1110         state->unit = unit;
1111
1112         state->format.format = AFMT_U8;
1113         state->format.rate = 8000;
1114         state->format.voices = 1;
1115         ymf_pcm_update_shift(&state->format);
1116
1117         return state;
1118
1119 out0:
1120         return NULL;
1121 }
1122
1123 /* AES/IEC958 channel status bits */
1124 #define SND_PCM_AES0_PROFESSIONAL       (1<<0)  /* 0 = consumer, 1 = professional */
1125 #define SND_PCM_AES0_NONAUDIO           (1<<1)  /* 0 = audio, 1 = non-audio */
1126 #define SND_PCM_AES0_PRO_EMPHASIS       (7<<2)  /* mask - emphasis */
1127 #define SND_PCM_AES0_PRO_EMPHASIS_NOTID (0<<2)  /* emphasis not indicated */
1128 #define SND_PCM_AES0_PRO_EMPHASIS_NONE  (1<<2)  /* none emphasis */
1129 #define SND_PCM_AES0_PRO_EMPHASIS_5015  (3<<2)  /* 50/15us emphasis */
1130 #define SND_PCM_AES0_PRO_EMPHASIS_CCITT (7<<2)  /* CCITT J.17 emphasis */
1131 #define SND_PCM_AES0_PRO_FREQ_UNLOCKED  (1<<5)  /* source sample frequency: 0 = locked, 1 = unlocked */
1132 #define SND_PCM_AES0_PRO_FS             (3<<6)  /* mask - sample frequency */
1133 #define SND_PCM_AES0_PRO_FS_NOTID       (0<<6)  /* fs not indicated */
1134 #define SND_PCM_AES0_PRO_FS_44100       (1<<6)  /* 44.1kHz */
1135 #define SND_PCM_AES0_PRO_FS_48000       (2<<6)  /* 48kHz */
1136 #define SND_PCM_AES0_PRO_FS_32000       (3<<6)  /* 32kHz */
1137 #define SND_PCM_AES0_CON_NOT_COPYRIGHT  (1<<2)  /* 0 = copyright, 1 = not copyright */
1138 #define SND_PCM_AES0_CON_EMPHASIS       (7<<3)  /* mask - emphasis */
1139 #define SND_PCM_AES0_CON_EMPHASIS_NONE  (0<<3)  /* none emphasis */
1140 #define SND_PCM_AES0_CON_EMPHASIS_5015  (1<<3)  /* 50/15us emphasis */
1141 #define SND_PCM_AES0_CON_MODE           (3<<6)  /* mask - mode */
1142 #define SND_PCM_AES1_PRO_MODE           (15<<0) /* mask - channel mode */
1143 #define SND_PCM_AES1_PRO_MODE_NOTID     (0<<0)  /* not indicated */
1144 #define SND_PCM_AES1_PRO_MODE_STEREOPHONIC (2<<0) /* stereophonic - ch A is left */
1145 #define SND_PCM_AES1_PRO_MODE_SINGLE    (4<<0)  /* single channel */
1146 #define SND_PCM_AES1_PRO_MODE_TWO       (8<<0)  /* two channels */
1147 #define SND_PCM_AES1_PRO_MODE_PRIMARY   (12<<0) /* primary/secondary */
1148 #define SND_PCM_AES1_PRO_MODE_BYTE3     (15<<0) /* vector to byte 3 */
1149 #define SND_PCM_AES1_PRO_USERBITS       (15<<4) /* mask - user bits */
1150 #define SND_PCM_AES1_PRO_USERBITS_NOTID (0<<4)  /* not indicated */
1151 #define SND_PCM_AES1_PRO_USERBITS_192   (8<<4)  /* 192-bit structure */
1152 #define SND_PCM_AES1_PRO_USERBITS_UDEF  (12<<4) /* user defined application */
1153 #define SND_PCM_AES1_CON_CATEGORY       0x7f
1154 #define SND_PCM_AES1_CON_GENERAL        0x00
1155 #define SND_PCM_AES1_CON_EXPERIMENTAL   0x40
1156 #define SND_PCM_AES1_CON_SOLIDMEM_MASK  0x0f
1157 #define SND_PCM_AES1_CON_SOLIDMEM_ID    0x08
1158 #define SND_PCM_AES1_CON_BROADCAST1_MASK 0x07
1159 #define SND_PCM_AES1_CON_BROADCAST1_ID  0x04
1160 #define SND_PCM_AES1_CON_DIGDIGCONV_MASK 0x07
1161 #define SND_PCM_AES1_CON_DIGDIGCONV_ID  0x02
1162 #define SND_PCM_AES1_CON_ADC_COPYRIGHT_MASK 0x1f
1163 #define SND_PCM_AES1_CON_ADC_COPYRIGHT_ID 0x06
1164 #define SND_PCM_AES1_CON_ADC_MASK       0x1f
1165 #define SND_PCM_AES1_CON_ADC_ID         0x16
1166 #define SND_PCM_AES1_CON_BROADCAST2_MASK 0x0f
1167 #define SND_PCM_AES1_CON_BROADCAST2_ID  0x0e
1168 #define SND_PCM_AES1_CON_LASEROPT_MASK  0x07
1169 #define SND_PCM_AES1_CON_LASEROPT_ID    0x01
1170 #define SND_PCM_AES1_CON_MUSICAL_MASK   0x07
1171 #define SND_PCM_AES1_CON_MUSICAL_ID     0x05
1172 #define SND_PCM_AES1_CON_MAGNETIC_MASK  0x07
1173 #define SND_PCM_AES1_CON_MAGNETIC_ID    0x03
1174 #define SND_PCM_AES1_CON_IEC908_CD      (SND_PCM_AES1_CON_LASEROPT_ID|0x00)
1175 #define SND_PCM_AES1_CON_NON_IEC908_CD  (SND_PCM_AES1_CON_LASEROPT_ID|0x08)
1176 #define SND_PCM_AES1_CON_PCM_CODER      (SND_PCM_AES1_CON_DIGDIGCONV_ID|0x00)
1177 #define SND_PCM_AES1_CON_SAMPLER        (SND_PCM_AES1_CON_DIGDIGCONV_ID|0x20)
1178 #define SND_PCM_AES1_CON_MIXER          (SND_PCM_AES1_CON_DIGDIGCONV_ID|0x10)
1179 #define SND_PCM_AES1_CON_RATE_CONVERTER (SND_PCM_AES1_CON_DIGDIGCONV_ID|0x18)
1180 #define SND_PCM_AES1_CON_SYNTHESIZER    (SND_PCM_AES1_CON_MUSICAL_ID|0x00)
1181 #define SND_PCM_AES1_CON_MICROPHONE     (SND_PCM_AES1_CON_MUSICAL_ID|0x08)
1182 #define SND_PCM_AES1_CON_DAT            (SND_PCM_AES1_CON_MAGNETIC_ID|0x00)
1183 #define SND_PCM_AES1_CON_VCR            (SND_PCM_AES1_CON_MAGNETIC_ID|0x08)
1184 #define SND_PCM_AES1_CON_ORIGINAL       (1<<7)  /* this bits depends on the category code */
1185 #define SND_PCM_AES2_PRO_SBITS          (7<<0)  /* mask - sample bits */
1186 #define SND_PCM_AES2_PRO_SBITS_20       (2<<0)  /* 20-bit - coordination */
1187 #define SND_PCM_AES2_PRO_SBITS_24       (4<<0)  /* 24-bit - main audio */
1188 #define SND_PCM_AES2_PRO_SBITS_UDEF     (6<<0)  /* user defined application */
1189 #define SND_PCM_AES2_PRO_WORDLEN        (7<<3)  /* mask - source word length */
1190 #define SND_PCM_AES2_PRO_WORDLEN_NOTID  (0<<3)  /* not indicated */
1191 #define SND_PCM_AES2_PRO_WORDLEN_22_18  (2<<3)  /* 22-bit or 18-bit */
1192 #define SND_PCM_AES2_PRO_WORDLEN_23_19  (4<<3)  /* 23-bit or 19-bit */
1193 #define SND_PCM_AES2_PRO_WORDLEN_24_20  (5<<3)  /* 24-bit or 20-bit */
1194 #define SND_PCM_AES2_PRO_WORDLEN_20_16  (6<<3)  /* 20-bit or 16-bit */
1195 #define SND_PCM_AES2_CON_SOURCE         (15<<0) /* mask - source number */
1196 #define SND_PCM_AES2_CON_SOURCE_UNSPEC  (0<<0)  /* unspecified */
1197 #define SND_PCM_AES2_CON_CHANNEL        (15<<4) /* mask - channel number */
1198 #define SND_PCM_AES2_CON_CHANNEL_UNSPEC (0<<4)  /* unspecified */
1199 #define SND_PCM_AES3_CON_FS             (15<<0) /* mask - sample frequency */
1200 #define SND_PCM_AES3_CON_FS_44100       (0<<0)  /* 44.1kHz */
1201 #define SND_PCM_AES3_CON_FS_48000       (2<<0)  /* 48kHz */
1202 #define SND_PCM_AES3_CON_FS_32000       (3<<0)  /* 32kHz */
1203 #define SND_PCM_AES3_CON_CLOCK          (3<<4)  /* mask - clock accuracy */
1204 #define SND_PCM_AES3_CON_CLOCK_1000PPM  (0<<4)  /* 1000 ppm */
1205 #define SND_PCM_AES3_CON_CLOCK_50PPM    (1<<4)  /* 50 ppm */
1206 #define SND_PCM_AES3_CON_CLOCK_VARIABLE (2<<4)  /* variable pitch */
1207
1208 /*
1209  * User interface
1210  */
1211
1212 /*
1213  * in this loop, dmabuf.count signifies the amount of data that is
1214  * waiting to be copied to the user's buffer.  it is filled by the dma
1215  * machine and drained by this loop.
1216  */
1217 static ssize_t
1218 ymf_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
1219 {
1220         struct ymf_state *state = (struct ymf_state *)file->private_data;
1221         struct ymf_dmabuf *dmabuf = &state->rpcm.dmabuf;
1222         struct ymf_unit *unit = state->unit;
1223         DECLARE_WAITQUEUE(waita, current);
1224         ssize_t ret;
1225         unsigned long flags;
1226         unsigned int swptr;
1227         int cnt;                        /* This many to go in this revolution */
1228
1229         if (dmabuf->mapped)
1230                 return -ENXIO;
1231         if (!dmabuf->ready && (ret = prog_dmabuf(state, 1)))
1232                 return ret;
1233         ret = 0;
1234
1235         add_wait_queue(&dmabuf->wait, &waita);
1236         set_current_state(TASK_INTERRUPTIBLE);
1237         while (count > 0) {
1238                 spin_lock_irqsave(&unit->reg_lock, flags);
1239                 if (unit->suspended) {
1240                         spin_unlock_irqrestore(&unit->reg_lock, flags);
1241                         schedule();
1242                         set_current_state(TASK_INTERRUPTIBLE);
1243                         if (signal_pending(current)) {
1244                                 if (!ret) ret = -EAGAIN;
1245                                 break;
1246                         }
1247                         continue;
1248                 }
1249                 swptr = dmabuf->swptr;
1250                 cnt = dmabuf->dmasize - swptr;
1251                 if (dmabuf->count < cnt)
1252                         cnt = dmabuf->count;
1253                 spin_unlock_irqrestore(&unit->reg_lock, flags);
1254
1255                 if (cnt > count)
1256                         cnt = count;
1257                 if (cnt <= 0) {
1258                         unsigned long tmo;
1259                         /* buffer is empty, start the dma machine and wait for data to be
1260                            recorded */
1261                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1262                         if (!state->rpcm.running) {
1263                                 ymf_capture_trigger(state->unit, &state->rpcm, 1);
1264                         }
1265                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1266                         if (file->f_flags & O_NONBLOCK) {
1267                                 if (!ret) ret = -EAGAIN;
1268                                 break;
1269                         }
1270                         /* This isnt strictly right for the 810  but it'll do */
1271                         tmo = (dmabuf->dmasize * HZ) / (state->format.rate * 2);
1272                         tmo >>= state->format.shift;
1273                         /* There are two situations when sleep_on_timeout returns, one is when
1274                            the interrupt is serviced correctly and the process is waked up by
1275                            ISR ON TIME. Another is when timeout is expired, which means that
1276                            either interrupt is NOT serviced correctly (pending interrupt) or it
1277                            is TOO LATE for the process to be scheduled to run (scheduler latency)
1278                            which results in a (potential) buffer overrun. And worse, there is
1279                            NOTHING we can do to prevent it. */
1280                         tmo = schedule_timeout(tmo);
1281                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1282                         set_current_state(TASK_INTERRUPTIBLE);
1283                         if (tmo == 0 && dmabuf->count == 0) {
1284                                 printk(KERN_ERR "ymfpci%d: recording schedule timeout, "
1285                                     "dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
1286                                     state->unit->dev_audio,
1287                                     dmabuf->dmasize, dmabuf->fragsize, dmabuf->count,
1288                                     dmabuf->hwptr, dmabuf->swptr);
1289                         }
1290                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1291                         if (signal_pending(current)) {
1292                                 if (!ret) ret = -ERESTARTSYS;
1293                                 break;
1294                         }
1295                         continue;
1296                 }
1297
1298                 if (copy_to_user(buffer, dmabuf->rawbuf + swptr, cnt)) {
1299                         if (!ret) ret = -EFAULT;
1300                         break;
1301                 }
1302
1303                 swptr = (swptr + cnt) % dmabuf->dmasize;
1304
1305                 spin_lock_irqsave(&unit->reg_lock, flags);
1306                 if (unit->suspended) {
1307                         spin_unlock_irqrestore(&unit->reg_lock, flags);
1308                         continue;
1309                 }
1310
1311                 dmabuf->swptr = swptr;
1312                 dmabuf->count -= cnt;
1313                 // spin_unlock_irqrestore(&unit->reg_lock, flags);
1314
1315                 count -= cnt;
1316                 buffer += cnt;
1317                 ret += cnt;
1318                 // spin_lock_irqsave(&unit->reg_lock, flags);
1319                 if (!state->rpcm.running) {
1320                         ymf_capture_trigger(unit, &state->rpcm, 1);
1321                 }
1322                 spin_unlock_irqrestore(&unit->reg_lock, flags);
1323         }
1324         set_current_state(TASK_RUNNING);
1325         remove_wait_queue(&dmabuf->wait, &waita);
1326
1327         return ret;
1328 }
1329
1330 static ssize_t
1331 ymf_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
1332 {
1333         struct ymf_state *state = (struct ymf_state *)file->private_data;
1334         struct ymf_dmabuf *dmabuf = &state->wpcm.dmabuf;
1335         struct ymf_unit *unit = state->unit;
1336         DECLARE_WAITQUEUE(waita, current);
1337         ssize_t ret;
1338         unsigned long flags;
1339         unsigned int swptr;
1340         int cnt;                        /* This many to go in this revolution */
1341         int redzone;
1342         int delay;
1343
1344         YMFDBGW("ymf_write: count %d\n", count);
1345
1346         if (dmabuf->mapped)
1347                 return -ENXIO;
1348         if (!dmabuf->ready && (ret = prog_dmabuf(state, 0)))
1349                 return ret;
1350         ret = 0;
1351
1352         /*
1353          * Alan's cs46xx works without a red zone - marvel of ingenuity.
1354          * We are not so brilliant... Red zone does two things:
1355          *  1. allows for safe start after a pause as we have no way
1356          *     to know what the actual, relentlessly advancing, hwptr is.
1357          *  2. makes computations in ymf_pcm_interrupt simpler.
1358          */
1359         redzone = ymf_calc_lend(state->format.rate) << state->format.shift;
1360         redzone *= 3;   /* 2 redzone + 1 possible uncertainty reserve. */
1361
1362         add_wait_queue(&dmabuf->wait, &waita);
1363         set_current_state(TASK_INTERRUPTIBLE);
1364         while (count > 0) {
1365                 spin_lock_irqsave(&unit->reg_lock, flags);
1366                 if (unit->suspended) {
1367                         spin_unlock_irqrestore(&unit->reg_lock, flags);
1368                         schedule();
1369                         set_current_state(TASK_INTERRUPTIBLE);
1370                         if (signal_pending(current)) {
1371                                 if (!ret) ret = -EAGAIN;
1372                                 break;
1373                         }
1374                         continue;
1375                 }
1376                 if (dmabuf->count < 0) {
1377                         printk(KERN_ERR
1378                            "ymf_write: count %d, was legal in cs46xx\n",
1379                             dmabuf->count);
1380                         dmabuf->count = 0;
1381                 }
1382                 if (dmabuf->count == 0) {
1383                         swptr = dmabuf->hwptr;
1384                         if (state->wpcm.running) {
1385                                 /*
1386                                  * Add uncertainty reserve.
1387                                  */
1388                                 cnt = ymf_calc_lend(state->format.rate);
1389                                 cnt <<= state->format.shift;
1390                                 if ((swptr += cnt) >= dmabuf->dmasize) {
1391                                         swptr -= dmabuf->dmasize;
1392                                 }
1393                         }
1394                         dmabuf->swptr = swptr;
1395                 } else {
1396                         /*
1397                          * XXX This is not right if dmabuf->count is small -
1398                          * about 2*x frame size or less. We cannot count on
1399                          * on appending and not causing an artefact.
1400                          * Should use a variation of the count==0 case above.
1401                          */
1402                         swptr = dmabuf->swptr;
1403                 }
1404                 cnt = dmabuf->dmasize - swptr;
1405                 if (dmabuf->count + cnt > dmabuf->dmasize - redzone)
1406                         cnt = (dmabuf->dmasize - redzone) - dmabuf->count;
1407                 spin_unlock_irqrestore(&unit->reg_lock, flags);
1408
1409                 if (cnt > count)
1410                         cnt = count;
1411                 if (cnt <= 0) {
1412                         YMFDBGW("ymf_write: full, count %d swptr %d\n",
1413                            dmabuf->count, dmabuf->swptr);
1414                         /*
1415                          * buffer is full, start the dma machine and
1416                          * wait for data to be played
1417                          */
1418                         spin_lock_irqsave(&unit->reg_lock, flags);
1419                         if (!state->wpcm.running) {
1420                                 ymf_playback_trigger(unit, &state->wpcm, 1);
1421                         }
1422                         spin_unlock_irqrestore(&unit->reg_lock, flags);
1423                         if (file->f_flags & O_NONBLOCK) {
1424                                 if (!ret) ret = -EAGAIN;
1425                                 break;
1426                         }
1427                         schedule();
1428                         set_current_state(TASK_INTERRUPTIBLE);
1429                         if (signal_pending(current)) {
1430                                 if (!ret) ret = -ERESTARTSYS;
1431                                 break;
1432                         }
1433                         continue;
1434                 }
1435                 if (copy_from_user(dmabuf->rawbuf + swptr, buffer, cnt)) {
1436                         if (!ret) ret = -EFAULT;
1437                         break;
1438                 }
1439
1440                 if ((swptr += cnt) >= dmabuf->dmasize) {
1441                         swptr -= dmabuf->dmasize;
1442                 }
1443
1444                 spin_lock_irqsave(&unit->reg_lock, flags);
1445                 if (unit->suspended) {
1446                         spin_unlock_irqrestore(&unit->reg_lock, flags);
1447                         continue;
1448                 }
1449                 dmabuf->swptr = swptr;
1450                 dmabuf->count += cnt;
1451
1452                 /*
1453                  * Start here is a bad idea - may cause startup click
1454                  * in /bin/play when dmabuf is not full yet.
1455                  * However, some broken applications do not make
1456                  * any use of SNDCTL_DSP_SYNC (Doom is the worst).
1457                  * One frame is about 5.3ms, Doom write size is 46ms.
1458                  */
1459                 delay = state->format.rate / 20;        /* 50ms */
1460                 delay <<= state->format.shift;
1461                 if (dmabuf->count >= delay && !state->wpcm.running) {
1462                         ymf_playback_trigger(unit, &state->wpcm, 1);
1463                 }
1464
1465                 spin_unlock_irqrestore(&unit->reg_lock, flags);
1466
1467                 count -= cnt;
1468                 buffer += cnt;
1469                 ret += cnt;
1470         }
1471
1472         set_current_state(TASK_RUNNING);
1473         remove_wait_queue(&dmabuf->wait, &waita);
1474
1475         YMFDBGW("ymf_write: ret %d dmabuf.count %d\n", ret, dmabuf->count);
1476         return ret;
1477 }
1478
1479 static unsigned int ymf_poll(struct file *file, struct poll_table_struct *wait)
1480 {
1481         struct ymf_state *state = (struct ymf_state *)file->private_data;
1482         struct ymf_dmabuf *dmabuf;
1483         int redzone;
1484         unsigned long flags;
1485         unsigned int mask = 0;
1486
1487         if (file->f_mode & FMODE_WRITE)
1488                 poll_wait(file, &state->wpcm.dmabuf.wait, wait);
1489         if (file->f_mode & FMODE_READ)
1490                 poll_wait(file, &state->rpcm.dmabuf.wait, wait);
1491
1492         spin_lock_irqsave(&state->unit->reg_lock, flags);
1493         if (file->f_mode & FMODE_READ) {
1494                 dmabuf = &state->rpcm.dmabuf;
1495                 if (dmabuf->count >= (signed)dmabuf->fragsize)
1496                         mask |= POLLIN | POLLRDNORM;
1497         }
1498         if (file->f_mode & FMODE_WRITE) {
1499                 redzone = ymf_calc_lend(state->format.rate);
1500                 redzone <<= state->format.shift;
1501                 redzone *= 3;
1502
1503                 dmabuf = &state->wpcm.dmabuf;
1504                 if (dmabuf->mapped) {
1505                         if (dmabuf->count >= (signed)dmabuf->fragsize)
1506                                 mask |= POLLOUT | POLLWRNORM;
1507                 } else {
1508                         /*
1509                          * Don't select unless a full fragment is available.
1510                          * Otherwise artsd does GETOSPACE, sees 0, and loops.
1511                          */
1512                         if (dmabuf->count + redzone + dmabuf->fragsize
1513                              <= dmabuf->dmasize)
1514                                 mask |= POLLOUT | POLLWRNORM;
1515                 }
1516         }
1517         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1518
1519         return mask;
1520 }
1521
1522 static int ymf_mmap(struct file *file, struct vm_area_struct *vma)
1523 {
1524         struct ymf_state *state = (struct ymf_state *)file->private_data;
1525         struct ymf_dmabuf *dmabuf = &state->wpcm.dmabuf;
1526         int ret;
1527         unsigned long size;
1528
1529         if (vma->vm_flags & VM_WRITE) {
1530                 if ((ret = prog_dmabuf(state, 0)) != 0)
1531                         return ret;
1532         } else if (vma->vm_flags & VM_READ) {
1533                 if ((ret = prog_dmabuf(state, 1)) != 0)
1534                         return ret;
1535         } else 
1536                 return -EINVAL;
1537
1538         if (vma->vm_pgoff != 0)
1539                 return -EINVAL;
1540         size = vma->vm_end - vma->vm_start;
1541         if (size > (PAGE_SIZE << dmabuf->buforder))
1542                 return -EINVAL;
1543         if (remap_pfn_range(vma, vma->vm_start,
1544                              virt_to_phys(dmabuf->rawbuf) >> PAGE_SHIFT,
1545                              size, vma->vm_page_prot))
1546                 return -EAGAIN;
1547         dmabuf->mapped = 1;
1548
1549 /* P3 */ printk(KERN_INFO "ymfpci: using memory mapped sound, untested!\n");
1550         return 0;
1551 }
1552
1553 static int ymf_ioctl(struct inode *inode, struct file *file,
1554     unsigned int cmd, unsigned long arg)
1555 {
1556         struct ymf_state *state = (struct ymf_state *)file->private_data;
1557         struct ymf_dmabuf *dmabuf;
1558         unsigned long flags;
1559         audio_buf_info abinfo;
1560         count_info cinfo;
1561         int redzone;
1562         int val;
1563         void __user *argp = (void __user *)arg;
1564         int __user *p = argp;
1565
1566         switch (cmd) {
1567         case OSS_GETVERSION:
1568                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETVER) arg 0x%lx\n", cmd, arg);
1569                 return put_user(SOUND_VERSION, p);
1570
1571         case SNDCTL_DSP_RESET:
1572                 YMFDBGX("ymf_ioctl: cmd 0x%x(RESET)\n", cmd);
1573                 if (file->f_mode & FMODE_WRITE) {
1574                         ymf_wait_dac(state);
1575                         dmabuf = &state->wpcm.dmabuf;
1576                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1577                         dmabuf->ready = 0;
1578                         dmabuf->swptr = dmabuf->hwptr;
1579                         dmabuf->count = dmabuf->total_bytes = 0;
1580                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1581                 }
1582                 if (file->f_mode & FMODE_READ) {
1583                         ymf_stop_adc(state);
1584                         dmabuf = &state->rpcm.dmabuf;
1585                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1586                         dmabuf->ready = 0;
1587                         dmabuf->swptr = dmabuf->hwptr;
1588                         dmabuf->count = dmabuf->total_bytes = 0;
1589                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1590                 }
1591                 return 0;
1592
1593         case SNDCTL_DSP_SYNC:
1594                 YMFDBGX("ymf_ioctl: cmd 0x%x(SYNC)\n", cmd);
1595                 if (file->f_mode & FMODE_WRITE) {
1596                         dmabuf = &state->wpcm.dmabuf;
1597                         if (file->f_flags & O_NONBLOCK) {
1598                                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1599                                 if (dmabuf->count != 0 && !state->wpcm.running) {
1600                                         ymf_start_dac(state);
1601                                 }
1602                                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1603                         } else {
1604                                 ymf_wait_dac(state);
1605                         }
1606                 }
1607                 /* XXX What does this do for reading? dmabuf->count=0; ? */
1608                 return 0;
1609
1610         case SNDCTL_DSP_SPEED: /* set smaple rate */
1611                 if (get_user(val, p))
1612                         return -EFAULT;
1613                 YMFDBGX("ymf_ioctl: cmd 0x%x(SPEED) sp %d\n", cmd, val);
1614                 if (val >= 8000 && val <= 48000) {
1615                         if (file->f_mode & FMODE_WRITE) {
1616                                 ymf_wait_dac(state);
1617                                 dmabuf = &state->wpcm.dmabuf;
1618                                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1619                                 dmabuf->ready = 0;
1620                                 state->format.rate = val;
1621                                 ymf_pcm_update_shift(&state->format);
1622                                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1623                         }
1624                         if (file->f_mode & FMODE_READ) {
1625                                 ymf_stop_adc(state);
1626                                 dmabuf = &state->rpcm.dmabuf;
1627                                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1628                                 dmabuf->ready = 0;
1629                                 state->format.rate = val;
1630                                 ymf_pcm_update_shift(&state->format);
1631                                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1632                         }
1633                 }
1634                 return put_user(state->format.rate, p);
1635
1636         /*
1637          * OSS manual does not mention SNDCTL_DSP_STEREO at all.
1638          * All channels are mono and if you want stereo, you
1639          * play into two channels with SNDCTL_DSP_CHANNELS.
1640          * However, mpg123 calls it. I wonder, why Michael Hipp used it.
1641          */
1642         case SNDCTL_DSP_STEREO: /* set stereo or mono channel */
1643                 if (get_user(val, p))
1644                         return -EFAULT;
1645                 YMFDBGX("ymf_ioctl: cmd 0x%x(STEREO) st %d\n", cmd, val);
1646                 if (file->f_mode & FMODE_WRITE) {
1647                         ymf_wait_dac(state); 
1648                         dmabuf = &state->wpcm.dmabuf;
1649                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1650                         dmabuf->ready = 0;
1651                         state->format.voices = val ? 2 : 1;
1652                         ymf_pcm_update_shift(&state->format);
1653                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1654                 }
1655                 if (file->f_mode & FMODE_READ) {
1656                         ymf_stop_adc(state);
1657                         dmabuf = &state->rpcm.dmabuf;
1658                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1659                         dmabuf->ready = 0;
1660                         state->format.voices = val ? 2 : 1;
1661                         ymf_pcm_update_shift(&state->format);
1662                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1663                 }
1664                 return 0;
1665
1666         case SNDCTL_DSP_GETBLKSIZE:
1667                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETBLK)\n", cmd);
1668                 if (file->f_mode & FMODE_WRITE) {
1669                         if ((val = prog_dmabuf(state, 0)))
1670                                 return val;
1671                         val = state->wpcm.dmabuf.fragsize;
1672                         YMFDBGX("ymf_ioctl: GETBLK w %d\n", val);
1673                         return put_user(val, p);
1674                 }
1675                 if (file->f_mode & FMODE_READ) {
1676                         if ((val = prog_dmabuf(state, 1)))
1677                                 return val;
1678                         val = state->rpcm.dmabuf.fragsize;
1679                         YMFDBGX("ymf_ioctl: GETBLK r %d\n", val);
1680                         return put_user(val, p);
1681                 }
1682                 return -EINVAL;
1683
1684         case SNDCTL_DSP_GETFMTS: /* Returns a mask of supported sample format*/
1685                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETFMTS)\n", cmd);
1686                 return put_user(AFMT_S16_LE|AFMT_U8, p);
1687
1688         case SNDCTL_DSP_SETFMT: /* Select sample format */
1689                 if (get_user(val, p))
1690                         return -EFAULT;
1691                 YMFDBGX("ymf_ioctl: cmd 0x%x(SETFMT) fmt %d\n", cmd, val);
1692                 if (val == AFMT_S16_LE || val == AFMT_U8) {
1693                         if (file->f_mode & FMODE_WRITE) {
1694                                 ymf_wait_dac(state);
1695                                 dmabuf = &state->wpcm.dmabuf;
1696                                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1697                                 dmabuf->ready = 0;
1698                                 state->format.format = val;
1699                                 ymf_pcm_update_shift(&state->format);
1700                                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1701                         }
1702                         if (file->f_mode & FMODE_READ) {
1703                                 ymf_stop_adc(state);
1704                                 dmabuf = &state->rpcm.dmabuf;
1705                                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1706                                 dmabuf->ready = 0;
1707                                 state->format.format = val;
1708                                 ymf_pcm_update_shift(&state->format);
1709                                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1710                         }
1711                 }
1712                 return put_user(state->format.format, p);
1713
1714         case SNDCTL_DSP_CHANNELS:
1715                 if (get_user(val, p))
1716                         return -EFAULT;
1717                 YMFDBGX("ymf_ioctl: cmd 0x%x(CHAN) ch %d\n", cmd, val);
1718                 if (val != 0) {
1719                         if (file->f_mode & FMODE_WRITE) {
1720                                 ymf_wait_dac(state);
1721                                 if (val == 1 || val == 2) {
1722                                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1723                                         dmabuf = &state->wpcm.dmabuf;
1724                                         dmabuf->ready = 0;
1725                                         state->format.voices = val;
1726                                         ymf_pcm_update_shift(&state->format);
1727                                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1728                                 }
1729                         }
1730                         if (file->f_mode & FMODE_READ) {
1731                                 ymf_stop_adc(state);
1732                                 if (val == 1 || val == 2) {
1733                                         spin_lock_irqsave(&state->unit->reg_lock, flags);
1734                                         dmabuf = &state->rpcm.dmabuf;
1735                                         dmabuf->ready = 0;
1736                                         state->format.voices = val;
1737                                         ymf_pcm_update_shift(&state->format);
1738                                         spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1739                                 }
1740                         }
1741                 }
1742                 return put_user(state->format.voices, p);
1743
1744         case SNDCTL_DSP_POST:
1745                 YMFDBGX("ymf_ioctl: cmd 0x%x(POST)\n", cmd);
1746                 /*
1747                  * Quoting OSS PG:
1748                  *    The ioctl SNDCTL_DSP_POST is a lightweight version of
1749                  *    SNDCTL_DSP_SYNC. It just tells to the driver that there
1750                  *    is likely to be a pause in the output. This makes it
1751                  *    possible for the device to handle the pause more
1752                  *    intelligently. This ioctl doesn't block the application.
1753                  *
1754                  * The paragraph above is a clumsy way to say "flush ioctl".
1755                  * This ioctl is used by mpg123.
1756                  */
1757                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1758                 if (state->wpcm.dmabuf.count != 0 && !state->wpcm.running) {
1759                         ymf_start_dac(state);
1760                 }
1761                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1762                 return 0;
1763
1764         case SNDCTL_DSP_SETFRAGMENT:
1765                 if (get_user(val, p))
1766                         return -EFAULT;
1767                 YMFDBGX("ymf_ioctl: cmd 0x%x(SETFRAG) fr 0x%04x:%04x(%d:%d)\n",
1768                     cmd,
1769                     (val >> 16) & 0xFFFF, val & 0xFFFF,
1770                     (val >> 16) & 0xFFFF, val & 0xFFFF);
1771                 dmabuf = &state->wpcm.dmabuf;
1772                 dmabuf->ossfragshift = val & 0xffff;
1773                 dmabuf->ossmaxfrags = (val >> 16) & 0xffff;
1774                 if (dmabuf->ossfragshift < 4)
1775                         dmabuf->ossfragshift = 4;
1776                 if (dmabuf->ossfragshift > 15)
1777                         dmabuf->ossfragshift = 15;
1778                 return 0;
1779
1780         case SNDCTL_DSP_GETOSPACE:
1781                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETOSPACE)\n", cmd);
1782                 if (!(file->f_mode & FMODE_WRITE))
1783                         return -EINVAL;
1784                 dmabuf = &state->wpcm.dmabuf;
1785                 if (!dmabuf->ready && (val = prog_dmabuf(state, 0)) != 0)
1786                         return val;
1787                 redzone = ymf_calc_lend(state->format.rate);
1788                 redzone <<= state->format.shift;
1789                 redzone *= 3;
1790                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1791                 abinfo.fragsize = dmabuf->fragsize;
1792                 abinfo.bytes = dmabuf->dmasize - dmabuf->count - redzone;
1793                 abinfo.fragstotal = dmabuf->numfrag;
1794                 abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
1795                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1796                 return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
1797
1798         case SNDCTL_DSP_GETISPACE:
1799                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETISPACE)\n", cmd);
1800                 if (!(file->f_mode & FMODE_READ))
1801                         return -EINVAL;
1802                 dmabuf = &state->rpcm.dmabuf;
1803                 if (!dmabuf->ready && (val = prog_dmabuf(state, 1)) != 0)
1804                         return val;
1805                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1806                 abinfo.fragsize = dmabuf->fragsize;
1807                 abinfo.bytes = dmabuf->count;
1808                 abinfo.fragstotal = dmabuf->numfrag;
1809                 abinfo.fragments = abinfo.bytes >> dmabuf->fragshift;
1810                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1811                 return copy_to_user(argp, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
1812
1813         case SNDCTL_DSP_NONBLOCK:
1814                 YMFDBGX("ymf_ioctl: cmd 0x%x(NONBLOCK)\n", cmd);
1815                 file->f_flags |= O_NONBLOCK;
1816                 return 0;
1817
1818         case SNDCTL_DSP_GETCAPS:
1819                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETCAPS)\n", cmd);
1820                 /* return put_user(DSP_CAP_REALTIME|DSP_CAP_TRIGGER|DSP_CAP_MMAP,
1821                             p); */
1822                 return put_user(0, p);
1823
1824         case SNDCTL_DSP_GETIPTR:
1825                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETIPTR)\n", cmd);
1826                 if (!(file->f_mode & FMODE_READ))
1827                         return -EINVAL;
1828                 dmabuf = &state->rpcm.dmabuf;
1829                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1830                 cinfo.bytes = dmabuf->total_bytes;
1831                 cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
1832                 cinfo.ptr = dmabuf->hwptr;
1833                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1834                 YMFDBGX("ymf_ioctl: GETIPTR ptr %d bytes %d\n",
1835                     cinfo.ptr, cinfo.bytes);
1836                 return copy_to_user(argp, &cinfo, sizeof(cinfo)) ? -EFAULT : 0;
1837
1838         case SNDCTL_DSP_GETOPTR:
1839                 YMFDBGX("ymf_ioctl: cmd 0x%x(GETOPTR)\n", cmd);
1840                 if (!(file->f_mode & FMODE_WRITE))
1841                         return -EINVAL;
1842                 dmabuf = &state->wpcm.dmabuf;
1843                 spin_lock_irqsave(&state->unit->reg_lock, flags);
1844                 cinfo.bytes = dmabuf->total_bytes;
1845                 cinfo.blocks = dmabuf->count >> dmabuf->fragshift;
1846                 cinfo.ptr = dmabuf->hwptr;
1847                 spin_unlock_irqrestore(&state->unit->reg_lock, flags);
1848                 YMFDBGX("ymf_ioctl: GETOPTR ptr %d bytes %d\n",
1849                     cinfo.ptr, cinfo.bytes);
1850                 return copy_to_user(argp, &cinfo, sizeof(cinfo)) ? -EFAULT : 0;
1851
1852         case SNDCTL_DSP_SETDUPLEX:
1853                 YMFDBGX("ymf_ioctl: cmd 0x%x(SETDUPLEX)\n", cmd);
1854                 return 0;               /* Always duplex */
1855
1856         case SOUND_PCM_READ_RATE:
1857                 YMFDBGX("ymf_ioctl: cmd 0x%x(READ_RATE)\n", cmd);
1858                 return put_user(state->format.rate, p);
1859
1860         case SOUND_PCM_READ_CHANNELS:
1861                 YMFDBGX("ymf_ioctl: cmd 0x%x(READ_CH)\n", cmd);
1862                 return put_user(state->format.voices, p);
1863
1864         case SOUND_PCM_READ_BITS:
1865                 YMFDBGX("ymf_ioctl: cmd 0x%x(READ_BITS)\n", cmd);
1866                 return put_user(AFMT_S16_LE, p);
1867
1868         case SNDCTL_DSP_MAPINBUF:
1869         case SNDCTL_DSP_MAPOUTBUF:
1870         case SNDCTL_DSP_SETSYNCRO:
1871         case SOUND_PCM_WRITE_FILTER:
1872         case SOUND_PCM_READ_FILTER:
1873                 YMFDBGX("ymf_ioctl: cmd 0x%x unsupported\n", cmd);
1874                 return -ENOTTY;
1875
1876         default:
1877                 /*
1878                  * Some programs mix up audio devices and ioctls
1879                  * or perhaps they expect "universal" ioctls,
1880                  * for instance we get SNDCTL_TMR_CONTINUE here.
1881                  * (mpg123 -g 100 ends here too - to be fixed.)
1882                  */
1883                 YMFDBGX("ymf_ioctl: cmd 0x%x unknown\n", cmd);
1884                 break;
1885         }
1886         return -ENOTTY;
1887 }
1888
1889 /*
1890  * open(2)
1891  * We use upper part of the minor to distinguish between soundcards.
1892  * Channels are opened with a clone open.
1893  */
1894 static int ymf_open(struct inode *inode, struct file *file)
1895 {
1896         struct list_head *list;
1897         ymfpci_t *unit = NULL;
1898         int minor;
1899         struct ymf_state *state;
1900         int err;
1901
1902         minor = iminor(inode);
1903         if ((minor & 0x0F) == 3) {      /* /dev/dspN */
1904                 ;
1905         } else {
1906                 return -ENXIO;
1907         }
1908
1909         unit = NULL;    /* gcc warns */
1910         spin_lock(&ymf_devs_lock);
1911         list_for_each(list, &ymf_devs) {
1912                 unit = list_entry(list, ymfpci_t, ymf_devs);
1913                 if (((unit->dev_audio ^ minor) & ~0x0F) == 0)
1914                         break;
1915         }
1916         spin_unlock(&ymf_devs_lock);
1917         if (unit == NULL)
1918                 return -ENODEV;
1919
1920         mutex_lock(&unit->open_mutex);
1921
1922         if ((state = ymf_state_alloc(unit)) == NULL) {
1923                 mutex_unlock(&unit->open_mutex);
1924                 return -ENOMEM;
1925         }
1926         list_add_tail(&state->chain, &unit->states);
1927
1928         file->private_data = state;
1929
1930         /*
1931          * ymf_read and ymf_write that we borrowed from cs46xx
1932          * allocate buffers with prog_dmabuf(). We call prog_dmabuf
1933          * here so that in case of DMA memory exhaustion open
1934          * fails rather than write.
1935          *
1936          * XXX prog_dmabuf allocates voice. Should allocate explicitly, above.
1937          */
1938         if (file->f_mode & FMODE_WRITE) {
1939                 if (!state->wpcm.dmabuf.ready) {
1940                         if ((err = prog_dmabuf(state, 0)) != 0) {
1941                                 goto out_nodma;
1942                         }
1943                 }
1944         }
1945         if (file->f_mode & FMODE_READ) {
1946                 if (!state->rpcm.dmabuf.ready) {
1947                         if ((err = prog_dmabuf(state, 1)) != 0) {
1948                                 goto out_nodma;
1949                         }
1950                 }
1951         }
1952
1953 #if 0 /* test if interrupts work */
1954         ymfpci_writew(unit, YDSXGR_TIMERCOUNT, 0xfffe); /* ~ 680ms */
1955         ymfpci_writeb(unit, YDSXGR_TIMERCTRL,
1956             (YDSXGR_TIMERCTRL_TEN|YDSXGR_TIMERCTRL_TIEN));
1957 #endif
1958         mutex_unlock(&unit->open_mutex);
1959
1960         return nonseekable_open(inode, file);
1961
1962 out_nodma:
1963         /*
1964          * XXX Broken custom: "goto out_xxx" in other place is
1965          * a nestable exception, but here it is not nestable due to semaphore.
1966          * XXX Doubtful technique of self-describing objects....
1967          */
1968         dealloc_dmabuf(unit, &state->wpcm.dmabuf);
1969         dealloc_dmabuf(unit, &state->rpcm.dmabuf);
1970         ymf_pcm_free_substream(&state->wpcm);
1971         ymf_pcm_free_substream(&state->rpcm);
1972
1973         list_del(&state->chain);
1974         kfree(state);
1975
1976         mutex_unlock(&unit->open_mutex);
1977         return err;
1978 }
1979
1980 static int ymf_release(struct inode *inode, struct file *file)
1981 {
1982         struct ymf_state *state = (struct ymf_state *)file->private_data;
1983         ymfpci_t *unit = state->unit;
1984
1985 #if 0 /* test if interrupts work */
1986         ymfpci_writeb(unit, YDSXGR_TIMERCTRL, 0);
1987 #endif
1988
1989         mutex_lock(&unit->open_mutex);
1990
1991         /*
1992          * XXX Solve the case of O_NONBLOCK close - don't deallocate here.
1993          * Deallocate when unloading the driver and we can wait.
1994          */
1995         ymf_wait_dac(state);
1996         ymf_stop_adc(state);            /* fortunately, it's immediate */
1997         dealloc_dmabuf(unit, &state->wpcm.dmabuf);
1998         dealloc_dmabuf(unit, &state->rpcm.dmabuf);
1999         ymf_pcm_free_substream(&state->wpcm);
2000         ymf_pcm_free_substream(&state->rpcm);
2001
2002         list_del(&state->chain);
2003         file->private_data = NULL;      /* Can you tell I programmed Solaris */
2004         kfree(state);
2005
2006         mutex_unlock(&unit->open_mutex);
2007
2008         return 0;
2009 }
2010
2011 /*
2012  * Mixer operations are based on cs46xx.
2013  */
2014 static int ymf_open_mixdev(struct inode *inode, struct file *file)
2015 {
2016         int minor = iminor(inode);
2017         struct list_head *list;
2018         ymfpci_t *unit;
2019         int i;
2020
2021         spin_lock(&ymf_devs_lock);
2022         list_for_each(list, &ymf_devs) {
2023                 unit = list_entry(list, ymfpci_t, ymf_devs);
2024                 for (i = 0; i < NR_AC97; i++) {
2025                         if (unit->ac97_codec[i] != NULL &&
2026                             unit->ac97_codec[i]->dev_mixer == minor) {
2027                                 spin_unlock(&ymf_devs_lock);
2028                                 goto match;
2029                         }
2030                 }
2031         }
2032         spin_unlock(&ymf_devs_lock);
2033         return -ENODEV;
2034
2035  match:
2036         file->private_data = unit->ac97_codec[i];
2037
2038         return nonseekable_open(inode, file);
2039 }
2040
2041 static int ymf_ioctl_mixdev(struct inode *inode, struct file *file,
2042     unsigned int cmd, unsigned long arg)
2043 {
2044         struct ac97_codec *codec = (struct ac97_codec *)file->private_data;
2045
2046         return codec->mixer_ioctl(codec, cmd, arg);
2047 }
2048
2049 static int ymf_release_mixdev(struct inode *inode, struct file *file)
2050 {
2051         return 0;
2052 }
2053
2054 static /*const*/ struct file_operations ymf_fops = {
2055         .owner          = THIS_MODULE,
2056         .llseek         = no_llseek,
2057         .read           = ymf_read,
2058         .write          = ymf_write,
2059         .poll           = ymf_poll,
2060         .ioctl          = ymf_ioctl,
2061         .mmap           = ymf_mmap,
2062         .open           = ymf_open,
2063         .release        = ymf_release,
2064 };
2065
2066 static /*const*/ struct file_operations ymf_mixer_fops = {
2067         .owner          = THIS_MODULE,
2068         .llseek         = no_llseek,
2069         .ioctl          = ymf_ioctl_mixdev,
2070         .open           = ymf_open_mixdev,
2071         .release        = ymf_release_mixdev,
2072 };
2073
2074 /*
2075  */
2076
2077 static int ymf_suspend(struct pci_dev *pcidev, pm_message_t unused)
2078 {
2079         struct ymf_unit *unit = pci_get_drvdata(pcidev);
2080         unsigned long flags;
2081         struct ymf_dmabuf *dmabuf;
2082         struct list_head *p;
2083         struct ymf_state *state;
2084         struct ac97_codec *codec;
2085         int i;
2086
2087         spin_lock_irqsave(&unit->reg_lock, flags);
2088
2089         unit->suspended = 1;
2090
2091         for (i = 0; i < NR_AC97; i++) {
2092                 if ((codec = unit->ac97_codec[i]) != NULL)
2093                         ac97_save_state(codec);
2094         }
2095
2096         list_for_each(p, &unit->states) {
2097                 state = list_entry(p, struct ymf_state, chain);
2098
2099                 dmabuf = &state->wpcm.dmabuf;
2100                 dmabuf->hwptr = dmabuf->swptr = 0;
2101                 dmabuf->total_bytes = 0;
2102                 dmabuf->count = 0;
2103
2104                 dmabuf = &state->rpcm.dmabuf;
2105                 dmabuf->hwptr = dmabuf->swptr = 0;
2106                 dmabuf->total_bytes = 0;
2107                 dmabuf->count = 0;
2108         }
2109
2110         ymfpci_writel(unit, YDSXGR_NATIVEDACOUTVOL, 0);
2111         ymfpci_disable_dsp(unit);
2112
2113         spin_unlock_irqrestore(&unit->reg_lock, flags);
2114         
2115         return 0;
2116 }
2117
2118 static int ymf_resume(struct pci_dev *pcidev)
2119 {
2120         struct ymf_unit *unit = pci_get_drvdata(pcidev);
2121         unsigned long flags;
2122         struct list_head *p;
2123         struct ymf_state *state;
2124         struct ac97_codec *codec;
2125         int i;
2126
2127         ymfpci_aclink_reset(unit->pci);
2128         ymfpci_codec_ready(unit, 0, 1);         /* prints diag if not ready. */
2129
2130 #ifdef CONFIG_SOUND_YMFPCI_LEGACY
2131         /* XXX At this time the legacy registers are probably deprogrammed. */
2132 #endif
2133
2134         ymfpci_download_image(unit);
2135
2136         ymf_memload(unit);
2137
2138         spin_lock_irqsave(&unit->reg_lock, flags);
2139
2140         if (unit->start_count) {
2141                 ymfpci_writel(unit, YDSXGR_MODE, 3);
2142                 unit->active_bank = ymfpci_readl(unit, YDSXGR_CTRLSELECT) & 1;
2143         }
2144
2145         for (i = 0; i < NR_AC97; i++) {
2146                 if ((codec = unit->ac97_codec[i]) != NULL)
2147                         ac97_restore_state(codec);
2148         }
2149
2150         unit->suspended = 0;
2151         list_for_each(p, &unit->states) {
2152                 state = list_entry(p, struct ymf_state, chain);
2153                 wake_up(&state->wpcm.dmabuf.wait);
2154                 wake_up(&state->rpcm.dmabuf.wait);
2155         }
2156
2157         spin_unlock_irqrestore(&unit->reg_lock, flags);
2158         return 0;
2159 }
2160
2161 /*
2162  *  initialization routines
2163  */
2164
2165 #ifdef CONFIG_SOUND_YMFPCI_LEGACY
2166
2167 static int ymfpci_setup_legacy(ymfpci_t *unit, struct pci_dev *pcidev)
2168 {
2169         int v;
2170         int mpuio = -1, oplio = -1;
2171
2172         switch (unit->iomidi) {
2173         case 0x330:
2174                 mpuio = 0;
2175                 break;
2176         case 0x300:
2177                 mpuio = 1;
2178                 break;
2179         case 0x332:
2180                 mpuio = 2;
2181                 break;
2182         case 0x334:
2183                 mpuio = 3;
2184                 break;
2185         default: ;
2186         }
2187
2188         switch (unit->iosynth) {
2189         case 0x388:
2190                 oplio = 0;
2191                 break;
2192         case 0x398:
2193                 oplio = 1;
2194                 break;
2195         case 0x3a0:
2196                 oplio = 2;
2197                 break;
2198         case 0x3a8:
2199                 oplio = 3;
2200                 break;
2201         default: ;
2202         }
2203
2204         if (mpuio >= 0 || oplio >= 0) {
2205                 /* 0x0020: 1 - 10 bits of I/O address decoded, 0 - 16 bits. */
2206                 v = 0x001e;
2207                 pci_write_config_word(pcidev, PCIR_LEGCTRL, v);
2208
2209                 switch (pcidev->device) {
2210                 case PCI_DEVICE_ID_YAMAHA_724:
2211                 case PCI_DEVICE_ID_YAMAHA_740:
2212                 case PCI_DEVICE_ID_YAMAHA_724F:
2213                 case PCI_DEVICE_ID_YAMAHA_740C:
2214                         v = 0x8800;
2215                         if (mpuio >= 0) { v |= mpuio<<4; }
2216                         if (oplio >= 0) { v |= oplio; }
2217                         pci_write_config_word(pcidev, PCIR_ELEGCTRL, v);
2218                         break;
2219
2220                 case PCI_DEVICE_ID_YAMAHA_744:
2221                 case PCI_DEVICE_ID_YAMAHA_754:
2222                         v = 0x8800;
2223                         pci_write_config_word(pcidev, PCIR_ELEGCTRL, v);
2224                         if (oplio >= 0) {
2225                                 pci_write_config_word(pcidev, PCIR_OPLADR, unit->iosynth);
2226                         }
2227                         if (mpuio >= 0) {
2228                                 pci_write_config_word(pcidev, PCIR_MPUADR, unit->iomidi);
2229                         }
2230                         break;
2231
2232                 default:
2233                         printk(KERN_ERR "ymfpci: Unknown device ID: 0x%x\n",
2234                             pcidev->device);
2235                         return -EINVAL;
2236                 }
2237         }
2238
2239         return 0;
2240 }
2241 #endif /* CONFIG_SOUND_YMFPCI_LEGACY */
2242
2243 static void ymfpci_aclink_reset(struct pci_dev * pci)
2244 {
2245         u8 cmd;
2246
2247         /*
2248          * In the 744, 754 only 0x01 exists, 0x02 is undefined.
2249          * It does not seem to hurt to trip both regardless of revision.
2250          */
2251         pci_read_config_byte(pci, PCIR_DSXGCTRL, &cmd);
2252         pci_write_config_byte(pci, PCIR_DSXGCTRL, cmd & 0xfc);
2253         pci_write_config_byte(pci, PCIR_DSXGCTRL, cmd | 0x03);
2254         pci_write_config_byte(pci, PCIR_DSXGCTRL, cmd & 0xfc);
2255
2256         pci_write_config_word(pci, PCIR_DSXPWRCTRL1, 0);
2257         pci_write_config_word(pci, PCIR_DSXPWRCTRL2, 0);
2258 }
2259
2260 static void ymfpci_enable_dsp(ymfpci_t *codec)
2261 {
2262         ymfpci_writel(codec, YDSXGR_CONFIG, 0x00000001);
2263 }
2264
2265 static void ymfpci_disable_dsp(ymfpci_t *codec)
2266 {
2267         u32 val;
2268         int timeout = 1000;
2269
2270         val = ymfpci_readl(codec, YDSXGR_CONFIG);
2271         if (val)
2272                 ymfpci_writel(codec, YDSXGR_CONFIG, 0x00000000);
2273         while (timeout-- > 0) {
2274                 val = ymfpci_readl(codec, YDSXGR_STATUS);
2275                 if ((val & 0x00000002) == 0)
2276                         break;
2277         }
2278 }
2279
2280 #include "ymfpci_image.h"
2281
2282 static void ymfpci_download_image(ymfpci_t *codec)
2283 {
2284         int i, ver_1e;
2285         u16 ctrl;
2286
2287         ymfpci_writel(codec, YDSXGR_NATIVEDACOUTVOL, 0x00000000);
2288         ymfpci_disable_dsp(codec);
2289         ymfpci_writel(codec, YDSXGR_MODE, 0x00010000);
2290         ymfpci_writel(codec, YDSXGR_MODE, 0x00000000);
2291         ymfpci_writel(codec, YDSXGR_MAPOFREC, 0x00000000);
2292         ymfpci_writel(codec, YDSXGR_MAPOFEFFECT, 0x00000000);
2293         ymfpci_writel(codec, YDSXGR_PLAYCTRLBASE, 0x00000000);
2294         ymfpci_writel(codec, YDSXGR_RECCTRLBASE, 0x00000000);
2295         ymfpci_writel(codec, YDSXGR_EFFCTRLBASE, 0x00000000);
2296         ctrl = ymfpci_readw(codec, YDSXGR_GLOBALCTRL);
2297         ymfpci_writew(codec, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
2298
2299         /* setup DSP instruction code */
2300         for (i = 0; i < YDSXG_DSPLENGTH / 4; i++)
2301                 ymfpci_writel(codec, YDSXGR_DSPINSTRAM + (i << 2), DspInst[i]);
2302
2303         switch (codec->pci->device) {
2304         case PCI_DEVICE_ID_YAMAHA_724F:
2305         case PCI_DEVICE_ID_YAMAHA_740C:
2306         case PCI_DEVICE_ID_YAMAHA_744:
2307         case PCI_DEVICE_ID_YAMAHA_754:
2308                 ver_1e = 1;
2309                 break;
2310         default:
2311                 ver_1e = 0;
2312         }
2313
2314         if (ver_1e) {
2315                 /* setup control instruction code */
2316                 for (i = 0; i < YDSXG_CTRLLENGTH / 4; i++)
2317                         ymfpci_writel(codec, YDSXGR_CTRLINSTRAM + (i << 2), CntrlInst1E[i]);
2318         } else {
2319                 for (i = 0; i < YDSXG_CTRLLENGTH / 4; i++)
2320                         ymfpci_writel(codec, YDSXGR_CTRLINSTRAM + (i << 2), CntrlInst[i]);
2321         }
2322
2323         ymfpci_enable_dsp(codec);
2324
2325         /* 0.02s sounds not too bad, we may do schedule_timeout() later. */
2326         mdelay(20); /* seems we need some delay after downloading image.. */
2327 }
2328
2329 static int ymfpci_memalloc(ymfpci_t *codec)
2330 {
2331         unsigned int playback_ctrl_size;
2332         unsigned int bank_size_playback;
2333         unsigned int bank_size_capture;
2334         unsigned int bank_size_effect;
2335         unsigned int size;
2336         unsigned int off;
2337         char *ptr;
2338         dma_addr_t pba;
2339         int voice, bank;
2340
2341         playback_ctrl_size = 4 + 4 * YDSXG_PLAYBACK_VOICES;
2342         bank_size_playback = ymfpci_readl(codec, YDSXGR_PLAYCTRLSIZE) << 2;
2343         bank_size_capture = ymfpci_readl(codec, YDSXGR_RECCTRLSIZE) << 2;
2344         bank_size_effect = ymfpci_readl(codec, YDSXGR_EFFCTRLSIZE) << 2;
2345         codec->work_size = YDSXG_DEFAULT_WORK_SIZE;
2346
2347         size = ((playback_ctrl_size + 0x00ff) & ~0x00ff) +
2348             ((bank_size_playback * 2 * YDSXG_PLAYBACK_VOICES + 0xff) & ~0xff) +
2349             ((bank_size_capture * 2 * YDSXG_CAPTURE_VOICES + 0xff) & ~0xff) +
2350             ((bank_size_effect * 2 * YDSXG_EFFECT_VOICES + 0xff) & ~0xff) +
2351             codec->work_size;
2352
2353         ptr = pci_alloc_consistent(codec->pci, size + 0xff, &pba);
2354         if (ptr == NULL)
2355                 return -ENOMEM;
2356         codec->dma_area_va = ptr;
2357         codec->dma_area_ba = pba;
2358         codec->dma_area_size = size + 0xff;
2359
2360         off = (unsigned long)ptr & 0xff;
2361         if (off) {
2362                 ptr += 0x100 - off;
2363                 pba += 0x100 - off;
2364         }
2365
2366         /*
2367          * Hardware requires only ptr[playback_ctrl_size] zeroed,
2368          * but in our judgement it is a wrong kind of savings, so clear it all.
2369          */
2370         memset(ptr, 0, size);
2371
2372         codec->ctrl_playback = (u32 *)ptr;
2373         codec->ctrl_playback_ba = pba;
2374         codec->ctrl_playback[0] = cpu_to_le32(YDSXG_PLAYBACK_VOICES);
2375         ptr += (playback_ctrl_size + 0x00ff) & ~0x00ff;
2376         pba += (playback_ctrl_size + 0x00ff) & ~0x00ff;
2377
2378         off = 0;
2379         for (voice = 0; voice < YDSXG_PLAYBACK_VOICES; voice++) {
2380                 codec->voices[voice].number = voice;
2381                 codec->voices[voice].bank =
2382                     (ymfpci_playback_bank_t *) (ptr + off);
2383                 codec->voices[voice].bank_ba = pba + off;
2384                 off += 2 * bank_size_playback;          /* 2 banks */
2385         }
2386         off = (off + 0xff) & ~0xff;
2387         ptr += off;
2388         pba += off;
2389
2390         off = 0;
2391         codec->bank_base_capture = pba;
2392         for (voice = 0; voice < YDSXG_CAPTURE_VOICES; voice++)
2393                 for (bank = 0; bank < 2; bank++) {
2394                         codec->bank_capture[voice][bank] =
2395                             (ymfpci_capture_bank_t *) (ptr + off);
2396                         off += bank_size_capture;
2397                 }
2398         off = (off + 0xff) & ~0xff;
2399         ptr += off;
2400         pba += off;
2401
2402         off = 0;
2403         codec->bank_base_effect = pba;
2404         for (voice = 0; voice < YDSXG_EFFECT_VOICES; voice++)
2405                 for (bank = 0; bank < 2; bank++) {
2406                         codec->bank_effect[voice][bank] =
2407                             (ymfpci_effect_bank_t *) (ptr + off);
2408                         off += bank_size_effect;
2409                 }
2410         off = (off + 0xff) & ~0xff;
2411         ptr += off;
2412         pba += off;
2413
2414         codec->work_base = pba;
2415
2416         return 0;
2417 }
2418
2419 static void ymfpci_memfree(ymfpci_t *codec)
2420 {
2421         ymfpci_writel(codec, YDSXGR_PLAYCTRLBASE, 0);
2422         ymfpci_writel(codec, YDSXGR_RECCTRLBASE, 0);
2423         ymfpci_writel(codec, YDSXGR_EFFCTRLBASE, 0);
2424         ymfpci_writel(codec, YDSXGR_WORKBASE, 0);
2425         ymfpci_writel(codec, YDSXGR_WORKSIZE, 0);
2426         pci_free_consistent(codec->pci,
2427             codec->dma_area_size, codec->dma_area_va, codec->dma_area_ba);
2428 }
2429
2430 static void ymf_memload(ymfpci_t *unit)
2431 {
2432
2433         ymfpci_writel(unit, YDSXGR_PLAYCTRLBASE, unit->ctrl_playback_ba);
2434         ymfpci_writel(unit, YDSXGR_RECCTRLBASE, unit->bank_base_capture);
2435         ymfpci_writel(unit, YDSXGR_EFFCTRLBASE, unit->bank_base_effect);
2436         ymfpci_writel(unit, YDSXGR_WORKBASE, unit->work_base);
2437         ymfpci_writel(unit, YDSXGR_WORKSIZE, unit->work_size >> 2);
2438
2439         /* S/PDIF output initialization */
2440         ymfpci_writew(unit, YDSXGR_SPDIFOUTCTRL, 0);
2441         ymfpci_writew(unit, YDSXGR_SPDIFOUTSTATUS,
2442                 SND_PCM_AES0_CON_EMPHASIS_NONE |
2443                 (SND_PCM_AES1_CON_ORIGINAL << 8) |
2444                 (SND_PCM_AES1_CON_PCM_CODER << 8));
2445
2446         /* S/PDIF input initialization */
2447         ymfpci_writew(unit, YDSXGR_SPDIFINCTRL, 0);
2448
2449         /* move this volume setup to mixer */
2450         ymfpci_writel(unit, YDSXGR_NATIVEDACOUTVOL, 0x3fff3fff);
2451         ymfpci_writel(unit, YDSXGR_BUF441OUTVOL, 0);
2452         ymfpci_writel(unit, YDSXGR_NATIVEADCINVOL, 0x3fff3fff);
2453         ymfpci_writel(unit, YDSXGR_NATIVEDACINVOL, 0x3fff3fff);
2454 }
2455
2456 static int ymf_ac97_init(ymfpci_t *unit, int num_ac97)
2457 {
2458         struct ac97_codec *codec;
2459         u16 eid;
2460
2461         if ((codec = ac97_alloc_codec()) == NULL)
2462                 return -ENOMEM;
2463
2464         /* initialize some basic codec information, other fields will be filled
2465            in ac97_probe_codec */
2466         codec->private_data = unit;
2467         codec->id = num_ac97;
2468
2469         codec->codec_read = ymfpci_codec_read;
2470         codec->codec_write = ymfpci_codec_write;
2471
2472         if (ac97_probe_codec(codec) == 0) {
2473                 printk(KERN_ERR "ymfpci: ac97_probe_codec failed\n");
2474                 goto out_kfree;
2475         }
2476
2477         eid = ymfpci_codec_read(codec, AC97_EXTENDED_ID);
2478         if (eid==0xFFFF) {
2479                 printk(KERN_WARNING "ymfpci: no codec attached ?\n");
2480                 goto out_kfree;
2481         }
2482
2483         unit->ac97_features = eid;
2484
2485         if ((codec->dev_mixer = register_sound_mixer(&ymf_mixer_fops, -1)) < 0) {
2486                 printk(KERN_ERR "ymfpci: couldn't register mixer!\n");
2487                 goto out_kfree;
2488         }
2489
2490         unit->ac97_codec[num_ac97] = codec;
2491
2492         return 0;
2493  out_kfree:
2494         ac97_release_codec(codec);
2495         return -ENODEV;
2496 }
2497
2498 #ifdef CONFIG_SOUND_YMFPCI_LEGACY
2499 # ifdef MODULE
2500 static int mpu_io;
2501 static int synth_io;
2502 module_param(mpu_io, int, 0);
2503 module_param(synth_io, int, 0);
2504 # else
2505 static int mpu_io     = 0x330;
2506 static int synth_io   = 0x388;
2507 # endif
2508 static int assigned;
2509 #endif /* CONFIG_SOUND_YMFPCI_LEGACY */
2510
2511 static int __devinit ymf_probe_one(struct pci_dev *pcidev, const struct pci_device_id *ent)
2512 {
2513         u16 ctrl;
2514         unsigned long base;
2515         ymfpci_t *codec;
2516
2517         int err;
2518
2519         if ((err = pci_enable_device(pcidev)) != 0) {
2520                 printk(KERN_ERR "ymfpci: pci_enable_device failed\n");
2521                 return err;
2522         }
2523         base = pci_resource_start(pcidev, 0);
2524
2525         if ((codec = kmalloc(sizeof(ymfpci_t), GFP_KERNEL)) == NULL) {
2526                 printk(KERN_ERR "ymfpci: no core\n");
2527                 return -ENOMEM;
2528         }
2529         memset(codec, 0, sizeof(*codec));
2530
2531         spin_lock_init(&codec->reg_lock);
2532         spin_lock_init(&codec->voice_lock);
2533         spin_lock_init(&codec->ac97_lock);
2534         mutex_init(&codec->open_mutex);
2535         INIT_LIST_HEAD(&codec->states);
2536         codec->pci = pcidev;
2537
2538         pci_read_config_byte(pcidev, PCI_REVISION_ID, &codec->rev);
2539
2540         if (request_mem_region(base, 0x8000, "ymfpci") == NULL) {
2541                 printk(KERN_ERR "ymfpci: unable to request mem region\n");
2542                 goto out_free;
2543         }
2544
2545         if ((codec->reg_area_virt = ioremap(base, 0x8000)) == NULL) {
2546                 printk(KERN_ERR "ymfpci: unable to map registers\n");
2547                 goto out_release_region;
2548         }
2549
2550         pci_set_master(pcidev);
2551
2552         printk(KERN_INFO "ymfpci: %s at 0x%lx IRQ %d\n",
2553             (char *)ent->driver_data, base, pcidev->irq);
2554
2555         ymfpci_aclink_reset(pcidev);
2556         if (ymfpci_codec_ready(codec, 0, 1) < 0)
2557                 goto out_unmap;
2558
2559 #ifdef CONFIG_SOUND_YMFPCI_LEGACY
2560         if (assigned == 0) {
2561                 codec->iomidi = mpu_io;
2562                 codec->iosynth = synth_io;
2563                 if (ymfpci_setup_legacy(codec, pcidev) < 0)
2564                         goto out_unmap;
2565                 assigned = 1;
2566         }
2567 #endif
2568
2569         ymfpci_download_image(codec);
2570
2571         if (ymfpci_memalloc(codec) < 0)
2572                 goto out_disable_dsp;
2573         ymf_memload(codec);
2574
2575         if (request_irq(pcidev->irq, ymf_interrupt, IRQF_SHARED, "ymfpci", codec) != 0) {
2576                 printk(KERN_ERR "ymfpci: unable to request IRQ %d\n",
2577                     pcidev->irq);
2578                 goto out_memfree;
2579         }
2580
2581         /* register /dev/dsp */
2582         if ((codec->dev_audio = register_sound_dsp(&ymf_fops, -1)) < 0) {
2583                 printk(KERN_ERR "ymfpci: unable to register dsp\n");
2584                 goto out_free_irq;
2585         }
2586
2587         /*
2588          * Poke just the primary for the moment.
2589          */
2590         if ((err = ymf_ac97_init(codec, 0)) != 0)
2591                 goto out_unregister_sound_dsp;
2592
2593 #ifdef CONFIG_SOUND_YMFPCI_LEGACY
2594         codec->opl3_data.name = "ymfpci";
2595         codec->mpu_data.name  = "ymfpci";
2596
2597         codec->opl3_data.io_base = codec->iosynth;
2598         codec->opl3_data.irq     = -1;
2599
2600         codec->mpu_data.io_base  = codec->iomidi;
2601         codec->mpu_data.irq      = -1;  /* May be different from our PCI IRQ. */
2602
2603         if (codec->iomidi) {
2604                 if (!probe_uart401(&codec->mpu_data, THIS_MODULE)) {
2605                         codec->iomidi = 0;      /* XXX kludge */
2606                 }
2607         }
2608 #endif /* CONFIG_SOUND_YMFPCI_LEGACY */
2609
2610         /* put it into driver list */
2611         spin_lock(&ymf_devs_lock);
2612         list_add_tail(&codec->ymf_devs, &ymf_devs);
2613         spin_unlock(&ymf_devs_lock);
2614         pci_set_drvdata(pcidev, codec);
2615
2616         return 0;
2617
2618  out_unregister_sound_dsp:
2619         unregister_sound_dsp(codec->dev_audio);
2620  out_free_irq:
2621         free_irq(pcidev->irq, codec);
2622  out_memfree:
2623         ymfpci_memfree(codec);
2624  out_disable_dsp:
2625         ymfpci_disable_dsp(codec);
2626         ctrl = ymfpci_readw(codec, YDSXGR_GLOBALCTRL);
2627         ymfpci_writew(codec, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
2628         ymfpci_writel(codec, YDSXGR_STATUS, ~0);
2629  out_unmap:
2630         iounmap(codec->reg_area_virt);
2631  out_release_region:
2632         release_mem_region(pci_resource_start(pcidev, 0), 0x8000);
2633  out_free:
2634         if (codec->ac97_codec[0])
2635                 ac97_release_codec(codec->ac97_codec[0]);
2636         return -ENODEV;
2637 }
2638
2639 static void __devexit ymf_remove_one(struct pci_dev *pcidev)
2640 {
2641         __u16 ctrl;
2642         ymfpci_t *codec = pci_get_drvdata(pcidev);
2643
2644         /* remove from list of devices */
2645         spin_lock(&ymf_devs_lock);
2646         list_del(&codec->ymf_devs);
2647         spin_unlock(&ymf_devs_lock);
2648
2649         unregister_sound_mixer(codec->ac97_codec[0]->dev_mixer);
2650         ac97_release_codec(codec->ac97_codec[0]);
2651         unregister_sound_dsp(codec->dev_audio);
2652         free_irq(pcidev->irq, codec);
2653         ymfpci_memfree(codec);
2654         ymfpci_writel(codec, YDSXGR_STATUS, ~0);
2655         ymfpci_disable_dsp(codec);
2656         ctrl = ymfpci_readw(codec, YDSXGR_GLOBALCTRL);
2657         ymfpci_writew(codec, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
2658         iounmap(codec->reg_area_virt);
2659         release_mem_region(pci_resource_start(pcidev, 0), 0x8000);
2660 #ifdef CONFIG_SOUND_YMFPCI_LEGACY
2661         if (codec->iomidi) {
2662                 unload_uart401(&codec->mpu_data);
2663         }
2664 #endif /* CONFIG_SOUND_YMFPCI_LEGACY */
2665 }
2666
2667 MODULE_AUTHOR("Jaroslav Kysela");
2668 MODULE_DESCRIPTION("Yamaha YMF7xx PCI Audio");
2669 MODULE_LICENSE("GPL");
2670
2671 static struct pci_driver ymfpci_driver = {
2672         .name           = "ymfpci",
2673         .id_table       = ymf_id_tbl,
2674         .probe          = ymf_probe_one,
2675         .remove         = __devexit_p(ymf_remove_one),
2676         .suspend        = ymf_suspend,
2677         .resume         = ymf_resume
2678 };
2679
2680 static int __init ymf_init_module(void)
2681 {
2682         return pci_register_driver(&ymfpci_driver);
2683 }
2684
2685 static void __exit ymf_cleanup_module (void)
2686 {
2687         pci_unregister_driver(&ymfpci_driver);
2688 }
2689
2690 module_init(ymf_init_module);
2691 module_exit(ymf_cleanup_module);