File: /usr/src/linux/drivers/sound/maestro.c

1     /*****************************************************************************
2      *
3      *      ESS Maestro/Maestro-2/Maestro-2E driver for Linux 2.[23].x
4      *
5      *      This program is free software; you can redistribute it and/or modify
6      *      it under the terms of the GNU General Public License as published by
7      *      the Free Software Foundation; either version 2 of the License, or
8      *      (at your option) any later version.
9      *
10      *      This program is distributed in the hope that it will be useful,
11      *      but WITHOUT ANY WARRANTY; without even the implied warranty of
12      *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13      *      GNU General Public License for more details.
14      *
15      *      You should have received a copy of the GNU General Public License
16      *      along with this program; if not, write to the Free Software
17      *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18      *
19      *	(c) Copyright 1999	 Alan Cox <alan.cox@linux.org>
20      *
21      *	Based heavily on SonicVibes.c:
22      *      Copyright (C) 1998-1999  Thomas Sailer (sailer@ife.ee.ethz.ch)
23      *
24      *	Heavily modified by Zach Brown <zab@zabbo.net> based on lunch
25      *	with ESS engineers.  Many thanks to Howard Kim for providing 
26      *	contacts and hardware.  Honorable mention goes to Eric 
27      *	Brombaugh for all sorts of things.  Best regards to the 
28      *	proprietors of Hack Central for fine lodging.
29      *
30      *  Supported devices:
31      *  /dev/dsp0-3    standard /dev/dsp device, (mostly) OSS compatible
32      *  /dev/mixer  standard /dev/mixer device, (mostly) OSS compatible
33      *
34      *  Hardware Description
35      *
36      *	A working Maestro setup contains the Maestro chip wired to a 
37      *	codec or 2.  In the Maestro we have the APUs, the ASSP, and the
38      *	Wavecache.  The APUs can be though of as virtual audio routing
39      *	channels.  They can take data from a number of sources and perform
40      *	basic encodings of the data.  The wavecache is a storehouse for
41      *	PCM data.  Typically it deals with PCI and interracts with the
42      *	APUs.  The ASSP is a wacky DSP like device that ESS is loth
43      *	to release docs on.  Thankfully it isn't required on the Maestro
44      *	until you start doing insane things like FM emulation and surround
45      *	encoding.  The codecs are almost always AC-97 compliant codecs, 
46      *	but it appears that early Maestros may have had PT101 (an ESS
47      *	part?) wired to them.  The only real difference in the Maestro
48      *	families is external goop like docking capability, memory for
49      *	the ASSP, and initialization differences.
50      *
51      *  Driver Operation
52      *
53      *	We only drive the APU/Wavecache as typical DACs and drive the
54      *	mixers in the codecs.  There are 64 APUs.  We assign 6 to each
55      *	/dev/dsp? device.  2 channels for output, and 4 channels for
56      *	input.
57      *
58      *	Each APU can do a number of things, but we only really use
59      *	3 basic functions.  For playback we use them to convert PCM
60      *	data fetched over PCI by the wavecahche into analog data that
61      *	is handed to the codec.  One APU for mono, and a pair for stereo.
62      *	When in stereo, the combination of smarts in the APU and Wavecache
63      *	decide which wavecache gets the left or right channel.
64      *
65      *	For record we still use the old overly mono system.  For each in
66      *	coming channel the data comes in from the codec, through a 'input'
67      *	APU, through another rate converter APU, and then into memory via
68      *	the wavecache and PCI.  If its stereo, we mash it back into LRLR in
69      *	software.  The pass between the 2 APUs is supposedly what requires us
70      *	to have a 512 byte buffer sitting around in wavecache/memory.
71      *
72      *	The wavecache makes our life even more fun.  First off, it can
73      *	only address the first 28 bits of PCI address space, making it
74      *	useless on quite a few architectures.  Secondly, its insane.
75      *	It claims to fetch from 4 regions of PCI space, each 4 meg in length.
76      *	But that doesn't really work.  You can only use 1 region.  So all our
77      *	allocations have to be in 4meg of each other.  Booo.  Hiss.
78      *	So we have a module parameter, dsps_order, that is the order of
79      *	the number of dsps to provide.  All their buffer space is allocated
80      *	on open time.  The sonicvibes OSS routines we inherited really want
81      *	power of 2 buffers, so we have all those next to each other, then
82      *	512 byte regions for the recording wavecaches.  This ends up
83      *	wasting quite a bit of memory.  The only fixes I can see would be 
84      *	getting a kernel allocator that could work in zones, or figuring out
85      *	just how to coerce the WP into doing what we want.
86      *
87      *	The indirection of the various registers means we have to spinlock
88      *	nearly all register accesses.  We have the main register indirection
89      *	like the wave cache, maestro registers, etc.  Then we have beasts
90      *	like the APU interface that is indirect registers gotten at through
91      *	the main maestro indirection.  Ouch.  We spinlock around the actual
92      *	ports on a per card basis.  This means spinlock activity at each IO
93      *	operation, but the only IO operation clusters are in non critical 
94      *	paths and it makes the code far easier to follow.  Interrupts are
95      *	blocked while holding the locks because the int handler has to
96      *	get at some of them :(.  The mixer interface doesn't, however.
97      *	We also have an OSS state lock that is thrown around in a few
98      *	places.
99      *
100      *	This driver has brute force APM suspend support.  We catch suspend
101      *	notifications and stop all work being done on the chip.  Any people
102      *	that try between this shutdown and the real suspend operation will
103      *	be put to sleep.  When we resume we restore our software state on
104      *	the chip and wake up the people that were using it.  The code thats
105      *	being used now is quite dirty and assumes we're on a uni-processor
106      *	machine.  Much of it will need to be cleaned up for SMP ACPI or 
107      *	similar.
108      *
109      *	We also pay attention to PCI power management now.  The driver
110      *	will power down units of the chip that it knows aren't needed.
111      *	The WaveProcessor and company are only powered on when people
112      *	have /dev/dsp*s open.  On removal the driver will
113      *	power down the maestro entirely.  There could still be
114      *	trouble with BIOSen that magically change power states 
115      *	themselves, but we'll see.  
116      *	
117      * History
118      *  v0.15 - May 21 2001 - Marcus Meissner <mm@caldera.de>
119      *      Ported to Linux 2.4 PCI API. Some clean ups, global devs list
120      *      removed (now using pci device driver data).
121      *      PM needs to be polished still. Bumped version.
122      *  (still kind of v0.14) May 13 2001 - Ben Pfaff <pfaffben@msu.edu>
123      *      Add support for 978 docking and basic hardware volume control
124      *  (still kind of v0.14) Nov 23 - Alan Cox <alan@redhat.com>
125      *	Add clocking= for people with seriously warped hardware
126      *  (still v0.14) Nov 10 2000 - Bartlomiej Zolnierkiewicz <bkz@linux-ide.org>
127      *	add __init to maestro_ac97_init() and maestro_install()
128      *  (still based on v0.14) Mar 29 2000 - Zach Brown <zab@redhat.com>
129      *	move to 2.3 power management interface, which
130      *		required hacking some suspend/resume/check paths 
131      *	make static compilation work
132      *  v0.14 - Jan 28 2000 - Zach Brown <zab@redhat.com>
133      *	add PCI power management through ACPI regs.
134      *	we now shut down on machine reboot/halt
135      *	leave scary PCI config items alone (isa stuff, mostly)
136      *	enable 1921s, it seems only mine was broke.
137      *	fix swapped left/right pcm dac.  har har.
138      *	up bob freq, increase buffers, fix pointers at underflow
139      *	silly compilation problems
140      *  v0.13 - Nov 18 1999 - Zach Brown <zab@redhat.com>
141      *	fix nec Versas?  man would that be cool.
142      *  v0.12 - Nov 12 1999 - Zach Brown <zab@redhat.com>
143      *	brown bag volume max fix..
144      *  v0.11 - Nov 11 1999 - Zach Brown <zab@redhat.com>
145      *	use proper stereo apu decoding, mmap/write should work.
146      *	make volume sliders more useful, tweak rate calculation.
147      *	fix lame 8bit format reporting bug.  duh. apm apu saving buglet also
148      *	fix maestro 1 clock freq "bug", remove pt101 support
149      *  v0.10 - Oct 28 1999 - Zach Brown <zab@redhat.com>
150      *	aha, so, sometimes the WP writes a status word to offset 0
151      *	  from one of the PCMBARs.  rearrange allocation accordingly..
152      *	  cheers again to Eric for being a good hacker in investigating this.
153      *	Jeroen Hoogervorst submits 7500 fix out of nowhere.  yay.  :)
154      *  v0.09 - Oct 23 1999 - Zach Brown <zab@redhat.com>
155      *	added APM support.
156      *	re-order something such that some 2Es now work.  Magic!
157      *	new codec reset routine.  made some codecs come to life.
158      *	fix clear_advance, sync some control with ESS.
159      *	now write to all base regs to be paranoid.
160      *  v0.08 - Oct 20 1999 - Zach Brown <zab@redhat.com>
161      *	Fix initial buflen bug.  I am so smart.  also smp compiling..
162      *	I owe Eric yet another beer: fixed recmask, igain, 
163      *	  muting, and adc sync consistency.  Go Team.
164      *  v0.07 - Oct 4 1999 - Zach Brown <zab@redhat.com>
165      *	tweak adc/dac, formating, and stuff to allow full duplex
166      *	allocate dsps memory at open() so we can fit in the wavecache window
167      *	fix wavecache braindamage.  again.  no more scribbling?
168      *	fix ess 1921 codec bug on some laptops.
169      *	fix dumb pci scanning bug
170      *	started 2.3 cleanup, redid spinlocks, little cleanups
171      *  v0.06 - Sep 20 1999 - Zach Brown <zab@redhat.com>
172      *	fix wavecache thinkos.  limit to 1 /dev/dsp.
173      *	eric is wearing his thinking toque this week.
174      *		spotted apu mode bugs and gain ramping problem
175      *	don't touch weird mixer regs, make recmask optional
176      *	fixed igain inversion, defaults for mixers, clean up rec_start
177      *	make mono recording work.
178      *	report subsystem stuff, please send reports.
179      *	littles: parallel out, amp now
180      *  v0.05 - Sep 17 1999 - Zach Brown <zab@redhat.com>
181      *	merged and fixed up Eric's initial recording code
182      *	munged format handling to catch misuse, needs rewrite.
183      *	revert ring bus init, fixup shared int, add pci busmaster setting
184      *	fix mixer oss interface, fix mic mute and recmask
185      *	mask off unsupported mixers, reset with all 1s, modularize defaults
186      *	make sure bob is running while we need it
187      *	got rid of device limit, initial minimal apm hooks
188      *	pull out dead code/includes, only allow multimedia/audio maestros
189      *  v0.04 - Sep 01 1999 - Zach Brown <zab@redhat.com>
190      *	copied memory leak fix from sonicvibes driver
191      *	different ac97 reset, play with 2.0 ac97, simplify ring bus setup
192      *	bob freq code, region sanity, jitter sync fix; all from Eric 
193      *
194      * TODO
195      *	fix bob frequency
196      *	endianness
197      *	do smart things with ac97 2.0 bits.
198      *	dual codecs
199      *	leave 54->61 open
200      *
201      *	it also would be fun to have a mode that would not use pci dma at all
202      *	but would copy into the wavecache on board memory and use that 
203      *	on architectures that don't like the maestro's pci dma ickiness.
204      */
205     
206     /*****************************************************************************/
207     
208     #include <linux/version.h>
209     #include <linux/module.h>
210     #include <linux/sched.h>
211     #include <linux/smp_lock.h>
212     #include <linux/wrapper.h>
213     #include <linux/string.h>
214     #include <linux/ctype.h>
215     #include <linux/ioport.h>
216     #include <linux/delay.h>
217     #include <linux/sound.h>
218     #include <linux/slab.h>
219     #include <linux/soundcard.h>
220     #include <linux/pci.h>
221     #include <linux/spinlock.h>
222     #include <asm/io.h>
223     #include <asm/dma.h>
224     #include <linux/init.h>
225     #include <linux/poll.h>
226     #include <linux/reboot.h>
227     #include <asm/uaccess.h>
228     #include <asm/hardirq.h>
229     #include <linux/bitops.h>
230     
231     #include <linux/pm.h>
232     static int maestro_pm_callback(struct pm_dev *dev, pm_request_t rqst, void *d);
233     
234     #include "maestro.h"
235     
236     static struct pci_driver maestro_pci_driver;
237     
238     /* --------------------------------------------------------------------- */
239     
240     #define M_DEBUG 1
241     
242     #ifdef M_DEBUG
243     static int debug=0;
244     #define M_printk(args...) {if (debug) printk(args);}
245     #else
246     #define M_printk(x)
247     #endif
248     
249     /* we try to setup 2^(dsps_order) /dev/dsp devices */
250     static int dsps_order=0;
251     /* wether or not we mess around with power management */
252     static int use_pm=2; /* set to 1 for force */
253     /* clocking for broken hardware - a few laptops seem to use a 50Khz clock
254     	ie insmod with clocking=50000 or so */
255     	
256     static int clocking=48000;
257     
258     MODULE_AUTHOR("Zach Brown <zab@zabbo.net>, Alan Cox <alan@redhat.com>");
259     MODULE_DESCRIPTION("ESS Maestro Driver");
260     #ifdef M_DEBUG
261     MODULE_PARM(debug,"i");
262     #endif
263     MODULE_PARM(dsps_order,"i");
264     MODULE_PARM(use_pm,"i");
265     MODULE_PARM(clocking, "i");
266     
267     /* --------------------------------------------------------------------- */
268     #define DRIVER_VERSION "0.15"
269     
270     #ifndef PCI_VENDOR_ESS
271     #define PCI_VENDOR_ESS			0x125D
272     #define PCI_DEVICE_ID_ESS_ESS1968	0x1968		/* Maestro 2	*/
273     #define PCI_DEVICE_ID_ESS_ESS1978      	0x1978		/* Maestro 2E	*/
274     
275     #define PCI_VENDOR_ESS_OLD		0x1285		/* Platform Tech, 
276     						the people the maestro 
277     						was bought from */
278     #define PCI_DEVICE_ID_ESS_ESS0100	0x0100		/* maestro 1 */
279     #endif /* PCI_VENDOR_ESS */
280     
281     #define ESS_CHAN_HARD		0x100
282     
283     /* NEC Versas ? */
284     #define NEC_VERSA_SUBID1	0x80581033
285     #define NEC_VERSA_SUBID2	0x803c1033
286     
287     
288     /* changed so that I could actually find all the
289     	references and fix them up.  its a little more readable now. */
290     #define ESS_FMT_STEREO	0x01
291     #define ESS_FMT_16BIT	0x02
292     #define ESS_FMT_MASK	0x03
293     #define ESS_DAC_SHIFT	0   
294     #define ESS_ADC_SHIFT	4
295     
296     #define ESS_STATE_MAGIC		0x125D1968
297     #define ESS_CARD_MAGIC		0x19283746
298     
299     #define DAC_RUNNING		1
300     #define ADC_RUNNING		2
301     
302     #define MAX_DSP_ORDER	2
303     #define MAX_DSPS	(1<<MAX_DSP_ORDER)
304     #define NR_DSPS		(1<<dsps_order)
305     #define NR_IDRS		32
306     
307     #define NR_APUS		64
308     #define NR_APU_REGS	16
309     
310     /* acpi states */
311     enum {
312     	ACPI_D0=0,
313     	ACPI_D1,
314     	ACPI_D2,
315     	ACPI_D3
316     };
317     
318     /* bits in the acpi masks */
319     #define ACPI_12MHZ	( 1 << 15)
320     #define ACPI_24MHZ	( 1 << 14)
321     #define ACPI_978	( 1 << 13)
322     #define ACPI_SPDIF	( 1 << 12)
323     #define ACPI_GLUE	( 1 << 11)
324     #define ACPI__10	( 1 << 10) /* reserved */
325     #define ACPI_PCIINT	( 1 << 9)
326     #define ACPI_HV		( 1 << 8) /* hardware volume */
327     #define ACPI_GPIO	( 1 << 7)
328     #define ACPI_ASSP	( 1 << 6)
329     #define ACPI_SB		( 1 << 5) /* sb emul */
330     #define ACPI_FM		( 1 << 4) /* fm emul */
331     #define ACPI_RB		( 1 << 3) /* ringbus / aclink */
332     #define ACPI_MIDI	( 1 << 2) 
333     #define ACPI_GP		( 1 << 1) /* game port */
334     #define ACPI_WP		( 1 << 0) /* wave processor */
335     
336     #define ACPI_ALL	(0xffff)
337     #define ACPI_SLEEP	(~(ACPI_SPDIF|ACPI_ASSP|ACPI_SB|ACPI_FM| \
338     			ACPI_MIDI|ACPI_GP|ACPI_WP))
339     #define ACPI_NONE	(ACPI__10)
340     
341     /* these masks indicate which units we care about at
342     	which states */
343     u16 acpi_state_mask[] = {
344     	[ACPI_D0] = ACPI_ALL,
345     	[ACPI_D1] = ACPI_SLEEP,
346     	[ACPI_D2] = ACPI_SLEEP,
347     	[ACPI_D3] = ACPI_NONE
348     };
349     
350     static char version[] __devinitdata =
351     KERN_INFO "maestro: version " DRIVER_VERSION " time " __TIME__ " " __DATE__ "\n";
352     
353     
354     
355     static const unsigned sample_size[] = { 1, 2, 2, 4 };
356     static const unsigned sample_shift[] = { 0, 1, 1, 2 };
357     
358     enum card_types_t {
359     	TYPE_MAESTRO,
360     	TYPE_MAESTRO2,
361     	TYPE_MAESTRO2E
362     };
363     
364     static const char *card_names[]={
365     	[TYPE_MAESTRO] = "ESS Maestro",
366     	[TYPE_MAESTRO2] = "ESS Maestro 2",
367     	[TYPE_MAESTRO2E] = "ESS Maestro 2E"
368     };
369     
370     static int clock_freq[]={
371     	[TYPE_MAESTRO] = (49152000L / 1024L),
372     	[TYPE_MAESTRO2] = (50000000L / 1024L),
373     	[TYPE_MAESTRO2E] = (50000000L / 1024L)
374     };
375     
376     static int maestro_notifier(struct notifier_block *nb, unsigned long event, void *buf);
377     
378     static struct notifier_block maestro_nb = {maestro_notifier, NULL, 0};
379     
380     /* --------------------------------------------------------------------- */
381     
382     struct ess_state {
383     	unsigned int magic;
384     	/* FIXME: we probably want submixers in here, but only one record pair */
385     	u8 apu[6];		/* l/r output, l/r intput converters, l/r input apus */
386     	u8 apu_mode[6];		/* Running mode for this APU */
387     	u8 apu_pan[6];		/* Panning setup for this APU */
388     	u32 apu_base[6];	/* base address for this apu */
389     	struct ess_card *card;	/* Card info */
390     	/* wave stuff */
391     	unsigned int rateadc, ratedac;
392     	unsigned char fmt, enable;
393     
394     	int index;
395     
396     	/* this locks around the oss state in the driver */
397     	spinlock_t lock;
398     	/* only let 1 be opening at a time */
399     	struct semaphore open_sem;
400     	wait_queue_head_t open_wait;
401     	mode_t open_mode;
402     
403     	/* soundcore stuff */
404     	int dev_audio;
405     
406     	struct dmabuf {
407     		void *rawbuf;
408     		unsigned buforder;
409     		unsigned numfrag;
410     		unsigned fragshift;
411     		/* XXX zab - swptr only in here so that it can be referenced by
412     			clear_advance, as far as I can tell :( */
413     		unsigned hwptr, swptr;
414     		unsigned total_bytes;
415     		int count;
416     		unsigned error; /* over/underrun */
417     		wait_queue_head_t wait;
418     		/* redundant, but makes calculations easier */
419     		unsigned fragsize;
420     		unsigned dmasize;
421     		unsigned fragsamples;
422     		/* OSS stuff */
423     		unsigned mapped:1;
424     		unsigned ready:1;	/* our oss buffers are ready to go */
425     		unsigned endcleared:1;
426     		unsigned ossfragshift;
427     		int ossmaxfrags;
428     		unsigned subdivision;
429     		u16 base;		/* Offset for ptr */
430     	} dma_dac, dma_adc;
431     
432     	/* pointer to each dsp?s piece of the apu->src buffer page */
433     	void *mixbuf;
434     
435     };
436     	
437     struct ess_card {
438     	unsigned int magic;
439     
440     	/* We keep maestro cards in a linked list */
441     	struct ess_card *next;
442     
443     	int dev_mixer;
444     
445     	int card_type;
446     
447     	/* as most of this is static,
448     		perhaps it should be a pointer to a global struct */
449     	struct mixer_goo {
450     		int modcnt;
451     		int supported_mixers;
452     		int stereo_mixers;
453     		int record_sources;
454     		/* the caller must guarantee arg sanity before calling these */
455     /*		int (*read_mixer)(struct ess_card *card, int index);*/
456     		void (*write_mixer)(struct ess_card *card,int mixer, unsigned int left,unsigned int right);
457     		int (*recmask_io)(struct ess_card *card,int rw,int mask);
458     		unsigned int mixer_state[SOUND_MIXER_NRDEVICES];
459     	} mix;
460     	
461     	int power_regs;
462     		
463     	int in_suspend;
464     	wait_queue_head_t suspend_queue;
465     
466     	struct ess_state channels[MAX_DSPS];
467     	u16 maestro_map[NR_IDRS];	/* Register map */
468     	/* we have to store this junk so that we can come back from a
469     		suspend */
470     	u16 apu_map[NR_APUS][NR_APU_REGS];	/* contents of apu regs */
471     
472     	/* this locks around the physical registers on the card */
473     	spinlock_t lock;
474     
475     	/* memory for this card.. wavecache limited :(*/
476     	void *dmapages;
477     	int dmaorder;
478     
479     	/* hardware resources */
480     	struct pci_dev *pcidev;
481     	u32 iobase;
482     	u32 irq;
483     
484     	int bob_freq;
485     	char dsps_open;
486     
487     	int dock_mute_vol;
488     };
489     
490     static void set_mixer(struct ess_card *card,unsigned int mixer, unsigned int val );
491     
492     static unsigned 
493     ld2(unsigned int x)
494     {
495     	unsigned r = 0;
496     	
497     	if (x >= 0x10000) {
498     		x >>= 16;
499     		r += 16;
500     	}
501     	if (x >= 0x100) {
502     		x >>= 8;
503     		r += 8;
504     	}
505     	if (x >= 0x10) {
506     		x >>= 4;
507     		r += 4;
508     	}
509     	if (x >= 4) {
510     		x >>= 2;
511     		r += 2;
512     	}
513     	if (x >= 2)
514     		r++;
515     	return r;
516     }
517     
518     
519     /* --------------------------------------------------------------------- */
520     
521     static void check_suspend(struct ess_card *card);
522     
523     /* --------------------------------------------------------------------- */
524     
525     
526     /*
527      *	ESS Maestro AC97 codec programming interface.
528      */
529     	 
530     static void maestro_ac97_set(struct ess_card *card, u8 cmd, u16 val)
531     {
532     	int io = card->iobase;
533     	int i;
534     	/*
535     	 *	Wait for the codec bus to be free 
536     	 */
537     
538     	check_suspend(card);
539     	 
540     	for(i=0;i<10000;i++)
541     	{
542     		if(!(inb(io+ESS_AC97_INDEX)&1)) 
543     			break;
544     	}
545     	/*
546     	 *	Write the bus
547     	 */ 
548     	outw(val, io+ESS_AC97_DATA);
549     	mdelay(1);
550     	outb(cmd, io+ESS_AC97_INDEX);
551     	mdelay(1);
552     }
553     
554     static u16 maestro_ac97_get(struct ess_card *card, u8 cmd)
555     {
556     	int io = card->iobase;
557     	int sanity=10000;
558     	u16 data;
559     	int i;
560     	
561     	check_suspend(card);
562     	/*
563     	 *	Wait for the codec bus to be free 
564     	 */
565     	 
566     	for(i=0;i<10000;i++)
567     	{
568     		if(!(inb(io+ESS_AC97_INDEX)&1))
569     			break;
570     	}
571     
572     	outb(cmd|0x80, io+ESS_AC97_INDEX);
573     	mdelay(1);
574     	
575     	while(inb(io+ESS_AC97_INDEX)&1)
576     	{
577     		sanity--;
578     		if(!sanity)
579     		{
580     			printk(KERN_ERR "maestro: ac97 codec timeout reading 0x%x.\n",cmd);
581     			return 0;
582     		}
583     	}
584     	data=inw(io+ESS_AC97_DATA);
585     	mdelay(1);
586     	return data;
587     }
588     
589     /* OSS interface to the ac97s.. */
590     
591     #define AC97_STEREO_MASK (SOUND_MASK_VOLUME|\
592     	SOUND_MASK_PCM|SOUND_MASK_LINE|SOUND_MASK_CD|\
593     	SOUND_MASK_VIDEO|SOUND_MASK_LINE1|SOUND_MASK_IGAIN)
594     
595     #define AC97_SUPPORTED_MASK (AC97_STEREO_MASK | \
596     	SOUND_MASK_BASS|SOUND_MASK_TREBLE|SOUND_MASK_MIC|\
597     	SOUND_MASK_SPEAKER)
598     
599     #define AC97_RECORD_MASK (SOUND_MASK_MIC|\
600     	SOUND_MASK_CD| SOUND_MASK_VIDEO| SOUND_MASK_LINE1| SOUND_MASK_LINE|\
601     	SOUND_MASK_PHONEIN)
602     
603     #define supported_mixer(CARD,FOO) ( CARD->mix.supported_mixers & (1<<FOO) )
604     
605     /* this table has default mixer values for all OSS mixers.
606     	be sure to fill it in if you add oss mixers
607     	to anyone's supported mixer defines */
608     
609      unsigned int mixer_defaults[SOUND_MIXER_NRDEVICES] = {
610     	[SOUND_MIXER_VOLUME] =          0x3232,
611     	[SOUND_MIXER_BASS] =            0x3232,
612     	[SOUND_MIXER_TREBLE] =          0x3232,
613     	[SOUND_MIXER_SPEAKER] =         0x3232,
614     	[SOUND_MIXER_MIC] =     0x8000, /* annoying */
615     	[SOUND_MIXER_LINE] =    0x3232,
616     	[SOUND_MIXER_CD] =      0x3232,
617     	[SOUND_MIXER_VIDEO] =   0x3232,
618     	[SOUND_MIXER_LINE1] =   0x3232,
619     	[SOUND_MIXER_PCM] =             0x3232,
620     	[SOUND_MIXER_IGAIN] =           0x3232
621     };
622     	
623     static struct ac97_mixer_hw {
624     	unsigned char offset;
625     	int scale;
626     } ac97_hw[SOUND_MIXER_NRDEVICES]= {
627     	[SOUND_MIXER_VOLUME]	=	{0x02,63},
628     	[SOUND_MIXER_BASS]	=	{0x08,15},
629     	[SOUND_MIXER_TREBLE]	=	{0x08,15},
630     	[SOUND_MIXER_SPEAKER]	=	{0x0a,15},
631     	[SOUND_MIXER_MIC]	=	{0x0e,31},
632     	[SOUND_MIXER_LINE]	=	{0x10,31},
633     	[SOUND_MIXER_CD]	=	{0x12,31},
634     	[SOUND_MIXER_VIDEO]	=	{0x14,31},
635     	[SOUND_MIXER_LINE1]	=	{0x16,31},
636     	[SOUND_MIXER_PCM]	=	{0x18,31},
637     	[SOUND_MIXER_IGAIN]	=	{0x1c,15}
638     };
639     
640     #if 0 /* *shrug* removed simply because we never used it.
641     		feel free to implement again if needed */
642     
643     /* reads the given OSS mixer from the ac97
644     	the caller must have insured that the ac97 knows
645     	about that given mixer, and should be holding a
646     	spinlock for the card */
647     static int ac97_read_mixer(struct ess_card *card, int mixer) 
648     {
649     	u16 val;
650     	int ret=0;
651     	struct ac97_mixer_hw *mh = &ac97_hw[mixer];
652     
653     	val = maestro_ac97_get(card, mh->offset);
654     
655     	if(AC97_STEREO_MASK & (1<<mixer)) {
656     		/* nice stereo mixers .. */
657     		int left,right;
658     
659     		left = (val >> 8)  & 0x7f;
660     		right = val  & 0x7f;
661     
662     		if (mixer == SOUND_MIXER_IGAIN) {
663     			right = (right * 100) / mh->scale;
664     			left = (left * 100) / mh->scale;
665     		else {
666     			right = 100 - ((right * 100) / mh->scale);
667     			left = 100 - ((left * 100) / mh->scale);
668     		}
669     
670     		ret = left | (right << 8);
671     	} else if (mixer == SOUND_MIXER_SPEAKER) {
672     		ret = 100 - ((((val & 0x1e)>>1) * 100) / mh->scale);
673     	} else if (mixer == SOUND_MIXER_MIC) {
674     		ret = 100 - (((val & 0x1f) * 100) / mh->scale);
675     	/*  the low bit is optional in the tone sliders and masking
676     		it lets is avoid the 0xf 'bypass'.. */
677     	} else if (mixer == SOUND_MIXER_BASS) {
678     		ret = 100 - ((((val >> 8) & 0xe) * 100) / mh->scale);
679     	} else if (mixer == SOUND_MIXER_TREBLE) {
680     		ret = 100 - (((val & 0xe) * 100) / mh->scale);
681     	}
682     
683     	M_printk("read mixer %d (0x%x) %x -> %x\n",mixer,mh->offset,val,ret);
684     
685     	return ret;
686     }
687     #endif
688     
689     /* write the OSS encoded volume to the given OSS encoded mixer,
690     	again caller's job to make sure all is well in arg land,
691     	call with spinlock held */
692     	
693     /* linear scale -> log */
694     static unsigned char lin2log[101] = 
695     {
696     0, 0 , 15 , 23 , 30 , 34 , 38 , 42 , 45 , 47 ,
697     50 , 52 , 53 , 55 , 57 , 58 , 60 , 61 , 62 ,
698     63 , 65 , 66 , 67 , 68 , 69 , 69 , 70 , 71 ,
699     72 , 73 , 73 , 74 , 75 , 75 , 76 , 77 , 77 ,
700     78 , 78 , 79 , 80 , 80 , 81 , 81 , 82 , 82 ,
701     83 , 83 , 84 , 84 , 84 , 85 , 85 , 86 , 86 ,
702     87 , 87 , 87 , 88 , 88 , 88 , 89 , 89 , 89 ,
703     90 , 90 , 90 , 91 , 91 , 91 , 92 , 92 , 92 ,
704     93 , 93 , 93 , 94 , 94 , 94 , 94 , 95 , 95 ,
705     95 , 95 , 96 , 96 , 96 , 96 , 97 , 97 , 97 ,
706     97 , 98 , 98 , 98 , 98 , 99 , 99 , 99 , 99 , 99 
707     };
708     
709     static void ac97_write_mixer(struct ess_card *card,int mixer, unsigned int left, unsigned int right)
710     {
711     	u16 val=0;
712     	struct ac97_mixer_hw *mh = &ac97_hw[mixer];
713     
714     	M_printk("wrote mixer %d (0x%x) %d,%d",mixer,mh->offset,left,right);
715     
716     	if(AC97_STEREO_MASK & (1<<mixer)) {
717     		/* stereo mixers, mute them if we can */
718     
719     		if (mixer == SOUND_MIXER_IGAIN) {
720     			/* igain's slider is reversed.. */
721     			right = (right * mh->scale) / 100;
722     			left = (left * mh->scale) / 100;
723     			if ((left == 0) && (right == 0))
724     				val |= 0x8000;
725     		} else {
726     			/* log conversion for the stereo controls */
727     			if((left == 0) && (right == 0))
728     				val = 0x8000;
729     			right = ((100 - lin2log[right]) * mh->scale) / 100;
730     			left = ((100 - lin2log[left]) * mh->scale) / 100;
731     		}
732     
733     		val |= (left << 8) | right;
734     
735     	} else if (mixer == SOUND_MIXER_SPEAKER) {
736     		val = (((100 - left) * mh->scale) / 100) << 1;
737     	} else if (mixer == SOUND_MIXER_MIC) {
738     		val = maestro_ac97_get(card, mh->offset) & ~0x801f;
739     		val |= (((100 - left) * mh->scale) / 100);
740     	/*  the low bit is optional in the tone sliders and masking
741     		it lets is avoid the 0xf 'bypass'.. */
742     	} else if (mixer == SOUND_MIXER_BASS) {
743     		val = maestro_ac97_get(card , mh->offset) & ~0x0f00;
744     		val |= ((((100 - left) * mh->scale) / 100) << 8) & 0x0e00;
745     	} else if (mixer == SOUND_MIXER_TREBLE)  {
746     		val = maestro_ac97_get(card , mh->offset) & ~0x000f;
747     		val |= (((100 - left) * mh->scale) / 100) & 0x000e;
748     	}
749     
750     	maestro_ac97_set(card , mh->offset, val);
751     	
752     	M_printk(" -> %x\n",val);
753     }
754     
755     /* the following tables allow us to go from 
756     	OSS <-> ac97 quickly. */
757     
758     enum ac97_recsettings {
759     	AC97_REC_MIC=0,
760     	AC97_REC_CD,
761     	AC97_REC_VIDEO,
762     	AC97_REC_AUX,
763     	AC97_REC_LINE,
764     	AC97_REC_STEREO, /* combination of all enabled outputs..  */
765     	AC97_REC_MONO,        /*.. or the mono equivalent */
766     	AC97_REC_PHONE        
767     };
768     
769     static unsigned int ac97_oss_mask[] = {
770     	[AC97_REC_MIC] = SOUND_MASK_MIC, 
771     	[AC97_REC_CD] = SOUND_MASK_CD, 
772     	[AC97_REC_VIDEO] = SOUND_MASK_VIDEO, 
773     	[AC97_REC_AUX] = SOUND_MASK_LINE1, 
774     	[AC97_REC_LINE] = SOUND_MASK_LINE, 
775     	[AC97_REC_PHONE] = SOUND_MASK_PHONEIN
776     };
777     
778     /* indexed by bit position */
779     static unsigned int ac97_oss_rm[] = {
780     	[SOUND_MIXER_MIC] = AC97_REC_MIC,
781     	[SOUND_MIXER_CD] = AC97_REC_CD,
782     	[SOUND_MIXER_VIDEO] = AC97_REC_VIDEO,
783     	[SOUND_MIXER_LINE1] = AC97_REC_AUX,
784     	[SOUND_MIXER_LINE] = AC97_REC_LINE,
785     	[SOUND_MIXER_PHONEIN] = AC97_REC_PHONE
786     };
787     	
788     /* read or write the recmask 
789     	the ac97 can really have left and right recording
790     	inputs independantly set, but OSS doesn't seem to 
791     	want us to express that to the user. 
792     	the caller guarantees that we have a supported bit set,
793     	and they must be holding the card's spinlock */
794     static int 
795     ac97_recmask_io(struct ess_card *card, int read, int mask) 
796     {
797     	unsigned int val = ac97_oss_mask[ maestro_ac97_get(card, 0x1a) & 0x7 ];
798     
799     	if (read) return val;
800     
801     	/* oss can have many inputs, maestro cant.  try
802     		to pick the 'new' one */
803     
804     	if (mask != val) mask &= ~val;
805     
806     	val = ffs(mask) - 1; 
807     	val = ac97_oss_rm[val];
808     	val |= val << 8;  /* set both channels */
809     
810     	M_printk("maestro: setting ac97 recmask to 0x%x\n",val);
811     
812     	maestro_ac97_set(card,0x1a,val);
813     
814     	return 0;
815     };
816     
817     /*
818      *	The Maestro can be wired to a standard AC97 compliant codec
819      *	(see www.intel.com for the pdf's on this), or to a PT101 codec
820      *	which appears to be the ES1918 (data sheet on the esstech.com.tw site)
821      *
822      *	The PT101 setup is untested.
823      */
824      
825     static u16 __init maestro_ac97_init(struct ess_card *card)
826     {
827     	u16 vend1, vend2, caps;
828     
829     	card->mix.supported_mixers = AC97_SUPPORTED_MASK;
830     	card->mix.stereo_mixers = AC97_STEREO_MASK;
831     	card->mix.record_sources = AC97_RECORD_MASK;
832     /*	card->mix.read_mixer = ac97_read_mixer;*/
833     	card->mix.write_mixer = ac97_write_mixer;
834     	card->mix.recmask_io = ac97_recmask_io;
835     
836     	vend1 = maestro_ac97_get(card, 0x7c);
837     	vend2 = maestro_ac97_get(card, 0x7e);
838     
839     	caps = maestro_ac97_get(card, 0x00);
840     
841     	printk(KERN_INFO "maestro: AC97 Codec detected: v: 0x%2x%2x caps: 0x%x pwr: 0x%x\n",
842     		vend1,vend2,caps,maestro_ac97_get(card,0x26) & 0xf);
843     
844     	if (! (caps & 0x4) ) {
845     		/* no bass/treble nobs */
846     		card->mix.supported_mixers &= ~(SOUND_MASK_BASS|SOUND_MASK_TREBLE);
847     	}
848     
849     	/* XXX endianness, dork head. */
850     	/* vendor specifc bits.. */
851     	switch ((long)(vend1 << 16) | vend2) {
852     	case 0x545200ff:	/* TriTech */
853     		/* no idea what this does */
854     		maestro_ac97_set(card,0x2a,0x0001);
855     		maestro_ac97_set(card,0x2c,0x0000);
856     		maestro_ac97_set(card,0x2c,0xffff);
857     		break;
858     #if 0	/* i thought the problems I was seeing were with
859     	the 1921, but apparently they were with the pci board
860     	it was on, so this code is commented out.
861     	 lets see if this holds true. */
862     	case 0x83847609:	/* ESS 1921 */
863     		/* writing to 0xe (mic) or 0x1a (recmask) seems
864     			to hang this codec */
865     		card->mix.supported_mixers &= ~(SOUND_MASK_MIC);
866     		card->mix.record_sources = 0;
867     		card->mix.recmask_io = NULL;
868     #if 0	/* don't ask.  I have yet to see what these actually do. */
869     		maestro_ac97_set(card,0x76,0xABBA); /* o/~ Take a chance on me o/~ */
870     		udelay(20);
871     		maestro_ac97_set(card,0x78,0x3002);
872     		udelay(20);
873     		maestro_ac97_set(card,0x78,0x3802);
874     		udelay(20);
875     #endif
876     		break;
877     #endif
878     	default: break;
879     	}
880     
881     	maestro_ac97_set(card, 0x1E, 0x0404);
882     	/* null misc stuff */
883     	maestro_ac97_set(card, 0x20, 0x0000);
884     
885     	return 0;
886     }
887     
888     #if 0  /* there has been 1 person on the planet with a pt101 that we
889     	know of.  If they care, they can put this back in :) */
890     static u16 maestro_pt101_init(struct ess_card *card,int iobase)
891     {
892     	printk(KERN_INFO "maestro: PT101 Codec detected, initializing but _not_ installing mixer device.\n");
893     	/* who knows.. */
894     	maestro_ac97_set(iobase, 0x2A, 0x0001);
895     	maestro_ac97_set(iobase, 0x2C, 0x0000);
896     	maestro_ac97_set(iobase, 0x2C, 0xFFFF);
897     	maestro_ac97_set(iobase, 0x10, 0x9F1F);
898     	maestro_ac97_set(iobase, 0x12, 0x0808);
899     	maestro_ac97_set(iobase, 0x14, 0x9F1F);
900     	maestro_ac97_set(iobase, 0x16, 0x9F1F);
901     	maestro_ac97_set(iobase, 0x18, 0x0404);
902     	maestro_ac97_set(iobase, 0x1A, 0x0000);
903     	maestro_ac97_set(iobase, 0x1C, 0x0000);
904     	maestro_ac97_set(iobase, 0x02, 0x0404);
905     	maestro_ac97_set(iobase, 0x04, 0x0808);
906     	maestro_ac97_set(iobase, 0x0C, 0x801F);
907     	maestro_ac97_set(iobase, 0x0E, 0x801F);
908     	return 0;
909     }
910     #endif
911     
912     /* this is very magic, and very slow.. */
913     static void 
914     maestro_ac97_reset(int ioaddr, struct pci_dev *pcidev)
915     {
916     	u16 save_68;
917     	u16 w;
918     	u32 vend;
919     
920     	outw( inw(ioaddr + 0x38) & 0xfffc, ioaddr + 0x38);
921     	outw( inw(ioaddr + 0x3a) & 0xfffc, ioaddr + 0x3a);
922     	outw( inw(ioaddr + 0x3c) & 0xfffc, ioaddr + 0x3c);
923     
924     	/* reset the first codec */
925     	outw(0x0000,  ioaddr+0x36);
926     	save_68 = inw(ioaddr+0x68);
927     	pci_read_config_word(pcidev, 0x58, &w);	/* something magical with gpio and bus arb. */
928     	pci_read_config_dword(pcidev, PCI_SUBSYSTEM_VENDOR_ID, &vend);
929     	if( w & 0x1)
930     		save_68 |= 0x10;
931     	outw(0xfffe, ioaddr + 0x64);	/* tickly gpio 0.. */
932     	outw(0x0001, ioaddr + 0x68);
933     	outw(0x0000, ioaddr + 0x60);
934     	udelay(20);
935     	outw(0x0001, ioaddr + 0x60);
936     	mdelay(20);
937     
938     	outw(save_68 | 0x1, ioaddr + 0x68);	/* now restore .. */
939     	outw( (inw(ioaddr + 0x38) & 0xfffc)|0x1, ioaddr + 0x38);
940     	outw( (inw(ioaddr + 0x3a) & 0xfffc)|0x1, ioaddr + 0x3a);
941     	outw( (inw(ioaddr + 0x3c) & 0xfffc)|0x1, ioaddr + 0x3c);
942     
943     	/* now the second codec */
944     	outw(0x0000,  ioaddr+0x36);
945     	outw(0xfff7, ioaddr + 0x64);
946     	save_68 = inw(ioaddr+0x68);
947     	outw(0x0009, ioaddr + 0x68);
948     	outw(0x0001, ioaddr + 0x60);
949     	udelay(20);
950     	outw(0x0009, ioaddr + 0x60);
951     	mdelay(500);	/* .. ouch.. */
952     	outw( inw(ioaddr + 0x38) & 0xfffc, ioaddr + 0x38);
953     	outw( inw(ioaddr + 0x3a) & 0xfffc, ioaddr + 0x3a);
954     	outw( inw(ioaddr + 0x3c) & 0xfffc, ioaddr + 0x3c);
955     
956     #if 0 /* the loop here needs to be much better if we want it.. */
957     	M_printk("trying software reset\n");
958     	/* try and do a software reset */
959     	outb(0x80|0x7c, ioaddr + 0x30);
960     	for (w=0; ; w++) {
961     		if ((inw(ioaddr+ 0x30) & 1) == 0) {
962     			if(inb(ioaddr + 0x32) !=0) break;
963     
964     			outb(0x80|0x7d, ioaddr + 0x30);
965     			if (((inw(ioaddr+ 0x30) & 1) == 0) && (inb(ioaddr + 0x32) !=0)) break;
966     			outb(0x80|0x7f, ioaddr + 0x30);
967     			if (((inw(ioaddr+ 0x30) & 1) == 0) && (inb(ioaddr + 0x32) !=0)) break;
968     		}
969     
970     		if( w > 10000) {
971     			outb( inb(ioaddr + 0x37) | 0x08, ioaddr + 0x37);  /* do a software reset */
972     			mdelay(500); /* oh my.. */
973     			outb( inb(ioaddr + 0x37) & ~0x08, ioaddr + 0x37);  
974     			udelay(1);
975     			outw( 0x80, ioaddr+0x30);
976     			for(w = 0 ; w < 10000; w++) {
977     				if((inw(ioaddr + 0x30) & 1) ==0) break;
978     			}
979     		}
980     	}
981     #endif
982     	if ( vend == NEC_VERSA_SUBID1 || vend == NEC_VERSA_SUBID2) {
983     		/* turn on external amp? */
984     		outw(0xf9ff, ioaddr + 0x64);
985     		outw(inw(ioaddr+0x68) | 0x600, ioaddr + 0x68);
986     		outw(0x0209, ioaddr + 0x60);
987     	}
988     
989     	/* Turn on the 978 docking chip.
990     	   First frob the "master output enable" bit,
991     	   then set most of the playback volume control registers to max. */
992     	outb(inb(ioaddr+0xc0)|(1<<5), ioaddr+0xc0);
993     	outb(0xff, ioaddr+0xc3);
994     	outb(0xff, ioaddr+0xc4);
995     	outb(0xff, ioaddr+0xc6);
996     	outb(0xff, ioaddr+0xc8);
997     	outb(0x3f, ioaddr+0xcf);
998     	outb(0x3f, ioaddr+0xd0);
999     }
1000     /*
1001      *	Indirect register access. Not all registers are readable so we
1002      *	need to keep register state ourselves
1003      */
1004      
1005     #define WRITEABLE_MAP	0xEFFFFF
1006     #define READABLE_MAP	0x64003F
1007     
1008     /*
1009      *	The Maestro engineers were a little indirection happy. These indirected
1010      *	registers themselves include indirect registers at another layer
1011      */
1012     
1013     static void __maestro_write(struct ess_card *card, u16 reg, u16 data)
1014     {
1015     	long ioaddr = card->iobase;
1016     
1017     	outw(reg, ioaddr+0x02);
1018     	outw(data, ioaddr+0x00);
1019     	if( reg >= NR_IDRS) printk("maestro: IDR %d out of bounds!\n",reg);
1020     	else card->maestro_map[reg]=data;
1021     
1022     }
1023      
1024     static void maestro_write(struct ess_state *s, u16 reg, u16 data)
1025     {
1026     	unsigned long flags;
1027     
1028     	check_suspend(s->card);
1029     	spin_lock_irqsave(&s->card->lock,flags);
1030     
1031     	__maestro_write(s->card,reg,data);
1032     
1033     	spin_unlock_irqrestore(&s->card->lock,flags);
1034     }
1035     
1036     static u16 __maestro_read(struct ess_card *card, u16 reg)
1037     {
1038     	long ioaddr = card->iobase;
1039     
1040     	outw(reg, ioaddr+0x02);
1041     	return card->maestro_map[reg]=inw(ioaddr+0x00);
1042     }
1043     
1044     static u16 maestro_read(struct ess_state *s, u16 reg)
1045     {
1046     	if(READABLE_MAP & (1<<reg))
1047     	{
1048     		unsigned long flags;
1049     		check_suspend(s->card);
1050     		spin_lock_irqsave(&s->card->lock,flags);
1051     
1052     		__maestro_read(s->card,reg);
1053     
1054     		spin_unlock_irqrestore(&s->card->lock,flags);
1055     	}
1056     	return s->card->maestro_map[reg];
1057     }
1058     
1059     /*
1060      *	These routines handle accessing the second level indirections to the
1061      *	wave ram.
1062      */
1063     
1064     /*
1065      *	The register names are the ones ESS uses (see 104T31.ZIP)
1066      */
1067      
1068     #define IDR0_DATA_PORT		0x00
1069     #define IDR1_CRAM_POINTER	0x01
1070     #define IDR2_CRAM_DATA		0x02
1071     #define IDR3_WAVE_DATA		0x03
1072     #define IDR4_WAVE_PTR_LOW	0x04
1073     #define IDR5_WAVE_PTR_HI	0x05
1074     #define IDR6_TIMER_CTRL		0x06
1075     #define IDR7_WAVE_ROMRAM	0x07
1076     
1077     static void apu_index_set(struct ess_card *card, u16 index)
1078     {
1079     	int i;
1080     	__maestro_write(card, IDR1_CRAM_POINTER, index);
1081     	for(i=0;i<1000;i++)
1082     		if(__maestro_read(card, IDR1_CRAM_POINTER)==index)
1083     			return;
1084     	printk(KERN_WARNING "maestro: APU register select failed.\n");
1085     }
1086     
1087     static void apu_data_set(struct ess_card *card, u16 data)
1088     {
1089     	int i;
1090     	for(i=0;i<1000;i++)
1091     	{
1092     		if(__maestro_read(card, IDR0_DATA_PORT)==data)
1093     			return;
1094     		__maestro_write(card, IDR0_DATA_PORT, data);
1095     	}
1096     }
1097     
1098     /*
1099      *	This is the public interface for APU manipulation. It handles the
1100      *	interlock to avoid two APU writes in parallel etc. Don't diddle
1101      *	directly with the stuff above.
1102      */
1103     
1104     static void apu_set_register(struct ess_state *s, u16 channel, u8 reg, u16 data)
1105     {
1106     	unsigned long flags;
1107     	
1108     	check_suspend(s->card);
1109     
1110     	if(channel&ESS_CHAN_HARD)
1111     		channel&=~ESS_CHAN_HARD;
1112     	else
1113     	{
1114     		if(channel>5)
1115     			printk("BAD CHANNEL %d.\n",channel);
1116     		else
1117     			channel = s->apu[channel];
1118     		/* store based on real hardware apu/reg */
1119     		s->card->apu_map[channel][reg]=data;
1120     	}
1121     	reg|=(channel<<4);
1122     	
1123     	/* hooray for double indirection!! */
1124     	spin_lock_irqsave(&s->card->lock,flags);
1125     
1126     	apu_index_set(s->card, reg);
1127     	apu_data_set(s->card, data);
1128     
1129     	spin_unlock_irqrestore(&s->card->lock,flags);
1130     }
1131     
1132     static u16 apu_get_register(struct ess_state *s, u16 channel, u8 reg)
1133     {
1134     	unsigned long flags;
1135     	u16 v;
1136     	
1137     	check_suspend(s->card);
1138     
1139     	if(channel&ESS_CHAN_HARD)
1140     		channel&=~ESS_CHAN_HARD;
1141     	else
1142     		channel = s->apu[channel];
1143     
1144     	reg|=(channel<<4);
1145     	
1146     	spin_lock_irqsave(&s->card->lock,flags);
1147     
1148     	apu_index_set(s->card, reg);
1149     	v=__maestro_read(s->card, IDR0_DATA_PORT);
1150     
1151     	spin_unlock_irqrestore(&s->card->lock,flags);
1152     	return v;
1153     }
1154     
1155     
1156     /*
1157      *	The wavecache buffers between the APUs and
1158      *	pci bus mastering
1159      */
1160      
1161     static void wave_set_register(struct ess_state *s, u16 reg, u16 value)
1162     {
1163     	long ioaddr = s->card->iobase;
1164     	unsigned long flags;
1165     	check_suspend(s->card);
1166     	
1167     	spin_lock_irqsave(&s->card->lock,flags);
1168     
1169     	outw(reg, ioaddr+0x10);
1170     	outw(value, ioaddr+0x12);
1171     
1172     	spin_unlock_irqrestore(&s->card->lock,flags);
1173     }
1174     
1175     static u16 wave_get_register(struct ess_state *s, u16 reg)
1176     {
1177     	long ioaddr = s->card->iobase;
1178     	unsigned long flags;
1179     	u16 value;
1180     	check_suspend(s->card);
1181     	
1182     	spin_lock_irqsave(&s->card->lock,flags);
1183     	outw(reg, ioaddr+0x10);
1184     	value=inw(ioaddr+0x12);
1185     	spin_unlock_irqrestore(&s->card->lock,flags);
1186     	
1187     	return value;
1188     }
1189     
1190     static void sound_reset(int ioaddr)
1191     {
1192     	outw(0x2000, 0x18+ioaddr);
1193     	udelay(1);
1194     	outw(0x0000, 0x18+ioaddr);
1195     	udelay(1);
1196     }
1197     
1198     /* sets the play formats of these apus, should be passed the already shifted format */
1199     static void set_apu_fmt(struct ess_state *s, int apu, int mode)
1200     {
1201     	int apu_fmt = 0x10;
1202     
1203     	if(!(mode&ESS_FMT_16BIT)) apu_fmt+=0x20; 
1204     	if((mode&ESS_FMT_STEREO)) apu_fmt+=0x10; 
1205     	s->apu_mode[apu]   = apu_fmt;
1206     	s->apu_mode[apu+1] = apu_fmt;
1207     }
1208     
1209     /* this only fixes the output apu mode to be later set by start_dac and
1210     	company.  output apu modes are set in ess_rec_setup */
1211     static void set_fmt(struct ess_state *s, unsigned char mask, unsigned char data)
1212     {
1213     	s->fmt = (s->fmt & mask) | data;
1214     	set_apu_fmt(s, 0, (s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK);
1215     }
1216     
1217     /* this is off by a little bit.. */
1218     static u32 compute_rate(struct ess_state *s, u32 freq)
1219     {
1220     	u32 clock = clock_freq[s->card->card_type];     
1221     
1222     	freq = (freq * clocking)/48000;
1223     	
1224     	if (freq == 48000) 
1225     		return 0x10000;
1226     
1227     	return ((freq / clock) <<16 )+  
1228     		(((freq % clock) << 16) / clock);
1229     }
1230     
1231     static void set_dac_rate(struct ess_state *s, unsigned int rate)
1232     {
1233     	u32 freq;
1234     	int fmt = (s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK;
1235     
1236     	if (rate > 48000)
1237     		rate = 48000;
1238     	if (rate < 4000)
1239     		rate = 4000;
1240     
1241     	s->ratedac = rate;
1242     
1243     	if(! (fmt & ESS_FMT_16BIT) && !(fmt & ESS_FMT_STEREO))
1244     		rate >>= 1;
1245     
1246     /*	M_printk("computing dac rate %d with mode %d\n",rate,s->fmt);*/
1247     
1248     	freq = compute_rate(s, rate);
1249     	
1250     	/* Load the frequency, turn on 6dB */
1251     	apu_set_register(s, 0, 2,(apu_get_register(s, 0, 2)&0x00FF)|
1252     		( ((freq&0xFF)<<8)|0x10 ));
1253     	apu_set_register(s, 0, 3, freq>>8);
1254     	apu_set_register(s, 1, 2,(apu_get_register(s, 1, 2)&0x00FF)|
1255     		( ((freq&0xFF)<<8)|0x10 ));
1256     	apu_set_register(s, 1, 3, freq>>8);
1257     }
1258     
1259     static void set_adc_rate(struct ess_state *s, unsigned rate)
1260     {
1261     	u32 freq;
1262     
1263     	/* Sample Rate conversion APUs don't like 0x10000 for their rate */
1264     	if (rate > 47999)
1265     		rate = 47999;
1266     	if (rate < 4000)
1267     		rate = 4000;
1268     
1269     	s->rateadc = rate;
1270     
1271     	freq = compute_rate(s, rate);
1272     	
1273     	/* Load the frequency, turn on 6dB */
1274     	apu_set_register(s, 2, 2,(apu_get_register(s, 2, 2)&0x00FF)|
1275     		( ((freq&0xFF)<<8)|0x10 ));
1276     	apu_set_register(s, 2, 3, freq>>8);
1277     	apu_set_register(s, 3, 2,(apu_get_register(s, 3, 2)&0x00FF)|
1278     		( ((freq&0xFF)<<8)|0x10 ));
1279     	apu_set_register(s, 3, 3, freq>>8);
1280     
1281     	/* fix mixer rate at 48khz.  and its _must_ be 0x10000. */
1282     	freq = 0x10000;
1283     
1284     	apu_set_register(s, 4, 2,(apu_get_register(s, 4, 2)&0x00FF)|
1285     		( ((freq&0xFF)<<8)|0x10 ));
1286     	apu_set_register(s, 4, 3, freq>>8);
1287     	apu_set_register(s, 5, 2,(apu_get_register(s, 5, 2)&0x00FF)|
1288     		( ((freq&0xFF)<<8)|0x10 ));
1289     	apu_set_register(s, 5, 3, freq>>8);
1290     }
1291     
1292     /* Stop our host of recording apus */
1293     static inline void stop_adc(struct ess_state *s)
1294     {
1295     	/* XXX lets hope we don't have to lock around this */
1296     	if (! (s->enable & ADC_RUNNING)) return;
1297     
1298     	s->enable &= ~ADC_RUNNING;
1299     	apu_set_register(s, 2, 0, apu_get_register(s, 2, 0)&0xFF0F);
1300     	apu_set_register(s, 3, 0, apu_get_register(s, 3, 0)&0xFF0F);
1301     	apu_set_register(s, 4, 0, apu_get_register(s, 2, 0)&0xFF0F);
1302     	apu_set_register(s, 5, 0, apu_get_register(s, 3, 0)&0xFF0F);
1303     }	
1304     
1305     /* stop output apus */
1306     static void stop_dac(struct ess_state *s)
1307     {
1308     	/* XXX have to lock around this? */
1309     	if (! (s->enable & DAC_RUNNING)) return;
1310     
1311     	s->enable &= ~DAC_RUNNING;
1312     	apu_set_register(s, 0, 0, apu_get_register(s, 0, 0)&0xFF0F);
1313     	apu_set_register(s, 1, 0, apu_get_register(s, 1, 0)&0xFF0F);
1314     }	
1315     
1316     static void start_dac(struct ess_state *s)
1317     {
1318     	/* XXX locks? */
1319     	if (	(s->dma_dac.mapped || s->dma_dac.count > 0) && 
1320     		s->dma_dac.ready &&
1321     		(! (s->enable & DAC_RUNNING)) ) {
1322     
1323     		s->enable |= DAC_RUNNING;
1324     
1325     		apu_set_register(s, 0, 0, 
1326     			(apu_get_register(s, 0, 0)&0xFF0F)|s->apu_mode[0]);
1327     
1328     		if((s->fmt >> ESS_DAC_SHIFT)  & ESS_FMT_STEREO) 
1329     			apu_set_register(s, 1, 0, 
1330     				(apu_get_register(s, 1, 0)&0xFF0F)|s->apu_mode[1]);
1331     	}
1332     }	
1333     
1334     static void start_adc(struct ess_state *s)
1335     {
1336     	/* XXX locks? */
1337     	if ((s->dma_adc.mapped || s->dma_adc.count < (signed)(s->dma_adc.dmasize - 2*s->dma_adc.fragsize)) 
1338     	    && s->dma_adc.ready && (! (s->enable & ADC_RUNNING)) ) {
1339     
1340     		s->enable |= ADC_RUNNING;
1341     		apu_set_register(s, 2, 0, 
1342     			(apu_get_register(s, 2, 0)&0xFF0F)|s->apu_mode[2]);
1343     		apu_set_register(s, 4, 0, 
1344     			(apu_get_register(s, 4, 0)&0xFF0F)|s->apu_mode[4]);
1345     
1346     		if( s->fmt & (ESS_FMT_STEREO << ESS_ADC_SHIFT)) {
1347     			apu_set_register(s, 3, 0, 
1348     				(apu_get_register(s, 3, 0)&0xFF0F)|s->apu_mode[3]);
1349     			apu_set_register(s, 5, 0, 
1350     				(apu_get_register(s, 5, 0)&0xFF0F)|s->apu_mode[5]);
1351     		}
1352     			
1353     	}
1354     }	
1355     
1356     
1357     /*
1358      *	Native play back driver 
1359      */
1360     
1361     /* the mode passed should be already shifted and masked */
1362     static void 
1363     ess_play_setup(struct ess_state *ess, int mode, u32 rate, void *buffer, int size)
1364     {
1365     	u32 pa;
1366     	u32 tmpval;
1367     	int high_apu = 0;
1368     	int channel;
1369     
1370     	M_printk("mode=%d rate=%d buf=%p len=%d.\n",
1371     		mode, rate, buffer, size);
1372     		
1373     	/* all maestro sizes are in 16bit words */
1374     	size >>=1;
1375     
1376     	if(mode&ESS_FMT_STEREO) {
1377     		high_apu++;
1378     		/* only 16/stereo gets size divided */
1379     		if(mode&ESS_FMT_16BIT)
1380     			size>>=1;
1381     	}
1382     	
1383     	for(channel=0; channel <= high_apu; channel++)
1384     	{
1385     		pa = virt_to_bus(buffer);
1386     
1387     		/* set the wavecache control reg */
1388     		tmpval = (pa - 0x10) & 0xFFF8;
1389     		if(!(mode & ESS_FMT_16BIT)) tmpval |= 4;
1390     		if(mode & ESS_FMT_STEREO) tmpval |= 2;
1391     		ess->apu_base[channel]=tmpval;
1392     		wave_set_register(ess, ess->apu[channel]<<3, tmpval);
1393     		
1394     		pa -= virt_to_bus(ess->card->dmapages);
1395     		pa>>=1; /* words */
1396     		
1397     		/* base offset of dma calcs when reading the pointer
1398     			on the left one */
1399     		if(!channel) ess->dma_dac.base = pa&0xFFFF;
1400     		
1401     		pa|=0x00400000;			/* System RAM */
1402     
1403     		/* XXX the 16bit here might not be needed.. */
1404     		if((mode & ESS_FMT_STEREO) && (mode & ESS_FMT_16BIT)) {
1405     			if(channel) 
1406     				pa|=0x00800000;			/* Stereo */
1407     			pa>>=1;
1408     		}
1409     			
1410     /* XXX think about endianess when writing these registers */
1411     		M_printk("maestro: ess_play_setup: APU[%d] pa = 0x%x\n", ess->apu[channel], pa);
1412     		/* start of sample */
1413     		apu_set_register(ess, channel, 4, ((pa>>16)&0xFF)<<8);
1414     		apu_set_register(ess, channel, 5, pa&0xFFFF);
1415     		/* sample end */
1416     		apu_set_register(ess, channel, 6, (pa+size)&0xFFFF);
1417     		/* setting loop len == sample len */
1418     		apu_set_register(ess, channel, 7, size);
1419     		
1420     		/* clear effects/env.. */
1421     		apu_set_register(ess, channel, 8, 0x0000);
1422     		/* set amp now to 0xd0 (?), low byte is 'amplitude dest'? */
1423     		apu_set_register(ess, channel, 9, 0xD000);
1424     
1425     		/* clear routing stuff */
1426     		apu_set_register(ess, channel, 11, 0x0000);
1427     		/* dma on, no envelopes, filter to all 1s) */
1428     		apu_set_register(ess, channel, 0, 0x400F);
1429     		
1430     		if(mode&ESS_FMT_16BIT)
1431     			ess->apu_mode[channel]=0x10;
1432     		else
1433     			ess->apu_mode[channel]=0x30;
1434     
1435     		if(mode&ESS_FMT_STEREO) {
1436     			/* set panning: left or right */
1437     			apu_set_register(ess, channel, 10, 0x8F00 | (channel ? 0 : 0x10));
1438     			ess->apu_mode[channel] += 0x10;
1439     		} else
1440     			apu_set_register(ess, channel, 10, 0x8F08);
1441     	}
1442     	
1443     	/* clear WP interrupts */
1444     	outw(1, ess->card->iobase+0x04);
1445     	/* enable WP ints */
1446     	outw(inw(ess->card->iobase+0x18)|4, ess->card->iobase+0x18);
1447     
1448     	/* go team! */
1449     	set_dac_rate(ess,rate);
1450     	start_dac(ess);
1451     }
1452     
1453     /*
1454      *	Native record driver 
1455      */
1456     
1457     /* again, passed mode is alrady shifted/masked */
1458     static void 
1459     ess_rec_setup(struct ess_state *ess, int mode, u32 rate, void *buffer, int size)
1460     {
1461     	int apu_step = 2;
1462     	int channel;
1463     
1464     	M_printk("maestro: ess_rec_setup: mode=%d rate=%d buf=0x%p len=%d.\n",
1465     		mode, rate, buffer, size);
1466     		
1467     	/* all maestro sizes are in 16bit words */
1468     	size >>=1;
1469     
1470     	/* we're given the full size of the buffer, but
1471     	in stereo each channel will only use its half */
1472     	if(mode&ESS_FMT_STEREO) {
1473     		size >>=1; 
1474     		apu_step = 1;
1475     	}
1476     	
1477     	/* APU assignments: 2 = mono/left SRC
1478     	                    3 = right SRC
1479     	                    4 = mono/left Input Mixer
1480     	                    5 = right Input Mixer */
1481     	for(channel=2;channel<6;channel+=apu_step)
1482     	{
1483     		int i;
1484     		int bsize, route;
1485     		u32 pa;
1486     		u32 tmpval;
1487     
1488     		/* data seems to flow from the codec, through an apu into
1489     			the 'mixbuf' bit of page, then through the SRC apu
1490     			and out to the real 'buffer'.  ok.  sure.  */
1491     		
1492     		if(channel & 0x04) {
1493     			/* ok, we're an input mixer going from adc
1494     				through the mixbuf to the other apus */
1495     
1496     			if(!(channel & 0x01)) { 
1497     				pa = virt_to_bus(ess->mixbuf);
1498     			} else {
1499     				pa = virt_to_bus(ess->mixbuf + (PAGE_SIZE >> 4));
1500     			}
1501     
1502     			/* we source from a 'magic' apu */
1503     			bsize = PAGE_SIZE >> 5;	/* half of this channels alloc, in words */
1504     			route = 0x14 + (channel - 4); /* parallel in crap, see maestro reg 0xC [8-11] */
1505     			ess->apu_mode[channel] = 0x90;  /* Input Mixer */
1506     
1507     		} else {  
1508     			/* we're a rate converter taking
1509     				input from the input apus and outputing it to
1510     				system memory */
1511     			if(!(channel & 0x01))  {
1512     				pa = virt_to_bus(buffer);
1513     			} else {
1514     				/* right channel records its split half.
1515     				*2 accomodates for rampant shifting earlier */
1516     				pa = virt_to_bus(buffer + size*2);
1517     			}
1518     
1519     			ess->apu_mode[channel] = 0xB0;  /* Sample Rate Converter */
1520     
1521     			bsize = size; 
1522     			/* get input from inputing apu */
1523     			route = channel + 2;
1524     		}
1525     
1526     		M_printk("maestro: ess_rec_setup: getting pa 0x%x from %d\n",pa,channel);
1527     		
1528     		/* set the wavecache control reg */
1529     		tmpval = (pa - 0x10) & 0xFFF8;
1530     		ess->apu_base[channel]=tmpval;
1531     		wave_set_register(ess, ess->apu[channel]<<3, tmpval);
1532     		
1533     		pa -= virt_to_bus(ess->card->dmapages);
1534     		pa>>=1; /* words */
1535     		
1536     		/* base offset of dma calcs when reading the pointer
1537     			on this left one */
1538     		if(channel==2) ess->dma_adc.base = pa&0xFFFF;
1539     
1540     		pa|=0x00400000;			/* bit 22 -> System RAM */
1541     
1542     		M_printk("maestro: ess_rec_setup: APU[%d] pa = 0x%x size = 0x%x route = 0x%x\n", 
1543     			ess->apu[channel], pa, bsize, route);
1544     		
1545     		/* Begin loading the APU */		
1546     		for(i=0;i<15;i++)		/* clear all PBRs */
1547     			apu_set_register(ess, channel, i, 0x0000);
1548     			
1549     		apu_set_register(ess, channel, 0, 0x400F);
1550     
1551     		/* need to enable subgroups.. and we should probably
1552     			have different groups for different /dev/dsps..  */
1553      		apu_set_register(ess, channel, 2, 0x8);
1554     				
1555     		/* Load the buffer into the wave engine */
1556     		apu_set_register(ess, channel, 4, ((pa>>16)&0xFF)<<8);
1557     		/* XXX reg is little endian.. */
1558     		apu_set_register(ess, channel, 5, pa&0xFFFF);
1559     		apu_set_register(ess, channel, 6, (pa+bsize)&0xFFFF);
1560     		apu_set_register(ess, channel, 7, bsize);
1561     				
1562     		/* clear effects/env.. */
1563     		apu_set_register(ess, channel, 8, 0x00F0);
1564     		
1565     		/* amplitude now?  sure.  why not.  */
1566     		apu_set_register(ess, channel, 9, 0x0000);
1567     
1568     		/* set filter tune, radius, polar pan */
1569     		apu_set_register(ess, channel, 10, 0x8F08);
1570     
1571     		/* route input */
1572     		apu_set_register(ess, channel, 11, route);
1573     	}
1574     	
1575     	/* clear WP interrupts */
1576     	outw(1, ess->card->iobase+0x04);
1577     	/* enable WP ints */
1578     	outw(inw(ess->card->iobase+0x18)|4, ess->card->iobase+0x18);
1579     
1580     	/* let 'er rip */
1581     	set_adc_rate(ess,rate);
1582     	start_adc(ess);
1583     }
1584     /* --------------------------------------------------------------------- */
1585     
1586     static void set_dmaa(struct ess_state *s, unsigned int addr, unsigned int count)
1587     {
1588     	M_printk("set_dmaa??\n");
1589     }
1590     
1591     static void set_dmac(struct ess_state *s, unsigned int addr, unsigned int count)
1592     {
1593     	M_printk("set_dmac??\n");
1594     }
1595     
1596     /* Playback pointer */
1597     static inline unsigned get_dmaa(struct ess_state *s)
1598     {
1599     	int offset;
1600     
1601     	offset = apu_get_register(s,0,5);
1602     
1603     /*	M_printk("dmaa: offset: %d, base: %d\n",offset,s->dma_dac.base); */
1604     	
1605     	offset-=s->dma_dac.base;
1606     
1607     	return (offset&0xFFFE)<<1; /* hardware is in words */
1608     }
1609     
1610     /* Record pointer */
1611     static inline unsigned get_dmac(struct ess_state *s)
1612     {
1613     	int offset;
1614     
1615     	offset = apu_get_register(s,2,5);
1616     
1617     /*	M_printk("dmac: offset: %d, base: %d\n",offset,s->dma_adc.base); */
1618     	
1619     	/* The offset is an address not a position relative to base */
1620     	offset-=s->dma_adc.base;
1621     	
1622     	return (offset&0xFFFE)<<1; /* hardware is in words */
1623     }
1624     
1625     /*
1626      *	Meet Bob, the timer...
1627      */
1628     
1629     static void ess_interrupt(int irq, void *dev_id, struct pt_regs *regs);
1630     
1631     static void stop_bob(struct ess_state *s)
1632     {
1633     	/* Mask IDR 11,17 */
1634     	maestro_write(s,  0x11, maestro_read(s, 0x11)&~1);
1635     	maestro_write(s,  0x17, maestro_read(s, 0x17)&~1);
1636     }
1637     
1638     /* eventually we could be clever and limit bob ints
1639     	to the frequency at which our smallest duration
1640     	chunks may expire */
1641     #define ESS_SYSCLK	50000000
1642     static void start_bob(struct ess_state *s)
1643     {
1644     	int prescale;
1645     	int divide;
1646     	
1647     	/* XXX make freq selector much smarter, see calc_bob_rate */
1648     	int freq = 200; 
1649     	
1650     	/* compute ideal interrupt frequency for buffer size & play rate */
1651     	/* first, find best prescaler value to match freq */
1652     	for(prescale=5;prescale<12;prescale++)
1653     		if(freq > (ESS_SYSCLK>>(prescale+9)))
1654     			break;
1655     			
1656     	/* next, back off prescaler whilst getting divider into optimum range */
1657     	divide=1;
1658     	while((prescale > 5) && (divide<32))
1659     	{
1660     		prescale--;
1661     		divide <<=1;
1662     	}
1663     	divide>>=1;
1664     	
1665     	/* now fine-tune the divider for best match */
1666     	for(;divide<31;divide++)
1667     		if(freq >= ((ESS_SYSCLK>>(prescale+9))/(divide+1)))
1668     			break;
1669     	
1670     	/* divide = 0 is illegal, but don't let prescale = 4! */
1671     	if(divide == 0)
1672     	{
1673     		divide++;
1674     		if(prescale>5)
1675     			prescale--;
1676     	}
1677     
1678     	maestro_write(s, 6, 0x9000 | (prescale<<5) | divide); /* set reg */
1679     	
1680     	/* Now set IDR 11/17 */
1681     	maestro_write(s, 0x11, maestro_read(s, 0x11)|1);
1682     	maestro_write(s, 0x17, maestro_read(s, 0x17)|1);
1683     }
1684     /* --------------------------------------------------------------------- */
1685     
1686     /* this quickly calculates the frequency needed for bob
1687     	and sets it if its different than what bob is
1688     	currently running at.  its called often so 
1689     	needs to be fairly quick. */
1690     #define BOB_MIN 50
1691     #define BOB_MAX 400
1692     static void calc_bob_rate(struct ess_state *s) {
1693     #if 0 /* this thing tries to set the frequency of bob such that
1694     	there are 2 interrupts / buffer walked by the dac/adc.  That
1695     	is probably very wrong for people who actually care about 
1696     	mid buffer positioning.  it should be calculated as bytes/interrupt
1697     	and that needs to be decided :)  so for now just use the static 150
1698     	in start_bob.*/
1699     
1700     	unsigned int dac_rate=2,adc_rate=1,newrate;
1701     	static int israte=-1;
1702     
1703     	if (s->dma_dac.fragsize == 0) dac_rate = BOB_MIN;
1704     	else  {
1705     		dac_rate =	(2 * s->ratedac * sample_size[(s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK]) /
1706     				(s->dma_dac.fragsize) ;
1707     	}
1708     		
1709     	if (s->dma_adc.fragsize == 0) adc_rate = BOB_MIN;
1710     	else {
1711     		adc_rate =	(2 * s->rateadc * sample_size[(s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK]) /
1712     				(s->dma_adc.fragsize) ;
1713     	}
1714     
1715     	if(dac_rate > adc_rate) newrate = adc_rate;
1716     	else newrate=dac_rate;
1717     
1718     	if(newrate > BOB_MAX) newrate = BOB_MAX;
1719     	else {
1720     		if(newrate < BOB_MIN) 
1721     			newrate = BOB_MIN;
1722     	}
1723     
1724     	if( israte != newrate) {
1725     		printk("dac: %d  adc: %d rate: %d\n",dac_rate,adc_rate,israte);
1726     		israte=newrate;
1727     	}
1728     #endif
1729     
1730     }
1731     
1732     static int 
1733     prog_dmabuf(struct ess_state *s, unsigned rec)
1734     {
1735     	struct dmabuf *db = rec ? &s->dma_adc : &s->dma_dac;
1736     	unsigned rate = rec ? s->rateadc : s->ratedac;
1737     	unsigned bytepersec;
1738     	unsigned bufs;
1739     	unsigned char fmt;
1740     	unsigned long flags;
1741     
1742     	spin_lock_irqsave(&s->lock, flags);
1743     	fmt = s->fmt;
1744     	if (rec) {
1745     		stop_adc(s);
1746     		fmt >>= ESS_ADC_SHIFT;
1747     	} else {
1748     		stop_dac(s);
1749     		fmt >>= ESS_DAC_SHIFT;
1750     	}
1751     	spin_unlock_irqrestore(&s->lock, flags);
1752     	fmt &= ESS_FMT_MASK;
1753     
1754     	db->hwptr = db->swptr = db->total_bytes = db->count = db->error = db->endcleared = 0;
1755     
1756     	/* this algorithm is a little nuts.. where did /1000 come from? */
1757     	bytepersec = rate << sample_shift[fmt];
1758     	bufs = PAGE_SIZE << db->buforder;
1759     	if (db->ossfragshift) {
1760     		if ((1000 << db->ossfragshift) < bytepersec)
1761     			db->fragshift = ld2(bytepersec/1000);
1762     		else
1763     			db->fragshift = db->ossfragshift;
1764     	} else {
1765     		db->fragshift = ld2(bytepersec/100/(db->subdivision ? db->subdivision : 1));
1766     		if (db->fragshift < 3)
1767     			db->fragshift = 3; 
1768     	}
1769     	db->numfrag = bufs >> db->fragshift;
1770     	while (db->numfrag < 4 && db->fragshift > 3) {
1771     		db->fragshift--;
1772     		db->numfrag = bufs >> db->fragshift;
1773     	}
1774     	db->fragsize = 1 << db->fragshift;
1775     	if (db->ossmaxfrags >= 4 && db->ossmaxfrags < db->numfrag)
1776     		db->numfrag = db->ossmaxfrags;
1777     	db->fragsamples = db->fragsize >> sample_shift[fmt];
1778     	db->dmasize = db->numfrag << db->fragshift;
1779     
1780     	M_printk("maestro: setup oss: numfrag: %d fragsize: %d dmasize: %d\n",db->numfrag,db->fragsize,db->dmasize);
1781     
1782     	memset(db->rawbuf, (fmt & ESS_FMT_16BIT) ? 0 : 0x80, db->dmasize);
1783     
1784     	spin_lock_irqsave(&s->lock, flags);
1785     	if (rec) 
1786     		ess_rec_setup(s, fmt, s->rateadc, db->rawbuf, db->dmasize);
1787     	else 
1788     		ess_play_setup(s, fmt, s->ratedac, db->rawbuf, db->dmasize);
1789     
1790     	spin_unlock_irqrestore(&s->lock, flags);
1791     	db->ready = 1;
1792     
1793     	return 0;
1794     }
1795     
1796     static __inline__ void 
1797     clear_advance(struct ess_state *s)
1798     {
1799     	unsigned char c = ((s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_16BIT) ? 0 : 0x80;
1800     	
1801     	unsigned char *buf = s->dma_dac.rawbuf;
1802     	unsigned bsize = s->dma_dac.dmasize;
1803     	unsigned bptr = s->dma_dac.swptr;
1804     	unsigned len = s->dma_dac.fragsize;
1805     	
1806     	if (bptr + len > bsize) {
1807     		unsigned x = bsize - bptr;
1808     		memset(buf + bptr, c, x);
1809     		/* account for wrapping? */
1810     		bptr = 0;
1811     		len -= x;
1812     	}
1813     	memset(buf + bptr, c, len);
1814     }
1815     
1816     /* call with spinlock held! */
1817     static void 
1818     ess_update_ptr(struct ess_state *s)
1819     {
1820     	unsigned hwptr;
1821     	int diff;
1822     
1823     	/* update ADC pointer */
1824     	if (s->dma_adc.ready) {
1825     		/* oh boy should this all be re-written.  everything in the current code paths think
1826     		that the various counters/pointers are expressed in bytes to the user but we have
1827     		two apus doing stereo stuff so we fix it up here.. it propogates to all the various
1828     		counters from here.  */
1829     		if ( s->fmt & (ESS_FMT_STEREO << ESS_ADC_SHIFT)) {
1830     			hwptr = (get_dmac(s)*2) % s->dma_adc.dmasize;
1831     		} else {
1832     			hwptr = get_dmac(s) % s->dma_adc.dmasize;
1833     		}
1834     		diff = (s->dma_adc.dmasize + hwptr - s->dma_adc.hwptr) % s->dma_adc.dmasize;
1835     		s->dma_adc.hwptr = hwptr;
1836     		s->dma_adc.total_bytes += diff;
1837     		s->dma_adc.count += diff;
1838     		if (s->dma_adc.count >= (signed)s->dma_adc.fragsize) 
1839     			wake_up(&s->dma_adc.wait);
1840     		if (!s->dma_adc.mapped) {
1841     			if (s->dma_adc.count > (signed)(s->dma_adc.dmasize - ((3 * s->dma_adc.fragsize) >> 1))) {
1842     				/* FILL ME 
1843     				wrindir(s, SV_CIENABLE, s->enable); */
1844     				stop_adc(s); 
1845     				/* brute force everyone back in sync, sigh */
1846     				s->dma_adc.count = 0;
1847     				s->dma_adc.swptr = 0;
1848     				s->dma_adc.hwptr = 0;
1849     				s->dma_adc.error++;
1850     			}
1851     		}
1852     	}
1853     	/* update DAC pointer */
1854     	if (s->dma_dac.ready) {
1855     		hwptr = get_dmaa(s) % s->dma_dac.dmasize; 
1856     		/* the apu only reports the length it has seen, not the
1857     			length of the memory that has been used (the WP
1858     			knows that) */
1859     		if ( ((s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK) == (ESS_FMT_STEREO|ESS_FMT_16BIT))
1860     			hwptr<<=1;
1861     
1862     		diff = (s->dma_dac.dmasize + hwptr - s->dma_dac.hwptr) % s->dma_dac.dmasize;
1863     /*		M_printk("updating dac: hwptr: %d diff: %d\n",hwptr,diff);*/
1864     		s->dma_dac.hwptr = hwptr;
1865     		s->dma_dac.total_bytes += diff;
1866     		if (s->dma_dac.mapped) {
1867     			s->dma_dac.count += diff;
1868     			if (s->dma_dac.count >= (signed)s->dma_dac.fragsize) {
1869     				wake_up(&s->dma_dac.wait);
1870     			}
1871     		} else {
1872     			s->dma_dac.count -= diff;
1873     /*			M_printk("maestro: ess_update_ptr: diff: %d, count: %d\n", diff, s->dma_dac.count); */
1874     			if (s->dma_dac.count <= 0) {
1875     				M_printk("underflow! diff: %d count: %d hw: %d sw: %d\n", diff, s->dma_dac.count, 
1876     					hwptr, s->dma_dac.swptr);
1877     				/* FILL ME 
1878     				wrindir(s, SV_CIENABLE, s->enable); */
1879     				/* XXX how on earth can calling this with the lock held work.. */
1880     				stop_dac(s);
1881     				/* brute force everyone back in sync, sigh */
1882     				s->dma_dac.count = 0; 
1883     				s->dma_dac.swptr = hwptr; 
1884     				s->dma_dac.error++;
1885     			} else if (s->dma_dac.count <= (signed)s->dma_dac.fragsize && !s->dma_dac.endcleared) {
1886     				clear_advance(s);
1887     				s->dma_dac.endcleared = 1;
1888     			}
1889     			if (s->dma_dac.count + (signed)s->dma_dac.fragsize <= (signed)s->dma_dac.dmasize) {
1890     				wake_up(&s->dma_dac.wait);
1891     /*				printk("waking up DAC count: %d sw: %d hw: %d\n",s->dma_dac.count, s->dma_dac.swptr, 
1892     					hwptr);*/
1893     			}
1894     		}
1895     	}
1896     }
1897     
1898     static void 
1899     ess_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1900     {
1901             struct ess_state *s;
1902             struct ess_card *c = (struct ess_card *)dev_id;
1903     	int i;
1904     	u32 event;
1905     
1906     	if ( ! (event = inb(c->iobase+0x1A)) ) return;
1907     
1908     	outw(inw(c->iobase+4)&1, c->iobase+4);
1909     
1910     /*	M_printk("maestro int: %x\n",event);*/
1911     	if(event&(1<<6))
1912     	{
1913     		int x;
1914     		enum {UP_EVT, DOWN_EVT, MUTE_EVT} vol_evt;
1915     		int volume;
1916     
1917     		/* Figure out which volume control button was pushed,
1918     		   based on differences from the default register
1919     		   values. */
1920     		x = inb(c->iobase+0x1c);
1921     		if (x&1) vol_evt = MUTE_EVT;
1922     		else if (((x>>1)&7) > 4) vol_evt = UP_EVT;
1923     		else vol_evt = DOWN_EVT;
1924     
1925     		/* Reset the volume control registers. */
1926     		outb(0x88, c->iobase+0x1c);
1927     		outb(0x88, c->iobase+0x1d);
1928     		outb(0x88, c->iobase+0x1e);
1929     		outb(0x88, c->iobase+0x1f);
1930     
1931     		/* Deal with the button press in a hammer-handed
1932     		   manner by adjusting the master mixer volume. */
1933     		volume = c->mix.mixer_state[0] & 0xff;
1934     		if (vol_evt == UP_EVT) {
1935     			volume += 10;
1936     			if (volume > 100)
1937     				volume = 100;
1938     		}
1939     		else if (vol_evt == DOWN_EVT) {
1940     			volume -= 10;
1941     			if (volume < 0)
1942     				volume = 0;
1943     		} else {
1944     			/* vol_evt == MUTE_EVT */
1945     			if (volume == 0)
1946     				volume = c->dock_mute_vol;
1947     			else {
1948     				c->dock_mute_vol = volume;
1949     				volume = 0;
1950     			}
1951     		}
1952     		set_mixer (c, 0, (volume << 8) | volume);
1953     	}
1954     
1955     	/* Ack all the interrupts. */
1956     	outb(0xFF, c->iobase+0x1A);
1957     		
1958     	/*
1959     	 *	Update the pointers for all APU's we are running.
1960     	 */
1961     	for(i=0;i<NR_DSPS;i++)
1962     	{
1963     		s=&c->channels[i];
1964     		if(s->dev_audio == -1)
1965     			break;
1966     		spin_lock(&s->lock);
1967     		ess_update_ptr(s);
1968     		spin_unlock(&s->lock);
1969     	}
1970     }
1971     
1972     
1973     /* --------------------------------------------------------------------- */
1974     
1975     static const char invalid_magic[] = KERN_CRIT "maestro: invalid magic value in %s\n";
1976     
1977     #define VALIDATE_MAGIC(FOO,MAG)                         \
1978     ({                                                \
1979     	if (!(FOO) || (FOO)->magic != MAG) { \
1980     		printk(invalid_magic,__FUNCTION__);            \
1981     		return -ENXIO;                    \
1982     	}                                         \
1983     })
1984     
1985     #define VALIDATE_STATE(a) VALIDATE_MAGIC(a,ESS_STATE_MAGIC)
1986     #define VALIDATE_CARD(a) VALIDATE_MAGIC(a,ESS_CARD_MAGIC)
1987     
1988     static void set_mixer(struct ess_card *card,unsigned int mixer, unsigned int val ) 
1989     {
1990     	unsigned int left,right;
1991     	/* cleanse input a little */
1992     	right = ((val >> 8)  & 0xff) ;
1993     	left = (val  & 0xff) ;
1994     
1995     	if(right > 100) right = 100;
1996     	if(left > 100) left = 100;
1997     
1998     	card->mix.mixer_state[mixer]=(right << 8) | left;
1999     	card->mix.write_mixer(card,mixer,left,right);
2000     }
2001     
2002     static void
2003     mixer_push_state(struct ess_card *card)
2004     {
2005     	int i;
2006     	for(i = 0 ; i < SOUND_MIXER_NRDEVICES ; i++) {
2007     		if( ! supported_mixer(card,i)) continue;
2008     
2009     		set_mixer(card,i,card->mix.mixer_state[i]);
2010     	}
2011     }
2012     
2013     static int mixer_ioctl(struct ess_card *card, unsigned int cmd, unsigned long arg)
2014     {
2015     	int i, val=0;
2016            unsigned long flags;
2017     
2018     	VALIDATE_CARD(card);
2019             if (cmd == SOUND_MIXER_INFO) {
2020     		mixer_info info;
2021     		strncpy(info.id, card_names[card->card_type], sizeof(info.id));
2022     		strncpy(info.name,card_names[card->card_type],sizeof(info.name));
2023     		info.modify_counter = card->mix.modcnt;
2024     		if (copy_to_user((void *)arg, &info, sizeof(info)))
2025     			return -EFAULT;
2026     		return 0;
2027     	}
2028     	if (cmd == SOUND_OLD_MIXER_INFO) {
2029     		_old_mixer_info info;
2030     		strncpy(info.id, card_names[card->card_type], sizeof(info.id));
2031     		strncpy(info.name,card_names[card->card_type],sizeof(info.name));
2032     		if (copy_to_user((void *)arg, &info, sizeof(info)))
2033     			return -EFAULT;
2034     		return 0;
2035     	}
2036     	if (cmd == OSS_GETVERSION)
2037     		return put_user(SOUND_VERSION, (int *)arg);
2038     
2039     	if (_IOC_TYPE(cmd) != 'M' || _IOC_SIZE(cmd) != sizeof(int))
2040                     return -EINVAL;
2041     
2042             if (_IOC_DIR(cmd) == _IOC_READ) {
2043                     switch (_IOC_NR(cmd)) {
2044                     case SOUND_MIXER_RECSRC: /* give them the current record source */
2045     
2046     			if(!card->mix.recmask_io) {
2047     				val = 0;
2048     			} else {
2049                                    spin_lock_irqsave(&card->lock, flags);
2050     				val = card->mix.recmask_io(card,1,0);
2051                                    spin_unlock_irqrestore(&card->lock, flags);
2052     			}
2053     			break;
2054     			
2055                     case SOUND_MIXER_DEVMASK: /* give them the supported mixers */
2056     			val = card->mix.supported_mixers;
2057     			break;
2058     
2059                     case SOUND_MIXER_RECMASK: /* Arg contains a bit for each supported recording source */
2060     			val = card->mix.record_sources;
2061     			break;
2062     			
2063                     case SOUND_MIXER_STEREODEVS: /* Mixer channels supporting stereo */
2064     			val = card->mix.stereo_mixers;
2065     			break;
2066     			
2067                     case SOUND_MIXER_CAPS:
2068     			val = SOUND_CAP_EXCL_INPUT;
2069     			break;
2070     
2071     		default: /* read a specific mixer */
2072     			i = _IOC_NR(cmd);
2073     
2074     			if ( ! supported_mixer(card,i)) 
2075     				return -EINVAL;
2076     
2077     			/* do we ever want to touch the hardware? */
2078     /*                     spin_lock_irqsave(&card->lock, flags);
2079     			val = card->mix.read_mixer(card,i);
2080                            spin_unlock_irqrestore(&card->lock, flags);*/
2081     
2082     			val = card->mix.mixer_state[i];
2083     /*			M_printk("returned 0x%x for mixer %d\n",val,i);*/
2084     
2085     			break;
2086     		}
2087     		return put_user(val,(int *)arg);
2088     	}
2089     	
2090             if (_IOC_DIR(cmd) != (_IOC_WRITE|_IOC_READ))
2091     		return -EINVAL;
2092     	
2093     	card->mix.modcnt++;
2094     
2095     	if (get_user(val, (int *)arg))
2096     		return -EFAULT;
2097     
2098     	switch (_IOC_NR(cmd)) {
2099     	case SOUND_MIXER_RECSRC: /* Arg contains a bit for each recording source */
2100     
2101     		if (!card->mix.recmask_io) return -EINVAL;
2102     		if(!val) return 0;
2103     		if(! (val &= card->mix.record_sources)) return -EINVAL;
2104     
2105                    spin_lock_irqsave(&card->lock, flags);
2106     		card->mix.recmask_io(card,0,val);
2107                    spin_unlock_irqrestore(&card->lock, flags);
2108     		return 0;
2109     
2110     	default:
2111     		i = _IOC_NR(cmd);
2112     
2113     		if ( ! supported_mixer(card,i)) 
2114     			return -EINVAL;
2115     
2116                    spin_lock_irqsave(&card->lock, flags);
2117     		set_mixer(card,i,val);
2118                    spin_unlock_irqrestore(&card->lock, flags);
2119     
2120     		return 0;
2121     	}
2122     }
2123     
2124     /* --------------------------------------------------------------------- */
2125     static int ess_open_mixdev(struct inode *inode, struct file *file)
2126     {
2127     	int minor = MINOR(inode->i_rdev);
2128     	struct ess_card *card = NULL;
2129     	struct pci_dev *pdev;
2130     	struct pci_driver *drvr;
2131     
2132     	pci_for_each_dev(pdev) {
2133     		drvr = pci_dev_driver (pdev);
2134     		if (drvr == &maestro_pci_driver) {
2135     			card = (struct ess_card*)pci_get_drvdata (pdev);
2136     			if (!card)
2137     				continue;
2138     			if (card->dev_mixer == minor)
2139     				break;
2140     		}
2141     	}
2142     	if (!card)
2143     		return -ENODEV;
2144     	file->private_data = card;
2145     	return 0;
2146     }
2147     
2148     static int ess_release_mixdev(struct inode *inode, struct file *file)
2149     {
2150     	struct ess_card *card = (struct ess_card *)file->private_data;
2151     
2152     	VALIDATE_CARD(card);
2153     	
2154     	return 0;
2155     }
2156     
2157     static int ess_ioctl_mixdev(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2158     {
2159     	struct ess_card *card = (struct ess_card *)file->private_data;
2160     
2161     	VALIDATE_CARD(card);
2162     
2163     	return mixer_ioctl(card, cmd, arg);
2164     }
2165     
2166     static /*const*/ struct file_operations ess_mixer_fops = {
2167     	owner:		THIS_MODULE,
2168     	llseek:         no_llseek,
2169     	ioctl:          ess_ioctl_mixdev,
2170     	open:           ess_open_mixdev,
2171     	release:        ess_release_mixdev,
2172     };
2173     
2174     /* --------------------------------------------------------------------- */
2175     
2176     static int drain_dac(struct ess_state *s, int nonblock)
2177     {
2178     	DECLARE_WAITQUEUE(wait,current);
2179     	unsigned long flags;
2180     	int count;
2181     	signed long tmo;
2182     
2183     	if (s->dma_dac.mapped || !s->dma_dac.ready)
2184     		return 0;
2185     	current->state = TASK_INTERRUPTIBLE;
2186             add_wait_queue(&s->dma_dac.wait, &wait);
2187             for (;;) {
2188     		/* XXX uhm.. questionable locking*/
2189                     spin_lock_irqsave(&s->lock, flags);
2190     		count = s->dma_dac.count;
2191                     spin_unlock_irqrestore(&s->lock, flags);
2192     		if (count <= 0)
2193     			break;
2194     		if (signal_pending(current))
2195                             break;
2196                     if (nonblock) {
2197                             remove_wait_queue(&s->dma_dac.wait, &wait);
2198     			current->state = TASK_RUNNING;
2199                             return -EBUSY;
2200                     }
2201     		tmo = (count * HZ) / s->ratedac;
2202     		tmo >>= sample_shift[(s->fmt >> ESS_DAC_SHIFT) & ESS_FMT_MASK];
2203     		/* XXX this is just broken.  someone is waking us up alot, or schedule_timeout is broken.
2204     			or something.  who cares. - zach */
2205     		if (!schedule_timeout(tmo ? tmo : 1) && tmo)
2206     			M_printk(KERN_DEBUG "maestro: dma timed out?? %ld\n",jiffies);
2207             }
2208             remove_wait_queue(&s->dma_dac.wait, &wait);
2209     	current->state = TASK_RUNNING;
2210             if (signal_pending(current))
2211                     return -ERESTARTSYS;
2212             return 0;
2213     }
2214     
2215     /* --------------------------------------------------------------------- */
2216     /* Zach sez: "god this is gross.." */
2217     static int 
2218     comb_stereo(unsigned char *real_buffer,unsigned char  *tmp_buffer, int offset, 
2219     	int count, int bufsize)
2220     {  
2221     	/* No such thing as stereo recording, so we
2222     	use dual input mixers.  which means we have to 
2223     	combine mono to stereo buffer.  yuck. 
2224     
2225     	but we don't have to be able to work a byte at a time..*/
2226     
2227     	unsigned char *so,*left,*right;
2228     	int i;
2229     
2230     	so = tmp_buffer;
2231     	left = real_buffer + offset;
2232     	right = real_buffer + bufsize/2 + offset;
2233     
2234     /*	M_printk("comb_stereo writing %d to %p from %p and %p, offset: %d size: %d\n",count/2, tmp_buffer,left,right,offset,bufsize);*/
2235     
2236     	for(i=count/4; i ; i--) {
2237     		(*(so+2)) = *(right++);
2238     		(*(so+3)) = *(right++);
2239     		(*so) = *(left++);
2240     		(*(so+1)) = *(left++);
2241     		so+=4;
2242     	}
2243     
2244     	return 0;
2245     }
2246     
2247     /* in this loop, dma_adc.count signifies the amount of data thats waiting
2248     	to be copied to the user's buffer.  it is filled by the interrupt
2249     	handler and drained by this loop. */
2250     static ssize_t 
2251     ess_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
2252     {
2253     	struct ess_state *s = (struct ess_state *)file->private_data;
2254     	ssize_t ret;
2255     	unsigned long flags;
2256     	unsigned swptr;
2257     	int cnt;
2258     	unsigned char *combbuf = NULL;
2259     	
2260     	VALIDATE_STATE(s);
2261     	if (ppos != &file->f_pos)
2262     		return -ESPIPE;
2263     	if (s->dma_adc.mapped)
2264     		return -ENXIO;
2265     	if (!s->dma_adc.ready && (ret = prog_dmabuf(s, 1)))
2266     		return ret;
2267     	if (!access_ok(VERIFY_WRITE, buffer, count))
2268     		return -EFAULT;
2269     	if(!(combbuf = kmalloc(count,GFP_KERNEL)))
2270     		return -ENOMEM;
2271     	ret = 0;
2272     
2273     	calc_bob_rate(s);
2274     
2275     	while (count > 0) {
2276     		spin_lock_irqsave(&s->lock, flags);
2277     		/* remember, all these things are expressed in bytes to be
2278     			sent to the user.. hence the evil / 2 down below */
2279     		swptr = s->dma_adc.swptr;
2280     		cnt = s->dma_adc.dmasize-swptr;
2281     		if (s->dma_adc.count < cnt)
2282     			cnt = s->dma_adc.count;
2283     		spin_unlock_irqrestore(&s->lock, flags);
2284     
2285     		if (cnt > count)
2286     			cnt = count;
2287     
2288     		if ( cnt > 0 ) cnt &= ~3;
2289     
2290     		if (cnt <= 0) {
2291     			start_adc(s);
2292     			if (file->f_flags & O_NONBLOCK) 
2293     			{
2294     				ret = ret ? ret : -EAGAIN;
2295     				goto rec_return_free;
2296     			}
2297     			if (!interruptible_sleep_on_timeout(&s->dma_adc.wait, HZ)) {
2298     				if(! s->card->in_suspend) printk(KERN_DEBUG "maestro: read: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
2299     				       s->dma_adc.dmasize, s->dma_adc.fragsize, s->dma_adc.count, 
2300     				       s->dma_adc.hwptr, s->dma_adc.swptr);
2301     				stop_adc(s);
2302     				spin_lock_irqsave(&s->lock, flags);
2303     				set_dmac(s, virt_to_bus(s->dma_adc.rawbuf), s->dma_adc.numfrag << s->dma_adc.fragshift);
2304     				/* program enhanced mode registers */
2305     				/* FILL ME */
2306     /*				wrindir(s, SV_CIDMACBASECOUNT1, (s->dma_adc.fragsamples-1) >> 8);
2307     				wrindir(s, SV_CIDMACBASECOUNT0, s->dma_adc.fragsamples-1); */
2308     				s->dma_adc.count = s->dma_adc.hwptr = s->dma_adc.swptr = 0;
2309     				spin_unlock_irqrestore(&s->lock, flags);
2310     			}
2311     			if (signal_pending(current)) 
2312     			{
2313     				ret = ret ? ret : -ERESTARTSYS;
2314     				goto rec_return_free;
2315     			}
2316     			continue;
2317     		}
2318     	
2319     		if(s->fmt & (ESS_FMT_STEREO << ESS_ADC_SHIFT)) {
2320     			/* swptr/2 so that we know the real offset in each apu's buffer */
2321     			comb_stereo(s->dma_adc.rawbuf,combbuf,swptr/2,cnt,s->dma_adc.dmasize);
2322     			if (copy_to_user(buffer, combbuf, cnt)) {
2323     				ret = ret ? ret : -EFAULT;
2324     				goto rec_return_free;
2325     			}
2326     		} else  {
2327     			if (copy_to_user(buffer, s->dma_adc.rawbuf + swptr, cnt)) {
2328     				ret = ret ? ret : -EFAULT;
2329     				goto rec_return_free;
2330     			}
2331     		}
2332     
2333     		swptr = (swptr + cnt) % s->dma_adc.dmasize;
2334     		spin_lock_irqsave(&s->lock, flags);
2335     		s->dma_adc.swptr = swptr;
2336     		s->dma_adc.count -= cnt;
2337     		spin_unlock_irqrestore(&s->lock, flags);
2338     		count -= cnt;
2339     		buffer += cnt;
2340     		ret += cnt;
2341     		start_adc(s);
2342     	}
2343     
2344     rec_return_free:
2345     	if(combbuf) kfree(combbuf);
2346     	return ret;
2347     }
2348     
2349     static ssize_t 
2350     ess_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
2351     {
2352     	struct ess_state *s = (struct ess_state *)file->private_data;
2353     	ssize_t ret;
2354     	unsigned long flags;
2355     	unsigned swptr;
2356     	int cnt;
2357     	
2358     	VALIDATE_STATE(s);
2359     	if (ppos != &file->f_pos)
2360     		return -ESPIPE;
2361     	if (s->dma_dac.mapped)
2362     		return -ENXIO;
2363     	if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2364     		return ret;
2365     	if (!access_ok(VERIFY_READ, buffer, count))
2366     		return -EFAULT;
2367     	ret = 0;
2368     
2369     	calc_bob_rate(s);
2370     
2371     	while (count > 0) {
2372     		spin_lock_irqsave(&s->lock, flags);
2373     
2374     		if (s->dma_dac.count < 0) {
2375     			s->dma_dac.count = 0;
2376     			s->dma_dac.swptr = s->dma_dac.hwptr;
2377     		}
2378     		swptr = s->dma_dac.swptr;
2379     
2380     		cnt = s->dma_dac.dmasize-swptr;
2381     
2382     		if (s->dma_dac.count + cnt > s->dma_dac.dmasize)
2383     			cnt = s->dma_dac.dmasize - s->dma_dac.count;
2384     
2385     		spin_unlock_irqrestore(&s->lock, flags);
2386     
2387     		if (cnt > count)
2388     			cnt = count;
2389     
2390     		if (cnt <= 0) {
2391     			start_dac(s);
2392     			if (file->f_flags & O_NONBLOCK) {
2393     				if(!ret) ret = -EAGAIN;
2394     				goto return_free;
2395     			}
2396     			if (!interruptible_sleep_on_timeout(&s->dma_dac.wait, HZ)) {
2397     				if(! s->card->in_suspend) printk(KERN_DEBUG "maestro: write: chip lockup? dmasz %u fragsz %u count %i hwptr %u swptr %u\n",
2398     				       s->dma_dac.dmasize, s->dma_dac.fragsize, s->dma_dac.count, 
2399     				       s->dma_dac.hwptr, s->dma_dac.swptr);
2400     				stop_dac(s);
2401     				spin_lock_irqsave(&s->lock, flags);
2402     				set_dmaa(s, virt_to_bus(s->dma_dac.rawbuf), s->dma_dac.numfrag << s->dma_dac.fragshift);
2403     				/* program enhanced mode registers */
2404     /*				wrindir(s, SV_CIDMAABASECOUNT1, (s->dma_dac.fragsamples-1) >> 8);
2405     				wrindir(s, SV_CIDMAABASECOUNT0, s->dma_dac.fragsamples-1); */
2406     				/* FILL ME */
2407     				s->dma_dac.count = s->dma_dac.hwptr = s->dma_dac.swptr = 0;
2408     				spin_unlock_irqrestore(&s->lock, flags);
2409     			}
2410     			if (signal_pending(current)) {
2411     				if (!ret) ret = -ERESTARTSYS;
2412     				goto return_free;
2413     			}
2414     			continue;
2415     		}
2416     		if (copy_from_user(s->dma_dac.rawbuf + swptr, buffer, cnt)) {
2417     			if (!ret) ret = -EFAULT;
2418     			goto return_free;
2419     		}
2420     /*		printk("wrote %d bytes at sw: %d cnt: %d while hw: %d\n",cnt, swptr, s->dma_dac.count, s->dma_dac.hwptr);*/
2421     
2422     		swptr = (swptr + cnt) % s->dma_dac.dmasize;
2423     
2424     		spin_lock_irqsave(&s->lock, flags);
2425     		s->dma_dac.swptr = swptr;
2426     		s->dma_dac.count += cnt;
2427     		s->dma_dac.endcleared = 0;
2428     		spin_unlock_irqrestore(&s->lock, flags);
2429     		count -= cnt;
2430     		buffer += cnt;
2431     		ret += cnt;
2432     		start_dac(s);
2433     	}
2434     return_free:
2435     	return ret;
2436     }
2437     
2438     /* No kernel lock - we have our own spinlock */
2439     static unsigned int ess_poll(struct file *file, struct poll_table_struct *wait)
2440     {
2441     	struct ess_state *s = (struct ess_state *)file->private_data;
2442     	unsigned long flags;
2443     	unsigned int mask = 0;
2444     
2445     	VALIDATE_STATE(s);
2446     
2447     /* In 0.14 prog_dmabuf always returns success anyway ... */
2448     	if (file->f_mode & FMODE_WRITE) {
2449     		if (!s->dma_dac.ready && prog_dmabuf(s, 0)) 
2450     			return 0;
2451     	}
2452     	if (file->f_mode & FMODE_READ) {
2453     	  	if (!s->dma_adc.ready && prog_dmabuf(s, 1))
2454     			return 0;
2455     	}
2456     
2457     	if (file->f_mode & FMODE_WRITE)
2458     		poll_wait(file, &s->dma_dac.wait, wait);
2459     	if (file->f_mode & FMODE_READ)
2460     		poll_wait(file, &s->dma_adc.wait, wait);
2461     	spin_lock_irqsave(&s->lock, flags);
2462     	ess_update_ptr(s);
2463     	if (file->f_mode & FMODE_READ) {
2464     		if (s->dma_adc.count >= (signed)s->dma_adc.fragsize)
2465     			mask |= POLLIN | POLLRDNORM;
2466     	}
2467     	if (file->f_mode & FMODE_WRITE) {
2468     		if (s->dma_dac.mapped) {
2469     			if (s->dma_dac.count >= (signed)s->dma_dac.fragsize) 
2470     				mask |= POLLOUT | POLLWRNORM;
2471     		} else {
2472     			if ((signed)s->dma_dac.dmasize >= s->dma_dac.count + (signed)s->dma_dac.fragsize)
2473     				mask |= POLLOUT | POLLWRNORM;
2474     		}
2475     	}
2476     	spin_unlock_irqrestore(&s->lock, flags);
2477     	return mask;
2478     }
2479     
2480     static int ess_mmap(struct file *file, struct vm_area_struct *vma)
2481     {
2482     	struct ess_state *s = (struct ess_state *)file->private_data;
2483     	struct dmabuf *db;
2484     	int ret = -EINVAL;
2485     	unsigned long size;
2486     
2487     	VALIDATE_STATE(s);
2488     	lock_kernel();
2489     	if (vma->vm_flags & VM_WRITE) {
2490     		if ((ret = prog_dmabuf(s, 1)) != 0)
2491     			goto out;
2492     		db = &s->dma_dac;
2493     	} else 
2494     #if 0
2495     	/* if we can have the wp/wc do the combining
2496     		we can turn this back on.  */
2497     	      if (vma->vm_flags & VM_READ) {
2498     		if ((ret = prog_dmabuf(s, 0)) != 0)
2499     			goto out;
2500     		db = &s->dma_adc;
2501     	} else  
2502     #endif
2503     		goto out;
2504     	ret = -EINVAL;
2505     	if (vma->vm_pgoff != 0)
2506     		goto out;
2507     	size = vma->vm_end - vma->vm_start;
2508     	if (size > (PAGE_SIZE << db->buforder))
2509     		goto out;
2510     	ret = -EAGAIN;
2511     	if (remap_page_range(vma->vm_start, virt_to_phys(db->rawbuf), size, vma->vm_page_prot))
2512     		goto out;
2513     	db->mapped = 1;
2514     	ret = 0;
2515     out:
2516     	unlock_kernel();
2517     	return ret;
2518     }
2519     
2520     static int ess_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2521     {
2522     	struct ess_state *s = (struct ess_state *)file->private_data;
2523     	unsigned long flags;
2524             audio_buf_info abinfo;
2525             count_info cinfo;
2526     	int val, mapped, ret;
2527     	unsigned char fmtm, fmtd;
2528     
2529     /*	printk("maestro: ess_ioctl: cmd %d\n", cmd);*/
2530     	
2531     	VALIDATE_STATE(s);
2532             mapped = ((file->f_mode & FMODE_WRITE) && s->dma_dac.mapped) ||
2533     		((file->f_mode & FMODE_READ) && s->dma_adc.mapped);
2534     	switch (cmd) {
2535     	case OSS_GETVERSION:
2536     		return put_user(SOUND_VERSION, (int *)arg);
2537     
2538     	case SNDCTL_DSP_SYNC:
2539     		if (file->f_mode & FMODE_WRITE)
2540     			return drain_dac(s, file->f_flags & O_NONBLOCK);
2541     		return 0;
2542     		
2543     	case SNDCTL_DSP_SETDUPLEX:
2544     		/* XXX fix */
2545     		return 0;
2546     
2547     	case SNDCTL_DSP_GETCAPS:
2548     		return put_user(DSP_CAP_DUPLEX | DSP_CAP_REALTIME | DSP_CAP_TRIGGER | DSP_CAP_MMAP, (int *)arg);
2549     		
2550             case SNDCTL_DSP_RESET:
2551     		if (file->f_mode & FMODE_WRITE) {
2552     			stop_dac(s);
2553     			synchronize_irq();
2554     			s->dma_dac.swptr = s->dma_dac.hwptr = s->dma_dac.count = s->dma_dac.total_bytes = 0;
2555     		}
2556     		if (file->f_mode & FMODE_READ) {
2557     			stop_adc(s);
2558     			synchronize_irq();
2559     			s->dma_adc.swptr = s->dma_adc.hwptr = s->dma_adc.count = s->dma_adc.total_bytes = 0;
2560     		}
2561     		return 0;
2562     
2563             case SNDCTL_DSP_SPEED:
2564                     if (get_user(val, (int *)arg))
2565     			return -EFAULT;
2566     		if (val >= 0) {
2567     			if (file->f_mode & FMODE_READ) {
2568     				stop_adc(s);
2569     				s->dma_adc.ready = 0;
2570     				set_adc_rate(s, val);
2571     			}
2572     			if (file->f_mode & FMODE_WRITE) {
2573     				stop_dac(s);
2574     				s->dma_dac.ready = 0;
2575     				set_dac_rate(s, val);
2576     			}
2577     		}
2578     		return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, (int *)arg);
2579     		
2580             case SNDCTL_DSP_STEREO:
2581     		if (get_user(val, (int *)arg))
2582     			return -EFAULT;
2583     		fmtd = 0;
2584     		fmtm = ~0;
2585     		if (file->f_mode & FMODE_READ) {
2586     			stop_adc(s);
2587     			s->dma_adc.ready = 0;
2588     			if (val)
2589     				fmtd |= ESS_FMT_STEREO << ESS_ADC_SHIFT;
2590     			else
2591     				fmtm &= ~(ESS_FMT_STEREO << ESS_ADC_SHIFT);
2592     		}
2593     		if (file->f_mode & FMODE_WRITE) {
2594     			stop_dac(s);
2595     			s->dma_dac.ready = 0;
2596     			if (val)
2597     				fmtd |= ESS_FMT_STEREO << ESS_DAC_SHIFT;
2598     			else
2599     				fmtm &= ~(ESS_FMT_STEREO << ESS_DAC_SHIFT);
2600     		}
2601     		set_fmt(s, fmtm, fmtd);
2602     		return 0;
2603     
2604             case SNDCTL_DSP_CHANNELS:
2605                     if (get_user(val, (int *)arg))
2606     			return -EFAULT;
2607     		if (val != 0) {
2608     			fmtd = 0;
2609     			fmtm = ~0;
2610     			if (file->f_mode & FMODE_READ) {
2611     				stop_adc(s);
2612     				s->dma_adc.ready = 0;
2613     				if (val >= 2)
2614     					fmtd |= ESS_FMT_STEREO << ESS_ADC_SHIFT;
2615     				else
2616     					fmtm &= ~(ESS_FMT_STEREO << ESS_ADC_SHIFT);
2617     			}
2618     			if (file->f_mode & FMODE_WRITE) {
2619     				stop_dac(s);
2620     				s->dma_dac.ready = 0;
2621     				if (val >= 2)
2622     					fmtd |= ESS_FMT_STEREO << ESS_DAC_SHIFT;
2623     				else
2624     					fmtm &= ~(ESS_FMT_STEREO << ESS_DAC_SHIFT);
2625     			}
2626     			set_fmt(s, fmtm, fmtd);
2627     		}
2628     		return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (ESS_FMT_STEREO << ESS_ADC_SHIFT) 
2629     					   : (ESS_FMT_STEREO << ESS_DAC_SHIFT))) ? 2 : 1, (int *)arg);
2630     		
2631     	case SNDCTL_DSP_GETFMTS: /* Returns a mask */
2632                     return put_user(AFMT_U8|AFMT_S16_LE, (int *)arg);
2633     		
2634     	case SNDCTL_DSP_SETFMT: /* Selects ONE fmt*/
2635     		if (get_user(val, (int *)arg))
2636     			return -EFAULT;
2637     		if (val != AFMT_QUERY) {
2638     			fmtd = 0;
2639     			fmtm = ~0;
2640     			if (file->f_mode & FMODE_READ) {
2641     				stop_adc(s);
2642     				s->dma_adc.ready = 0;
2643     	/* fixed at 16bit for now */
2644     				fmtd |= ESS_FMT_16BIT << ESS_ADC_SHIFT;
2645     #if 0
2646     				if (val == AFMT_S16_LE)
2647     					fmtd |= ESS_FMT_16BIT << ESS_ADC_SHIFT;
2648     				else
2649     					fmtm &= ~(ESS_FMT_16BIT << ESS_ADC_SHIFT);
2650     #endif
2651     			}
2652     			if (file->f_mode & FMODE_WRITE) {
2653     				stop_dac(s);
2654     				s->dma_dac.ready = 0;
2655     				if (val == AFMT_S16_LE)
2656     					fmtd |= ESS_FMT_16BIT << ESS_DAC_SHIFT;
2657     				else
2658     					fmtm &= ~(ESS_FMT_16BIT << ESS_DAC_SHIFT);
2659     			}
2660     			set_fmt(s, fmtm, fmtd);
2661     		}
2662      		return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? 
2663     			(ESS_FMT_16BIT << ESS_ADC_SHIFT) 
2664     			: (ESS_FMT_16BIT << ESS_DAC_SHIFT))) ? 
2665     				AFMT_S16_LE : 
2666     				AFMT_U8, 
2667     			(int *)arg);
2668     		
2669     	case SNDCTL_DSP_POST:
2670                     return 0;
2671     
2672             case SNDCTL_DSP_GETTRIGGER:
2673     		val = 0;
2674     		if ((file->f_mode & FMODE_READ) && (s->enable & ADC_RUNNING))
2675     			val |= PCM_ENABLE_INPUT;
2676     		if ((file->f_mode & FMODE_WRITE) && (s->enable & DAC_RUNNING)) 
2677     			val |= PCM_ENABLE_OUTPUT;
2678     		return put_user(val, (int *)arg);
2679     		
2680     	case SNDCTL_DSP_SETTRIGGER:
2681     		if (get_user(val, (int *)arg))
2682     			return -EFAULT;
2683     		if (file->f_mode & FMODE_READ) {
2684     			if (val & PCM_ENABLE_INPUT) {
2685     				if (!s->dma_adc.ready && (ret =  prog_dmabuf(s, 1)))
2686     					return ret;
2687     				start_adc(s);
2688     			} else
2689     				stop_adc(s);
2690     		}
2691     		if (file->f_mode & FMODE_WRITE) {
2692     			if (val & PCM_ENABLE_OUTPUT) {
2693     				if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2694     					return ret;
2695     				start_dac(s);
2696     			} else
2697     				stop_dac(s);
2698     		}
2699     		return 0;
2700     
2701     	case SNDCTL_DSP_GETOSPACE:
2702     		if (!(file->f_mode & FMODE_WRITE))
2703     			return -EINVAL;
2704     		if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2705     			return ret;
2706     		spin_lock_irqsave(&s->lock, flags);
2707     		ess_update_ptr(s);
2708     		abinfo.fragsize = s->dma_dac.fragsize;
2709                     abinfo.bytes = s->dma_dac.dmasize - s->dma_dac.count;
2710                     abinfo.fragstotal = s->dma_dac.numfrag;
2711                     abinfo.fragments = abinfo.bytes >> s->dma_dac.fragshift;      
2712     		spin_unlock_irqrestore(&s->lock, flags);
2713     		return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2714     
2715     	case SNDCTL_DSP_GETISPACE:
2716     		if (!(file->f_mode & FMODE_READ))
2717     			return -EINVAL;
2718     		if (!s->dma_adc.ready && (ret =  prog_dmabuf(s, 1)))
2719     			return ret;
2720     		spin_lock_irqsave(&s->lock, flags);
2721     		ess_update_ptr(s);
2722     		abinfo.fragsize = s->dma_adc.fragsize;
2723                     abinfo.bytes = s->dma_adc.count;
2724                     abinfo.fragstotal = s->dma_adc.numfrag;
2725                     abinfo.fragments = abinfo.bytes >> s->dma_adc.fragshift;      
2726     		spin_unlock_irqrestore(&s->lock, flags);
2727     		return copy_to_user((void *)arg, &abinfo, sizeof(abinfo)) ? -EFAULT : 0;
2728     		
2729             case SNDCTL_DSP_NONBLOCK:
2730                     file->f_flags |= O_NONBLOCK;
2731                     return 0;
2732     
2733             case SNDCTL_DSP_GETODELAY:
2734     		if (!(file->f_mode & FMODE_WRITE))
2735     			return -EINVAL;
2736     		if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2737     			return ret;
2738     		spin_lock_irqsave(&s->lock, flags);
2739     		ess_update_ptr(s);
2740                     val = s->dma_dac.count;
2741     		spin_unlock_irqrestore(&s->lock, flags);
2742     		return put_user(val, (int *)arg);
2743     
2744             case SNDCTL_DSP_GETIPTR:
2745     		if (!(file->f_mode & FMODE_READ))
2746     			return -EINVAL;
2747     		if (!s->dma_adc.ready && (ret =  prog_dmabuf(s, 1)))
2748     			return ret;
2749     		spin_lock_irqsave(&s->lock, flags);
2750     		ess_update_ptr(s);
2751                     cinfo.bytes = s->dma_adc.total_bytes;
2752                     cinfo.blocks = s->dma_adc.count >> s->dma_adc.fragshift;
2753                     cinfo.ptr = s->dma_adc.hwptr;
2754     		if (s->dma_adc.mapped)
2755     			s->dma_adc.count &= s->dma_adc.fragsize-1;
2756     		spin_unlock_irqrestore(&s->lock, flags);
2757                     return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
2758     
2759             case SNDCTL_DSP_GETOPTR:
2760     		if (!(file->f_mode & FMODE_WRITE))
2761     			return -EINVAL;
2762     		if (!s->dma_dac.ready && (ret = prog_dmabuf(s, 0)))
2763     			return ret;
2764     		spin_lock_irqsave(&s->lock, flags);
2765     		ess_update_ptr(s);
2766                     cinfo.bytes = s->dma_dac.total_bytes;
2767                     cinfo.blocks = s->dma_dac.count >> s->dma_dac.fragshift;
2768                     cinfo.ptr = s->dma_dac.hwptr;
2769     		if (s->dma_dac.mapped)
2770     			s->dma_dac.count &= s->dma_dac.fragsize-1;
2771     		spin_unlock_irqrestore(&s->lock, flags);
2772                     return copy_to_user((void *)arg, &cinfo, sizeof(cinfo));
2773     
2774             case SNDCTL_DSP_GETBLKSIZE:
2775     		if (file->f_mode & FMODE_WRITE) {
2776     			if ((val = prog_dmabuf(s, 0)))
2777     				return val;
2778     			return put_user(s->dma_dac.fragsize, (int *)arg);
2779     		}
2780     		if ((val = prog_dmabuf(s, 1)))
2781     			return val;
2782     		return put_user(s->dma_adc.fragsize, (int *)arg);
2783     
2784             case SNDCTL_DSP_SETFRAGMENT:
2785                     if (get_user(val, (int *)arg))
2786     			return -EFAULT;
2787     		M_printk("maestro: SETFRAGMENT: %0x\n",val);
2788     		if (file->f_mode & FMODE_READ) {
2789     			s->dma_adc.ossfragshift = val & 0xffff;
2790     			s->dma_adc.ossmaxfrags = (val >> 16) & 0xffff;
2791     			if (s->dma_adc.ossfragshift < 4)
2792     				s->dma_adc.ossfragshift = 4;
2793     			if (s->dma_adc.ossfragshift > 15)
2794     				s->dma_adc.ossfragshift = 15;
2795     			if (s->dma_adc.ossmaxfrags < 4)
2796     				s->dma_adc.ossmaxfrags = 4;
2797     		}
2798     		if (file->f_mode & FMODE_WRITE) {
2799     			s->dma_dac.ossfragshift = val & 0xffff;
2800     			s->dma_dac.ossmaxfrags = (val >> 16) & 0xffff;
2801     			if (s->dma_dac.ossfragshift < 4)
2802     				s->dma_dac.ossfragshift = 4;
2803     			if (s->dma_dac.ossfragshift > 15)
2804     				s->dma_dac.ossfragshift = 15;
2805     			if (s->dma_dac.ossmaxfrags < 4)
2806     				s->dma_dac.ossmaxfrags = 4;
2807     		}
2808     		return 0;
2809     
2810             case SNDCTL_DSP_SUBDIVIDE:
2811     		if ((file->f_mode & FMODE_READ && s->dma_adc.subdivision) ||
2812     		    (file->f_mode & FMODE_WRITE && s->dma_dac.subdivision))
2813     			return -EINVAL;
2814                     if (get_user(val, (int *)arg))
2815     			return -EFAULT;
2816     		if (val != 1 && val != 2 && val != 4)
2817     			return -EINVAL;
2818     		if (file->f_mode & FMODE_READ)
2819     			s->dma_adc.subdivision = val;
2820     		if (file->f_mode & FMODE_WRITE)
2821     			s->dma_dac.subdivision = val;
2822     		return 0;
2823     
2824             case SOUND_PCM_READ_RATE:
2825     		return put_user((file->f_mode & FMODE_READ) ? s->rateadc : s->ratedac, (int *)arg);
2826     
2827             case SOUND_PCM_READ_CHANNELS:
2828     		return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (ESS_FMT_STEREO << ESS_ADC_SHIFT) 
2829     					   : (ESS_FMT_STEREO << ESS_DAC_SHIFT))) ? 2 : 1, (int *)arg);
2830     
2831             case SOUND_PCM_READ_BITS:
2832     		return put_user((s->fmt & ((file->f_mode & FMODE_READ) ? (ESS_FMT_16BIT << ESS_ADC_SHIFT) 
2833     					   : (ESS_FMT_16BIT << ESS_DAC_SHIFT))) ? 16 : 8, (int *)arg);
2834     
2835             case SOUND_PCM_WRITE_FILTER:
2836             case SNDCTL_DSP_SETSYNCRO:
2837             case SOUND_PCM_READ_FILTER:
2838                     return -EINVAL;
2839     		
2840     	}
2841     	return -EINVAL;
2842     }
2843     
2844     static void
2845     set_base_registers(struct ess_state *s,void *vaddr)
2846     {
2847     	unsigned long packed_phys = virt_to_bus(vaddr)>>12;
2848     	wave_set_register(s, 0x01FC , packed_phys);
2849     	wave_set_register(s, 0x01FD , packed_phys);
2850     	wave_set_register(s, 0x01FE , packed_phys);
2851     	wave_set_register(s, 0x01FF , packed_phys);
2852     }
2853     
2854     /* 
2855      * this guy makes sure we're in the right power
2856      * state for what we want to be doing 
2857      */
2858     static void maestro_power(struct ess_card *card, int tostate)
2859     {
2860     	u16 active_mask = acpi_state_mask[tostate];
2861     	u8 state;
2862     
2863     	if(!use_pm) return;
2864     
2865     	pci_read_config_byte(card->pcidev, card->power_regs+0x4, &state);
2866     	state&=3;
2867     
2868     	/* make sure we're in the right state */
2869     	if(state != tostate) {
2870     		M_printk(KERN_WARNING "maestro: dev %02x:%02x.%x switching from D%d to D%d\n",
2871     			card->pcidev->bus->number, 
2872     			PCI_SLOT(card->pcidev->devfn),
2873     			PCI_FUNC(card->pcidev->devfn),
2874     			state,tostate);
2875     		pci_write_config_byte(card->pcidev, card->power_regs+0x4, tostate);
2876     	}
2877     
2878     	/* and make sure the units we care about are on 
2879     		XXX we might want to do this before state flipping? */
2880     	pci_write_config_word(card->pcidev, 0x54, ~ active_mask);
2881     	pci_write_config_word(card->pcidev, 0x56, ~ active_mask);
2882     }
2883     
2884     /* we allocate a large power of two for all our memory.
2885     	this is cut up into (not to scale :):
2886     	|silly fifo word	| 512byte mixbuf per adc	| dac/adc * channels |
2887     */
2888     static int
2889     allocate_buffers(struct ess_state *s)
2890     {
2891     	void *rawbuf=NULL;
2892     	int order,i;
2893     	struct page *page, *pend;
2894     
2895     	/* alloc as big a chunk as we can */
2896     	for (order = (dsps_order + (16-PAGE_SHIFT) + 1); order >= (dsps_order + 2 + 1); order--)
2897     		if((rawbuf = (void *)__get_free_pages(GFP_KERNEL|GFP_DMA, order)))
2898     			break;
2899     
2900     	if (!rawbuf)
2901     		return 1;
2902     
2903     	M_printk("maestro: allocated %ld (%d) bytes at %p\n",PAGE_SIZE<<order,order, rawbuf);
2904     
2905     	if ((virt_to_bus(rawbuf) + (PAGE_SIZE << order) - 1) & ~((1<<28)-1))  {
2906     		printk(KERN_ERR "maestro: DMA buffer beyond 256MB! busaddr 0x%lx  size %ld\n",
2907     			virt_to_bus(rawbuf), PAGE_SIZE << order);
2908     		kfree(rawbuf);
2909     		return 1;
2910     	}
2911     
2912     	s->card->dmapages = rawbuf;
2913     	s->card->dmaorder = order;
2914     
2915     	for(i=0;i<NR_DSPS;i++) {
2916     		struct ess_state *ess = &s->card->channels[i];
2917     
2918     		if(ess->dev_audio == -1)
2919     			continue;
2920     
2921     		ess->dma_dac.ready = s->dma_dac.mapped = 0;
2922     		ess->dma_adc.ready = s->dma_adc.mapped = 0;
2923     		ess->dma_adc.buforder = ess->dma_dac.buforder = order - 1 - dsps_order - 1;
2924     
2925     		/* offset dac and adc buffers starting half way through and then at each [da][ad]c's
2926     			order's intervals.. */
2927     		ess->dma_dac.rawbuf = rawbuf + (PAGE_SIZE<<(order-1)) + (i * ( PAGE_SIZE << (ess->dma_dac.buforder + 1 )));
2928     		ess->dma_adc.rawbuf = ess->dma_dac.rawbuf + ( PAGE_SIZE << ess->dma_dac.buforder);
2929     		/* offset mixbuf by a mixbuf so that the lame status fifo can
2930     			happily scribble away.. */ 
2931     		ess->mixbuf = rawbuf + (512 * (i+1));
2932     
2933     		M_printk("maestro: setup apu %d: dac: %p adc: %p mix: %p\n",i,ess->dma_dac.rawbuf,
2934     			ess->dma_adc.rawbuf, ess->mixbuf);
2935     
2936     	}
2937     
2938     	/* now mark the pages as reserved; otherwise remap_page_range doesn't do what we want */
2939     	pend = virt_to_page(rawbuf + (PAGE_SIZE << order) - 1);
2940     	for (page = virt_to_page(rawbuf); page <= pend; page++)
2941     		mem_map_reserve(page);
2942     
2943     	return 0;
2944     } 
2945     static void
2946     free_buffers(struct ess_state *s)
2947     {
2948     	struct page *page, *pend;
2949     
2950     	s->dma_dac.rawbuf = s->dma_adc.rawbuf = NULL;
2951     	s->dma_dac.mapped = s->dma_adc.mapped = 0;
2952     	s->dma_dac.ready = s->dma_adc.ready = 0;
2953     
2954     	M_printk("maestro: freeing %p\n",s->card->dmapages);
2955     	/* undo marking the pages as reserved */
2956     
2957     	pend = virt_to_page(s->card->dmapages + (PAGE_SIZE << s->card->dmaorder) - 1);
2958     	for (page = virt_to_page(s->card->dmapages); page <= pend; page++)
2959     		mem_map_unreserve(page);
2960     
2961     	free_pages((unsigned long)s->card->dmapages,s->card->dmaorder);
2962     	s->card->dmapages = NULL;
2963     }
2964     
2965     static int 
2966     ess_open(struct inode *inode, struct file *file)
2967     {
2968     	int minor = MINOR(inode->i_rdev);
2969     	struct ess_state *s = NULL;
2970     	unsigned char fmtm = ~0, fmts = 0;
2971     	struct pci_dev *pdev;
2972     	/*
2973     	 *	Scan the cards and find the channel. We only
2974     	 *	do this at open time so it is ok
2975     	 */
2976     
2977     	pci_for_each_dev(pdev) {
2978     		struct ess_card *c;
2979     		struct pci_driver *drvr;
2980     
2981     		drvr = pci_dev_driver (pdev);
2982     		if (drvr == &maestro_pci_driver) {
2983     			int i;
2984     			struct ess_state *sp;
2985     
2986     			c = (struct ess_card*)pci_get_drvdata (pdev);
2987     			if (!c)
2988     				continue;
2989     			for(i=0;i<NR_DSPS;i++)
2990     			{
2991     				sp=&c->channels[i];
2992     				if(sp->dev_audio < 0)
2993     					continue;
2994     				if((sp->dev_audio ^ minor) & ~0xf)
2995     					continue;
2996     				s=sp;
2997     			}
2998     		}
2999     	}
3000     	if (!s)
3001     		return -ENODEV;
3002     
3003            	VALIDATE_STATE(s);
3004     	file->private_data = s;
3005     	/* wait for device to become free */
3006     	down(&s->open_sem);
3007     	while (s->open_mode & file->f_mode) {
3008     		if (file->f_flags & O_NONBLOCK) {
3009     			up(&s->open_sem);
3010     			return -EWOULDBLOCK;
3011     		}
3012     		up(&s->open_sem);
3013     		interruptible_sleep_on(&s->open_wait);
3014     		if (signal_pending(current))
3015     			return -ERESTARTSYS;
3016     		down(&s->open_sem);
3017     	}
3018     
3019     	/* under semaphore.. */
3020     	if ((s->card->dmapages==NULL) && allocate_buffers(s)) {
3021     		up(&s->open_sem);
3022     		return -ENOMEM;
3023     	}
3024     
3025     	/* we're covered by the open_sem */
3026     	if( ! s->card->dsps_open )  {
3027     		maestro_power(s->card,ACPI_D0);
3028     		start_bob(s);
3029     	}
3030     	s->card->dsps_open++;
3031     	M_printk("maestro: open, %d bobs now\n",s->card->dsps_open);
3032     
3033     	/* ok, lets write WC base regs now that we've 
3034     		powered up the chip */
3035     	M_printk("maestro: writing 0x%lx (bus 0x%lx) to the wp\n",virt_to_bus(s->card->dmapages),
3036     		((virt_to_bus(s->card->dmapages))&0xFFE00000)>>12);
3037     	set_base_registers(s,s->card->dmapages);
3038     
3039     	if (file->f_mode & FMODE_READ) {
3040     /*
3041     		fmtm &= ~((ESS_FMT_STEREO | ESS_FMT_16BIT) << ESS_ADC_SHIFT);
3042     		if ((minor & 0xf) == SND_DEV_DSP16)
3043     			fmts |= ESS_FMT_16BIT << ESS_ADC_SHIFT; */
3044     
3045     		fmtm &= ~((ESS_FMT_STEREO|ESS_FMT_16BIT) << ESS_ADC_SHIFT);
3046     		fmts = (ESS_FMT_STEREO|ESS_FMT_16BIT) << ESS_ADC_SHIFT;
3047     
3048     		s->dma_adc.ossfragshift = s->dma_adc.ossmaxfrags = s->dma_adc.subdivision = 0;
3049     		set_adc_rate(s, 8000);
3050     	}
3051     	if (file->f_mode & FMODE_WRITE) {
3052     		fmtm &= ~((ESS_FMT_STEREO | ESS_FMT_16BIT) << ESS_DAC_SHIFT);
3053     		if ((minor & 0xf) == SND_DEV_DSP16)
3054     			fmts |= ESS_FMT_16BIT << ESS_DAC_SHIFT;
3055     
3056     		s->dma_dac.ossfragshift = s->dma_dac.ossmaxfrags = s->dma_dac.subdivision = 0;
3057     		set_dac_rate(s, 8000);
3058     	}
3059     	set_fmt(s, fmtm, fmts);
3060     	s->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
3061     
3062     	up(&s->open_sem);
3063     	return 0;
3064     }
3065     
3066     static int 
3067     ess_release(struct inode *inode, struct file *file)
3068     {
3069     	struct ess_state *s = (struct ess_state *)file->private_data;
3070     
3071     	VALIDATE_STATE(s);
3072     	lock_kernel();
3073     	if (file->f_mode & FMODE_WRITE)
3074     		drain_dac(s, file->f_flags & O_NONBLOCK);
3075     	down(&s->open_sem);
3076     	if (file->f_mode & FMODE_WRITE) {
3077     		stop_dac(s);
3078     	}
3079     	if (file->f_mode & FMODE_READ) {
3080     		stop_adc(s);
3081     	}
3082     		
3083     	s->open_mode &= (~file->f_mode) & (FMODE_READ|FMODE_WRITE);
3084     	/* we're covered by the open_sem */
3085     	M_printk("maestro: %d dsps now alive\n",s->card->dsps_open-1);
3086     	if( --s->card->dsps_open <= 0) {
3087     		s->card->dsps_open = 0;
3088     		stop_bob(s);
3089     		free_buffers(s);
3090     		maestro_power(s->card,ACPI_D2);
3091     	}
3092     	up(&s->open_sem);
3093     	wake_up(&s->open_wait);
3094     	unlock_kernel();
3095     	return 0;
3096     }
3097     
3098     static struct file_operations ess_audio_fops = {
3099     	owner:		THIS_MODULE,
3100     	llseek:         no_llseek,
3101     	read:           ess_read,
3102     	write:          ess_write,
3103     	poll:           ess_poll,
3104     	ioctl:          ess_ioctl,
3105     	mmap:           ess_mmap,
3106     	open:           ess_open,
3107     	release:        ess_release,
3108     };
3109     
3110     static int
3111     maestro_config(struct ess_card *card) 
3112     {
3113     	struct pci_dev *pcidev = card->pcidev;
3114     	struct ess_state *ess = &card->channels[0];
3115     	int apu,iobase  = card->iobase;
3116     	u16 w;
3117     	u32 n;
3118     
3119     	/* We used to muck around with pci config space that
3120     	 * we had no business messing with.  We don't know enough
3121     	 * about the machine to know which DMA mode is appropriate, 
3122     	 * etc.  We were guessing wrong on some machines and making
3123     	 * them unhappy.  We now trust in the BIOS to do things right,
3124     	 * which almost certainly means a new host of problems will
3125     	 * arise with broken BIOS implementations.  screw 'em. 
3126     	 * We're already intolerant of machines that don't assign
3127     	 * IRQs.
3128     	 */
3129     	
3130     	/* do config work at full power */
3131     	maestro_power(card,ACPI_D0);
3132     	 
3133     	pci_read_config_word(pcidev, 0x50, &w);
3134     
3135     	w&=~(1<<5);			/* Don't swap left/right (undoc)*/
3136     	
3137     	pci_write_config_word(pcidev, 0x50, w);
3138     	
3139     	pci_read_config_word(pcidev, 0x52, &w);
3140     	w&=~(1<<15);		/* Turn off internal clock multiplier */
3141     	/* XXX how do we know which to use? */
3142     	w&=~(1<<14);		/* External clock */
3143     	
3144     	w|= (1<<7);		/* Hardware volume control on */
3145     	w|= (1<<6);		/* Debounce off: easier to push the HWV buttons. */
3146     	w&=~(1<<5);		/* GPIO 4:5 */
3147     	w|= (1<<4);             /* Disconnect from the CHI.  Enabling this made a dell 7500 work. */
3148     	w&=~(1<<2);		/* MIDI fix off (undoc) */
3149     	w&=~(1<<1);		/* reserved, always write 0 */
3150     	pci_write_config_word(pcidev, 0x52, w);
3151     	
3152     	/*
3153     	 *	Legacy mode
3154     	 */
3155     
3156     	pci_read_config_word(pcidev, 0x40, &w);
3157     	w|=(1<<15);	/* legacy decode off */
3158     	w&=~(1<<14);	/* Disable SIRQ */
3159     	w&=~(0x1f);	/* disable mpu irq/io, game port, fm, SB */
3160     	 
3161     	pci_write_config_word(pcidev, 0x40, w);
3162     
3163     	/* Set up 978 docking control chip. */
3164     	pci_read_config_word(pcidev, 0x58, &w);
3165     	w|=1<<2;	/* Enable 978. */
3166     	w|=1<<3;	/* Turn on 978 hardware volume control. */
3167     	w&=~(1<<11);	/* Turn on 978 mixer volume control. */
3168     	pci_write_config_word(pcidev, 0x58, w);
3169     	
3170     	sound_reset(iobase);
3171     
3172     	/*
3173     	 *	Ring Bus Setup
3174     	 */
3175     
3176     	/* setup usual 0x34 stuff.. 0x36 may be chip specific */
3177             outw(0xC090, iobase+0x34); /* direct sound, stereo */
3178             udelay(20);
3179             outw(0x3000, iobase+0x36); /* direct sound, stereo */
3180             udelay(20);
3181     
3182     
3183     	/*
3184     	 *	Reset the CODEC
3185     	 */
3186     	 
3187     	maestro_ac97_reset(iobase,pcidev);
3188     	
3189     	/*
3190     	 *	Ring Bus Setup
3191     	 */
3192     	 	 
3193     	n=inl(iobase+0x34);
3194     	n&=~0xF000;
3195     	n|=12<<12;		/* Direct Sound, Stereo */
3196     	outl(n, iobase+0x34);
3197     
3198     	n=inl(iobase+0x34);
3199     	n&=~0x0F00;		/* Modem off */
3200     	outl(n, iobase+0x34);
3201     
3202     	n=inl(iobase+0x34);
3203     	n&=~0x00F0;
3204     	n|=9<<4;		/* DAC, Stereo */
3205     	outl(n, iobase+0x34);
3206     	
3207     	n=inl(iobase+0x34);
3208     	n&=~0x000F;		/* ASSP off */
3209     	outl(n, iobase+0x34);
3210     	
3211     	n=inl(iobase+0x34);
3212     	n|=(1<<29);		/* Enable ring bus */
3213     	outl(n, iobase+0x34);
3214     	
3215     	n=inl(iobase+0x34);
3216     	n|=(1<<28);		/* Enable serial bus */
3217     	outl(n, iobase+0x34);
3218     	
3219     	n=inl(iobase+0x34);
3220     	n&=~0x00F00000;		/* MIC off */
3221     	outl(n, iobase+0x34);
3222     	
3223     	n=inl(iobase+0x34);
3224     	n&=~0x000F0000;		/* I2S off */
3225     	outl(n, iobase+0x34);
3226     	
3227     
3228     	w=inw(iobase+0x18);
3229     	w&=~(1<<7);		/* ClkRun off */
3230     	outw(w, iobase+0x18);
3231     
3232     	w=inw(iobase+0x18);
3233     	w&=~(1<<6);		/* Hardware volume control interrupt off... for now. */
3234     	outw(w, iobase+0x18);
3235     	
3236     	w=inw(iobase+0x18);
3237     	w&=~(1<<4);		/* ASSP irq off */
3238     	outw(w, iobase+0x18);
3239     	
3240     	w=inw(iobase+0x18);
3241     	w&=~(1<<3);		/* ISDN irq off */
3242     	outw(w, iobase+0x18);
3243     	
3244     	w=inw(iobase+0x18);
3245     	w|=(1<<2);		/* Direct Sound IRQ on */
3246     	outw(w, iobase+0x18);
3247     
3248     	w=inw(iobase+0x18);
3249     	w&=~(1<<1);		/* MPU401 IRQ off */
3250     	outw(w, iobase+0x18);
3251     
3252     	w=inw(iobase+0x18);
3253     	w|=(1<<0);		/* SB IRQ on */
3254     	outw(w, iobase+0x18);
3255     
3256     	/* Set hardware volume control registers to midpoints.
3257     	   We can tell which button was pushed based on how they change. */
3258     	outb(0x88, iobase+0x1c);
3259     	outb(0x88, iobase+0x1d);
3260     	outb(0x88, iobase+0x1e);
3261     	outb(0x88, iobase+0x1f);
3262     
3263     	/* it appears some maestros (dell 7500) only work if these are set,
3264     		regardless of wether we use the assp or not. */
3265     
3266     	outb(0, iobase+0xA4); 
3267     	outb(3, iobase+0xA2); 
3268     	outb(0, iobase+0xA6);
3269     	
3270     	for(apu=0;apu<16;apu++)
3271     	{
3272     		/* Write 0 into the buffer area 0x1E0->1EF */
3273     		outw(0x01E0+apu, 0x10+iobase);
3274     		outw(0x0000, 0x12+iobase);
3275     	
3276     		/*
3277     		 * The 1.10 test program seem to write 0 into the buffer area
3278     		 * 0x1D0-0x1DF too.
3279     		 */
3280     		outw(0x01D0+apu, 0x10+iobase);
3281     		outw(0x0000, 0x12+iobase);
3282     	}
3283     
3284     #if 1
3285     	wave_set_register(ess, IDR7_WAVE_ROMRAM, 
3286     		(wave_get_register(ess, IDR7_WAVE_ROMRAM)&0xFF00));
3287     	wave_set_register(ess, IDR7_WAVE_ROMRAM,
3288     		wave_get_register(ess, IDR7_WAVE_ROMRAM)|0x100);
3289     	wave_set_register(ess, IDR7_WAVE_ROMRAM,
3290     		wave_get_register(ess, IDR7_WAVE_ROMRAM)&~0x200);
3291     	wave_set_register(ess, IDR7_WAVE_ROMRAM,
3292     		wave_get_register(ess, IDR7_WAVE_ROMRAM)|~0x400);
3293     #else		
3294     	maestro_write(ess, IDR7_WAVE_ROMRAM, 
3295     		(maestro_read(ess, IDR7_WAVE_ROMRAM)&0xFF00));
3296     	maestro_write(ess, IDR7_WAVE_ROMRAM,
3297     		maestro_read(ess, IDR7_WAVE_ROMRAM)|0x100);
3298     	maestro_write(ess, IDR7_WAVE_ROMRAM,
3299     		maestro_read(ess, IDR7_WAVE_ROMRAM)&~0x200);
3300     	maestro_write(ess, IDR7_WAVE_ROMRAM,
3301     		maestro_read(ess, IDR7_WAVE_ROMRAM)|0x400);
3302     #endif
3303     	
3304     	maestro_write(ess, IDR2_CRAM_DATA, 0x0000);
3305     	maestro_write(ess, 0x08, 0xB004);
3306     	/* Now back to the DirectSound stuff */
3307     	maestro_write(ess, 0x09, 0x001B);
3308     	maestro_write(ess, 0x0A, 0x8000);
3309     	maestro_write(ess, 0x0B, 0x3F37);
3310     	maestro_write(ess, 0x0C, 0x0098);
3311     	
3312     	/* parallel out ?? */
3313     	maestro_write(ess, 0x0C, 
3314     		(maestro_read(ess, 0x0C)&~0xF000)|0x8000); 
3315     	/* parallel in, has something to do with recording :) */
3316     	maestro_write(ess, 0x0C, 
3317     		(maestro_read(ess, 0x0C)&~0x0F00)|0x0500);
3318     
3319     	maestro_write(ess, 0x0D, 0x7632);
3320     			
3321     	/* Wave cache control on - test off, sg off, 
3322     		enable, enable extra chans 1Mb */
3323     
3324     	outw(inw(0x14+iobase)|(1<<8),0x14+iobase);
3325     	outw(inw(0x14+iobase)&0xFE03,0x14+iobase);
3326     	outw((inw(0x14+iobase)&0xFFFC), 0x14+iobase);
3327     	outw(inw(0x14+iobase)|(1<<7),0x14+iobase);
3328     
3329     	outw(0xA1A0, 0x14+iobase);      /* 0300 ? */
3330     
3331     	/* Now clear the APU control ram */	
3332     	for(apu=0;apu<NR_APUS;apu++)
3333     	{
3334     		for(w=0;w<NR_APU_REGS;w++)
3335     			apu_set_register(ess, apu|ESS_CHAN_HARD, w, 0);
3336     		
3337     	}
3338     
3339     	return 0;
3340     	
3341     }
3342     
3343     /* this guy tries to find the pci power management
3344      * register bank.  this should really be in core
3345      * code somewhere.  1 on success. */
3346     int
3347     parse_power(struct ess_card *card, struct pci_dev *pcidev)
3348     {
3349     	u32 n;
3350     	u16 w;
3351     	u8 next;
3352     	int max = 64;  /* an a 8bit guy pointing to 32bit guys
3353     				can only express so much. */
3354     
3355     	card->power_regs = 0;
3356     
3357     	/* check to see if we have a capabilities list in
3358     		the config register */
3359     	pci_read_config_word(pcidev, PCI_STATUS, &w);
3360     	if(! w & PCI_STATUS_CAP_LIST) return 0;
3361     
3362     	/* walk the list, starting at the head. */
3363     	pci_read_config_byte(pcidev,PCI_CAPABILITY_LIST,&next);
3364     
3365     	while(next && max--) {
3366     		pci_read_config_dword(pcidev, next & ~3, &n);
3367     		if((n & 0xff) == PCI_CAP_ID_PM) {
3368     			card->power_regs = next;
3369     			break;
3370     		}
3371     		next = ((n>>8) & 0xff);
3372     	}
3373     
3374     	return card->power_regs ? 1 : 0;
3375     }
3376     
3377     static int __init
3378     maestro_probe(struct pci_dev *pcidev,const struct pci_device_id *pdid)
3379     {
3380     	int card_type = pdid->driver_data;
3381     	u32 n;
3382     	int iobase;
3383     	int i, ret;
3384     	struct ess_card *card;
3385     	struct ess_state *ess;
3386     	struct pm_dev *pmdev;
3387     	int num = 0;
3388     
3389     /* when built into the kernel, we only print version if device is found */
3390     #ifndef MODULE
3391     	static int printed_version;
3392     	if (!printed_version++)
3393     		printk(version);
3394     #endif
3395     
3396     	/* don't pick up weird modem maestros */
3397     	if(((pcidev->class >> 8) & 0xffff) != PCI_CLASS_MULTIMEDIA_AUDIO)
3398     		return -ENODEV;
3399     
3400     
3401     	if ((ret=pci_enable_device(pcidev)))
3402     		return ret;
3403     			
3404     	iobase = pci_resource_start(pcidev,0);
3405     	if (!iobase || !(pci_resource_flags(pcidev, 0 ) & IORESOURCE_IO))
3406     		return -ENODEV;
3407     
3408     	if(pcidev->irq == 0)
3409     		return -ENODEV;
3410     
3411     	/* stake our claim on the iospace */
3412     	if( request_region(iobase, 256, card_names[card_type]) == NULL )
3413     	{
3414     		printk(KERN_WARNING "maestro: can't allocate 256 bytes I/O at 0x%4.4x\n", iobase);
3415     		return -EBUSY;
3416     	}
3417     
3418     	/* just to be sure */
3419     	pci_set_master(pcidev);
3420     
3421     	card = kmalloc(sizeof(struct ess_card), GFP_KERNEL);
3422     	if(card == NULL)
3423     	{
3424     		printk(KERN_WARNING "maestro: out of memory\n");
3425     		release_region(iobase, 256);
3426     		return -ENOMEM;
3427     	}
3428     	
3429     	memset(card, 0, sizeof(*card));
3430     	card->pcidev = pcidev;
3431     
3432     	pmdev = pm_register(PM_PCI_DEV, PM_PCI_ID(pcidev),
3433     			maestro_pm_callback);
3434     	if (pmdev)
3435     		pmdev->data = card;
3436     
3437     	card->iobase = iobase;
3438     	card->card_type = card_type;
3439     	card->irq = pcidev->irq;
3440     	card->magic = ESS_CARD_MAGIC;
3441     	spin_lock_init(&card->lock);
3442     	init_waitqueue_head(&card->suspend_queue);
3443     
3444     	card->dock_mute_vol = 50;
3445     	
3446     	/* init our groups of 6 apus */
3447     	for(i=0;i<NR_DSPS;i++)
3448     	{
3449     		struct ess_state *s=&card->channels[i];
3450     
3451     		s->index = i;
3452     
3453     		s->card = card;
3454     		init_waitqueue_head(&s->dma_adc.wait);
3455     		init_waitqueue_head(&s->dma_dac.wait);
3456     		init_waitqueue_head(&s->open_wait);
3457     		spin_lock_init(&s->lock);
3458     		init_MUTEX(&s->open_sem);
3459     		s->magic = ESS_STATE_MAGIC;
3460     		
3461     		s->apu[0] = 6*i;
3462     		s->apu[1] = (6*i)+1;
3463     		s->apu[2] = (6*i)+2;
3464     		s->apu[3] = (6*i)+3;
3465     		s->apu[4] = (6*i)+4;
3466     		s->apu[5] = (6*i)+5;
3467     		
3468     		if(s->dma_adc.ready || s->dma_dac.ready || s->dma_adc.rawbuf)
3469     			printk("maestro: BOTCH!\n");
3470     		/* register devices */
3471     		if ((s->dev_audio = register_sound_dsp(&ess_audio_fops, -1)) < 0)
3472     			break;
3473     	}
3474     	
3475     	num = i;
3476     	
3477     	/* clear the rest if we ran out of slots to register */
3478     	for(;i<NR_DSPS;i++)
3479     	{
3480     		struct ess_state *s=&card->channels[i];
3481     		s->dev_audio = -1;
3482     	}
3483     	
3484     	ess = &card->channels[0];
3485     
3486     	/*
3487     	 *	Ok card ready. Begin setup proper
3488     	 */
3489     
3490     	printk(KERN_INFO "maestro: Configuring %s found at IO 0x%04X IRQ %d\n", 
3491     		card_names[card_type],iobase,card->irq);
3492     	pci_read_config_dword(pcidev, PCI_SUBSYSTEM_VENDOR_ID, &n);
3493     	printk(KERN_INFO "maestro:  subvendor id: 0x%08x\n",n); 
3494     
3495     	/* turn off power management unless:
3496     	 *	- the user explicitly asks for it
3497     	 * 		or
3498     	 *		- we're not a 2e, lesser chipps seem to have problems.
3499     	 *		- we're not on our _very_ small whitelist.  some implemenetations
3500     	 *			really dont' like the pm code, others require it.
3501     	 *			feel free to expand this as required.
3502     	 */
3503     #define SUBSYSTEM_VENDOR(x) (x&0xffff)
3504     	if(	(use_pm != 1) && 
3505     		((card_type != TYPE_MAESTRO2E)	|| (SUBSYSTEM_VENDOR(n) != 0x1028)))
3506     			use_pm = 0;
3507     
3508     	if(!use_pm) 
3509     		printk(KERN_INFO "maestro: not attempting power management.\n");
3510     	else {
3511     		if(!parse_power(card,pcidev)) 
3512     			printk(KERN_INFO "maestro: no PCI power management interface found.\n");
3513     		else {
3514     			pci_read_config_dword(pcidev, card->power_regs, &n);
3515     			printk(KERN_INFO "maestro: PCI power management capability: 0x%x\n",n>>16);
3516     		}	
3517     	}
3518     
3519     	maestro_config(card);
3520     
3521     	if(maestro_ac97_get(card, 0x00)==0x0080) {
3522     		printk(KERN_ERR "maestro: my goodness!  you seem to have a pt101 codec, which is quite rare.\n"
3523     				"\tyou should tell someone about this.\n");
3524     	} else {
3525     		maestro_ac97_init(card);
3526     	}
3527     
3528     	if ((card->dev_mixer = register_sound_mixer(&ess_mixer_fops, -1)) < 0) {
3529     		printk("maestro: couldn't register mixer!\n");
3530     	} else {
3531     		memcpy(card->mix.mixer_state,mixer_defaults,sizeof(card->mix.mixer_state));
3532     		mixer_push_state(card);
3533     	}
3534     	
3535     	if((ret=request_irq(card->irq, ess_interrupt, SA_SHIRQ, card_names[card_type], card)))
3536     	{
3537     		printk(KERN_ERR "maestro: unable to allocate irq %d,\n", card->irq);
3538     		unregister_sound_mixer(card->dev_mixer);
3539     		for(i=0;i<NR_DSPS;i++)
3540     		{
3541     			struct ess_state *s = &card->channels[i];
3542     			if(s->dev_audio != -1)
3543     				unregister_sound_dsp(s->dev_audio);
3544     		}
3545     		release_region(card->iobase, 256);		
3546     		unregister_reboot_notifier(&maestro_nb);
3547     		kfree(card);
3548     		return ret;
3549     	}
3550     
3551     	/* Turn on hardware volume control interrupt.
3552     	   This has to come after we grab the IRQ above,
3553     	   or a crash will result on installation if a button has been pressed,
3554     	   because in that case we'll get an immediate interrupt. */
3555     	n = inw(iobase+0x18);
3556     	n|=(1<<6);
3557     	outw(n, iobase+0x18);
3558     
3559     	pci_set_drvdata(pcidev,card);
3560     	/* now go to sleep 'till something interesting happens */
3561     	maestro_power(card,ACPI_D2);
3562     
3563     	printk(KERN_INFO "maestro: %d channels configured.\n", num);
3564     	return 0;
3565     }
3566     
3567     static void maestro_remove(struct pci_dev *pcidev) {
3568     	struct ess_card *card = pci_get_drvdata(pcidev);
3569     	int i;
3570     	
3571     	/* XXX maybe should force stop bob, but should be all 
3572     		stopped by _release by now */
3573     	free_irq(card->irq, card);
3574     	unregister_sound_mixer(card->dev_mixer);
3575     	for(i=0;i<NR_DSPS;i++)
3576     	{
3577     		struct ess_state *ess = &card->channels[i];
3578     		if(ess->dev_audio != -1)
3579     			unregister_sound_dsp(ess->dev_audio);
3580     	}
3581     	/* Goodbye, Mr. Bond. */
3582     	maestro_power(card,ACPI_D3);
3583      	release_region(card->iobase, 256);
3584     	kfree(card);
3585     	pci_set_drvdata(pcidev,NULL);
3586     }
3587     
3588     static struct pci_device_id maestro_pci_tbl[] __devinitdata = {
3589     	{PCI_VENDOR_ESS, PCI_DEVICE_ID_ESS_ESS1968, PCI_ANY_ID, PCI_ANY_ID, 0, 0, TYPE_MAESTRO2},
3590     	{PCI_VENDOR_ESS, PCI_DEVICE_ID_ESS_ESS1978, PCI_ANY_ID, PCI_ANY_ID, 0, 0, TYPE_MAESTRO2E},
3591     	{PCI_VENDOR_ESS_OLD, PCI_DEVICE_ID_ESS_ESS0100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, TYPE_MAESTRO},
3592     	{0,}
3593     };
3594     MODULE_DEVICE_TABLE(pci, maestro_pci_tbl);
3595     
3596     static struct pci_driver maestro_pci_driver = {
3597     	name:"maestro",
3598     	id_table:maestro_pci_tbl,
3599     	probe:maestro_probe,
3600     	remove:maestro_remove,
3601     };
3602     
3603     int __init init_maestro(void)
3604     {
3605     	int rc;
3606     
3607     	rc = pci_module_init(&maestro_pci_driver);
3608     	if (rc < 0)
3609     		return rc;
3610     
3611     	if (register_reboot_notifier(&maestro_nb))
3612     		printk(KERN_WARNING "maestro: reboot notifier registration failed; may not reboot properly.\n");
3613     #ifdef MODULE
3614     	printk(version);
3615     #endif
3616     	if (dsps_order < 0)   {
3617     		dsps_order = 1;
3618     		printk(KERN_WARNING "maestro: clipping dsps_order to %d\n",dsps_order);
3619     	}
3620     	else if (dsps_order > MAX_DSP_ORDER)  {
3621     		dsps_order = MAX_DSP_ORDER;
3622     		printk(KERN_WARNING "maestro: clipping dsps_order to %d\n",dsps_order);
3623     	}
3624     	return 0;
3625     }
3626     
3627     static int maestro_notifier(struct notifier_block *nb, unsigned long event, void *buf)
3628     {
3629     	/* this notifier is called when the kernel is really shut down. */
3630     	M_printk("maestro: shutting down\n");
3631     	/* this will remove all card instances too */
3632     	pci_unregister_driver(&maestro_pci_driver);
3633     	/* XXX dunno about power management */
3634     	return NOTIFY_OK;
3635     }
3636     
3637     /* --------------------------------------------------------------------- */
3638     
3639     
3640     void cleanup_maestro(void) {
3641     	M_printk("maestro: unloading\n");
3642     	pci_unregister_driver(&maestro_pci_driver);
3643     	pm_unregister_all(maestro_pm_callback);
3644     	unregister_reboot_notifier(&maestro_nb);
3645     }
3646     
3647     /* --------------------------------------------------------------------- */
3648     
3649     void
3650     check_suspend(struct ess_card *card)
3651     {
3652     	DECLARE_WAITQUEUE(wait, current);
3653     
3654     	if(!card->in_suspend) return;
3655     
3656     	card->in_suspend++;
3657     	add_wait_queue(&(card->suspend_queue), &wait);
3658     	current->state = TASK_UNINTERRUPTIBLE;
3659     	schedule();
3660     	remove_wait_queue(&(card->suspend_queue), &wait);
3661     	current->state = TASK_RUNNING;
3662     }
3663     
3664     static int 
3665     maestro_suspend(struct ess_card *card)
3666     {
3667     	unsigned long flags;
3668     	int i,j;
3669     
3670     	save_flags(flags); 
3671     	cli(); /* over-kill */
3672     
3673     	M_printk("maestro: apm in dev %p\n",card);
3674     
3675     	/* we have to read from the apu regs, need
3676     		to power it up */
3677     	maestro_power(card,ACPI_D0);
3678     
3679     	for(i=0;i<NR_DSPS;i++) {
3680     		struct ess_state *s = &card->channels[i];
3681     
3682     		if(s->dev_audio == -1)
3683     			continue;
3684     
3685     		M_printk("maestro: stopping apus for device %d\n",i);
3686     		stop_dac(s);
3687     		stop_adc(s);
3688     		for(j=0;j<6;j++) 
3689     			card->apu_map[s->apu[j]][5]=apu_get_register(s,j,5);
3690     
3691     	}
3692     
3693     	/* get rid of interrupts? */
3694     	if( card->dsps_open > 0)
3695     		stop_bob(&card->channels[0]);
3696     
3697     	card->in_suspend++;
3698     
3699     	restore_flags(flags);
3700     
3701     	/* we trust in the bios to power down the chip on suspend.
3702     	 * XXX I'm also not sure that in_suspend will protect
3703     	 * against all reg accesses from here on out. 
3704     	 */
3705     	return 0;
3706     }
3707     static int 
3708     maestro_resume(struct ess_card *card)
3709     {
3710     	unsigned long flags;
3711     	int i;
3712     
3713     	save_flags(flags);
3714     	cli(); /* over-kill */
3715     
3716     	card->in_suspend = 0;
3717     
3718     	M_printk("maestro: resuming card at %p\n",card);
3719     
3720     	/* restore all our config */
3721     	maestro_config(card);
3722     	/* need to restore the base pointers.. */ 
3723     	if(card->dmapages) 
3724     		set_base_registers(&card->channels[0],card->dmapages);
3725     
3726     	mixer_push_state(card);
3727     
3728     	/* set each channels' apu control registers before
3729     	 * restoring audio 
3730     	 */
3731     	for(i=0;i<NR_DSPS;i++) {
3732     		struct ess_state *s = &card->channels[i];
3733     		int chan,reg;
3734     
3735     		if(s->dev_audio == -1)
3736     			continue;
3737     
3738     		for(chan = 0 ; chan < 6 ; chan++) {
3739     			wave_set_register(s,s->apu[chan]<<3,s->apu_base[chan]);
3740     			for(reg = 1 ; reg < NR_APU_REGS ; reg++)  
3741     				apu_set_register(s,chan,reg,s->card->apu_map[s->apu[chan]][reg]);
3742     		}
3743     		for(chan = 0 ; chan < 6 ; chan++)  
3744     			apu_set_register(s,chan,0,s->card->apu_map[s->apu[chan]][0] & 0xFF0F);
3745     	}
3746     
3747     	/* now we flip on the music */
3748     
3749     	if( card->dsps_open <= 0) {
3750     		/* this card's idle */
3751     		maestro_power(card,ACPI_D2);
3752     	} else {
3753     		/* ok, we're actually playing things on
3754     			this card */
3755     		maestro_power(card,ACPI_D0);
3756     		start_bob(&card->channels[0]);
3757     		for(i=0;i<NR_DSPS;i++) {
3758     			struct ess_state *s = &card->channels[i];
3759     
3760     			/* these use the apu_mode, and can handle
3761     				spurious calls */
3762     			start_dac(s);	
3763     			start_adc(s);	
3764     		}
3765     	}
3766     
3767     	restore_flags(flags);
3768     
3769     	/* all right, we think things are ready, 
3770     		wake up people who were using the device
3771     		when we suspended */
3772     	wake_up(&(card->suspend_queue));
3773     
3774     	return 0;
3775     }
3776     
3777     int 
3778     maestro_pm_callback(struct pm_dev *dev, pm_request_t rqst, void *data) 
3779     {
3780     	struct ess_card *card = (struct ess_card*) dev->data;
3781     
3782     	if ( ! card ) goto out;
3783     
3784     	M_printk("maestro: pm event 0x%x received for card %p\n", rqst, card);
3785     	
3786     	switch (rqst) {
3787     		case PM_SUSPEND: 
3788     			maestro_suspend(card);
3789     		break;
3790     		case PM_RESUME: 
3791     			maestro_resume(card);
3792     		break;
3793     		/*
3794     		 * we'd also like to find out about
3795     		 * power level changes because some biosen
3796     		 * do mean things to the maestro when they
3797     		 * change their power state.
3798     		 */
3799             }
3800     out:
3801     	return 0;
3802     }
3803     
3804     module_init(init_maestro);
3805     module_exit(cleanup_maestro);
3806