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