1/*
2 * Sound driver for Silicon Graphics 320 and 540 Visual Workstations'
3 * onboard audio.  See notes in Documentation/sound/oss/vwsnd .
4 *
5 * Copyright 1999 Silicon Graphics, Inc.  All rights reserved.
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22#undef VWSND_DEBUG			/* define for debugging */
23
24
25/*
26 * Things to test -
27 *
28 *	Will readv/writev work?  Write a test.
29 *
30 *	insmod/rmmod 100 million times.
31 *
32 *	Run I/O until int ptrs wrap around (roughly 6.2 hours @ DAT
33 *	rate).
34 *
35 *	Concurrent threads banging on mixer simultaneously, both UP
36 *	and SMP kernels.  Especially, watch for thread A changing
37 *	OUTSRC while thread B changes gain -- both write to the same
38 *	ad1843 register.
39 *
40 *	What happens if a client opens /dev/audio then forks?
41 *	Do two procs have /dev/audio open?  Test.
42 *
43 *	Pump audio through the CD, MIC and line inputs and verify that
44 *	they mix/mute into the output.
45 *
46 *	Apps:
47 *		amp
48 *		mpg123
49 *		x11amp
50 *		mxv
51 *		kmedia
52 *		esound
53 *		need more input apps
54 *
55 *	Run tests while bombarding with signals.  setitimer(2) will do it...  */
56
57/*
58 * This driver is organized in nine sections.
59 * The nine sections are:
60 *
61 *	debug stuff
62 * 	low level lithium access
63 *	high level lithium access
64 *	AD1843 access
65 *	PCM I/O
66 *	audio driver
67 *	mixer driver
68 *	probe/attach/unload
69 *	initialization and loadable kernel module interface
70 *
71 * That is roughly the order of increasing abstraction, so forward
72 * dependencies are minimal.
73 */
74
75/*
76 * Locking Notes
77 *
78 *	INC_USE_COUNT and DEC_USE_COUNT keep track of the number of
79 *	open descriptors to this driver. They store it in vwsnd_use_count.
80 * 	The global device list, vwsnd_dev_list,	is immutable when the IN_USE
81 *	is true.
82 *
83 *	devc->open_lock is a semaphore that is used to enforce the
84 *	single reader/single writer rule for /dev/audio.  The rule is
85 *	that each device may have at most one reader and one writer.
86 *	Open will block until the previous client has closed the
87 *	device, unless O_NONBLOCK is specified.
88 *
89 *	The semaphore devc->io_mutex serializes PCM I/O syscalls.  This
90 *	is unnecessary in Linux 2.2, because the kernel lock
91 *	serializes read, write, and ioctl globally, but it's there,
92 *	ready for the brave, new post-kernel-lock world.
93 *
94 *	Locking between interrupt and baselevel is handled by the
95 *	"lock" spinlock in vwsnd_port (one lock each for read and
96 *	write).  Each half holds the lock just long enough to see what
97 *	area it owns and update its pointers.  See pcm_output() and
98 *	pcm_input() for most of the gory stuff.
99 *
100 *	devc->mix_mutex serializes all mixer ioctls.  This is also
101 *	redundant because of the kernel lock.
102 *
103 *	The lowest level lock is lith->lithium_lock.  It is a
104 *	spinlock which is held during the two-register tango of
105 *	reading/writing an AD1843 register.  See
106 *	li_{read,write}_ad1843_reg().
107 */
108
109/*
110 * Sample Format Notes
111 *
112 *	Lithium's DMA engine has two formats: 16-bit 2's complement
113 *	and 8-bit unsigned .  16-bit transfers the data unmodified, 2
114 *	bytes per sample.  8-bit unsigned transfers 1 byte per sample
115 *	and XORs each byte with 0x80.  Lithium can input or output
116 *	either mono or stereo in either format.
117 *
118 *	The AD1843 has four formats: 16-bit 2's complement, 8-bit
119 *	unsigned, 8-bit mu-Law and 8-bit A-Law.
120 *
121 *	This driver supports five formats: AFMT_S8, AFMT_U8,
122 *	AFMT_MU_LAW, AFMT_A_LAW, and AFMT_S16_LE.
123 *
124 *	For AFMT_U8 output, we keep the AD1843 in 16-bit mode, and
125 *	rely on Lithium's XOR to translate between U8 and S8.
126 *
127 *	For AFMT_S8, AFMT_MU_LAW and AFMT_A_LAW output, we have to XOR
128 *	the 0x80 bit in software to compensate for Lithium's XOR.
129 *	This happens in pcm_copy_{in,out}().
130 *
131 * Changes:
132 * 11-10-2000	Bartlomiej Zolnierkiewicz <bkz@linux-ide.org>
133 *		Added some __init/__exit
134 */
135
136#include <linux/module.h>
137#include <linux/init.h>
138
139#include <linux/spinlock.h>
140#include <linux/smp_lock.h>
141#include <linux/wait.h>
142#include <linux/interrupt.h>
143#include <linux/mutex.h>
144#include <linux/slab.h>
145
146#include <asm/visws/cobalt.h>
147
148#include "sound_config.h"
149
150/*****************************************************************************/
151/* debug stuff */
152
153#ifdef VWSND_DEBUG
154
155static int shut_up = 1;
156
157/*
158 * dbgassert - called when an assertion fails.
159 */
160
161static void dbgassert(const char *fcn, int line, const char *expr)
162{
163	if (in_interrupt())
164		panic("ASSERTION FAILED IN INTERRUPT, %s:%s:%d %s\n",
165		      __FILE__, fcn, line, expr);
166	else {
167		int x;
168		printk(KERN_ERR "ASSERTION FAILED, %s:%s:%d %s\n",
169		       __FILE__, fcn, line, expr);
170		x = * (volatile int *) 0; /* force proc to exit */
171	}
172}
173
174/*
175 * Bunch of useful debug macros:
176 *
177 *	ASSERT	- print unless e nonzero (panic if in interrupt)
178 *	DBGDO	- include arbitrary code if debugging
179 *	DBGX	- debug print raw (w/o function name)
180 *	DBGP	- debug print w/ function name
181 *	DBGE	- debug print function entry
182 *	DBGC	- debug print function call
183 *	DBGR	- debug print function return
184 *	DBGXV	- debug print raw when verbose
185 *	DBGPV	- debug print when verbose
186 *	DBGEV	- debug print function entry when verbose
187 *	DBGRV	- debug print function return when verbose
188 */
189
190#define ASSERT(e)      ((e) ? (void) 0 : dbgassert(__func__, __LINE__, #e))
191#define DBGDO(x)            x
192#define DBGX(fmt, args...)  (in_interrupt() ? 0 : printk(KERN_ERR fmt, ##args))
193#define DBGP(fmt, args...)  (DBGX("%s: " fmt, __func__ , ##args))
194#define DBGE(fmt, args...)  (DBGX("%s" fmt, __func__ , ##args))
195#define DBGC(rtn)           (DBGP("calling %s\n", rtn))
196#define DBGR()              (DBGP("returning\n"))
197#define DBGXV(fmt, args...) (shut_up ? 0 : DBGX(fmt, ##args))
198#define DBGPV(fmt, args...) (shut_up ? 0 : DBGP(fmt, ##args))
199#define DBGEV(fmt, args...) (shut_up ? 0 : DBGE(fmt, ##args))
200#define DBGCV(rtn)          (shut_up ? 0 : DBGC(rtn))
201#define DBGRV()             (shut_up ? 0 : DBGR())
202
203#else /* !VWSND_DEBUG */
204
205#define ASSERT(e)           ((void) 0)
206#define DBGDO(x)            /* don't */
207#define DBGX(fmt, args...)  ((void) 0)
208#define DBGP(fmt, args...)  ((void) 0)
209#define DBGE(fmt, args...)  ((void) 0)
210#define DBGC(rtn)           ((void) 0)
211#define DBGR()              ((void) 0)
212#define DBGPV(fmt, args...) ((void) 0)
213#define DBGXV(fmt, args...) ((void) 0)
214#define DBGEV(fmt, args...) ((void) 0)
215#define DBGCV(rtn)          ((void) 0)
216#define DBGRV()             ((void) 0)
217
218#endif /* !VWSND_DEBUG */
219
220/*****************************************************************************/
221/* low level lithium access */
222
223/*
224 * We need to talk to Lithium registers on three pages.  Here are
225 * the pages' offsets from the base address (0xFF001000).
226 */
227
228enum {
229	LI_PAGE0_OFFSET = 0x01000 - 0x1000, /* FF001000 */
230	LI_PAGE1_OFFSET = 0x0F000 - 0x1000, /* FF00F000 */
231	LI_PAGE2_OFFSET = 0x10000 - 0x1000, /* FF010000 */
232};
233
234/* low-level lithium data */
235
236typedef struct lithium {
237	void *		page0;		/* virtual addresses */
238	void *		page1;
239	void *		page2;
240	spinlock_t	lock;		/* protects codec and UST/MSC access */
241} lithium_t;
242
243/*
244 * li_destroy destroys the lithium_t structure and vm mappings.
245 */
246
247static void li_destroy(lithium_t *lith)
248{
249	if (lith->page0) {
250		iounmap(lith->page0);
251		lith->page0 = NULL;
252	}
253	if (lith->page1) {
254		iounmap(lith->page1);
255		lith->page1 = NULL;
256	}
257	if (lith->page2) {
258		iounmap(lith->page2);
259		lith->page2 = NULL;
260	}
261}
262
263/*
264 * li_create initializes the lithium_t structure and sets up vm mappings
265 * to access the registers.
266 * Returns 0 on success, -errno on failure.
267 */
268
269static int __init li_create(lithium_t *lith, unsigned long baseaddr)
270{
271	spin_lock_init(&lith->lock);
272	lith->page0 = ioremap_nocache(baseaddr + LI_PAGE0_OFFSET, PAGE_SIZE);
273	lith->page1 = ioremap_nocache(baseaddr + LI_PAGE1_OFFSET, PAGE_SIZE);
274	lith->page2 = ioremap_nocache(baseaddr + LI_PAGE2_OFFSET, PAGE_SIZE);
275	if (!lith->page0 || !lith->page1 || !lith->page2) {
276		li_destroy(lith);
277		return -ENOMEM;
278	}
279	return 0;
280}
281
282/*
283 * basic register accessors - read/write long/byte
284 */
285
286static __inline__ unsigned long li_readl(lithium_t *lith, int off)
287{
288	return * (volatile unsigned long *) (lith->page0 + off);
289}
290
291static __inline__ unsigned char li_readb(lithium_t *lith, int off)
292{
293	return * (volatile unsigned char *) (lith->page0 + off);
294}
295
296static __inline__ void li_writel(lithium_t *lith, int off, unsigned long val)
297{
298	* (volatile unsigned long *) (lith->page0 + off) = val;
299}
300
301static __inline__ void li_writeb(lithium_t *lith, int off, unsigned char val)
302{
303	* (volatile unsigned char *) (lith->page0 + off) = val;
304}
305
306/*****************************************************************************/
307/* High Level Lithium Access */
308
309/*
310 * Lithium DMA Notes
311 *
312 * Lithium has two dedicated DMA channels for audio.  They are known
313 * as comm1 and comm2 (communication areas 1 and 2).  Comm1 is for
314 * input, and comm2 is for output.  Each is controlled by three
315 * registers: BASE (base address), CFG (config) and CCTL
316 * (config/control).
317 *
318 * Each DMA channel points to a physically contiguous ring buffer in
319 * main memory of up to 8 Kbytes.  (This driver always uses 8 Kb.)
320 * There are three pointers into the ring buffer: read, write, and
321 * trigger.  The pointers are 8 bits each.  Each pointer points to
322 * 32-byte "chunks" of data.  The DMA engine moves 32 bytes at a time,
323 * so there is no finer-granularity control.
324 *
325 * In comm1, the hardware updates the write ptr, and software updates
326 * the read ptr.  In comm2, it's the opposite: hardware updates the
327 * read ptr, and software updates the write ptr.  I designate the
328 * hardware-updated ptr as the hwptr, and the software-updated ptr as
329 * the swptr.
330 *
331 * The trigger ptr and trigger mask are used to trigger interrupts.
332 * From the Lithium spec, section 5.6.8, revision of 12/15/1998:
333 *
334 *	Trigger Mask Value
335 *
336 *	A three bit wide field that represents a power of two mask
337 *	that is used whenever the trigger pointer is compared to its
338 *	respective read or write pointer.  A value of zero here
339 *	implies a mask of 0xFF and a value of seven implies a mask
340 *	0x01.  This value can be used to sub-divide the ring buffer
341 *	into pie sections so that interrupts monitor the progress of
342 *	hardware from section to section.
343 *
344 * My interpretation of that is, whenever the hw ptr is updated, it is
345 * compared with the trigger ptr, and the result is masked by the
346 * trigger mask.  (Actually, by the complement of the trigger mask.)
347 * If the result is zero, an interrupt is triggered.  I.e., interrupt
348 * if ((hwptr & ~mask) == (trptr & ~mask)).  The mask is formed from
349 * the trigger register value as mask = (1 << (8 - tmreg)) - 1.
350 *
351 * In yet different words, setting tmreg to 0 causes an interrupt after
352 * every 256 DMA chunks (8192 bytes) or once per traversal of the
353 * ring buffer.  Setting it to 7 caues an interrupt every 2 DMA chunks
354 * (64 bytes) or 128 times per traversal of the ring buffer.
355 */
356
357/* Lithium register offsets and bit definitions */
358
359#define LI_HOST_CONTROLLER	0x000
360# define LI_HC_RESET		 0x00008000
361# define LI_HC_LINK_ENABLE	 0x00004000
362# define LI_HC_LINK_FAILURE	 0x00000004
363# define LI_HC_LINK_CODEC	 0x00000002
364# define LI_HC_LINK_READY	 0x00000001
365
366#define LI_INTR_STATUS		0x010
367#define LI_INTR_MASK		0x014
368# define LI_INTR_LINK_ERR	 0x00008000
369# define LI_INTR_COMM2_TRIG	 0x00000008
370# define LI_INTR_COMM2_UNDERFLOW 0x00000004
371# define LI_INTR_COMM1_TRIG	 0x00000002
372# define LI_INTR_COMM1_OVERFLOW  0x00000001
373
374#define LI_CODEC_COMMAND	0x018
375# define LI_CC_BUSY		 0x00008000
376# define LI_CC_DIR		 0x00000080
377#  define LI_CC_DIR_RD		  LI_CC_DIR
378#  define LI_CC_DIR_WR		(!LI_CC_DIR)
379# define LI_CC_ADDR_MASK	 0x0000007F
380
381#define LI_CODEC_DATA		0x01C
382
383#define LI_COMM1_BASE		0x100
384#define LI_COMM1_CTL		0x104
385# define LI_CCTL_RESET		 0x80000000
386# define LI_CCTL_SIZE		 0x70000000
387# define LI_CCTL_DMA_ENABLE	 0x08000000
388# define LI_CCTL_TMASK		 0x07000000 /* trigger mask */
389# define LI_CCTL_TPTR		 0x00FF0000 /* trigger pointer */
390# define LI_CCTL_RPTR		 0x0000FF00
391# define LI_CCTL_WPTR		 0x000000FF
392#define LI_COMM1_CFG		0x108
393# define LI_CCFG_LOCK		 0x00008000
394# define LI_CCFG_SLOT		 0x00000070
395# define LI_CCFG_DIRECTION	 0x00000008
396#  define LI_CCFG_DIR_IN	(!LI_CCFG_DIRECTION)
397#  define LI_CCFG_DIR_OUT	  LI_CCFG_DIRECTION
398# define LI_CCFG_MODE		 0x00000004
399#  define LI_CCFG_MODE_MONO	(!LI_CCFG_MODE)
400#  define LI_CCFG_MODE_STEREO	  LI_CCFG_MODE
401# define LI_CCFG_FORMAT		 0x00000003
402#  define LI_CCFG_FMT_8BIT	  0x00000000
403#  define LI_CCFG_FMT_16BIT	  0x00000001
404#define LI_COMM2_BASE		0x10C
405#define LI_COMM2_CTL		0x110
406 /* bit definitions are the same as LI_COMM1_CTL */
407#define LI_COMM2_CFG		0x114
408 /* bit definitions are the same as LI_COMM1_CFG */
409
410#define LI_UST_LOW		0x200	/* 64-bit Unadjusted System Time is */
411#define LI_UST_HIGH		0x204	/* microseconds since boot */
412
413#define LI_AUDIO1_UST		0x300	/* UST-MSC pairs */
414#define LI_AUDIO1_MSC		0x304	/* MSC (Media Stream Counter) */
415#define LI_AUDIO2_UST		0x308	/* counts samples actually */
416#define LI_AUDIO2_MSC		0x30C	/* processed as of time UST */
417
418/*
419 * Lithium's DMA engine operates on chunks of 32 bytes.  We call that
420 * a DMACHUNK.
421 */
422
423#define DMACHUNK_SHIFT 5
424#define DMACHUNK_SIZE (1 << DMACHUNK_SHIFT)
425#define BYTES_TO_CHUNKS(bytes) ((bytes) >> DMACHUNK_SHIFT)
426#define CHUNKS_TO_BYTES(chunks) ((chunks) << DMACHUNK_SHIFT)
427
428/*
429 * Two convenient macros to shift bitfields into/out of position.
430 *
431 * Observe that (mask & -mask) is (1 << low_set_bit_of(mask)).
432 * As long as mask is constant, we trust the compiler will change the
433 * multipy and divide into shifts.
434 */
435
436#define SHIFT_FIELD(val, mask) (((val) * ((mask) & -(mask))) & (mask))
437#define UNSHIFT_FIELD(val, mask) (((val) & (mask)) / ((mask) & -(mask)))
438
439/*
440 * dma_chan_desc is invariant information about a Lithium
441 * DMA channel.  There are two instances, li_comm1 and li_comm2.
442 *
443 * Note that the CCTL register fields are write ptr and read ptr, but what
444 * we care about are which pointer is updated by software and which by
445 * hardware.
446 */
447
448typedef struct dma_chan_desc {
449	int basereg;
450	int cfgreg;
451	int ctlreg;
452	int hwptrreg;
453	int swptrreg;
454	int ustreg;
455	int mscreg;
456	unsigned long swptrmask;
457	int ad1843_slot;
458	int direction;			/* LI_CCTL_DIR_IN/OUT */
459} dma_chan_desc_t;
460
461static const dma_chan_desc_t li_comm1 = {
462	LI_COMM1_BASE,			/* base register offset */
463	LI_COMM1_CFG,			/* config register offset */
464	LI_COMM1_CTL,			/* control register offset */
465	LI_COMM1_CTL + 0,		/* hw ptr reg offset (write ptr) */
466	LI_COMM1_CTL + 1,		/* sw ptr reg offset (read ptr) */
467	LI_AUDIO1_UST,			/* ust reg offset */
468	LI_AUDIO1_MSC,			/* msc reg offset */
469	LI_CCTL_RPTR,			/* sw ptr bitmask in ctlval */
470	2,				/* ad1843 serial slot */
471	LI_CCFG_DIR_IN			/* direction */
472};
473
474static const dma_chan_desc_t li_comm2 = {
475	LI_COMM2_BASE,			/* base register offset */
476	LI_COMM2_CFG,			/* config register offset */
477	LI_COMM2_CTL,			/* control register offset */
478	LI_COMM2_CTL + 1,		/* hw ptr reg offset (read ptr) */
479	LI_COMM2_CTL + 0,		/* sw ptr reg offset (writr ptr) */
480	LI_AUDIO2_UST,			/* ust reg offset */
481	LI_AUDIO2_MSC,			/* msc reg offset */
482	LI_CCTL_WPTR,			/* sw ptr bitmask in ctlval */
483	2,				/* ad1843 serial slot */
484	LI_CCFG_DIR_OUT			/* direction */
485};
486
487/*
488 * dma_chan is variable information about a Lithium DMA channel.
489 *
490 * The desc field points to invariant information.
491 * The lith field points to a lithium_t which is passed
492 * to li_read* and li_write* to access the registers.
493 * The *val fields shadow the lithium registers' contents.
494 */
495
496typedef struct dma_chan {
497	const dma_chan_desc_t *desc;
498	lithium_t      *lith;
499	unsigned long   baseval;
500	unsigned long	cfgval;
501	unsigned long	ctlval;
502} dma_chan_t;
503
504/*
505 * ustmsc is a UST/MSC pair (Unadjusted System Time/Media Stream Counter).
506 * UST is time in microseconds since the system booted, and MSC is a
507 * counter that increments with every audio sample.
508 */
509
510typedef struct ustmsc {
511	unsigned long long ust;
512	unsigned long msc;
513} ustmsc_t;
514
515/*
516 * li_ad1843_wait waits until lithium says the AD1843 register
517 * exchange is not busy.  Returns 0 on success, -EBUSY on timeout.
518 *
519 * Locking: must be called with lithium_lock held.
520 */
521
522static int li_ad1843_wait(lithium_t *lith)
523{
524	unsigned long later = jiffies + 2;
525	while (li_readl(lith, LI_CODEC_COMMAND) & LI_CC_BUSY)
526		if (time_after_eq(jiffies, later))
527			return -EBUSY;
528	return 0;
529}
530
531/*
532 * li_read_ad1843_reg returns the current contents of a 16 bit AD1843 register.
533 *
534 * Returns unsigned register value on success, -errno on failure.
535 */
536
537static int li_read_ad1843_reg(lithium_t *lith, int reg)
538{
539	int val;
540
541	ASSERT(!in_interrupt());
542	spin_lock(&lith->lock);
543	{
544		val = li_ad1843_wait(lith);
545		if (val == 0) {
546			li_writel(lith, LI_CODEC_COMMAND, LI_CC_DIR_RD | reg);
547			val = li_ad1843_wait(lith);
548		}
549		if (val == 0)
550			val = li_readl(lith, LI_CODEC_DATA);
551	}
552	spin_unlock(&lith->lock);
553
554	DBGXV("li_read_ad1843_reg(lith=0x%p, reg=%d) returns 0x%04x\n",
555	      lith, reg, val);
556
557	return val;
558}
559
560/*
561 * li_write_ad1843_reg writes the specified value to a 16 bit AD1843 register.
562 */
563
564static void li_write_ad1843_reg(lithium_t *lith, int reg, int newval)
565{
566	spin_lock(&lith->lock);
567	{
568		if (li_ad1843_wait(lith) == 0) {
569			li_writel(lith, LI_CODEC_DATA, newval);
570			li_writel(lith, LI_CODEC_COMMAND, LI_CC_DIR_WR | reg);
571		}
572	}
573	spin_unlock(&lith->lock);
574}
575
576/*
577 * li_setup_dma calculates all the register settings for DMA in a particular
578 * mode.  It takes too many arguments.
579 */
580
581static void li_setup_dma(dma_chan_t *chan,
582			 const dma_chan_desc_t *desc,
583			 lithium_t *lith,
584			 unsigned long buffer_paddr,
585			 int bufshift,
586			 int fragshift,
587			 int channels,
588			 int sampsize)
589{
590	unsigned long mode, format;
591	unsigned long size, tmask;
592
593	DBGEV("(chan=0x%p, desc=0x%p, lith=0x%p, buffer_paddr=0x%lx, "
594	     "bufshift=%d, fragshift=%d, channels=%d, sampsize=%d)\n",
595	     chan, desc, lith, buffer_paddr,
596	     bufshift, fragshift, channels, sampsize);
597
598	/* Reset the channel first. */
599
600	li_writel(lith, desc->ctlreg, LI_CCTL_RESET);
601
602	ASSERT(channels == 1 || channels == 2);
603	if (channels == 2)
604		mode = LI_CCFG_MODE_STEREO;
605	else
606		mode = LI_CCFG_MODE_MONO;
607	ASSERT(sampsize == 1 || sampsize == 2);
608	if (sampsize == 2)
609		format = LI_CCFG_FMT_16BIT;
610	else
611		format = LI_CCFG_FMT_8BIT;
612	chan->desc = desc;
613	chan->lith = lith;
614
615	/*
616	 * Lithium DMA address register takes a 40-bit physical
617	 * address, right-shifted by 8 so it fits in 32 bits.  Bit 37
618	 * must be set -- it enables cache coherence.
619	 */
620
621	ASSERT(!(buffer_paddr & 0xFF));
622	chan->baseval = (buffer_paddr >> 8) | 1 << (37 - 8);
623
624	chan->cfgval = ((chan->cfgval & ~LI_CCFG_LOCK) |
625			SHIFT_FIELD(desc->ad1843_slot, LI_CCFG_SLOT) |
626			desc->direction |
627			mode |
628			format);
629
630	size = bufshift - 6;
631	tmask = 13 - fragshift;		/* See Lithium DMA Notes above. */
632	ASSERT(size >= 2 && size <= 7);
633	ASSERT(tmask >= 1 && tmask <= 7);
634	chan->ctlval = ((chan->ctlval & ~LI_CCTL_RESET) |
635			SHIFT_FIELD(size, LI_CCTL_SIZE) |
636			(chan->ctlval & ~LI_CCTL_DMA_ENABLE) |
637			SHIFT_FIELD(tmask, LI_CCTL_TMASK) |
638			SHIFT_FIELD(0, LI_CCTL_TPTR));
639
640	DBGPV("basereg 0x%x = 0x%lx\n", desc->basereg, chan->baseval);
641	DBGPV("cfgreg 0x%x = 0x%lx\n", desc->cfgreg, chan->cfgval);
642	DBGPV("ctlreg 0x%x = 0x%lx\n", desc->ctlreg, chan->ctlval);
643
644	li_writel(lith, desc->basereg, chan->baseval);
645	li_writel(lith, desc->cfgreg, chan->cfgval);
646	li_writel(lith, desc->ctlreg, chan->ctlval);
647
648	DBGRV();
649}
650
651static void li_shutdown_dma(dma_chan_t *chan)
652{
653	lithium_t *lith = chan->lith;
654	void * lith1 = lith->page1;
655
656	DBGEV("(chan=0x%p)\n", chan);
657
658	chan->ctlval &= ~LI_CCTL_DMA_ENABLE;
659	DBGPV("ctlreg 0x%x = 0x%lx\n", chan->desc->ctlreg, chan->ctlval);
660	li_writel(lith, chan->desc->ctlreg, chan->ctlval);
661
662	/*
663	 * Offset 0x500 on Lithium page 1 is an undocumented,
664	 * unsupported register that holds the zero sample value.
665	 * Lithium is supposed to output zero samples when DMA is
666	 * inactive, and repeat the last sample when DMA underflows.
667	 * But it has a bug, where, after underflow occurs, the zero
668	 * sample is not reset.
669	 *
670	 * I expect this to break in a future rev of Lithium.
671	 */
672
673	if (lith1 && chan->desc->direction == LI_CCFG_DIR_OUT)
674		* (volatile unsigned long *) (lith1 + 0x500) = 0;
675}
676
677/*
678 * li_activate_dma always starts dma at the beginning of the buffer.
679 *
680 * N.B., these may be called from interrupt.
681 */
682
683static __inline__ void li_activate_dma(dma_chan_t *chan)
684{
685	chan->ctlval |= LI_CCTL_DMA_ENABLE;
686	DBGPV("ctlval = 0x%lx\n", chan->ctlval);
687	li_writel(chan->lith, chan->desc->ctlreg, chan->ctlval);
688}
689
690static void li_deactivate_dma(dma_chan_t *chan)
691{
692	lithium_t *lith = chan->lith;
693	void * lith2 = lith->page2;
694
695	chan->ctlval &= ~(LI_CCTL_DMA_ENABLE | LI_CCTL_RPTR | LI_CCTL_WPTR);
696	DBGPV("ctlval = 0x%lx\n", chan->ctlval);
697	DBGPV("ctlreg 0x%x = 0x%lx\n", chan->desc->ctlreg, chan->ctlval);
698	li_writel(lith, chan->desc->ctlreg, chan->ctlval);
699
700	/*
701	 * Offsets 0x98 and 0x9C on Lithium page 2 are undocumented,
702	 * unsupported registers that are internal copies of the DMA
703	 * read and write pointers.  Because of a Lithium bug, these
704	 * registers aren't zeroed correctly when DMA is shut off.  So
705	 * we whack them directly.
706	 *
707	 * I expect this to break in a future rev of Lithium.
708	 */
709
710	if (lith2 && chan->desc->direction == LI_CCFG_DIR_OUT) {
711		* (volatile unsigned long *) (lith2 + 0x98) = 0;
712		* (volatile unsigned long *) (lith2 + 0x9C) = 0;
713	}
714}
715
716/*
717 * read/write the ring buffer pointers.  These routines' arguments and results
718 * are byte offsets from the beginning of the ring buffer.
719 */
720
721static __inline__ int li_read_swptr(dma_chan_t *chan)
722{
723	const unsigned long mask = chan->desc->swptrmask;
724
725	return CHUNKS_TO_BYTES(UNSHIFT_FIELD(chan->ctlval, mask));
726}
727
728static __inline__ int li_read_hwptr(dma_chan_t *chan)
729{
730	return CHUNKS_TO_BYTES(li_readb(chan->lith, chan->desc->hwptrreg));
731}
732
733static __inline__ void li_write_swptr(dma_chan_t *chan, int val)
734{
735	const unsigned long mask = chan->desc->swptrmask;
736
737	ASSERT(!(val & ~CHUNKS_TO_BYTES(0xFF)));
738	val = BYTES_TO_CHUNKS(val);
739	chan->ctlval = (chan->ctlval & ~mask) | SHIFT_FIELD(val, mask);
740	li_writeb(chan->lith, chan->desc->swptrreg, val);
741}
742
743/* li_read_USTMSC() returns a UST/MSC pair for the given channel. */
744
745static void li_read_USTMSC(dma_chan_t *chan, ustmsc_t *ustmsc)
746{
747	lithium_t *lith = chan->lith;
748	const dma_chan_desc_t *desc = chan->desc;
749	unsigned long now_low, now_high0, now_high1, chan_ust;
750
751	spin_lock(&lith->lock);
752	{
753		/*
754		 * retry until we do all five reads without the
755		 * high word changing.  (High word increments
756		 * every 2^32 microseconds, i.e., not often)
757		 */
758		do {
759			now_high0 = li_readl(lith, LI_UST_HIGH);
760			now_low = li_readl(lith, LI_UST_LOW);
761
762			/*
763			 * Lithium guarantees these two reads will be
764			 * atomic -- ust will not increment after msc
765			 * is read.
766			 */
767
768			ustmsc->msc = li_readl(lith, desc->mscreg);
769			chan_ust = li_readl(lith, desc->ustreg);
770
771			now_high1 = li_readl(lith, LI_UST_HIGH);
772		} while (now_high0 != now_high1);
773	}
774	spin_unlock(&lith->lock);
775	ustmsc->ust = ((unsigned long long) now_high0 << 32 | chan_ust);
776}
777
778static void li_enable_interrupts(lithium_t *lith, unsigned int mask)
779{
780	DBGEV("(lith=0x%p, mask=0x%x)\n", lith, mask);
781
782	/* clear any already-pending interrupts. */
783
784	li_writel(lith, LI_INTR_STATUS, mask);
785
786	/* enable the interrupts. */
787
788	mask |= li_readl(lith, LI_INTR_MASK);
789	li_writel(lith, LI_INTR_MASK, mask);
790}
791
792static void li_disable_interrupts(lithium_t *lith, unsigned int mask)
793{
794	unsigned int keepmask;
795
796	DBGEV("(lith=0x%p, mask=0x%x)\n", lith, mask);
797
798	/* disable the interrupts */
799
800	keepmask = li_readl(lith, LI_INTR_MASK) & ~mask;
801	li_writel(lith, LI_INTR_MASK, keepmask);
802
803	/* clear any pending interrupts. */
804
805	li_writel(lith, LI_INTR_STATUS, mask);
806}
807
808/* Get the interrupt status and clear all pending interrupts. */
809
810static unsigned int li_get_clear_intr_status(lithium_t *lith)
811{
812	unsigned int status;
813
814	status = li_readl(lith, LI_INTR_STATUS);
815	li_writel(lith, LI_INTR_STATUS, ~0);
816	return status & li_readl(lith, LI_INTR_MASK);
817}
818
819static int li_init(lithium_t *lith)
820{
821	/* 1. System power supplies stabilize. */
822
823	/* 2. Assert the ~RESET signal. */
824
825	li_writel(lith, LI_HOST_CONTROLLER, LI_HC_RESET);
826	udelay(1);
827
828	/* 3. Deassert the ~RESET signal and enter a wait period to allow
829	   the AD1843 internal clocks and the external crystal oscillator
830	   to stabilize. */
831
832	li_writel(lith, LI_HOST_CONTROLLER, LI_HC_LINK_ENABLE);
833	udelay(1);
834
835	return 0;
836}
837
838/*****************************************************************************/
839/* AD1843 access */
840
841/*
842 * AD1843 bitfield definitions.  All are named as in the AD1843 data
843 * sheet, with ad1843_ prepended and individual bit numbers removed.
844 *
845 * E.g., bits LSS0 through LSS2 become ad1843_LSS.
846 *
847 * Only the bitfields we need are defined.
848 */
849
850typedef struct ad1843_bitfield {
851	char reg;
852	char lo_bit;
853	char nbits;
854} ad1843_bitfield_t;
855
856static const ad1843_bitfield_t
857	ad1843_PDNO   = {  0, 14,  1 },	/* Converter Power-Down Flag */
858	ad1843_INIT   = {  0, 15,  1 },	/* Clock Initialization Flag */
859	ad1843_RIG    = {  2,  0,  4 },	/* Right ADC Input Gain */
860	ad1843_RMGE   = {  2,  4,  1 },	/* Right ADC Mic Gain Enable */
861	ad1843_RSS    = {  2,  5,  3 },	/* Right ADC Source Select */
862	ad1843_LIG    = {  2,  8,  4 },	/* Left ADC Input Gain */
863	ad1843_LMGE   = {  2, 12,  1 },	/* Left ADC Mic Gain Enable */
864	ad1843_LSS    = {  2, 13,  3 },	/* Left ADC Source Select */
865	ad1843_RX1M   = {  4,  0,  5 },	/* Right Aux 1 Mix Gain/Atten */
866	ad1843_RX1MM  = {  4,  7,  1 },	/* Right Aux 1 Mix Mute */
867	ad1843_LX1M   = {  4,  8,  5 },	/* Left Aux 1 Mix Gain/Atten */
868	ad1843_LX1MM  = {  4, 15,  1 },	/* Left Aux 1 Mix Mute */
869	ad1843_RX2M   = {  5,  0,  5 },	/* Right Aux 2 Mix Gain/Atten */
870	ad1843_RX2MM  = {  5,  7,  1 },	/* Right Aux 2 Mix Mute */
871	ad1843_LX2M   = {  5,  8,  5 },	/* Left Aux 2 Mix Gain/Atten */
872	ad1843_LX2MM  = {  5, 15,  1 },	/* Left Aux 2 Mix Mute */
873	ad1843_RMCM   = {  7,  0,  5 },	/* Right Mic Mix Gain/Atten */
874	ad1843_RMCMM  = {  7,  7,  1 },	/* Right Mic Mix Mute */
875	ad1843_LMCM   = {  7,  8,  5 },	/* Left Mic Mix Gain/Atten */
876	ad1843_LMCMM  = {  7, 15,  1 },	/* Left Mic Mix Mute */
877	ad1843_HPOS   = {  8,  4,  1 },	/* Headphone Output Voltage Swing */
878	ad1843_HPOM   = {  8,  5,  1 },	/* Headphone Output Mute */
879	ad1843_RDA1G  = {  9,  0,  6 },	/* Right DAC1 Analog/Digital Gain */
880	ad1843_RDA1GM = {  9,  7,  1 },	/* Right DAC1 Analog Mute */
881	ad1843_LDA1G  = {  9,  8,  6 },	/* Left DAC1 Analog/Digital Gain */
882	ad1843_LDA1GM = {  9, 15,  1 },	/* Left DAC1 Analog Mute */
883	ad1843_RDA1AM = { 11,  7,  1 },	/* Right DAC1 Digital Mute */
884	ad1843_LDA1AM = { 11, 15,  1 },	/* Left DAC1 Digital Mute */
885	ad1843_ADLC   = { 15,  0,  2 },	/* ADC Left Sample Rate Source */
886	ad1843_ADRC   = { 15,  2,  2 },	/* ADC Right Sample Rate Source */
887	ad1843_DA1C   = { 15,  8,  2 },	/* DAC1 Sample Rate Source */
888	ad1843_C1C    = { 17,  0, 16 },	/* Clock 1 Sample Rate Select */
889	ad1843_C2C    = { 20,  0, 16 },	/* Clock 1 Sample Rate Select */
890	ad1843_DAADL  = { 25,  4,  2 },	/* Digital ADC Left Source Select */
891	ad1843_DAADR  = { 25,  6,  2 },	/* Digital ADC Right Source Select */
892	ad1843_DRSFLT = { 25, 15,  1 },	/* Digital Reampler Filter Mode */
893	ad1843_ADLF   = { 26,  0,  2 }, /* ADC Left Channel Data Format */
894	ad1843_ADRF   = { 26,  2,  2 }, /* ADC Right Channel Data Format */
895	ad1843_ADTLK  = { 26,  4,  1 },	/* ADC Transmit Lock Mode Select */
896	ad1843_SCF    = { 26,  7,  1 },	/* SCLK Frequency Select */
897	ad1843_DA1F   = { 26,  8,  2 },	/* DAC1 Data Format Select */
898	ad1843_DA1SM  = { 26, 14,  1 },	/* DAC1 Stereo/Mono Mode Select */
899	ad1843_ADLEN  = { 27,  0,  1 },	/* ADC Left Channel Enable */
900	ad1843_ADREN  = { 27,  1,  1 },	/* ADC Right Channel Enable */
901	ad1843_AAMEN  = { 27,  4,  1 },	/* Analog to Analog Mix Enable */
902	ad1843_ANAEN  = { 27,  7,  1 },	/* Analog Channel Enable */
903	ad1843_DA1EN  = { 27,  8,  1 },	/* DAC1 Enable */
904	ad1843_DA2EN  = { 27,  9,  1 },	/* DAC2 Enable */
905	ad1843_C1EN   = { 28, 11,  1 },	/* Clock Generator 1 Enable */
906	ad1843_C2EN   = { 28, 12,  1 },	/* Clock Generator 2 Enable */
907	ad1843_PDNI   = { 28, 15,  1 };	/* Converter Power Down */
908
909/*
910 * The various registers of the AD1843 use three different formats for
911 * specifying gain.  The ad1843_gain structure parameterizes the
912 * formats.
913 */
914
915typedef struct ad1843_gain {
916
917	int	negative;		/* nonzero if gain is negative. */
918	const ad1843_bitfield_t *lfield;
919	const ad1843_bitfield_t *rfield;
920
921} ad1843_gain_t;
922
923static const ad1843_gain_t ad1843_gain_RECLEV
924				= { 0, &ad1843_LIG,   &ad1843_RIG };
925static const ad1843_gain_t ad1843_gain_LINE
926				= { 1, &ad1843_LX1M,  &ad1843_RX1M };
927static const ad1843_gain_t ad1843_gain_CD
928				= { 1, &ad1843_LX2M,  &ad1843_RX2M };
929static const ad1843_gain_t ad1843_gain_MIC
930				= { 1, &ad1843_LMCM,  &ad1843_RMCM };
931static const ad1843_gain_t ad1843_gain_PCM
932				= { 1, &ad1843_LDA1G, &ad1843_RDA1G };
933
934/* read the current value of an AD1843 bitfield. */
935
936static int ad1843_read_bits(lithium_t *lith, const ad1843_bitfield_t *field)
937{
938	int w = li_read_ad1843_reg(lith, field->reg);
939	int val = w >> field->lo_bit & ((1 << field->nbits) - 1);
940
941	DBGXV("ad1843_read_bits(lith=0x%p, field->{%d %d %d}) returns 0x%x\n",
942	      lith, field->reg, field->lo_bit, field->nbits, val);
943
944	return val;
945}
946
947/*
948 * write a new value to an AD1843 bitfield and return the old value.
949 */
950
951static int ad1843_write_bits(lithium_t *lith,
952			     const ad1843_bitfield_t *field,
953			     int newval)
954{
955	int w = li_read_ad1843_reg(lith, field->reg);
956	int mask = ((1 << field->nbits) - 1) << field->lo_bit;
957	int oldval = (w & mask) >> field->lo_bit;
958	int newbits = (newval << field->lo_bit) & mask;
959	w = (w & ~mask) | newbits;
960	(void) li_write_ad1843_reg(lith, field->reg, w);
961
962	DBGXV("ad1843_write_bits(lith=0x%p, field->{%d %d %d}, val=0x%x) "
963	      "returns 0x%x\n",
964	      lith, field->reg, field->lo_bit, field->nbits, newval,
965	      oldval);
966
967	return oldval;
968}
969
970/*
971 * ad1843_read_multi reads multiple bitfields from the same AD1843
972 * register.  It uses a single read cycle to do it.  (Reading the
973 * ad1843 requires 256 bit times at 12.288 MHz, or nearly 20
974 * microseconds.)
975 *
976 * Called ike this.
977 *
978 *  ad1843_read_multi(lith, nfields,
979 *		      &ad1843_FIELD1, &val1,
980 *		      &ad1843_FIELD2, &val2, ...);
981 */
982
983static void ad1843_read_multi(lithium_t *lith, int argcount, ...)
984{
985	va_list ap;
986	const ad1843_bitfield_t *fp;
987	int w = 0, mask, *value, reg = -1;
988
989	va_start(ap, argcount);
990	while (--argcount >= 0) {
991		fp = va_arg(ap, const ad1843_bitfield_t *);
992		value = va_arg(ap, int *);
993		if (reg == -1) {
994			reg = fp->reg;
995			w = li_read_ad1843_reg(lith, reg);
996		}
997		ASSERT(reg == fp->reg);
998		mask = (1 << fp->nbits) - 1;
999		*value = w >> fp->lo_bit & mask;
1000	}
1001	va_end(ap);
1002}
1003
1004/*
1005 * ad1843_write_multi stores multiple bitfields into the same AD1843
1006 * register.  It uses one read and one write cycle to do it.
1007 *
1008 * Called like this.
1009 *
1010 *  ad1843_write_multi(lith, nfields,
1011 *		       &ad1843_FIELD1, val1,
1012 *		       &ad1843_FIELF2, val2, ...);
1013 */
1014
1015static void ad1843_write_multi(lithium_t *lith, int argcount, ...)
1016{
1017	va_list ap;
1018	int reg;
1019	const ad1843_bitfield_t *fp;
1020	int value;
1021	int w, m, mask, bits;
1022
1023	mask = 0;
1024	bits = 0;
1025	reg = -1;
1026
1027	va_start(ap, argcount);
1028	while (--argcount >= 0) {
1029		fp = va_arg(ap, const ad1843_bitfield_t *);
1030		value = va_arg(ap, int);
1031		if (reg == -1)
1032			reg = fp->reg;
1033		ASSERT(fp->reg == reg);
1034		m = ((1 << fp->nbits) - 1) << fp->lo_bit;
1035		mask |= m;
1036		bits |= (value << fp->lo_bit) & m;
1037	}
1038	va_end(ap);
1039	ASSERT(!(bits & ~mask));
1040	if (~mask & 0xFFFF)
1041		w = li_read_ad1843_reg(lith, reg);
1042	else
1043		w = 0;
1044	w = (w & ~mask) | bits;
1045	(void) li_write_ad1843_reg(lith, reg, w);
1046}
1047
1048/*
1049 * ad1843_get_gain reads the specified register and extracts the gain value
1050 * using the supplied gain type.  It returns the gain in OSS format.
1051 */
1052
1053static int ad1843_get_gain(lithium_t *lith, const ad1843_gain_t *gp)
1054{
1055	int lg, rg;
1056	unsigned short mask = (1 << gp->lfield->nbits) - 1;
1057
1058	ad1843_read_multi(lith, 2, gp->lfield, &lg, gp->rfield, &rg);
1059	if (gp->negative) {
1060		lg = mask - lg;
1061		rg = mask - rg;
1062	}
1063	lg = (lg * 100 + (mask >> 1)) / mask;
1064	rg = (rg * 100 + (mask >> 1)) / mask;
1065	return lg << 0 | rg << 8;
1066}
1067
1068/*
1069 * Set an audio channel's gain. Converts from OSS format to AD1843's
1070 * format.
1071 *
1072 * Returns the new gain, which may be lower than the old gain.
1073 */
1074
1075static int ad1843_set_gain(lithium_t *lith,
1076			   const ad1843_gain_t *gp,
1077			   int newval)
1078{
1079	unsigned short mask = (1 << gp->lfield->nbits) - 1;
1080
1081	int lg = newval >> 0 & 0xFF;
1082	int rg = newval >> 8;
1083	if (lg < 0 || lg > 100 || rg < 0 || rg > 100)
1084		return -EINVAL;
1085	lg = (lg * mask + (mask >> 1)) / 100;
1086	rg = (rg * mask + (mask >> 1)) / 100;
1087	if (gp->negative) {
1088		lg = mask - lg;
1089		rg = mask - rg;
1090	}
1091	ad1843_write_multi(lith, 2, gp->lfield, lg, gp->rfield, rg);
1092	return ad1843_get_gain(lith, gp);
1093}
1094
1095/* Returns the current recording source, in OSS format. */
1096
1097static int ad1843_get_recsrc(lithium_t *lith)
1098{
1099	int ls = ad1843_read_bits(lith, &ad1843_LSS);
1100
1101	switch (ls) {
1102	case 1:
1103		return SOUND_MASK_MIC;
1104	case 2:
1105		return SOUND_MASK_LINE;
1106	case 3:
1107		return SOUND_MASK_CD;
1108	case 6:
1109		return SOUND_MASK_PCM;
1110	default:
1111		ASSERT(0);
1112		return -1;
1113	}
1114}
1115
1116/*
1117 * Enable/disable digital resample mode in the AD1843.
1118 *
1119 * The AD1843 requires that ADL, ADR, DA1 and DA2 be powered down
1120 * while switching modes.  So we save DA1's state (DA2's state is not
1121 * interesting), power them down, switch into/out of resample mode,
1122 * power them up, and restore state.
1123 *
1124 * This will cause audible glitches if D/A or A/D is going on, so the
1125 * driver disallows that (in mixer_write_ioctl()).
1126 *
1127 * The open question is, is this worth doing?  I'm leaving it in,
1128 * because it's written, but...
1129 */
1130
1131static void ad1843_set_resample_mode(lithium_t *lith, int onoff)
1132{
1133	/* Save DA1 mute and gain (addr 9 is DA1 analog gain/attenuation) */
1134	int save_da1 = li_read_ad1843_reg(lith, 9);
1135
1136	/* Power down A/D and D/A. */
1137	ad1843_write_multi(lith, 4,
1138			   &ad1843_DA1EN, 0,
1139			   &ad1843_DA2EN, 0,
1140			   &ad1843_ADLEN, 0,
1141			   &ad1843_ADREN, 0);
1142
1143	/* Switch mode */
1144	ASSERT(onoff == 0 || onoff == 1);
1145	ad1843_write_bits(lith, &ad1843_DRSFLT, onoff);
1146
1147 	/* Power up A/D and D/A. */
1148	ad1843_write_multi(lith, 3,
1149			   &ad1843_DA1EN, 1,
1150			   &ad1843_ADLEN, 1,
1151			   &ad1843_ADREN, 1);
1152
1153	/* Restore DA1 mute and gain. */
1154	li_write_ad1843_reg(lith, 9, save_da1);
1155}
1156
1157/*
1158 * Set recording source.  Arg newsrc specifies an OSS channel mask.
1159 *
1160 * The complication is that when we switch into/out of loopback mode
1161 * (i.e., src = SOUND_MASK_PCM), we change the AD1843 into/out of
1162 * digital resampling mode.
1163 *
1164 * Returns newsrc on success, -errno on failure.
1165 */
1166
1167static int ad1843_set_recsrc(lithium_t *lith, int newsrc)
1168{
1169	int bits;
1170	int oldbits;
1171
1172	switch (newsrc) {
1173	case SOUND_MASK_PCM:
1174		bits = 6;
1175		break;
1176
1177	case SOUND_MASK_MIC:
1178		bits = 1;
1179		break;
1180
1181	case SOUND_MASK_LINE:
1182		bits = 2;
1183		break;
1184
1185	case SOUND_MASK_CD:
1186		bits = 3;
1187		break;
1188
1189	default:
1190		return -EINVAL;
1191	}
1192	oldbits = ad1843_read_bits(lith, &ad1843_LSS);
1193	if (newsrc == SOUND_MASK_PCM && oldbits != 6) {
1194		DBGP("enabling digital resample mode\n");
1195		ad1843_set_resample_mode(lith, 1);
1196		ad1843_write_multi(lith, 2,
1197				   &ad1843_DAADL, 2,
1198				   &ad1843_DAADR, 2);
1199	} else if (newsrc != SOUND_MASK_PCM && oldbits == 6) {
1200		DBGP("disabling digital resample mode\n");
1201		ad1843_set_resample_mode(lith, 0);
1202		ad1843_write_multi(lith, 2,
1203				   &ad1843_DAADL, 0,
1204				   &ad1843_DAADR, 0);
1205	}
1206	ad1843_write_multi(lith, 2, &ad1843_LSS, bits, &ad1843_RSS, bits);
1207	return newsrc;
1208}
1209
1210/*
1211 * Return current output sources, in OSS format.
1212 */
1213
1214static int ad1843_get_outsrc(lithium_t *lith)
1215{
1216	int pcm, line, mic, cd;
1217
1218	pcm  = ad1843_read_bits(lith, &ad1843_LDA1GM) ? 0 : SOUND_MASK_PCM;
1219	line = ad1843_read_bits(lith, &ad1843_LX1MM)  ? 0 : SOUND_MASK_LINE;
1220	cd   = ad1843_read_bits(lith, &ad1843_LX2MM)  ? 0 : SOUND_MASK_CD;
1221	mic  = ad1843_read_bits(lith, &ad1843_LMCMM)  ? 0 : SOUND_MASK_MIC;
1222
1223	return pcm | line | cd | mic;
1224}
1225
1226/*
1227 * Set output sources.  Arg is a mask of active sources in OSS format.
1228 *
1229 * Returns source mask on success, -errno on failure.
1230 */
1231
1232static int ad1843_set_outsrc(lithium_t *lith, int mask)
1233{
1234	int pcm, line, mic, cd;
1235
1236	if (mask & ~(SOUND_MASK_PCM | SOUND_MASK_LINE |
1237		     SOUND_MASK_CD | SOUND_MASK_MIC))
1238		return -EINVAL;
1239	pcm  = (mask & SOUND_MASK_PCM)  ? 0 : 1;
1240	line = (mask & SOUND_MASK_LINE) ? 0 : 1;
1241	mic  = (mask & SOUND_MASK_MIC)  ? 0 : 1;
1242	cd   = (mask & SOUND_MASK_CD)   ? 0 : 1;
1243
1244	ad1843_write_multi(lith, 2, &ad1843_LDA1GM, pcm, &ad1843_RDA1GM, pcm);
1245	ad1843_write_multi(lith, 2, &ad1843_LX1MM, line, &ad1843_RX1MM, line);
1246	ad1843_write_multi(lith, 2, &ad1843_LX2MM, cd,   &ad1843_RX2MM, cd);
1247	ad1843_write_multi(lith, 2, &ad1843_LMCMM, mic,  &ad1843_RMCMM, mic);
1248
1249	return mask;
1250}
1251
1252/* Setup ad1843 for D/A conversion. */
1253
1254static void ad1843_setup_dac(lithium_t *lith,
1255			     int framerate,
1256			     int fmt,
1257			     int channels)
1258{
1259	int ad_fmt = 0, ad_mode = 0;
1260
1261	DBGEV("(lith=0x%p, framerate=%d, fmt=%d, channels=%d)\n",
1262	      lith, framerate, fmt, channels);
1263
1264	switch (fmt) {
1265	case AFMT_S8:		ad_fmt = 1; break;
1266	case AFMT_U8:		ad_fmt = 1; break;
1267	case AFMT_S16_LE:	ad_fmt = 1; break;
1268	case AFMT_MU_LAW:	ad_fmt = 2; break;
1269	case AFMT_A_LAW:	ad_fmt = 3; break;
1270	default:		ASSERT(0);
1271	}
1272
1273	switch (channels) {
1274	case 2:			ad_mode = 0; break;
1275	case 1:			ad_mode = 1; break;
1276	default:		ASSERT(0);
1277	}
1278
1279	DBGPV("ad_mode = %d, ad_fmt = %d\n", ad_mode, ad_fmt);
1280	ASSERT(framerate >= 4000 && framerate <= 49000);
1281	ad1843_write_bits(lith, &ad1843_C1C, framerate);
1282	ad1843_write_multi(lith, 2,
1283			   &ad1843_DA1SM, ad_mode, &ad1843_DA1F, ad_fmt);
1284}
1285
1286static void ad1843_shutdown_dac(lithium_t *lith)
1287{
1288	ad1843_write_bits(lith, &ad1843_DA1F, 1);
1289}
1290
1291static void ad1843_setup_adc(lithium_t *lith, int framerate, int fmt, int channels)
1292{
1293	int da_fmt = 0;
1294
1295	DBGEV("(lith=0x%p, framerate=%d, fmt=%d, channels=%d)\n",
1296	      lith, framerate, fmt, channels);
1297
1298	switch (fmt) {
1299	case AFMT_S8:		da_fmt = 1; break;
1300	case AFMT_U8:		da_fmt = 1; break;
1301	case AFMT_S16_LE:	da_fmt = 1; break;
1302	case AFMT_MU_LAW:	da_fmt = 2; break;
1303	case AFMT_A_LAW:	da_fmt = 3; break;
1304	default:		ASSERT(0);
1305	}
1306
1307	DBGPV("da_fmt = %d\n", da_fmt);
1308	ASSERT(framerate >= 4000 && framerate <= 49000);
1309	ad1843_write_bits(lith, &ad1843_C2C, framerate);
1310	ad1843_write_multi(lith, 2,
1311			   &ad1843_ADLF, da_fmt, &ad1843_ADRF, da_fmt);
1312}
1313
1314static void ad1843_shutdown_adc(lithium_t *lith)
1315{
1316	/* nothing to do */
1317}
1318
1319/*
1320 * Fully initialize the ad1843.  As described in the AD1843 data
1321 * sheet, section "START-UP SEQUENCE".  The numbered comments are
1322 * subsection headings from the data sheet.  See the data sheet, pages
1323 * 52-54, for more info.
1324 *
1325 * return 0 on success, -errno on failure.  */
1326
1327static int __init ad1843_init(lithium_t *lith)
1328{
1329	unsigned long later;
1330	int err;
1331
1332	err = li_init(lith);
1333	if (err)
1334		return err;
1335
1336	if (ad1843_read_bits(lith, &ad1843_INIT) != 0) {
1337		printk(KERN_ERR "vwsnd sound: AD1843 won't initialize\n");
1338		return -EIO;
1339	}
1340
1341	ad1843_write_bits(lith, &ad1843_SCF, 1);
1342
1343	/* 4. Put the conversion resources into standby. */
1344
1345	ad1843_write_bits(lith, &ad1843_PDNI, 0);
1346	later = jiffies + HZ / 2;	/* roughly half a second */
1347	DBGDO(shut_up++);
1348	while (ad1843_read_bits(lith, &ad1843_PDNO)) {
1349		if (time_after(jiffies, later)) {
1350			printk(KERN_ERR
1351			       "vwsnd audio: AD1843 won't power up\n");
1352			return -EIO;
1353		}
1354		schedule();
1355	}
1356	DBGDO(shut_up--);
1357
1358	/* 5. Power up the clock generators and enable clock output pins. */
1359
1360	ad1843_write_multi(lith, 2, &ad1843_C1EN, 1, &ad1843_C2EN, 1);
1361
1362	/* 6. Configure conversion resources while they are in standby. */
1363
1364 	/* DAC1 uses clock 1 as source, ADC uses clock 2.  Always. */
1365
1366	ad1843_write_multi(lith, 3,
1367			   &ad1843_DA1C, 1,
1368			   &ad1843_ADLC, 2,
1369			   &ad1843_ADRC, 2);
1370
1371	/* 7. Enable conversion resources. */
1372
1373	ad1843_write_bits(lith, &ad1843_ADTLK, 1);
1374	ad1843_write_multi(lith, 5,
1375			   &ad1843_ANAEN, 1,
1376			   &ad1843_AAMEN, 1,
1377			   &ad1843_DA1EN, 1,
1378			   &ad1843_ADLEN, 1,
1379			   &ad1843_ADREN, 1);
1380
1381	/* 8. Configure conversion resources while they are enabled. */
1382
1383	ad1843_write_bits(lith, &ad1843_DA1C, 1);
1384
1385	/* Unmute all channels. */
1386
1387	ad1843_set_outsrc(lith,
1388			  (SOUND_MASK_PCM | SOUND_MASK_LINE |
1389			   SOUND_MASK_MIC | SOUND_MASK_CD));
1390	ad1843_write_multi(lith, 2, &ad1843_LDA1AM, 0, &ad1843_RDA1AM, 0);
1391
1392	/* Set default recording source to Line In and set
1393	 * mic gain to +20 dB.
1394	 */
1395
1396	ad1843_set_recsrc(lith, SOUND_MASK_LINE);
1397	ad1843_write_multi(lith, 2, &ad1843_LMGE, 1, &ad1843_RMGE, 1);
1398
1399	/* Set Speaker Out level to +/- 4V and unmute it. */
1400
1401	ad1843_write_multi(lith, 2, &ad1843_HPOS, 1, &ad1843_HPOM, 0);
1402
1403	return 0;
1404}
1405
1406/*****************************************************************************/
1407/* PCM I/O */
1408
1409#define READ_INTR_MASK  (LI_INTR_COMM1_TRIG | LI_INTR_COMM1_OVERFLOW)
1410#define WRITE_INTR_MASK (LI_INTR_COMM2_TRIG | LI_INTR_COMM2_UNDERFLOW)
1411
1412typedef enum vwsnd_port_swstate {	/* software state */
1413	SW_OFF,
1414	SW_INITIAL,
1415	SW_RUN,
1416	SW_DRAIN,
1417} vwsnd_port_swstate_t;
1418
1419typedef enum vwsnd_port_hwstate {	/* hardware state */
1420	HW_STOPPED,
1421	HW_RUNNING,
1422} vwsnd_port_hwstate_t;
1423
1424/*
1425 * These flags are read by ISR, but only written at baseline.
1426 */
1427
1428typedef enum vwsnd_port_flags {
1429	DISABLED = 1 << 0,
1430	ERFLOWN  = 1 << 1,		/* overflown or underflown */
1431	HW_BUSY  = 1 << 2,
1432} vwsnd_port_flags_t;
1433
1434/*
1435 * vwsnd_port is the per-port data structure.  Each device has two
1436 * ports, one for input and one for output.
1437 *
1438 * Locking:
1439 *
1440 *	port->lock protects: hwstate, flags, swb_[iu]_avail.
1441 *
1442 *	devc->io_mutex protects: swstate, sw_*, swb_[iu]_idx.
1443 *
1444 *	everything else is only written by open/release or
1445 *	pcm_{setup,shutdown}(), which are serialized by a
1446 *	combination of devc->open_mutex and devc->io_mutex.
1447 */
1448
1449typedef struct vwsnd_port {
1450
1451	spinlock_t	lock;
1452	wait_queue_head_t queue;
1453	vwsnd_port_swstate_t swstate;
1454	vwsnd_port_hwstate_t hwstate;
1455	vwsnd_port_flags_t flags;
1456
1457	int		sw_channels;
1458	int		sw_samplefmt;
1459	int		sw_framerate;
1460	int		sample_size;
1461	int		frame_size;
1462	unsigned int	zero_word;	/* zero for the sample format */
1463
1464	int		sw_fragshift;
1465	int		sw_fragcount;
1466	int		sw_subdivshift;
1467
1468	unsigned int	hw_fragshift;
1469	unsigned int	hw_fragsize;
1470	unsigned int	hw_fragcount;
1471
1472	int		hwbuf_size;
1473	unsigned long	hwbuf_paddr;
1474	unsigned long	hwbuf_vaddr;
1475	void *		hwbuf;		/* hwbuf == hwbuf_vaddr */
1476	int		hwbuf_max;	/* max bytes to preload */
1477
1478	void *		swbuf;
1479	unsigned int	swbuf_size;	/* size in bytes */
1480	unsigned int	swb_u_idx;	/* index of next user byte */
1481	unsigned int	swb_i_idx;	/* index of next intr byte */
1482	unsigned int	swb_u_avail;	/* # bytes avail to user */
1483	unsigned int	swb_i_avail;	/* # bytes avail to intr */
1484
1485	dma_chan_t	chan;
1486
1487	/* Accounting */
1488
1489	int		byte_count;
1490	int		frag_count;
1491	int		MSC_offset;
1492
1493} vwsnd_port_t;
1494
1495/* vwsnd_dev is the per-device data structure. */
1496
1497typedef struct vwsnd_dev {
1498	struct vwsnd_dev *next_dev;
1499	int		audio_minor;	/* minor number of audio device */
1500	int		mixer_minor;	/* minor number of mixer device */
1501
1502	struct mutex open_mutex;
1503	struct mutex io_mutex;
1504	struct mutex mix_mutex;
1505	fmode_t		open_mode;
1506	wait_queue_head_t open_wait;
1507
1508	lithium_t	lith;
1509
1510	vwsnd_port_t	rport;
1511	vwsnd_port_t	wport;
1512} vwsnd_dev_t;
1513
1514static vwsnd_dev_t *vwsnd_dev_list;	/* linked list of all devices */
1515
1516static atomic_t vwsnd_use_count = ATOMIC_INIT(0);
1517
1518# define INC_USE_COUNT (atomic_inc(&vwsnd_use_count))
1519# define DEC_USE_COUNT (atomic_dec(&vwsnd_use_count))
1520# define IN_USE        (atomic_read(&vwsnd_use_count) != 0)
1521
1522
1523#define HWBUF_SHIFT 13
1524#define HWBUF_SIZE (1 << HWBUF_SHIFT)
1525# define HBO         (HWBUF_SHIFT > PAGE_SHIFT ? HWBUF_SHIFT - PAGE_SHIFT : 0)
1526# define HWBUF_ORDER (HBO + 1)		/* next size bigger */
1527#define MIN_SPEED 4000
1528#define MAX_SPEED 49000
1529
1530#define MIN_FRAGSHIFT			(DMACHUNK_SHIFT + 1)
1531#define MAX_FRAGSHIFT			(PAGE_SHIFT)
1532#define MIN_FRAGSIZE			(1 << MIN_FRAGSHIFT)
1533#define MAX_FRAGSIZE			(1 << MAX_FRAGSHIFT)
1534#define MIN_FRAGCOUNT(fragsize)		3
1535#define MAX_FRAGCOUNT(fragsize)		(32 * PAGE_SIZE / (fragsize))
1536#define DEFAULT_FRAGSHIFT		12
1537#define DEFAULT_FRAGCOUNT		16
1538#define DEFAULT_SUBDIVSHIFT		0
1539
1540/*
1541 * The software buffer (swbuf) is a ring buffer shared between user
1542 * level and interrupt level.  Each level owns some of the bytes in
1543 * the buffer, and may give bytes away by calling swb_inc_{u,i}().
1544 * User level calls _u for user, and interrupt level calls _i for
1545 * interrupt.
1546 *
1547 * port->swb_{u,i}_avail is the number of bytes available to that level.
1548 *
1549 * port->swb_{u,i}_idx is the index of the first available byte in the
1550 * buffer.
1551 *
1552 * Each level calls swb_inc_{u,i}() to atomically increment its index,
1553 * recalculate the number of bytes available for both sides, and
1554 * return the number of bytes available.  Since each side can only
1555 * give away bytes, the other side can only increase the number of
1556 * bytes available to this side.  Each side updates its own index
1557 * variable, swb_{u,i}_idx, so no lock is needed to read it.
1558 *
1559 * To query the number of bytes available, call swb_inc_{u,i} with an
1560 * increment of zero.
1561 */
1562
1563static __inline__ unsigned int __swb_inc_u(vwsnd_port_t *port, int inc)
1564{
1565	if (inc) {
1566		port->swb_u_idx += inc;
1567		port->swb_u_idx %= port->swbuf_size;
1568		port->swb_u_avail -= inc;
1569		port->swb_i_avail += inc;
1570	}
1571	return port->swb_u_avail;
1572}
1573
1574static __inline__ unsigned int swb_inc_u(vwsnd_port_t *port, int inc)
1575{
1576	unsigned long flags;
1577	unsigned int ret;
1578
1579	spin_lock_irqsave(&port->lock, flags);
1580	{
1581		ret = __swb_inc_u(port, inc);
1582	}
1583	spin_unlock_irqrestore(&port->lock, flags);
1584	return ret;
1585}
1586
1587static __inline__ unsigned int __swb_inc_i(vwsnd_port_t *port, int inc)
1588{
1589	if (inc) {
1590		port->swb_i_idx += inc;
1591		port->swb_i_idx %= port->swbuf_size;
1592		port->swb_i_avail -= inc;
1593		port->swb_u_avail += inc;
1594	}
1595	return port->swb_i_avail;
1596}
1597
1598static __inline__ unsigned int swb_inc_i(vwsnd_port_t *port, int inc)
1599{
1600	unsigned long flags;
1601	unsigned int ret;
1602
1603	spin_lock_irqsave(&port->lock, flags);
1604	{
1605		ret = __swb_inc_i(port, inc);
1606	}
1607	spin_unlock_irqrestore(&port->lock, flags);
1608	return ret;
1609}
1610
1611/*
1612 * pcm_setup - this routine initializes all port state after
1613 * mode-setting ioctls have been done, but before the first I/O is
1614 * done.
1615 *
1616 * Locking: called with devc->io_mutex held.
1617 *
1618 * Returns 0 on success, -errno on failure.
1619 */
1620
1621static int pcm_setup(vwsnd_dev_t *devc,
1622		     vwsnd_port_t *rport,
1623		     vwsnd_port_t *wport)
1624{
1625	vwsnd_port_t *aport = rport ? rport : wport;
1626	int sample_size;
1627	unsigned int zero_word;
1628
1629	DBGEV("(devc=0x%p, rport=0x%p, wport=0x%p)\n", devc, rport, wport);
1630
1631	ASSERT(aport != NULL);
1632	if (aport->swbuf != NULL)
1633		return 0;
1634	switch (aport->sw_samplefmt) {
1635	case AFMT_MU_LAW:
1636		sample_size = 1;
1637		zero_word = 0xFFFFFFFF ^ 0x80808080;
1638		break;
1639
1640	case AFMT_A_LAW:
1641		sample_size = 1;
1642		zero_word = 0xD5D5D5D5 ^ 0x80808080;
1643		break;
1644
1645	case AFMT_U8:
1646		sample_size = 1;
1647		zero_word = 0x80808080;
1648		break;
1649
1650	case AFMT_S8:
1651		sample_size = 1;
1652		zero_word = 0x00000000;
1653		break;
1654
1655	case AFMT_S16_LE:
1656		sample_size = 2;
1657		zero_word = 0x00000000;
1658		break;
1659
1660	default:
1661		sample_size = 0;	/* prevent compiler warning */
1662		zero_word = 0;
1663		ASSERT(0);
1664	}
1665	aport->sample_size  = sample_size;
1666	aport->zero_word    = zero_word;
1667	aport->frame_size   = aport->sw_channels * aport->sample_size;
1668	aport->hw_fragshift = aport->sw_fragshift - aport->sw_subdivshift;
1669	aport->hw_fragsize  = 1 << aport->hw_fragshift;
1670	aport->hw_fragcount = aport->sw_fragcount << aport->sw_subdivshift;
1671	ASSERT(aport->hw_fragsize >= MIN_FRAGSIZE);
1672	ASSERT(aport->hw_fragsize <= MAX_FRAGSIZE);
1673	ASSERT(aport->hw_fragcount >= MIN_FRAGCOUNT(aport->hw_fragsize));
1674	ASSERT(aport->hw_fragcount <= MAX_FRAGCOUNT(aport->hw_fragsize));
1675	if (rport) {
1676		int hwfrags, swfrags;
1677		rport->hwbuf_max = aport->hwbuf_size - DMACHUNK_SIZE;
1678		hwfrags = rport->hwbuf_max >> aport->hw_fragshift;
1679		swfrags = aport->hw_fragcount - hwfrags;
1680		if (swfrags < 2)
1681			swfrags = 2;
1682		rport->swbuf_size = swfrags * aport->hw_fragsize;
1683		DBGPV("hwfrags = %d, swfrags = %d\n", hwfrags, swfrags);
1684		DBGPV("read hwbuf_max = %d, swbuf_size = %d\n",
1685		     rport->hwbuf_max, rport->swbuf_size);
1686	}
1687	if (wport) {
1688		int hwfrags, swfrags;
1689		int total_bytes = aport->hw_fragcount * aport->hw_fragsize;
1690		wport->hwbuf_max = aport->hwbuf_size - DMACHUNK_SIZE;
1691		if (wport->hwbuf_max > total_bytes)
1692			wport->hwbuf_max = total_bytes;
1693		hwfrags = wport->hwbuf_max >> aport->hw_fragshift;
1694		DBGPV("hwfrags = %d\n", hwfrags);
1695		swfrags = aport->hw_fragcount - hwfrags;
1696		if (swfrags < 2)
1697			swfrags = 2;
1698		wport->swbuf_size = swfrags * aport->hw_fragsize;
1699		DBGPV("hwfrags = %d, swfrags = %d\n", hwfrags, swfrags);
1700		DBGPV("write hwbuf_max = %d, swbuf_size = %d\n",
1701		     wport->hwbuf_max, wport->swbuf_size);
1702	}
1703
1704	aport->swb_u_idx    = 0;
1705	aport->swb_i_idx    = 0;
1706	aport->byte_count   = 0;
1707
1708	/*
1709	 * Is this a Cobalt bug?  We need to make this buffer extend
1710	 * one page further than we actually use -- somehow memcpy
1711	 * causes an exceptoin otherwise.  I suspect there's a bug in
1712	 * Cobalt (or somewhere) where it's generating a fault on a
1713	 * speculative load or something.  Obviously, I haven't taken
1714	 * the time to track it down.
1715	 */
1716
1717	aport->swbuf        = vmalloc(aport->swbuf_size + PAGE_SIZE);
1718	if (!aport->swbuf)
1719		return -ENOMEM;
1720	if (rport && wport) {
1721		ASSERT(aport == rport);
1722		ASSERT(wport->swbuf == NULL);
1723		/* One extra page - see comment above. */
1724		wport->swbuf = vmalloc(aport->swbuf_size + PAGE_SIZE);
1725		if (!wport->swbuf) {
1726			vfree(aport->swbuf);
1727			aport->swbuf = NULL;
1728			return -ENOMEM;
1729		}
1730		wport->sample_size  = rport->sample_size;
1731		wport->zero_word    = rport->zero_word;
1732		wport->frame_size   = rport->frame_size;
1733		wport->hw_fragshift = rport->hw_fragshift;
1734		wport->hw_fragsize  = rport->hw_fragsize;
1735		wport->hw_fragcount = rport->hw_fragcount;
1736		wport->swbuf_size   = rport->swbuf_size;
1737		wport->hwbuf_max    = rport->hwbuf_max;
1738		wport->swb_u_idx    = rport->swb_u_idx;
1739		wport->swb_i_idx    = rport->swb_i_idx;
1740		wport->byte_count   = rport->byte_count;
1741	}
1742	if (rport) {
1743		rport->swb_u_avail = 0;
1744		rport->swb_i_avail = rport->swbuf_size;
1745		rport->swstate = SW_RUN;
1746		li_setup_dma(&rport->chan,
1747			     &li_comm1,
1748			     &devc->lith,
1749			     rport->hwbuf_paddr,
1750			     HWBUF_SHIFT,
1751			     rport->hw_fragshift,
1752			     rport->sw_channels,
1753			     rport->sample_size);
1754		ad1843_setup_adc(&devc->lith,
1755				 rport->sw_framerate,
1756				 rport->sw_samplefmt,
1757				 rport->sw_channels);
1758		li_enable_interrupts(&devc->lith, READ_INTR_MASK);
1759		if (!(rport->flags & DISABLED)) {
1760			ustmsc_t ustmsc;
1761			rport->hwstate = HW_RUNNING;
1762			li_activate_dma(&rport->chan);
1763			li_read_USTMSC(&rport->chan, &ustmsc);
1764			rport->MSC_offset = ustmsc.msc;
1765		}
1766	}
1767	if (wport) {
1768		if (wport->hwbuf_max > wport->swbuf_size)
1769			wport->hwbuf_max = wport->swbuf_size;
1770		wport->flags &= ~ERFLOWN;
1771		wport->swb_u_avail = wport->swbuf_size;
1772		wport->swb_i_avail = 0;
1773		wport->swstate = SW_RUN;
1774		li_setup_dma(&wport->chan,
1775			     &li_comm2,
1776			     &devc->lith,
1777			     wport->hwbuf_paddr,
1778			     HWBUF_SHIFT,
1779			     wport->hw_fragshift,
1780			     wport->sw_channels,
1781			     wport->sample_size);
1782		ad1843_setup_dac(&devc->lith,
1783				 wport->sw_framerate,
1784				 wport->sw_samplefmt,
1785				 wport->sw_channels);
1786		li_enable_interrupts(&devc->lith, WRITE_INTR_MASK);
1787	}
1788	DBGRV();
1789	return 0;
1790}
1791
1792/*
1793 * pcm_shutdown_port - shut down one port (direction) for PCM I/O.
1794 * Only called from pcm_shutdown.
1795 */
1796
1797static void pcm_shutdown_port(vwsnd_dev_t *devc,
1798			      vwsnd_port_t *aport,
1799			      unsigned int mask)
1800{
1801	unsigned long flags;
1802	vwsnd_port_hwstate_t hwstate;
1803	DECLARE_WAITQUEUE(wait, current);
1804
1805	aport->swstate = SW_INITIAL;
1806	add_wait_queue(&aport->queue, &wait);
1807	while (1) {
1808		set_current_state(TASK_UNINTERRUPTIBLE);
1809		spin_lock_irqsave(&aport->lock, flags);
1810		{
1811			hwstate = aport->hwstate;
1812		}
1813		spin_unlock_irqrestore(&aport->lock, flags);
1814		if (hwstate == HW_STOPPED)
1815			break;
1816		schedule();
1817	}
1818	current->state = TASK_RUNNING;
1819	remove_wait_queue(&aport->queue, &wait);
1820	li_disable_interrupts(&devc->lith, mask);
1821	if (aport == &devc->rport)
1822		ad1843_shutdown_adc(&devc->lith);
1823	else /* aport == &devc->wport) */
1824		ad1843_shutdown_dac(&devc->lith);
1825	li_shutdown_dma(&aport->chan);
1826	vfree(aport->swbuf);
1827	aport->swbuf = NULL;
1828	aport->byte_count = 0;
1829}
1830
1831/*
1832 * pcm_shutdown undoes what pcm_setup did.
1833 * Also sets the ports' swstate to newstate.
1834 */
1835
1836static void pcm_shutdown(vwsnd_dev_t *devc,
1837			 vwsnd_port_t *rport,
1838			 vwsnd_port_t *wport)
1839{
1840	DBGEV("(devc=0x%p, rport=0x%p, wport=0x%p)\n", devc, rport, wport);
1841
1842	if (rport && rport->swbuf) {
1843		DBGPV("shutting down rport\n");
1844		pcm_shutdown_port(devc, rport, READ_INTR_MASK);
1845	}
1846	if (wport && wport->swbuf) {
1847		DBGPV("shutting down wport\n");
1848		pcm_shutdown_port(devc, wport, WRITE_INTR_MASK);
1849	}
1850	DBGRV();
1851}
1852
1853static void pcm_copy_in(vwsnd_port_t *rport, int swidx, int hwidx, int nb)
1854{
1855	char *src = rport->hwbuf + hwidx;
1856	char *dst = rport->swbuf + swidx;
1857	int fmt = rport->sw_samplefmt;
1858
1859	DBGPV("swidx = %d, hwidx = %d\n", swidx, hwidx);
1860	ASSERT(rport->hwbuf != NULL);
1861	ASSERT(rport->swbuf != NULL);
1862	ASSERT(nb > 0 && (nb % 32) == 0);
1863	ASSERT(swidx % 32 == 0 && hwidx % 32 == 0);
1864	ASSERT(swidx >= 0 && swidx + nb <= rport->swbuf_size);
1865	ASSERT(hwidx >= 0 && hwidx + nb <= rport->hwbuf_size);
1866
1867	if (fmt == AFMT_MU_LAW || fmt == AFMT_A_LAW || fmt == AFMT_S8) {
1868
1869		/* See Sample Format Notes above. */
1870
1871		char *end = src + nb;
1872		while (src < end)
1873			*dst++ = *src++ ^ 0x80;
1874	} else
1875		memcpy(dst, src, nb);
1876}
1877
1878static void pcm_copy_out(vwsnd_port_t *wport, int swidx, int hwidx, int nb)
1879{
1880	char *src = wport->swbuf + swidx;
1881	char *dst = wport->hwbuf + hwidx;
1882	int fmt = wport->sw_samplefmt;
1883
1884	ASSERT(nb > 0 && (nb % 32) == 0);
1885	ASSERT(wport->hwbuf != NULL);
1886	ASSERT(wport->swbuf != NULL);
1887	ASSERT(swidx % 32 == 0 && hwidx % 32 == 0);
1888	ASSERT(swidx >= 0 && swidx + nb <= wport->swbuf_size);
1889	ASSERT(hwidx >= 0 && hwidx + nb <= wport->hwbuf_size);
1890	if (fmt == AFMT_MU_LAW || fmt == AFMT_A_LAW || fmt == AFMT_S8) {
1891
1892		/* See Sample Format Notes above. */
1893
1894		char *end = src + nb;
1895		while (src < end)
1896			*dst++ = *src++ ^ 0x80;
1897	} else
1898		memcpy(dst, src, nb);
1899}
1900
1901/*
1902 * pcm_output() is called both from baselevel and from interrupt level.
1903 * This is where audio frames are copied into the hardware-accessible
1904 * ring buffer.
1905 *
1906 * Locking note: The part of this routine that figures out what to do
1907 * holds wport->lock.  The longer part releases wport->lock, but sets
1908 * wport->flags & HW_BUSY.  Afterward, it reacquires wport->lock, and
1909 * checks for more work to do.
1910 *
1911 * If another thread calls pcm_output() while HW_BUSY is set, it
1912 * returns immediately, knowing that the thread that set HW_BUSY will
1913 * look for more work to do before returning.
1914 *
1915 * This has the advantage that port->lock is held for several short
1916 * periods instead of one long period.  Also, when pcm_output is
1917 * called from base level, it reenables interrupts.
1918 */
1919
1920static void pcm_output(vwsnd_dev_t *devc, int erflown, int nb)
1921{
1922	vwsnd_port_t *wport = &devc->wport;
1923	const int hwmax  = wport->hwbuf_max;
1924	const int hwsize = wport->hwbuf_size;
1925	const int swsize = wport->swbuf_size;
1926	const int fragsize = wport->hw_fragsize;
1927	unsigned long iflags;
1928
1929	DBGEV("(devc=0x%p, erflown=%d, nb=%d)\n", devc, erflown, nb);
1930	spin_lock_irqsave(&wport->lock, iflags);
1931	if (erflown)
1932		wport->flags |= ERFLOWN;
1933	(void) __swb_inc_u(wport, nb);
1934	if (wport->flags & HW_BUSY) {
1935		spin_unlock_irqrestore(&wport->lock, iflags);
1936		DBGPV("returning: HW BUSY\n");
1937		return;
1938	}
1939	if (wport->flags & DISABLED) {
1940		spin_unlock_irqrestore(&wport->lock, iflags);
1941		DBGPV("returning: DISABLED\n");
1942		return;
1943	}
1944	wport->flags |= HW_BUSY;
1945	while (1) {
1946		int swptr, hwptr, hw_avail, sw_avail, swidx;
1947		vwsnd_port_hwstate_t hwstate = wport->hwstate;
1948		vwsnd_port_swstate_t swstate = wport->swstate;
1949		int hw_unavail;
1950		ustmsc_t ustmsc;
1951
1952		hwptr = li_read_hwptr(&wport->chan);
1953		swptr = li_read_swptr(&wport->chan);
1954		hw_unavail = (swptr - hwptr + hwsize) % hwsize;
1955		hw_avail = (hwmax - hw_unavail) & -fragsize;
1956		sw_avail = wport->swb_i_avail & -fragsize;
1957		if (sw_avail && swstate == SW_RUN) {
1958			if (wport->flags & ERFLOWN) {
1959				wport->flags &= ~ERFLOWN;
1960			}
1961		} else if (swstate == SW_INITIAL ||
1962			 swstate == SW_OFF ||
1963			 (swstate == SW_DRAIN &&
1964			  !sw_avail &&
1965			  (wport->flags & ERFLOWN))) {
1966			DBGP("stopping.  hwstate = %d\n", hwstate);
1967			if (hwstate != HW_STOPPED) {
1968				li_deactivate_dma(&wport->chan);
1969				wport->hwstate = HW_STOPPED;
1970			}
1971			wake_up(&wport->queue);
1972			break;
1973		}
1974		if (!sw_avail || !hw_avail)
1975			break;
1976		spin_unlock_irqrestore(&wport->lock, iflags);
1977
1978		/*
1979		 * We gave up the port lock, but we have the HW_BUSY flag.
1980		 * Proceed without accessing any nonlocal state.
1981		 * Do not exit the loop -- must check for more work.
1982		 */
1983
1984		swidx = wport->swb_i_idx;
1985		nb = hw_avail;
1986		if (nb > sw_avail)
1987			nb = sw_avail;
1988		if (nb > hwsize - swptr)
1989			nb = hwsize - swptr; /* don't overflow hwbuf */
1990		if (nb > swsize - swidx)
1991			nb = swsize - swidx; /* don't overflow swbuf */
1992		ASSERT(nb > 0);
1993		if (nb % fragsize) {
1994			DBGP("nb = %d, fragsize = %d\n", nb, fragsize);
1995			DBGP("hw_avail = %d\n", hw_avail);
1996			DBGP("sw_avail = %d\n", sw_avail);
1997			DBGP("hwsize = %d, swptr = %d\n", hwsize, swptr);
1998			DBGP("swsize = %d, swidx = %d\n", swsize, swidx);
1999		}
2000		ASSERT(!(nb % fragsize));
2001		DBGPV("copying swb[%d..%d] to hwb[%d..%d]\n",
2002		      swidx, swidx + nb, swptr, swptr + nb);
2003		pcm_copy_out(wport, swidx, swptr, nb);
2004		li_write_swptr(&wport->chan, (swptr + nb) % hwsize);
2005		spin_lock_irqsave(&wport->lock, iflags);
2006		if (hwstate == HW_STOPPED) {
2007			DBGPV("starting\n");
2008			li_activate_dma(&wport->chan);
2009			wport->hwstate = HW_RUNNING;
2010			li_read_USTMSC(&wport->chan, &ustmsc);
2011			ASSERT(wport->byte_count % wport->frame_size == 0);
2012			wport->MSC_offset = ustmsc.msc - wport->byte_count / wport->frame_size;
2013		}
2014		__swb_inc_i(wport, nb);
2015		wport->byte_count += nb;
2016		wport->frag_count += nb / fragsize;
2017		ASSERT(nb % fragsize == 0);
2018		wake_up(&wport->queue);
2019	}
2020	wport->flags &= ~HW_BUSY;
2021	spin_unlock_irqrestore(&wport->lock, iflags);
2022	DBGRV();
2023}
2024
2025/*
2026 * pcm_input() is called both from baselevel and from interrupt level.
2027 * This is where audio frames are copied out of the hardware-accessible
2028 * ring buffer.
2029 *
2030 * Locking note: The part of this routine that figures out what to do
2031 * holds rport->lock.  The longer part releases rport->lock, but sets
2032 * rport->flags & HW_BUSY.  Afterward, it reacquires rport->lock, and
2033 * checks for more work to do.
2034 *
2035 * If another thread calls pcm_input() while HW_BUSY is set, it
2036 * returns immediately, knowing that the thread that set HW_BUSY will
2037 * look for more work to do before returning.
2038 *
2039 * This has the advantage that port->lock is held for several short
2040 * periods instead of one long period.  Also, when pcm_input is
2041 * called from base level, it reenables interrupts.
2042 */
2043
2044static void pcm_input(vwsnd_dev_t *devc, int erflown, int nb)
2045{
2046	vwsnd_port_t *rport = &devc->rport;
2047	const int hwmax  = rport->hwbuf_max;
2048	const int hwsize = rport->hwbuf_size;
2049	const int swsize = rport->swbuf_size;
2050	const int fragsize = rport->hw_fragsize;
2051	unsigned long iflags;
2052
2053	DBGEV("(devc=0x%p, erflown=%d, nb=%d)\n", devc, erflown, nb);
2054
2055	spin_lock_irqsave(&rport->lock, iflags);
2056	if (erflown)
2057		rport->flags |= ERFLOWN;
2058	(void) __swb_inc_u(rport, nb);
2059	if (rport->flags & HW_BUSY || !rport->swbuf) {
2060		spin_unlock_irqrestore(&rport->lock, iflags);
2061		DBGPV("returning: HW BUSY or !swbuf\n");
2062		return;
2063	}
2064	if (rport->flags & DISABLED) {
2065		spin_unlock_irqrestore(&rport->lock, iflags);
2066		DBGPV("returning: DISABLED\n");
2067		return;
2068	}
2069	rport->flags |= HW_BUSY;
2070	while (1) {
2071		int swptr, hwptr, hw_avail, sw_avail, swidx;
2072		vwsnd_port_hwstate_t hwstate = rport->hwstate;
2073		vwsnd_port_swstate_t swstate = rport->swstate;
2074
2075		hwptr = li_read_hwptr(&rport->chan);
2076		swptr = li_read_swptr(&rport->chan);
2077		hw_avail = (hwptr - swptr + hwsize) % hwsize & -fragsize;
2078		if (hw_avail > hwmax)
2079			hw_avail = hwmax;
2080		sw_avail = rport->swb_i_avail & -fragsize;
2081		if (swstate != SW_RUN) {
2082			DBGP("stopping.  hwstate = %d\n", hwstate);
2083			if (hwstate != HW_STOPPED) {
2084				li_deactivate_dma(&rport->chan);
2085				rport->hwstate = HW_STOPPED;
2086			}
2087			wake_up(&rport->queue);
2088			break;
2089		}
2090		if (!sw_avail || !hw_avail)
2091			break;
2092		spin_unlock_irqrestore(&rport->lock, iflags);
2093
2094		/*
2095		 * We gave up the port lock, but we have the HW_BUSY flag.
2096		 * Proceed without accessing any nonlocal state.
2097		 * Do not exit the loop -- must check for more work.
2098		 */
2099
2100		swidx = rport->swb_i_idx;
2101		nb = hw_avail;
2102		if (nb > sw_avail)
2103			nb = sw_avail;
2104		if (nb > hwsize - swptr)
2105			nb = hwsize - swptr; /* don't overflow hwbuf */
2106		if (nb > swsize - swidx)
2107			nb = swsize - swidx; /* don't overflow swbuf */
2108		ASSERT(nb > 0);
2109		if (nb % fragsize) {
2110			DBGP("nb = %d, fragsize = %d\n", nb, fragsize);
2111			DBGP("hw_avail = %d\n", hw_avail);
2112			DBGP("sw_avail = %d\n", sw_avail);
2113			DBGP("hwsize = %d, swptr = %d\n", hwsize, swptr);
2114			DBGP("swsize = %d, swidx = %d\n", swsize, swidx);
2115		}
2116		ASSERT(!(nb % fragsize));
2117		DBGPV("copying hwb[%d..%d] to swb[%d..%d]\n",
2118		      swptr, swptr + nb, swidx, swidx + nb);
2119		pcm_copy_in(rport, swidx, swptr, nb);
2120		li_write_swptr(&rport->chan, (swptr + nb) % hwsize);
2121		spin_lock_irqsave(&rport->lock, iflags);
2122		__swb_inc_i(rport, nb);
2123		rport->byte_count += nb;
2124		rport->frag_count += nb / fragsize;
2125		ASSERT(nb % fragsize == 0);
2126		wake_up(&rport->queue);
2127	}
2128	rport->flags &= ~HW_BUSY;
2129	spin_unlock_irqrestore(&rport->lock, iflags);
2130	DBGRV();
2131}
2132
2133/*
2134 * pcm_flush_frag() writes zero samples to fill the current fragment,
2135 * then flushes it to the hardware.
2136 *
2137 * It is only meaningful to flush output, not input.
2138 */
2139
2140static void pcm_flush_frag(vwsnd_dev_t *devc)
2141{
2142	vwsnd_port_t *wport = &devc->wport;
2143
2144	DBGPV("swstate = %d\n", wport->swstate);
2145	if (wport->swstate == SW_RUN) {
2146		int idx = wport->swb_u_idx;
2147		int end = (idx + wport->hw_fragsize - 1)
2148			>> wport->hw_fragshift
2149			<< wport->hw_fragshift;
2150		int nb = end - idx;
2151		DBGPV("clearing %d bytes\n", nb);
2152		if (nb)
2153			memset(wport->swbuf + idx,
2154			       (char) wport->zero_word,
2155			       nb);
2156		wport->swstate = SW_DRAIN;
2157		pcm_output(devc, 0, nb);
2158	}
2159	DBGRV();
2160}
2161
2162/*
2163 * Wait for output to drain.  This sleeps uninterruptibly because
2164 * there is nothing intelligent we can do if interrupted.  This
2165 * means the process will be delayed in responding to the signal.
2166 */
2167
2168static void pcm_write_sync(vwsnd_dev_t *devc)
2169{
2170	vwsnd_port_t *wport = &devc->wport;
2171	DECLARE_WAITQUEUE(wait, current);
2172	unsigned long flags;
2173	vwsnd_port_hwstate_t hwstate;
2174
2175	DBGEV("(devc=0x%p)\n", devc);
2176	add_wait_queue(&wport->queue, &wait);
2177	while (1) {
2178		set_current_state(TASK_UNINTERRUPTIBLE);
2179		spin_lock_irqsave(&wport->lock, flags);
2180		{
2181			hwstate = wport->hwstate;
2182		}
2183		spin_unlock_irqrestore(&wport->lock, flags);
2184		if (hwstate == HW_STOPPED)
2185			break;
2186		schedule();
2187	}
2188	current->state = TASK_RUNNING;
2189	remove_wait_queue(&wport->queue, &wait);
2190	DBGPV("swstate = %d, hwstate = %d\n", wport->swstate, wport->hwstate);
2191	DBGRV();
2192}
2193
2194/*****************************************************************************/
2195/* audio driver */
2196
2197/*
2198 * seek on an audio device always fails.
2199 */
2200
2201static void vwsnd_audio_read_intr(vwsnd_dev_t *devc, unsigned int status)
2202{
2203	int overflown = status & LI_INTR_COMM1_OVERFLOW;
2204
2205	if (status & READ_INTR_MASK)
2206		pcm_input(devc, overflown, 0);
2207}
2208
2209static void vwsnd_audio_write_intr(vwsnd_dev_t *devc, unsigned int status)
2210{
2211	int underflown = status & LI_INTR_COMM2_UNDERFLOW;
2212
2213	if (status & WRITE_INTR_MASK)
2214		pcm_output(devc, underflown, 0);
2215}
2216
2217static irqreturn_t vwsnd_audio_intr(int irq, void *dev_id)
2218{
2219	vwsnd_dev_t *devc = dev_id;
2220	unsigned int status;
2221
2222	DBGEV("(irq=%d, dev_id=0x%p)\n", irq, dev_id);
2223
2224	status = li_get_clear_intr_status(&devc->lith);
2225	vwsnd_audio_read_intr(devc, status);
2226	vwsnd_audio_write_intr(devc, status);
2227	return IRQ_HANDLED;
2228}
2229
2230static ssize_t vwsnd_audio_do_read(struct file *file,
2231				   char *buffer,
2232				   size_t count,
2233				   loff_t *ppos)
2234{
2235	vwsnd_dev_t *devc = file->private_data;
2236	vwsnd_port_t *rport = ((file->f_mode & FMODE_READ) ?
2237			       &devc->rport : NULL);
2238	int ret, nb;
2239
2240	DBGEV("(file=0x%p, buffer=0x%p, count=%d, ppos=0x%p)\n",
2241	     file, buffer, count, ppos);
2242
2243	if (!rport)
2244		return -EINVAL;
2245
2246	if (rport->swbuf == NULL) {
2247		vwsnd_port_t *wport = (file->f_mode & FMODE_WRITE) ?
2248			&devc->wport : NULL;
2249		ret = pcm_setup(devc, rport, wport);
2250		if (ret < 0)
2251			return ret;
2252	}
2253
2254	if (!access_ok(VERIFY_READ, buffer, count))
2255		return -EFAULT;
2256	ret = 0;
2257	while (count) {
2258		DECLARE_WAITQUEUE(wait, current);
2259		add_wait_queue(&rport->queue, &wait);
2260		while ((nb = swb_inc_u(rport, 0)) == 0) {
2261			DBGPV("blocking\n");
2262			set_current_state(TASK_INTERRUPTIBLE);
2263			if (rport->flags & DISABLED ||
2264			    file->f_flags & O_NONBLOCK) {
2265				current->state = TASK_RUNNING;
2266				remove_wait_queue(&rport->queue, &wait);
2267				return ret ? ret : -EAGAIN;
2268			}
2269			schedule();
2270			if (signal_pending(current)) {
2271				current->state = TASK_RUNNING;
2272				remove_wait_queue(&rport->queue, &wait);
2273				return ret ? ret : -ERESTARTSYS;
2274			}
2275		}
2276		current->state = TASK_RUNNING;
2277		remove_wait_queue(&rport->queue, &wait);
2278		pcm_input(devc, 0, 0);
2279		/* nb bytes are available in userbuf. */
2280		if (nb > count)
2281			nb = count;
2282		DBGPV("nb = %d\n", nb);
2283		if (copy_to_user(buffer, rport->swbuf + rport->swb_u_idx, nb))
2284			return -EFAULT;
2285		(void) swb_inc_u(rport, nb);
2286		buffer += nb;
2287		count -= nb;
2288		ret += nb;
2289	}
2290	DBGPV("returning %d\n", ret);
2291	return ret;
2292}
2293
2294static ssize_t vwsnd_audio_read(struct file *file,
2295				char *buffer,
2296				size_t count,
2297				loff_t *ppos)
2298{
2299	vwsnd_dev_t *devc = file->private_data;
2300	ssize_t ret;
2301
2302	mutex_lock(&devc->io_mutex);
2303	ret = vwsnd_audio_do_read(file, buffer, count, ppos);
2304	mutex_unlock(&devc->io_mutex);
2305	return ret;
2306}
2307
2308static ssize_t vwsnd_audio_do_write(struct file *file,
2309				    const char *buffer,
2310				    size_t count,
2311				    loff_t *ppos)
2312{
2313	vwsnd_dev_t *devc = file->private_data;
2314	vwsnd_port_t *wport = ((file->f_mode & FMODE_WRITE) ?
2315			       &devc->wport : NULL);
2316	int ret, nb;
2317
2318	DBGEV("(file=0x%p, buffer=0x%p, count=%d, ppos=0x%p)\n",
2319	      file, buffer, count, ppos);
2320
2321	if (!wport)
2322		return -EINVAL;
2323
2324	if (wport->swbuf == NULL) {
2325		vwsnd_port_t *rport = (file->f_mode & FMODE_READ) ?
2326			&devc->rport : NULL;
2327		ret = pcm_setup(devc, rport, wport);
2328		if (ret < 0)
2329			return ret;
2330	}
2331	if (!access_ok(VERIFY_WRITE, buffer, count))
2332		return -EFAULT;
2333	ret = 0;
2334	while (count) {
2335		DECLARE_WAITQUEUE(wait, current);
2336		add_wait_queue(&wport->queue, &wait);
2337		while ((nb = swb_inc_u(wport, 0)) == 0) {
2338			set_current_state(TASK_INTERRUPTIBLE);
2339			if (wport->flags & DISABLED ||
2340			    file->f_flags & O_NONBLOCK) {
2341				current->state = TASK_RUNNING;
2342				remove_wait_queue(&wport->queue, &wait);
2343				return ret ? ret : -EAGAIN;
2344			}
2345			schedule();
2346			if (signal_pending(current)) {
2347				current->state = TASK_RUNNING;
2348				remove_wait_queue(&wport->queue, &wait);
2349				return ret ? ret : -ERESTARTSYS;
2350			}
2351		}
2352		current->state = TASK_RUNNING;
2353		remove_wait_queue(&wport->queue, &wait);
2354		/* nb bytes are available in userbuf. */
2355		if (nb > count)
2356			nb = count;
2357		DBGPV("nb = %d\n", nb);
2358		if (copy_from_user(wport->swbuf + wport->swb_u_idx, buffer, nb))
2359			return -EFAULT;
2360		pcm_output(devc, 0, nb);
2361		buffer += nb;
2362		count -= nb;
2363		ret += nb;
2364	}
2365	DBGPV("returning %d\n", ret);
2366	return ret;
2367}
2368
2369static ssize_t vwsnd_audio_write(struct file *file,
2370				 const char *buffer,
2371				 size_t count,
2372				 loff_t *ppos)
2373{
2374	vwsnd_dev_t *devc = file->private_data;
2375	ssize_t ret;
2376
2377	mutex_lock(&devc->io_mutex);
2378	ret = vwsnd_audio_do_write(file, buffer, count, ppos);
2379	mutex_unlock(&devc->io_mutex);
2380	return ret;
2381}
2382
2383/* No kernel lock - fine */
2384static unsigned int vwsnd_audio_poll(struct file *file,
2385				     struct poll_table_struct *wait)
2386{
2387	vwsnd_dev_t *devc = (vwsnd_dev_t *) file->private_data;
2388	vwsnd_port_t *rport = (file->f_mode & FMODE_READ) ?
2389		&devc->rport : NULL;
2390	vwsnd_port_t *wport = (file->f_mode & FMODE_WRITE) ?
2391		&devc->wport : NULL;
2392	unsigned int mask = 0;
2393
2394	DBGEV("(file=0x%p, wait=0x%p)\n", file, wait);
2395
2396	ASSERT(rport || wport);
2397	if (rport) {
2398		poll_wait(file, &rport->queue, wait);
2399		if (swb_inc_u(rport, 0))
2400			mask |= (POLLIN | POLLRDNORM);
2401	}
2402	if (wport) {
2403		poll_wait(file, &wport->queue, wait);
2404		if (wport->swbuf == NULL || swb_inc_u(wport, 0))
2405			mask |= (POLLOUT | POLLWRNORM);
2406	}
2407
2408	DBGPV("returning 0x%x\n", mask);
2409	return mask;
2410}
2411
2412static int vwsnd_audio_do_ioctl(struct file *file,
2413				unsigned int cmd,
2414				unsigned long arg)
2415{
2416	vwsnd_dev_t *devc = (vwsnd_dev_t *) file->private_data;
2417	vwsnd_port_t *rport = (file->f_mode & FMODE_READ) ?
2418		&devc->rport : NULL;
2419	vwsnd_port_t *wport = (file->f_mode & FMODE_WRITE) ?
2420		&devc->wport : NULL;
2421	vwsnd_port_t *aport = rport ? rport : wport;
2422	struct audio_buf_info buf_info;
2423	struct count_info info;
2424	unsigned long flags;
2425	int ival;
2426
2427
2428	DBGEV("(file=0x%p, cmd=0x%x, arg=0x%lx)\n",
2429	      file, cmd, arg);
2430	switch (cmd) {
2431	case OSS_GETVERSION:		/* _SIOR ('M', 118, int) */
2432		DBGX("OSS_GETVERSION\n");
2433		ival = SOUND_VERSION;
2434		return put_user(ival, (int *) arg);
2435
2436	case SNDCTL_DSP_GETCAPS:	/* _SIOR ('P',15, int) */
2437		DBGX("SNDCTL_DSP_GETCAPS\n");
2438		ival = DSP_CAP_DUPLEX | DSP_CAP_REALTIME | DSP_CAP_TRIGGER;
2439		return put_user(ival, (int *) arg);
2440
2441	case SNDCTL_DSP_GETFMTS:	/* _SIOR ('P',11, int) */
2442		DBGX("SNDCTL_DSP_GETFMTS\n");
2443		ival = (AFMT_S16_LE | AFMT_MU_LAW | AFMT_A_LAW |
2444			AFMT_U8 | AFMT_S8);
2445		return put_user(ival, (int *) arg);
2446		break;
2447
2448	case SOUND_PCM_READ_RATE:	/* _SIOR ('P', 2, int) */
2449		DBGX("SOUND_PCM_READ_RATE\n");
2450		ival = aport->sw_framerate;
2451		return put_user(ival, (int *) arg);
2452
2453	case SOUND_PCM_READ_CHANNELS:	/* _SIOR ('P', 6, int) */
2454		DBGX("SOUND_PCM_READ_CHANNELS\n");
2455		ival = aport->sw_channels;
2456		return put_user(ival, (int *) arg);
2457
2458	case SNDCTL_DSP_SPEED:		/* _SIOWR('P', 2, int) */
2459		if (get_user(ival, (int *) arg))
2460			return -EFAULT;
2461		DBGX("SNDCTL_DSP_SPEED %d\n", ival);
2462		if (ival) {
2463			if (aport->swstate != SW_INITIAL) {
2464				DBGX("SNDCTL_DSP_SPEED failed: swstate = %d\n",
2465				     aport->swstate);
2466				return -EINVAL;
2467			}
2468			if (ival < MIN_SPEED)
2469				ival = MIN_SPEED;
2470			if (ival > MAX_SPEED)
2471				ival = MAX_SPEED;
2472			if (rport)
2473				rport->sw_framerate = ival;
2474			if (wport)
2475				wport->sw_framerate = ival;
2476		} else
2477			ival = aport->sw_framerate;
2478		return put_user(ival, (int *) arg);
2479
2480	case SNDCTL_DSP_STEREO:		/* _SIOWR('P', 3, int) */
2481		if (get_user(ival, (int *) arg))
2482			return -EFAULT;
2483		DBGX("SNDCTL_DSP_STEREO %d\n", ival);
2484		if (ival != 0 && ival != 1)
2485			return -EINVAL;
2486		if (aport->swstate != SW_INITIAL)
2487			return -EINVAL;
2488		if (rport)
2489			rport->sw_channels = ival + 1;
2490		if (wport)
2491			wport->sw_channels = ival + 1;
2492		return put_user(ival, (int *) arg);
2493
2494	case SNDCTL_DSP_CHANNELS:	/* _SIOWR('P', 6, int) */
2495		if (get_user(ival, (int *) arg))
2496			return -EFAULT;
2497		DBGX("SNDCTL_DSP_CHANNELS %d\n", ival);
2498		if (ival != 1 && ival != 2)
2499			return -EINVAL;
2500		if (aport->swstate != SW_INITIAL)
2501			return -EINVAL;
2502		if (rport)
2503			rport->sw_channels = ival;
2504		if (wport)
2505			wport->sw_channels = ival;
2506		return put_user(ival, (int *) arg);
2507
2508	case SNDCTL_DSP_GETBLKSIZE:	/* _SIOWR('P', 4, int) */
2509		ival = pcm_setup(devc, rport, wport);
2510		if (ival < 0) {
2511			DBGX("SNDCTL_DSP_GETBLKSIZE failed, errno %d\n", ival);
2512			return ival;
2513		}
2514		ival = 1 << aport->sw_fragshift;
2515		DBGX("SNDCTL_DSP_GETBLKSIZE returning %d\n", ival);
2516		return put_user(ival, (int *) arg);
2517
2518	case SNDCTL_DSP_SETFRAGMENT:	/* _SIOWR('P',10, int) */
2519		if (get_user(ival, (int *) arg))
2520			return -EFAULT;
2521		DBGX("SNDCTL_DSP_SETFRAGMENT %d:%d\n",
2522		     ival >> 16, ival & 0xFFFF);
2523		if (aport->swstate != SW_INITIAL)
2524			return -EINVAL;
2525		{
2526			int sw_fragshift = ival & 0xFFFF;
2527			int sw_subdivshift = aport->sw_subdivshift;
2528			int hw_fragshift = sw_fragshift - sw_subdivshift;
2529			int sw_fragcount = (ival >> 16) & 0xFFFF;
2530			int hw_fragsize;
2531			if (hw_fragshift < MIN_FRAGSHIFT)
2532				hw_fragshift = MIN_FRAGSHIFT;
2533			if (hw_fragshift > MAX_FRAGSHIFT)
2534				hw_fragshift = MAX_FRAGSHIFT;
2535			sw_fragshift = hw_fragshift + aport->sw_subdivshift;
2536			hw_fragsize = 1 << hw_fragshift;
2537			if (sw_fragcount < MIN_FRAGCOUNT(hw_fragsize))
2538				sw_fragcount = MIN_FRAGCOUNT(hw_fragsize);
2539			if (sw_fragcount > MAX_FRAGCOUNT(hw_fragsize))
2540				sw_fragcount = MAX_FRAGCOUNT(hw_fragsize);
2541			DBGPV("sw_fragshift = %d\n", sw_fragshift);
2542			DBGPV("rport = 0x%p, wport = 0x%p\n", rport, wport);
2543			if (rport) {
2544				rport->sw_fragshift = sw_fragshift;
2545				rport->sw_fragcount = sw_fragcount;
2546			}
2547			if (wport) {
2548				wport->sw_fragshift = sw_fragshift;
2549				wport->sw_fragcount = sw_fragcount;
2550			}
2551			ival = sw_fragcount << 16 | sw_fragshift;
2552		}
2553		DBGX("SNDCTL_DSP_SETFRAGMENT returns %d:%d\n",
2554		      ival >> 16, ival & 0xFFFF);
2555		return put_user(ival, (int *) arg);
2556
2557	case SNDCTL_DSP_SUBDIVIDE:	/* _SIOWR('P', 9, int) */
2558                if (get_user(ival, (int *) arg))
2559			return -EFAULT;
2560		DBGX("SNDCTL_DSP_SUBDIVIDE %d\n", ival);
2561		if (aport->swstate != SW_INITIAL)
2562			return -EINVAL;
2563		{
2564			int subdivshift;
2565			int hw_fragshift, hw_fragsize, hw_fragcount;
2566			switch (ival) {
2567			case 1: subdivshift = 0; break;
2568			case 2: subdivshift = 1; break;
2569			case 4: subdivshift = 2; break;
2570			default: return -EINVAL;
2571			}
2572			hw_fragshift = aport->sw_fragshift - subdivshift;
2573			if (hw_fragshift < MIN_FRAGSHIFT ||
2574			    hw_fragshift > MAX_FRAGSHIFT)
2575				return -EINVAL;
2576			hw_fragsize = 1 << hw_fragshift;
2577			hw_fragcount = aport->sw_fragcount >> subdivshift;
2578			if (hw_fragcount < MIN_FRAGCOUNT(hw_fragsize) ||
2579			    hw_fragcount > MAX_FRAGCOUNT(hw_fragsize))
2580				return -EINVAL;
2581			if (rport)
2582				rport->sw_subdivshift = subdivshift;
2583			if (wport)
2584				wport->sw_subdivshift = subdivshift;
2585		}
2586		return 0;
2587
2588	case SNDCTL_DSP_SETFMT:		/* _SIOWR('P',5, int) */
2589		if (get_user(ival, (int *) arg))
2590			return -EFAULT;
2591		DBGX("SNDCTL_DSP_SETFMT %d\n", ival);
2592		if (ival != AFMT_QUERY) {
2593			if (aport->swstate != SW_INITIAL) {
2594				DBGP("SETFMT failed, swstate = %d\n",
2595				     aport->swstate);
2596				return -EINVAL;
2597			}
2598			switch (ival) {
2599			case AFMT_MU_LAW:
2600			case AFMT_A_LAW:
2601			case AFMT_U8:
2602			case AFMT_S8:
2603			case AFMT_S16_LE:
2604				if (rport)
2605					rport->sw_samplefmt = ival;
2606				if (wport)
2607					wport->sw_samplefmt = ival;
2608				break;
2609			default:
2610				return -EINVAL;
2611			}
2612		}
2613		ival = aport->sw_samplefmt;
2614		return put_user(ival, (int *) arg);
2615
2616	case SNDCTL_DSP_GETOSPACE:	/* _SIOR ('P',12, audio_buf_info) */
2617		DBGXV("SNDCTL_DSP_GETOSPACE\n");
2618		if (!wport)
2619			return -EINVAL;
2620		ival = pcm_setup(devc, rport, wport);
2621		if (ival < 0)
2622			return ival;
2623		ival = swb_inc_u(wport, 0);
2624		buf_info.fragments = ival >> wport->sw_fragshift;
2625		buf_info.fragstotal = wport->sw_fragcount;
2626		buf_info.fragsize = 1 << wport->sw_fragshift;
2627		buf_info.bytes = ival;
2628		DBGXV("SNDCTL_DSP_GETOSPACE returns { %d %d %d %d }\n",
2629		     buf_info.fragments, buf_info.fragstotal,
2630		     buf_info.fragsize, buf_info.bytes);
2631		if (copy_to_user((void *) arg, &buf_info, sizeof buf_info))
2632			return -EFAULT;
2633		return 0;
2634
2635	case SNDCTL_DSP_GETISPACE:	/* _SIOR ('P',13, audio_buf_info) */
2636		DBGX("SNDCTL_DSP_GETISPACE\n");
2637		if (!rport)
2638			return -EINVAL;
2639		ival = pcm_setup(devc, rport, wport);
2640		if (ival < 0)
2641			return ival;
2642		ival = swb_inc_u(rport, 0);
2643		buf_info.fragments = ival >> rport->sw_fragshift;
2644		buf_info.fragstotal = rport->sw_fragcount;
2645		buf_info.fragsize = 1 << rport->sw_fragshift;
2646		buf_info.bytes = ival;
2647		DBGX("SNDCTL_DSP_GETISPACE returns { %d %d %d %d }\n",
2648		     buf_info.fragments, buf_info.fragstotal,
2649		     buf_info.fragsize, buf_info.bytes);
2650		if (copy_to_user((void *) arg, &buf_info, sizeof buf_info))
2651			return -EFAULT;
2652		return 0;
2653
2654	case SNDCTL_DSP_NONBLOCK:	/* _SIO  ('P',14) */
2655		DBGX("SNDCTL_DSP_NONBLOCK\n");
2656		spin_lock(&file->f_lock);
2657		file->f_flags |= O_NONBLOCK;
2658		spin_unlock(&file->f_lock);
2659		return 0;
2660
2661	case SNDCTL_DSP_RESET:		/* _SIO  ('P', 0) */
2662		DBGX("SNDCTL_DSP_RESET\n");
2663		/*
2664		 * Nothing special needs to be done for input.  Input
2665		 * samples sit in swbuf, but it will be reinitialized
2666		 * to empty when pcm_setup() is called.
2667		 */
2668		if (wport && wport->swbuf) {
2669			wport->swstate = SW_INITIAL;
2670			pcm_output(devc, 0, 0);
2671			pcm_write_sync(devc);
2672		}
2673		pcm_shutdown(devc, rport, wport);
2674		return 0;
2675
2676	case SNDCTL_DSP_SYNC:		/* _SIO  ('P', 1) */
2677		DBGX("SNDCTL_DSP_SYNC\n");
2678		if (wport) {
2679			pcm_flush_frag(devc);
2680			pcm_write_sync(devc);
2681		}
2682		pcm_shutdown(devc, rport, wport);
2683		return 0;
2684
2685	case SNDCTL_DSP_POST:		/* _SIO  ('P', 8) */
2686		DBGX("SNDCTL_DSP_POST\n");
2687		if (!wport)
2688			return -EINVAL;
2689		pcm_flush_frag(devc);
2690		return 0;
2691
2692	case SNDCTL_DSP_GETIPTR:	/* _SIOR ('P', 17, count_info) */
2693		DBGX("SNDCTL_DSP_GETIPTR\n");
2694		if (!rport)
2695			return -EINVAL;
2696		spin_lock_irqsave(&rport->lock, flags);
2697		{
2698			ustmsc_t ustmsc;
2699			if (rport->hwstate == HW_RUNNING) {
2700				ASSERT(rport->swstate == SW_RUN);
2701				li_read_USTMSC(&rport->chan, &ustmsc);
2702				info.bytes = ustmsc.msc - rport->MSC_offset;
2703				info.bytes *= rport->frame_size;
2704			} else {
2705				info.bytes = rport->byte_count;
2706			}
2707			info.blocks = rport->frag_count;
2708			info.ptr = 0;	/* not implemented */
2709			rport->frag_count = 0;
2710		}
2711		spin_unlock_irqrestore(&rport->lock, flags);
2712		if (copy_to_user((void *) arg, &info, sizeof info))
2713			return -EFAULT;
2714		return 0;
2715
2716	case SNDCTL_DSP_GETOPTR:	/* _SIOR ('P',18, count_info) */
2717		DBGX("SNDCTL_DSP_GETOPTR\n");
2718		if (!wport)
2719			return -EINVAL;
2720		spin_lock_irqsave(&wport->lock, flags);
2721		{
2722			ustmsc_t ustmsc;
2723			if (wport->hwstate == HW_RUNNING) {
2724				ASSERT(wport->swstate == SW_RUN);
2725				li_read_USTMSC(&wport->chan, &ustmsc);
2726				info.bytes = ustmsc.msc - wport->MSC_offset;
2727				info.bytes *= wport->frame_size;
2728			} else {
2729				info.bytes = wport->byte_count;
2730			}
2731			info.blocks = wport->frag_count;
2732			info.ptr = 0;	/* not implemented */
2733			wport->frag_count = 0;
2734		}
2735		spin_unlock_irqrestore(&wport->lock, flags);
2736		if (copy_to_user((void *) arg, &info, sizeof info))
2737			return -EFAULT;
2738		return 0;
2739
2740	case SNDCTL_DSP_GETODELAY:	/* _SIOR ('P', 23, int) */
2741		DBGX("SNDCTL_DSP_GETODELAY\n");
2742		if (!wport)
2743			return -EINVAL;
2744		spin_lock_irqsave(&wport->lock, flags);
2745		{
2746			int fsize = wport->frame_size;
2747			ival = wport->swb_i_avail / fsize;
2748			if (wport->hwstate == HW_RUNNING) {
2749				int swptr, hwptr, hwframes, hwbytes, hwsize;
2750				int totalhwbytes;
2751				ustmsc_t ustmsc;
2752
2753				hwsize = wport->hwbuf_size;
2754				swptr = li_read_swptr(&wport->chan);
2755				li_read_USTMSC(&wport->chan, &ustmsc);
2756				hwframes = ustmsc.msc - wport->MSC_offset;
2757				totalhwbytes = hwframes * fsize;
2758				hwptr = totalhwbytes % hwsize;
2759				hwbytes = (swptr - hwptr + hwsize) % hwsize;
2760				ival += hwbytes / fsize;
2761			}
2762		}
2763		spin_unlock_irqrestore(&wport->lock, flags);
2764		return put_user(ival, (int *) arg);
2765
2766	case SNDCTL_DSP_PROFILE:	/* _SIOW ('P', 23, int) */
2767		DBGX("SNDCTL_DSP_PROFILE\n");
2768
2769		/*
2770		 * Thomas Sailer explains SNDCTL_DSP_PROFILE
2771		 * (private email, March 24, 1999):
2772		 *
2773		 *     This gives the sound driver a hint on what it
2774		 *     should do with partial fragments
2775		 *     (i.e. fragments partially filled with write).
2776		 *     This can direct the driver to zero them or
2777		 *     leave them alone.  But don't ask me what this
2778		 *     is good for, my driver just zeroes the last
2779		 *     fragment before the receiver stops, no idea
2780		 *     what good for any other behaviour could
2781		 *     be. Implementing it as NOP seems safe.
2782		 */
2783
2784		break;
2785
2786	case SNDCTL_DSP_GETTRIGGER:	/* _SIOR ('P',16, int) */
2787		DBGX("SNDCTL_DSP_GETTRIGGER\n");
2788		ival = 0;
2789		if (rport) {
2790			spin_lock_irqsave(&rport->lock, flags);
2791			{
2792				if (!(rport->flags & DISABLED))
2793					ival |= PCM_ENABLE_INPUT;
2794			}
2795			spin_unlock_irqrestore(&rport->lock, flags);
2796		}
2797		if (wport) {
2798			spin_lock_irqsave(&wport->lock, flags);
2799			{
2800				if (!(wport->flags & DISABLED))
2801					ival |= PCM_ENABLE_OUTPUT;
2802			}
2803			spin_unlock_irqrestore(&wport->lock, flags);
2804		}
2805		return put_user(ival, (int *) arg);
2806
2807	case SNDCTL_DSP_SETTRIGGER:	/* _SIOW ('P',16, int) */
2808		if (get_user(ival, (int *) arg))
2809			return -EFAULT;
2810		DBGX("SNDCTL_DSP_SETTRIGGER %d\n", ival);
2811
2812		/*
2813		 * If user is disabling I/O and port is not in initial
2814		 * state, fail with EINVAL.
2815		 */
2816
2817		if (((rport && !(ival & PCM_ENABLE_INPUT)) ||
2818		     (wport && !(ival & PCM_ENABLE_OUTPUT))) &&
2819		    aport->swstate != SW_INITIAL)
2820			return -EINVAL;
2821
2822		if (rport) {
2823			vwsnd_port_hwstate_t hwstate;
2824			spin_lock_irqsave(&rport->lock, flags);
2825			{
2826				hwstate = rport->hwstate;
2827				if (ival & PCM_ENABLE_INPUT)
2828					rport->flags &= ~DISABLED;
2829				else
2830					rport->flags |= DISABLED;
2831			}
2832			spin_unlock_irqrestore(&rport->lock, flags);
2833			if (hwstate != HW_RUNNING && ival & PCM_ENABLE_INPUT) {
2834
2835				if (rport->swstate == SW_INITIAL)
2836					pcm_setup(devc, rport, wport);
2837				else
2838					li_activate_dma(&rport->chan);
2839			}
2840		}
2841		if (wport) {
2842			vwsnd_port_flags_t pflags;
2843			spin_lock_irqsave(&wport->lock, flags);
2844			{
2845				pflags = wport->flags;
2846				if (ival & PCM_ENABLE_OUTPUT)
2847					wport->flags &= ~DISABLED;
2848				else
2849					wport->flags |= DISABLED;
2850			}
2851			spin_unlock_irqrestore(&wport->lock, flags);
2852			if (pflags & DISABLED && ival & PCM_ENABLE_OUTPUT) {
2853				if (wport->swstate == SW_RUN)
2854					pcm_output(devc, 0, 0);
2855			}
2856		}
2857		return 0;
2858
2859	default:
2860		DBGP("unknown ioctl 0x%x\n", cmd);
2861		return -EINVAL;
2862	}
2863	DBGP("unimplemented ioctl 0x%x\n", cmd);
2864	return -EINVAL;
2865}
2866
2867static long vwsnd_audio_ioctl(struct file *file,
2868				unsigned int cmd,
2869				unsigned long arg)
2870{
2871	vwsnd_dev_t *devc = (vwsnd_dev_t *) file->private_data;
2872	int ret;
2873
2874	lock_kernel();
2875	mutex_lock(&devc->io_mutex);
2876	ret = vwsnd_audio_do_ioctl(file, cmd, arg);
2877	mutex_unlock(&devc->io_mutex);
2878	unlock_kernel();
2879
2880	return ret;
2881}
2882
2883/* No mmap. */
2884
2885static int vwsnd_audio_mmap(struct file *file, struct vm_area_struct *vma)
2886{
2887	DBGE("(file=0x%p, vma=0x%p)\n", file, vma);
2888	return -ENODEV;
2889}
2890
2891/*
2892 * Open the audio device for read and/or write.
2893 *
2894 * Returns 0 on success, -errno on failure.
2895 */
2896
2897static int vwsnd_audio_open(struct inode *inode, struct file *file)
2898{
2899	vwsnd_dev_t *devc;
2900	int minor = iminor(inode);
2901	int sw_samplefmt;
2902
2903	DBGE("(inode=0x%p, file=0x%p)\n", inode, file);
2904
2905	lock_kernel();
2906	INC_USE_COUNT;
2907	for (devc = vwsnd_dev_list; devc; devc = devc->next_dev)
2908		if ((devc->audio_minor & ~0x0F) == (minor & ~0x0F))
2909			break;
2910
2911	if (devc == NULL) {
2912		DEC_USE_COUNT;
2913		unlock_kernel();
2914		return -ENODEV;
2915	}
2916
2917	mutex_lock(&devc->open_mutex);
2918	while (devc->open_mode & file->f_mode) {
2919		mutex_unlock(&devc->open_mutex);
2920		if (file->f_flags & O_NONBLOCK) {
2921			DEC_USE_COUNT;
2922			unlock_kernel();
2923			return -EBUSY;
2924		}
2925		interruptible_sleep_on(&devc->open_wait);
2926		if (signal_pending(current)) {
2927			DEC_USE_COUNT;
2928			unlock_kernel();
2929			return -ERESTARTSYS;
2930		}
2931		mutex_lock(&devc->open_mutex);
2932	}
2933	devc->open_mode |= file->f_mode & (FMODE_READ | FMODE_WRITE);
2934	mutex_unlock(&devc->open_mutex);
2935
2936	/* get default sample format from minor number. */
2937
2938	sw_samplefmt = 0;
2939	if ((minor & 0xF) == SND_DEV_DSP)
2940		sw_samplefmt = AFMT_U8;
2941	else if ((minor & 0xF) == SND_DEV_AUDIO)
2942		sw_samplefmt = AFMT_MU_LAW;
2943	else if ((minor & 0xF) == SND_DEV_DSP16)
2944		sw_samplefmt = AFMT_S16_LE;
2945	else
2946		ASSERT(0);
2947
2948	/* Initialize vwsnd_ports. */
2949
2950	mutex_lock(&devc->io_mutex);
2951	{
2952		if (file->f_mode & FMODE_READ) {
2953			devc->rport.swstate        = SW_INITIAL;
2954			devc->rport.flags          = 0;
2955			devc->rport.sw_channels    = 1;
2956			devc->rport.sw_samplefmt   = sw_samplefmt;
2957			devc->rport.sw_framerate   = 8000;
2958			devc->rport.sw_fragshift   = DEFAULT_FRAGSHIFT;
2959			devc->rport.sw_fragcount   = DEFAULT_FRAGCOUNT;
2960			devc->rport.sw_subdivshift = DEFAULT_SUBDIVSHIFT;
2961			devc->rport.byte_count     = 0;
2962			devc->rport.frag_count     = 0;
2963		}
2964		if (file->f_mode & FMODE_WRITE) {
2965			devc->wport.swstate        = SW_INITIAL;
2966			devc->wport.flags          = 0;
2967			devc->wport.sw_channels    = 1;
2968			devc->wport.sw_samplefmt   = sw_samplefmt;
2969			devc->wport.sw_framerate   = 8000;
2970			devc->wport.sw_fragshift   = DEFAULT_FRAGSHIFT;
2971			devc->wport.sw_fragcount   = DEFAULT_FRAGCOUNT;
2972			devc->wport.sw_subdivshift = DEFAULT_SUBDIVSHIFT;
2973			devc->wport.byte_count     = 0;
2974			devc->wport.frag_count     = 0;
2975		}
2976	}
2977	mutex_unlock(&devc->io_mutex);
2978
2979	file->private_data = devc;
2980	DBGRV();
2981	unlock_kernel();
2982	return 0;
2983}
2984
2985/*
2986 * Release (close) the audio device.
2987 */
2988
2989static int vwsnd_audio_release(struct inode *inode, struct file *file)
2990{
2991	vwsnd_dev_t *devc = (vwsnd_dev_t *) file->private_data;
2992	vwsnd_port_t *wport = NULL, *rport = NULL;
2993	int err = 0;
2994
2995	lock_kernel();
2996	mutex_lock(&devc->io_mutex);
2997	{
2998		DBGEV("(inode=0x%p, file=0x%p)\n", inode, file);
2999
3000		if (file->f_mode & FMODE_READ)
3001			rport = &devc->rport;
3002		if (file->f_mode & FMODE_WRITE) {
3003			wport = &devc->wport;
3004			pcm_flush_frag(devc);
3005			pcm_write_sync(devc);
3006		}
3007		pcm_shutdown(devc, rport, wport);
3008		if (rport)
3009			rport->swstate = SW_OFF;
3010		if (wport)
3011			wport->swstate = SW_OFF;
3012	}
3013	mutex_unlock(&devc->io_mutex);
3014
3015	mutex_lock(&devc->open_mutex);
3016	{
3017		devc->open_mode &= ~file->f_mode;
3018	}
3019	mutex_unlock(&devc->open_mutex);
3020	wake_up(&devc->open_wait);
3021	DEC_USE_COUNT;
3022	DBGR();
3023	unlock_kernel();
3024	return err;
3025}
3026
3027static const struct file_operations vwsnd_audio_fops = {
3028	.owner =	THIS_MODULE,
3029	.llseek =	no_llseek,
3030	.read =		vwsnd_audio_read,
3031	.write =	vwsnd_audio_write,
3032	.poll =		vwsnd_audio_poll,
3033	.unlocked_ioctl = vwsnd_audio_ioctl,
3034	.mmap =		vwsnd_audio_mmap,
3035	.open =		vwsnd_audio_open,
3036	.release =	vwsnd_audio_release,
3037};
3038
3039/*****************************************************************************/
3040/* mixer driver */
3041
3042/* open the mixer device. */
3043
3044static int vwsnd_mixer_open(struct inode *inode, struct file *file)
3045{
3046	vwsnd_dev_t *devc;
3047
3048	DBGEV("(inode=0x%p, file=0x%p)\n", inode, file);
3049
3050	INC_USE_COUNT;
3051	lock_kernel();
3052	for (devc = vwsnd_dev_list; devc; devc = devc->next_dev)
3053		if (devc->mixer_minor == iminor(inode))
3054			break;
3055
3056	if (devc == NULL) {
3057		DEC_USE_COUNT;
3058		unlock_kernel();
3059		return -ENODEV;
3060	}
3061	file->private_data = devc;
3062	unlock_kernel();
3063	return 0;
3064}
3065
3066/* release (close) the mixer device. */
3067
3068static int vwsnd_mixer_release(struct inode *inode, struct file *file)
3069{
3070	DBGEV("(inode=0x%p, file=0x%p)\n", inode, file);
3071	DEC_USE_COUNT;
3072	return 0;
3073}
3074
3075/* mixer_read_ioctl handles all read ioctls on the mixer device. */
3076
3077static int mixer_read_ioctl(vwsnd_dev_t *devc, unsigned int nr, void __user *arg)
3078{
3079	int val = -1;
3080
3081	DBGEV("(devc=0x%p, nr=0x%x, arg=0x%p)\n", devc, nr, arg);
3082
3083	switch (nr) {
3084	case SOUND_MIXER_CAPS:
3085		val = SOUND_CAP_EXCL_INPUT;
3086		break;
3087
3088	case SOUND_MIXER_DEVMASK:
3089		val = (SOUND_MASK_PCM | SOUND_MASK_LINE |
3090		       SOUND_MASK_MIC | SOUND_MASK_CD | SOUND_MASK_RECLEV);
3091		break;
3092
3093	case SOUND_MIXER_STEREODEVS:
3094		val = (SOUND_MASK_PCM | SOUND_MASK_LINE |
3095		       SOUND_MASK_MIC | SOUND_MASK_CD | SOUND_MASK_RECLEV);
3096		break;
3097
3098	case SOUND_MIXER_OUTMASK:
3099		val = (SOUND_MASK_PCM | SOUND_MASK_LINE |
3100		       SOUND_MASK_MIC | SOUND_MASK_CD);
3101		break;
3102
3103	case SOUND_MIXER_RECMASK:
3104		val = (SOUND_MASK_PCM | SOUND_MASK_LINE |
3105		       SOUND_MASK_MIC | SOUND_MASK_CD);
3106		break;
3107
3108	case SOUND_MIXER_PCM:
3109		val = ad1843_get_gain(&devc->lith, &ad1843_gain_PCM);
3110		break;
3111
3112	case SOUND_MIXER_LINE:
3113		val = ad1843_get_gain(&devc->lith, &ad1843_gain_LINE);
3114		break;
3115
3116	case SOUND_MIXER_MIC:
3117		val = ad1843_get_gain(&devc->lith, &ad1843_gain_MIC);
3118		break;
3119
3120	case SOUND_MIXER_CD:
3121		val = ad1843_get_gain(&devc->lith, &ad1843_gain_CD);
3122		break;
3123
3124	case SOUND_MIXER_RECLEV:
3125		val = ad1843_get_gain(&devc->lith, &ad1843_gain_RECLEV);
3126		break;
3127
3128	case SOUND_MIXER_RECSRC:
3129		val = ad1843_get_recsrc(&devc->lith);
3130		break;
3131
3132	case SOUND_MIXER_OUTSRC:
3133		val = ad1843_get_outsrc(&devc->lith);
3134		break;
3135
3136	default:
3137		return -EINVAL;
3138	}
3139	return put_user(val, (int __user *) arg);
3140}
3141
3142/* mixer_write_ioctl handles all write ioctls on the mixer device. */
3143
3144static int mixer_write_ioctl(vwsnd_dev_t *devc, unsigned int nr, void __user *arg)
3145{
3146	int val;
3147	int err;
3148
3149	DBGEV("(devc=0x%p, nr=0x%x, arg=0x%p)\n", devc, nr, arg);
3150
3151	err = get_user(val, (int __user *) arg);
3152	if (err)
3153		return -EFAULT;
3154	switch (nr) {
3155	case SOUND_MIXER_PCM:
3156		val = ad1843_set_gain(&devc->lith, &ad1843_gain_PCM, val);
3157		break;
3158
3159	case SOUND_MIXER_LINE:
3160		val = ad1843_set_gain(&devc->lith, &ad1843_gain_LINE, val);
3161		break;
3162
3163	case SOUND_MIXER_MIC:
3164		val = ad1843_set_gain(&devc->lith, &ad1843_gain_MIC, val);
3165		break;
3166
3167	case SOUND_MIXER_CD:
3168		val = ad1843_set_gain(&devc->lith, &ad1843_gain_CD, val);
3169		break;
3170
3171	case SOUND_MIXER_RECLEV:
3172		val = ad1843_set_gain(&devc->lith, &ad1843_gain_RECLEV, val);
3173		break;
3174
3175	case SOUND_MIXER_RECSRC:
3176		if (devc->rport.swbuf || devc->wport.swbuf)
3177			return -EBUSY;	/* can't change recsrc while running */
3178		val = ad1843_set_recsrc(&devc->lith, val);
3179		break;
3180
3181	case SOUND_MIXER_OUTSRC:
3182		val = ad1843_set_outsrc(&devc->lith, val);
3183		break;
3184
3185	default:
3186		return -EINVAL;
3187	}
3188	if (val < 0)
3189		return val;
3190	return put_user(val, (int __user *) arg);
3191}
3192
3193/* This is the ioctl entry to the mixer driver. */
3194
3195static long vwsnd_mixer_ioctl(struct file *file,
3196			      unsigned int cmd,
3197			      unsigned long arg)
3198{
3199	vwsnd_dev_t *devc = (vwsnd_dev_t *) file->private_data;
3200	const unsigned int nrmask = _IOC_NRMASK << _IOC_NRSHIFT;
3201	const unsigned int nr = (cmd & nrmask) >> _IOC_NRSHIFT;
3202	int retval;
3203
3204	DBGEV("(devc=0x%p, cmd=0x%x, arg=0x%lx)\n", devc, cmd, arg);
3205
3206	lock_kernel();
3207	mutex_lock(&devc->mix_mutex);
3208	{
3209		if ((cmd & ~nrmask) == MIXER_READ(0))
3210			retval = mixer_read_ioctl(devc, nr, (void __user *) arg);
3211		else if ((cmd & ~nrmask) == MIXER_WRITE(0))
3212			retval = mixer_write_ioctl(devc, nr, (void __user *) arg);
3213		else
3214			retval = -EINVAL;
3215	}
3216	mutex_unlock(&devc->mix_mutex);
3217	unlock_kernel();
3218	return retval;
3219}
3220
3221static const struct file_operations vwsnd_mixer_fops = {
3222	.owner =	THIS_MODULE,
3223	.llseek =	no_llseek,
3224	.unlocked_ioctl = vwsnd_mixer_ioctl,
3225	.open =		vwsnd_mixer_open,
3226	.release =	vwsnd_mixer_release,
3227};
3228
3229/*****************************************************************************/
3230/* probe/attach/unload */
3231
3232/* driver probe routine.  Return nonzero if hardware is found. */
3233
3234static int __init probe_vwsnd(struct address_info *hw_config)
3235{
3236	lithium_t lith;
3237	int w;
3238	unsigned long later;
3239
3240	DBGEV("(hw_config=0x%p)\n", hw_config);
3241
3242
3243	if (li_create(&lith, hw_config->io_base) != 0) {
3244		printk(KERN_WARNING "probe_vwsnd: can't map lithium\n");
3245		return 0;
3246	}
3247	later = jiffies + 2;
3248	li_writel(&lith, LI_HOST_CONTROLLER, LI_HC_LINK_ENABLE);
3249	do {
3250		w = li_readl(&lith, LI_HOST_CONTROLLER);
3251	} while (w == LI_HC_LINK_ENABLE && time_before(jiffies, later));
3252
3253	li_destroy(&lith);
3254
3255	DBGPV("HC = 0x%04x\n", w);
3256
3257	if ((w == LI_HC_LINK_ENABLE) || (w & LI_HC_LINK_CODEC)) {
3258
3259		/* This may indicate a beta machine with no audio,
3260		 * or a future machine with different audio.
3261		 * On beta-release 320 w/ no audio, HC == 0x4000 */
3262
3263		printk(KERN_WARNING "probe_vwsnd: audio codec not found\n");
3264		return 0;
3265	}
3266
3267	if (w & LI_HC_LINK_FAILURE) {
3268		printk(KERN_WARNING "probe_vwsnd: can't init audio codec\n");
3269		return 0;
3270	}
3271
3272	printk(KERN_INFO "vwsnd: lithium audio at mmio %#x irq %d\n",
3273		hw_config->io_base, hw_config->irq);
3274
3275	return 1;
3276}
3277
3278/*
3279 * driver attach routine.  Initialize driver data structures and
3280 * initialize hardware.  A new vwsnd_dev_t is allocated and put
3281 * onto the global list, vwsnd_dev_list.
3282 *
3283 * Return +minor_dev on success, -errno on failure.
3284 */
3285
3286static int __init attach_vwsnd(struct address_info *hw_config)
3287{
3288	vwsnd_dev_t *devc = NULL;
3289	int err = -ENOMEM;
3290
3291	DBGEV("(hw_config=0x%p)\n", hw_config);
3292
3293	devc = kmalloc(sizeof (vwsnd_dev_t), GFP_KERNEL);
3294	if (devc == NULL)
3295		goto fail0;
3296
3297	err = li_create(&devc->lith, hw_config->io_base);
3298	if (err)
3299		goto fail1;
3300
3301	init_waitqueue_head(&devc->open_wait);
3302
3303	devc->rport.hwbuf_size = HWBUF_SIZE;
3304	devc->rport.hwbuf_vaddr = __get_free_pages(GFP_KERNEL, HWBUF_ORDER);
3305	if (!devc->rport.hwbuf_vaddr)
3306		goto fail2;
3307	devc->rport.hwbuf = (void *) devc->rport.hwbuf_vaddr;
3308	devc->rport.hwbuf_paddr = virt_to_phys(devc->rport.hwbuf);
3309
3310	/*
3311	 * Quote from the NT driver:
3312	 *
3313	 * // WARNING!!! HACK to setup output dma!!!
3314	 * // This is required because even on output there is some data
3315	 * // trickling into the input DMA channel.  This is a bug in the
3316	 * // Lithium microcode.
3317	 * // --sde
3318	 *
3319	 * We set the input side's DMA base address here.  It will remain
3320	 * valid until the driver is unloaded.
3321	 */
3322
3323	li_writel(&devc->lith, LI_COMM1_BASE,
3324		  devc->rport.hwbuf_paddr >> 8 | 1 << (37 - 8));
3325
3326	devc->wport.hwbuf_size = HWBUF_SIZE;
3327	devc->wport.hwbuf_vaddr = __get_free_pages(GFP_KERNEL, HWBUF_ORDER);
3328	if (!devc->wport.hwbuf_vaddr)
3329		goto fail3;
3330	devc->wport.hwbuf = (void *) devc->wport.hwbuf_vaddr;
3331	devc->wport.hwbuf_paddr = virt_to_phys(devc->wport.hwbuf);
3332	DBGP("wport hwbuf = 0x%p\n", devc->wport.hwbuf);
3333
3334	DBGDO(shut_up++);
3335	err = ad1843_init(&devc->lith);
3336	DBGDO(shut_up--);
3337	if (err)
3338		goto fail4;
3339
3340	/* install interrupt handler */
3341
3342	err = request_irq(hw_config->irq, vwsnd_audio_intr, 0, "vwsnd", devc);
3343	if (err)
3344		goto fail5;
3345
3346	/* register this device's drivers. */
3347
3348	devc->audio_minor = register_sound_dsp(&vwsnd_audio_fops, -1);
3349	if ((err = devc->audio_minor) < 0) {
3350		DBGDO(printk(KERN_WARNING
3351			     "attach_vwsnd: register_sound_dsp error %d\n",
3352			     err));
3353		goto fail6;
3354	}
3355	devc->mixer_minor = register_sound_mixer(&vwsnd_mixer_fops,
3356						 devc->audio_minor >> 4);
3357	if ((err = devc->mixer_minor) < 0) {
3358		DBGDO(printk(KERN_WARNING
3359			     "attach_vwsnd: register_sound_mixer error %d\n",
3360			     err));
3361		goto fail7;
3362	}
3363
3364	/* Squirrel away device indices for unload routine. */
3365
3366	hw_config->slots[0] = devc->audio_minor;
3367
3368	/* Initialize as much of *devc as possible */
3369
3370	mutex_init(&devc->open_mutex);
3371	mutex_init(&devc->io_mutex);
3372	mutex_init(&devc->mix_mutex);
3373	devc->open_mode = 0;
3374	spin_lock_init(&devc->rport.lock);
3375	init_waitqueue_head(&devc->rport.queue);
3376	devc->rport.swstate = SW_OFF;
3377	devc->rport.hwstate = HW_STOPPED;
3378	devc->rport.flags = 0;
3379	devc->rport.swbuf = NULL;
3380	spin_lock_init(&devc->wport.lock);
3381	init_waitqueue_head(&devc->wport.queue);
3382	devc->wport.swstate = SW_OFF;
3383	devc->wport.hwstate = HW_STOPPED;
3384	devc->wport.flags = 0;
3385	devc->wport.swbuf = NULL;
3386
3387	/* Success.  Link us onto the local device list. */
3388
3389	devc->next_dev = vwsnd_dev_list;
3390	vwsnd_dev_list = devc;
3391	return devc->audio_minor;
3392
3393	/* So many ways to fail.  Undo what we did. */
3394
3395 fail7:
3396	unregister_sound_dsp(devc->audio_minor);
3397 fail6:
3398	free_irq(hw_config->irq, devc);
3399 fail5:
3400 fail4:
3401	free_pages(devc->wport.hwbuf_vaddr, HWBUF_ORDER);
3402 fail3:
3403	free_pages(devc->rport.hwbuf_vaddr, HWBUF_ORDER);
3404 fail2:
3405	li_destroy(&devc->lith);
3406 fail1:
3407	kfree(devc);
3408 fail0:
3409	return err;
3410}
3411
3412static int __exit unload_vwsnd(struct address_info *hw_config)
3413{
3414	vwsnd_dev_t *devc, **devcp;
3415
3416	DBGE("()\n");
3417
3418	devcp = &vwsnd_dev_list;
3419	while ((devc = *devcp)) {
3420		if (devc->audio_minor == hw_config->slots[0]) {
3421			*devcp = devc->next_dev;
3422			break;
3423		}
3424		devcp = &devc->next_dev;
3425	}
3426
3427	if (!devc)
3428		return -ENODEV;
3429
3430	unregister_sound_mixer(devc->mixer_minor);
3431	unregister_sound_dsp(devc->audio_minor);
3432	free_irq(hw_config->irq, devc);
3433	free_pages(devc->wport.hwbuf_vaddr, HWBUF_ORDER);
3434	free_pages(devc->rport.hwbuf_vaddr, HWBUF_ORDER);
3435	li_destroy(&devc->lith);
3436	kfree(devc);
3437
3438	return 0;
3439}
3440
3441/*****************************************************************************/
3442/* initialization and loadable kernel module interface */
3443
3444static struct address_info the_hw_config = {
3445	0xFF001000,			/* lithium phys addr  */
3446	CO_IRQ(CO_APIC_LI_AUDIO)	/* irq */
3447};
3448
3449MODULE_DESCRIPTION("SGI Visual Workstation sound module");
3450MODULE_AUTHOR("Bob Miller <kbob@sgi.com>");
3451MODULE_LICENSE("GPL");
3452
3453static int __init init_vwsnd(void)
3454{
3455	int err;
3456
3457	DBGXV("\n");
3458	DBGXV("sound::vwsnd::init_module()\n");
3459
3460	if (!probe_vwsnd(&the_hw_config))
3461		return -ENODEV;
3462
3463	err = attach_vwsnd(&the_hw_config);
3464	if (err < 0)
3465		return err;
3466	return 0;
3467}
3468
3469static void __exit cleanup_vwsnd(void)
3470{
3471	DBGX("sound::vwsnd::cleanup_module()\n");
3472
3473	unload_vwsnd(&the_hw_config);
3474}
3475
3476module_init(init_vwsnd);
3477module_exit(cleanup_vwsnd);
3478