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