b1fad46a7b02afe7be74c40354f7fc1e148fabdf
[linux-2.6.git] / sound / pci / azt3328.c
1 /*
2  *  azt3328.c - driver for Aztech AZF3328 based soundcards (e.g. PCI168).
3  *  Copyright (C) 2002, 2005 - 2010 by Andreas Mohr <andi AT lisas.de>
4  *
5  *  Framework borrowed from Bart Hartgers's als4000.c.
6  *  Driver developed on PCI168 AP(W) version (PCI rev. 10, subsystem ID 1801),
7  *  found in a Fujitsu-Siemens PC ("Cordant", aluminum case).
8  *  Other versions are:
9  *  PCI168 A(W), sub ID 1800
10  *  PCI168 A/AP, sub ID 8000
11  *  Please give me feedback in case you try my driver with one of these!!
12  *
13  *  Keywords: Windows XP Vista 168nt4-125.zip 168win95-125.zip PCI 168 download
14  *  (XP/Vista do not support this card at all but every Linux distribution
15  *   has very good support out of the box;
16  *   just to make sure that the right people hit this and get to know that,
17  *   despite the high level of Internet ignorance - as usual :-P -
18  *   about very good support for this card - on Linux!)
19  *
20  * GPL LICENSE
21  *  This program is free software; you can redistribute it and/or modify
22  *  it under the terms of the GNU General Public License as published by
23  *  the Free Software Foundation; either version 2 of the License, or
24  *  (at your option) any later version.
25  *
26  *  This program is distributed in the hope that it will be useful,
27  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
28  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29  *  GNU General Public License for more details.
30
31  *  You should have received a copy of the GNU General Public License
32  *  along with this program; if not, write to the Free Software
33  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
34  *
35  * NOTES
36  *  Since Aztech does not provide any chipset documentation,
37  *  even on repeated request to various addresses,
38  *  and the answer that was finally given was negative
39  *  (and I was stupid enough to manage to get hold of a PCI168 soundcard
40  *  in the first place >:-P}),
41  *  I was forced to base this driver on reverse engineering
42  *  (3 weeks' worth of evenings filled with driver work).
43  *  (and no, I did NOT go the easy way: to pick up a SB PCI128 for 9 Euros)
44  *
45  *  It is quite likely that the AZF3328 chip is the PCI cousin of the
46  *  AZF3318 ("azt1020 pnp", "MM Pro 16") ISA chip, given very similar specs.
47  *
48  *  The AZF3328 chip (note: AZF3328, *not* AZT3328, that's just the driver name
49  *  for compatibility reasons) from Azfin (joint-venture of Aztech and Fincitec,
50  *  Fincitec acquired by National Semiconductor in 2002, together with the
51  *  Fincitec-related company ARSmikro) has the following features:
52  *
53  *  - compatibility & compliance:
54  *    - Microsoft PC 97 ("PC 97 Hardware Design Guide",
55  *                       http://www.microsoft.com/whdc/archive/pcguides.mspx)
56  *    - Microsoft PC 98 Baseline Audio
57  *    - MPU401 UART
58  *    - Sound Blaster Emulation (DOS Box)
59  *  - builtin AC97 conformant codec (SNR over 80dB)
60  *    Note that "conformant" != "compliant"!! this chip's mixer register layout
61  *    *differs* from the standard AC97 layout:
62  *    they chose to not implement the headphone register (which is not a
63  *    problem since it's merely optional), yet when doing this, they committed
64  *    the grave sin of letting other registers follow immediately instead of
65  *    keeping a headphone dummy register, thereby shifting the mixer register
66  *    addresses illegally. So far unfortunately it looks like the very flexible
67  *    ALSA AC97 support is still not enough to easily compensate for such a
68  *    grave layout violation despite all tweaks and quirks mechanisms it offers.
69  *  - builtin genuine OPL3 - verified to work fine, 20080506
70  *  - full duplex 16bit playback/record at independent sampling rate
71  *  - MPU401 (+ legacy address support, claimed by one official spec sheet)
72  *    FIXME: how to enable legacy addr??
73  *  - game port (legacy address support)
74  *  - builtin DirectInput support, helps reduce CPU overhead (interrupt-driven
75  *    features supported). - See common term "Digital Enhanced Game Port"...
76  *    (probably DirectInput 3.0 spec - confirm)
77  *  - builtin 3D enhancement (said to be YAMAHA Ymersion)
78  *  - built-in General DirectX timer having a 20 bits counter
79  *    with 1us resolution (see below!)
80  *  - I2S serial output port for external DAC
81  *    [FIXME: 3.3V or 5V level? maximum rate is 66.2kHz right?]
82  *  - supports 33MHz PCI spec 2.1, PCI power management 1.0, compliant with ACPI
83  *  - supports hardware volume control
84  *  - single chip low cost solution (128 pin QFP)
85  *  - supports programmable Sub-vendor and Sub-system ID [24C02 SEEPROM chip]
86  *    required for Microsoft's logo compliance (FIXME: where?)
87  *    At least the Trident 4D Wave DX has one bit somewhere
88  *    to enable writes to PCI subsystem VID registers, that should be it.
89  *    This might easily be in extended PCI reg space, since PCI168 also has
90  *    some custom data starting at 0x80. What kind of config settings
91  *    are located in our extended PCI space anyway??
92  *  - PCI168 AP(W) card: power amplifier with 4 Watts/channel at 4 Ohms
93  *    [TDA1517P chip]
94  *
95  *  Note that this driver now is actually *better* than the Windows driver,
96  *  since it additionally supports the card's 1MHz DirectX timer - just try
97  *  the following snd-seq module parameters etc.:
98  *  - options snd-seq seq_default_timer_class=2 seq_default_timer_sclass=0
99  *    seq_default_timer_card=0 seq_client_load=1 seq_default_timer_device=0
100  *    seq_default_timer_subdevice=0 seq_default_timer_resolution=1000000
101  *  - "timidity -iAv -B2,8 -Os -EFreverb=0"
102  *  - "pmidi -p 128:0 jazz.mid"
103  *
104  *  OPL3 hardware playback testing, try something like:
105  *  cat /proc/asound/hwdep
106  *  and
107  *  aconnect -o
108  *  Then use
109  *  sbiload -Dhw:x,y --opl3 /usr/share/sounds/opl3/std.o3 ......./drums.o3
110  *  where x,y is the xx-yy number as given in hwdep.
111  *  Then try
112  *  pmidi -p a:b jazz.mid
113  *  where a:b is the client number plus 0 usually, as given by aconnect above.
114  *  Oh, and make sure to unmute the FM mixer control (doh!)
115  *  NOTE: power use during OPL3 playback is _VERY_ high (70W --> 90W!)
116  *  despite no CPU activity, possibly due to hindering ACPI idling somehow.
117  *  Shouldn't be a problem of the AZF3328 chip itself, I'd hope.
118  *  Higher PCM / FM mixer levels seem to conflict (causes crackling),
119  *  at least sometimes.   Maybe even use with hardware sequencer timer above :)
120  *  adplay/adplug-utils might soon offer hardware-based OPL3 playback, too.
121  *
122  *  Certain PCI versions of this card are susceptible to DMA traffic underruns
123  *  in some systems (resulting in sound crackling/clicking/popping),
124  *  probably because they don't have a DMA FIFO buffer or so.
125  *  Overview (PCI ID/PCI subID/PCI rev.):
126  *  - no DMA crackling on SiS735: 0x50DC/0x1801/16
127  *  - unknown performance: 0x50DC/0x1801/10
128  *    (well, it's not bad on an Athlon 1800 with now very optimized IRQ handler)
129  *
130  *  Crackling happens with VIA chipsets or, in my case, an SiS735, which is
131  *  supposed to be very fast and supposed to get rid of crackling much
132  *  better than a VIA, yet ironically I still get crackling, like many other
133  *  people with the same chipset.
134  *  Possible remedies:
135  *  - use speaker (amplifier) output instead of headphone output
136  *    (in case crackling is due to overloaded output clipping)
137  *  - plug card into a different PCI slot, preferrably one that isn't shared
138  *    too much (this helps a lot, but not completely!)
139  *  - get rid of PCI VGA card, use AGP instead
140  *  - upgrade or downgrade BIOS
141  *  - fiddle with PCI latency settings (setpci -v -s BUSID latency_timer=XX)
142  *    Not too helpful.
143  *  - Disable ACPI/power management/"Auto Detect RAM/PCI Clk" in BIOS
144  *
145  * BUGS
146  *  - full-duplex might *still* be problematic, however a recent test was fine
147  *  - (non-bug) "Bass/Treble or 3D settings don't work" - they do get evaluated
148  *    if you set PCM output switch to "pre 3D" instead of "post 3D".
149  *    If this can't be set, then get a mixer application that Isn't Stupid (tm)
150  *    (e.g. kmix, gamix) - unfortunately several are!!
151  *  - locking is not entirely clean, especially the audio stream activity
152  *    ints --> may be racy
153  *  - an _unconnected_ secondary joystick at the gameport will be reported
154  *    to be "active" (floating values, not precisely -1) due to the way we need
155  *    to read the Digital Enhanced Game Port. Not sure whether it is fixable.
156  *
157  * TODO
158  *  - use PCI_VDEVICE
159  *  - verify driver status on x86_64
160  *  - test multi-card driver operation
161  *  - (ab)use 1MHz DirectX timer as kernel clocksource
162  *  - test MPU401 MIDI playback etc.
163  *  - add more power micro-management (disable various units of the card
164  *    as long as they're unused, to improve audio quality and save power).
165  *    However this requires more I/O ports which I haven't figured out yet
166  *    and which thus might not even exist...
167  *    The standard suspend/resume functionality could probably make use of
168  *    some improvement, too...
169  *  - figure out what all unknown port bits are responsible for
170  *  - figure out some cleverly evil scheme to possibly make ALSA AC97 code
171  *    fully accept our quite incompatible ""AC97"" mixer and thus save some
172  *    code (but I'm not too optimistic that doing this is possible at all)
173  *  - use MMIO (memory-mapped I/O)? Slightly faster access, e.g. for gameport.
174  */
175
176 #include <asm/io.h>
177 #include <linux/init.h>
178 #include <linux/pci.h>
179 #include <linux/delay.h>
180 #include <linux/slab.h>
181 #include <linux/gameport.h>
182 #include <linux/moduleparam.h>
183 #include <linux/dma-mapping.h>
184 #include <sound/core.h>
185 #include <sound/control.h>
186 #include <sound/pcm.h>
187 #include <sound/rawmidi.h>
188 #include <sound/mpu401.h>
189 #include <sound/opl3.h>
190 #include <sound/initval.h>
191 #include "azt3328.h"
192
193 MODULE_AUTHOR("Andreas Mohr <andi AT lisas.de>");
194 MODULE_DESCRIPTION("Aztech AZF3328 (PCI168)");
195 MODULE_LICENSE("GPL");
196 MODULE_SUPPORTED_DEVICE("{{Aztech,AZF3328}}");
197
198 #if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
199 #define SUPPORT_GAMEPORT 1
200 #endif
201
202 /* === Debug settings ===
203   Further diagnostic functionality than the settings below
204   does not need to be provided, since one can easily write a POSIX shell script
205   to dump the card's I/O ports (those listed in lspci -v -v):
206   dump()
207   {
208     local descr=$1; local addr=$2; local count=$3
209
210     echo "${descr}: ${count} @ ${addr}:"
211     dd if=/dev/port skip=`printf %d ${addr}` count=${count} bs=1 \
212       2>/dev/null| hexdump -C
213   }
214   and then use something like
215   "dump joy200 0x200 8", "dump mpu388 0x388 4", "dump joy 0xb400 8",
216   "dump codec00 0xa800 32", "dump mixer 0xb800 64", "dump synth 0xbc00 8",
217   possibly within a "while true; do ... sleep 1; done" loop.
218   Tweaking ports could be done using
219   VALSTRING="`printf "%02x" $value`"
220   printf "\x""$VALSTRING"|dd of=/dev/port seek=`printf %d ${addr}` bs=1 \
221     2>/dev/null
222 */
223
224 #define DEBUG_MISC      0
225 #define DEBUG_CALLS     0
226 #define DEBUG_MIXER     0
227 #define DEBUG_CODEC     0
228 #define DEBUG_TIMER     0
229 #define DEBUG_GAME      0
230 #define DEBUG_PM        0
231 #define MIXER_TESTING   0
232
233 #if DEBUG_MISC
234 #define snd_azf3328_dbgmisc(format, args...) printk(KERN_DEBUG format, ##args)
235 #else
236 #define snd_azf3328_dbgmisc(format, args...)
237 #endif
238
239 #if DEBUG_CALLS
240 #define snd_azf3328_dbgcalls(format, args...) printk(format, ##args)
241 #define snd_azf3328_dbgcallenter() printk(KERN_DEBUG "--> %s\n", __func__)
242 #define snd_azf3328_dbgcallleave() printk(KERN_DEBUG "<-- %s\n", __func__)
243 #else
244 #define snd_azf3328_dbgcalls(format, args...)
245 #define snd_azf3328_dbgcallenter()
246 #define snd_azf3328_dbgcallleave()
247 #endif
248
249 #if DEBUG_MIXER
250 #define snd_azf3328_dbgmixer(format, args...) printk(KERN_DEBUG format, ##args)
251 #else
252 #define snd_azf3328_dbgmixer(format, args...)
253 #endif
254
255 #if DEBUG_CODEC
256 #define snd_azf3328_dbgcodec(format, args...) printk(KERN_DEBUG format, ##args)
257 #else
258 #define snd_azf3328_dbgcodec(format, args...)
259 #endif
260
261 #if DEBUG_MISC
262 #define snd_azf3328_dbgtimer(format, args...) printk(KERN_DEBUG format, ##args)
263 #else
264 #define snd_azf3328_dbgtimer(format, args...)
265 #endif
266
267 #if DEBUG_GAME
268 #define snd_azf3328_dbggame(format, args...) printk(KERN_DEBUG format, ##args)
269 #else
270 #define snd_azf3328_dbggame(format, args...)
271 #endif
272
273 #if DEBUG_PM
274 #define snd_azf3328_dbgpm(format, args...) printk(KERN_DEBUG format, ##args)
275 #else
276 #define snd_azf3328_dbgpm(format, args...)
277 #endif
278
279 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 0-MAX */
280 module_param_array(index, int, NULL, 0444);
281 MODULE_PARM_DESC(index, "Index value for AZF3328 soundcard.");
282
283 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
284 module_param_array(id, charp, NULL, 0444);
285 MODULE_PARM_DESC(id, "ID string for AZF3328 soundcard.");
286
287 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;      /* Enable this card */
288 module_param_array(enable, bool, NULL, 0444);
289 MODULE_PARM_DESC(enable, "Enable AZF3328 soundcard.");
290
291 static int seqtimer_scaling = 128;
292 module_param(seqtimer_scaling, int, 0444);
293 MODULE_PARM_DESC(seqtimer_scaling, "Set 1024000Hz sequencer timer scale factor (lockup danger!). Default 128.");
294
295 struct snd_azf3328_codec_data {
296         unsigned long io_base;
297         unsigned int dma_base; /* helper to avoid an indirection in hotpath */
298         struct snd_pcm_substream *substream;
299         bool running;
300         const char *name;
301 };
302
303 enum snd_azf3328_codec_type {
304   /* warning: fixed indices (also used for bitmask checks!) */
305   AZF_CODEC_PLAYBACK = 0,
306   AZF_CODEC_CAPTURE = 1,
307   AZF_CODEC_I2S_OUT = 2,
308 };
309
310 struct snd_azf3328 {
311         /* often-used fields towards beginning, then grouped */
312
313         unsigned long ctrl_io; /* usually 0xb000, size 128 */
314         unsigned long game_io;  /* usually 0xb400, size 8 */
315         unsigned long mpu_io;   /* usually 0xb800, size 4 */
316         unsigned long opl3_io; /* usually 0xbc00, size 8 */
317         unsigned long mixer_io; /* usually 0xc000, size 64 */
318
319         spinlock_t reg_lock;
320
321         struct snd_timer *timer;
322
323         struct snd_pcm *pcm[3];
324
325         /* playback, recording and I2S out codecs */
326         struct snd_azf3328_codec_data codecs[3];
327
328         struct snd_card *card;
329         struct snd_rawmidi *rmidi;
330
331 #ifdef SUPPORT_GAMEPORT
332         struct gameport *gameport;
333         u16 axes[4];
334 #endif
335
336         struct pci_dev *pci;
337         int irq;
338
339         /* register 0x6a is write-only, thus need to remember setting.
340          * If we need to add more registers here, then we might try to fold this
341          * into some transparent combined shadow register handling with
342          * CONFIG_PM register storage below, but that's slightly difficult. */
343         u16 shadow_reg_ctrl_6AH;
344
345 #ifdef CONFIG_PM
346         /* register value containers for power management
347          * Note: not always full I/O range preserved (similar to Win driver!) */
348         u32 saved_regs_ctrl[AZF_ALIGN(AZF_IO_SIZE_CTRL_PM) / 4];
349         u32 saved_regs_game[AZF_ALIGN(AZF_IO_SIZE_GAME_PM) / 4];
350         u32 saved_regs_mpu[AZF_ALIGN(AZF_IO_SIZE_MPU_PM) / 4];
351         u32 saved_regs_opl3[AZF_ALIGN(AZF_IO_SIZE_OPL3_PM) / 4];
352         u32 saved_regs_mixer[AZF_ALIGN(AZF_IO_SIZE_MIXER_PM) / 4];
353 #endif
354 };
355
356 static DEFINE_PCI_DEVICE_TABLE(snd_azf3328_ids) = {
357         { 0x122D, 0x50DC, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },   /* PCI168/3328 */
358         { 0x122D, 0x80DA, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },   /* 3328 */
359         { 0, }
360 };
361
362 MODULE_DEVICE_TABLE(pci, snd_azf3328_ids);
363
364
365 static int
366 snd_azf3328_io_reg_setb(unsigned reg, u8 mask, bool do_set)
367 {
368         /* Well, strictly spoken, the inb/outb sequence isn't atomic
369            and would need locking. However we currently don't care
370            since it potentially complicates matters. */
371         u8 prev = inb(reg), new;
372
373         new = (do_set) ? (prev|mask) : (prev & ~mask);
374         /* we need to always write the new value no matter whether it differs
375          * or not, since some register bits don't indicate their setting */
376         outb(new, reg);
377         if (new != prev)
378                 return 1;
379
380         return 0;
381 }
382
383 static inline void
384 snd_azf3328_codec_outb(const struct snd_azf3328_codec_data *codec,
385                        unsigned reg,
386                        u8 value
387 )
388 {
389         outb(value, codec->io_base + reg);
390 }
391
392 static inline u8
393 snd_azf3328_codec_inb(const struct snd_azf3328_codec_data *codec, unsigned reg)
394 {
395         return inb(codec->io_base + reg);
396 }
397
398 static inline void
399 snd_azf3328_codec_outw(const struct snd_azf3328_codec_data *codec,
400                        unsigned reg,
401                        u16 value
402 )
403 {
404         outw(value, codec->io_base + reg);
405 }
406
407 static inline u16
408 snd_azf3328_codec_inw(const struct snd_azf3328_codec_data *codec, unsigned reg)
409 {
410         return inw(codec->io_base + reg);
411 }
412
413 static inline void
414 snd_azf3328_codec_outl(const struct snd_azf3328_codec_data *codec,
415                        unsigned reg,
416                        u32 value
417 )
418 {
419         outl(value, codec->io_base + reg);
420 }
421
422 static inline u32
423 snd_azf3328_codec_inl(const struct snd_azf3328_codec_data *codec, unsigned reg)
424 {
425         return inl(codec->io_base + reg);
426 }
427
428 static inline void
429 snd_azf3328_ctrl_outb(const struct snd_azf3328 *chip, unsigned reg, u8 value)
430 {
431         outb(value, chip->ctrl_io + reg);
432 }
433
434 static inline u8
435 snd_azf3328_ctrl_inb(const struct snd_azf3328 *chip, unsigned reg)
436 {
437         return inb(chip->ctrl_io + reg);
438 }
439
440 static inline void
441 snd_azf3328_ctrl_outw(const struct snd_azf3328 *chip, unsigned reg, u16 value)
442 {
443         outw(value, chip->ctrl_io + reg);
444 }
445
446 static inline void
447 snd_azf3328_ctrl_outl(const struct snd_azf3328 *chip, unsigned reg, u32 value)
448 {
449         outl(value, chip->ctrl_io + reg);
450 }
451
452 static inline void
453 snd_azf3328_game_outb(const struct snd_azf3328 *chip, unsigned reg, u8 value)
454 {
455         outb(value, chip->game_io + reg);
456 }
457
458 static inline void
459 snd_azf3328_game_outw(const struct snd_azf3328 *chip, unsigned reg, u16 value)
460 {
461         outw(value, chip->game_io + reg);
462 }
463
464 static inline u8
465 snd_azf3328_game_inb(const struct snd_azf3328 *chip, unsigned reg)
466 {
467         return inb(chip->game_io + reg);
468 }
469
470 static inline u16
471 snd_azf3328_game_inw(const struct snd_azf3328 *chip, unsigned reg)
472 {
473         return inw(chip->game_io + reg);
474 }
475
476 static inline void
477 snd_azf3328_mixer_outw(const struct snd_azf3328 *chip, unsigned reg, u16 value)
478 {
479         outw(value, chip->mixer_io + reg);
480 }
481
482 static inline u16
483 snd_azf3328_mixer_inw(const struct snd_azf3328 *chip, unsigned reg)
484 {
485         return inw(chip->mixer_io + reg);
486 }
487
488 #define AZF_MUTE_BIT 0x80
489
490 static bool
491 snd_azf3328_mixer_set_mute(const struct snd_azf3328 *chip,
492                            unsigned reg, bool do_mute
493 )
494 {
495         unsigned long portbase = chip->mixer_io + reg + 1;
496         bool updated;
497
498         /* the mute bit is on the *second* (i.e. right) register of a
499          * left/right channel setting */
500         updated = snd_azf3328_io_reg_setb(portbase, AZF_MUTE_BIT, do_mute);
501
502         /* indicate whether it was muted before */
503         return (do_mute) ? !updated : updated;
504 }
505
506 static void
507 snd_azf3328_mixer_write_volume_gradually(const struct snd_azf3328 *chip,
508                                          unsigned reg,
509                                          unsigned char dst_vol_left,
510                                          unsigned char dst_vol_right,
511                                          int chan_sel, int delay
512 )
513 {
514         unsigned long portbase = chip->mixer_io + reg;
515         unsigned char curr_vol_left = 0, curr_vol_right = 0;
516         int left_change = 0, right_change = 0;
517
518         snd_azf3328_dbgcallenter();
519
520         if (chan_sel & SET_CHAN_LEFT) {
521                 curr_vol_left  = inb(portbase + 1);
522
523                 /* take care of muting flag contained in left channel */
524                 if (curr_vol_left & AZF_MUTE_BIT)
525                         dst_vol_left |= AZF_MUTE_BIT;
526                 else
527                         dst_vol_left &= ~AZF_MUTE_BIT;
528
529                 left_change = (curr_vol_left > dst_vol_left) ? -1 : 1;
530         }
531
532         if (chan_sel & SET_CHAN_RIGHT) {
533                 curr_vol_right = inb(portbase + 0);
534
535                 right_change = (curr_vol_right > dst_vol_right) ? -1 : 1;
536         }
537
538         do {
539                 if (left_change) {
540                         if (curr_vol_left != dst_vol_left) {
541                                 curr_vol_left += left_change;
542                                 outb(curr_vol_left, portbase + 1);
543                         } else
544                             left_change = 0;
545                 }
546                 if (right_change) {
547                         if (curr_vol_right != dst_vol_right) {
548                                 curr_vol_right += right_change;
549
550                         /* during volume change, the right channel is crackling
551                          * somewhat more than the left channel, unfortunately.
552                          * This seems to be a hardware issue. */
553                                 outb(curr_vol_right, portbase + 0);
554                         } else
555                             right_change = 0;
556                 }
557                 if (delay)
558                         mdelay(delay);
559         } while ((left_change) || (right_change));
560         snd_azf3328_dbgcallleave();
561 }
562
563 /*
564  * general mixer element
565  */
566 struct azf3328_mixer_reg {
567         unsigned reg;
568         unsigned int lchan_shift, rchan_shift;
569         unsigned int mask;
570         unsigned int invert: 1;
571         unsigned int stereo: 1;
572         unsigned int enum_c: 4;
573 };
574
575 #define COMPOSE_MIXER_REG(reg,lchan_shift,rchan_shift,mask,invert,stereo,enum_c) \
576  ((reg) | (lchan_shift << 8) | (rchan_shift << 12) | \
577   (mask << 16) | \
578   (invert << 24) | \
579   (stereo << 25) | \
580   (enum_c << 26))
581
582 static void snd_azf3328_mixer_reg_decode(struct azf3328_mixer_reg *r, unsigned long val)
583 {
584         r->reg = val & 0xff;
585         r->lchan_shift = (val >> 8) & 0x0f;
586         r->rchan_shift = (val >> 12) & 0x0f;
587         r->mask = (val >> 16) & 0xff;
588         r->invert = (val >> 24) & 1;
589         r->stereo = (val >> 25) & 1;
590         r->enum_c = (val >> 26) & 0x0f;
591 }
592
593 /*
594  * mixer switches/volumes
595  */
596
597 #define AZF3328_MIXER_SWITCH(xname, reg, shift, invert) \
598 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
599   .info = snd_azf3328_info_mixer, \
600   .get = snd_azf3328_get_mixer, .put = snd_azf3328_put_mixer, \
601   .private_value = COMPOSE_MIXER_REG(reg, shift, 0, 0x1, invert, 0, 0), \
602 }
603
604 #define AZF3328_MIXER_VOL_STEREO(xname, reg, mask, invert) \
605 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
606   .info = snd_azf3328_info_mixer, \
607   .get = snd_azf3328_get_mixer, .put = snd_azf3328_put_mixer, \
608   .private_value = COMPOSE_MIXER_REG(reg, 8, 0, mask, invert, 1, 0), \
609 }
610
611 #define AZF3328_MIXER_VOL_MONO(xname, reg, mask, is_right_chan) \
612 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
613   .info = snd_azf3328_info_mixer, \
614   .get = snd_azf3328_get_mixer, .put = snd_azf3328_put_mixer, \
615   .private_value = COMPOSE_MIXER_REG(reg, is_right_chan ? 0 : 8, 0, mask, 1, 0, 0), \
616 }
617
618 #define AZF3328_MIXER_VOL_SPECIAL(xname, reg, mask, shift, invert) \
619 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
620   .info = snd_azf3328_info_mixer, \
621   .get = snd_azf3328_get_mixer, .put = snd_azf3328_put_mixer, \
622   .private_value = COMPOSE_MIXER_REG(reg, shift, 0, mask, invert, 0, 0), \
623 }
624
625 #define AZF3328_MIXER_ENUM(xname, reg, enum_c, shift) \
626 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
627   .info = snd_azf3328_info_mixer_enum, \
628   .get = snd_azf3328_get_mixer_enum, .put = snd_azf3328_put_mixer_enum, \
629   .private_value = COMPOSE_MIXER_REG(reg, shift, 0, 0, 0, 0, enum_c), \
630 }
631
632 static int
633 snd_azf3328_info_mixer(struct snd_kcontrol *kcontrol,
634                        struct snd_ctl_elem_info *uinfo)
635 {
636         struct azf3328_mixer_reg reg;
637
638         snd_azf3328_dbgcallenter();
639         snd_azf3328_mixer_reg_decode(&reg, kcontrol->private_value);
640         uinfo->type = reg.mask == 1 ?
641                 SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
642         uinfo->count = reg.stereo + 1;
643         uinfo->value.integer.min = 0;
644         uinfo->value.integer.max = reg.mask;
645         snd_azf3328_dbgcallleave();
646         return 0;
647 }
648
649 static int
650 snd_azf3328_get_mixer(struct snd_kcontrol *kcontrol,
651                       struct snd_ctl_elem_value *ucontrol)
652 {
653         struct snd_azf3328 *chip = snd_kcontrol_chip(kcontrol);
654         struct azf3328_mixer_reg reg;
655         u16 oreg, val;
656
657         snd_azf3328_dbgcallenter();
658         snd_azf3328_mixer_reg_decode(&reg, kcontrol->private_value);
659
660         oreg = snd_azf3328_mixer_inw(chip, reg.reg);
661         val = (oreg >> reg.lchan_shift) & reg.mask;
662         if (reg.invert)
663                 val = reg.mask - val;
664         ucontrol->value.integer.value[0] = val;
665         if (reg.stereo) {
666                 val = (oreg >> reg.rchan_shift) & reg.mask;
667                 if (reg.invert)
668                         val = reg.mask - val;
669                 ucontrol->value.integer.value[1] = val;
670         }
671         snd_azf3328_dbgmixer("get: %02x is %04x -> vol %02lx|%02lx "
672                              "(shift %02d|%02d, mask %02x, inv. %d, stereo %d)\n",
673                 reg.reg, oreg,
674                 ucontrol->value.integer.value[0], ucontrol->value.integer.value[1],
675                 reg.lchan_shift, reg.rchan_shift, reg.mask, reg.invert, reg.stereo);
676         snd_azf3328_dbgcallleave();
677         return 0;
678 }
679
680 static int
681 snd_azf3328_put_mixer(struct snd_kcontrol *kcontrol,
682                       struct snd_ctl_elem_value *ucontrol)
683 {
684         struct snd_azf3328 *chip = snd_kcontrol_chip(kcontrol);
685         struct azf3328_mixer_reg reg;
686         u16 oreg, nreg, val;
687
688         snd_azf3328_dbgcallenter();
689         snd_azf3328_mixer_reg_decode(&reg, kcontrol->private_value);
690         oreg = snd_azf3328_mixer_inw(chip, reg.reg);
691         val = ucontrol->value.integer.value[0] & reg.mask;
692         if (reg.invert)
693                 val = reg.mask - val;
694         nreg = oreg & ~(reg.mask << reg.lchan_shift);
695         nreg |= (val << reg.lchan_shift);
696         if (reg.stereo) {
697                 val = ucontrol->value.integer.value[1] & reg.mask;
698                 if (reg.invert)
699                         val = reg.mask - val;
700                 nreg &= ~(reg.mask << reg.rchan_shift);
701                 nreg |= (val << reg.rchan_shift);
702         }
703         if (reg.mask >= 0x07) /* it's a volume control, so better take care */
704                 snd_azf3328_mixer_write_volume_gradually(
705                         chip, reg.reg, nreg >> 8, nreg & 0xff,
706                         /* just set both channels, doesn't matter */
707                         SET_CHAN_LEFT|SET_CHAN_RIGHT,
708                         0);
709         else
710                 snd_azf3328_mixer_outw(chip, reg.reg, nreg);
711
712         snd_azf3328_dbgmixer("put: %02x to %02lx|%02lx, "
713                              "oreg %04x; shift %02d|%02d -> nreg %04x; after: %04x\n",
714                 reg.reg, ucontrol->value.integer.value[0], ucontrol->value.integer.value[1],
715                 oreg, reg.lchan_shift, reg.rchan_shift,
716                 nreg, snd_azf3328_mixer_inw(chip, reg.reg));
717         snd_azf3328_dbgcallleave();
718         return (nreg != oreg);
719 }
720
721 static int
722 snd_azf3328_info_mixer_enum(struct snd_kcontrol *kcontrol,
723                             struct snd_ctl_elem_info *uinfo)
724 {
725         static const char * const texts1[] = {
726                 "Mic1", "Mic2"
727         };
728         static const char * const texts2[] = {
729                 "Mix", "Mic"
730         };
731         static const char * const texts3[] = {
732                 "Mic", "CD", "Video", "Aux",
733                 "Line", "Mix", "Mix Mono", "Phone"
734         };
735         static const char * const texts4[] = {
736                 "pre 3D", "post 3D"
737         };
738         struct azf3328_mixer_reg reg;
739         const char * const *p = NULL;
740
741         snd_azf3328_mixer_reg_decode(&reg, kcontrol->private_value);
742         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
743         uinfo->count = (reg.reg == IDX_MIXER_REC_SELECT) ? 2 : 1;
744         uinfo->value.enumerated.items = reg.enum_c;
745         if (uinfo->value.enumerated.item > reg.enum_c - 1U)
746                 uinfo->value.enumerated.item = reg.enum_c - 1U;
747         if (reg.reg == IDX_MIXER_ADVCTL2) {
748                 switch(reg.lchan_shift) {
749                 case 8: /* modem out sel */
750                         p = texts1;
751                         break;
752                 case 9: /* mono sel source */
753                         p = texts2;
754                         break;
755                 case 15: /* PCM Out Path */
756                         p = texts4;
757                         break;
758                 }
759         } else
760         if (reg.reg == IDX_MIXER_REC_SELECT)
761                 p = texts3;
762
763         strcpy(uinfo->value.enumerated.name, p[uinfo->value.enumerated.item]);
764         return 0;
765 }
766
767 static int
768 snd_azf3328_get_mixer_enum(struct snd_kcontrol *kcontrol,
769                            struct snd_ctl_elem_value *ucontrol)
770 {
771         struct snd_azf3328 *chip = snd_kcontrol_chip(kcontrol);
772         struct azf3328_mixer_reg reg;
773         unsigned short val;
774
775         snd_azf3328_mixer_reg_decode(&reg, kcontrol->private_value);
776         val = snd_azf3328_mixer_inw(chip, reg.reg);
777         if (reg.reg == IDX_MIXER_REC_SELECT) {
778                 ucontrol->value.enumerated.item[0] = (val >> 8) & (reg.enum_c - 1);
779                 ucontrol->value.enumerated.item[1] = (val >> 0) & (reg.enum_c - 1);
780         } else
781                 ucontrol->value.enumerated.item[0] = (val >> reg.lchan_shift) & (reg.enum_c - 1);
782
783         snd_azf3328_dbgmixer("get_enum: %02x is %04x -> %d|%d (shift %02d, enum_c %d)\n",
784                 reg.reg, val, ucontrol->value.enumerated.item[0], ucontrol->value.enumerated.item[1],
785                 reg.lchan_shift, reg.enum_c);
786         return 0;
787 }
788
789 static int
790 snd_azf3328_put_mixer_enum(struct snd_kcontrol *kcontrol,
791                            struct snd_ctl_elem_value *ucontrol)
792 {
793         struct snd_azf3328 *chip = snd_kcontrol_chip(kcontrol);
794         struct azf3328_mixer_reg reg;
795         u16 oreg, nreg, val;
796
797         snd_azf3328_mixer_reg_decode(&reg, kcontrol->private_value);
798         oreg = snd_azf3328_mixer_inw(chip, reg.reg);
799         val = oreg;
800         if (reg.reg == IDX_MIXER_REC_SELECT) {
801                 if (ucontrol->value.enumerated.item[0] > reg.enum_c - 1U ||
802                 ucontrol->value.enumerated.item[1] > reg.enum_c - 1U)
803                         return -EINVAL;
804                 val = (ucontrol->value.enumerated.item[0] << 8) |
805                       (ucontrol->value.enumerated.item[1] << 0);
806         } else {
807                 if (ucontrol->value.enumerated.item[0] > reg.enum_c - 1U)
808                         return -EINVAL;
809                 val &= ~((reg.enum_c - 1) << reg.lchan_shift);
810                 val |= (ucontrol->value.enumerated.item[0] << reg.lchan_shift);
811         }
812         snd_azf3328_mixer_outw(chip, reg.reg, val);
813         nreg = val;
814
815         snd_azf3328_dbgmixer("put_enum: %02x to %04x, oreg %04x\n", reg.reg, val, oreg);
816         return (nreg != oreg);
817 }
818
819 static struct snd_kcontrol_new snd_azf3328_mixer_controls[] __devinitdata = {
820         AZF3328_MIXER_SWITCH("Master Playback Switch", IDX_MIXER_PLAY_MASTER, 15, 1),
821         AZF3328_MIXER_VOL_STEREO("Master Playback Volume", IDX_MIXER_PLAY_MASTER, 0x1f, 1),
822         AZF3328_MIXER_SWITCH("PCM Playback Switch", IDX_MIXER_WAVEOUT, 15, 1),
823         AZF3328_MIXER_VOL_STEREO("PCM Playback Volume",
824                                         IDX_MIXER_WAVEOUT, 0x1f, 1),
825         AZF3328_MIXER_SWITCH("PCM 3D Bypass Playback Switch",
826                                         IDX_MIXER_ADVCTL2, 7, 1),
827         AZF3328_MIXER_SWITCH("FM Playback Switch", IDX_MIXER_FMSYNTH, 15, 1),
828         AZF3328_MIXER_VOL_STEREO("FM Playback Volume", IDX_MIXER_FMSYNTH, 0x1f, 1),
829         AZF3328_MIXER_SWITCH("CD Playback Switch", IDX_MIXER_CDAUDIO, 15, 1),
830         AZF3328_MIXER_VOL_STEREO("CD Playback Volume", IDX_MIXER_CDAUDIO, 0x1f, 1),
831         AZF3328_MIXER_SWITCH("Capture Switch", IDX_MIXER_REC_VOLUME, 15, 1),
832         AZF3328_MIXER_VOL_STEREO("Capture Volume", IDX_MIXER_REC_VOLUME, 0x0f, 0),
833         AZF3328_MIXER_ENUM("Capture Source", IDX_MIXER_REC_SELECT, 8, 0),
834         AZF3328_MIXER_SWITCH("Mic Playback Switch", IDX_MIXER_MIC, 15, 1),
835         AZF3328_MIXER_VOL_MONO("Mic Playback Volume", IDX_MIXER_MIC, 0x1f, 1),
836         AZF3328_MIXER_SWITCH("Mic Boost (+20dB)", IDX_MIXER_MIC, 6, 0),
837         AZF3328_MIXER_SWITCH("Line Playback Switch", IDX_MIXER_LINEIN, 15, 1),
838         AZF3328_MIXER_VOL_STEREO("Line Playback Volume", IDX_MIXER_LINEIN, 0x1f, 1),
839         AZF3328_MIXER_SWITCH("Beep Playback Switch", IDX_MIXER_PCBEEP, 15, 1),
840         AZF3328_MIXER_VOL_SPECIAL("Beep Playback Volume", IDX_MIXER_PCBEEP, 0x0f, 1, 1),
841         AZF3328_MIXER_SWITCH("Video Playback Switch", IDX_MIXER_VIDEO, 15, 1),
842         AZF3328_MIXER_VOL_STEREO("Video Playback Volume", IDX_MIXER_VIDEO, 0x1f, 1),
843         AZF3328_MIXER_SWITCH("Aux Playback Switch", IDX_MIXER_AUX, 15, 1),
844         AZF3328_MIXER_VOL_STEREO("Aux Playback Volume", IDX_MIXER_AUX, 0x1f, 1),
845         AZF3328_MIXER_SWITCH("Modem Playback Switch", IDX_MIXER_MODEMOUT, 15, 1),
846         AZF3328_MIXER_VOL_MONO("Modem Playback Volume", IDX_MIXER_MODEMOUT, 0x1f, 1),
847         AZF3328_MIXER_SWITCH("Modem Capture Switch", IDX_MIXER_MODEMIN, 15, 1),
848         AZF3328_MIXER_VOL_MONO("Modem Capture Volume", IDX_MIXER_MODEMIN, 0x1f, 1),
849         AZF3328_MIXER_ENUM("Mic Select", IDX_MIXER_ADVCTL2, 2, 8),
850         AZF3328_MIXER_ENUM("Mono Output Select", IDX_MIXER_ADVCTL2, 2, 9),
851         AZF3328_MIXER_ENUM("PCM Output Route", IDX_MIXER_ADVCTL2, 2, 15), /* PCM Out Path, place in front since it controls *both* 3D and Bass/Treble! */
852         AZF3328_MIXER_VOL_SPECIAL("Tone Control - Treble", IDX_MIXER_BASSTREBLE, 0x07, 1, 0),
853         AZF3328_MIXER_VOL_SPECIAL("Tone Control - Bass", IDX_MIXER_BASSTREBLE, 0x07, 9, 0),
854         AZF3328_MIXER_SWITCH("3D Control - Switch", IDX_MIXER_ADVCTL2, 13, 0),
855         AZF3328_MIXER_VOL_SPECIAL("3D Control - Width", IDX_MIXER_ADVCTL1, 0x07, 1, 0), /* "3D Width" */
856         AZF3328_MIXER_VOL_SPECIAL("3D Control - Depth", IDX_MIXER_ADVCTL1, 0x03, 8, 0), /* "Hifi 3D" */
857 #if MIXER_TESTING
858         AZF3328_MIXER_SWITCH("0", IDX_MIXER_ADVCTL2, 0, 0),
859         AZF3328_MIXER_SWITCH("1", IDX_MIXER_ADVCTL2, 1, 0),
860         AZF3328_MIXER_SWITCH("2", IDX_MIXER_ADVCTL2, 2, 0),
861         AZF3328_MIXER_SWITCH("3", IDX_MIXER_ADVCTL2, 3, 0),
862         AZF3328_MIXER_SWITCH("4", IDX_MIXER_ADVCTL2, 4, 0),
863         AZF3328_MIXER_SWITCH("5", IDX_MIXER_ADVCTL2, 5, 0),
864         AZF3328_MIXER_SWITCH("6", IDX_MIXER_ADVCTL2, 6, 0),
865         AZF3328_MIXER_SWITCH("7", IDX_MIXER_ADVCTL2, 7, 0),
866         AZF3328_MIXER_SWITCH("8", IDX_MIXER_ADVCTL2, 8, 0),
867         AZF3328_MIXER_SWITCH("9", IDX_MIXER_ADVCTL2, 9, 0),
868         AZF3328_MIXER_SWITCH("10", IDX_MIXER_ADVCTL2, 10, 0),
869         AZF3328_MIXER_SWITCH("11", IDX_MIXER_ADVCTL2, 11, 0),
870         AZF3328_MIXER_SWITCH("12", IDX_MIXER_ADVCTL2, 12, 0),
871         AZF3328_MIXER_SWITCH("13", IDX_MIXER_ADVCTL2, 13, 0),
872         AZF3328_MIXER_SWITCH("14", IDX_MIXER_ADVCTL2, 14, 0),
873         AZF3328_MIXER_SWITCH("15", IDX_MIXER_ADVCTL2, 15, 0),
874 #endif
875 };
876
877 static u16 __devinitdata snd_azf3328_init_values[][2] = {
878         { IDX_MIXER_PLAY_MASTER,        MIXER_MUTE_MASK|0x1f1f },
879         { IDX_MIXER_MODEMOUT,           MIXER_MUTE_MASK|0x1f1f },
880         { IDX_MIXER_BASSTREBLE,         0x0000 },
881         { IDX_MIXER_PCBEEP,             MIXER_MUTE_MASK|0x1f1f },
882         { IDX_MIXER_MODEMIN,            MIXER_MUTE_MASK|0x1f1f },
883         { IDX_MIXER_MIC,                MIXER_MUTE_MASK|0x001f },
884         { IDX_MIXER_LINEIN,             MIXER_MUTE_MASK|0x1f1f },
885         { IDX_MIXER_CDAUDIO,            MIXER_MUTE_MASK|0x1f1f },
886         { IDX_MIXER_VIDEO,              MIXER_MUTE_MASK|0x1f1f },
887         { IDX_MIXER_AUX,                MIXER_MUTE_MASK|0x1f1f },
888         { IDX_MIXER_WAVEOUT,            MIXER_MUTE_MASK|0x1f1f },
889         { IDX_MIXER_FMSYNTH,            MIXER_MUTE_MASK|0x1f1f },
890         { IDX_MIXER_REC_VOLUME,         MIXER_MUTE_MASK|0x0707 },
891 };
892
893 static int __devinit
894 snd_azf3328_mixer_new(struct snd_azf3328 *chip)
895 {
896         struct snd_card *card;
897         const struct snd_kcontrol_new *sw;
898         unsigned int idx;
899         int err;
900
901         snd_azf3328_dbgcallenter();
902         if (snd_BUG_ON(!chip || !chip->card))
903                 return -EINVAL;
904
905         card = chip->card;
906
907         /* mixer reset */
908         snd_azf3328_mixer_outw(chip, IDX_MIXER_RESET, 0x0000);
909
910         /* mute and zero volume channels */
911         for (idx = 0; idx < ARRAY_SIZE(snd_azf3328_init_values); ++idx) {
912                 snd_azf3328_mixer_outw(chip,
913                         snd_azf3328_init_values[idx][0],
914                         snd_azf3328_init_values[idx][1]);
915         }
916
917         /* add mixer controls */
918         sw = snd_azf3328_mixer_controls;
919         for (idx = 0; idx < ARRAY_SIZE(snd_azf3328_mixer_controls);
920                         ++idx, ++sw) {
921                 if ((err = snd_ctl_add(chip->card, snd_ctl_new1(sw, chip))) < 0)
922                         return err;
923         }
924         snd_component_add(card, "AZF3328 mixer");
925         strcpy(card->mixername, "AZF3328 mixer");
926
927         snd_azf3328_dbgcallleave();
928         return 0;
929 }
930
931 static int
932 snd_azf3328_hw_params(struct snd_pcm_substream *substream,
933                                  struct snd_pcm_hw_params *hw_params)
934 {
935         int res;
936         snd_azf3328_dbgcallenter();
937         res = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
938         snd_azf3328_dbgcallleave();
939         return res;
940 }
941
942 static int
943 snd_azf3328_hw_free(struct snd_pcm_substream *substream)
944 {
945         snd_azf3328_dbgcallenter();
946         snd_pcm_lib_free_pages(substream);
947         snd_azf3328_dbgcallleave();
948         return 0;
949 }
950
951 static void
952 snd_azf3328_codec_setfmt(struct snd_azf3328 *chip,
953                                enum snd_azf3328_codec_type codec_type,
954                                enum azf_freq_t bitrate,
955                                unsigned int format_width,
956                                unsigned int channels
957 )
958 {
959         unsigned long flags;
960         const struct snd_azf3328_codec_data *codec = &chip->codecs[codec_type];
961         u16 val = 0xff00;
962         u8 freq = 0;
963
964         snd_azf3328_dbgcallenter();
965         switch (bitrate) {
966 #define AZF_FMT_XLATE(in_freq, out_bits) \
967         do { \
968                 case AZF_FREQ_ ## in_freq: \
969                         freq = SOUNDFORMAT_FREQ_ ## out_bits; \
970                         break; \
971         } while (0);
972         AZF_FMT_XLATE(4000, SUSPECTED_4000)
973         AZF_FMT_XLATE(4800, SUSPECTED_4800)
974         /* the AZF3328 names it "5510" for some strange reason: */
975         AZF_FMT_XLATE(5512, 5510)
976         AZF_FMT_XLATE(6620, 6620)
977         AZF_FMT_XLATE(8000, 8000)
978         AZF_FMT_XLATE(9600, 9600)
979         AZF_FMT_XLATE(11025, 11025)
980         AZF_FMT_XLATE(13240, SUSPECTED_13240)
981         AZF_FMT_XLATE(16000, 16000)
982         AZF_FMT_XLATE(22050, 22050)
983         AZF_FMT_XLATE(32000, 32000)
984         default:
985                 snd_printk(KERN_WARNING "unknown bitrate %d, assuming 44.1kHz!\n", bitrate);
986                 /* fall-through */
987         AZF_FMT_XLATE(44100, 44100)
988         AZF_FMT_XLATE(48000, 48000)
989         AZF_FMT_XLATE(66200, SUSPECTED_66200)
990 #undef AZF_FMT_XLATE
991         }
992         /* val = 0xff07; 3m27.993s (65301Hz; -> 64000Hz???) hmm, 66120, 65967, 66123 */
993         /* val = 0xff09; 17m15.098s (13123,478Hz; -> 12000Hz???) hmm, 13237.2Hz? */
994         /* val = 0xff0a; 47m30.599s (4764,891Hz; -> 4800Hz???) yup, 4803Hz */
995         /* val = 0xff0c; 57m0.510s (4010,263Hz; -> 4000Hz???) yup, 4003Hz */
996         /* val = 0xff05; 5m11.556s (... -> 44100Hz) */
997         /* val = 0xff03; 10m21.529s (21872,463Hz; -> 22050Hz???) */
998         /* val = 0xff0f; 20m41.883s (10937,993Hz; -> 11025Hz???) */
999         /* val = 0xff0d; 41m23.135s (5523,600Hz; -> 5512Hz???) */
1000         /* val = 0xff0e; 28m30.777s (8017Hz; -> 8000Hz???) */
1001
1002         val |= freq;
1003
1004         if (channels == 2)
1005                 val |= SOUNDFORMAT_FLAG_2CHANNELS;
1006
1007         if (format_width == 16)
1008                 val |= SOUNDFORMAT_FLAG_16BIT;
1009
1010         spin_lock_irqsave(&chip->reg_lock, flags);
1011
1012         /* set bitrate/format */
1013         snd_azf3328_codec_outw(codec, IDX_IO_CODEC_SOUNDFORMAT, val);
1014
1015         /* changing the bitrate/format settings switches off the
1016          * audio output with an annoying click in case of 8/16bit format change
1017          * (maybe shutting down DAC/ADC?), thus immediately
1018          * do some tweaking to reenable it and get rid of the clicking
1019          * (FIXME: yes, it works, but what exactly am I doing here?? :)
1020          * FIXME: does this have some side effects for full-duplex
1021          * or other dramatic side effects? */
1022         /* do it for non-capture codecs only */
1023         if (codec_type == AZF_CODEC_PLAYBACK)
1024                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS,
1025                         snd_azf3328_codec_inw(codec, IDX_IO_CODEC_DMA_FLAGS) |
1026                         DMA_RUN_SOMETHING1 |
1027                         DMA_RUN_SOMETHING2 |
1028                         SOMETHING_ALMOST_ALWAYS_SET |
1029                         DMA_EPILOGUE_SOMETHING |
1030                         DMA_SOMETHING_ELSE
1031                 );
1032
1033         spin_unlock_irqrestore(&chip->reg_lock, flags);
1034         snd_azf3328_dbgcallleave();
1035 }
1036
1037 static inline void
1038 snd_azf3328_codec_setfmt_lowpower(struct snd_azf3328 *chip,
1039                             enum snd_azf3328_codec_type codec_type
1040 )
1041 {
1042         /* choose lowest frequency for low power consumption.
1043          * While this will cause louder noise due to rather coarse frequency,
1044          * it should never matter since output should always
1045          * get disabled properly when idle anyway. */
1046         snd_azf3328_codec_setfmt(chip, codec_type, AZF_FREQ_4000, 8, 1);
1047 }
1048
1049 static void
1050 snd_azf3328_ctrl_reg_6AH_update(struct snd_azf3328 *chip,
1051                                         unsigned bitmask,
1052                                         bool enable
1053 )
1054 {
1055         bool do_mask = !enable;
1056         if (do_mask)
1057                 chip->shadow_reg_ctrl_6AH |= bitmask;
1058         else
1059                 chip->shadow_reg_ctrl_6AH &= ~bitmask;
1060         snd_azf3328_dbgcodec("6AH_update mask 0x%04x do_mask %d: val 0x%04x\n",
1061                         bitmask, do_mask, chip->shadow_reg_ctrl_6AH);
1062         snd_azf3328_ctrl_outw(chip, IDX_IO_6AH, chip->shadow_reg_ctrl_6AH);
1063 }
1064
1065 static inline void
1066 snd_azf3328_ctrl_enable_codecs(struct snd_azf3328 *chip, bool enable)
1067 {
1068         snd_azf3328_dbgcodec("codec_enable %d\n", enable);
1069         /* no idea what exactly is being done here, but I strongly assume it's
1070          * PM related */
1071         snd_azf3328_ctrl_reg_6AH_update(
1072                 chip, IO_6A_PAUSE_PLAYBACK_BIT8, enable
1073         );
1074 }
1075
1076 static void
1077 snd_azf3328_ctrl_codec_activity(struct snd_azf3328 *chip,
1078                                 enum snd_azf3328_codec_type codec_type,
1079                                 bool enable
1080 )
1081 {
1082         struct snd_azf3328_codec_data *codec = &chip->codecs[codec_type];
1083         bool need_change = (codec->running != enable);
1084
1085         snd_azf3328_dbgcodec(
1086                 "codec_activity: %s codec, enable %d, need_change %d\n",
1087                                 codec->name, enable, need_change
1088         );
1089         if (need_change) {
1090                 static const struct {
1091                         enum snd_azf3328_codec_type other1;
1092                         enum snd_azf3328_codec_type other2;
1093                 } peer_codecs[3] =
1094                         { { AZF_CODEC_CAPTURE, AZF_CODEC_I2S_OUT },
1095                           { AZF_CODEC_PLAYBACK, AZF_CODEC_I2S_OUT },
1096                           { AZF_CODEC_PLAYBACK, AZF_CODEC_CAPTURE } };
1097                 bool call_function;
1098
1099                 if (enable)
1100                         /* if enable codec, call enable_codecs func
1101                            to enable codec supply... */
1102                         call_function = 1;
1103                 else {
1104                         /* ...otherwise call enable_codecs func
1105                            (which globally shuts down operation of codecs)
1106                            only in case the other codecs are currently
1107                            not active either! */
1108                         call_function =
1109                                 ((!chip->codecs[peer_codecs[codec_type].other1]
1110                                         .running)
1111                              &&  (!chip->codecs[peer_codecs[codec_type].other2]
1112                                         .running));
1113                  }
1114                  if (call_function)
1115                         snd_azf3328_ctrl_enable_codecs(chip, enable);
1116
1117                 /* ...and adjust clock, too
1118                  * (reduce noise and power consumption) */
1119                 if (!enable)
1120                         snd_azf3328_codec_setfmt_lowpower(
1121                                 chip,
1122                                 codec_type
1123                         );
1124                 codec->running = enable;
1125         }
1126 }
1127
1128 static void
1129 snd_azf3328_codec_setdmaa(struct snd_azf3328 *chip,
1130                                 enum snd_azf3328_codec_type codec_type,
1131                                 unsigned long addr,
1132                                 unsigned int count,
1133                                 unsigned int size
1134 )
1135 {
1136         const struct snd_azf3328_codec_data *codec = &chip->codecs[codec_type];
1137         snd_azf3328_dbgcallenter();
1138         if (!codec->running) {
1139                 /* AZF3328 uses a two buffer pointer DMA transfer approach */
1140
1141                 unsigned long flags, addr_area2;
1142
1143                 /* width 32bit (prevent overflow): */
1144                 u32 count_areas, lengths;
1145
1146                 count_areas = size/2;
1147                 addr_area2 = addr+count_areas;
1148                 snd_azf3328_dbgcodec("setdma: buffers %08lx[%u] / %08lx[%u]\n",
1149                                 addr, count_areas, addr_area2, count_areas);
1150
1151                 count_areas--; /* max. index */
1152
1153                 /* build combined I/O buffer length word */
1154                 lengths = (count_areas << 16) | (count_areas);
1155                 spin_lock_irqsave(&chip->reg_lock, flags);
1156                 snd_azf3328_codec_outl(codec, IDX_IO_CODEC_DMA_START_1, addr);
1157                 snd_azf3328_codec_outl(codec, IDX_IO_CODEC_DMA_START_2,
1158                                                                 addr_area2);
1159                 snd_azf3328_codec_outl(codec, IDX_IO_CODEC_DMA_LENGTHS,
1160                                                                 lengths);
1161                 spin_unlock_irqrestore(&chip->reg_lock, flags);
1162         }
1163         snd_azf3328_dbgcallleave();
1164 }
1165
1166 static int
1167 snd_azf3328_codec_prepare(struct snd_pcm_substream *substream)
1168 {
1169         struct snd_pcm_runtime *runtime = substream->runtime;
1170         struct snd_azf3328_codec *codec = runtime->private_data;
1171 #if 0
1172         unsigned int size = snd_pcm_lib_buffer_bytes(substream);
1173         unsigned int count = snd_pcm_lib_period_bytes(substream);
1174 #endif
1175
1176         snd_azf3328_dbgcallenter();
1177
1178         codec->dma_base = runtime->dma_addr;
1179
1180 #if 0
1181         snd_azf3328_codec_setfmt(chip, AZF_CODEC_...,
1182                 runtime->rate,
1183                 snd_pcm_format_width(runtime->format),
1184                 runtime->channels);
1185         snd_azf3328_codec_setdmaa(chip, AZF_CODEC_...,
1186                                         runtime->dma_addr, count, size);
1187 #endif
1188         snd_azf3328_dbgcallleave();
1189         return 0;
1190 }
1191
1192 static int
1193 snd_azf3328_codec_trigger(enum snd_azf3328_codec_type codec_type,
1194                         struct snd_pcm_substream *substream, int cmd)
1195 {
1196         struct snd_azf3328 *chip = snd_pcm_substream_chip(substream);
1197         const struct snd_azf3328_codec_data *codec = &chip->codecs[codec_type];
1198         struct snd_pcm_runtime *runtime = substream->runtime;
1199         int result = 0;
1200         u16 flags1;
1201         bool previously_muted = 0;
1202         bool is_playback_codec = (AZF_CODEC_PLAYBACK == codec_type);
1203
1204         snd_azf3328_dbgcalls("snd_azf3328_codec_trigger cmd %d\n", cmd);
1205
1206         switch (cmd) {
1207         case SNDRV_PCM_TRIGGER_START:
1208                 snd_azf3328_dbgcodec("START %s\n", codec->name);
1209
1210                 if (is_playback_codec) {
1211                         /* mute WaveOut (avoid clicking during setup) */
1212                         previously_muted =
1213                                 snd_azf3328_mixer_set_mute(
1214                                                 chip, IDX_MIXER_WAVEOUT, 1
1215                                 );
1216                 }
1217
1218                 snd_azf3328_codec_setfmt(chip, codec_type,
1219                         runtime->rate,
1220                         snd_pcm_format_width(runtime->format),
1221                         runtime->channels);
1222
1223                 spin_lock(&chip->reg_lock);
1224                 /* first, remember current value: */
1225                 flags1 = snd_azf3328_codec_inw(codec, IDX_IO_CODEC_DMA_FLAGS);
1226
1227                 /* stop transfer */
1228                 flags1 &= ~DMA_RESUME;
1229                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS, flags1);
1230
1231                 /* FIXME: clear interrupts or what??? */
1232                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_IRQTYPE, 0xffff);
1233                 spin_unlock(&chip->reg_lock);
1234
1235                 snd_azf3328_codec_setdmaa(chip, codec_type, runtime->dma_addr,
1236                         snd_pcm_lib_period_bytes(substream),
1237                         snd_pcm_lib_buffer_bytes(substream)
1238                 );
1239
1240                 spin_lock(&chip->reg_lock);
1241 #ifdef WIN9X
1242                 /* FIXME: enable playback/recording??? */
1243                 flags1 |= DMA_RUN_SOMETHING1 | DMA_RUN_SOMETHING2;
1244                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS, flags1);
1245
1246                 /* start transfer again */
1247                 /* FIXME: what is this value (0x0010)??? */
1248                 flags1 |= DMA_RESUME | DMA_EPILOGUE_SOMETHING;
1249                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS, flags1);
1250 #else /* NT4 */
1251                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS,
1252                         0x0000);
1253                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS,
1254                         DMA_RUN_SOMETHING1);
1255                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS,
1256                         DMA_RUN_SOMETHING1 |
1257                         DMA_RUN_SOMETHING2);
1258                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS,
1259                         DMA_RESUME |
1260                         SOMETHING_ALMOST_ALWAYS_SET |
1261                         DMA_EPILOGUE_SOMETHING |
1262                         DMA_SOMETHING_ELSE);
1263 #endif
1264                 spin_unlock(&chip->reg_lock);
1265                 snd_azf3328_ctrl_codec_activity(chip, codec_type, 1);
1266
1267                 if (is_playback_codec) {
1268                         /* now unmute WaveOut */
1269                         if (!previously_muted)
1270                                 snd_azf3328_mixer_set_mute(
1271                                                 chip, IDX_MIXER_WAVEOUT, 0
1272                                 );
1273                 }
1274
1275                 snd_azf3328_dbgcodec("STARTED %s\n", codec->name);
1276                 break;
1277         case SNDRV_PCM_TRIGGER_RESUME:
1278                 snd_azf3328_dbgcodec("RESUME %s\n", codec->name);
1279                 /* resume codec if we were active */
1280                 spin_lock(&chip->reg_lock);
1281                 if (codec->running)
1282                         snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS,
1283                                 snd_azf3328_codec_inw(
1284                                         codec, IDX_IO_CODEC_DMA_FLAGS
1285                                 ) | DMA_RESUME
1286                         );
1287                 spin_unlock(&chip->reg_lock);
1288                 break;
1289         case SNDRV_PCM_TRIGGER_STOP:
1290                 snd_azf3328_dbgcodec("STOP %s\n", codec->name);
1291
1292                 if (is_playback_codec) {
1293                         /* mute WaveOut (avoid clicking during setup) */
1294                         previously_muted =
1295                                 snd_azf3328_mixer_set_mute(
1296                                                 chip, IDX_MIXER_WAVEOUT, 1
1297                                 );
1298                 }
1299
1300                 spin_lock(&chip->reg_lock);
1301                 /* first, remember current value: */
1302                 flags1 = snd_azf3328_codec_inw(codec, IDX_IO_CODEC_DMA_FLAGS);
1303
1304                 /* stop transfer */
1305                 flags1 &= ~DMA_RESUME;
1306                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS, flags1);
1307
1308                 /* hmm, is this really required? we're resetting the same bit
1309                  * immediately thereafter... */
1310                 flags1 |= DMA_RUN_SOMETHING1;
1311                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS, flags1);
1312
1313                 flags1 &= ~DMA_RUN_SOMETHING1;
1314                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS, flags1);
1315                 spin_unlock(&chip->reg_lock);
1316                 snd_azf3328_ctrl_codec_activity(chip, codec_type, 0);
1317
1318                 if (is_playback_codec) {
1319                         /* now unmute WaveOut */
1320                         if (!previously_muted)
1321                                 snd_azf3328_mixer_set_mute(
1322                                                 chip, IDX_MIXER_WAVEOUT, 0
1323                                 );
1324                 }
1325
1326                 snd_azf3328_dbgcodec("STOPPED %s\n", codec->name);
1327                 break;
1328         case SNDRV_PCM_TRIGGER_SUSPEND:
1329                 snd_azf3328_dbgcodec("SUSPEND %s\n", codec->name);
1330                 /* make sure codec is stopped */
1331                 snd_azf3328_codec_outw(codec, IDX_IO_CODEC_DMA_FLAGS,
1332                         snd_azf3328_codec_inw(
1333                                 codec, IDX_IO_CODEC_DMA_FLAGS
1334                         ) & ~DMA_RESUME
1335                 );
1336                 break;
1337         case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
1338                 snd_printk(KERN_ERR "FIXME: SNDRV_PCM_TRIGGER_PAUSE_PUSH NIY!\n");
1339                 break;
1340         case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
1341                 snd_printk(KERN_ERR "FIXME: SNDRV_PCM_TRIGGER_PAUSE_RELEASE NIY!\n");
1342                 break;
1343         default:
1344                 snd_printk(KERN_ERR "FIXME: unknown trigger mode!\n");
1345                 return -EINVAL;
1346         }
1347
1348         snd_azf3328_dbgcallleave();
1349         return result;
1350 }
1351
1352 static int
1353 snd_azf3328_codec_playback_trigger(struct snd_pcm_substream *substream, int cmd)
1354 {
1355         return snd_azf3328_codec_trigger(AZF_CODEC_PLAYBACK, substream, cmd);
1356 }
1357
1358 static int
1359 snd_azf3328_codec_capture_trigger(struct snd_pcm_substream *substream, int cmd)
1360 {
1361         return snd_azf3328_codec_trigger(AZF_CODEC_CAPTURE, substream, cmd);
1362 }
1363
1364 static int
1365 snd_azf3328_codec_i2s_out_trigger(struct snd_pcm_substream *substream, int cmd)
1366 {
1367         return snd_azf3328_codec_trigger(AZF_CODEC_I2S_OUT, substream, cmd);
1368 }
1369
1370 static snd_pcm_uframes_t
1371 snd_azf3328_codec_pointer(struct snd_pcm_substream *substream,
1372                           enum snd_azf3328_codec_type codec_type
1373 )
1374 {
1375         const struct snd_azf3328 *chip = snd_pcm_substream_chip(substream);
1376         const struct snd_azf3328_codec_data *codec = &chip->codecs[codec_type];
1377         unsigned long result;
1378         snd_pcm_uframes_t frmres;
1379
1380         result = snd_azf3328_codec_inl(codec, IDX_IO_CODEC_DMA_CURRPOS);
1381
1382         /* calculate offset */
1383 #ifdef QUERY_HARDWARE
1384         result -= snd_azf3328_codec_inl(codec, IDX_IO_CODEC_DMA_START_1);
1385 #else
1386         result -= codec->dma_base;
1387 #endif
1388         frmres = bytes_to_frames( substream->runtime, result);
1389         snd_azf3328_dbgcodec("%08li %s @ 0x%8lx, frames %8ld\n",
1390                                 jiffies, codec->name, result, frmres);
1391         return frmres;
1392 }
1393
1394 static snd_pcm_uframes_t
1395 snd_azf3328_codec_playback_pointer(struct snd_pcm_substream *substream)
1396 {
1397         return snd_azf3328_codec_pointer(substream, AZF_CODEC_PLAYBACK);
1398 }
1399
1400 static snd_pcm_uframes_t
1401 snd_azf3328_codec_capture_pointer(struct snd_pcm_substream *substream)
1402 {
1403         return snd_azf3328_codec_pointer(substream, AZF_CODEC_CAPTURE);
1404 }
1405
1406 static snd_pcm_uframes_t
1407 snd_azf3328_codec_i2s_out_pointer(struct snd_pcm_substream *substream)
1408 {
1409         return snd_azf3328_codec_pointer(substream, AZF_CODEC_I2S_OUT);
1410 }
1411
1412 /******************************************************************/
1413
1414 #ifdef SUPPORT_GAMEPORT
1415 static inline void
1416 snd_azf3328_gameport_irq_enable(struct snd_azf3328 *chip,
1417                                 bool enable
1418 )
1419 {
1420         snd_azf3328_io_reg_setb(
1421                 chip->game_io+IDX_GAME_HWCONFIG,
1422                 GAME_HWCFG_IRQ_ENABLE,
1423                 enable
1424         );
1425 }
1426
1427 static inline void
1428 snd_azf3328_gameport_legacy_address_enable(struct snd_azf3328 *chip,
1429                                            bool enable
1430 )
1431 {
1432         snd_azf3328_io_reg_setb(
1433                 chip->game_io+IDX_GAME_HWCONFIG,
1434                 GAME_HWCFG_LEGACY_ADDRESS_ENABLE,
1435                 enable
1436         );
1437 }
1438
1439 static void
1440 snd_azf3328_gameport_set_counter_frequency(struct snd_azf3328 *chip,
1441                                            unsigned int freq_cfg
1442 )
1443 {
1444         snd_azf3328_io_reg_setb(
1445                 chip->game_io+IDX_GAME_HWCONFIG,
1446                 0x02,
1447                 (freq_cfg & 1) != 0
1448         );
1449         snd_azf3328_io_reg_setb(
1450                 chip->game_io+IDX_GAME_HWCONFIG,
1451                 0x04,
1452                 (freq_cfg & 2) != 0
1453         );
1454 }
1455
1456 static inline void
1457 snd_azf3328_gameport_axis_circuit_enable(struct snd_azf3328 *chip, bool enable)
1458 {
1459         snd_azf3328_ctrl_reg_6AH_update(
1460                 chip, IO_6A_SOMETHING2_GAMEPORT, enable
1461         );
1462 }
1463
1464 static inline void
1465 snd_azf3328_gameport_interrupt(struct snd_azf3328 *chip)
1466 {
1467         /*
1468          * skeleton handler only
1469          * (we do not want axis reading in interrupt handler - too much load!)
1470          */
1471         snd_azf3328_dbggame("gameport irq\n");
1472
1473          /* this should ACK the gameport IRQ properly, hopefully. */
1474         snd_azf3328_game_inw(chip, IDX_GAME_AXIS_VALUE);
1475 }
1476
1477 static int
1478 snd_azf3328_gameport_open(struct gameport *gameport, int mode)
1479 {
1480         struct snd_azf3328 *chip = gameport_get_port_data(gameport);
1481         int res;
1482
1483         snd_azf3328_dbggame("gameport_open, mode %d\n", mode);
1484         switch (mode) {
1485         case GAMEPORT_MODE_COOKED:
1486         case GAMEPORT_MODE_RAW:
1487                 res = 0;
1488                 break;
1489         default:
1490                 res = -1;
1491                 break;
1492         }
1493
1494         snd_azf3328_gameport_set_counter_frequency(chip,
1495                                 GAME_HWCFG_ADC_COUNTER_FREQ_STD);
1496         snd_azf3328_gameport_axis_circuit_enable(chip, (res == 0));
1497
1498         return res;
1499 }
1500
1501 static void
1502 snd_azf3328_gameport_close(struct gameport *gameport)
1503 {
1504         struct snd_azf3328 *chip = gameport_get_port_data(gameport);
1505
1506         snd_azf3328_dbggame("gameport_close\n");
1507         snd_azf3328_gameport_set_counter_frequency(chip,
1508                                 GAME_HWCFG_ADC_COUNTER_FREQ_1_200);
1509         snd_azf3328_gameport_axis_circuit_enable(chip, 0);
1510 }
1511
1512 static int
1513 snd_azf3328_gameport_cooked_read(struct gameport *gameport,
1514                                  int *axes,
1515                                  int *buttons
1516 )
1517 {
1518         struct snd_azf3328 *chip = gameport_get_port_data(gameport);
1519         int i;
1520         u8 val;
1521         unsigned long flags;
1522
1523         if (snd_BUG_ON(!chip))
1524                 return 0;
1525
1526         spin_lock_irqsave(&chip->reg_lock, flags);
1527         val = snd_azf3328_game_inb(chip, IDX_GAME_LEGACY_COMPATIBLE);
1528         *buttons = (~(val) >> 4) & 0xf;
1529
1530         /* ok, this one is a bit dirty: cooked_read is being polled by a timer,
1531          * thus we're atomic and cannot actively wait in here
1532          * (which would be useful for us since it probably would be better
1533          * to trigger a measurement in here, then wait a short amount of
1534          * time until it's finished, then read values of _this_ measurement).
1535          *
1536          * Thus we simply resort to reading values if they're available already
1537          * and trigger the next measurement.
1538          */
1539
1540         val = snd_azf3328_game_inb(chip, IDX_GAME_AXES_CONFIG);
1541         if (val & GAME_AXES_SAMPLING_READY) {
1542                 for (i = 0; i < ARRAY_SIZE(chip->axes); ++i) {
1543                         /* configure the axis to read */
1544                         val = (i << 4) | 0x0f;
1545                         snd_azf3328_game_outb(chip, IDX_GAME_AXES_CONFIG, val);
1546
1547                         chip->axes[i] = snd_azf3328_game_inw(
1548                                                 chip, IDX_GAME_AXIS_VALUE
1549                                         );
1550                 }
1551         }
1552
1553         /* trigger next sampling of axes, to be evaluated the next time we
1554          * enter this function */
1555
1556         /* for some very, very strange reason we cannot enable
1557          * Measurement Ready monitoring for all axes here,
1558          * at least not when only one joystick connected */
1559         val = 0x03; /* we're able to monitor axes 1 and 2 only */
1560         snd_azf3328_game_outb(chip, IDX_GAME_AXES_CONFIG, val);
1561
1562         snd_azf3328_game_outw(chip, IDX_GAME_AXIS_VALUE, 0xffff);
1563         spin_unlock_irqrestore(&chip->reg_lock, flags);
1564
1565         for (i = 0; i < ARRAY_SIZE(chip->axes); i++) {
1566                 axes[i] = chip->axes[i];
1567                 if (axes[i] == 0xffff)
1568                         axes[i] = -1;
1569         }
1570
1571         snd_azf3328_dbggame("cooked_read: axes %d %d %d %d buttons %d\n",
1572                 axes[0], axes[1], axes[2], axes[3], *buttons
1573         );
1574
1575         return 0;
1576 }
1577
1578 static int __devinit
1579 snd_azf3328_gameport(struct snd_azf3328 *chip, int dev)
1580 {
1581         struct gameport *gp;
1582
1583         chip->gameport = gp = gameport_allocate_port();
1584         if (!gp) {
1585                 printk(KERN_ERR "azt3328: cannot alloc memory for gameport\n");
1586                 return -ENOMEM;
1587         }
1588
1589         gameport_set_name(gp, "AZF3328 Gameport");
1590         gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci));
1591         gameport_set_dev_parent(gp, &chip->pci->dev);
1592         gp->io = chip->game_io;
1593         gameport_set_port_data(gp, chip);
1594
1595         gp->open = snd_azf3328_gameport_open;
1596         gp->close = snd_azf3328_gameport_close;
1597         gp->fuzz = 16; /* seems ok */
1598         gp->cooked_read = snd_azf3328_gameport_cooked_read;
1599
1600         /* DISABLE legacy address: we don't need it! */
1601         snd_azf3328_gameport_legacy_address_enable(chip, 0);
1602
1603         snd_azf3328_gameport_set_counter_frequency(chip,
1604                                 GAME_HWCFG_ADC_COUNTER_FREQ_1_200);
1605         snd_azf3328_gameport_axis_circuit_enable(chip, 0);
1606
1607         gameport_register_port(chip->gameport);
1608
1609         return 0;
1610 }
1611
1612 static void
1613 snd_azf3328_gameport_free(struct snd_azf3328 *chip)
1614 {
1615         if (chip->gameport) {
1616                 gameport_unregister_port(chip->gameport);
1617                 chip->gameport = NULL;
1618         }
1619         snd_azf3328_gameport_irq_enable(chip, 0);
1620 }
1621 #else
1622 static inline int
1623 snd_azf3328_gameport(struct snd_azf3328 *chip, int dev) { return -ENOSYS; }
1624 static inline void
1625 snd_azf3328_gameport_free(struct snd_azf3328 *chip) { }
1626 static inline void
1627 snd_azf3328_gameport_interrupt(struct snd_azf3328 *chip)
1628 {
1629         printk(KERN_WARNING "huh, game port IRQ occurred!?\n");
1630 }
1631 #endif /* SUPPORT_GAMEPORT */
1632
1633 /******************************************************************/
1634
1635 static inline void
1636 snd_azf3328_irq_log_unknown_type(u8 which)
1637 {
1638         snd_azf3328_dbgcodec(
1639         "azt3328: unknown IRQ type (%x) occurred, please report!\n",
1640                 which
1641         );
1642 }
1643
1644 static inline void
1645 snd_azf3328_codec_interrupt(struct snd_azf3328 *chip, u8 status)
1646 {
1647         u8 which;
1648         enum snd_azf3328_codec_type codec_type;
1649         const struct snd_azf3328_codec_data *codec;
1650
1651         for (codec_type = AZF_CODEC_PLAYBACK;
1652                  codec_type <= AZF_CODEC_I2S_OUT;
1653                          ++codec_type) {
1654
1655                 /* skip codec if there's no interrupt for it */
1656                 if (!(status & (1 << codec_type)))
1657                         continue;
1658
1659                 codec = &chip->codecs[codec_type];
1660
1661                 spin_lock(&chip->reg_lock);
1662                 which = snd_azf3328_codec_inb(codec, IDX_IO_CODEC_IRQTYPE);
1663                 /* ack all IRQ types immediately */
1664                 snd_azf3328_codec_outb(codec, IDX_IO_CODEC_IRQTYPE, which);
1665                 spin_unlock(&chip->reg_lock);
1666
1667                 if ((chip->pcm[codec_type]) && (codec->substream)) {
1668                         snd_pcm_period_elapsed(codec->substream);
1669                         snd_azf3328_dbgcodec("%s period done (#%x), @ %x\n",
1670                                 codec->name,
1671                                 which,
1672                                 snd_azf3328_codec_inl(
1673                                         codec, IDX_IO_CODEC_DMA_CURRPOS
1674                                 )
1675                         );
1676                 } else
1677                         printk(KERN_WARNING "azt3328: irq handler problem!\n");
1678                 if (which & IRQ_SOMETHING)
1679                         snd_azf3328_irq_log_unknown_type(which);
1680         }
1681 }
1682
1683 static irqreturn_t
1684 snd_azf3328_interrupt(int irq, void *dev_id)
1685 {
1686         struct snd_azf3328 *chip = dev_id;
1687         u8 status;
1688 #if DEBUG_CODEC
1689         static unsigned long irq_count;
1690 #endif
1691
1692         status = snd_azf3328_ctrl_inb(chip, IDX_IO_IRQSTATUS);
1693
1694         /* fast path out, to ease interrupt sharing */
1695         if (!(status &
1696                 (IRQ_PLAYBACK|IRQ_RECORDING|IRQ_I2S_OUT
1697                 |IRQ_GAMEPORT|IRQ_MPU401|IRQ_TIMER)
1698         ))
1699                 return IRQ_NONE; /* must be interrupt for another device */
1700
1701         snd_azf3328_dbgcodec(
1702                 "irq_count %ld! IDX_IO_IRQSTATUS %04x\n",
1703                         irq_count++ /* debug-only */,
1704                         status
1705         );
1706
1707         if (status & IRQ_TIMER) {
1708                 /* snd_azf3328_dbgcodec("timer %ld\n",
1709                         snd_azf3328_codec_inl(chip, IDX_IO_TIMER_VALUE)
1710                                 & TIMER_VALUE_MASK
1711                 ); */
1712                 if (chip->timer)
1713                         snd_timer_interrupt(chip->timer, chip->timer->sticks);
1714                 /* ACK timer */
1715                 spin_lock(&chip->reg_lock);
1716                 snd_azf3328_ctrl_outb(chip, IDX_IO_TIMER_VALUE + 3, 0x07);
1717                 spin_unlock(&chip->reg_lock);
1718                 snd_azf3328_dbgcodec("azt3328: timer IRQ\n");
1719         }
1720
1721         if (status & (IRQ_PLAYBACK|IRQ_RECORDING|IRQ_I2S_OUT))
1722                 snd_azf3328_codec_interrupt(chip, status);
1723
1724         if (status & IRQ_GAMEPORT)
1725                 snd_azf3328_gameport_interrupt(chip);
1726
1727         /* MPU401 has less critical IRQ requirements
1728          * than timer and playback/recording, right? */
1729         if (status & IRQ_MPU401) {
1730                 snd_mpu401_uart_interrupt(irq, chip->rmidi->private_data);
1731
1732                 /* hmm, do we have to ack the IRQ here somehow?
1733                  * If so, then I don't know how yet... */
1734                 snd_azf3328_dbgcodec("azt3328: MPU401 IRQ\n");
1735         }
1736         return IRQ_HANDLED;
1737 }
1738
1739 /*****************************************************************/
1740
1741 /* as long as we think we have identical snd_pcm_hardware parameters
1742    for playback, capture and i2s out, we can use the same physical struct
1743    since the struct is simply being copied into a member.
1744 */
1745 static const struct snd_pcm_hardware snd_azf3328_hardware =
1746 {
1747         /* FIXME!! Correct? */
1748         .info =                 SNDRV_PCM_INFO_MMAP |
1749                                 SNDRV_PCM_INFO_INTERLEAVED |
1750                                 SNDRV_PCM_INFO_MMAP_VALID,
1751         .formats =              SNDRV_PCM_FMTBIT_S8 |
1752                                 SNDRV_PCM_FMTBIT_U8 |
1753                                 SNDRV_PCM_FMTBIT_S16_LE |
1754                                 SNDRV_PCM_FMTBIT_U16_LE,
1755         .rates =                SNDRV_PCM_RATE_5512 |
1756                                 SNDRV_PCM_RATE_8000_48000 |
1757                                 SNDRV_PCM_RATE_KNOT,
1758         .rate_min =             AZF_FREQ_4000,
1759         .rate_max =             AZF_FREQ_66200,
1760         .channels_min =         1,
1761         .channels_max =         2,
1762         .buffer_bytes_max =     (64*1024),
1763         .period_bytes_min =     1024,
1764         .period_bytes_max =     (32*1024),
1765         /* We simply have two DMA areas (instead of a list of descriptors
1766            such as other cards); I believe that this is a fixed hardware
1767            attribute and there isn't much driver magic to be done to expand it.
1768            Thus indicate that we have at least and at most 2 periods. */
1769         .periods_min =          2,
1770         .periods_max =          2,
1771         /* FIXME: maybe that card actually has a FIFO?
1772          * Hmm, it seems newer revisions do have one, but we still don't know
1773          * its size... */
1774         .fifo_size =            0,
1775 };
1776
1777
1778 static unsigned int snd_azf3328_fixed_rates[] = {
1779         AZF_FREQ_4000,
1780         AZF_FREQ_4800,
1781         AZF_FREQ_5512,
1782         AZF_FREQ_6620,
1783         AZF_FREQ_8000,
1784         AZF_FREQ_9600,
1785         AZF_FREQ_11025,
1786         AZF_FREQ_13240,
1787         AZF_FREQ_16000,
1788         AZF_FREQ_22050,
1789         AZF_FREQ_32000,
1790         AZF_FREQ_44100,
1791         AZF_FREQ_48000,
1792         AZF_FREQ_66200
1793 };
1794
1795 static struct snd_pcm_hw_constraint_list snd_azf3328_hw_constraints_rates = {
1796         .count = ARRAY_SIZE(snd_azf3328_fixed_rates),
1797         .list = snd_azf3328_fixed_rates,
1798         .mask = 0,
1799 };
1800
1801 /*****************************************************************/
1802
1803 static int
1804 snd_azf3328_pcm_open(struct snd_pcm_substream *substream,
1805                      enum snd_azf3328_codec_type codec_type
1806 )
1807 {
1808         struct snd_azf3328 *chip = snd_pcm_substream_chip(substream);
1809         struct snd_pcm_runtime *runtime = substream->runtime;
1810
1811         snd_azf3328_dbgcallenter();
1812         chip->codecs[codec_type].substream = substream;
1813
1814         /* same parameters for all our codecs - at least we think so... */
1815         runtime->hw = snd_azf3328_hardware;
1816
1817         snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
1818                                    &snd_azf3328_hw_constraints_rates);
1819         snd_azf3328_dbgcallleave();
1820         return 0;
1821 }
1822
1823 static int
1824 snd_azf3328_playback_open(struct snd_pcm_substream *substream)
1825 {
1826         return snd_azf3328_pcm_open(substream, AZF_CODEC_PLAYBACK);
1827 }
1828
1829 static int
1830 snd_azf3328_capture_open(struct snd_pcm_substream *substream)
1831 {
1832         return snd_azf3328_pcm_open(substream, AZF_CODEC_CAPTURE);
1833 }
1834
1835 static int
1836 snd_azf3328_i2s_out_open(struct snd_pcm_substream *substream)
1837 {
1838         return snd_azf3328_pcm_open(substream, AZF_CODEC_I2S_OUT);
1839 }
1840
1841 static int
1842 snd_azf3328_pcm_close(struct snd_pcm_substream *substream,
1843                       enum snd_azf3328_codec_type codec_type
1844 )
1845 {
1846         struct snd_azf3328 *chip = snd_pcm_substream_chip(substream);
1847
1848         snd_azf3328_dbgcallenter();
1849         chip->codecs[codec_type].substream = NULL;
1850         snd_azf3328_dbgcallleave();
1851         return 0;
1852 }
1853
1854 static int
1855 snd_azf3328_playback_close(struct snd_pcm_substream *substream)
1856 {
1857         return snd_azf3328_pcm_close(substream, AZF_CODEC_PLAYBACK);
1858 }
1859
1860 static int
1861 snd_azf3328_capture_close(struct snd_pcm_substream *substream)
1862 {
1863         return snd_azf3328_pcm_close(substream, AZF_CODEC_CAPTURE);
1864 }
1865
1866 static int
1867 snd_azf3328_i2s_out_close(struct snd_pcm_substream *substream)
1868 {
1869         return snd_azf3328_pcm_close(substream, AZF_CODEC_I2S_OUT);
1870 }
1871
1872 /******************************************************************/
1873
1874 static struct snd_pcm_ops snd_azf3328_playback_ops = {
1875         .open =         snd_azf3328_playback_open,
1876         .close =        snd_azf3328_playback_close,
1877         .ioctl =        snd_pcm_lib_ioctl,
1878         .hw_params =    snd_azf3328_hw_params,
1879         .hw_free =      snd_azf3328_hw_free,
1880         .prepare =      snd_azf3328_codec_prepare,
1881         .trigger =      snd_azf3328_codec_playback_trigger,
1882         .pointer =      snd_azf3328_codec_playback_pointer
1883 };
1884
1885 static struct snd_pcm_ops snd_azf3328_capture_ops = {
1886         .open =         snd_azf3328_capture_open,
1887         .close =        snd_azf3328_capture_close,
1888         .ioctl =        snd_pcm_lib_ioctl,
1889         .hw_params =    snd_azf3328_hw_params,
1890         .hw_free =      snd_azf3328_hw_free,
1891         .prepare =      snd_azf3328_codec_prepare,
1892         .trigger =      snd_azf3328_codec_capture_trigger,
1893         .pointer =      snd_azf3328_codec_capture_pointer
1894 };
1895
1896 static struct snd_pcm_ops snd_azf3328_i2s_out_ops = {
1897         .open =         snd_azf3328_i2s_out_open,
1898         .close =        snd_azf3328_i2s_out_close,
1899         .ioctl =        snd_pcm_lib_ioctl,
1900         .hw_params =    snd_azf3328_hw_params,
1901         .hw_free =      snd_azf3328_hw_free,
1902         .prepare =      snd_azf3328_codec_prepare,
1903         .trigger =      snd_azf3328_codec_i2s_out_trigger,
1904         .pointer =      snd_azf3328_codec_i2s_out_pointer
1905 };
1906
1907 static int __devinit
1908 snd_azf3328_pcm(struct snd_azf3328 *chip)
1909 {
1910 enum { AZF_PCMDEV_STD, AZF_PCMDEV_I2S_OUT, NUM_AZF_PCMDEVS }; /* pcm devices */
1911
1912         struct snd_pcm *pcm;
1913         int err;
1914
1915         snd_azf3328_dbgcallenter();
1916
1917         err = snd_pcm_new(chip->card, "AZF3328 DSP", AZF_PCMDEV_STD,
1918                                                                 1, 1, &pcm);
1919         if (err < 0)
1920                 return err;
1921         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
1922                                                 &snd_azf3328_playback_ops);
1923         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
1924                                                 &snd_azf3328_capture_ops);
1925
1926         pcm->private_data = chip;
1927         pcm->info_flags = 0;
1928         strcpy(pcm->name, chip->card->shortname);
1929         /* same pcm object for playback/capture (see snd_pcm_new() above) */
1930         chip->pcm[AZF_CODEC_PLAYBACK] = pcm;
1931         chip->pcm[AZF_CODEC_CAPTURE] = pcm;
1932
1933         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
1934                                                 snd_dma_pci_data(chip->pci),
1935                                                         64*1024, 64*1024);
1936
1937         err = snd_pcm_new(chip->card, "AZF3328 I2S OUT", AZF_PCMDEV_I2S_OUT,
1938                                                                 1, 0, &pcm);
1939         if (err < 0)
1940                 return err;
1941         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
1942                                                 &snd_azf3328_i2s_out_ops);
1943
1944         pcm->private_data = chip;
1945         pcm->info_flags = 0;
1946         strcpy(pcm->name, chip->card->shortname);
1947         chip->pcm[AZF_CODEC_I2S_OUT] = pcm;
1948
1949         snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
1950                                                 snd_dma_pci_data(chip->pci),
1951                                                         64*1024, 64*1024);
1952
1953         snd_azf3328_dbgcallleave();
1954         return 0;
1955 }
1956
1957 /******************************************************************/
1958
1959 /*** NOTE: the physical timer resolution actually is 1024000 ticks per second
1960  *** (probably derived from main crystal via a divider of 24),
1961  *** but announcing those attributes to user-space would make programs
1962  *** configure the timer to a 1 tick value, resulting in an absolutely fatal
1963  *** timer IRQ storm.
1964  *** Thus I chose to announce a down-scaled virtual timer to the outside and
1965  *** calculate real timer countdown values internally.
1966  *** (the scale factor can be set via module parameter "seqtimer_scaling").
1967  ***/
1968
1969 static int
1970 snd_azf3328_timer_start(struct snd_timer *timer)
1971 {
1972         struct snd_azf3328 *chip;
1973         unsigned long flags;
1974         unsigned int delay;
1975
1976         snd_azf3328_dbgcallenter();
1977         chip = snd_timer_chip(timer);
1978         delay = ((timer->sticks * seqtimer_scaling) - 1) & TIMER_VALUE_MASK;
1979         if (delay < 49) {
1980                 /* uhoh, that's not good, since user-space won't know about
1981                  * this timing tweak
1982                  * (we need to do it to avoid a lockup, though) */
1983
1984                 snd_azf3328_dbgtimer("delay was too low (%d)!\n", delay);
1985                 delay = 49; /* minimum time is 49 ticks */
1986         }
1987         snd_azf3328_dbgtimer("setting timer countdown value %d\n", delay);
1988         delay |= TIMER_COUNTDOWN_ENABLE | TIMER_IRQ_ENABLE;
1989         spin_lock_irqsave(&chip->reg_lock, flags);
1990         snd_azf3328_ctrl_outl(chip, IDX_IO_TIMER_VALUE, delay);
1991         spin_unlock_irqrestore(&chip->reg_lock, flags);
1992         snd_azf3328_dbgcallleave();
1993         return 0;
1994 }
1995
1996 static int
1997 snd_azf3328_timer_stop(struct snd_timer *timer)
1998 {
1999         struct snd_azf3328 *chip;
2000         unsigned long flags;
2001
2002         snd_azf3328_dbgcallenter();
2003         chip = snd_timer_chip(timer);
2004         spin_lock_irqsave(&chip->reg_lock, flags);
2005         /* disable timer countdown and interrupt */
2006         /* Hmm, should we write TIMER_IRQ_ACK here?
2007            YES indeed, otherwise a rogue timer operation - which prompts
2008            ALSA(?) to call repeated stop() in vain, but NOT start() -
2009            will never end (value 0x03 is kept shown in control byte).
2010            Simply manually poking 0x04 _once_ immediately successfully stops
2011            the hardware/ALSA interrupt activity. */
2012         snd_azf3328_ctrl_outb(chip, IDX_IO_TIMER_VALUE + 3, 0x04);
2013         spin_unlock_irqrestore(&chip->reg_lock, flags);
2014         snd_azf3328_dbgcallleave();
2015         return 0;
2016 }
2017
2018
2019 static int
2020 snd_azf3328_timer_precise_resolution(struct snd_timer *timer,
2021                                                unsigned long *num, unsigned long *den)
2022 {
2023         snd_azf3328_dbgcallenter();
2024         *num = 1;
2025         *den = 1024000 / seqtimer_scaling;
2026         snd_azf3328_dbgcallleave();
2027         return 0;
2028 }
2029
2030 static struct snd_timer_hardware snd_azf3328_timer_hw = {
2031         .flags = SNDRV_TIMER_HW_AUTO,
2032         .resolution = 977, /* 1000000/1024000 = 0.9765625us */
2033         .ticks = 1024000, /* max tick count, defined by the value register; actually it's not 1024000, but 1048576, but we don't care */
2034         .start = snd_azf3328_timer_start,
2035         .stop = snd_azf3328_timer_stop,
2036         .precise_resolution = snd_azf3328_timer_precise_resolution,
2037 };
2038
2039 static int __devinit
2040 snd_azf3328_timer(struct snd_azf3328 *chip, int device)
2041 {
2042         struct snd_timer *timer = NULL;
2043         struct snd_timer_id tid;
2044         int err;
2045
2046         snd_azf3328_dbgcallenter();
2047         tid.dev_class = SNDRV_TIMER_CLASS_CARD;
2048         tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
2049         tid.card = chip->card->number;
2050         tid.device = device;
2051         tid.subdevice = 0;
2052
2053         snd_azf3328_timer_hw.resolution *= seqtimer_scaling;
2054         snd_azf3328_timer_hw.ticks /= seqtimer_scaling;
2055
2056         err = snd_timer_new(chip->card, "AZF3328", &tid, &timer);
2057         if (err < 0)
2058                 goto out;
2059
2060         strcpy(timer->name, "AZF3328 timer");
2061         timer->private_data = chip;
2062         timer->hw = snd_azf3328_timer_hw;
2063
2064         chip->timer = timer;
2065
2066         snd_azf3328_timer_stop(timer);
2067
2068         err = 0;
2069
2070 out:
2071         snd_azf3328_dbgcallleave();
2072         return err;
2073 }
2074
2075 /******************************************************************/
2076
2077 static int
2078 snd_azf3328_free(struct snd_azf3328 *chip)
2079 {
2080         if (chip->irq < 0)
2081                 goto __end_hw;
2082
2083         /* reset (close) mixer:
2084          * first mute master volume, then reset
2085          */
2086         snd_azf3328_mixer_set_mute(chip, IDX_MIXER_PLAY_MASTER, 1);
2087         snd_azf3328_mixer_outw(chip, IDX_MIXER_RESET, 0x0000);
2088
2089         snd_azf3328_timer_stop(chip->timer);
2090         snd_azf3328_gameport_free(chip);
2091
2092         if (chip->irq >= 0)
2093                 synchronize_irq(chip->irq);
2094 __end_hw:
2095         if (chip->irq >= 0)
2096                 free_irq(chip->irq, chip);
2097         pci_release_regions(chip->pci);
2098         pci_disable_device(chip->pci);
2099
2100         kfree(chip);
2101         return 0;
2102 }
2103
2104 static int
2105 snd_azf3328_dev_free(struct snd_device *device)
2106 {
2107         struct snd_azf3328 *chip = device->device_data;
2108         return snd_azf3328_free(chip);
2109 }
2110
2111 #if 0
2112 /* check whether a bit can be modified */
2113 static void
2114 snd_azf3328_test_bit(unsigned unsigned reg, int bit)
2115 {
2116         unsigned char val, valoff, valon;
2117
2118         val = inb(reg);
2119
2120         outb(val & ~(1 << bit), reg);
2121         valoff = inb(reg);
2122
2123         outb(val|(1 << bit), reg);
2124         valon = inb(reg);
2125
2126         outb(val, reg);
2127
2128         printk(KERN_DEBUG "reg %04x bit %d: %02x %02x %02x\n",
2129                                 reg, bit, val, valoff, valon
2130         );
2131 }
2132 #endif
2133
2134 static inline void
2135 snd_azf3328_debug_show_ports(const struct snd_azf3328 *chip)
2136 {
2137 #if DEBUG_MISC
2138         u16 tmp;
2139
2140         snd_azf3328_dbgmisc(
2141                 "ctrl_io 0x%lx, game_io 0x%lx, mpu_io 0x%lx, "
2142                 "opl3_io 0x%lx, mixer_io 0x%lx, irq %d\n",
2143                 chip->ctrl_io, chip->game_io, chip->mpu_io,
2144                 chip->opl3_io, chip->mixer_io, chip->irq
2145         );
2146
2147         snd_azf3328_dbgmisc("game %02x %02x %02x %02x %02x %02x\n",
2148                 snd_azf3328_game_inb(chip, 0),
2149                 snd_azf3328_game_inb(chip, 1),
2150                 snd_azf3328_game_inb(chip, 2),
2151                 snd_azf3328_game_inb(chip, 3),
2152                 snd_azf3328_game_inb(chip, 4),
2153                 snd_azf3328_game_inb(chip, 5)
2154         );
2155
2156         for (tmp = 0; tmp < 0x07; tmp += 1)
2157                 snd_azf3328_dbgmisc("mpu_io 0x%04x\n", inb(chip->mpu_io + tmp));
2158
2159         for (tmp = 0; tmp <= 0x07; tmp += 1)
2160                 snd_azf3328_dbgmisc("0x%02x: game200 0x%04x, game208 0x%04x\n",
2161                         tmp, inb(0x200 + tmp), inb(0x208 + tmp));
2162
2163         for (tmp = 0; tmp <= 0x01; tmp += 1)
2164                 snd_azf3328_dbgmisc(
2165                         "0x%02x: mpu300 0x%04x, mpu310 0x%04x, mpu320 0x%04x, "
2166                         "mpu330 0x%04x opl388 0x%04x opl38c 0x%04x\n",
2167                                 tmp,
2168                                 inb(0x300 + tmp),
2169                                 inb(0x310 + tmp),
2170                                 inb(0x320 + tmp),
2171                                 inb(0x330 + tmp),
2172                                 inb(0x388 + tmp),
2173                                 inb(0x38c + tmp)
2174                 );
2175
2176         for (tmp = 0; tmp < AZF_IO_SIZE_CTRL; tmp += 2)
2177                 snd_azf3328_dbgmisc("ctrl 0x%02x: 0x%04x\n",
2178                         tmp, snd_azf3328_ctrl_inw(chip, tmp)
2179                 );
2180
2181         for (tmp = 0; tmp < AZF_IO_SIZE_MIXER; tmp += 2)
2182                 snd_azf3328_dbgmisc("mixer 0x%02x: 0x%04x\n",
2183                         tmp, snd_azf3328_mixer_inw(chip, tmp)
2184                 );
2185 #endif /* DEBUG_MISC */
2186 }
2187
2188 static int __devinit
2189 snd_azf3328_create(struct snd_card *card,
2190                    struct pci_dev *pci,
2191                    unsigned long device_type,
2192                    struct snd_azf3328 **rchip)
2193 {
2194         struct snd_azf3328 *chip;
2195         int err;
2196         static struct snd_device_ops ops = {
2197                 .dev_free =     snd_azf3328_dev_free,
2198         };
2199         u8 dma_init;
2200         enum snd_azf3328_codec_type codec_type;
2201         struct snd_azf3328_codec *codec_setup;
2202
2203         *rchip = NULL;
2204
2205         err = pci_enable_device(pci);
2206         if (err < 0)
2207                 return err;
2208
2209         chip = kzalloc(sizeof(*chip), GFP_KERNEL);
2210         if (chip == NULL) {
2211                 err = -ENOMEM;
2212                 goto out_err;
2213         }
2214         spin_lock_init(&chip->reg_lock);
2215         chip->card = card;
2216         chip->pci = pci;
2217         chip->irq = -1;
2218
2219         /* check if we can restrict PCI DMA transfers to 24 bits */
2220         if (pci_set_dma_mask(pci, DMA_BIT_MASK(24)) < 0 ||
2221             pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(24)) < 0) {
2222                 snd_printk(KERN_ERR "architecture does not support "
2223                                         "24bit PCI busmaster DMA\n"
2224                 );
2225                 err = -ENXIO;
2226                 goto out_err;
2227         }
2228
2229         err = pci_request_regions(pci, "Aztech AZF3328");
2230         if (err < 0)
2231                 goto out_err;
2232
2233         chip->ctrl_io  = pci_resource_start(pci, 0);
2234         chip->game_io  = pci_resource_start(pci, 1);
2235         chip->mpu_io   = pci_resource_start(pci, 2);
2236         chip->opl3_io  = pci_resource_start(pci, 3);
2237         chip->mixer_io = pci_resource_start(pci, 4);
2238
2239         codec_setup = &chip->codecs[AZF_CODEC_PLAYBACK];
2240         codec_setup->io_base = chip->ctrl_io + AZF_IO_OFFS_CODEC_PLAYBACK;
2241         codec_setup->name = "PLAYBACK";
2242
2243         codec_setup = &chip->codecs[AZF_CODEC_CAPTURE];
2244         codec_setup->io_base = chip->ctrl_io + AZF_IO_OFFS_CODEC_CAPTURE;
2245         codec_setup->name = "CAPTURE";
2246
2247         codec_setup = &chip->codecs[AZF_CODEC_I2S_OUT];
2248         codec_setup->io_base = chip->ctrl_io + AZF_IO_OFFS_CODEC_I2S_OUT;
2249         codec_setup->name = "I2S_OUT";
2250
2251         if (request_irq(pci->irq, snd_azf3328_interrupt,
2252                         IRQF_SHARED, card->shortname, chip)) {
2253                 snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
2254                 err = -EBUSY;
2255                 goto out_err;
2256         }
2257         chip->irq = pci->irq;
2258         pci_set_master(pci);
2259         synchronize_irq(chip->irq);
2260
2261         snd_azf3328_debug_show_ports(chip);
2262
2263         err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
2264         if (err < 0)
2265                 goto out_err;
2266
2267         /* create mixer interface & switches */
2268         err = snd_azf3328_mixer_new(chip);
2269         if (err < 0)
2270                 goto out_err;
2271
2272         /* standard codec init stuff */
2273                 /* default DMA init value */
2274         dma_init = DMA_RUN_SOMETHING2|DMA_EPILOGUE_SOMETHING|DMA_SOMETHING_ELSE;
2275
2276         for (codec_type = AZF_CODEC_PLAYBACK;
2277                 codec_type <= AZF_CODEC_I2S_OUT; ++codec_type) {
2278                 struct snd_azf3328_codec_data *codec =
2279                          &chip->codecs[codec_type];
2280
2281                 /* shutdown codecs to reduce power / noise */
2282                         /* have ...ctrl_codec_activity() act properly */
2283                 codec->running = 1;
2284                 snd_azf3328_ctrl_codec_activity(chip, codec_type, 0);
2285
2286                 spin_lock_irq(&chip->reg_lock);
2287                 snd_azf3328_codec_outb(codec, IDX_IO_CODEC_DMA_FLAGS,
2288                                                  dma_init);
2289                 spin_unlock_irq(&chip->reg_lock);
2290         }
2291
2292         snd_card_set_dev(card, &pci->dev);
2293
2294         *rchip = chip;
2295
2296         err = 0;
2297         goto out;
2298
2299 out_err:
2300         if (chip)
2301                 snd_azf3328_free(chip);
2302         pci_disable_device(pci);
2303
2304 out:
2305         return err;
2306 }
2307
2308 static int __devinit
2309 snd_azf3328_probe(struct pci_dev *pci, const struct pci_device_id *pci_id)
2310 {
2311         static int dev;
2312         struct snd_card *card;
2313         struct snd_azf3328 *chip;
2314         struct snd_opl3 *opl3;
2315         int err;
2316
2317         snd_azf3328_dbgcallenter();
2318         if (dev >= SNDRV_CARDS)
2319                 return -ENODEV;
2320         if (!enable[dev]) {
2321                 dev++;
2322                 return -ENOENT;
2323         }
2324
2325         err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
2326         if (err < 0)
2327                 return err;
2328
2329         strcpy(card->driver, "AZF3328");
2330         strcpy(card->shortname, "Aztech AZF3328 (PCI168)");
2331
2332         err = snd_azf3328_create(card, pci, pci_id->driver_data, &chip);
2333         if (err < 0)
2334                 goto out_err;
2335
2336         card->private_data = chip;
2337
2338         /* chose to use MPU401_HW_AZT2320 ID instead of MPU401_HW_MPU401,
2339            since our hardware ought to be similar, thus use same ID. */
2340         err = snd_mpu401_uart_new(
2341                 card, 0,
2342                 MPU401_HW_AZT2320, chip->mpu_io, MPU401_INFO_INTEGRATED,
2343                 pci->irq, 0, &chip->rmidi
2344         );
2345         if (err < 0) {
2346                 snd_printk(KERN_ERR "azf3328: no MPU-401 device at 0x%lx?\n",
2347                                 chip->mpu_io
2348                 );
2349                 goto out_err;
2350         }
2351
2352         err = snd_azf3328_timer(chip, 0);
2353         if (err < 0)
2354                 goto out_err;
2355
2356         err = snd_azf3328_pcm(chip);
2357         if (err < 0)
2358                 goto out_err;
2359
2360         if (snd_opl3_create(card, chip->opl3_io, chip->opl3_io+2,
2361                             OPL3_HW_AUTO, 1, &opl3) < 0) {
2362                 snd_printk(KERN_ERR "azf3328: no OPL3 device at 0x%lx-0x%lx?\n",
2363                            chip->opl3_io, chip->opl3_io+2
2364                 );
2365         } else {
2366                 /* need to use IDs 1, 2 since ID 0 is snd_azf3328_timer above */
2367                 err = snd_opl3_timer_new(opl3, 1, 2);
2368                 if (err < 0)
2369                         goto out_err;
2370                 err = snd_opl3_hwdep_new(opl3, 0, 1, NULL);
2371                 if (err < 0)
2372                         goto out_err;
2373         }
2374
2375         opl3->private_data = chip;
2376
2377         sprintf(card->longname, "%s at 0x%lx, irq %i",
2378                 card->shortname, chip->ctrl_io, chip->irq);
2379
2380         err = snd_card_register(card);
2381         if (err < 0)
2382                 goto out_err;
2383
2384 #ifdef MODULE
2385         printk(KERN_INFO
2386 "azt3328: Sound driver for Aztech AZF3328-based soundcards such as PCI168.\n"
2387 "azt3328: Hardware was completely undocumented, unfortunately.\n"
2388 "azt3328: Feel free to contact andi AT lisas.de for bug reports etc.!\n"
2389 "azt3328: User-scalable sequencer timer set to %dHz (1024000Hz / %d).\n",
2390         1024000 / seqtimer_scaling, seqtimer_scaling);
2391 #endif
2392
2393         snd_azf3328_gameport(chip, dev);
2394
2395         pci_set_drvdata(pci, card);
2396         dev++;
2397
2398         err = 0;
2399         goto out;
2400
2401 out_err:
2402         snd_printk(KERN_ERR "azf3328: something failed, exiting\n");
2403         snd_card_free(card);
2404
2405 out:
2406         snd_azf3328_dbgcallleave();
2407         return err;
2408 }
2409
2410 static void __devexit
2411 snd_azf3328_remove(struct pci_dev *pci)
2412 {
2413         snd_azf3328_dbgcallenter();
2414         snd_card_free(pci_get_drvdata(pci));
2415         pci_set_drvdata(pci, NULL);
2416         snd_azf3328_dbgcallleave();
2417 }
2418
2419 #ifdef CONFIG_PM
2420 static inline void
2421 snd_azf3328_suspend_regs(unsigned long io_addr, unsigned count, u32 *saved_regs)
2422 {
2423         unsigned reg;
2424
2425         for (reg = 0; reg < count; ++reg) {
2426                 *saved_regs = inl(io_addr);
2427                 snd_azf3328_dbgpm("suspend: io 0x%04lx: 0x%08x\n",
2428                         io_addr, *saved_regs);
2429                 ++saved_regs;
2430                 io_addr += sizeof(*saved_regs);
2431         }
2432 }
2433
2434 static int
2435 snd_azf3328_suspend(struct pci_dev *pci, pm_message_t state)
2436 {
2437         struct snd_card *card = pci_get_drvdata(pci);
2438         struct snd_azf3328 *chip = card->private_data;
2439         u16 *saved_regs_ctrl_u16;
2440
2441         snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
2442
2443         /* same pcm object for playback/capture */
2444         snd_pcm_suspend_all(chip->pcm[AZF_CODEC_PLAYBACK]);
2445         snd_pcm_suspend_all(chip->pcm[AZF_CODEC_I2S_OUT]);
2446
2447         snd_azf3328_suspend_regs(chip->mixer_io,
2448                 ARRAY_SIZE(chip->saved_regs_mixer), chip->saved_regs_mixer);
2449
2450         /* make sure to disable master volume etc. to prevent looping sound */
2451         snd_azf3328_mixer_set_mute(chip, IDX_MIXER_PLAY_MASTER, 1);
2452         snd_azf3328_mixer_set_mute(chip, IDX_MIXER_WAVEOUT, 1);
2453
2454         snd_azf3328_suspend_regs(chip->ctrl_io,
2455                 ARRAY_SIZE(chip->saved_regs_ctrl), chip->saved_regs_ctrl);
2456
2457         /* manually store the one currently relevant write-only reg, too */
2458         saved_regs_ctrl_u16 = (u16 *)chip->saved_regs_ctrl;
2459         saved_regs_ctrl_u16[IDX_IO_6AH / 2] = chip->shadow_reg_ctrl_6AH;
2460
2461         snd_azf3328_suspend_regs(chip->game_io,
2462                 ARRAY_SIZE(chip->saved_regs_game), chip->saved_regs_game);
2463         snd_azf3328_suspend_regs(chip->mpu_io,
2464                 ARRAY_SIZE(chip->saved_regs_mpu), chip->saved_regs_mpu);
2465         snd_azf3328_suspend_regs(chip->opl3_io,
2466                 ARRAY_SIZE(chip->saved_regs_opl3), chip->saved_regs_opl3);
2467
2468         pci_disable_device(pci);
2469         pci_save_state(pci);
2470         pci_set_power_state(pci, pci_choose_state(pci, state));
2471         return 0;
2472 }
2473
2474 static inline void
2475 snd_azf3328_resume_regs(const u32 *saved_regs,
2476                         unsigned long io_addr,
2477                         unsigned count
2478 )
2479 {
2480         unsigned reg;
2481
2482         for (reg = 0; reg < count; ++reg) {
2483                 outl(*saved_regs, io_addr);
2484                 snd_azf3328_dbgpm("resume: io 0x%04lx: 0x%08x --> 0x%08x\n",
2485                         io_addr, *saved_regs, inl(io_addr));
2486                 ++saved_regs;
2487                 io_addr += sizeof(*saved_regs);
2488         }
2489 }
2490
2491 static int
2492 snd_azf3328_resume(struct pci_dev *pci)
2493 {
2494         struct snd_card *card = pci_get_drvdata(pci);
2495         const struct snd_azf3328 *chip = card->private_data;
2496
2497         pci_set_power_state(pci, PCI_D0);
2498         pci_restore_state(pci);
2499         if (pci_enable_device(pci) < 0) {
2500                 printk(KERN_ERR "azt3328: pci_enable_device failed, "
2501                        "disabling device\n");
2502                 snd_card_disconnect(card);
2503                 return -EIO;
2504         }
2505         pci_set_master(pci);
2506
2507         snd_azf3328_resume_regs(chip->saved_regs_game, chip->game_io,
2508                                         ARRAY_SIZE(chip->saved_regs_game));
2509         snd_azf3328_resume_regs(chip->saved_regs_mpu, chip->mpu_io,
2510                                         ARRAY_SIZE(chip->saved_regs_mpu));
2511         snd_azf3328_resume_regs(chip->saved_regs_opl3, chip->opl3_io,
2512                                         ARRAY_SIZE(chip->saved_regs_opl3));
2513
2514         snd_azf3328_resume_regs(chip->saved_regs_mixer, chip->mixer_io,
2515                                         ARRAY_SIZE(chip->saved_regs_mixer));
2516
2517         /* unfortunately with 32bit transfers, IDX_MIXER_PLAY_MASTER (0x02)
2518            and IDX_MIXER_RESET (offset 0x00) get touched at the same time,
2519            resulting in a mixer reset condition persisting until _after_
2520            master vol was restored. Thus master vol needs an extra restore. */
2521         outw(((u16 *)chip->saved_regs_mixer)[1], chip->mixer_io + 2);
2522
2523         snd_azf3328_resume_regs(chip->saved_regs_ctrl, chip->ctrl_io,
2524                                         ARRAY_SIZE(chip->saved_regs_ctrl));
2525
2526         snd_power_change_state(card, SNDRV_CTL_POWER_D0);
2527         return 0;
2528 }
2529 #endif /* CONFIG_PM */
2530
2531
2532 static struct pci_driver driver = {
2533         .name = "AZF3328",
2534         .id_table = snd_azf3328_ids,
2535         .probe = snd_azf3328_probe,
2536         .remove = __devexit_p(snd_azf3328_remove),
2537 #ifdef CONFIG_PM
2538         .suspend = snd_azf3328_suspend,
2539         .resume = snd_azf3328_resume,
2540 #endif
2541 };
2542
2543 static int __init
2544 alsa_card_azf3328_init(void)
2545 {
2546         int err;
2547         snd_azf3328_dbgcallenter();
2548         err = pci_register_driver(&driver);
2549         snd_azf3328_dbgcallleave();
2550         return err;
2551 }
2552
2553 static void __exit
2554 alsa_card_azf3328_exit(void)
2555 {
2556         snd_azf3328_dbgcallenter();
2557         pci_unregister_driver(&driver);
2558         snd_azf3328_dbgcallleave();
2559 }
2560
2561 module_init(alsa_card_azf3328_init)
2562 module_exit(alsa_card_azf3328_exit)