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