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