GNU Linux-libre 6.8.9-gnu
[releases.git] / sound / pci / es1968.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Driver for ESS Maestro 1/2/2E Sound Card (started 21.8.99)
4  *  Copyright (c) by Matze Braun <MatzeBraun@gmx.de>.
5  *                   Takashi Iwai <tiwai@suse.de>
6  *                  
7  *  Most of the driver code comes from Zach Brown(zab@redhat.com)
8  *      Alan Cox OSS Driver
9  *  Rewritted from card-es1938.c source.
10  *
11  *  TODO:
12  *   Perhaps Synth
13  *
14  *  Notes from Zach Brown about the driver code
15  *
16  *  Hardware Description
17  *
18  *      A working Maestro setup contains the Maestro chip wired to a 
19  *      codec or 2.  In the Maestro we have the APUs, the ASSP, and the
20  *      Wavecache.  The APUs can be though of as virtual audio routing
21  *      channels.  They can take data from a number of sources and perform
22  *      basic encodings of the data.  The wavecache is a storehouse for
23  *      PCM data.  Typically it deals with PCI and interracts with the
24  *      APUs.  The ASSP is a wacky DSP like device that ESS is loth
25  *      to release docs on.  Thankfully it isn't required on the Maestro
26  *      until you start doing insane things like FM emulation and surround
27  *      encoding.  The codecs are almost always AC-97 compliant codecs, 
28  *      but it appears that early Maestros may have had PT101 (an ESS
29  *      part?) wired to them.  The only real difference in the Maestro
30  *      families is external goop like docking capability, memory for
31  *      the ASSP, and initialization differences.
32  *
33  *  Driver Operation
34  *
35  *      We only drive the APU/Wavecache as typical DACs and drive the
36  *      mixers in the codecs.  There are 64 APUs.  We assign 6 to each
37  *      /dev/dsp? device.  2 channels for output, and 4 channels for
38  *      input.
39  *
40  *      Each APU can do a number of things, but we only really use
41  *      3 basic functions.  For playback we use them to convert PCM
42  *      data fetched over PCI by the wavecahche into analog data that
43  *      is handed to the codec.  One APU for mono, and a pair for stereo.
44  *      When in stereo, the combination of smarts in the APU and Wavecache
45  *      decide which wavecache gets the left or right channel.
46  *
47  *      For record we still use the old overly mono system.  For each in
48  *      coming channel the data comes in from the codec, through a 'input'
49  *      APU, through another rate converter APU, and then into memory via
50  *      the wavecache and PCI.  If its stereo, we mash it back into LRLR in
51  *      software.  The pass between the 2 APUs is supposedly what requires us
52  *      to have a 512 byte buffer sitting around in wavecache/memory.
53  *
54  *      The wavecache makes our life even more fun.  First off, it can
55  *      only address the first 28 bits of PCI address space, making it
56  *      useless on quite a few architectures.  Secondly, its insane.
57  *      It claims to fetch from 4 regions of PCI space, each 4 meg in length.
58  *      But that doesn't really work.  You can only use 1 region.  So all our
59  *      allocations have to be in 4meg of each other.  Booo.  Hiss.
60  *      So we have a module parameter, dsps_order, that is the order of
61  *      the number of dsps to provide.  All their buffer space is allocated
62  *      on open time.  The sonicvibes OSS routines we inherited really want
63  *      power of 2 buffers, so we have all those next to each other, then
64  *      512 byte regions for the recording wavecaches.  This ends up
65  *      wasting quite a bit of memory.  The only fixes I can see would be 
66  *      getting a kernel allocator that could work in zones, or figuring out
67  *      just how to coerce the WP into doing what we want.
68  *
69  *      The indirection of the various registers means we have to spinlock
70  *      nearly all register accesses.  We have the main register indirection
71  *      like the wave cache, maestro registers, etc.  Then we have beasts
72  *      like the APU interface that is indirect registers gotten at through
73  *      the main maestro indirection.  Ouch.  We spinlock around the actual
74  *      ports on a per card basis.  This means spinlock activity at each IO
75  *      operation, but the only IO operation clusters are in non critical 
76  *      paths and it makes the code far easier to follow.  Interrupts are
77  *      blocked while holding the locks because the int handler has to
78  *      get at some of them :(.  The mixer interface doesn't, however.
79  *      We also have an OSS state lock that is thrown around in a few
80  *      places.
81  */
82
83 #include <linux/io.h>
84 #include <linux/delay.h>
85 #include <linux/interrupt.h>
86 #include <linux/init.h>
87 #include <linux/pci.h>
88 #include <linux/dma-mapping.h>
89 #include <linux/slab.h>
90 #include <linux/gameport.h>
91 #include <linux/module.h>
92 #include <linux/mutex.h>
93 #include <linux/input.h>
94
95 #include <sound/core.h>
96 #include <sound/pcm.h>
97 #include <sound/mpu401.h>
98 #include <sound/ac97_codec.h>
99 #include <sound/initval.h>
100
101 #ifdef CONFIG_SND_ES1968_RADIO
102 #include <media/drv-intf/tea575x.h>
103 #endif
104
105 #define CARD_NAME "ESS Maestro1/2"
106 #define DRIVER_NAME "ES1968"
107
108 MODULE_DESCRIPTION("ESS Maestro");
109 MODULE_LICENSE("GPL");
110
111 #if IS_REACHABLE(CONFIG_GAMEPORT)
112 #define SUPPORT_JOYSTICK 1
113 #endif
114
115 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 1-MAX */
116 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
117 static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;     /* Enable this card */
118 static int total_bufsize[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1024 };
119 static int pcm_substreams_p[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 4 };
120 static int pcm_substreams_c[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1 };
121 static int clock[SNDRV_CARDS];
122 static int use_pm[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2};
123 static int enable_mpu[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2};
124 #ifdef SUPPORT_JOYSTICK
125 static bool joystick[SNDRV_CARDS];
126 #endif
127 static int radio_nr[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = -1};
128
129 module_param_array(index, int, NULL, 0444);
130 MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
131 module_param_array(id, charp, NULL, 0444);
132 MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
133 module_param_array(enable, bool, NULL, 0444);
134 MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
135 module_param_array(total_bufsize, int, NULL, 0444);
136 MODULE_PARM_DESC(total_bufsize, "Total buffer size in kB.");
137 module_param_array(pcm_substreams_p, int, NULL, 0444);
138 MODULE_PARM_DESC(pcm_substreams_p, "PCM Playback substreams for " CARD_NAME " soundcard.");
139 module_param_array(pcm_substreams_c, int, NULL, 0444);
140 MODULE_PARM_DESC(pcm_substreams_c, "PCM Capture substreams for " CARD_NAME " soundcard.");
141 module_param_array(clock, int, NULL, 0444);
142 MODULE_PARM_DESC(clock, "Clock on " CARD_NAME " soundcard.  (0 = auto-detect)");
143 module_param_array(use_pm, int, NULL, 0444);
144 MODULE_PARM_DESC(use_pm, "Toggle power-management.  (0 = off, 1 = on, 2 = auto)");
145 module_param_array(enable_mpu, int, NULL, 0444);
146 MODULE_PARM_DESC(enable_mpu, "Enable MPU401.  (0 = off, 1 = on, 2 = auto)");
147 #ifdef SUPPORT_JOYSTICK
148 module_param_array(joystick, bool, NULL, 0444);
149 MODULE_PARM_DESC(joystick, "Enable joystick.");
150 #endif
151 module_param_array(radio_nr, int, NULL, 0444);
152 MODULE_PARM_DESC(radio_nr, "Radio device numbers");
153
154
155
156 #define NR_APUS                 64
157 #define NR_APU_REGS             16
158
159 /* NEC Versas ? */
160 #define NEC_VERSA_SUBID1        0x80581033
161 #define NEC_VERSA_SUBID2        0x803c1033
162
163 /* Mode Flags */
164 #define ESS_FMT_STEREO          0x01
165 #define ESS_FMT_16BIT           0x02
166
167 #define DAC_RUNNING             1
168 #define ADC_RUNNING             2
169
170 /* Values for the ESM_LEGACY_AUDIO_CONTROL */
171
172 #define ESS_DISABLE_AUDIO       0x8000
173 #define ESS_ENABLE_SERIAL_IRQ   0x4000
174 #define IO_ADRESS_ALIAS         0x0020
175 #define MPU401_IRQ_ENABLE       0x0010
176 #define MPU401_IO_ENABLE        0x0008
177 #define GAME_IO_ENABLE          0x0004
178 #define FM_IO_ENABLE            0x0002
179 #define SB_IO_ENABLE            0x0001
180
181 /* Values for the ESM_CONFIG_A */
182
183 #define PIC_SNOOP1              0x4000
184 #define PIC_SNOOP2              0x2000
185 #define SAFEGUARD               0x0800
186 #define DMA_CLEAR               0x0700
187 #define DMA_DDMA                0x0000
188 #define DMA_TDMA                0x0100
189 #define DMA_PCPCI               0x0200
190 #define POST_WRITE              0x0080
191 #define PCI_TIMING              0x0040
192 #define SWAP_LR                 0x0020
193 #define SUBTR_DECODE            0x0002
194
195 /* Values for the ESM_CONFIG_B */
196
197 #define SPDIF_CONFB             0x0100
198 #define HWV_CONFB               0x0080
199 #define DEBOUNCE                0x0040
200 #define GPIO_CONFB              0x0020
201 #define CHI_CONFB               0x0010
202 #define IDMA_CONFB              0x0008  /*undoc */
203 #define MIDI_FIX                0x0004  /*undoc */
204 #define IRQ_TO_ISA              0x0001  /*undoc */
205
206 /* Values for Ring Bus Control B */
207 #define RINGB_2CODEC_ID_MASK    0x0003
208 #define RINGB_DIS_VALIDATION    0x0008
209 #define RINGB_EN_SPDIF          0x0010
210 #define RINGB_EN_2CODEC         0x0020
211 #define RINGB_SING_BIT_DUAL     0x0040
212
213 /* ****Port Addresses**** */
214
215 /*   Write & Read */
216 #define ESM_INDEX               0x02
217 #define ESM_DATA                0x00
218
219 /*   AC97 + RingBus */
220 #define ESM_AC97_INDEX          0x30
221 #define ESM_AC97_DATA           0x32
222 #define ESM_RING_BUS_DEST       0x34
223 #define ESM_RING_BUS_CONTR_A    0x36
224 #define ESM_RING_BUS_CONTR_B    0x38
225 #define ESM_RING_BUS_SDO        0x3A
226
227 /*   WaveCache*/
228 #define WC_INDEX                0x10
229 #define WC_DATA                 0x12
230 #define WC_CONTROL              0x14
231
232 /*   ASSP*/
233 #define ASSP_INDEX              0x80
234 #define ASSP_MEMORY             0x82
235 #define ASSP_DATA               0x84
236 #define ASSP_CONTROL_A          0xA2
237 #define ASSP_CONTROL_B          0xA4
238 #define ASSP_CONTROL_C          0xA6
239 #define ASSP_HOSTW_INDEX        0xA8
240 #define ASSP_HOSTW_DATA         0xAA
241 #define ASSP_HOSTW_IRQ          0xAC
242 /* Midi */
243 #define ESM_MPU401_PORT         0x98
244 /* Others */
245 #define ESM_PORT_HOST_IRQ       0x18
246
247 #define IDR0_DATA_PORT          0x00
248 #define IDR1_CRAM_POINTER       0x01
249 #define IDR2_CRAM_DATA          0x02
250 #define IDR3_WAVE_DATA          0x03
251 #define IDR4_WAVE_PTR_LOW       0x04
252 #define IDR5_WAVE_PTR_HI        0x05
253 #define IDR6_TIMER_CTRL         0x06
254 #define IDR7_WAVE_ROMRAM        0x07
255
256 #define WRITEABLE_MAP           0xEFFFFF
257 #define READABLE_MAP            0x64003F
258
259 /* PCI Register */
260
261 #define ESM_LEGACY_AUDIO_CONTROL 0x40
262 #define ESM_ACPI_COMMAND        0x54
263 #define ESM_CONFIG_A            0x50
264 #define ESM_CONFIG_B            0x52
265 #define ESM_DDMA                0x60
266
267 /* Bob Bits */
268 #define ESM_BOB_ENABLE          0x0001
269 #define ESM_BOB_START           0x0001
270
271 /* Host IRQ Control Bits */
272 #define ESM_RESET_MAESTRO       0x8000
273 #define ESM_RESET_DIRECTSOUND   0x4000
274 #define ESM_HIRQ_ClkRun         0x0100
275 #define ESM_HIRQ_HW_VOLUME      0x0040
276 #define ESM_HIRQ_HARPO          0x0030  /* What's that? */
277 #define ESM_HIRQ_ASSP           0x0010
278 #define ESM_HIRQ_DSIE           0x0004
279 #define ESM_HIRQ_MPU401         0x0002
280 #define ESM_HIRQ_SB             0x0001
281
282 /* Host IRQ Status Bits */
283 #define ESM_MPU401_IRQ          0x02
284 #define ESM_SB_IRQ              0x01
285 #define ESM_SOUND_IRQ           0x04
286 #define ESM_ASSP_IRQ            0x10
287 #define ESM_HWVOL_IRQ           0x40
288
289 #define ESS_SYSCLK              50000000
290 #define ESM_BOB_FREQ            200
291 #define ESM_BOB_FREQ_MAX        800
292
293 #define ESM_FREQ_ESM1           (49152000L / 1024L)     /* default rate 48000 */
294 #define ESM_FREQ_ESM2           (50000000L / 1024L)
295
296 /* APU Modes: reg 0x00, bit 4-7 */
297 #define ESM_APU_MODE_SHIFT      4
298 #define ESM_APU_MODE_MASK       (0xf << 4)
299 #define ESM_APU_OFF             0x00
300 #define ESM_APU_16BITLINEAR     0x01    /* 16-Bit Linear Sample Player */
301 #define ESM_APU_16BITSTEREO     0x02    /* 16-Bit Stereo Sample Player */
302 #define ESM_APU_8BITLINEAR      0x03    /* 8-Bit Linear Sample Player */
303 #define ESM_APU_8BITSTEREO      0x04    /* 8-Bit Stereo Sample Player */
304 #define ESM_APU_8BITDIFF        0x05    /* 8-Bit Differential Sample Playrer */
305 #define ESM_APU_DIGITALDELAY    0x06    /* Digital Delay Line */
306 #define ESM_APU_DUALTAP         0x07    /* Dual Tap Reader */
307 #define ESM_APU_CORRELATOR      0x08    /* Correlator */
308 #define ESM_APU_INPUTMIXER      0x09    /* Input Mixer */
309 #define ESM_APU_WAVETABLE       0x0A    /* Wave Table Mode */
310 #define ESM_APU_SRCONVERTOR     0x0B    /* Sample Rate Convertor */
311 #define ESM_APU_16BITPINGPONG   0x0C    /* 16-Bit Ping-Pong Sample Player */
312 #define ESM_APU_RESERVED1       0x0D    /* Reserved 1 */
313 #define ESM_APU_RESERVED2       0x0E    /* Reserved 2 */
314 #define ESM_APU_RESERVED3       0x0F    /* Reserved 3 */
315
316 /* reg 0x00 */
317 #define ESM_APU_FILTER_Q_SHIFT          0
318 #define ESM_APU_FILTER_Q_MASK           (3 << 0)
319 /* APU Filtey Q Control */
320 #define ESM_APU_FILTER_LESSQ    0x00
321 #define ESM_APU_FILTER_MOREQ    0x03
322
323 #define ESM_APU_FILTER_TYPE_SHIFT       2
324 #define ESM_APU_FILTER_TYPE_MASK        (3 << 2)
325 #define ESM_APU_ENV_TYPE_SHIFT          8
326 #define ESM_APU_ENV_TYPE_MASK           (3 << 8)
327 #define ESM_APU_ENV_STATE_SHIFT         10
328 #define ESM_APU_ENV_STATE_MASK          (3 << 10)
329 #define ESM_APU_END_CURVE               (1 << 12)
330 #define ESM_APU_INT_ON_LOOP             (1 << 13)
331 #define ESM_APU_DMA_ENABLE              (1 << 14)
332
333 /* reg 0x02 */
334 #define ESM_APU_SUBMIX_GROUP_SHIRT      0
335 #define ESM_APU_SUBMIX_GROUP_MASK       (7 << 0)
336 #define ESM_APU_SUBMIX_MODE             (1 << 3)
337 #define ESM_APU_6dB                     (1 << 4)
338 #define ESM_APU_DUAL_EFFECT             (1 << 5)
339 #define ESM_APU_EFFECT_CHANNELS_SHIFT   6
340 #define ESM_APU_EFFECT_CHANNELS_MASK    (3 << 6)
341
342 /* reg 0x03 */
343 #define ESM_APU_STEP_SIZE_MASK          0x0fff
344
345 /* reg 0x04 */
346 #define ESM_APU_PHASE_SHIFT             0
347 #define ESM_APU_PHASE_MASK              (0xff << 0)
348 #define ESM_APU_WAVE64K_PAGE_SHIFT      8       /* most 8bit of wave start offset */
349 #define ESM_APU_WAVE64K_PAGE_MASK       (0xff << 8)
350
351 /* reg 0x05 - wave start offset */
352 /* reg 0x06 - wave end offset */
353 /* reg 0x07 - wave loop length */
354
355 /* reg 0x08 */
356 #define ESM_APU_EFFECT_GAIN_SHIFT       0
357 #define ESM_APU_EFFECT_GAIN_MASK        (0xff << 0)
358 #define ESM_APU_TREMOLO_DEPTH_SHIFT     8
359 #define ESM_APU_TREMOLO_DEPTH_MASK      (0xf << 8)
360 #define ESM_APU_TREMOLO_RATE_SHIFT      12
361 #define ESM_APU_TREMOLO_RATE_MASK       (0xf << 12)
362
363 /* reg 0x09 */
364 /* bit 0-7 amplitude dest? */
365 #define ESM_APU_AMPLITUDE_NOW_SHIFT     8
366 #define ESM_APU_AMPLITUDE_NOW_MASK      (0xff << 8)
367
368 /* reg 0x0a */
369 #define ESM_APU_POLAR_PAN_SHIFT         0
370 #define ESM_APU_POLAR_PAN_MASK          (0x3f << 0)
371 /* Polar Pan Control */
372 #define ESM_APU_PAN_CENTER_CIRCLE               0x00
373 #define ESM_APU_PAN_MIDDLE_RADIUS               0x01
374 #define ESM_APU_PAN_OUTSIDE_RADIUS              0x02
375
376 #define ESM_APU_FILTER_TUNING_SHIFT     8
377 #define ESM_APU_FILTER_TUNING_MASK      (0xff << 8)
378
379 /* reg 0x0b */
380 #define ESM_APU_DATA_SRC_A_SHIFT        0
381 #define ESM_APU_DATA_SRC_A_MASK         (0x7f << 0)
382 #define ESM_APU_INV_POL_A               (1 << 7)
383 #define ESM_APU_DATA_SRC_B_SHIFT        8
384 #define ESM_APU_DATA_SRC_B_MASK         (0x7f << 8)
385 #define ESM_APU_INV_POL_B               (1 << 15)
386
387 #define ESM_APU_VIBRATO_RATE_SHIFT      0
388 #define ESM_APU_VIBRATO_RATE_MASK       (0xf << 0)
389 #define ESM_APU_VIBRATO_DEPTH_SHIFT     4
390 #define ESM_APU_VIBRATO_DEPTH_MASK      (0xf << 4)
391 #define ESM_APU_VIBRATO_PHASE_SHIFT     8
392 #define ESM_APU_VIBRATO_PHASE_MASK      (0xff << 8)
393
394 /* reg 0x0c */
395 #define ESM_APU_RADIUS_SELECT           (1 << 6)
396
397 /* APU Filter Control */
398 #define ESM_APU_FILTER_2POLE_LOPASS     0x00
399 #define ESM_APU_FILTER_2POLE_BANDPASS   0x01
400 #define ESM_APU_FILTER_2POLE_HIPASS     0x02
401 #define ESM_APU_FILTER_1POLE_LOPASS     0x03
402 #define ESM_APU_FILTER_1POLE_HIPASS     0x04
403 #define ESM_APU_FILTER_OFF              0x05
404
405 /* APU ATFP Type */
406 #define ESM_APU_ATFP_AMPLITUDE                  0x00
407 #define ESM_APU_ATFP_TREMELO                    0x01
408 #define ESM_APU_ATFP_FILTER                     0x02
409 #define ESM_APU_ATFP_PAN                        0x03
410
411 /* APU ATFP Flags */
412 #define ESM_APU_ATFP_FLG_OFF                    0x00
413 #define ESM_APU_ATFP_FLG_WAIT                   0x01
414 #define ESM_APU_ATFP_FLG_DONE                   0x02
415 #define ESM_APU_ATFP_FLG_INPROCESS              0x03
416
417
418 /* capture mixing buffer size */
419 #define ESM_MEM_ALIGN           0x1000
420 #define ESM_MIXBUF_SIZE         0x400
421
422 #define ESM_MODE_PLAY           0
423 #define ESM_MODE_CAPTURE        1
424
425
426 /* APU use in the driver */
427 enum snd_enum_apu_type {
428         ESM_APU_PCM_PLAY,
429         ESM_APU_PCM_CAPTURE,
430         ESM_APU_PCM_RATECONV,
431         ESM_APU_FREE
432 };
433
434 /* chip type */
435 enum {
436         TYPE_MAESTRO, TYPE_MAESTRO2, TYPE_MAESTRO2E
437 };
438
439 /* DMA Hack! */
440 struct esm_memory {
441         struct snd_dma_buffer buf;
442         int empty;      /* status */
443         struct list_head list;
444 };
445
446 /* Playback Channel */
447 struct esschan {
448         int running;
449
450         u8 apu[4];
451         u8 apu_mode[4];
452
453         /* playback/capture pcm buffer */
454         struct esm_memory *memory;
455         /* capture mixer buffer */
456         struct esm_memory *mixbuf;
457
458         unsigned int hwptr;     /* current hw pointer in bytes */
459         unsigned int count;     /* sample counter in bytes */
460         unsigned int dma_size;  /* total buffer size in bytes */
461         unsigned int frag_size; /* period size in bytes */
462         unsigned int wav_shift;
463         u16 base[4];            /* offset for ptr */
464
465         /* stereo/16bit flag */
466         unsigned char fmt;
467         int mode;       /* playback / capture */
468
469         int bob_freq;   /* required timer frequency */
470
471         struct snd_pcm_substream *substream;
472
473         /* linked list */
474         struct list_head list;
475
476 #ifdef CONFIG_PM_SLEEP
477         u16 wc_map[4];
478 #endif
479 };
480
481 struct es1968 {
482         /* Module Config */
483         int total_bufsize;                      /* in bytes */
484
485         int playback_streams, capture_streams;
486
487         unsigned int clock;             /* clock */
488         /* for clock measurement */
489         unsigned int in_measurement: 1;
490         unsigned int measure_apu;
491         unsigned int measure_lastpos;
492         unsigned int measure_count;
493
494         /* buffer */
495         struct snd_dma_buffer dma;
496
497         /* Resources... */
498         int irq;
499         unsigned long io_port;
500         int type;
501         struct pci_dev *pci;
502         struct snd_card *card;
503         struct snd_pcm *pcm;
504         int do_pm;              /* power-management enabled */
505
506         /* DMA memory block */
507         struct list_head buf_list;
508
509         /* ALSA Stuff */
510         struct snd_ac97 *ac97;
511         struct snd_rawmidi *rmidi;
512
513         spinlock_t reg_lock;
514         unsigned int in_suspend;
515
516         /* Maestro Stuff */
517         u16 maestro_map[32];
518         int bobclient;          /* active timer instancs */
519         int bob_freq;           /* timer frequency */
520         struct mutex memory_mutex;      /* memory lock */
521
522         /* APU states */
523         unsigned char apu[NR_APUS];
524
525         /* active substreams */
526         struct list_head substream_list;
527         spinlock_t substream_lock;
528
529 #ifdef CONFIG_PM_SLEEP
530         u16 apu_map[NR_APUS][NR_APU_REGS];
531 #endif
532
533 #ifdef SUPPORT_JOYSTICK
534         struct gameport *gameport;
535 #endif
536
537 #ifdef CONFIG_SND_ES1968_INPUT
538         struct input_dev *input_dev;
539         char phys[64];                  /* physical device path */
540 #else
541         struct snd_kcontrol *master_switch; /* for h/w volume control */
542         struct snd_kcontrol *master_volume;
543 #endif
544         struct work_struct hwvol_work;
545
546 #ifdef CONFIG_SND_ES1968_RADIO
547         struct v4l2_device v4l2_dev;
548         struct snd_tea575x tea;
549         unsigned int tea575x_tuner;
550 #endif
551 };
552
553 static irqreturn_t snd_es1968_interrupt(int irq, void *dev_id);
554
555 static const struct pci_device_id snd_es1968_ids[] = {
556         /* Maestro 1 */
557         { 0x1285, 0x0100, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_MULTIMEDIA_AUDIO << 8, 0xffff00, TYPE_MAESTRO },
558         /* Maestro 2 */
559         { 0x125d, 0x1968, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_MULTIMEDIA_AUDIO << 8, 0xffff00, TYPE_MAESTRO2 },
560         /* Maestro 2E */
561         { 0x125d, 0x1978, PCI_ANY_ID, PCI_ANY_ID, PCI_CLASS_MULTIMEDIA_AUDIO << 8, 0xffff00, TYPE_MAESTRO2E },
562         { 0, }
563 };
564
565 MODULE_DEVICE_TABLE(pci, snd_es1968_ids);
566
567 /* *********************
568    * Low Level Funcs!  *
569    *********************/
570
571 /* no spinlock */
572 static void __maestro_write(struct es1968 *chip, u16 reg, u16 data)
573 {
574         outw(reg, chip->io_port + ESM_INDEX);
575         outw(data, chip->io_port + ESM_DATA);
576         chip->maestro_map[reg] = data;
577 }
578
579 static inline void maestro_write(struct es1968 *chip, u16 reg, u16 data)
580 {
581         unsigned long flags;
582         spin_lock_irqsave(&chip->reg_lock, flags);
583         __maestro_write(chip, reg, data);
584         spin_unlock_irqrestore(&chip->reg_lock, flags);
585 }
586
587 /* no spinlock */
588 static u16 __maestro_read(struct es1968 *chip, u16 reg)
589 {
590         if (READABLE_MAP & (1 << reg)) {
591                 outw(reg, chip->io_port + ESM_INDEX);
592                 chip->maestro_map[reg] = inw(chip->io_port + ESM_DATA);
593         }
594         return chip->maestro_map[reg];
595 }
596
597 static inline u16 maestro_read(struct es1968 *chip, u16 reg)
598 {
599         unsigned long flags;
600         u16 result;
601         spin_lock_irqsave(&chip->reg_lock, flags);
602         result = __maestro_read(chip, reg);
603         spin_unlock_irqrestore(&chip->reg_lock, flags);
604         return result;
605 }
606
607 /* Wait for the codec bus to be free */
608 static int snd_es1968_ac97_wait(struct es1968 *chip)
609 {
610         int timeout = 100000;
611
612         while (timeout-- > 0) {
613                 if (!(inb(chip->io_port + ESM_AC97_INDEX) & 1))
614                         return 0;
615                 cond_resched();
616         }
617         dev_dbg(chip->card->dev, "ac97 timeout\n");
618         return 1; /* timeout */
619 }
620
621 static int snd_es1968_ac97_wait_poll(struct es1968 *chip)
622 {
623         int timeout = 100000;
624
625         while (timeout-- > 0) {
626                 if (!(inb(chip->io_port + ESM_AC97_INDEX) & 1))
627                         return 0;
628         }
629         dev_dbg(chip->card->dev, "ac97 timeout\n");
630         return 1; /* timeout */
631 }
632
633 static void snd_es1968_ac97_write(struct snd_ac97 *ac97, unsigned short reg, unsigned short val)
634 {
635         struct es1968 *chip = ac97->private_data;
636
637         snd_es1968_ac97_wait(chip);
638
639         /* Write the bus */
640         outw(val, chip->io_port + ESM_AC97_DATA);
641         /*msleep(1);*/
642         outb(reg, chip->io_port + ESM_AC97_INDEX);
643         /*msleep(1);*/
644 }
645
646 static unsigned short snd_es1968_ac97_read(struct snd_ac97 *ac97, unsigned short reg)
647 {
648         u16 data = 0;
649         struct es1968 *chip = ac97->private_data;
650
651         snd_es1968_ac97_wait(chip);
652
653         outb(reg | 0x80, chip->io_port + ESM_AC97_INDEX);
654         /*msleep(1);*/
655
656         if (!snd_es1968_ac97_wait_poll(chip)) {
657                 data = inw(chip->io_port + ESM_AC97_DATA);
658                 /*msleep(1);*/
659         }
660
661         return data;
662 }
663
664 /* no spinlock */
665 static void apu_index_set(struct es1968 *chip, u16 index)
666 {
667         int i;
668         __maestro_write(chip, IDR1_CRAM_POINTER, index);
669         for (i = 0; i < 1000; i++)
670                 if (__maestro_read(chip, IDR1_CRAM_POINTER) == index)
671                         return;
672         dev_dbg(chip->card->dev, "APU register select failed. (Timeout)\n");
673 }
674
675 /* no spinlock */
676 static void apu_data_set(struct es1968 *chip, u16 data)
677 {
678         int i;
679         for (i = 0; i < 1000; i++) {
680                 if (__maestro_read(chip, IDR0_DATA_PORT) == data)
681                         return;
682                 __maestro_write(chip, IDR0_DATA_PORT, data);
683         }
684         dev_dbg(chip->card->dev, "APU register set probably failed (Timeout)!\n");
685 }
686
687 /* no spinlock */
688 static void __apu_set_register(struct es1968 *chip, u16 channel, u8 reg, u16 data)
689 {
690         if (snd_BUG_ON(channel >= NR_APUS))
691                 return;
692 #ifdef CONFIG_PM_SLEEP
693         chip->apu_map[channel][reg] = data;
694 #endif
695         reg |= (channel << 4);
696         apu_index_set(chip, reg);
697         apu_data_set(chip, data);
698 }
699
700 static void apu_set_register(struct es1968 *chip, u16 channel, u8 reg, u16 data)
701 {
702         unsigned long flags;
703         spin_lock_irqsave(&chip->reg_lock, flags);
704         __apu_set_register(chip, channel, reg, data);
705         spin_unlock_irqrestore(&chip->reg_lock, flags);
706 }
707
708 static u16 __apu_get_register(struct es1968 *chip, u16 channel, u8 reg)
709 {
710         if (snd_BUG_ON(channel >= NR_APUS))
711                 return 0;
712         reg |= (channel << 4);
713         apu_index_set(chip, reg);
714         return __maestro_read(chip, IDR0_DATA_PORT);
715 }
716
717 static u16 apu_get_register(struct es1968 *chip, u16 channel, u8 reg)
718 {
719         unsigned long flags;
720         u16 v;
721         spin_lock_irqsave(&chip->reg_lock, flags);
722         v = __apu_get_register(chip, channel, reg);
723         spin_unlock_irqrestore(&chip->reg_lock, flags);
724         return v;
725 }
726
727 #if 0 /* ASSP is not supported */
728
729 static void assp_set_register(struct es1968 *chip, u32 reg, u32 value)
730 {
731         unsigned long flags;
732
733         spin_lock_irqsave(&chip->reg_lock, flags);
734         outl(reg, chip->io_port + ASSP_INDEX);
735         outl(value, chip->io_port + ASSP_DATA);
736         spin_unlock_irqrestore(&chip->reg_lock, flags);
737 }
738
739 static u32 assp_get_register(struct es1968 *chip, u32 reg)
740 {
741         unsigned long flags;
742         u32 value;
743
744         spin_lock_irqsave(&chip->reg_lock, flags);
745         outl(reg, chip->io_port + ASSP_INDEX);
746         value = inl(chip->io_port + ASSP_DATA);
747         spin_unlock_irqrestore(&chip->reg_lock, flags);
748
749         return value;
750 }
751
752 #endif
753
754 static void wave_set_register(struct es1968 *chip, u16 reg, u16 value)
755 {
756         unsigned long flags;
757
758         spin_lock_irqsave(&chip->reg_lock, flags);
759         outw(reg, chip->io_port + WC_INDEX);
760         outw(value, chip->io_port + WC_DATA);
761         spin_unlock_irqrestore(&chip->reg_lock, flags);
762 }
763
764 static u16 wave_get_register(struct es1968 *chip, u16 reg)
765 {
766         unsigned long flags;
767         u16 value;
768
769         spin_lock_irqsave(&chip->reg_lock, flags);
770         outw(reg, chip->io_port + WC_INDEX);
771         value = inw(chip->io_port + WC_DATA);
772         spin_unlock_irqrestore(&chip->reg_lock, flags);
773
774         return value;
775 }
776
777 /* *******************
778    * Bob the Timer!  *
779    *******************/
780
781 static void snd_es1968_bob_stop(struct es1968 *chip)
782 {
783         u16 reg;
784
785         reg = __maestro_read(chip, 0x11);
786         reg &= ~ESM_BOB_ENABLE;
787         __maestro_write(chip, 0x11, reg);
788         reg = __maestro_read(chip, 0x17);
789         reg &= ~ESM_BOB_START;
790         __maestro_write(chip, 0x17, reg);
791 }
792
793 static void snd_es1968_bob_start(struct es1968 *chip)
794 {
795         int prescale;
796         int divide;
797
798         /* compute ideal interrupt frequency for buffer size & play rate */
799         /* first, find best prescaler value to match freq */
800         for (prescale = 5; prescale < 12; prescale++)
801                 if (chip->bob_freq > (ESS_SYSCLK >> (prescale + 9)))
802                         break;
803
804         /* next, back off prescaler whilst getting divider into optimum range */
805         divide = 1;
806         while ((prescale > 5) && (divide < 32)) {
807                 prescale--;
808                 divide <<= 1;
809         }
810         divide >>= 1;
811
812         /* now fine-tune the divider for best match */
813         for (; divide < 31; divide++)
814                 if (chip->bob_freq >
815                     ((ESS_SYSCLK >> (prescale + 9)) / (divide + 1))) break;
816
817         /* divide = 0 is illegal, but don't let prescale = 4! */
818         if (divide == 0) {
819                 divide++;
820                 if (prescale > 5)
821                         prescale--;
822         } else if (divide > 1)
823                 divide--;
824
825         __maestro_write(chip, 6, 0x9000 | (prescale << 5) | divide);    /* set reg */
826
827         /* Now set IDR 11/17 */
828         __maestro_write(chip, 0x11, __maestro_read(chip, 0x11) | 1);
829         __maestro_write(chip, 0x17, __maestro_read(chip, 0x17) | 1);
830 }
831
832 /* call with substream spinlock */
833 static void snd_es1968_bob_inc(struct es1968 *chip, int freq)
834 {
835         chip->bobclient++;
836         if (chip->bobclient == 1) {
837                 chip->bob_freq = freq;
838                 snd_es1968_bob_start(chip);
839         } else if (chip->bob_freq < freq) {
840                 snd_es1968_bob_stop(chip);
841                 chip->bob_freq = freq;
842                 snd_es1968_bob_start(chip);
843         }
844 }
845
846 /* call with substream spinlock */
847 static void snd_es1968_bob_dec(struct es1968 *chip)
848 {
849         chip->bobclient--;
850         if (chip->bobclient <= 0)
851                 snd_es1968_bob_stop(chip);
852         else if (chip->bob_freq > ESM_BOB_FREQ) {
853                 /* check reduction of timer frequency */
854                 int max_freq = ESM_BOB_FREQ;
855                 struct esschan *es;
856                 list_for_each_entry(es, &chip->substream_list, list) {
857                         if (max_freq < es->bob_freq)
858                                 max_freq = es->bob_freq;
859                 }
860                 if (max_freq != chip->bob_freq) {
861                         snd_es1968_bob_stop(chip);
862                         chip->bob_freq = max_freq;
863                         snd_es1968_bob_start(chip);
864                 }
865         }
866 }
867
868 static int
869 snd_es1968_calc_bob_rate(struct es1968 *chip, struct esschan *es,
870                          struct snd_pcm_runtime *runtime)
871 {
872         /* we acquire 4 interrupts per period for precise control.. */
873         int freq = runtime->rate * 4;
874         if (es->fmt & ESS_FMT_STEREO)
875                 freq <<= 1;
876         if (es->fmt & ESS_FMT_16BIT)
877                 freq <<= 1;
878         freq /= es->frag_size;
879         if (freq < ESM_BOB_FREQ)
880                 freq = ESM_BOB_FREQ;
881         else if (freq > ESM_BOB_FREQ_MAX)
882                 freq = ESM_BOB_FREQ_MAX;
883         return freq;
884 }
885
886
887 /*************
888  *  PCM Part *
889  *************/
890
891 static u32 snd_es1968_compute_rate(struct es1968 *chip, u32 freq)
892 {
893         u32 rate = (freq << 16) / chip->clock;
894 #if 0 /* XXX: do we need this? */ 
895         if (rate > 0x10000)
896                 rate = 0x10000;
897 #endif
898         return rate;
899 }
900
901 /* get current pointer */
902 static inline unsigned int
903 snd_es1968_get_dma_ptr(struct es1968 *chip, struct esschan *es)
904 {
905         unsigned int offset;
906
907         offset = apu_get_register(chip, es->apu[0], 5);
908
909         offset -= es->base[0];
910
911         return (offset & 0xFFFE);       /* hardware is in words */
912 }
913
914 static void snd_es1968_apu_set_freq(struct es1968 *chip, int apu, int freq)
915 {
916         apu_set_register(chip, apu, 2,
917                            (apu_get_register(chip, apu, 2) & 0x00FF) |
918                            ((freq & 0xff) << 8) | 0x10);
919         apu_set_register(chip, apu, 3, freq >> 8);
920 }
921
922 /* spin lock held */
923 static inline void snd_es1968_trigger_apu(struct es1968 *esm, int apu, int mode)
924 {
925         /* set the APU mode */
926         __apu_set_register(esm, apu, 0,
927                            (__apu_get_register(esm, apu, 0) & 0xff0f) |
928                            (mode << 4));
929 }
930
931 static void snd_es1968_pcm_start(struct es1968 *chip, struct esschan *es)
932 {
933         spin_lock(&chip->reg_lock);
934         __apu_set_register(chip, es->apu[0], 5, es->base[0]);
935         snd_es1968_trigger_apu(chip, es->apu[0], es->apu_mode[0]);
936         if (es->mode == ESM_MODE_CAPTURE) {
937                 __apu_set_register(chip, es->apu[2], 5, es->base[2]);
938                 snd_es1968_trigger_apu(chip, es->apu[2], es->apu_mode[2]);
939         }
940         if (es->fmt & ESS_FMT_STEREO) {
941                 __apu_set_register(chip, es->apu[1], 5, es->base[1]);
942                 snd_es1968_trigger_apu(chip, es->apu[1], es->apu_mode[1]);
943                 if (es->mode == ESM_MODE_CAPTURE) {
944                         __apu_set_register(chip, es->apu[3], 5, es->base[3]);
945                         snd_es1968_trigger_apu(chip, es->apu[3], es->apu_mode[3]);
946                 }
947         }
948         spin_unlock(&chip->reg_lock);
949 }
950
951 static void snd_es1968_pcm_stop(struct es1968 *chip, struct esschan *es)
952 {
953         spin_lock(&chip->reg_lock);
954         snd_es1968_trigger_apu(chip, es->apu[0], 0);
955         snd_es1968_trigger_apu(chip, es->apu[1], 0);
956         if (es->mode == ESM_MODE_CAPTURE) {
957                 snd_es1968_trigger_apu(chip, es->apu[2], 0);
958                 snd_es1968_trigger_apu(chip, es->apu[3], 0);
959         }
960         spin_unlock(&chip->reg_lock);
961 }
962
963 /* set the wavecache control reg */
964 static void snd_es1968_program_wavecache(struct es1968 *chip, struct esschan *es,
965                                          int channel, u32 addr, int capture)
966 {
967         u32 tmpval = (addr - 0x10) & 0xFFF8;
968
969         if (! capture) {
970                 if (!(es->fmt & ESS_FMT_16BIT))
971                         tmpval |= 4;    /* 8bit */
972                 if (es->fmt & ESS_FMT_STEREO)
973                         tmpval |= 2;    /* stereo */
974         }
975
976         /* set the wavecache control reg */
977         wave_set_register(chip, es->apu[channel] << 3, tmpval);
978
979 #ifdef CONFIG_PM_SLEEP
980         es->wc_map[channel] = tmpval;
981 #endif
982 }
983
984
985 static void snd_es1968_playback_setup(struct es1968 *chip, struct esschan *es,
986                                       struct snd_pcm_runtime *runtime)
987 {
988         u32 pa;
989         int high_apu = 0;
990         int channel, apu;
991         int i, size;
992         unsigned long flags;
993         u32 freq;
994
995         size = es->dma_size >> es->wav_shift;
996
997         if (es->fmt & ESS_FMT_STEREO)
998                 high_apu++;
999
1000         for (channel = 0; channel <= high_apu; channel++) {
1001                 apu = es->apu[channel];
1002
1003                 snd_es1968_program_wavecache(chip, es, channel, es->memory->buf.addr, 0);
1004
1005                 /* Offset to PCMBAR */
1006                 pa = es->memory->buf.addr;
1007                 pa -= chip->dma.addr;
1008                 pa >>= 1;       /* words */
1009
1010                 pa |= 0x00400000;       /* System RAM (Bit 22) */
1011
1012                 if (es->fmt & ESS_FMT_STEREO) {
1013                         /* Enable stereo */
1014                         if (channel)
1015                                 pa |= 0x00800000;       /* (Bit 23) */
1016                         if (es->fmt & ESS_FMT_16BIT)
1017                                 pa >>= 1;
1018                 }
1019
1020                 /* base offset of dma calcs when reading the pointer
1021                    on this left one */
1022                 es->base[channel] = pa & 0xFFFF;
1023
1024                 for (i = 0; i < 16; i++)
1025                         apu_set_register(chip, apu, i, 0x0000);
1026
1027                 /* Load the buffer into the wave engine */
1028                 apu_set_register(chip, apu, 4, ((pa >> 16) & 0xFF) << 8);
1029                 apu_set_register(chip, apu, 5, pa & 0xFFFF);
1030                 apu_set_register(chip, apu, 6, (pa + size) & 0xFFFF);
1031                 /* setting loop == sample len */
1032                 apu_set_register(chip, apu, 7, size);
1033
1034                 /* clear effects/env.. */
1035                 apu_set_register(chip, apu, 8, 0x0000);
1036                 /* set amp now to 0xd0 (?), low byte is 'amplitude dest'? */
1037                 apu_set_register(chip, apu, 9, 0xD000);
1038
1039                 /* clear routing stuff */
1040                 apu_set_register(chip, apu, 11, 0x0000);
1041                 /* dma on, no envelopes, filter to all 1s) */
1042                 apu_set_register(chip, apu, 0, 0x400F);
1043
1044                 if (es->fmt & ESS_FMT_16BIT)
1045                         es->apu_mode[channel] = ESM_APU_16BITLINEAR;
1046                 else
1047                         es->apu_mode[channel] = ESM_APU_8BITLINEAR;
1048
1049                 if (es->fmt & ESS_FMT_STEREO) {
1050                         /* set panning: left or right */
1051                         /* Check: different panning. On my Canyon 3D Chipset the
1052                            Channels are swapped. I don't know, about the output
1053                            to the SPDif Link. Perhaps you have to change this
1054                            and not the APU Regs 4-5. */
1055                         apu_set_register(chip, apu, 10,
1056                                          0x8F00 | (channel ? 0 : 0x10));
1057                         es->apu_mode[channel] += 1;     /* stereo */
1058                 } else
1059                         apu_set_register(chip, apu, 10, 0x8F08);
1060         }
1061
1062         spin_lock_irqsave(&chip->reg_lock, flags);
1063         /* clear WP interrupts */
1064         outw(1, chip->io_port + 0x04);
1065         /* enable WP ints */
1066         outw(inw(chip->io_port + ESM_PORT_HOST_IRQ) | ESM_HIRQ_DSIE, chip->io_port + ESM_PORT_HOST_IRQ);
1067         spin_unlock_irqrestore(&chip->reg_lock, flags);
1068
1069         freq = runtime->rate;
1070         /* set frequency */
1071         if (freq > 48000)
1072                 freq = 48000;
1073         if (freq < 4000)
1074                 freq = 4000;
1075
1076         /* hmmm.. */
1077         if (!(es->fmt & ESS_FMT_16BIT) && !(es->fmt & ESS_FMT_STEREO))
1078                 freq >>= 1;
1079
1080         freq = snd_es1968_compute_rate(chip, freq);
1081
1082         /* Load the frequency, turn on 6dB */
1083         snd_es1968_apu_set_freq(chip, es->apu[0], freq);
1084         snd_es1968_apu_set_freq(chip, es->apu[1], freq);
1085 }
1086
1087
1088 static void init_capture_apu(struct es1968 *chip, struct esschan *es, int channel,
1089                              unsigned int pa, unsigned int bsize,
1090                              int mode, int route)
1091 {
1092         int i, apu = es->apu[channel];
1093
1094         es->apu_mode[channel] = mode;
1095
1096         /* set the wavecache control reg */
1097         snd_es1968_program_wavecache(chip, es, channel, pa, 1);
1098
1099         /* Offset to PCMBAR */
1100         pa -= chip->dma.addr;
1101         pa >>= 1;       /* words */
1102
1103         /* base offset of dma calcs when reading the pointer
1104            on this left one */
1105         es->base[channel] = pa & 0xFFFF;
1106         pa |= 0x00400000;       /* bit 22 -> System RAM */
1107
1108         /* Begin loading the APU */
1109         for (i = 0; i < 16; i++)
1110                 apu_set_register(chip, apu, i, 0x0000);
1111
1112         /* need to enable subgroups.. and we should probably
1113            have different groups for different /dev/dsps..  */
1114         apu_set_register(chip, apu, 2, 0x8);
1115
1116         /* Load the buffer into the wave engine */
1117         apu_set_register(chip, apu, 4, ((pa >> 16) & 0xFF) << 8);
1118         apu_set_register(chip, apu, 5, pa & 0xFFFF);
1119         apu_set_register(chip, apu, 6, (pa + bsize) & 0xFFFF);
1120         apu_set_register(chip, apu, 7, bsize);
1121         /* clear effects/env.. */
1122         apu_set_register(chip, apu, 8, 0x00F0);
1123         /* amplitude now?  sure.  why not.  */
1124         apu_set_register(chip, apu, 9, 0x0000);
1125         /* set filter tune, radius, polar pan */
1126         apu_set_register(chip, apu, 10, 0x8F08);
1127         /* route input */
1128         apu_set_register(chip, apu, 11, route);
1129         /* dma on, no envelopes, filter to all 1s) */
1130         apu_set_register(chip, apu, 0, 0x400F);
1131 }
1132
1133 static void snd_es1968_capture_setup(struct es1968 *chip, struct esschan *es,
1134                                      struct snd_pcm_runtime *runtime)
1135 {
1136         int size;
1137         u32 freq;
1138         unsigned long flags;
1139
1140         size = es->dma_size >> es->wav_shift;
1141
1142         /* APU assignments:
1143            0 = mono/left SRC
1144            1 = right SRC
1145            2 = mono/left Input Mixer
1146            3 = right Input Mixer
1147         */
1148         /* data seems to flow from the codec, through an apu into
1149            the 'mixbuf' bit of page, then through the SRC apu
1150            and out to the real 'buffer'.  ok.  sure.  */
1151
1152         /* input mixer (left/mono) */
1153         /* parallel in crap, see maestro reg 0xC [8-11] */
1154         init_capture_apu(chip, es, 2,
1155                          es->mixbuf->buf.addr, ESM_MIXBUF_SIZE/4, /* in words */
1156                          ESM_APU_INPUTMIXER, 0x14);
1157         /* SRC (left/mono); get input from inputing apu */
1158         init_capture_apu(chip, es, 0, es->memory->buf.addr, size,
1159                          ESM_APU_SRCONVERTOR, es->apu[2]);
1160         if (es->fmt & ESS_FMT_STEREO) {
1161                 /* input mixer (right) */
1162                 init_capture_apu(chip, es, 3,
1163                                  es->mixbuf->buf.addr + ESM_MIXBUF_SIZE/2,
1164                                  ESM_MIXBUF_SIZE/4, /* in words */
1165                                  ESM_APU_INPUTMIXER, 0x15);
1166                 /* SRC (right) */
1167                 init_capture_apu(chip, es, 1,
1168                                  es->memory->buf.addr + size*2, size,
1169                                  ESM_APU_SRCONVERTOR, es->apu[3]);
1170         }
1171
1172         freq = runtime->rate;
1173         /* Sample Rate conversion APUs don't like 0x10000 for their rate */
1174         if (freq > 47999)
1175                 freq = 47999;
1176         if (freq < 4000)
1177                 freq = 4000;
1178
1179         freq = snd_es1968_compute_rate(chip, freq);
1180
1181         /* Load the frequency, turn on 6dB */
1182         snd_es1968_apu_set_freq(chip, es->apu[0], freq);
1183         snd_es1968_apu_set_freq(chip, es->apu[1], freq);
1184
1185         /* fix mixer rate at 48khz.  and its _must_ be 0x10000. */
1186         freq = 0x10000;
1187         snd_es1968_apu_set_freq(chip, es->apu[2], freq);
1188         snd_es1968_apu_set_freq(chip, es->apu[3], freq);
1189
1190         spin_lock_irqsave(&chip->reg_lock, flags);
1191         /* clear WP interrupts */
1192         outw(1, chip->io_port + 0x04);
1193         /* enable WP ints */
1194         outw(inw(chip->io_port + ESM_PORT_HOST_IRQ) | ESM_HIRQ_DSIE, chip->io_port + ESM_PORT_HOST_IRQ);
1195         spin_unlock_irqrestore(&chip->reg_lock, flags);
1196 }
1197
1198 /*******************
1199  *  ALSA Interface *
1200  *******************/
1201
1202 static int snd_es1968_pcm_prepare(struct snd_pcm_substream *substream)
1203 {
1204         struct es1968 *chip = snd_pcm_substream_chip(substream);
1205         struct snd_pcm_runtime *runtime = substream->runtime;
1206         struct esschan *es = runtime->private_data;
1207
1208         es->dma_size = snd_pcm_lib_buffer_bytes(substream);
1209         es->frag_size = snd_pcm_lib_period_bytes(substream);
1210
1211         es->wav_shift = 1; /* maestro handles always 16bit */
1212         es->fmt = 0;
1213         if (snd_pcm_format_width(runtime->format) == 16)
1214                 es->fmt |= ESS_FMT_16BIT;
1215         if (runtime->channels > 1) {
1216                 es->fmt |= ESS_FMT_STEREO;
1217                 if (es->fmt & ESS_FMT_16BIT) /* 8bit is already word shifted */
1218                         es->wav_shift++;
1219         }
1220         es->bob_freq = snd_es1968_calc_bob_rate(chip, es, runtime);
1221
1222         switch (es->mode) {
1223         case ESM_MODE_PLAY:
1224                 snd_es1968_playback_setup(chip, es, runtime);
1225                 break;
1226         case ESM_MODE_CAPTURE:
1227                 snd_es1968_capture_setup(chip, es, runtime);
1228                 break;
1229         }
1230
1231         return 0;
1232 }
1233
1234 static int snd_es1968_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
1235 {
1236         struct es1968 *chip = snd_pcm_substream_chip(substream);
1237         struct esschan *es = substream->runtime->private_data;
1238
1239         spin_lock(&chip->substream_lock);
1240         switch (cmd) {
1241         case SNDRV_PCM_TRIGGER_START:
1242         case SNDRV_PCM_TRIGGER_RESUME:
1243                 if (es->running)
1244                         break;
1245                 snd_es1968_bob_inc(chip, es->bob_freq);
1246                 es->count = 0;
1247                 es->hwptr = 0;
1248                 snd_es1968_pcm_start(chip, es);
1249                 es->running = 1;
1250                 break;
1251         case SNDRV_PCM_TRIGGER_STOP:
1252         case SNDRV_PCM_TRIGGER_SUSPEND:
1253                 if (! es->running)
1254                         break;
1255                 snd_es1968_pcm_stop(chip, es);
1256                 es->running = 0;
1257                 snd_es1968_bob_dec(chip);
1258                 break;
1259         }
1260         spin_unlock(&chip->substream_lock);
1261         return 0;
1262 }
1263
1264 static snd_pcm_uframes_t snd_es1968_pcm_pointer(struct snd_pcm_substream *substream)
1265 {
1266         struct es1968 *chip = snd_pcm_substream_chip(substream);
1267         struct esschan *es = substream->runtime->private_data;
1268         unsigned int ptr;
1269
1270         ptr = snd_es1968_get_dma_ptr(chip, es) << es->wav_shift;
1271         
1272         return bytes_to_frames(substream->runtime, ptr % es->dma_size);
1273 }
1274
1275 static const struct snd_pcm_hardware snd_es1968_playback = {
1276         .info =                 (SNDRV_PCM_INFO_MMAP |
1277                                  SNDRV_PCM_INFO_MMAP_VALID |
1278                                  SNDRV_PCM_INFO_INTERLEAVED |
1279                                  SNDRV_PCM_INFO_BLOCK_TRANSFER |
1280                                  /*SNDRV_PCM_INFO_PAUSE |*/
1281                                  SNDRV_PCM_INFO_RESUME),
1282         .formats =              SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
1283         .rates =                SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
1284         .rate_min =             4000,
1285         .rate_max =             48000,
1286         .channels_min =         1,
1287         .channels_max =         2,
1288         .buffer_bytes_max =     65536,
1289         .period_bytes_min =     256,
1290         .period_bytes_max =     65536,
1291         .periods_min =          1,
1292         .periods_max =          1024,
1293         .fifo_size =            0,
1294 };
1295
1296 static const struct snd_pcm_hardware snd_es1968_capture = {
1297         .info =                 (SNDRV_PCM_INFO_NONINTERLEAVED |
1298                                  SNDRV_PCM_INFO_MMAP |
1299                                  SNDRV_PCM_INFO_MMAP_VALID |
1300                                  SNDRV_PCM_INFO_BLOCK_TRANSFER |
1301                                  /*SNDRV_PCM_INFO_PAUSE |*/
1302                                  SNDRV_PCM_INFO_RESUME),
1303         .formats =              /*SNDRV_PCM_FMTBIT_U8 |*/ SNDRV_PCM_FMTBIT_S16_LE,
1304         .rates =                SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
1305         .rate_min =             4000,
1306         .rate_max =             48000,
1307         .channels_min =         1,
1308         .channels_max =         2,
1309         .buffer_bytes_max =     65536,
1310         .period_bytes_min =     256,
1311         .period_bytes_max =     65536,
1312         .periods_min =          1,
1313         .periods_max =          1024,
1314         .fifo_size =            0,
1315 };
1316
1317 /* *************************
1318    * DMA memory management *
1319    *************************/
1320
1321 /* Because the Maestro can only take addresses relative to the PCM base address
1322    register :( */
1323
1324 static int calc_available_memory_size(struct es1968 *chip)
1325 {
1326         int max_size = 0;
1327         struct esm_memory *buf;
1328
1329         mutex_lock(&chip->memory_mutex);
1330         list_for_each_entry(buf, &chip->buf_list, list) {
1331                 if (buf->empty && buf->buf.bytes > max_size)
1332                         max_size = buf->buf.bytes;
1333         }
1334         mutex_unlock(&chip->memory_mutex);
1335         if (max_size >= 128*1024)
1336                 max_size = 127*1024;
1337         return max_size;
1338 }
1339
1340 /* allocate a new memory chunk with the specified size */
1341 static struct esm_memory *snd_es1968_new_memory(struct es1968 *chip, int size)
1342 {
1343         struct esm_memory *buf;
1344
1345         size = ALIGN(size, ESM_MEM_ALIGN);
1346         mutex_lock(&chip->memory_mutex);
1347         list_for_each_entry(buf, &chip->buf_list, list) {
1348                 if (buf->empty && buf->buf.bytes >= size)
1349                         goto __found;
1350         }
1351         mutex_unlock(&chip->memory_mutex);
1352         return NULL;
1353
1354 __found:
1355         if (buf->buf.bytes > size) {
1356                 struct esm_memory *chunk = kmalloc(sizeof(*chunk), GFP_KERNEL);
1357                 if (chunk == NULL) {
1358                         mutex_unlock(&chip->memory_mutex);
1359                         return NULL;
1360                 }
1361                 chunk->buf = buf->buf;
1362                 chunk->buf.bytes -= size;
1363                 chunk->buf.area += size;
1364                 chunk->buf.addr += size;
1365                 chunk->empty = 1;
1366                 buf->buf.bytes = size;
1367                 list_add(&chunk->list, &buf->list);
1368         }
1369         buf->empty = 0;
1370         mutex_unlock(&chip->memory_mutex);
1371         return buf;
1372 }
1373
1374 /* free a memory chunk */
1375 static void snd_es1968_free_memory(struct es1968 *chip, struct esm_memory *buf)
1376 {
1377         struct esm_memory *chunk;
1378
1379         mutex_lock(&chip->memory_mutex);
1380         buf->empty = 1;
1381         if (buf->list.prev != &chip->buf_list) {
1382                 chunk = list_entry(buf->list.prev, struct esm_memory, list);
1383                 if (chunk->empty) {
1384                         chunk->buf.bytes += buf->buf.bytes;
1385                         list_del(&buf->list);
1386                         kfree(buf);
1387                         buf = chunk;
1388                 }
1389         }
1390         if (buf->list.next != &chip->buf_list) {
1391                 chunk = list_entry(buf->list.next, struct esm_memory, list);
1392                 if (chunk->empty) {
1393                         buf->buf.bytes += chunk->buf.bytes;
1394                         list_del(&chunk->list);
1395                         kfree(chunk);
1396                 }
1397         }
1398         mutex_unlock(&chip->memory_mutex);
1399 }
1400
1401 static void snd_es1968_free_dmabuf(struct es1968 *chip)
1402 {
1403         struct list_head *p;
1404
1405         if (! chip->dma.area)
1406                 return;
1407         snd_dma_free_pages(&chip->dma);
1408         while ((p = chip->buf_list.next) != &chip->buf_list) {
1409                 struct esm_memory *chunk = list_entry(p, struct esm_memory, list);
1410                 list_del(p);
1411                 kfree(chunk);
1412         }
1413 }
1414
1415 static int
1416 snd_es1968_init_dmabuf(struct es1968 *chip)
1417 {
1418         int err;
1419         struct esm_memory *chunk;
1420
1421         err = snd_dma_alloc_pages_fallback(SNDRV_DMA_TYPE_DEV,
1422                                            &chip->pci->dev,
1423                                            chip->total_bufsize, &chip->dma);
1424         if (err < 0 || ! chip->dma.area) {
1425                 dev_err(chip->card->dev,
1426                         "can't allocate dma pages for size %d\n",
1427                            chip->total_bufsize);
1428                 return -ENOMEM;
1429         }
1430         if ((chip->dma.addr + chip->dma.bytes - 1) & ~((1 << 28) - 1)) {
1431                 snd_dma_free_pages(&chip->dma);
1432                 dev_err(chip->card->dev, "DMA buffer beyond 256MB.\n");
1433                 return -ENOMEM;
1434         }
1435
1436         INIT_LIST_HEAD(&chip->buf_list);
1437         /* allocate an empty chunk */
1438         chunk = kmalloc(sizeof(*chunk), GFP_KERNEL);
1439         if (chunk == NULL) {
1440                 snd_es1968_free_dmabuf(chip);
1441                 return -ENOMEM;
1442         }
1443         memset(chip->dma.area, 0, ESM_MEM_ALIGN);
1444         chunk->buf = chip->dma;
1445         chunk->buf.area += ESM_MEM_ALIGN;
1446         chunk->buf.addr += ESM_MEM_ALIGN;
1447         chunk->buf.bytes -= ESM_MEM_ALIGN;
1448         chunk->empty = 1;
1449         list_add(&chunk->list, &chip->buf_list);
1450
1451         return 0;
1452 }
1453
1454 /* setup the dma_areas */
1455 /* buffer is extracted from the pre-allocated memory chunk */
1456 static int snd_es1968_hw_params(struct snd_pcm_substream *substream,
1457                                 struct snd_pcm_hw_params *hw_params)
1458 {
1459         struct es1968 *chip = snd_pcm_substream_chip(substream);
1460         struct snd_pcm_runtime *runtime = substream->runtime;
1461         struct esschan *chan = runtime->private_data;
1462         int size = params_buffer_bytes(hw_params);
1463
1464         if (chan->memory) {
1465                 if (chan->memory->buf.bytes >= size) {
1466                         runtime->dma_bytes = size;
1467                         return 0;
1468                 }
1469                 snd_es1968_free_memory(chip, chan->memory);
1470         }
1471         chan->memory = snd_es1968_new_memory(chip, size);
1472         if (chan->memory == NULL) {
1473                 dev_dbg(chip->card->dev,
1474                         "cannot allocate dma buffer: size = %d\n", size);
1475                 return -ENOMEM;
1476         }
1477         snd_pcm_set_runtime_buffer(substream, &chan->memory->buf);
1478         return 1; /* area was changed */
1479 }
1480
1481 /* remove dma areas if allocated */
1482 static int snd_es1968_hw_free(struct snd_pcm_substream *substream)
1483 {
1484         struct es1968 *chip = snd_pcm_substream_chip(substream);
1485         struct snd_pcm_runtime *runtime = substream->runtime;
1486         struct esschan *chan;
1487         
1488         if (runtime->private_data == NULL)
1489                 return 0;
1490         chan = runtime->private_data;
1491         if (chan->memory) {
1492                 snd_es1968_free_memory(chip, chan->memory);
1493                 chan->memory = NULL;
1494         }
1495         return 0;
1496 }
1497
1498
1499 /*
1500  * allocate APU pair
1501  */
1502 static int snd_es1968_alloc_apu_pair(struct es1968 *chip, int type)
1503 {
1504         int apu;
1505
1506         for (apu = 0; apu < NR_APUS; apu += 2) {
1507                 if (chip->apu[apu] == ESM_APU_FREE &&
1508                     chip->apu[apu + 1] == ESM_APU_FREE) {
1509                         chip->apu[apu] = chip->apu[apu + 1] = type;
1510                         return apu;
1511                 }
1512         }
1513         return -EBUSY;
1514 }
1515
1516 /*
1517  * release APU pair
1518  */
1519 static void snd_es1968_free_apu_pair(struct es1968 *chip, int apu)
1520 {
1521         chip->apu[apu] = chip->apu[apu + 1] = ESM_APU_FREE;
1522 }
1523
1524
1525 /******************
1526  * PCM open/close *
1527  ******************/
1528
1529 static int snd_es1968_playback_open(struct snd_pcm_substream *substream)
1530 {
1531         struct es1968 *chip = snd_pcm_substream_chip(substream);
1532         struct snd_pcm_runtime *runtime = substream->runtime;
1533         struct esschan *es;
1534         int apu1;
1535
1536         /* search 2 APUs */
1537         apu1 = snd_es1968_alloc_apu_pair(chip, ESM_APU_PCM_PLAY);
1538         if (apu1 < 0)
1539                 return apu1;
1540
1541         es = kzalloc(sizeof(*es), GFP_KERNEL);
1542         if (!es) {
1543                 snd_es1968_free_apu_pair(chip, apu1);
1544                 return -ENOMEM;
1545         }
1546
1547         es->apu[0] = apu1;
1548         es->apu[1] = apu1 + 1;
1549         es->apu_mode[0] = 0;
1550         es->apu_mode[1] = 0;
1551         es->running = 0;
1552         es->substream = substream;
1553         es->mode = ESM_MODE_PLAY;
1554
1555         runtime->private_data = es;
1556         runtime->hw = snd_es1968_playback;
1557         runtime->hw.buffer_bytes_max = runtime->hw.period_bytes_max =
1558                 calc_available_memory_size(chip);
1559
1560         spin_lock_irq(&chip->substream_lock);
1561         list_add(&es->list, &chip->substream_list);
1562         spin_unlock_irq(&chip->substream_lock);
1563
1564         return 0;
1565 }
1566
1567 static int snd_es1968_capture_open(struct snd_pcm_substream *substream)
1568 {
1569         struct snd_pcm_runtime *runtime = substream->runtime;
1570         struct es1968 *chip = snd_pcm_substream_chip(substream);
1571         struct esschan *es;
1572         int apu1, apu2;
1573
1574         apu1 = snd_es1968_alloc_apu_pair(chip, ESM_APU_PCM_CAPTURE);
1575         if (apu1 < 0)
1576                 return apu1;
1577         apu2 = snd_es1968_alloc_apu_pair(chip, ESM_APU_PCM_RATECONV);
1578         if (apu2 < 0) {
1579                 snd_es1968_free_apu_pair(chip, apu1);
1580                 return apu2;
1581         }
1582         
1583         es = kzalloc(sizeof(*es), GFP_KERNEL);
1584         if (!es) {
1585                 snd_es1968_free_apu_pair(chip, apu1);
1586                 snd_es1968_free_apu_pair(chip, apu2);
1587                 return -ENOMEM;
1588         }
1589
1590         es->apu[0] = apu1;
1591         es->apu[1] = apu1 + 1;
1592         es->apu[2] = apu2;
1593         es->apu[3] = apu2 + 1;
1594         es->apu_mode[0] = 0;
1595         es->apu_mode[1] = 0;
1596         es->apu_mode[2] = 0;
1597         es->apu_mode[3] = 0;
1598         es->running = 0;
1599         es->substream = substream;
1600         es->mode = ESM_MODE_CAPTURE;
1601
1602         /* get mixbuffer */
1603         es->mixbuf = snd_es1968_new_memory(chip, ESM_MIXBUF_SIZE);
1604         if (!es->mixbuf) {
1605                 snd_es1968_free_apu_pair(chip, apu1);
1606                 snd_es1968_free_apu_pair(chip, apu2);
1607                 kfree(es);
1608                 return -ENOMEM;
1609         }
1610         memset(es->mixbuf->buf.area, 0, ESM_MIXBUF_SIZE);
1611
1612         runtime->private_data = es;
1613         runtime->hw = snd_es1968_capture;
1614         runtime->hw.buffer_bytes_max = runtime->hw.period_bytes_max =
1615                 calc_available_memory_size(chip) - 1024; /* keep MIXBUF size */
1616         snd_pcm_hw_constraint_pow2(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_BYTES);
1617
1618         spin_lock_irq(&chip->substream_lock);
1619         list_add(&es->list, &chip->substream_list);
1620         spin_unlock_irq(&chip->substream_lock);
1621
1622         return 0;
1623 }
1624
1625 static int snd_es1968_playback_close(struct snd_pcm_substream *substream)
1626 {
1627         struct es1968 *chip = snd_pcm_substream_chip(substream);
1628         struct esschan *es;
1629
1630         if (substream->runtime->private_data == NULL)
1631                 return 0;
1632         es = substream->runtime->private_data;
1633         spin_lock_irq(&chip->substream_lock);
1634         list_del(&es->list);
1635         spin_unlock_irq(&chip->substream_lock);
1636         snd_es1968_free_apu_pair(chip, es->apu[0]);
1637         kfree(es);
1638
1639         return 0;
1640 }
1641
1642 static int snd_es1968_capture_close(struct snd_pcm_substream *substream)
1643 {
1644         struct es1968 *chip = snd_pcm_substream_chip(substream);
1645         struct esschan *es;
1646
1647         if (substream->runtime->private_data == NULL)
1648                 return 0;
1649         es = substream->runtime->private_data;
1650         spin_lock_irq(&chip->substream_lock);
1651         list_del(&es->list);
1652         spin_unlock_irq(&chip->substream_lock);
1653         snd_es1968_free_memory(chip, es->mixbuf);
1654         snd_es1968_free_apu_pair(chip, es->apu[0]);
1655         snd_es1968_free_apu_pair(chip, es->apu[2]);
1656         kfree(es);
1657
1658         return 0;
1659 }
1660
1661 static const struct snd_pcm_ops snd_es1968_playback_ops = {
1662         .open =         snd_es1968_playback_open,
1663         .close =        snd_es1968_playback_close,
1664         .hw_params =    snd_es1968_hw_params,
1665         .hw_free =      snd_es1968_hw_free,
1666         .prepare =      snd_es1968_pcm_prepare,
1667         .trigger =      snd_es1968_pcm_trigger,
1668         .pointer =      snd_es1968_pcm_pointer,
1669 };
1670
1671 static const struct snd_pcm_ops snd_es1968_capture_ops = {
1672         .open =         snd_es1968_capture_open,
1673         .close =        snd_es1968_capture_close,
1674         .hw_params =    snd_es1968_hw_params,
1675         .hw_free =      snd_es1968_hw_free,
1676         .prepare =      snd_es1968_pcm_prepare,
1677         .trigger =      snd_es1968_pcm_trigger,
1678         .pointer =      snd_es1968_pcm_pointer,
1679 };
1680
1681
1682 /*
1683  * measure clock
1684  */
1685 #define CLOCK_MEASURE_BUFSIZE   16768   /* enough large for a single shot */
1686
1687 static void es1968_measure_clock(struct es1968 *chip)
1688 {
1689         int i, apu;
1690         unsigned int pa, offset, t;
1691         struct esm_memory *memory;
1692         ktime_t start_time, stop_time;
1693         ktime_t diff;
1694
1695         if (chip->clock == 0)
1696                 chip->clock = 48000; /* default clock value */
1697
1698         /* search 2 APUs (although one apu is enough) */
1699         apu = snd_es1968_alloc_apu_pair(chip, ESM_APU_PCM_PLAY);
1700         if (apu < 0) {
1701                 dev_err(chip->card->dev, "Hmm, cannot find empty APU pair!?\n");
1702                 return;
1703         }
1704         memory = snd_es1968_new_memory(chip, CLOCK_MEASURE_BUFSIZE);
1705         if (!memory) {
1706                 dev_warn(chip->card->dev,
1707                          "cannot allocate dma buffer - using default clock %d\n",
1708                          chip->clock);
1709                 snd_es1968_free_apu_pair(chip, apu);
1710                 return;
1711         }
1712
1713         memset(memory->buf.area, 0, CLOCK_MEASURE_BUFSIZE);
1714
1715         wave_set_register(chip, apu << 3, (memory->buf.addr - 0x10) & 0xfff8);
1716
1717         pa = (unsigned int)((memory->buf.addr - chip->dma.addr) >> 1);
1718         pa |= 0x00400000;       /* System RAM (Bit 22) */
1719
1720         /* initialize apu */
1721         for (i = 0; i < 16; i++)
1722                 apu_set_register(chip, apu, i, 0x0000);
1723
1724         apu_set_register(chip, apu, 0, 0x400f);
1725         apu_set_register(chip, apu, 4, ((pa >> 16) & 0xff) << 8);
1726         apu_set_register(chip, apu, 5, pa & 0xffff);
1727         apu_set_register(chip, apu, 6, (pa + CLOCK_MEASURE_BUFSIZE/2) & 0xffff);
1728         apu_set_register(chip, apu, 7, CLOCK_MEASURE_BUFSIZE/2);
1729         apu_set_register(chip, apu, 8, 0x0000);
1730         apu_set_register(chip, apu, 9, 0xD000);
1731         apu_set_register(chip, apu, 10, 0x8F08);
1732         apu_set_register(chip, apu, 11, 0x0000);
1733         spin_lock_irq(&chip->reg_lock);
1734         outw(1, chip->io_port + 0x04); /* clear WP interrupts */
1735         outw(inw(chip->io_port + ESM_PORT_HOST_IRQ) | ESM_HIRQ_DSIE, chip->io_port + ESM_PORT_HOST_IRQ); /* enable WP ints */
1736         spin_unlock_irq(&chip->reg_lock);
1737
1738         snd_es1968_apu_set_freq(chip, apu, ((unsigned int)48000 << 16) / chip->clock); /* 48000 Hz */
1739
1740         chip->in_measurement = 1;
1741         chip->measure_apu = apu;
1742         spin_lock_irq(&chip->reg_lock);
1743         snd_es1968_bob_inc(chip, ESM_BOB_FREQ);
1744         __apu_set_register(chip, apu, 5, pa & 0xffff);
1745         snd_es1968_trigger_apu(chip, apu, ESM_APU_16BITLINEAR);
1746         start_time = ktime_get();
1747         spin_unlock_irq(&chip->reg_lock);
1748         msleep(50);
1749         spin_lock_irq(&chip->reg_lock);
1750         offset = __apu_get_register(chip, apu, 5);
1751         stop_time = ktime_get();
1752         snd_es1968_trigger_apu(chip, apu, 0); /* stop */
1753         snd_es1968_bob_dec(chip);
1754         chip->in_measurement = 0;
1755         spin_unlock_irq(&chip->reg_lock);
1756
1757         /* check the current position */
1758         offset -= (pa & 0xffff);
1759         offset &= 0xfffe;
1760         offset += chip->measure_count * (CLOCK_MEASURE_BUFSIZE/2);
1761
1762         diff = ktime_sub(stop_time, start_time);
1763         t = ktime_to_us(diff);
1764         if (t == 0) {
1765                 dev_err(chip->card->dev, "?? calculation error..\n");
1766         } else {
1767                 offset *= 1000;
1768                 offset = (offset / t) * 1000 + ((offset % t) * 1000) / t;
1769                 if (offset < 47500 || offset > 48500) {
1770                         if (offset >= 40000 && offset <= 50000)
1771                                 chip->clock = (chip->clock * offset) / 48000;
1772                 }
1773                 dev_info(chip->card->dev, "clocking to %d\n", chip->clock);
1774         }
1775         snd_es1968_free_memory(chip, memory);
1776         snd_es1968_free_apu_pair(chip, apu);
1777 }
1778
1779
1780 /*
1781  */
1782
1783 static void snd_es1968_pcm_free(struct snd_pcm *pcm)
1784 {
1785         struct es1968 *esm = pcm->private_data;
1786         snd_es1968_free_dmabuf(esm);
1787         esm->pcm = NULL;
1788 }
1789
1790 static int
1791 snd_es1968_pcm(struct es1968 *chip, int device)
1792 {
1793         struct snd_pcm *pcm;
1794         int err;
1795
1796         /* get DMA buffer */
1797         err = snd_es1968_init_dmabuf(chip);
1798         if (err < 0)
1799                 return err;
1800
1801         /* set PCMBAR */
1802         wave_set_register(chip, 0x01FC, chip->dma.addr >> 12);
1803         wave_set_register(chip, 0x01FD, chip->dma.addr >> 12);
1804         wave_set_register(chip, 0x01FE, chip->dma.addr >> 12);
1805         wave_set_register(chip, 0x01FF, chip->dma.addr >> 12);
1806
1807         err = snd_pcm_new(chip->card, "ESS Maestro", device,
1808                           chip->playback_streams,
1809                           chip->capture_streams, &pcm);
1810         if (err < 0)
1811                 return err;
1812
1813         pcm->private_data = chip;
1814         pcm->private_free = snd_es1968_pcm_free;
1815
1816         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_es1968_playback_ops);
1817         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_es1968_capture_ops);
1818
1819         pcm->info_flags = 0;
1820
1821         strcpy(pcm->name, "ESS Maestro");
1822
1823         chip->pcm = pcm;
1824
1825         return 0;
1826 }
1827 /*
1828  * suppress jitter on some maestros when playing stereo
1829  */
1830 static void snd_es1968_suppress_jitter(struct es1968 *chip, struct esschan *es)
1831 {
1832         unsigned int cp1;
1833         unsigned int cp2;
1834         unsigned int diff;
1835
1836         cp1 = __apu_get_register(chip, 0, 5);
1837         cp2 = __apu_get_register(chip, 1, 5);
1838         diff = (cp1 > cp2 ? cp1 - cp2 : cp2 - cp1);
1839
1840         if (diff > 1)
1841                 __maestro_write(chip, IDR0_DATA_PORT, cp1);
1842 }
1843
1844 /*
1845  * update pointer
1846  */
1847 static void snd_es1968_update_pcm(struct es1968 *chip, struct esschan *es)
1848 {
1849         unsigned int hwptr;
1850         unsigned int diff;
1851         struct snd_pcm_substream *subs = es->substream;
1852         
1853         if (subs == NULL || !es->running)
1854                 return;
1855
1856         hwptr = snd_es1968_get_dma_ptr(chip, es) << es->wav_shift;
1857         hwptr %= es->dma_size;
1858
1859         diff = (es->dma_size + hwptr - es->hwptr) % es->dma_size;
1860
1861         es->hwptr = hwptr;
1862         es->count += diff;
1863
1864         if (es->count > es->frag_size) {
1865                 spin_unlock(&chip->substream_lock);
1866                 snd_pcm_period_elapsed(subs);
1867                 spin_lock(&chip->substream_lock);
1868                 es->count %= es->frag_size;
1869         }
1870 }
1871
1872 /* The hardware volume works by incrementing / decrementing 2 counters
1873    (without wrap around) in response to volume button presses and then
1874    generating an interrupt. The pair of counters is stored in bits 1-3 and 5-7
1875    of a byte wide register. The meaning of bits 0 and 4 is unknown. */
1876 static void es1968_update_hw_volume(struct work_struct *work)
1877 {
1878         struct es1968 *chip = container_of(work, struct es1968, hwvol_work);
1879         int x, val;
1880
1881         /* Figure out which volume control button was pushed,
1882            based on differences from the default register
1883            values. */
1884         x = inb(chip->io_port + 0x1c) & 0xee;
1885         /* Reset the volume control registers. */
1886         outb(0x88, chip->io_port + 0x1c);
1887         outb(0x88, chip->io_port + 0x1d);
1888         outb(0x88, chip->io_port + 0x1e);
1889         outb(0x88, chip->io_port + 0x1f);
1890
1891         if (chip->in_suspend)
1892                 return;
1893
1894 #ifndef CONFIG_SND_ES1968_INPUT
1895         if (! chip->master_switch || ! chip->master_volume)
1896                 return;
1897
1898         val = snd_ac97_read(chip->ac97, AC97_MASTER);
1899         switch (x) {
1900         case 0x88:
1901                 /* mute */
1902                 val ^= 0x8000;
1903                 break;
1904         case 0xaa:
1905                 /* volume up */
1906                 if ((val & 0x7f) > 0)
1907                         val--;
1908                 if ((val & 0x7f00) > 0)
1909                         val -= 0x0100;
1910                 break;
1911         case 0x66:
1912                 /* volume down */
1913                 if ((val & 0x7f) < 0x1f)
1914                         val++;
1915                 if ((val & 0x7f00) < 0x1f00)
1916                         val += 0x0100;
1917                 break;
1918         }
1919         if (snd_ac97_update(chip->ac97, AC97_MASTER, val))
1920                 snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
1921                                &chip->master_volume->id);
1922 #else
1923         if (!chip->input_dev)
1924                 return;
1925
1926         val = 0;
1927         switch (x) {
1928         case 0x88:
1929                 /* The counters have not changed, yet we've received a HV
1930                    interrupt. According to tests run by various people this
1931                    happens when pressing the mute button. */
1932                 val = KEY_MUTE;
1933                 break;
1934         case 0xaa:
1935                 /* counters increased by 1 -> volume up */
1936                 val = KEY_VOLUMEUP;
1937                 break;
1938         case 0x66:
1939                 /* counters decreased by 1 -> volume down */
1940                 val = KEY_VOLUMEDOWN;
1941                 break;
1942         }
1943
1944         if (val) {
1945                 input_report_key(chip->input_dev, val, 1);
1946                 input_sync(chip->input_dev);
1947                 input_report_key(chip->input_dev, val, 0);
1948                 input_sync(chip->input_dev);
1949         }
1950 #endif
1951 }
1952
1953 /*
1954  * interrupt handler
1955  */
1956 static irqreturn_t snd_es1968_interrupt(int irq, void *dev_id)
1957 {
1958         struct es1968 *chip = dev_id;
1959         u32 event;
1960
1961         event = inb(chip->io_port + 0x1A);
1962         if (!event)
1963                 return IRQ_NONE;
1964
1965         outw(inw(chip->io_port + 4) & 1, chip->io_port + 4);
1966
1967         if (event & ESM_HWVOL_IRQ)
1968                 schedule_work(&chip->hwvol_work);
1969
1970         /* else ack 'em all, i imagine */
1971         outb(0xFF, chip->io_port + 0x1A);
1972
1973         if ((event & ESM_MPU401_IRQ) && chip->rmidi) {
1974                 snd_mpu401_uart_interrupt(irq, chip->rmidi->private_data);
1975         }
1976
1977         if (event & ESM_SOUND_IRQ) {
1978                 struct esschan *es;
1979                 spin_lock(&chip->substream_lock);
1980                 list_for_each_entry(es, &chip->substream_list, list) {
1981                         if (es->running) {
1982                                 snd_es1968_update_pcm(chip, es);
1983                                 if (es->fmt & ESS_FMT_STEREO)
1984                                         snd_es1968_suppress_jitter(chip, es);
1985                         }
1986                 }
1987                 spin_unlock(&chip->substream_lock);
1988                 if (chip->in_measurement) {
1989                         unsigned int curp = __apu_get_register(chip, chip->measure_apu, 5);
1990                         if (curp < chip->measure_lastpos)
1991                                 chip->measure_count++;
1992                         chip->measure_lastpos = curp;
1993                 }
1994         }
1995
1996         return IRQ_HANDLED;
1997 }
1998
1999 /*
2000  *  Mixer stuff
2001  */
2002
2003 static int
2004 snd_es1968_mixer(struct es1968 *chip)
2005 {
2006         struct snd_ac97_bus *pbus;
2007         struct snd_ac97_template ac97;
2008         int err;
2009         static const struct snd_ac97_bus_ops ops = {
2010                 .write = snd_es1968_ac97_write,
2011                 .read = snd_es1968_ac97_read,
2012         };
2013
2014         err = snd_ac97_bus(chip->card, 0, &ops, NULL, &pbus);
2015         if (err < 0)
2016                 return err;
2017         pbus->no_vra = 1; /* ES1968 doesn't need VRA */
2018
2019         memset(&ac97, 0, sizeof(ac97));
2020         ac97.private_data = chip;
2021         err = snd_ac97_mixer(pbus, &ac97, &chip->ac97);
2022         if (err < 0)
2023                 return err;
2024
2025 #ifndef CONFIG_SND_ES1968_INPUT
2026         /* attach master switch / volumes for h/w volume control */
2027         chip->master_switch = snd_ctl_find_id_mixer(chip->card,
2028                                                     "Master Playback Switch");
2029         chip->master_volume = snd_ctl_find_id_mixer(chip->card,
2030                                                     "Master Playback Volume");
2031 #endif
2032
2033         return 0;
2034 }
2035
2036 /*
2037  * reset ac97 codec
2038  */
2039
2040 static void snd_es1968_ac97_reset(struct es1968 *chip)
2041 {
2042         unsigned long ioaddr = chip->io_port;
2043
2044         unsigned short save_ringbus_a;
2045         unsigned short save_68;
2046         unsigned short w;
2047         unsigned int vend;
2048
2049         /* save configuration */
2050         save_ringbus_a = inw(ioaddr + 0x36);
2051
2052         //outw(inw(ioaddr + 0x38) & 0xfffc, ioaddr + 0x38); /* clear second codec id? */
2053         /* set command/status address i/o to 1st codec */
2054         outw(inw(ioaddr + 0x3a) & 0xfffc, ioaddr + 0x3a);
2055         outw(inw(ioaddr + 0x3c) & 0xfffc, ioaddr + 0x3c);
2056
2057         /* disable ac link */
2058         outw(0x0000, ioaddr + 0x36);
2059         save_68 = inw(ioaddr + 0x68);
2060         pci_read_config_word(chip->pci, 0x58, &w);      /* something magical with gpio and bus arb. */
2061         pci_read_config_dword(chip->pci, PCI_SUBSYSTEM_VENDOR_ID, &vend);
2062         if (w & 1)
2063                 save_68 |= 0x10;
2064         outw(0xfffe, ioaddr + 0x64);    /* unmask gpio 0 */
2065         outw(0x0001, ioaddr + 0x68);    /* gpio write */
2066         outw(0x0000, ioaddr + 0x60);    /* write 0 to gpio 0 */
2067         udelay(20);
2068         outw(0x0001, ioaddr + 0x60);    /* write 1 to gpio 1 */
2069         msleep(20);
2070
2071         outw(save_68 | 0x1, ioaddr + 0x68);     /* now restore .. */
2072         outw((inw(ioaddr + 0x38) & 0xfffc) | 0x1, ioaddr + 0x38);
2073         outw((inw(ioaddr + 0x3a) & 0xfffc) | 0x1, ioaddr + 0x3a);
2074         outw((inw(ioaddr + 0x3c) & 0xfffc) | 0x1, ioaddr + 0x3c);
2075
2076         /* now the second codec */
2077         /* disable ac link */
2078         outw(0x0000, ioaddr + 0x36);
2079         outw(0xfff7, ioaddr + 0x64);    /* unmask gpio 3 */
2080         save_68 = inw(ioaddr + 0x68);
2081         outw(0x0009, ioaddr + 0x68);    /* gpio write 0 & 3 ?? */
2082         outw(0x0001, ioaddr + 0x60);    /* write 1 to gpio */
2083         udelay(20);
2084         outw(0x0009, ioaddr + 0x60);    /* write 9 to gpio */
2085         msleep(500);
2086         //outw(inw(ioaddr + 0x38) & 0xfffc, ioaddr + 0x38);
2087         outw(inw(ioaddr + 0x3a) & 0xfffc, ioaddr + 0x3a);
2088         outw(inw(ioaddr + 0x3c) & 0xfffc, ioaddr + 0x3c);
2089
2090 #if 0                           /* the loop here needs to be much better if we want it.. */
2091         dev_info(chip->card->dev, "trying software reset\n");
2092         /* try and do a software reset */
2093         outb(0x80 | 0x7c, ioaddr + 0x30);
2094         for (w = 0;; w++) {
2095                 if ((inw(ioaddr + 0x30) & 1) == 0) {
2096                         if (inb(ioaddr + 0x32) != 0)
2097                                 break;
2098
2099                         outb(0x80 | 0x7d, ioaddr + 0x30);
2100                         if (((inw(ioaddr + 0x30) & 1) == 0)
2101                             && (inb(ioaddr + 0x32) != 0))
2102                                 break;
2103                         outb(0x80 | 0x7f, ioaddr + 0x30);
2104                         if (((inw(ioaddr + 0x30) & 1) == 0)
2105                             && (inb(ioaddr + 0x32) != 0))
2106                                 break;
2107                 }
2108
2109                 if (w > 10000) {
2110                         outb(inb(ioaddr + 0x37) | 0x08, ioaddr + 0x37); /* do a software reset */
2111                         msleep(500);    /* oh my.. */
2112                         outb(inb(ioaddr + 0x37) & ~0x08,
2113                                 ioaddr + 0x37);
2114                         udelay(1);
2115                         outw(0x80, ioaddr + 0x30);
2116                         for (w = 0; w < 10000; w++) {
2117                                 if ((inw(ioaddr + 0x30) & 1) == 0)
2118                                         break;
2119                         }
2120                 }
2121         }
2122 #endif
2123         if (vend == NEC_VERSA_SUBID1 || vend == NEC_VERSA_SUBID2) {
2124                 /* turn on external amp? */
2125                 outw(0xf9ff, ioaddr + 0x64);
2126                 outw(inw(ioaddr + 0x68) | 0x600, ioaddr + 0x68);
2127                 outw(0x0209, ioaddr + 0x60);
2128         }
2129
2130         /* restore.. */
2131         outw(save_ringbus_a, ioaddr + 0x36);
2132
2133         /* Turn on the 978 docking chip.
2134            First frob the "master output enable" bit,
2135            then set most of the playback volume control registers to max. */
2136         outb(inb(ioaddr+0xc0)|(1<<5), ioaddr+0xc0);
2137         outb(0xff, ioaddr+0xc3);
2138         outb(0xff, ioaddr+0xc4);
2139         outb(0xff, ioaddr+0xc6);
2140         outb(0xff, ioaddr+0xc8);
2141         outb(0x3f, ioaddr+0xcf);
2142         outb(0x3f, ioaddr+0xd0);
2143 }
2144
2145 static void snd_es1968_reset(struct es1968 *chip)
2146 {
2147         /* Reset */
2148         outw(ESM_RESET_MAESTRO | ESM_RESET_DIRECTSOUND,
2149              chip->io_port + ESM_PORT_HOST_IRQ);
2150         udelay(10);
2151         outw(0x0000, chip->io_port + ESM_PORT_HOST_IRQ);
2152         udelay(10);
2153 }
2154
2155 /*
2156  * initialize maestro chip
2157  */
2158 static void snd_es1968_chip_init(struct es1968 *chip)
2159 {
2160         struct pci_dev *pci = chip->pci;
2161         int i;
2162         unsigned long iobase  = chip->io_port;
2163         u16 w;
2164         u32 n;
2165
2166         /* We used to muck around with pci config space that
2167          * we had no business messing with.  We don't know enough
2168          * about the machine to know which DMA mode is appropriate, 
2169          * etc.  We were guessing wrong on some machines and making
2170          * them unhappy.  We now trust in the BIOS to do things right,
2171          * which almost certainly means a new host of problems will
2172          * arise with broken BIOS implementations.  screw 'em. 
2173          * We're already intolerant of machines that don't assign
2174          * IRQs.
2175          */
2176         
2177         /* Config Reg A */
2178         pci_read_config_word(pci, ESM_CONFIG_A, &w);
2179
2180         w &= ~DMA_CLEAR;        /* Clear DMA bits */
2181         w &= ~(PIC_SNOOP1 | PIC_SNOOP2);        /* Clear Pic Snoop Mode Bits */
2182         w &= ~SAFEGUARD;        /* Safeguard off */
2183         w |= POST_WRITE;        /* Posted write */
2184         w |= PCI_TIMING;        /* PCI timing on */
2185         /* XXX huh?  claims to be reserved.. */
2186         w &= ~SWAP_LR;          /* swap left/right 
2187                                    seems to only have effect on SB
2188                                    Emulation */
2189         w &= ~SUBTR_DECODE;     /* Subtractive decode off */
2190
2191         pci_write_config_word(pci, ESM_CONFIG_A, w);
2192
2193         /* Config Reg B */
2194
2195         pci_read_config_word(pci, ESM_CONFIG_B, &w);
2196
2197         w &= ~(1 << 15);        /* Turn off internal clock multiplier */
2198         /* XXX how do we know which to use? */
2199         w &= ~(1 << 14);        /* External clock */
2200
2201         w &= ~SPDIF_CONFB;      /* disable S/PDIF output */
2202         w |= HWV_CONFB;         /* HWV on */
2203         w |= DEBOUNCE;          /* Debounce off: easier to push the HW buttons */
2204         w &= ~GPIO_CONFB;       /* GPIO 4:5 */
2205         w |= CHI_CONFB;         /* Disconnect from the CHI.  Enabling this made a dell 7500 work. */
2206         w &= ~IDMA_CONFB;       /* IDMA off (undocumented) */
2207         w &= ~MIDI_FIX;         /* MIDI fix off (undoc) */
2208         w &= ~(1 << 1);         /* reserved, always write 0 */
2209         w &= ~IRQ_TO_ISA;       /* IRQ to ISA off (undoc) */
2210
2211         pci_write_config_word(pci, ESM_CONFIG_B, w);
2212
2213         /* DDMA off */
2214
2215         pci_read_config_word(pci, ESM_DDMA, &w);
2216         w &= ~(1 << 0);
2217         pci_write_config_word(pci, ESM_DDMA, w);
2218
2219         /*
2220          *      Legacy mode
2221          */
2222
2223         pci_read_config_word(pci, ESM_LEGACY_AUDIO_CONTROL, &w);
2224
2225         w |= ESS_DISABLE_AUDIO; /* Disable Legacy Audio */
2226         w &= ~ESS_ENABLE_SERIAL_IRQ;    /* Disable SIRQ */
2227         w &= ~(0x1f);           /* disable mpu irq/io, game port, fm, SB */
2228
2229         pci_write_config_word(pci, ESM_LEGACY_AUDIO_CONTROL, w);
2230
2231         /* Set up 978 docking control chip. */
2232         pci_read_config_word(pci, 0x58, &w);
2233         w|=1<<2;        /* Enable 978. */
2234         w|=1<<3;        /* Turn on 978 hardware volume control. */
2235         w&=~(1<<11);    /* Turn on 978 mixer volume control. */
2236         pci_write_config_word(pci, 0x58, w);
2237         
2238         /* Sound Reset */
2239
2240         snd_es1968_reset(chip);
2241
2242         /*
2243          *      Ring Bus Setup
2244          */
2245
2246         /* setup usual 0x34 stuff.. 0x36 may be chip specific */
2247         outw(0xC090, iobase + ESM_RING_BUS_DEST); /* direct sound, stereo */
2248         udelay(20);
2249         outw(0x3000, iobase + ESM_RING_BUS_CONTR_A); /* enable ringbus/serial */
2250         udelay(20);
2251
2252         /*
2253          *      Reset the CODEC
2254          */
2255          
2256         snd_es1968_ac97_reset(chip);
2257
2258         /* Ring Bus Control B */
2259
2260         n = inl(iobase + ESM_RING_BUS_CONTR_B);
2261         n &= ~RINGB_EN_SPDIF;   /* SPDIF off */
2262         //w |= RINGB_EN_2CODEC; /* enable 2nd codec */
2263         outl(n, iobase + ESM_RING_BUS_CONTR_B);
2264
2265         /* Set hardware volume control registers to midpoints.
2266            We can tell which button was pushed based on how they change. */
2267         outb(0x88, iobase+0x1c);
2268         outb(0x88, iobase+0x1d);
2269         outb(0x88, iobase+0x1e);
2270         outb(0x88, iobase+0x1f);
2271
2272         /* it appears some maestros (dell 7500) only work if these are set,
2273            regardless of whether we use the assp or not. */
2274
2275         outb(0, iobase + ASSP_CONTROL_B);
2276         outb(3, iobase + ASSP_CONTROL_A);       /* M: Reserved bits... */
2277         outb(0, iobase + ASSP_CONTROL_C);       /* M: Disable ASSP, ASSP IRQ's and FM Port */
2278
2279         /*
2280          * set up wavecache
2281          */
2282         for (i = 0; i < 16; i++) {
2283                 /* Write 0 into the buffer area 0x1E0->1EF */
2284                 outw(0x01E0 + i, iobase + WC_INDEX);
2285                 outw(0x0000, iobase + WC_DATA);
2286
2287                 /* The 1.10 test program seem to write 0 into the buffer area
2288                  * 0x1D0-0x1DF too.*/
2289                 outw(0x01D0 + i, iobase + WC_INDEX);
2290                 outw(0x0000, iobase + WC_DATA);
2291         }
2292         wave_set_register(chip, IDR7_WAVE_ROMRAM,
2293                           (wave_get_register(chip, IDR7_WAVE_ROMRAM) & 0xFF00));
2294         wave_set_register(chip, IDR7_WAVE_ROMRAM,
2295                           wave_get_register(chip, IDR7_WAVE_ROMRAM) | 0x100);
2296         wave_set_register(chip, IDR7_WAVE_ROMRAM,
2297                           wave_get_register(chip, IDR7_WAVE_ROMRAM) & ~0x200);
2298         wave_set_register(chip, IDR7_WAVE_ROMRAM,
2299                           wave_get_register(chip, IDR7_WAVE_ROMRAM) | ~0x400);
2300
2301
2302         maestro_write(chip, IDR2_CRAM_DATA, 0x0000);
2303         /* Now back to the DirectSound stuff */
2304         /* audio serial configuration.. ? */
2305         maestro_write(chip, 0x08, 0xB004);
2306         maestro_write(chip, 0x09, 0x001B);
2307         maestro_write(chip, 0x0A, 0x8000);
2308         maestro_write(chip, 0x0B, 0x3F37);
2309         maestro_write(chip, 0x0C, 0x0098);
2310
2311         /* parallel in, has something to do with recording :) */
2312         maestro_write(chip, 0x0C,
2313                       (maestro_read(chip, 0x0C) & ~0xF000) | 0x8000);
2314         /* parallel out */
2315         maestro_write(chip, 0x0C,
2316                       (maestro_read(chip, 0x0C) & ~0x0F00) | 0x0500);
2317
2318         maestro_write(chip, 0x0D, 0x7632);
2319
2320         /* Wave cache control on - test off, sg off, 
2321            enable, enable extra chans 1Mb */
2322
2323         w = inw(iobase + WC_CONTROL);
2324
2325         w &= ~0xFA00;           /* Seems to be reserved? I don't know */
2326         w |= 0xA000;            /* reserved... I don't know */
2327         w &= ~0x0200;           /* Channels 56,57,58,59 as Extra Play,Rec Channel enable
2328                                    Seems to crash the Computer if enabled... */
2329         w |= 0x0100;            /* Wave Cache Operation Enabled */
2330         w |= 0x0080;            /* Channels 60/61 as Placback/Record enabled */
2331         w &= ~0x0060;           /* Clear Wavtable Size */
2332         w |= 0x0020;            /* Wavetable Size : 1MB */
2333         /* Bit 4 is reserved */
2334         w &= ~0x000C;           /* DMA Stuff? I don't understand what the datasheet means */
2335         /* Bit 1 is reserved */
2336         w &= ~0x0001;           /* Test Mode off */
2337
2338         outw(w, iobase + WC_CONTROL);
2339
2340         /* Now clear the APU control ram */
2341         for (i = 0; i < NR_APUS; i++) {
2342                 for (w = 0; w < NR_APU_REGS; w++)
2343                         apu_set_register(chip, i, w, 0);
2344
2345         }
2346 }
2347
2348 /* Enable IRQ's */
2349 static void snd_es1968_start_irq(struct es1968 *chip)
2350 {
2351         unsigned short w;
2352         w = ESM_HIRQ_DSIE | ESM_HIRQ_HW_VOLUME;
2353         if (chip->rmidi)
2354                 w |= ESM_HIRQ_MPU401;
2355         outb(w, chip->io_port + 0x1A);
2356         outw(w, chip->io_port + ESM_PORT_HOST_IRQ);
2357 }
2358
2359 #ifdef CONFIG_PM_SLEEP
2360 /*
2361  * PM support
2362  */
2363 static int es1968_suspend(struct device *dev)
2364 {
2365         struct snd_card *card = dev_get_drvdata(dev);
2366         struct es1968 *chip = card->private_data;
2367
2368         if (! chip->do_pm)
2369                 return 0;
2370
2371         chip->in_suspend = 1;
2372         cancel_work_sync(&chip->hwvol_work);
2373         snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
2374         snd_ac97_suspend(chip->ac97);
2375         snd_es1968_bob_stop(chip);
2376         return 0;
2377 }
2378
2379 static int es1968_resume(struct device *dev)
2380 {
2381         struct snd_card *card = dev_get_drvdata(dev);
2382         struct es1968 *chip = card->private_data;
2383         struct esschan *es;
2384
2385         if (! chip->do_pm)
2386                 return 0;
2387
2388         snd_es1968_chip_init(chip);
2389
2390         /* need to restore the base pointers.. */ 
2391         if (chip->dma.addr) {
2392                 /* set PCMBAR */
2393                 wave_set_register(chip, 0x01FC, chip->dma.addr >> 12);
2394         }
2395
2396         snd_es1968_start_irq(chip);
2397
2398         /* restore ac97 state */
2399         snd_ac97_resume(chip->ac97);
2400
2401         list_for_each_entry(es, &chip->substream_list, list) {
2402                 switch (es->mode) {
2403                 case ESM_MODE_PLAY:
2404                         snd_es1968_playback_setup(chip, es, es->substream->runtime);
2405                         break;
2406                 case ESM_MODE_CAPTURE:
2407                         snd_es1968_capture_setup(chip, es, es->substream->runtime);
2408                         break;
2409                 }
2410         }
2411
2412         /* start timer again */
2413         if (chip->bobclient)
2414                 snd_es1968_bob_start(chip);
2415
2416         snd_power_change_state(card, SNDRV_CTL_POWER_D0);
2417         chip->in_suspend = 0;
2418         return 0;
2419 }
2420
2421 static SIMPLE_DEV_PM_OPS(es1968_pm, es1968_suspend, es1968_resume);
2422 #define ES1968_PM_OPS   &es1968_pm
2423 #else
2424 #define ES1968_PM_OPS   NULL
2425 #endif /* CONFIG_PM_SLEEP */
2426
2427 #ifdef SUPPORT_JOYSTICK
2428 #define JOYSTICK_ADDR   0x200
2429 static int snd_es1968_create_gameport(struct es1968 *chip, int dev)
2430 {
2431         struct gameport *gp;
2432         struct resource *r;
2433         u16 val;
2434
2435         if (!joystick[dev])
2436                 return -ENODEV;
2437
2438         r = devm_request_region(&chip->pci->dev, JOYSTICK_ADDR, 8,
2439                                 "ES1968 gameport");
2440         if (!r)
2441                 return -EBUSY;
2442
2443         chip->gameport = gp = gameport_allocate_port();
2444         if (!gp) {
2445                 dev_err(chip->card->dev,
2446                         "cannot allocate memory for gameport\n");
2447                 return -ENOMEM;
2448         }
2449
2450         pci_read_config_word(chip->pci, ESM_LEGACY_AUDIO_CONTROL, &val);
2451         pci_write_config_word(chip->pci, ESM_LEGACY_AUDIO_CONTROL, val | 0x04);
2452
2453         gameport_set_name(gp, "ES1968 Gameport");
2454         gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci));
2455         gameport_set_dev_parent(gp, &chip->pci->dev);
2456         gp->io = JOYSTICK_ADDR;
2457
2458         gameport_register_port(gp);
2459
2460         return 0;
2461 }
2462
2463 static void snd_es1968_free_gameport(struct es1968 *chip)
2464 {
2465         if (chip->gameport) {
2466                 gameport_unregister_port(chip->gameport);
2467                 chip->gameport = NULL;
2468         }
2469 }
2470 #else
2471 static inline int snd_es1968_create_gameport(struct es1968 *chip, int dev) { return -ENOSYS; }
2472 static inline void snd_es1968_free_gameport(struct es1968 *chip) { }
2473 #endif
2474
2475 #ifdef CONFIG_SND_ES1968_INPUT
2476 static int snd_es1968_input_register(struct es1968 *chip)
2477 {
2478         struct input_dev *input_dev;
2479         int err;
2480
2481         input_dev = devm_input_allocate_device(&chip->pci->dev);
2482         if (!input_dev)
2483                 return -ENOMEM;
2484
2485         snprintf(chip->phys, sizeof(chip->phys), "pci-%s/input0",
2486                  pci_name(chip->pci));
2487
2488         input_dev->name = chip->card->driver;
2489         input_dev->phys = chip->phys;
2490         input_dev->id.bustype = BUS_PCI;
2491         input_dev->id.vendor  = chip->pci->vendor;
2492         input_dev->id.product = chip->pci->device;
2493         input_dev->dev.parent = &chip->pci->dev;
2494
2495         __set_bit(EV_KEY, input_dev->evbit);
2496         __set_bit(KEY_MUTE, input_dev->keybit);
2497         __set_bit(KEY_VOLUMEDOWN, input_dev->keybit);
2498         __set_bit(KEY_VOLUMEUP, input_dev->keybit);
2499
2500         err = input_register_device(input_dev);
2501         if (err)
2502                 return err;
2503
2504         chip->input_dev = input_dev;
2505         return 0;
2506 }
2507 #endif /* CONFIG_SND_ES1968_INPUT */
2508
2509 #ifdef CONFIG_SND_ES1968_RADIO
2510 #define GPIO_DATA       0x60
2511 #define IO_MASK         4      /* mask      register offset from GPIO_DATA
2512                                 bits 1=unmask write to given bit */
2513 #define IO_DIR          8      /* direction register offset from GPIO_DATA
2514                                 bits 0/1=read/write direction */
2515
2516 /* GPIO to TEA575x maps */
2517 struct snd_es1968_tea575x_gpio {
2518         u8 data, clk, wren, most;
2519         char *name;
2520 };
2521
2522 static const struct snd_es1968_tea575x_gpio snd_es1968_tea575x_gpios[] = {
2523         { .data = 6, .clk = 7, .wren = 8, .most = 9, .name = "SF64-PCE2" },
2524         { .data = 7, .clk = 8, .wren = 6, .most = 10, .name = "M56VAP" },
2525 };
2526
2527 #define get_tea575x_gpio(chip) \
2528         (&snd_es1968_tea575x_gpios[(chip)->tea575x_tuner])
2529
2530
2531 static void snd_es1968_tea575x_set_pins(struct snd_tea575x *tea, u8 pins)
2532 {
2533         struct es1968 *chip = tea->private_data;
2534         struct snd_es1968_tea575x_gpio gpio = *get_tea575x_gpio(chip);
2535         u16 val = 0;
2536
2537         val |= (pins & TEA575X_DATA) ? (1 << gpio.data) : 0;
2538         val |= (pins & TEA575X_CLK)  ? (1 << gpio.clk)  : 0;
2539         val |= (pins & TEA575X_WREN) ? (1 << gpio.wren) : 0;
2540
2541         outw(val, chip->io_port + GPIO_DATA);
2542 }
2543
2544 static u8 snd_es1968_tea575x_get_pins(struct snd_tea575x *tea)
2545 {
2546         struct es1968 *chip = tea->private_data;
2547         struct snd_es1968_tea575x_gpio gpio = *get_tea575x_gpio(chip);
2548         u16 val = inw(chip->io_port + GPIO_DATA);
2549         u8 ret = 0;
2550
2551         if (val & (1 << gpio.data))
2552                 ret |= TEA575X_DATA;
2553         if (val & (1 << gpio.most))
2554                 ret |= TEA575X_MOST;
2555
2556         return ret;
2557 }
2558
2559 static void snd_es1968_tea575x_set_direction(struct snd_tea575x *tea, bool output)
2560 {
2561         struct es1968 *chip = tea->private_data;
2562         unsigned long io = chip->io_port + GPIO_DATA;
2563         u16 odir = inw(io + IO_DIR);
2564         struct snd_es1968_tea575x_gpio gpio = *get_tea575x_gpio(chip);
2565
2566         if (output) {
2567                 outw(~((1 << gpio.data) | (1 << gpio.clk) | (1 << gpio.wren)),
2568                         io + IO_MASK);
2569                 outw(odir | (1 << gpio.data) | (1 << gpio.clk) | (1 << gpio.wren),
2570                         io + IO_DIR);
2571         } else {
2572                 outw(~((1 << gpio.clk) | (1 << gpio.wren) | (1 << gpio.data) | (1 << gpio.most)),
2573                         io + IO_MASK);
2574                 outw((odir & ~((1 << gpio.data) | (1 << gpio.most)))
2575                         | (1 << gpio.clk) | (1 << gpio.wren), io + IO_DIR);
2576         }
2577 }
2578
2579 static const struct snd_tea575x_ops snd_es1968_tea_ops = {
2580         .set_pins = snd_es1968_tea575x_set_pins,
2581         .get_pins = snd_es1968_tea575x_get_pins,
2582         .set_direction = snd_es1968_tea575x_set_direction,
2583 };
2584 #endif
2585
2586 static void snd_es1968_free(struct snd_card *card)
2587 {
2588         struct es1968 *chip = card->private_data;
2589
2590         cancel_work_sync(&chip->hwvol_work);
2591
2592         if (chip->io_port) {
2593                 outw(1, chip->io_port + 0x04); /* clear WP interrupts */
2594                 outw(0, chip->io_port + ESM_PORT_HOST_IRQ); /* disable IRQ */
2595         }
2596
2597 #ifdef CONFIG_SND_ES1968_RADIO
2598         snd_tea575x_exit(&chip->tea);
2599         v4l2_device_unregister(&chip->v4l2_dev);
2600 #endif
2601
2602         snd_es1968_free_gameport(chip);
2603 }
2604
2605 struct ess_device_list {
2606         unsigned short type;    /* chip type */
2607         unsigned short vendor;  /* subsystem vendor id */
2608 };
2609
2610 static const struct ess_device_list pm_allowlist[] = {
2611         { TYPE_MAESTRO2E, 0x0e11 },     /* Compaq Armada */
2612         { TYPE_MAESTRO2E, 0x1028 },
2613         { TYPE_MAESTRO2E, 0x103c },
2614         { TYPE_MAESTRO2E, 0x1179 },
2615         { TYPE_MAESTRO2E, 0x14c0 },     /* HP omnibook 4150 */
2616         { TYPE_MAESTRO2E, 0x1558 },
2617         { TYPE_MAESTRO2E, 0x125d },     /* a PCI card, e.g. Terratec DMX */
2618         { TYPE_MAESTRO2, 0x125d },      /* a PCI card, e.g. SF64-PCE2 */
2619 };
2620
2621 static const struct ess_device_list mpu_denylist[] = {
2622         { TYPE_MAESTRO2, 0x125d },
2623 };
2624
2625 static int snd_es1968_create(struct snd_card *card,
2626                              struct pci_dev *pci,
2627                              int total_bufsize,
2628                              int play_streams,
2629                              int capt_streams,
2630                              int chip_type,
2631                              int do_pm,
2632                              int radio_nr)
2633 {
2634         struct es1968 *chip = card->private_data;
2635         int i, err;
2636
2637         /* enable PCI device */
2638         err = pcim_enable_device(pci);
2639         if (err < 0)
2640                 return err;
2641         /* check, if we can restrict PCI DMA transfers to 28 bits */
2642         if (dma_set_mask_and_coherent(&pci->dev, DMA_BIT_MASK(28))) {
2643                 dev_err(card->dev,
2644                         "architecture does not support 28bit PCI busmaster DMA\n");
2645                 return -ENXIO;
2646         }
2647
2648         /* Set Vars */
2649         chip->type = chip_type;
2650         spin_lock_init(&chip->reg_lock);
2651         spin_lock_init(&chip->substream_lock);
2652         INIT_LIST_HEAD(&chip->buf_list);
2653         INIT_LIST_HEAD(&chip->substream_list);
2654         mutex_init(&chip->memory_mutex);
2655         INIT_WORK(&chip->hwvol_work, es1968_update_hw_volume);
2656         chip->card = card;
2657         chip->pci = pci;
2658         chip->irq = -1;
2659         chip->total_bufsize = total_bufsize;    /* in bytes */
2660         chip->playback_streams = play_streams;
2661         chip->capture_streams = capt_streams;
2662
2663         err = pci_request_regions(pci, "ESS Maestro");
2664         if (err < 0)
2665                 return err;
2666         chip->io_port = pci_resource_start(pci, 0);
2667         if (devm_request_irq(&pci->dev, pci->irq, snd_es1968_interrupt,
2668                              IRQF_SHARED, KBUILD_MODNAME, chip)) {
2669                 dev_err(card->dev, "unable to grab IRQ %d\n", pci->irq);
2670                 return -EBUSY;
2671         }
2672         chip->irq = pci->irq;
2673         card->sync_irq = chip->irq;
2674         card->private_free = snd_es1968_free;
2675                 
2676         /* Clear Maestro_map */
2677         for (i = 0; i < 32; i++)
2678                 chip->maestro_map[i] = 0;
2679
2680         /* Clear Apu Map */
2681         for (i = 0; i < NR_APUS; i++)
2682                 chip->apu[i] = ESM_APU_FREE;
2683
2684         /* just to be sure */
2685         pci_set_master(pci);
2686
2687         if (do_pm > 1) {
2688                 /* disable power-management if not on the allowlist */
2689                 unsigned short vend;
2690                 pci_read_config_word(chip->pci, PCI_SUBSYSTEM_VENDOR_ID, &vend);
2691                 for (i = 0; i < (int)ARRAY_SIZE(pm_allowlist); i++) {
2692                         if (chip->type == pm_allowlist[i].type &&
2693                             vend == pm_allowlist[i].vendor) {
2694                                 do_pm = 1;
2695                                 break;
2696                         }
2697                 }
2698                 if (do_pm > 1) {
2699                         /* not matched; disabling pm */
2700                         dev_info(card->dev, "not attempting power management.\n");
2701                         do_pm = 0;
2702                 }
2703         }
2704         chip->do_pm = do_pm;
2705
2706         snd_es1968_chip_init(chip);
2707
2708 #ifdef CONFIG_SND_ES1968_RADIO
2709         /* don't play with GPIOs on laptops */
2710         if (chip->pci->subsystem_vendor != 0x125d)
2711                 return 0;
2712         err = v4l2_device_register(&pci->dev, &chip->v4l2_dev);
2713         if (err < 0)
2714                 return err;
2715         chip->tea.v4l2_dev = &chip->v4l2_dev;
2716         chip->tea.private_data = chip;
2717         chip->tea.radio_nr = radio_nr;
2718         chip->tea.ops = &snd_es1968_tea_ops;
2719         sprintf(chip->tea.bus_info, "PCI:%s", pci_name(pci));
2720         for (i = 0; i < ARRAY_SIZE(snd_es1968_tea575x_gpios); i++) {
2721                 chip->tea575x_tuner = i;
2722                 if (!snd_tea575x_init(&chip->tea, THIS_MODULE)) {
2723                         dev_info(card->dev, "detected TEA575x radio type %s\n",
2724                                    get_tea575x_gpio(chip)->name);
2725                         strscpy(chip->tea.card, get_tea575x_gpio(chip)->name,
2726                                 sizeof(chip->tea.card));
2727                         break;
2728                 }
2729         }
2730 #endif
2731         return 0;
2732 }
2733
2734
2735 /*
2736  */
2737 static int __snd_es1968_probe(struct pci_dev *pci,
2738                               const struct pci_device_id *pci_id)
2739 {
2740         static int dev;
2741         struct snd_card *card;
2742         struct es1968 *chip;
2743         unsigned int i;
2744         int err;
2745
2746         if (dev >= SNDRV_CARDS)
2747                 return -ENODEV;
2748         if (!enable[dev]) {
2749                 dev++;
2750                 return -ENOENT;
2751         }
2752
2753         err = snd_devm_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
2754                                 sizeof(*chip), &card);
2755         if (err < 0)
2756                 return err;
2757         chip = card->private_data;
2758                 
2759         if (total_bufsize[dev] < 128)
2760                 total_bufsize[dev] = 128;
2761         if (total_bufsize[dev] > 4096)
2762                 total_bufsize[dev] = 4096;
2763         err = snd_es1968_create(card, pci,
2764                                 total_bufsize[dev] * 1024, /* in bytes */
2765                                 pcm_substreams_p[dev],
2766                                 pcm_substreams_c[dev],
2767                                 pci_id->driver_data,
2768                                 use_pm[dev],
2769                                 radio_nr[dev]);
2770         if (err < 0)
2771                 return err;
2772
2773         switch (chip->type) {
2774         case TYPE_MAESTRO2E:
2775                 strcpy(card->driver, "ES1978");
2776                 strcpy(card->shortname, "ESS ES1978 (Maestro 2E)");
2777                 break;
2778         case TYPE_MAESTRO2:
2779                 strcpy(card->driver, "ES1968");
2780                 strcpy(card->shortname, "ESS ES1968 (Maestro 2)");
2781                 break;
2782         case TYPE_MAESTRO:
2783                 strcpy(card->driver, "ESM1");
2784                 strcpy(card->shortname, "ESS Maestro 1");
2785                 break;
2786         }
2787
2788         err = snd_es1968_pcm(chip, 0);
2789         if (err < 0)
2790                 return err;
2791
2792         err = snd_es1968_mixer(chip);
2793         if (err < 0)
2794                 return err;
2795
2796         if (enable_mpu[dev] == 2) {
2797                 /* check the deny list */
2798                 unsigned short vend;
2799                 pci_read_config_word(chip->pci, PCI_SUBSYSTEM_VENDOR_ID, &vend);
2800                 for (i = 0; i < ARRAY_SIZE(mpu_denylist); i++) {
2801                         if (chip->type == mpu_denylist[i].type &&
2802                             vend == mpu_denylist[i].vendor) {
2803                                 enable_mpu[dev] = 0;
2804                                 break;
2805                         }
2806                 }
2807         }
2808         if (enable_mpu[dev]) {
2809                 err = snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401,
2810                                           chip->io_port + ESM_MPU401_PORT,
2811                                           MPU401_INFO_INTEGRATED |
2812                                           MPU401_INFO_IRQ_HOOK,
2813                                           -1, &chip->rmidi);
2814                 if (err < 0)
2815                         dev_warn(card->dev, "skipping MPU-401 MIDI support..\n");
2816         }
2817
2818         snd_es1968_create_gameport(chip, dev);
2819
2820 #ifdef CONFIG_SND_ES1968_INPUT
2821         err = snd_es1968_input_register(chip);
2822         if (err)
2823                 dev_warn(card->dev,
2824                          "Input device registration failed with error %i", err);
2825 #endif
2826
2827         snd_es1968_start_irq(chip);
2828
2829         chip->clock = clock[dev];
2830         if (! chip->clock)
2831                 es1968_measure_clock(chip);
2832
2833         sprintf(card->longname, "%s at 0x%lx, irq %i",
2834                 card->shortname, chip->io_port, chip->irq);
2835
2836         err = snd_card_register(card);
2837         if (err < 0)
2838                 return err;
2839         pci_set_drvdata(pci, card);
2840         dev++;
2841         return 0;
2842 }
2843
2844 static int snd_es1968_probe(struct pci_dev *pci,
2845                             const struct pci_device_id *pci_id)
2846 {
2847         return snd_card_free_on_error(&pci->dev, __snd_es1968_probe(pci, pci_id));
2848 }
2849
2850 static struct pci_driver es1968_driver = {
2851         .name = KBUILD_MODNAME,
2852         .id_table = snd_es1968_ids,
2853         .probe = snd_es1968_probe,
2854         .driver = {
2855                 .pm = ES1968_PM_OPS,
2856         },
2857 };
2858
2859 module_pci_driver(es1968_driver);