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