[ALSA] dbri sparc: fixes TS leak
[powerpc.git] / sound / sparc / dbri.c
1 /*
2  * Driver for DBRI sound chip found on Sparcs.
3  * Copyright (C) 2004, 2005 Martin Habets (mhabets@users.sourceforge.net)
4  *
5  * Converted to ring buffered version by Krzysztof Helt (krzysztof.h1@wp.pl)
6  *
7  * Based entirely upon drivers/sbus/audio/dbri.c which is:
8  * Copyright (C) 1997 Rudolf Koenig (rfkoenig@immd4.informatik.uni-erlangen.de)
9  * Copyright (C) 1998, 1999 Brent Baccala (baccala@freesoft.org)
10  *
11  * This is the lowlevel driver for the DBRI & MMCODEC duo used for ISDN & AUDIO
12  * on Sun SPARCstation 10, 20, LX and Voyager models.
13  *
14  * - DBRI: AT&T T5900FX Dual Basic Rates ISDN Interface. It is a 32 channel
15  *   data time multiplexer with ISDN support (aka T7259)
16  *   Interfaces: SBus,ISDN NT & TE, CHI, 4 bits parallel.
17  *   CHI: (spelled ki) Concentration Highway Interface (AT&T or Intel bus ?).
18  *   Documentation:
19  *   - "STP 4000SBus Dual Basic Rate ISDN (DBRI) Tranceiver" from
20  *     Sparc Technology Business (courtesy of Sun Support)
21  *   - Data sheet of the T7903, a newer but very similar ISA bus equivalent
22  *     available from the Lucent (formarly AT&T microelectronics) home
23  *     page.
24  *   - http://www.freesoft.org/Linux/DBRI/
25  * - MMCODEC: Crystal Semiconductor CS4215 16 bit Multimedia Audio Codec
26  *   Interfaces: CHI, Audio In & Out, 2 bits parallel
27  *   Documentation: from the Crystal Semiconductor home page.
28  *
29  * The DBRI is a 32 pipe machine, each pipe can transfer some bits between
30  * memory and a serial device (long pipes, nr 0-15) or between two serial
31  * devices (short pipes, nr 16-31), or simply send a fixed data to a serial
32  * device (short pipes).
33  * A timeslot defines the bit-offset and nr of bits read from a serial device.
34  * The timeslots are linked to 6 circular lists, one for each direction for
35  * each serial device (NT,TE,CHI). A timeslot is associated to 1 or 2 pipes
36  * (the second one is a monitor/tee pipe, valid only for serial input).
37  *
38  * The mmcodec is connected via the CHI bus and needs the data & some
39  * parameters (volume, output selection) timemultiplexed in 8 byte
40  * chunks. It also has a control mode, which serves for audio format setting.
41  *
42  * Looking at the CS4215 data sheet it is easy to set up 2 or 4 codecs on
43  * the same CHI bus, so I thought perhaps it is possible to use the onboard
44  * & the speakerbox codec simultanously, giving 2 (not very independent :-)
45  * audio devices. But the SUN HW group decided against it, at least on my
46  * LX the speakerbox connector has at least 1 pin missing and 1 wrongly
47  * connected.
48  *
49  * I've tried to stick to the following function naming conventions:
50  * snd_*        ALSA stuff
51  * cs4215_*     CS4215 codec specific stuff
52  * dbri_*       DBRI high-level stuff
53  * other        DBRI low-level stuff
54  */
55
56 #include <sound/driver.h>
57 #include <linux/interrupt.h>
58 #include <linux/delay.h>
59
60 #include <sound/core.h>
61 #include <sound/pcm.h>
62 #include <sound/pcm_params.h>
63 #include <sound/info.h>
64 #include <sound/control.h>
65 #include <sound/initval.h>
66
67 #include <asm/irq.h>
68 #include <asm/io.h>
69 #include <asm/sbus.h>
70 #include <asm/atomic.h>
71
72 MODULE_AUTHOR("Rudolf Koenig, Brent Baccala and Martin Habets");
73 MODULE_DESCRIPTION("Sun DBRI");
74 MODULE_LICENSE("GPL");
75 MODULE_SUPPORTED_DEVICE("{{Sun,DBRI}}");
76
77 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 0-MAX */
78 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
79 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;      /* Enable this card */
80
81 module_param_array(index, int, NULL, 0444);
82 MODULE_PARM_DESC(index, "Index value for Sun DBRI soundcard.");
83 module_param_array(id, charp, NULL, 0444);
84 MODULE_PARM_DESC(id, "ID string for Sun DBRI soundcard.");
85 module_param_array(enable, bool, NULL, 0444);
86 MODULE_PARM_DESC(enable, "Enable Sun DBRI soundcard.");
87
88 #undef DBRI_DEBUG
89
90 #define D_INT   (1<<0)
91 #define D_GEN   (1<<1)
92 #define D_CMD   (1<<2)
93 #define D_MM    (1<<3)
94 #define D_USR   (1<<4)
95 #define D_DESC  (1<<5)
96
97 static int dbri_debug;
98 module_param(dbri_debug, int, 0644);
99 MODULE_PARM_DESC(dbri_debug, "Debug value for Sun DBRI soundcard.");
100
101 #ifdef DBRI_DEBUG
102 static char *cmds[] = {
103         "WAIT", "PAUSE", "JUMP", "IIQ", "REX", "SDP", "CDP", "DTS",
104         "SSP", "CHI", "NT", "TE", "CDEC", "TEST", "CDM", "RESRV"
105 };
106
107 #define dprintk(a, x...) if(dbri_debug & a) printk(KERN_DEBUG x)
108
109 #else
110 #define dprintk(a, x...) do { } while (0)
111
112 #endif                          /* DBRI_DEBUG */
113
114 #define DBRI_CMD(cmd, intr, value) ((cmd << 28) |       \
115                                     (intr << 27) |      \
116                                     value)
117
118 /***************************************************************************
119         CS4215 specific definitions and structures
120 ****************************************************************************/
121
122 struct cs4215 {
123         __u8 data[4];           /* Data mode: Time slots 5-8 */
124         __u8 ctrl[4];           /* Ctrl mode: Time slots 1-4 */
125         __u8 onboard;
126         __u8 offset;            /* Bit offset from frame sync to time slot 1 */
127         volatile __u32 status;
128         volatile __u32 version;
129         __u8 precision;         /* In bits, either 8 or 16 */
130         __u8 channels;          /* 1 or 2 */
131 };
132
133 /*
134  * Control mode first 
135  */
136
137 /* Time Slot 1, Status register */
138 #define CS4215_CLB      (1<<2)  /* Control Latch Bit */
139 #define CS4215_OLB      (1<<3)  /* 1: line: 2.0V, speaker 4V */
140                                 /* 0: line: 2.8V, speaker 8V */
141 #define CS4215_MLB      (1<<4)  /* 1: Microphone: 20dB gain disabled */
142 #define CS4215_RSRVD_1  (1<<5)
143
144 /* Time Slot 2, Data Format Register */
145 #define CS4215_DFR_LINEAR16     0
146 #define CS4215_DFR_ULAW         1
147 #define CS4215_DFR_ALAW         2
148 #define CS4215_DFR_LINEAR8      3
149 #define CS4215_DFR_STEREO       (1<<2)
150 static struct {
151         unsigned short freq;
152         unsigned char xtal;
153         unsigned char csval;
154 } CS4215_FREQ[] = {
155         {  8000, (1 << 4), (0 << 3) },
156         { 16000, (1 << 4), (1 << 3) },
157         { 27429, (1 << 4), (2 << 3) },  /* Actually 24428.57 */
158         { 32000, (1 << 4), (3 << 3) },
159      /* {    NA, (1 << 4), (4 << 3) }, */
160      /* {    NA, (1 << 4), (5 << 3) }, */
161         { 48000, (1 << 4), (6 << 3) },
162         {  9600, (1 << 4), (7 << 3) },
163         {  5512, (2 << 4), (0 << 3) },  /* Actually 5512.5 */
164         { 11025, (2 << 4), (1 << 3) },
165         { 18900, (2 << 4), (2 << 3) },
166         { 22050, (2 << 4), (3 << 3) },
167         { 37800, (2 << 4), (4 << 3) },
168         { 44100, (2 << 4), (5 << 3) },
169         { 33075, (2 << 4), (6 << 3) },
170         {  6615, (2 << 4), (7 << 3) },
171         { 0, 0, 0}
172 };
173
174 #define CS4215_HPF      (1<<7)  /* High Pass Filter, 1: Enabled */
175
176 #define CS4215_12_MASK  0xfcbf  /* Mask off reserved bits in slot 1 & 2 */
177
178 /* Time Slot 3, Serial Port Control register */
179 #define CS4215_XEN      (1<<0)  /* 0: Enable serial output */
180 #define CS4215_XCLK     (1<<1)  /* 1: Master mode: Generate SCLK */
181 #define CS4215_BSEL_64  (0<<2)  /* Bitrate: 64 bits per frame */
182 #define CS4215_BSEL_128 (1<<2)
183 #define CS4215_BSEL_256 (2<<2)
184 #define CS4215_MCK_MAST (0<<4)  /* Master clock */
185 #define CS4215_MCK_XTL1 (1<<4)  /* 24.576 MHz clock source */
186 #define CS4215_MCK_XTL2 (2<<4)  /* 16.9344 MHz clock source */
187 #define CS4215_MCK_CLK1 (3<<4)  /* Clockin, 256 x Fs */
188 #define CS4215_MCK_CLK2 (4<<4)  /* Clockin, see DFR */
189
190 /* Time Slot 4, Test Register */
191 #define CS4215_DAD      (1<<0)  /* 0:Digital-Dig loop, 1:Dig-Analog-Dig loop */
192 #define CS4215_ENL      (1<<1)  /* Enable Loopback Testing */
193
194 /* Time Slot 5, Parallel Port Register */
195 /* Read only here and the same as the in data mode */
196
197 /* Time Slot 6, Reserved  */
198
199 /* Time Slot 7, Version Register  */
200 #define CS4215_VERSION_MASK 0xf /* Known versions 0/C, 1/D, 2/E */
201
202 /* Time Slot 8, Reserved  */
203
204 /*
205  * Data mode
206  */
207 /* Time Slot 1-2: Left Channel Data, 2-3: Right Channel Data  */
208
209 /* Time Slot 5, Output Setting  */
210 #define CS4215_LO(v)    v       /* Left Output Attenuation 0x3f: -94.5 dB */
211 #define CS4215_LE       (1<<6)  /* Line Out Enable */
212 #define CS4215_HE       (1<<7)  /* Headphone Enable */
213
214 /* Time Slot 6, Output Setting  */
215 #define CS4215_RO(v)    v       /* Right Output Attenuation 0x3f: -94.5 dB */
216 #define CS4215_SE       (1<<6)  /* Speaker Enable */
217 #define CS4215_ADI      (1<<7)  /* A/D Data Invalid: Busy in calibration */
218
219 /* Time Slot 7, Input Setting */
220 #define CS4215_LG(v)    v       /* Left Gain Setting 0xf: 22.5 dB */
221 #define CS4215_IS       (1<<4)  /* Input Select: 1=Microphone, 0=Line */
222 #define CS4215_OVR      (1<<5)  /* 1: Overrange condition occurred */
223 #define CS4215_PIO0     (1<<6)  /* Parallel I/O 0 */
224 #define CS4215_PIO1     (1<<7)
225
226 /* Time Slot 8, Input Setting */
227 #define CS4215_RG(v)    v       /* Right Gain Setting 0xf: 22.5 dB */
228 #define CS4215_MA(v)    (v<<4)  /* Monitor Path Attenuation 0xf: mute */
229
230 /***************************************************************************
231                 DBRI specific definitions and structures
232 ****************************************************************************/
233
234 /* DBRI main registers */
235 #define REG0    0x00UL          /* Status and Control */
236 #define REG1    0x04UL          /* Mode and Interrupt */
237 #define REG2    0x08UL          /* Parallel IO */
238 #define REG3    0x0cUL          /* Test */
239 #define REG8    0x20UL          /* Command Queue Pointer */
240 #define REG9    0x24UL          /* Interrupt Queue Pointer */
241
242 #define DBRI_NO_CMDS    64
243 #define DBRI_INT_BLK    64
244 #define DBRI_NO_DESCS   64
245 #define DBRI_NO_PIPES   32
246 #define DBRI_MAX_PIPE   (DBRI_NO_PIPES - 1)
247
248 #define DBRI_REC        0
249 #define DBRI_PLAY       1
250 #define DBRI_NO_STREAMS 2
251
252 /* One transmit/receive descriptor */
253 /* When ba != 0 descriptor is used */
254 struct dbri_mem {
255         volatile __u32 word1;
256         __u32 ba;       /* Transmit/Receive Buffer Address */
257         __u32 nda;      /* Next Descriptor Address */
258         volatile __u32 word4;
259 };
260
261 /* This structure is in a DMA region where it can accessed by both
262  * the CPU and the DBRI
263  */
264 struct dbri_dma {
265         s32 cmd[DBRI_NO_CMDS];                  /* Place for commands */
266         volatile s32 intr[DBRI_INT_BLK];        /* Interrupt field  */
267         struct dbri_mem desc[DBRI_NO_DESCS];    /* Xmit/receive descriptors */
268 };
269
270 #define dbri_dma_off(member, elem)      \
271         ((u32)(unsigned long)           \
272          (&(((struct dbri_dma *)0)->member[elem])))
273
274 enum in_or_out { PIPEinput, PIPEoutput };
275
276 struct dbri_pipe {
277         u32 sdp;                /* SDP command word */
278         int nextpipe;           /* Next pipe in linked list */
279         int length;             /* Length of timeslot (bits) */
280         int first_desc;         /* Index of first descriptor */
281         int desc;               /* Index of active descriptor */
282         volatile __u32 *recv_fixed_ptr; /* Ptr to receive fixed data */
283 };
284
285 /* Per stream (playback or record) information */
286 struct dbri_streaminfo {
287         struct snd_pcm_substream *substream;
288         u32 dvma_buffer;        /* Device view of Alsa DMA buffer */
289         int size;               /* Size of DMA buffer             */
290         size_t offset;          /* offset in user buffer          */
291         int pipe;               /* Data pipe used                 */
292         int left_gain;          /* mixer elements                 */
293         int right_gain;
294 };
295
296 /* This structure holds the information for both chips (DBRI & CS4215) */
297 struct snd_dbri {
298         struct snd_card *card;  /* ALSA card */
299
300         int regs_size, irq;     /* Needed for unload */
301         struct sbus_dev *sdev;  /* SBUS device info */
302         spinlock_t lock;
303
304         struct dbri_dma *dma;   /* Pointer to our DMA block */
305         u32 dma_dvma;           /* DBRI visible DMA address */
306
307         void __iomem *regs;     /* dbri HW regs */
308         int dbri_irqp;          /* intr queue pointer */
309
310         struct dbri_pipe pipes[DBRI_NO_PIPES];  /* DBRI's 32 data pipes */
311         int next_desc[DBRI_NO_DESCS];           /* Index of next desc, or -1 */
312         spinlock_t cmdlock;     /* Protects cmd queue accesses */
313         s32 *cmdptr;            /* Pointer to the last queued cmd */
314
315         int chi_bpf;
316
317         struct cs4215 mm;       /* mmcodec special info */
318                                 /* per stream (playback/record) info */
319         struct dbri_streaminfo stream_info[DBRI_NO_STREAMS];
320
321         struct snd_dbri *next;
322 };
323
324 #define DBRI_MAX_VOLUME         63      /* Output volume */
325 #define DBRI_MAX_GAIN           15      /* Input gain */
326
327 /* DBRI Reg0 - Status Control Register - defines. (Page 17) */
328 #define D_P             (1<<15) /* Program command & queue pointer valid */
329 #define D_G             (1<<14) /* Allow 4-Word SBus Burst */
330 #define D_S             (1<<13) /* Allow 16-Word SBus Burst */
331 #define D_E             (1<<12) /* Allow 8-Word SBus Burst */
332 #define D_X             (1<<7)  /* Sanity Timer Disable */
333 #define D_T             (1<<6)  /* Permit activation of the TE interface */
334 #define D_N             (1<<5)  /* Permit activation of the NT interface */
335 #define D_C             (1<<4)  /* Permit activation of the CHI interface */
336 #define D_F             (1<<3)  /* Force Sanity Timer Time-Out */
337 #define D_D             (1<<2)  /* Disable Master Mode */
338 #define D_H             (1<<1)  /* Halt for Analysis */
339 #define D_R             (1<<0)  /* Soft Reset */
340
341 /* DBRI Reg1 - Mode and Interrupt Register - defines. (Page 18) */
342 #define D_LITTLE_END    (1<<8)  /* Byte Order */
343 #define D_BIG_END       (0<<8)  /* Byte Order */
344 #define D_MRR           (1<<4)  /* Multiple Error Ack on SBus (readonly) */
345 #define D_MLE           (1<<3)  /* Multiple Late Error on SBus (readonly) */
346 #define D_LBG           (1<<2)  /* Lost Bus Grant on SBus (readonly) */
347 #define D_MBE           (1<<1)  /* Burst Error on SBus (readonly) */
348 #define D_IR            (1<<0)  /* Interrupt Indicator (readonly) */
349
350 /* DBRI Reg2 - Parallel IO Register - defines. (Page 18) */
351 #define D_ENPIO3        (1<<7)  /* Enable Pin 3 */
352 #define D_ENPIO2        (1<<6)  /* Enable Pin 2 */
353 #define D_ENPIO1        (1<<5)  /* Enable Pin 1 */
354 #define D_ENPIO0        (1<<4)  /* Enable Pin 0 */
355 #define D_ENPIO         (0xf0)  /* Enable all the pins */
356 #define D_PIO3          (1<<3)  /* Pin 3: 1: Data mode, 0: Ctrl mode */
357 #define D_PIO2          (1<<2)  /* Pin 2: 1: Onboard PDN */
358 #define D_PIO1          (1<<1)  /* Pin 1: 0: Reset */
359 #define D_PIO0          (1<<0)  /* Pin 0: 1: Speakerbox PDN */
360
361 /* DBRI Commands (Page 20) */
362 #define D_WAIT          0x0     /* Stop execution */
363 #define D_PAUSE         0x1     /* Flush long pipes */
364 #define D_JUMP          0x2     /* New command queue */
365 #define D_IIQ           0x3     /* Initialize Interrupt Queue */
366 #define D_REX           0x4     /* Report command execution via interrupt */
367 #define D_SDP           0x5     /* Setup Data Pipe */
368 #define D_CDP           0x6     /* Continue Data Pipe (reread NULL Pointer) */
369 #define D_DTS           0x7     /* Define Time Slot */
370 #define D_SSP           0x8     /* Set short Data Pipe */
371 #define D_CHI           0x9     /* Set CHI Global Mode */
372 #define D_NT            0xa     /* NT Command */
373 #define D_TE            0xb     /* TE Command */
374 #define D_CDEC          0xc     /* Codec setup */
375 #define D_TEST          0xd     /* No comment */
376 #define D_CDM           0xe     /* CHI Data mode command */
377
378 /* Special bits for some commands */
379 #define D_PIPE(v)      ((v)<<0) /* Pipe Nr: 0-15 long, 16-21 short */
380
381 /* Setup Data Pipe */
382 /* IRM */
383 #define D_SDP_2SAME     (1<<18) /* Report 2nd time in a row value rcvd */
384 #define D_SDP_CHANGE    (2<<18) /* Report any changes */
385 #define D_SDP_EVERY     (3<<18) /* Report any changes */
386 #define D_SDP_EOL       (1<<17) /* EOL interrupt enable */
387 #define D_SDP_IDLE      (1<<16) /* HDLC idle interrupt enable */
388
389 /* Pipe data MODE */
390 #define D_SDP_MEM       (0<<13) /* To/from memory */
391 #define D_SDP_HDLC      (2<<13)
392 #define D_SDP_HDLC_D    (3<<13) /* D Channel (prio control) */
393 #define D_SDP_SER       (4<<13) /* Serial to serial */
394 #define D_SDP_FIXED     (6<<13) /* Short only */
395 #define D_SDP_MODE(v)   ((v)&(7<<13))
396
397 #define D_SDP_TO_SER    (1<<12) /* Direction */
398 #define D_SDP_FROM_SER  (0<<12) /* Direction */
399 #define D_SDP_MSB       (1<<11) /* Bit order within Byte */
400 #define D_SDP_LSB       (0<<11) /* Bit order within Byte */
401 #define D_SDP_P         (1<<10) /* Pointer Valid */
402 #define D_SDP_A         (1<<8)  /* Abort */
403 #define D_SDP_C         (1<<7)  /* Clear */
404
405 /* Define Time Slot */
406 #define D_DTS_VI        (1<<17) /* Valid Input Time-Slot Descriptor */
407 #define D_DTS_VO        (1<<16) /* Valid Output Time-Slot Descriptor */
408 #define D_DTS_INS       (1<<15) /* Insert Time Slot */
409 #define D_DTS_DEL       (0<<15) /* Delete Time Slot */
410 #define D_DTS_PRVIN(v) ((v)<<10)        /* Previous In Pipe */
411 #define D_DTS_PRVOUT(v)        ((v)<<5) /* Previous Out Pipe */
412
413 /* Time Slot defines */
414 #define D_TS_LEN(v)     ((v)<<24)       /* Number of bits in this time slot */
415 #define D_TS_CYCLE(v)   ((v)<<14)       /* Bit Count at start of TS */
416 #define D_TS_DI         (1<<13) /* Data Invert */
417 #define D_TS_1CHANNEL   (0<<10) /* Single Channel / Normal mode */
418 #define D_TS_MONITOR    (2<<10) /* Monitor pipe */
419 #define D_TS_NONCONTIG  (3<<10) /* Non contiguous mode */
420 #define D_TS_ANCHOR     (7<<10) /* Starting short pipes */
421 #define D_TS_MON(v)    ((v)<<5) /* Monitor Pipe */
422 #define D_TS_NEXT(v)   ((v)<<0) /* Pipe Nr: 0-15 long, 16-21 short */
423
424 /* Concentration Highway Interface Modes */
425 #define D_CHI_CHICM(v)  ((v)<<16)       /* Clock mode */
426 #define D_CHI_IR        (1<<15) /* Immediate Interrupt Report */
427 #define D_CHI_EN        (1<<14) /* CHIL Interrupt enabled */
428 #define D_CHI_OD        (1<<13) /* Open Drain Enable */
429 #define D_CHI_FE        (1<<12) /* Sample CHIFS on Rising Frame Edge */
430 #define D_CHI_FD        (1<<11) /* Frame Drive */
431 #define D_CHI_BPF(v)    ((v)<<0)        /* Bits per Frame */
432
433 /* NT: These are here for completeness */
434 #define D_NT_FBIT       (1<<17) /* Frame Bit */
435 #define D_NT_NBF        (1<<16) /* Number of bad frames to loose framing */
436 #define D_NT_IRM_IMM    (1<<15) /* Interrupt Report & Mask: Immediate */
437 #define D_NT_IRM_EN     (1<<14) /* Interrupt Report & Mask: Enable */
438 #define D_NT_ISNT       (1<<13) /* Configfure interface as NT */
439 #define D_NT_FT         (1<<12) /* Fixed Timing */
440 #define D_NT_EZ         (1<<11) /* Echo Channel is Zeros */
441 #define D_NT_IFA        (1<<10) /* Inhibit Final Activation */
442 #define D_NT_ACT        (1<<9)  /* Activate Interface */
443 #define D_NT_MFE        (1<<8)  /* Multiframe Enable */
444 #define D_NT_RLB(v)     ((v)<<5)        /* Remote Loopback */
445 #define D_NT_LLB(v)     ((v)<<2)        /* Local Loopback */
446 #define D_NT_FACT       (1<<1)  /* Force Activation */
447 #define D_NT_ABV        (1<<0)  /* Activate Bipolar Violation */
448
449 /* Codec Setup */
450 #define D_CDEC_CK(v)    ((v)<<24)       /* Clock Select */
451 #define D_CDEC_FED(v)   ((v)<<12)       /* FSCOD Falling Edge Delay */
452 #define D_CDEC_RED(v)   ((v)<<0)        /* FSCOD Rising Edge Delay */
453
454 /* Test */
455 #define D_TEST_RAM(v)   ((v)<<16)       /* RAM Pointer */
456 #define D_TEST_SIZE(v)  ((v)<<11)       /* */
457 #define D_TEST_ROMONOFF 0x5     /* Toggle ROM opcode monitor on/off */
458 #define D_TEST_PROC     0x6     /* MicroProcessor test */
459 #define D_TEST_SER      0x7     /* Serial-Controller test */
460 #define D_TEST_RAMREAD  0x8     /* Copy from Ram to system memory */
461 #define D_TEST_RAMWRITE 0x9     /* Copy into Ram from system memory */
462 #define D_TEST_RAMBIST  0xa     /* RAM Built-In Self Test */
463 #define D_TEST_MCBIST   0xb     /* Microcontroller Built-In Self Test */
464 #define D_TEST_DUMP     0xe     /* ROM Dump */
465
466 /* CHI Data Mode */
467 #define D_CDM_THI       (1<<8)  /* Transmit Data on CHIDR Pin */
468 #define D_CDM_RHI       (1<<7)  /* Receive Data on CHIDX Pin */
469 #define D_CDM_RCE       (1<<6)  /* Receive on Rising Edge of CHICK */
470 #define D_CDM_XCE       (1<<2)  /* Transmit Data on Rising Edge of CHICK */
471 #define D_CDM_XEN       (1<<1)  /* Transmit Highway Enable */
472 #define D_CDM_REN       (1<<0)  /* Receive Highway Enable */
473
474 /* The Interrupts */
475 #define D_INTR_BRDY     1       /* Buffer Ready for processing */
476 #define D_INTR_MINT     2       /* Marked Interrupt in RD/TD */
477 #define D_INTR_IBEG     3       /* Flag to idle transition detected (HDLC) */
478 #define D_INTR_IEND     4       /* Idle to flag transition detected (HDLC) */
479 #define D_INTR_EOL      5       /* End of List */
480 #define D_INTR_CMDI     6       /* Command has bean read */
481 #define D_INTR_XCMP     8       /* Transmission of frame complete */
482 #define D_INTR_SBRI     9       /* BRI status change info */
483 #define D_INTR_FXDT     10      /* Fixed data change */
484 #define D_INTR_CHIL     11      /* CHI lost frame sync (channel 36 only) */
485 #define D_INTR_COLL     11      /* Unrecoverable D-Channel collision */
486 #define D_INTR_DBYT     12      /* Dropped by frame slip */
487 #define D_INTR_RBYT     13      /* Repeated by frame slip */
488 #define D_INTR_LINT     14      /* Lost Interrupt */
489 #define D_INTR_UNDR     15      /* DMA underrun */
490
491 #define D_INTR_TE       32
492 #define D_INTR_NT       34
493 #define D_INTR_CHI      36
494 #define D_INTR_CMD      38
495
496 #define D_INTR_GETCHAN(v)       (((v)>>24) & 0x3f)
497 #define D_INTR_GETCODE(v)       (((v)>>20) & 0xf)
498 #define D_INTR_GETCMD(v)        (((v)>>16) & 0xf)
499 #define D_INTR_GETVAL(v)        ((v) & 0xffff)
500 #define D_INTR_GETRVAL(v)       ((v) & 0xfffff)
501
502 #define D_P_0           0       /* TE receive anchor */
503 #define D_P_1           1       /* TE transmit anchor */
504 #define D_P_2           2       /* NT transmit anchor */
505 #define D_P_3           3       /* NT receive anchor */
506 #define D_P_4           4       /* CHI send data */
507 #define D_P_5           5       /* CHI receive data */
508 #define D_P_6           6       /* */
509 #define D_P_7           7       /* */
510 #define D_P_8           8       /* */
511 #define D_P_9           9       /* */
512 #define D_P_10          10      /* */
513 #define D_P_11          11      /* */
514 #define D_P_12          12      /* */
515 #define D_P_13          13      /* */
516 #define D_P_14          14      /* */
517 #define D_P_15          15      /* */
518 #define D_P_16          16      /* CHI anchor pipe */
519 #define D_P_17          17      /* CHI send */
520 #define D_P_18          18      /* CHI receive */
521 #define D_P_19          19      /* CHI receive */
522 #define D_P_20          20      /* CHI receive */
523 #define D_P_21          21      /* */
524 #define D_P_22          22      /* */
525 #define D_P_23          23      /* */
526 #define D_P_24          24      /* */
527 #define D_P_25          25      /* */
528 #define D_P_26          26      /* */
529 #define D_P_27          27      /* */
530 #define D_P_28          28      /* */
531 #define D_P_29          29      /* */
532 #define D_P_30          30      /* */
533 #define D_P_31          31      /* */
534
535 /* Transmit descriptor defines */
536 #define DBRI_TD_F       (1<<31) /* End of Frame */
537 #define DBRI_TD_D       (1<<30) /* Do not append CRC */
538 #define DBRI_TD_CNT(v)  ((v)<<16)       /* Number of valid bytes in the buffer */
539 #define DBRI_TD_B       (1<<15) /* Final interrupt */
540 #define DBRI_TD_M       (1<<14) /* Marker interrupt */
541 #define DBRI_TD_I       (1<<13) /* Transmit Idle Characters */
542 #define DBRI_TD_FCNT(v) (v)     /* Flag Count */
543 #define DBRI_TD_UNR     (1<<3)  /* Underrun: transmitter is out of data */
544 #define DBRI_TD_ABT     (1<<2)  /* Abort: frame aborted */
545 #define DBRI_TD_TBC     (1<<0)  /* Transmit buffer Complete */
546 #define DBRI_TD_STATUS(v)       ((v)&0xff)      /* Transmit status */
547                         /* Maximum buffer size per TD: almost 8Kb */
548 #define DBRI_TD_MAXCNT  ((1 << 13) - 4)
549
550 /* Receive descriptor defines */
551 #define DBRI_RD_F       (1<<31) /* End of Frame */
552 #define DBRI_RD_C       (1<<30) /* Completed buffer */
553 #define DBRI_RD_B       (1<<15) /* Final interrupt */
554 #define DBRI_RD_M       (1<<14) /* Marker interrupt */
555 #define DBRI_RD_BCNT(v) (v)     /* Buffer size */
556 #define DBRI_RD_CRC     (1<<7)  /* 0: CRC is correct */
557 #define DBRI_RD_BBC     (1<<6)  /* 1: Bad Byte received */
558 #define DBRI_RD_ABT     (1<<5)  /* Abort: frame aborted */
559 #define DBRI_RD_OVRN    (1<<3)  /* Overrun: data lost */
560 #define DBRI_RD_STATUS(v)      ((v)&0xff)       /* Receive status */
561 #define DBRI_RD_CNT(v) (((v)>>16)&0x1fff)       /* Valid bytes in the buffer */
562
563 /* stream_info[] access */
564 /* Translate the ALSA direction into the array index */
565 #define DBRI_STREAMNO(substream)                                \
566                 (substream->stream ==                           \
567                  SNDRV_PCM_STREAM_PLAYBACK? DBRI_PLAY: DBRI_REC)
568
569 /* Return a pointer to dbri_streaminfo */
570 #define DBRI_STREAM(dbri, substream)    &dbri->stream_info[DBRI_STREAMNO(substream)]
571
572 static struct snd_dbri *dbri_list;      /* All DBRI devices */
573
574 /*
575  * Short data pipes transmit LSB first. The CS4215 receives MSB first. Grrr.
576  * So we have to reverse the bits. Note: not all bit lengths are supported
577  */
578 static __u32 reverse_bytes(__u32 b, int len)
579 {
580         switch (len) {
581         case 32:
582                 b = ((b & 0xffff0000) >> 16) | ((b & 0x0000ffff) << 16);
583         case 16:
584                 b = ((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8);
585         case 8:
586                 b = ((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4);
587         case 4:
588                 b = ((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2);
589         case 2:
590                 b = ((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1);
591         case 1:
592         case 0:
593                 break;
594         default:
595                 printk(KERN_ERR "DBRI reverse_bytes: unsupported length\n");
596         };
597
598         return b;
599 }
600
601 /*
602 ****************************************************************************
603 ************** DBRI initialization and command synchronization *************
604 ****************************************************************************
605
606 Commands are sent to the DBRI by building a list of them in memory,
607 then writing the address of the first list item to DBRI register 8.
608 The list is terminated with a WAIT command, which generates a
609 CPU interrupt to signal completion.
610
611 Since the DBRI can run in parallel with the CPU, several means of
612 synchronization present themselves. The method implemented here is only
613 use of the dbri_cmdwait() to wait for execution of batch of sent commands.
614
615 A circular command buffer is used here. A new command is being added 
616 while another can be executed. The scheme works by adding two WAIT commands
617 after each sent batch of commands. When the next batch is prepared it is
618 added after the WAIT commands then the WAITs are replaced with single JUMP
619 command to the new batch. The the DBRI is forced to reread the last WAIT 
620 command (replaced by the JUMP by then). If the DBRI is still executing 
621 previous commands the request to reread the WAIT command is ignored.
622
623 Every time a routine wants to write commands to the DBRI, it must
624 first call dbri_cmdlock() and get pointer to a free space in 
625 dbri->dma->cmd buffer. After this, the commands can be written to 
626 the buffer, and dbri_cmdsend() is called with the final pointer value 
627 to send them to the DBRI.
628
629 */
630
631 #define MAXLOOPS 20
632 /*
633  * Wait for the current command string to execute
634  */
635 static void dbri_cmdwait(struct snd_dbri *dbri)
636 {
637         int maxloops = MAXLOOPS;
638
639         /* Delay if previous commands are still being processed */
640         while ((--maxloops) > 0 && (sbus_readl(dbri->regs + REG0) & D_P))
641                 msleep_interruptible(1);
642
643         if (maxloops == 0) {
644                 printk(KERN_ERR "DBRI: Chip never completed command buffer\n");
645         } else {
646                 dprintk(D_CMD, "Chip completed command buffer (%d)\n",
647                         MAXLOOPS - maxloops - 1);
648         }
649 }
650 /*
651  * Lock the command queue and returns pointer to a space for len cmd words
652  * It locks the cmdlock spinlock.
653  */
654 static s32 *dbri_cmdlock(struct snd_dbri * dbri, int len)
655 {
656         /* Space for 2 WAIT cmds (replaced later by 1 JUMP cmd) */
657         len += 2;
658         spin_lock(&dbri->cmdlock);
659         if (dbri->cmdptr - dbri->dma->cmd + len < DBRI_NO_CMDS - 2)
660                 return dbri->cmdptr + 2;
661         else if (len < sbus_readl(dbri->regs + REG8) - dbri->dma_dvma)
662                 return dbri->dma->cmd;
663         else
664                 printk(KERN_ERR "DBRI: no space for commands.");
665
666         return 0;
667 }
668
669 /*
670  * Send prepared cmd string. It works by writting a JUMP cmd into
671  * the last WAIT cmd and force DBRI to reread the cmd.
672  * The JUMP cmd points to the new cmd string.
673  * It also releases the cmdlock spinlock.
674  */
675 static void dbri_cmdsend(struct snd_dbri * dbri, s32 * cmd,int len)
676 {
677         s32 tmp, addr;
678         unsigned long flags;
679         static int wait_id = 0;
680
681         wait_id++;
682         wait_id &= 0xffff;      /* restrict it to a 16 bit counter. */
683         *(cmd) = DBRI_CMD(D_WAIT, 1, wait_id);
684         *(cmd+1) = DBRI_CMD(D_WAIT, 1, wait_id);
685
686         /* Replace the last command with JUMP */
687         addr = dbri->dma_dvma + (cmd - len - dbri->dma->cmd) * sizeof(s32);
688         *(dbri->cmdptr+1) = addr;
689         *(dbri->cmdptr) = DBRI_CMD(D_JUMP, 0, 0);
690
691 #ifdef DBRI_DEBUG
692         if (cmd > dbri->cmdptr) {
693                 s32 *ptr;
694
695                 for (ptr = dbri->cmdptr; ptr < cmd+2; ptr++)
696                         dprintk(D_CMD, "cmd: %lx:%08x\n", (unsigned long)ptr, *ptr);
697         } else {
698                 s32 *ptr = dbri->cmdptr;
699
700                 dprintk(D_CMD, "cmd: %lx:%08x\n", (unsigned long)ptr, *ptr);
701                 ptr++;
702                 dprintk(D_CMD, "cmd: %lx:%08x\n", (unsigned long)ptr, *ptr);
703                 for (ptr = dbri->dma->cmd; ptr < cmd+2; ptr++) {
704                         dprintk(D_CMD, "cmd: %lx:%08x\n", (unsigned long)ptr, *ptr);
705                 }
706         }
707 #endif
708
709         spin_lock_irqsave(&dbri->lock, flags);
710         /* Reread the last command */
711         tmp = sbus_readl(dbri->regs + REG0);
712         tmp |= D_P;
713         sbus_writel(tmp, dbri->regs + REG0);
714         spin_unlock_irqrestore(&dbri->lock, flags);
715
716         dbri->cmdptr = cmd;
717         spin_unlock(&dbri->cmdlock);
718 }
719
720 /* Lock must be held when calling this */
721 static void dbri_reset(struct snd_dbri * dbri)
722 {
723         int i;
724         u32 tmp;
725
726         dprintk(D_GEN, "reset 0:%x 2:%x 8:%x 9:%x\n",
727                 sbus_readl(dbri->regs + REG0),
728                 sbus_readl(dbri->regs + REG2),
729                 sbus_readl(dbri->regs + REG8), sbus_readl(dbri->regs + REG9));
730
731         sbus_writel(D_R, dbri->regs + REG0);    /* Soft Reset */
732         for (i = 0; (sbus_readl(dbri->regs + REG0) & D_R) && i < 64; i++)
733                 udelay(10);
734
735         /* A brute approach - DBRI falls back to working burst size by itself
736          * On SS20 D_S does not work, so do not try so high. */
737         tmp = sbus_readl(dbri->regs + REG0);
738         tmp |= D_G | D_E;
739         tmp &= ~D_S;
740         sbus_writel(tmp, dbri->regs + REG0);
741 }
742
743 /* Lock must not be held before calling this */
744 static void dbri_initialize(struct snd_dbri * dbri)
745 {
746         s32 *cmd;
747         u32 dma_addr;
748         unsigned long flags;
749         int n;
750
751         spin_lock_irqsave(&dbri->lock, flags);
752
753         dbri_reset(dbri);
754
755         /* Initialize pipes */
756         for (n = 0; n < DBRI_NO_PIPES; n++)
757                 dbri->pipes[n].desc = dbri->pipes[n].first_desc = -1;
758
759         spin_lock_init(&dbri->cmdlock);
760         /*
761          * Initialize the interrupt ringbuffer.
762          */
763         dma_addr = dbri->dma_dvma + dbri_dma_off(intr, 0);
764         dbri->dma->intr[0] = dma_addr;
765         dbri->dbri_irqp = 1;
766         /*
767          * Set up the interrupt queue
768          */
769         spin_lock(&dbri->cmdlock);
770         cmd = dbri->cmdptr = dbri->dma->cmd;
771         *(cmd++) = DBRI_CMD(D_IIQ, 0, 0);
772         *(cmd++) = dma_addr;
773         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
774         dbri->cmdptr = cmd;
775         *(cmd++) = DBRI_CMD(D_WAIT, 1, 0);
776         *(cmd++) = DBRI_CMD(D_WAIT, 1, 0);
777         dma_addr = dbri->dma_dvma + dbri_dma_off(cmd, 0);
778         sbus_writel(dma_addr, dbri->regs + REG8);
779         spin_unlock(&dbri->cmdlock);
780         dbri_cmdwait(dbri);
781
782         spin_unlock_irqrestore(&dbri->lock, flags);
783 }
784
785 /*
786 ****************************************************************************
787 ************************** DBRI data pipe management ***********************
788 ****************************************************************************
789
790 While DBRI control functions use the command and interrupt buffers, the
791 main data path takes the form of data pipes, which can be short (command
792 and interrupt driven), or long (attached to DMA buffers).  These functions
793 provide a rudimentary means of setting up and managing the DBRI's pipes,
794 but the calling functions have to make sure they respect the pipes' linked
795 list ordering, among other things.  The transmit and receive functions
796 here interface closely with the transmit and receive interrupt code.
797
798 */
799 static int pipe_active(struct snd_dbri * dbri, int pipe)
800 {
801         return ((pipe >= 0) && (dbri->pipes[pipe].desc != -1));
802 }
803
804 /* reset_pipe(dbri, pipe)
805  *
806  * Called on an in-use pipe to clear anything being transmitted or received
807  * Lock must be held before calling this.
808  */
809 static void reset_pipe(struct snd_dbri * dbri, int pipe)
810 {
811         int sdp;
812         int desc;
813         s32 *cmd;
814
815         if (pipe < 0 || pipe > DBRI_MAX_PIPE) {
816                 printk(KERN_ERR "DBRI: reset_pipe called with illegal pipe number\n");
817                 return;
818         }
819
820         sdp = dbri->pipes[pipe].sdp;
821         if (sdp == 0) {
822                 printk(KERN_ERR "DBRI: reset_pipe called on uninitialized pipe\n");
823                 return;
824         }
825
826         cmd = dbri_cmdlock(dbri, 3);
827         *(cmd++) = DBRI_CMD(D_SDP, 0, sdp | D_SDP_C | D_SDP_P);
828         *(cmd++) = 0;
829         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
830         dbri_cmdsend(dbri, cmd, 3);
831
832         desc = dbri->pipes[pipe].first_desc;
833         if ( desc >= 0)
834                 do {
835                         dbri->dma->desc[desc].nda = dbri->dma->desc[desc].ba = 0;
836                         desc = dbri->next_desc[desc];
837                 } while (desc != -1 && desc != dbri->pipes[pipe].first_desc);
838
839         dbri->pipes[pipe].desc = -1;
840         dbri->pipes[pipe].first_desc = -1;
841 }
842
843 static void setup_pipe(struct snd_dbri * dbri, int pipe, int sdp)
844 {
845         if (pipe < 0 || pipe > DBRI_MAX_PIPE) {
846                 printk(KERN_ERR "DBRI: setup_pipe called with illegal pipe number\n");
847                 return;
848         }
849
850         if ((sdp & 0xf800) != sdp) {
851                 printk(KERN_ERR "DBRI: setup_pipe called with strange SDP value\n");
852                 /* sdp &= 0xf800; */
853         }
854
855         /* If this is a fixed receive pipe, arrange for an interrupt
856          * every time its data changes
857          */
858         if (D_SDP_MODE(sdp) == D_SDP_FIXED && !(sdp & D_SDP_TO_SER))
859                 sdp |= D_SDP_CHANGE;
860
861         sdp |= D_PIPE(pipe);
862         dbri->pipes[pipe].sdp = sdp;
863         dbri->pipes[pipe].desc = -1;
864         dbri->pipes[pipe].first_desc = -1;
865
866         reset_pipe(dbri, pipe);
867 }
868
869 static void link_time_slot(struct snd_dbri * dbri, int pipe,
870                            int prevpipe, int nextpipe,
871                            int length, int cycle)
872 {
873         s32 *cmd;
874         int val;
875
876         if (pipe < 0 || pipe > DBRI_MAX_PIPE 
877                         || prevpipe < 0 || prevpipe > DBRI_MAX_PIPE
878                         || nextpipe < 0 || nextpipe > DBRI_MAX_PIPE) {
879                 printk(KERN_ERR 
880                     "DBRI: link_time_slot called with illegal pipe number\n");
881                 return;
882         }
883
884         if (dbri->pipes[pipe].sdp == 0 
885                         || dbri->pipes[prevpipe].sdp == 0
886                         || dbri->pipes[nextpipe].sdp == 0) {
887                 printk(KERN_ERR "DBRI: link_time_slot called on uninitialized pipe\n");
888                 return;
889         }
890
891         dbri->pipes[prevpipe].nextpipe = pipe;
892         dbri->pipes[pipe].nextpipe = nextpipe;
893         dbri->pipes[pipe].length = length;
894
895         cmd = dbri_cmdlock(dbri, 4);
896
897         if (dbri->pipes[pipe].sdp & D_SDP_TO_SER) {
898                 /* Deal with CHI special case:
899                  * "If transmission on edges 0 or 1 is desired, then cycle n
900                  *  (where n = # of bit times per frame...) must be used."
901                  *                  - DBRI data sheet, page 11
902                  */
903                 if (prevpipe == 16 && cycle == 0)
904                         cycle = dbri->chi_bpf;
905
906                 val = D_DTS_VO | D_DTS_INS | D_DTS_PRVOUT(prevpipe) | pipe;
907                 *(cmd++) = DBRI_CMD(D_DTS, 0, val);
908                 *(cmd++) = 0;
909                 *(cmd++) =
910                     D_TS_LEN(length) | D_TS_CYCLE(cycle) | D_TS_NEXT(nextpipe);
911         } else {
912                 val = D_DTS_VI | D_DTS_INS | D_DTS_PRVIN(prevpipe) | pipe;
913                 *(cmd++) = DBRI_CMD(D_DTS, 0, val);
914                 *(cmd++) =
915                     D_TS_LEN(length) | D_TS_CYCLE(cycle) | D_TS_NEXT(nextpipe);
916                 *(cmd++) = 0;
917         }
918         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
919
920         dbri_cmdsend(dbri, cmd, 4);
921 }
922
923 static void unlink_time_slot(struct snd_dbri * dbri, int pipe,
924                              enum in_or_out direction, int prevpipe,
925                              int nextpipe)
926 {
927         s32 *cmd;
928         int val;
929
930         if (pipe < 0 || pipe > DBRI_MAX_PIPE 
931                         || prevpipe < 0 || prevpipe > DBRI_MAX_PIPE
932                         || nextpipe < 0 || nextpipe > DBRI_MAX_PIPE) {
933                 printk(KERN_ERR 
934                     "DBRI: unlink_time_slot called with illegal pipe number\n");
935                 return;
936         }
937
938         cmd = dbri_cmdlock(dbri, 4);
939
940         if (direction == PIPEinput) {
941                 val = D_DTS_VI | D_DTS_DEL | D_DTS_PRVIN(prevpipe) | pipe;
942                 *(cmd++) = DBRI_CMD(D_DTS, 0, val);
943                 *(cmd++) = D_TS_NEXT(nextpipe);
944                 *(cmd++) = 0;
945         } else {
946                 val = D_DTS_VO | D_DTS_DEL | D_DTS_PRVOUT(prevpipe) | pipe;
947                 *(cmd++) = DBRI_CMD(D_DTS, 0, val);
948                 *(cmd++) = 0;
949                 *(cmd++) = D_TS_NEXT(nextpipe);
950         }
951         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
952
953         dbri_cmdsend(dbri, cmd, 4);
954 }
955
956 /* xmit_fixed() / recv_fixed()
957  *
958  * Transmit/receive data on a "fixed" pipe - i.e, one whose contents are not
959  * expected to change much, and which we don't need to buffer.
960  * The DBRI only interrupts us when the data changes (receive pipes),
961  * or only changes the data when this function is called (transmit pipes).
962  * Only short pipes (numbers 16-31) can be used in fixed data mode.
963  *
964  * These function operate on a 32-bit field, no matter how large
965  * the actual time slot is.  The interrupt handler takes care of bit
966  * ordering and alignment.  An 8-bit time slot will always end up
967  * in the low-order 8 bits, filled either MSB-first or LSB-first,
968  * depending on the settings passed to setup_pipe()
969  */
970 static void xmit_fixed(struct snd_dbri * dbri, int pipe, unsigned int data)
971 {
972         s32 *cmd;
973
974         if (pipe < 16 || pipe > DBRI_MAX_PIPE) {
975                 printk(KERN_ERR "DBRI: xmit_fixed: Illegal pipe number\n");
976                 return;
977         }
978
979         if (D_SDP_MODE(dbri->pipes[pipe].sdp) == 0) {
980                 printk(KERN_ERR "DBRI: xmit_fixed: Uninitialized pipe %d\n", pipe);
981                 return;
982         }
983
984         if (D_SDP_MODE(dbri->pipes[pipe].sdp) != D_SDP_FIXED) {
985                 printk(KERN_ERR "DBRI: xmit_fixed: Non-fixed pipe %d\n", pipe);
986                 return;
987         }
988
989         if (!(dbri->pipes[pipe].sdp & D_SDP_TO_SER)) {
990                 printk(KERN_ERR "DBRI: xmit_fixed: Called on receive pipe %d\n", pipe);
991                 return;
992         }
993
994         /* DBRI short pipes always transmit LSB first */
995
996         if (dbri->pipes[pipe].sdp & D_SDP_MSB)
997                 data = reverse_bytes(data, dbri->pipes[pipe].length);
998
999         cmd = dbri_cmdlock(dbri, 3);
1000
1001         *(cmd++) = DBRI_CMD(D_SSP, 0, pipe);
1002         *(cmd++) = data;
1003         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
1004
1005         dbri_cmdsend(dbri, cmd, 3);
1006         dbri_cmdwait(dbri);
1007 }
1008
1009 static void recv_fixed(struct snd_dbri * dbri, int pipe, volatile __u32 * ptr)
1010 {
1011         if (pipe < 16 || pipe > DBRI_MAX_PIPE) {
1012                 printk(KERN_ERR "DBRI: recv_fixed called with illegal pipe number\n");
1013                 return;
1014         }
1015
1016         if (D_SDP_MODE(dbri->pipes[pipe].sdp) != D_SDP_FIXED) {
1017                 printk(KERN_ERR "DBRI: recv_fixed called on non-fixed pipe %d\n", pipe);
1018                 return;
1019         }
1020
1021         if (dbri->pipes[pipe].sdp & D_SDP_TO_SER) {
1022                 printk(KERN_ERR "DBRI: recv_fixed called on transmit pipe %d\n", pipe);
1023                 return;
1024         }
1025
1026         dbri->pipes[pipe].recv_fixed_ptr = ptr;
1027 }
1028
1029 /* setup_descs()
1030  *
1031  * Setup transmit/receive data on a "long" pipe - i.e, one associated
1032  * with a DMA buffer.
1033  *
1034  * Only pipe numbers 0-15 can be used in this mode.
1035  *
1036  * This function takes a stream number pointing to a data buffer,
1037  * and work by building chains of descriptors which identify the
1038  * data buffers.  Buffers too large for a single descriptor will
1039  * be spread across multiple descriptors.
1040  *
1041  * All descriptors create a ring buffer.
1042  */
1043 static int setup_descs(struct snd_dbri * dbri, int streamno, unsigned int period)
1044 {
1045         struct dbri_streaminfo *info = &dbri->stream_info[streamno];
1046         __u32 dvma_buffer;
1047         int desc;
1048         int len;
1049         int first_desc = -1;
1050         int last_desc = -1;
1051
1052         if (info->pipe < 0 || info->pipe > 15) {
1053                 printk(KERN_ERR "DBRI: setup_descs: Illegal pipe number\n");
1054                 return -2;
1055         }
1056
1057         if (dbri->pipes[info->pipe].sdp == 0) {
1058                 printk(KERN_ERR "DBRI: setup_descs: Uninitialized pipe %d\n",
1059                        info->pipe);
1060                 return -2;
1061         }
1062
1063         dvma_buffer = info->dvma_buffer;
1064         len = info->size;
1065
1066         if (streamno == DBRI_PLAY) {
1067                 if (!(dbri->pipes[info->pipe].sdp & D_SDP_TO_SER)) {
1068                         printk(KERN_ERR "DBRI: setup_descs: Called on receive pipe %d\n",
1069                                info->pipe);
1070                         return -2;
1071                 }
1072         } else {
1073                 if (dbri->pipes[info->pipe].sdp & D_SDP_TO_SER) {
1074                         printk(KERN_ERR 
1075                             "DBRI: setup_descs: Called on transmit pipe %d\n",
1076                              info->pipe);
1077                         return -2;
1078                 }
1079                 /* Should be able to queue multiple buffers to receive on a pipe */
1080                 if (pipe_active(dbri, info->pipe)) {
1081                         printk(KERN_ERR "DBRI: recv_on_pipe: Called on active pipe %d\n",
1082                                info->pipe);
1083                         return -2;
1084                 }
1085
1086                 /* Make sure buffer size is multiple of four */
1087                 len &= ~3;
1088         }
1089
1090         /* Free descriptors if pipe has any */
1091         desc = dbri->pipes[info->pipe].first_desc;
1092         if ( desc >= 0)
1093                 do {
1094                         dbri->dma->desc[desc].nda = dbri->dma->desc[desc].ba = 0;
1095                         desc = dbri->next_desc[desc];
1096                 } while (desc != -1 && desc != dbri->pipes[info->pipe].first_desc);
1097
1098         dbri->pipes[info->pipe].desc = -1;
1099         dbri->pipes[info->pipe].first_desc = -1;
1100
1101         desc = 0;
1102         while (len > 0) {
1103                 int mylen;
1104
1105                 for (; desc < DBRI_NO_DESCS; desc++) {
1106                         if (!dbri->dma->desc[desc].ba)
1107                                 break;
1108                 }
1109                 if (desc == DBRI_NO_DESCS) {
1110                         printk(KERN_ERR "DBRI: setup_descs: No descriptors\n");
1111                         return -1;
1112                 }
1113
1114                 if (len > DBRI_TD_MAXCNT)
1115                         mylen = DBRI_TD_MAXCNT; /* 8KB - 4 */
1116                 else
1117                         mylen = len;
1118
1119                 if (mylen > period)
1120                         mylen = period;
1121
1122                 dbri->next_desc[desc] = -1;
1123                 dbri->dma->desc[desc].ba = dvma_buffer;
1124                 dbri->dma->desc[desc].nda = 0;
1125
1126                 if (streamno == DBRI_PLAY) {
1127                         dbri->dma->desc[desc].word1 = DBRI_TD_CNT(mylen);
1128                         dbri->dma->desc[desc].word4 = 0;
1129                         dbri->dma->desc[desc].word1 |= 
1130                             DBRI_TD_F | DBRI_TD_B;
1131                 } else {
1132                         dbri->dma->desc[desc].word1 = 0;
1133                         dbri->dma->desc[desc].word4 =
1134                             DBRI_RD_B | DBRI_RD_BCNT(mylen);
1135                 }
1136
1137                 if (first_desc == -1)
1138                         first_desc = desc;
1139                 else {
1140                         dbri->next_desc[last_desc] = desc;
1141                         dbri->dma->desc[last_desc].nda =
1142                             dbri->dma_dvma + dbri_dma_off(desc, desc);
1143                 }
1144
1145                 last_desc = desc;
1146                 dvma_buffer += mylen;
1147                 len -= mylen;
1148         }
1149
1150         if (first_desc == -1 || last_desc == -1) {
1151                 printk(KERN_ERR "DBRI: setup_descs: Not enough descriptors available\n");
1152                 return -1;
1153         }
1154
1155         dbri->dma->desc[last_desc].nda =
1156             dbri->dma_dvma + dbri_dma_off(desc, first_desc);
1157         dbri->next_desc[last_desc] = first_desc;
1158         dbri->pipes[info->pipe].first_desc = first_desc;
1159         dbri->pipes[info->pipe].desc = first_desc;
1160
1161 #ifdef DBRI_DEBUG
1162         for (desc = first_desc; desc != -1; ) {
1163                 dprintk(D_DESC, "DESC %d: %08x %08x %08x %08x\n",
1164                         desc,
1165                         dbri->dma->desc[desc].word1,
1166                         dbri->dma->desc[desc].ba,
1167                         dbri->dma->desc[desc].nda, dbri->dma->desc[desc].word4);
1168                         desc = dbri->next_desc[desc];
1169                         if ( desc == first_desc )
1170                                 break;
1171         }
1172 #endif
1173         return 0;
1174 }
1175
1176 /*
1177 ****************************************************************************
1178 ************************** DBRI - CHI interface ****************************
1179 ****************************************************************************
1180
1181 The CHI is a four-wire (clock, frame sync, data in, data out) time-division
1182 multiplexed serial interface which the DBRI can operate in either master
1183 (give clock/frame sync) or slave (take clock/frame sync) mode.
1184
1185 */
1186
1187 enum master_or_slave { CHImaster, CHIslave };
1188
1189 static void reset_chi(struct snd_dbri * dbri, enum master_or_slave master_or_slave,
1190                       int bits_per_frame)
1191 {
1192         s32 *cmd;
1193         int val;
1194
1195         /* Set CHI Anchor: Pipe 16 */
1196
1197         cmd = dbri_cmdlock(dbri, 4);
1198         val = D_DTS_VO | D_DTS_VI | D_DTS_INS 
1199                 | D_DTS_PRVIN(16) | D_PIPE(16) | D_DTS_PRVOUT(16);
1200         *(cmd++) = DBRI_CMD(D_DTS, 0, val);
1201         *(cmd++) = D_TS_ANCHOR | D_TS_NEXT(16);
1202         *(cmd++) = D_TS_ANCHOR | D_TS_NEXT(16);
1203         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
1204         dbri_cmdsend(dbri, cmd, 4);
1205
1206         dbri->pipes[16].sdp = 1;
1207         dbri->pipes[16].nextpipe = 16;
1208
1209         cmd = dbri_cmdlock(dbri, 4);
1210
1211         if (master_or_slave == CHIslave) {
1212                 /* Setup DBRI for CHI Slave - receive clock, frame sync (FS)
1213                  *
1214                  * CHICM  = 0 (slave mode, 8 kHz frame rate)
1215                  * IR     = give immediate CHI status interrupt
1216                  * EN     = give CHI status interrupt upon change
1217                  */
1218                 *(cmd++) = DBRI_CMD(D_CHI, 0, D_CHI_CHICM(0));
1219         } else {
1220                 /* Setup DBRI for CHI Master - generate clock, FS
1221                  *
1222                  * BPF                          =  bits per 8 kHz frame
1223                  * 12.288 MHz / CHICM_divisor   = clock rate
1224                  * FD  =  1 - drive CHIFS on rising edge of CHICK
1225                  */
1226                 int clockrate = bits_per_frame * 8;
1227                 int divisor = 12288 / clockrate;
1228
1229                 if (divisor > 255 || divisor * clockrate != 12288)
1230                         printk(KERN_ERR "DBRI: illegal bits_per_frame in setup_chi\n");
1231
1232                 *(cmd++) = DBRI_CMD(D_CHI, 0, D_CHI_CHICM(divisor) | D_CHI_FD
1233                                     | D_CHI_BPF(bits_per_frame));
1234         }
1235
1236         dbri->chi_bpf = bits_per_frame;
1237
1238         /* CHI Data Mode
1239          *
1240          * RCE   =  0 - receive on falling edge of CHICK
1241          * XCE   =  1 - transmit on rising edge of CHICK
1242          * XEN   =  1 - enable transmitter
1243          * REN   =  1 - enable receiver
1244          */
1245
1246         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
1247         *(cmd++) = DBRI_CMD(D_CDM, 0, D_CDM_XCE | D_CDM_XEN | D_CDM_REN);
1248         *(cmd++) = DBRI_CMD(D_PAUSE, 0, 0);
1249
1250         dbri_cmdsend(dbri, cmd, 4);
1251 }
1252
1253 /*
1254 ****************************************************************************
1255 *********************** CS4215 audio codec management **********************
1256 ****************************************************************************
1257
1258 In the standard SPARC audio configuration, the CS4215 codec is attached
1259 to the DBRI via the CHI interface and few of the DBRI's PIO pins.
1260
1261 */
1262 static void cs4215_setup_pipes(struct snd_dbri * dbri)
1263 {
1264         /*
1265          * Data mode:
1266          * Pipe  4: Send timeslots 1-4 (audio data)
1267          * Pipe 20: Send timeslots 5-8 (part of ctrl data)
1268          * Pipe  6: Receive timeslots 1-4 (audio data)
1269          * Pipe 21: Receive timeslots 6-7. We can only receive 20 bits via
1270          *          interrupt, and the rest of the data (slot 5 and 8) is
1271          *          not relevant for us (only for doublechecking).
1272          *
1273          * Control mode:
1274          * Pipe 17: Send timeslots 1-4 (slots 5-8 are readonly)
1275          * Pipe 18: Receive timeslot 1 (clb).
1276          * Pipe 19: Receive timeslot 7 (version). 
1277          */
1278
1279         setup_pipe(dbri, 4, D_SDP_MEM | D_SDP_TO_SER | D_SDP_MSB);
1280         setup_pipe(dbri, 20, D_SDP_FIXED | D_SDP_TO_SER | D_SDP_MSB);
1281         setup_pipe(dbri, 6, D_SDP_MEM | D_SDP_FROM_SER | D_SDP_MSB);
1282         setup_pipe(dbri, 21, D_SDP_FIXED | D_SDP_FROM_SER | D_SDP_MSB);
1283
1284         setup_pipe(dbri, 17, D_SDP_FIXED | D_SDP_TO_SER | D_SDP_MSB);
1285         setup_pipe(dbri, 18, D_SDP_FIXED | D_SDP_FROM_SER | D_SDP_MSB);
1286         setup_pipe(dbri, 19, D_SDP_FIXED | D_SDP_FROM_SER | D_SDP_MSB);
1287
1288         dbri_cmdwait(dbri);
1289 }
1290
1291 static int cs4215_init_data(struct cs4215 *mm)
1292 {
1293         /*
1294          * No action, memory resetting only.
1295          *
1296          * Data Time Slot 5-8
1297          * Speaker,Line and Headphone enable. Gain set to the half.
1298          * Input is mike.
1299          */
1300         mm->data[0] = CS4215_LO(0x20) | CS4215_HE | CS4215_LE;
1301         mm->data[1] = CS4215_RO(0x20) | CS4215_SE;
1302         mm->data[2] = CS4215_LG(0x8) | CS4215_IS | CS4215_PIO0 | CS4215_PIO1;
1303         mm->data[3] = CS4215_RG(0x8) | CS4215_MA(0xf);
1304
1305         /*
1306          * Control Time Slot 1-4
1307          * 0: Default I/O voltage scale
1308          * 1: 8 bit ulaw, 8kHz, mono, high pass filter disabled
1309          * 2: Serial enable, CHI master, 128 bits per frame, clock 1
1310          * 3: Tests disabled
1311          */
1312         mm->ctrl[0] = CS4215_RSRVD_1 | CS4215_MLB;
1313         mm->ctrl[1] = CS4215_DFR_ULAW | CS4215_FREQ[0].csval;
1314         mm->ctrl[2] = CS4215_XCLK | CS4215_BSEL_128 | CS4215_FREQ[0].xtal;
1315         mm->ctrl[3] = 0;
1316
1317         mm->status = 0;
1318         mm->version = 0xff;
1319         mm->precision = 8;      /* For ULAW */
1320         mm->channels = 1;
1321
1322         return 0;
1323 }
1324
1325 static void cs4215_setdata(struct snd_dbri * dbri, int muted)
1326 {
1327         if (muted) {
1328                 dbri->mm.data[0] |= 63;
1329                 dbri->mm.data[1] |= 63;
1330                 dbri->mm.data[2] &= ~15;
1331                 dbri->mm.data[3] &= ~15;
1332         } else {
1333                 /* Start by setting the playback attenuation. */
1334                 struct dbri_streaminfo *info = &dbri->stream_info[DBRI_PLAY];
1335                 int left_gain = info->left_gain & 0x3f;
1336                 int right_gain = info->right_gain & 0x3f;
1337
1338                 dbri->mm.data[0] &= ~0x3f;      /* Reset the volume bits */
1339                 dbri->mm.data[1] &= ~0x3f;
1340                 dbri->mm.data[0] |= (DBRI_MAX_VOLUME - left_gain);
1341                 dbri->mm.data[1] |= (DBRI_MAX_VOLUME - right_gain);
1342
1343                 /* Now set the recording gain. */
1344                 info = &dbri->stream_info[DBRI_REC];
1345                 left_gain = info->left_gain & 0xf;
1346                 right_gain = info->right_gain & 0xf;
1347                 dbri->mm.data[2] |= CS4215_LG(left_gain);
1348                 dbri->mm.data[3] |= CS4215_RG(right_gain);
1349         }
1350
1351         xmit_fixed(dbri, 20, *(int *)dbri->mm.data);
1352 }
1353
1354 /*
1355  * Set the CS4215 to data mode.
1356  */
1357 static void cs4215_open(struct snd_dbri * dbri)
1358 {
1359         int data_width;
1360         u32 tmp;
1361
1362         dprintk(D_MM, "cs4215_open: %d channels, %d bits\n",
1363                 dbri->mm.channels, dbri->mm.precision);
1364
1365         /* Temporarily mute outputs, and wait 1/8000 sec (125 us)
1366          * to make sure this takes.  This avoids clicking noises.
1367          */
1368
1369         cs4215_setdata(dbri, 1);
1370         udelay(125);
1371
1372         /*
1373          * Data mode:
1374          * Pipe  4: Send timeslots 1-4 (audio data)
1375          * Pipe 20: Send timeslots 5-8 (part of ctrl data)
1376          * Pipe  6: Receive timeslots 1-4 (audio data)
1377          * Pipe 21: Receive timeslots 6-7. We can only receive 20 bits via
1378          *          interrupt, and the rest of the data (slot 5 and 8) is
1379          *          not relevant for us (only for doublechecking).
1380          *
1381          * Just like in control mode, the time slots are all offset by eight
1382          * bits.  The CS4215, it seems, observes TSIN (the delayed signal)
1383          * even if it's the CHI master.  Don't ask me...
1384          */
1385         tmp = sbus_readl(dbri->regs + REG0);
1386         tmp &= ~(D_C);          /* Disable CHI */
1387         sbus_writel(tmp, dbri->regs + REG0);
1388
1389         /* Switch CS4215 to data mode - set PIO3 to 1 */
1390         sbus_writel(D_ENPIO | D_PIO1 | D_PIO3 |
1391                     (dbri->mm.onboard ? D_PIO0 : D_PIO2), dbri->regs + REG2);
1392
1393         reset_chi(dbri, CHIslave, 128);
1394
1395         /* Note: this next doesn't work for 8-bit stereo, because the two
1396          * channels would be on timeslots 1 and 3, with 2 and 4 idle.
1397          * (See CS4215 datasheet Fig 15)
1398          *
1399          * DBRI non-contiguous mode would be required to make this work.
1400          */
1401         data_width = dbri->mm.channels * dbri->mm.precision;
1402
1403         link_time_slot(dbri, 4, 16, 16, data_width, dbri->mm.offset);
1404         link_time_slot(dbri, 20, 4, 16, 32, dbri->mm.offset + 32);
1405         link_time_slot(dbri, 6, 16, 16, data_width, dbri->mm.offset);
1406         link_time_slot(dbri, 21, 6, 16, 16, dbri->mm.offset + 40);
1407
1408         /* FIXME: enable CHI after _setdata? */
1409         tmp = sbus_readl(dbri->regs + REG0);
1410         tmp |= D_C;             /* Enable CHI */
1411         sbus_writel(tmp, dbri->regs + REG0);
1412
1413         cs4215_setdata(dbri, 0);
1414 }
1415
1416 /*
1417  * Send the control information (i.e. audio format)
1418  */
1419 static int cs4215_setctrl(struct snd_dbri * dbri)
1420 {
1421         int i, val;
1422         u32 tmp;
1423
1424         /* FIXME - let the CPU do something useful during these delays */
1425
1426         /* Temporarily mute outputs, and wait 1/8000 sec (125 us)
1427          * to make sure this takes.  This avoids clicking noises.
1428          */
1429         cs4215_setdata(dbri, 1);
1430         udelay(125);
1431
1432         /*
1433          * Enable Control mode: Set DBRI's PIO3 (4215's D/~C) to 0, then wait
1434          * 12 cycles <= 12/(5512.5*64) sec = 34.01 usec
1435          */
1436         val = D_ENPIO | D_PIO1 | (dbri->mm.onboard ? D_PIO0 : D_PIO2);
1437         sbus_writel(val, dbri->regs + REG2);
1438         dprintk(D_MM, "cs4215_setctrl: reg2=0x%x\n", val);
1439         udelay(34);
1440
1441         /* In Control mode, the CS4215 is a slave device, so the DBRI must
1442          * operate as CHI master, supplying clocking and frame synchronization.
1443          *
1444          * In Data mode, however, the CS4215 must be CHI master to insure
1445          * that its data stream is synchronous with its codec.
1446          *
1447          * The upshot of all this?  We start by putting the DBRI into master
1448          * mode, program the CS4215 in Control mode, then switch the CS4215
1449          * into Data mode and put the DBRI into slave mode.  Various timing
1450          * requirements must be observed along the way.
1451          *
1452          * Oh, and one more thing, on a SPARCStation 20 (and maybe
1453          * others?), the addressing of the CS4215's time slots is
1454          * offset by eight bits, so we add eight to all the "cycle"
1455          * values in the Define Time Slot (DTS) commands.  This is
1456          * done in hardware by a TI 248 that delays the DBRI->4215
1457          * frame sync signal by eight clock cycles.  Anybody know why?
1458          */
1459         tmp = sbus_readl(dbri->regs + REG0);
1460         tmp &= ~D_C;            /* Disable CHI */
1461         sbus_writel(tmp, dbri->regs + REG0);
1462
1463         reset_chi(dbri, CHImaster, 128);
1464
1465         /*
1466          * Control mode:
1467          * Pipe 17: Send timeslots 1-4 (slots 5-8 are readonly)
1468          * Pipe 18: Receive timeslot 1 (clb).
1469          * Pipe 19: Receive timeslot 7 (version). 
1470          */
1471
1472         link_time_slot(dbri, 17, 16, 16, 32, dbri->mm.offset);
1473         link_time_slot(dbri, 18, 16, 16, 8, dbri->mm.offset);
1474         link_time_slot(dbri, 19, 18, 16, 8, dbri->mm.offset + 48);
1475
1476         /* Wait for the chip to echo back CLB (Control Latch Bit) as zero */
1477         dbri->mm.ctrl[0] &= ~CS4215_CLB;
1478         xmit_fixed(dbri, 17, *(int *)dbri->mm.ctrl);
1479
1480         tmp = sbus_readl(dbri->regs + REG0);
1481         tmp |= D_C;             /* Enable CHI */
1482         sbus_writel(tmp, dbri->regs + REG0);
1483
1484         for (i = 10; ((dbri->mm.status & 0xe4) != 0x20); --i) {
1485                 msleep_interruptible(1);
1486         }
1487         if (i == 0) {
1488                 dprintk(D_MM, "CS4215 didn't respond to CLB (0x%02x)\n",
1489                         dbri->mm.status);
1490                 return -1;
1491         }
1492
1493         /* Disable changes to our copy of the version number, as we are about
1494          * to leave control mode.
1495          */
1496         recv_fixed(dbri, 19, NULL);
1497
1498         /* Terminate CS4215 control mode - data sheet says
1499          * "Set CLB=1 and send two more frames of valid control info"
1500          */
1501         dbri->mm.ctrl[0] |= CS4215_CLB;
1502         xmit_fixed(dbri, 17, *(int *)dbri->mm.ctrl);
1503
1504         /* Two frames of control info @ 8kHz frame rate = 250 us delay */
1505         udelay(250);
1506
1507         cs4215_setdata(dbri, 0);
1508
1509         return 0;
1510 }
1511
1512 /*
1513  * Setup the codec with the sampling rate, audio format and number of
1514  * channels.
1515  * As part of the process we resend the settings for the data
1516  * timeslots as well.
1517  */
1518 static int cs4215_prepare(struct snd_dbri * dbri, unsigned int rate,
1519                           snd_pcm_format_t format, unsigned int channels)
1520 {
1521         int freq_idx;
1522         int ret = 0;
1523
1524         /* Lookup index for this rate */
1525         for (freq_idx = 0; CS4215_FREQ[freq_idx].freq != 0; freq_idx++) {
1526                 if (CS4215_FREQ[freq_idx].freq == rate)
1527                         break;
1528         }
1529         if (CS4215_FREQ[freq_idx].freq != rate) {
1530                 printk(KERN_WARNING "DBRI: Unsupported rate %d Hz\n", rate);
1531                 return -1;
1532         }
1533
1534         switch (format) {
1535         case SNDRV_PCM_FORMAT_MU_LAW:
1536                 dbri->mm.ctrl[1] = CS4215_DFR_ULAW;
1537                 dbri->mm.precision = 8;
1538                 break;
1539         case SNDRV_PCM_FORMAT_A_LAW:
1540                 dbri->mm.ctrl[1] = CS4215_DFR_ALAW;
1541                 dbri->mm.precision = 8;
1542                 break;
1543         case SNDRV_PCM_FORMAT_U8:
1544                 dbri->mm.ctrl[1] = CS4215_DFR_LINEAR8;
1545                 dbri->mm.precision = 8;
1546                 break;
1547         case SNDRV_PCM_FORMAT_S16_BE:
1548                 dbri->mm.ctrl[1] = CS4215_DFR_LINEAR16;
1549                 dbri->mm.precision = 16;
1550                 break;
1551         default:
1552                 printk(KERN_WARNING "DBRI: Unsupported format %d\n", format);
1553                 return -1;
1554         }
1555
1556         /* Add rate parameters */
1557         dbri->mm.ctrl[1] |= CS4215_FREQ[freq_idx].csval;
1558         dbri->mm.ctrl[2] = CS4215_XCLK |
1559             CS4215_BSEL_128 | CS4215_FREQ[freq_idx].xtal;
1560
1561         dbri->mm.channels = channels;
1562         if (channels == 2)
1563                 dbri->mm.ctrl[1] |= CS4215_DFR_STEREO;
1564
1565         ret = cs4215_setctrl(dbri);
1566         if (ret == 0)
1567                 cs4215_open(dbri);      /* set codec to data mode */
1568
1569         return ret;
1570 }
1571
1572 /*
1573  *
1574  */
1575 static int cs4215_init(struct snd_dbri * dbri)
1576 {
1577         u32 reg2 = sbus_readl(dbri->regs + REG2);
1578         dprintk(D_MM, "cs4215_init: reg2=0x%x\n", reg2);
1579
1580         /* Look for the cs4215 chips */
1581         if (reg2 & D_PIO2) {
1582                 dprintk(D_MM, "Onboard CS4215 detected\n");
1583                 dbri->mm.onboard = 1;
1584         }
1585         if (reg2 & D_PIO0) {
1586                 dprintk(D_MM, "Speakerbox detected\n");
1587                 dbri->mm.onboard = 0;
1588
1589                 if (reg2 & D_PIO2) {
1590                         printk(KERN_INFO "DBRI: Using speakerbox / "
1591                                "ignoring onboard mmcodec.\n");
1592                         sbus_writel(D_ENPIO2, dbri->regs + REG2);
1593                 }
1594         }
1595
1596         if (!(reg2 & (D_PIO0 | D_PIO2))) {
1597                 printk(KERN_ERR "DBRI: no mmcodec found.\n");
1598                 return -EIO;
1599         }
1600
1601         cs4215_setup_pipes(dbri);
1602         cs4215_init_data(&dbri->mm);
1603
1604         /* Enable capture of the status & version timeslots. */
1605         recv_fixed(dbri, 18, &dbri->mm.status);
1606         recv_fixed(dbri, 19, &dbri->mm.version);
1607
1608         dbri->mm.offset = dbri->mm.onboard ? 0 : 8;
1609         if (cs4215_setctrl(dbri) == -1 || dbri->mm.version == 0xff) {
1610                 dprintk(D_MM, "CS4215 failed probe at offset %d\n",
1611                         dbri->mm.offset);
1612                 return -EIO;
1613         }
1614         dprintk(D_MM, "Found CS4215 at offset %d\n", dbri->mm.offset);
1615
1616         return 0;
1617 }
1618
1619 /*
1620 ****************************************************************************
1621 *************************** DBRI interrupt handler *************************
1622 ****************************************************************************
1623
1624 The DBRI communicates with the CPU mainly via a circular interrupt
1625 buffer.  When an interrupt is signaled, the CPU walks through the
1626 buffer and calls dbri_process_one_interrupt() for each interrupt word.
1627 Complicated interrupts are handled by dedicated functions (which
1628 appear first in this file).  Any pending interrupts can be serviced by
1629 calling dbri_process_interrupt_buffer(), which works even if the CPU's
1630 interrupts are disabled.
1631
1632 */
1633
1634 /* xmit_descs()
1635  *
1636  * Starts transmiting the current TD's for recording/playing.
1637  * For playback, ALSA has filled the DMA memory with new data (we hope).
1638  */
1639 static void xmit_descs(struct snd_dbri *dbri)
1640 {
1641         struct dbri_streaminfo *info;
1642         s32 *cmd;
1643         unsigned long flags;
1644         int first_td;
1645
1646         if (dbri == NULL)
1647                 return;         /* Disabled */
1648
1649         info = &dbri->stream_info[DBRI_REC];
1650         spin_lock_irqsave(&dbri->lock, flags);
1651
1652         if (info->pipe >= 0) {
1653                 first_td = dbri->pipes[info->pipe].first_desc;
1654
1655                 dprintk(D_DESC, "xmit_descs rec @ TD %d\n", first_td);
1656
1657                 /* Stream could be closed by the time we run. */
1658                 if (first_td >= 0) {
1659                         cmd = dbri_cmdlock(dbri, 2);
1660                         *(cmd++) = DBRI_CMD(D_SDP, 0,
1661                                             dbri->pipes[info->pipe].sdp
1662                                             | D_SDP_P | D_SDP_EVERY | D_SDP_C);
1663                         *(cmd++) = dbri->dma_dvma + dbri_dma_off(desc, first_td);
1664                         dbri_cmdsend(dbri, cmd, 2);
1665
1666                         /* Reset our admin of the pipe. */
1667                         dbri->pipes[info->pipe].desc = first_td;
1668                 }
1669         }
1670
1671         info = &dbri->stream_info[DBRI_PLAY];
1672
1673         if (info->pipe >= 0) {
1674                 first_td = dbri->pipes[info->pipe].first_desc;
1675
1676                 dprintk(D_DESC, "xmit_descs play @ TD %d\n", first_td);
1677
1678                 /* Stream could be closed by the time we run. */
1679                 if (first_td >= 0) {
1680                         cmd = dbri_cmdlock(dbri, 2);
1681                         *(cmd++) = DBRI_CMD(D_SDP, 0,
1682                                             dbri->pipes[info->pipe].sdp
1683                                             | D_SDP_P | D_SDP_EVERY | D_SDP_C);
1684                         *(cmd++) = dbri->dma_dvma + dbri_dma_off(desc, first_td);
1685                         dbri_cmdsend(dbri, cmd, 2);
1686
1687                         /* Reset our admin of the pipe. */
1688                         dbri->pipes[info->pipe].desc = first_td;
1689                 }
1690         }
1691         spin_unlock_irqrestore(&dbri->lock, flags);
1692 }
1693
1694 /* transmission_complete_intr()
1695  *
1696  * Called by main interrupt handler when DBRI signals transmission complete
1697  * on a pipe (interrupt triggered by the B bit in a transmit descriptor).
1698  *
1699  * Walks through the pipe's list of transmit buffer descriptors and marks
1700  * them as available. Stops when the first descriptor is found without
1701  * TBC (Transmit Buffer Complete) set, or we've run through them all.
1702  *
1703  * The DMA buffers are not released. They form a ring buffer and
1704  * they are filled by ALSA while others are transmitted by DMA.
1705  *
1706  */
1707
1708 static void transmission_complete_intr(struct snd_dbri * dbri, int pipe)
1709 {
1710         struct dbri_streaminfo *info;
1711         int td;
1712         int status;
1713
1714         info = &dbri->stream_info[DBRI_PLAY];
1715
1716         td = dbri->pipes[pipe].desc;
1717         while (td >= 0) {
1718                 if (td >= DBRI_NO_DESCS) {
1719                         printk(KERN_ERR "DBRI: invalid td on pipe %d\n", pipe);
1720                         return;
1721                 }
1722
1723                 status = DBRI_TD_STATUS(dbri->dma->desc[td].word4);
1724                 if (!(status & DBRI_TD_TBC)) {
1725                         break;
1726                 }
1727
1728                 dprintk(D_INT, "TD %d, status 0x%02x\n", td, status);
1729
1730                 dbri->dma->desc[td].word4 = 0;  /* Reset it for next time. */
1731                 info->offset += DBRI_RD_CNT(dbri->dma->desc[td].word1);
1732
1733                 td = dbri->next_desc[td];
1734                 dbri->pipes[pipe].desc = td;
1735         }
1736
1737         /* Notify ALSA */
1738         if (spin_is_locked(&dbri->lock)) {
1739                 spin_unlock(&dbri->lock);
1740                 snd_pcm_period_elapsed(info->substream);
1741                 spin_lock(&dbri->lock);
1742         } else
1743                 snd_pcm_period_elapsed(info->substream);
1744 }
1745
1746 static void reception_complete_intr(struct snd_dbri * dbri, int pipe)
1747 {
1748         struct dbri_streaminfo *info;
1749         int rd = dbri->pipes[pipe].desc;
1750         s32 status;
1751
1752         if (rd < 0 || rd >= DBRI_NO_DESCS) {
1753                 printk(KERN_ERR "DBRI: invalid rd on pipe %d\n", pipe);
1754                 return;
1755         }
1756
1757         dbri->pipes[pipe].desc = dbri->next_desc[rd];
1758         status = dbri->dma->desc[rd].word1;
1759         dbri->dma->desc[rd].word1 = 0;  /* Reset it for next time. */
1760
1761         info = &dbri->stream_info[DBRI_REC];
1762         info->offset += DBRI_RD_CNT(status);
1763
1764         /* FIXME: Check status */
1765
1766         dprintk(D_INT, "Recv RD %d, status 0x%02x, len %d\n",
1767                 rd, DBRI_RD_STATUS(status), DBRI_RD_CNT(status));
1768
1769         /* Notify ALSA */
1770         if (spin_is_locked(&dbri->lock)) {
1771                 spin_unlock(&dbri->lock);
1772                 snd_pcm_period_elapsed(info->substream);
1773                 spin_lock(&dbri->lock);
1774         } else
1775                 snd_pcm_period_elapsed(info->substream);
1776 }
1777
1778 static void dbri_process_one_interrupt(struct snd_dbri * dbri, int x)
1779 {
1780         int val = D_INTR_GETVAL(x);
1781         int channel = D_INTR_GETCHAN(x);
1782         int command = D_INTR_GETCMD(x);
1783         int code = D_INTR_GETCODE(x);
1784 #ifdef DBRI_DEBUG
1785         int rval = D_INTR_GETRVAL(x);
1786 #endif
1787
1788         if (channel == D_INTR_CMD) {
1789                 dprintk(D_CMD, "INTR: Command: %-5s  Value:%d\n",
1790                         cmds[command], val);
1791         } else {
1792                 dprintk(D_INT, "INTR: Chan:%d Code:%d Val:%#x\n",
1793                         channel, code, rval);
1794         }
1795
1796         switch (code) {
1797         case D_INTR_CMDI:
1798                 if (command != D_WAIT)
1799                         printk(KERN_ERR "DBRI: Command read interrupt\n");
1800                 break;
1801         case D_INTR_BRDY:
1802                 reception_complete_intr(dbri, channel);
1803                 break;
1804         case D_INTR_XCMP:
1805         case D_INTR_MINT:
1806                 transmission_complete_intr(dbri, channel);
1807                 break;
1808         case D_INTR_UNDR:
1809                 /* UNDR - Transmission underrun
1810                  * resend SDP command with clear pipe bit (C) set
1811                  */
1812                 {
1813         /* FIXME: do something useful in case of underrun */
1814                         printk(KERN_ERR "DBRI: Underrun error\n");
1815 #if 0
1816                         s32 *cmd;
1817                         int pipe = channel;
1818                         int td = dbri->pipes[pipe].desc;
1819
1820                         dbri->dma->desc[td].word4 = 0;
1821                         cmd = dbri_cmdlock(dbri, NoGetLock);
1822                         *(cmd++) = DBRI_CMD(D_SDP, 0,
1823                                             dbri->pipes[pipe].sdp
1824                                             | D_SDP_P | D_SDP_C | D_SDP_2SAME);
1825                         *(cmd++) = dbri->dma_dvma + dbri_dma_off(desc, td);
1826                         dbri_cmdsend(dbri, cmd);
1827 #endif
1828                 }
1829                 break;
1830         case D_INTR_FXDT:
1831                 /* FXDT - Fixed data change */
1832                 if (dbri->pipes[channel].sdp & D_SDP_MSB)
1833                         val = reverse_bytes(val, dbri->pipes[channel].length);
1834
1835                 if (dbri->pipes[channel].recv_fixed_ptr)
1836                         *(dbri->pipes[channel].recv_fixed_ptr) = val;
1837                 break;
1838         default:
1839                 if (channel != D_INTR_CMD)
1840                         printk(KERN_WARNING
1841                                "DBRI: Ignored Interrupt: %d (0x%x)\n", code, x);
1842         }
1843 }
1844
1845 /* dbri_process_interrupt_buffer advances through the DBRI's interrupt
1846  * buffer until it finds a zero word (indicating nothing more to do
1847  * right now).  Non-zero words require processing and are handed off
1848  * to dbri_process_one_interrupt AFTER advancing the pointer.
1849  */
1850 static void dbri_process_interrupt_buffer(struct snd_dbri * dbri)
1851 {
1852         s32 x;
1853
1854         while ((x = dbri->dma->intr[dbri->dbri_irqp]) != 0) {
1855                 dbri->dma->intr[dbri->dbri_irqp] = 0;
1856                 dbri->dbri_irqp++;
1857                 if (dbri->dbri_irqp == DBRI_INT_BLK)
1858                         dbri->dbri_irqp = 1;
1859
1860                 dbri_process_one_interrupt(dbri, x);
1861         }
1862 }
1863
1864 static irqreturn_t snd_dbri_interrupt(int irq, void *dev_id,
1865                                       struct pt_regs *regs)
1866 {
1867         struct snd_dbri *dbri = dev_id;
1868         static int errcnt = 0;
1869         int x;
1870
1871         if (dbri == NULL)
1872                 return IRQ_NONE;
1873         spin_lock(&dbri->lock);
1874
1875         /*
1876          * Read it, so the interrupt goes away.
1877          */
1878         x = sbus_readl(dbri->regs + REG1);
1879
1880         if (x & (D_MRR | D_MLE | D_LBG | D_MBE)) {
1881                 u32 tmp;
1882
1883                 if (x & D_MRR)
1884                         printk(KERN_ERR
1885                                "DBRI: Multiple Error Ack on SBus reg1=0x%x\n",
1886                                x);
1887                 if (x & D_MLE)
1888                         printk(KERN_ERR
1889                                "DBRI: Multiple Late Error on SBus reg1=0x%x\n",
1890                                x);
1891                 if (x & D_LBG)
1892                         printk(KERN_ERR
1893                                "DBRI: Lost Bus Grant on SBus reg1=0x%x\n", x);
1894                 if (x & D_MBE)
1895                         printk(KERN_ERR
1896                                "DBRI: Burst Error on SBus reg1=0x%x\n", x);
1897
1898                 /* Some of these SBus errors cause the chip's SBus circuitry
1899                  * to be disabled, so just re-enable and try to keep going.
1900                  *
1901                  * The only one I've seen is MRR, which will be triggered
1902                  * if you let a transmit pipe underrun, then try to CDP it.
1903                  *
1904                  * If these things persist, we reset the chip.
1905                  */
1906                 if ((++errcnt) % 10 == 0) {
1907                         dprintk(D_INT, "Interrupt errors exceeded.\n");
1908                         dbri_reset(dbri);
1909                 } else {
1910                         tmp = sbus_readl(dbri->regs + REG0);
1911                         tmp &= ~(D_D);
1912                         sbus_writel(tmp, dbri->regs + REG0);
1913                 }
1914         }
1915
1916         dbri_process_interrupt_buffer(dbri);
1917
1918         spin_unlock(&dbri->lock);
1919
1920         return IRQ_HANDLED;
1921 }
1922
1923 /****************************************************************************
1924                 PCM Interface
1925 ****************************************************************************/
1926 static struct snd_pcm_hardware snd_dbri_pcm_hw = {
1927         .info                   = (SNDRV_PCM_INFO_MMAP |
1928                                    SNDRV_PCM_INFO_INTERLEAVED |
1929                                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
1930                                    SNDRV_PCM_INFO_MMAP_VALID),
1931         .formats                = SNDRV_PCM_FMTBIT_MU_LAW |
1932                                   SNDRV_PCM_FMTBIT_A_LAW |
1933                                   SNDRV_PCM_FMTBIT_U8 |
1934                                   SNDRV_PCM_FMTBIT_S16_BE,
1935         .rates                  = SNDRV_PCM_RATE_8000_48000 | SNDRV_PCM_RATE_5512,
1936         .rate_min               = 5512,
1937         .rate_max               = 48000,
1938         .channels_min           = 1,
1939         .channels_max           = 2,
1940         .buffer_bytes_max       = (64 * 1024),
1941         .period_bytes_min       = 1,
1942         .period_bytes_max       = DBRI_TD_MAXCNT,
1943         .periods_min            = 1,
1944         .periods_max            = 1024,
1945 };
1946
1947 static int snd_hw_rule_format(struct snd_pcm_hw_params *params,
1948                               struct snd_pcm_hw_rule *rule)
1949 {
1950         struct snd_interval *c = hw_param_interval(params,
1951                                 SNDRV_PCM_HW_PARAM_CHANNELS);
1952         struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1953         struct snd_mask fmt;
1954
1955         snd_mask_any(&fmt);
1956         if (c->min > 1) {
1957                 fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_BE;
1958                 return snd_mask_refine(f, &fmt);
1959         }
1960         return 0;
1961 }
1962
1963 static int snd_hw_rule_channels(struct snd_pcm_hw_params *params,
1964                                 struct snd_pcm_hw_rule *rule)
1965 {
1966         struct snd_interval *c = hw_param_interval(params,
1967                                 SNDRV_PCM_HW_PARAM_CHANNELS);
1968         struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
1969         struct snd_interval ch;
1970
1971         snd_interval_any(&ch);
1972         if (!(f->bits[0] & SNDRV_PCM_FMTBIT_S16_BE)) {
1973                 ch.min = ch.max = 1;
1974                 ch.integer = 1;
1975                 return snd_interval_refine(c, &ch);
1976         }
1977         return 0;
1978 }
1979
1980 static int snd_dbri_open(struct snd_pcm_substream *substream)
1981 {
1982         struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
1983         struct snd_pcm_runtime *runtime = substream->runtime;
1984         struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
1985         unsigned long flags;
1986
1987         dprintk(D_USR, "open audio output.\n");
1988         runtime->hw = snd_dbri_pcm_hw;
1989
1990         spin_lock_irqsave(&dbri->lock, flags);
1991         info->substream = substream;
1992         info->offset = 0;
1993         info->dvma_buffer = 0;
1994         info->pipe = -1;
1995         spin_unlock_irqrestore(&dbri->lock, flags);
1996
1997         snd_pcm_hw_rule_add(runtime,0,SNDRV_PCM_HW_PARAM_CHANNELS,
1998                             snd_hw_rule_format, 0, SNDRV_PCM_HW_PARAM_FORMAT,
1999                             -1);
2000         snd_pcm_hw_rule_add(runtime,0,SNDRV_PCM_HW_PARAM_FORMAT,
2001                             snd_hw_rule_channels, 0, 
2002                             SNDRV_PCM_HW_PARAM_CHANNELS,
2003                             -1);
2004                                 
2005         cs4215_open(dbri);
2006
2007         return 0;
2008 }
2009
2010 static int snd_dbri_close(struct snd_pcm_substream *substream)
2011 {
2012         struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
2013         struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
2014
2015         dprintk(D_USR, "close audio output.\n");
2016         info->substream = NULL;
2017         info->offset = 0;
2018
2019         return 0;
2020 }
2021
2022 static int snd_dbri_hw_params(struct snd_pcm_substream *substream,
2023                               struct snd_pcm_hw_params *hw_params)
2024 {
2025         struct snd_pcm_runtime *runtime = substream->runtime;
2026         struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
2027         struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
2028         int direction;
2029         int ret;
2030
2031         /* set sampling rate, audio format and number of channels */
2032         ret = cs4215_prepare(dbri, params_rate(hw_params),
2033                              params_format(hw_params),
2034                              params_channels(hw_params));
2035         if (ret != 0)
2036                 return ret;
2037
2038         if ((ret = snd_pcm_lib_malloc_pages(substream,
2039                                 params_buffer_bytes(hw_params))) < 0) {
2040                 printk(KERN_ERR "malloc_pages failed with %d\n", ret);
2041                 return ret;
2042         }
2043
2044         /* hw_params can get called multiple times. Only map the DMA once.
2045          */
2046         if (info->dvma_buffer == 0) {
2047                 if (DBRI_STREAMNO(substream) == DBRI_PLAY)
2048                         direction = SBUS_DMA_TODEVICE;
2049                 else
2050                         direction = SBUS_DMA_FROMDEVICE;
2051
2052                 info->dvma_buffer = sbus_map_single(dbri->sdev,
2053                                         runtime->dma_area,
2054                                         params_buffer_bytes(hw_params),
2055                                         direction);
2056         }
2057
2058         direction = params_buffer_bytes(hw_params);
2059         dprintk(D_USR, "hw_params: %d bytes, dvma=%x\n",
2060                 direction, info->dvma_buffer);
2061         return 0;
2062 }
2063
2064 static int snd_dbri_hw_free(struct snd_pcm_substream *substream)
2065 {
2066         struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
2067         struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
2068         int direction;
2069
2070         dprintk(D_USR, "hw_free.\n");
2071
2072         /* hw_free can get called multiple times. Only unmap the DMA once.
2073          */
2074         if (info->dvma_buffer) {
2075                 if (DBRI_STREAMNO(substream) == DBRI_PLAY)
2076                         direction = SBUS_DMA_TODEVICE;
2077                 else
2078                         direction = SBUS_DMA_FROMDEVICE;
2079
2080                 sbus_unmap_single(dbri->sdev, info->dvma_buffer,
2081                                   substream->runtime->buffer_size, direction);
2082                 info->dvma_buffer = 0;
2083         }
2084         if (info->pipe != -1) {
2085                 reset_pipe(dbri, info->pipe);
2086                 info->pipe = -1;
2087         }
2088
2089         return snd_pcm_lib_free_pages(substream);
2090 }
2091
2092 static int snd_dbri_prepare(struct snd_pcm_substream *substream)
2093 {
2094         struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
2095         struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
2096         struct snd_pcm_runtime *runtime = substream->runtime;
2097         int ret;
2098
2099         info->size = snd_pcm_lib_buffer_bytes(substream);
2100         if (DBRI_STREAMNO(substream) == DBRI_PLAY)
2101                 info->pipe = 4; /* Send pipe */
2102         else
2103                 info->pipe = 6; /* Receive pipe */
2104
2105         spin_lock_irq(&dbri->lock);
2106         info->offset = 0;
2107
2108         /* Setup the all the transmit/receive desciptors to cover the
2109          * whole DMA buffer.
2110          */
2111         ret = setup_descs(dbri, DBRI_STREAMNO(substream),
2112                           snd_pcm_lib_period_bytes(substream));
2113
2114         runtime->stop_threshold = DBRI_TD_MAXCNT / runtime->channels;
2115
2116         spin_unlock_irq(&dbri->lock);
2117
2118         dprintk(D_USR, "prepare audio output. %d bytes\n", info->size);
2119         return ret;
2120 }
2121
2122 static int snd_dbri_trigger(struct snd_pcm_substream *substream, int cmd)
2123 {
2124         struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
2125         struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
2126         int ret = 0;
2127
2128         switch (cmd) {
2129         case SNDRV_PCM_TRIGGER_START:
2130                 dprintk(D_USR, "start audio, period is %d bytes\n",
2131                         (int)snd_pcm_lib_period_bytes(substream));
2132                 /* Re-submit the TDs. */
2133                 xmit_descs(dbri);
2134                 break;
2135         case SNDRV_PCM_TRIGGER_STOP:
2136                 dprintk(D_USR, "stop audio.\n");
2137                 reset_pipe(dbri, info->pipe);
2138                 break;
2139         default:
2140                 ret = -EINVAL;
2141         }
2142
2143         return ret;
2144 }
2145
2146 static snd_pcm_uframes_t snd_dbri_pointer(struct snd_pcm_substream *substream)
2147 {
2148         struct snd_dbri *dbri = snd_pcm_substream_chip(substream);
2149         struct dbri_streaminfo *info = DBRI_STREAM(dbri, substream);
2150         snd_pcm_uframes_t ret;
2151
2152         ret = bytes_to_frames(substream->runtime, info->offset)
2153                 % substream->runtime->buffer_size;
2154         dprintk(D_USR, "I/O pointer: %ld frames of %ld.\n",
2155                 ret, substream->runtime->buffer_size);
2156         return ret;
2157 }
2158
2159 static struct snd_pcm_ops snd_dbri_ops = {
2160         .open = snd_dbri_open,
2161         .close = snd_dbri_close,
2162         .ioctl = snd_pcm_lib_ioctl,
2163         .hw_params = snd_dbri_hw_params,
2164         .hw_free = snd_dbri_hw_free,
2165         .prepare = snd_dbri_prepare,
2166         .trigger = snd_dbri_trigger,
2167         .pointer = snd_dbri_pointer,
2168 };
2169
2170 static int __devinit snd_dbri_pcm(struct snd_dbri * dbri)
2171 {
2172         struct snd_pcm *pcm;
2173         int err;
2174
2175         if ((err = snd_pcm_new(dbri->card,
2176                                /* ID */             "sun_dbri",
2177                                /* device */         0,
2178                                /* playback count */ 1,
2179                                /* capture count */  1, &pcm)) < 0)
2180                 return err;
2181         snd_assert(pcm != NULL, return -EINVAL);
2182
2183         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_dbri_ops);
2184         snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_dbri_ops);
2185
2186         pcm->private_data = dbri;
2187         pcm->info_flags = 0;
2188         strcpy(pcm->name, dbri->card->shortname);
2189
2190         if ((err = snd_pcm_lib_preallocate_pages_for_all(pcm,
2191                         SNDRV_DMA_TYPE_CONTINUOUS,
2192                         snd_dma_continuous_data(GFP_KERNEL),
2193                         64 * 1024, 64 * 1024)) < 0) {
2194                 return err;
2195         }
2196
2197         return 0;
2198 }
2199
2200 /*****************************************************************************
2201                         Mixer interface
2202 *****************************************************************************/
2203
2204 static int snd_cs4215_info_volume(struct snd_kcontrol *kcontrol,
2205                                   struct snd_ctl_elem_info *uinfo)
2206 {
2207         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
2208         uinfo->count = 2;
2209         uinfo->value.integer.min = 0;
2210         if (kcontrol->private_value == DBRI_PLAY) {
2211                 uinfo->value.integer.max = DBRI_MAX_VOLUME;
2212         } else {
2213                 uinfo->value.integer.max = DBRI_MAX_GAIN;
2214         }
2215         return 0;
2216 }
2217
2218 static int snd_cs4215_get_volume(struct snd_kcontrol *kcontrol,
2219                                  struct snd_ctl_elem_value *ucontrol)
2220 {
2221         struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
2222         struct dbri_streaminfo *info;
2223         snd_assert(dbri != NULL, return -EINVAL);
2224         info = &dbri->stream_info[kcontrol->private_value];
2225         snd_assert(info != NULL, return -EINVAL);
2226
2227         ucontrol->value.integer.value[0] = info->left_gain;
2228         ucontrol->value.integer.value[1] = info->right_gain;
2229         return 0;
2230 }
2231
2232 static int snd_cs4215_put_volume(struct snd_kcontrol *kcontrol,
2233                                  struct snd_ctl_elem_value *ucontrol)
2234 {
2235         struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
2236         struct dbri_streaminfo *info = &dbri->stream_info[kcontrol->private_value];
2237         unsigned long flags;
2238         int changed = 0;
2239
2240         if (info->left_gain != ucontrol->value.integer.value[0]) {
2241                 info->left_gain = ucontrol->value.integer.value[0];
2242                 changed = 1;
2243         }
2244         if (info->right_gain != ucontrol->value.integer.value[1]) {
2245                 info->right_gain = ucontrol->value.integer.value[1];
2246                 changed = 1;
2247         }
2248         if (changed == 1) {
2249                 /* First mute outputs, and wait 1/8000 sec (125 us)
2250                  * to make sure this takes.  This avoids clicking noises.
2251                  */
2252                 spin_lock_irqsave(&dbri->lock, flags);
2253
2254                 cs4215_setdata(dbri, 1);
2255                 udelay(125);
2256                 cs4215_setdata(dbri, 0);
2257
2258                 spin_unlock_irqrestore(&dbri->lock, flags);
2259         }
2260         return changed;
2261 }
2262
2263 static int snd_cs4215_info_single(struct snd_kcontrol *kcontrol,
2264                                   struct snd_ctl_elem_info *uinfo)
2265 {
2266         int mask = (kcontrol->private_value >> 16) & 0xff;
2267
2268         uinfo->type = (mask == 1) ?
2269             SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
2270         uinfo->count = 1;
2271         uinfo->value.integer.min = 0;
2272         uinfo->value.integer.max = mask;
2273         return 0;
2274 }
2275
2276 static int snd_cs4215_get_single(struct snd_kcontrol *kcontrol,
2277                                  struct snd_ctl_elem_value *ucontrol)
2278 {
2279         struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
2280         int elem = kcontrol->private_value & 0xff;
2281         int shift = (kcontrol->private_value >> 8) & 0xff;
2282         int mask = (kcontrol->private_value >> 16) & 0xff;
2283         int invert = (kcontrol->private_value >> 24) & 1;
2284         snd_assert(dbri != NULL, return -EINVAL);
2285
2286         if (elem < 4) {
2287                 ucontrol->value.integer.value[0] =
2288                     (dbri->mm.data[elem] >> shift) & mask;
2289         } else {
2290                 ucontrol->value.integer.value[0] =
2291                     (dbri->mm.ctrl[elem - 4] >> shift) & mask;
2292         }
2293
2294         if (invert == 1) {
2295                 ucontrol->value.integer.value[0] =
2296                     mask - ucontrol->value.integer.value[0];
2297         }
2298         return 0;
2299 }
2300
2301 static int snd_cs4215_put_single(struct snd_kcontrol *kcontrol,
2302                                  struct snd_ctl_elem_value *ucontrol)
2303 {
2304         struct snd_dbri *dbri = snd_kcontrol_chip(kcontrol);
2305         unsigned long flags;
2306         int elem = kcontrol->private_value & 0xff;
2307         int shift = (kcontrol->private_value >> 8) & 0xff;
2308         int mask = (kcontrol->private_value >> 16) & 0xff;
2309         int invert = (kcontrol->private_value >> 24) & 1;
2310         int changed = 0;
2311         unsigned short val;
2312         snd_assert(dbri != NULL, return -EINVAL);
2313
2314         val = (ucontrol->value.integer.value[0] & mask);
2315         if (invert == 1)
2316                 val = mask - val;
2317         val <<= shift;
2318
2319         if (elem < 4) {
2320                 dbri->mm.data[elem] = (dbri->mm.data[elem] &
2321                                        ~(mask << shift)) | val;
2322                 changed = (val != dbri->mm.data[elem]);
2323         } else {
2324                 dbri->mm.ctrl[elem - 4] = (dbri->mm.ctrl[elem - 4] &
2325                                            ~(mask << shift)) | val;
2326                 changed = (val != dbri->mm.ctrl[elem - 4]);
2327         }
2328
2329         dprintk(D_GEN, "put_single: mask=0x%x, changed=%d, "
2330                 "mixer-value=%ld, mm-value=0x%x\n",
2331                 mask, changed, ucontrol->value.integer.value[0],
2332                 dbri->mm.data[elem & 3]);
2333
2334         if (changed) {
2335                 /* First mute outputs, and wait 1/8000 sec (125 us)
2336                  * to make sure this takes.  This avoids clicking noises.
2337                  */
2338                 spin_lock_irqsave(&dbri->lock, flags);
2339
2340                 cs4215_setdata(dbri, 1);
2341                 udelay(125);
2342                 cs4215_setdata(dbri, 0);
2343
2344                 spin_unlock_irqrestore(&dbri->lock, flags);
2345         }
2346         return changed;
2347 }
2348
2349 /* Entries 0-3 map to the 4 data timeslots, entries 4-7 map to the 4 control
2350    timeslots. Shift is the bit offset in the timeslot, mask defines the
2351    number of bits. invert is a boolean for use with attenuation.
2352  */
2353 #define CS4215_SINGLE(xname, entry, shift, mask, invert) \
2354 { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
2355   .info = snd_cs4215_info_single, \
2356   .get = snd_cs4215_get_single, .put = snd_cs4215_put_single, \
2357   .private_value = entry | (shift << 8) | (mask << 16) | (invert << 24) },
2358
2359 static struct snd_kcontrol_new dbri_controls[] __devinitdata = {
2360         {
2361          .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2362          .name  = "Playback Volume",
2363          .info  = snd_cs4215_info_volume,
2364          .get   = snd_cs4215_get_volume,
2365          .put   = snd_cs4215_put_volume,
2366          .private_value = DBRI_PLAY,
2367          },
2368         CS4215_SINGLE("Headphone switch", 0, 7, 1, 0)
2369         CS4215_SINGLE("Line out switch", 0, 6, 1, 0)
2370         CS4215_SINGLE("Speaker switch", 1, 6, 1, 0)
2371         {
2372          .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
2373          .name  = "Capture Volume",
2374          .info  = snd_cs4215_info_volume,
2375          .get   = snd_cs4215_get_volume,
2376          .put   = snd_cs4215_put_volume,
2377          .private_value = DBRI_REC,
2378          },
2379         /* FIXME: mic/line switch */
2380         CS4215_SINGLE("Line in switch", 2, 4, 1, 0)
2381         CS4215_SINGLE("High Pass Filter switch", 5, 7, 1, 0)
2382         CS4215_SINGLE("Monitor Volume", 3, 4, 0xf, 1)
2383         CS4215_SINGLE("Mic boost", 4, 4, 1, 1)
2384 };
2385
2386 #define NUM_CS4215_CONTROLS (sizeof(dbri_controls)/sizeof(struct snd_kcontrol_new))
2387
2388 static int __init snd_dbri_mixer(struct snd_dbri * dbri)
2389 {
2390         struct snd_card *card;
2391         int idx, err;
2392
2393         snd_assert(dbri != NULL && dbri->card != NULL, return -EINVAL);
2394
2395         card = dbri->card;
2396         strcpy(card->mixername, card->shortname);
2397
2398         for (idx = 0; idx < NUM_CS4215_CONTROLS; idx++) {
2399                 if ((err = snd_ctl_add(card,
2400                                 snd_ctl_new1(&dbri_controls[idx], dbri))) < 0)
2401                         return err;
2402         }
2403
2404         for (idx = DBRI_REC; idx < DBRI_NO_STREAMS; idx++) {
2405                 dbri->stream_info[idx].left_gain = 0;
2406                 dbri->stream_info[idx].right_gain = 0;
2407         }
2408
2409         return 0;
2410 }
2411
2412 /****************************************************************************
2413                         /proc interface
2414 ****************************************************************************/
2415 static void dbri_regs_read(struct snd_info_entry * entry, struct snd_info_buffer *buffer)
2416 {
2417         struct snd_dbri *dbri = entry->private_data;
2418
2419         snd_iprintf(buffer, "REG0: 0x%x\n", sbus_readl(dbri->regs + REG0));
2420         snd_iprintf(buffer, "REG2: 0x%x\n", sbus_readl(dbri->regs + REG2));
2421         snd_iprintf(buffer, "REG8: 0x%x\n", sbus_readl(dbri->regs + REG8));
2422         snd_iprintf(buffer, "REG9: 0x%x\n", sbus_readl(dbri->regs + REG9));
2423 }
2424
2425 #ifdef DBRI_DEBUG
2426 static void dbri_debug_read(struct snd_info_entry * entry,
2427                             struct snd_info_buffer *buffer)
2428 {
2429         struct snd_dbri *dbri = entry->private_data;
2430         int pipe;
2431         snd_iprintf(buffer, "debug=%d\n", dbri_debug);
2432
2433         for (pipe = 0; pipe < 32; pipe++) {
2434                 if (pipe_active(dbri, pipe)) {
2435                         struct dbri_pipe *pptr = &dbri->pipes[pipe];
2436                         snd_iprintf(buffer,
2437                                     "Pipe %d: %s SDP=0x%x desc=%d, "
2438                                     "len=%d next %d\n",
2439                                     pipe,
2440                                    ((pptr->sdp & D_SDP_TO_SER) ? "output" : "input"),
2441                                     pptr->sdp, pptr->desc,
2442                                     pptr->length, pptr->nextpipe);
2443                 }
2444         }
2445 }
2446 #endif
2447
2448 void snd_dbri_proc(struct snd_dbri * dbri)
2449 {
2450         struct snd_info_entry *entry;
2451
2452         if (! snd_card_proc_new(dbri->card, "regs", &entry))
2453                 snd_info_set_text_ops(entry, dbri, dbri_regs_read);
2454
2455 #ifdef DBRI_DEBUG
2456         if (! snd_card_proc_new(dbri->card, "debug", &entry)) {
2457                 snd_info_set_text_ops(entry, dbri, dbri_debug_read);
2458                 entry->mode = S_IFREG | S_IRUGO;        /* Readable only. */
2459         }
2460 #endif
2461 }
2462
2463 /*
2464 ****************************************************************************
2465 **************************** Initialization ********************************
2466 ****************************************************************************
2467 */
2468 static void snd_dbri_free(struct snd_dbri * dbri);
2469
2470 static int __init snd_dbri_create(struct snd_card *card,
2471                                   struct sbus_dev *sdev,
2472                                   struct linux_prom_irqs *irq, int dev)
2473 {
2474         struct snd_dbri *dbri = card->private_data;
2475         int err;
2476
2477         spin_lock_init(&dbri->lock);
2478         dbri->card = card;
2479         dbri->sdev = sdev;
2480         dbri->irq = irq->pri;
2481
2482         dbri->dma = sbus_alloc_consistent(sdev, sizeof(struct dbri_dma),
2483                                           &dbri->dma_dvma);
2484         memset((void *)dbri->dma, 0, sizeof(struct dbri_dma));
2485
2486         dprintk(D_GEN, "DMA Cmd Block 0x%p (0x%08x)\n",
2487                 dbri->dma, dbri->dma_dvma);
2488
2489         /* Map the registers into memory. */
2490         dbri->regs_size = sdev->reg_addrs[0].reg_size;
2491         dbri->regs = sbus_ioremap(&sdev->resource[0], 0,
2492                                   dbri->regs_size, "DBRI Registers");
2493         if (!dbri->regs) {
2494                 printk(KERN_ERR "DBRI: could not allocate registers\n");
2495                 sbus_free_consistent(sdev, sizeof(struct dbri_dma),
2496                                      (void *)dbri->dma, dbri->dma_dvma);
2497                 return -EIO;
2498         }
2499
2500         err = request_irq(dbri->irq, snd_dbri_interrupt, IRQF_SHARED,
2501                           "DBRI audio", dbri);
2502         if (err) {
2503                 printk(KERN_ERR "DBRI: Can't get irq %d\n", dbri->irq);
2504                 sbus_iounmap(dbri->regs, dbri->regs_size);
2505                 sbus_free_consistent(sdev, sizeof(struct dbri_dma),
2506                                      (void *)dbri->dma, dbri->dma_dvma);
2507                 return err;
2508         }
2509
2510         /* Do low level initialization of the DBRI and CS4215 chips */
2511         dbri_initialize(dbri);
2512         err = cs4215_init(dbri);
2513         if (err) {
2514                 snd_dbri_free(dbri);
2515                 return err;
2516         }
2517
2518         dbri->next = dbri_list;
2519         dbri_list = dbri;
2520
2521         return 0;
2522 }
2523
2524 static void snd_dbri_free(struct snd_dbri * dbri)
2525 {
2526         dprintk(D_GEN, "snd_dbri_free\n");
2527         dbri_reset(dbri);
2528
2529         if (dbri->irq)
2530                 free_irq(dbri->irq, dbri);
2531
2532         if (dbri->regs)
2533                 sbus_iounmap(dbri->regs, dbri->regs_size);
2534
2535         if (dbri->dma)
2536                 sbus_free_consistent(dbri->sdev, sizeof(struct dbri_dma),
2537                                      (void *)dbri->dma, dbri->dma_dvma);
2538 }
2539
2540 static int __init dbri_attach(int prom_node, struct sbus_dev *sdev)
2541 {
2542         struct snd_dbri *dbri;
2543         struct linux_prom_irqs irq;
2544         struct resource *rp;
2545         struct snd_card *card;
2546         static int dev = 0;
2547         int err;
2548
2549         if (sdev->prom_name[9] < 'e') {
2550                 printk(KERN_ERR "DBRI: unsupported chip version %c found.\n",
2551                        sdev->prom_name[9]);
2552                 return -EIO;
2553         }
2554
2555         if (dev >= SNDRV_CARDS)
2556                 return -ENODEV;
2557         if (!enable[dev]) {
2558                 dev++;
2559                 return -ENOENT;
2560         }
2561
2562         err = prom_getproperty(prom_node, "intr", (char *)&irq, sizeof(irq));
2563         if (err < 0) {
2564                 printk(KERN_ERR "DBRI-%d: Firmware node lacks IRQ property.\n", dev);
2565                 return -ENODEV;
2566         }
2567
2568         card = snd_card_new(index[dev], id[dev], THIS_MODULE,
2569                             sizeof(struct snd_dbri));
2570         if (card == NULL)
2571                 return -ENOMEM;
2572
2573         strcpy(card->driver, "DBRI");
2574         strcpy(card->shortname, "Sun DBRI");
2575         rp = &sdev->resource[0];
2576         sprintf(card->longname, "%s at 0x%02lx:0x%016Lx, irq %d",
2577                 card->shortname,
2578                 rp->flags & 0xffL, (unsigned long long)rp->start, irq.pri);
2579
2580         if ((err = snd_dbri_create(card, sdev, &irq, dev)) < 0) {
2581                 snd_card_free(card);
2582                 return err;
2583         }
2584
2585         dbri = card->private_data;
2586         if ((err = snd_dbri_pcm(dbri)) < 0)
2587                 goto _err;
2588
2589         if ((err = snd_dbri_mixer(dbri)) < 0)
2590                 goto _err;
2591
2592         /* /proc file handling */
2593         snd_dbri_proc(dbri);
2594
2595         if ((err = snd_card_register(card)) < 0)
2596                 goto _err;
2597
2598         printk(KERN_INFO "audio%d at %p (irq %d) is DBRI(%c)+CS4215(%d)\n",
2599                dev, dbri->regs,
2600                dbri->irq, sdev->prom_name[9], dbri->mm.version);
2601         dev++;
2602
2603         return 0;
2604
2605  _err:
2606         snd_dbri_free(dbri);
2607         snd_card_free(card);
2608         return err;
2609 }
2610
2611 /* Probe for the dbri chip and then attach the driver. */
2612 static int __init dbri_init(void)
2613 {
2614         struct sbus_bus *sbus;
2615         struct sbus_dev *sdev;
2616         int found = 0;
2617
2618         /* Probe each SBUS for the DBRI chip(s). */
2619         for_all_sbusdev(sdev, sbus) {
2620                 /*
2621                  * The version is coded in the last character
2622                  */
2623                 if (!strncmp(sdev->prom_name, "SUNW,DBRI", 9)) {
2624                         dprintk(D_GEN, "DBRI: Found %s in SBUS slot %d\n",
2625                                 sdev->prom_name, sdev->slot);
2626
2627                         if (dbri_attach(sdev->prom_node, sdev) == 0)
2628                                 found++;
2629                 }
2630         }
2631
2632         return (found > 0) ? 0 : -EIO;
2633 }
2634
2635 static void __exit dbri_exit(void)
2636 {
2637         struct snd_dbri *this = dbri_list;
2638
2639         while (this != NULL) {
2640                 struct snd_dbri *next = this->next;
2641                 struct snd_card *card = this->card;
2642
2643                 snd_dbri_free(this);
2644                 snd_card_free(card);
2645                 this = next;
2646         }
2647         dbri_list = NULL;
2648 }
2649
2650 module_init(dbri_init);
2651 module_exit(dbri_exit);