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