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