vserver 1.9.3
[linux-2.6.git] / sound / pci / korg1212 / korg1212.c
1 /*
2  *   Driver for the Korg 1212 IO PCI card
3  *
4  *      Copyright (c) 2001 Haroldo Gamal <gamal@alternex.com.br>
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19  *
20  */
21
22 #include <sound/driver.h>
23 #include <linux/delay.h>
24 #include <linux/init.h>
25 #include <linux/interrupt.h>
26 #include <linux/pci.h>
27 #include <linux/slab.h>
28 #include <linux/wait.h>
29 #include <linux/moduleparam.h>
30
31 #include <sound/core.h>
32 #include <sound/info.h>
33 #include <sound/control.h>
34 #include <sound/pcm.h>
35 #include <sound/pcm_params.h>
36 #include <sound/initval.h>
37
38 #include <asm/io.h>
39
40 // ----------------------------------------------------------------------------
41 // Debug Stuff
42 // ----------------------------------------------------------------------------
43 #define K1212_DEBUG_LEVEL               0
44 #define K1212_DEBUG_PRINTK              printk
45 //#define K1212_DEBUG_PRINTK(x...)      printk("<0>" x)
46
47 // ----------------------------------------------------------------------------
48 // Record/Play Buffer Allocation Method. If K1212_LARGEALLOC is defined all 
49 // buffers are alocated as a large piece inside KorgSharedBuffer.
50 // ----------------------------------------------------------------------------
51 //#define K1212_LARGEALLOC              1
52
53 // ----------------------------------------------------------------------------
54 // the following enum defines the valid states of the Korg 1212 I/O card.
55 // ----------------------------------------------------------------------------
56 typedef enum {
57    K1212_STATE_NONEXISTENT,             // there is no card here
58    K1212_STATE_UNINITIALIZED,           // the card is awaiting DSP download
59    K1212_STATE_DSP_IN_PROCESS,          // the card is currently downloading its DSP code
60    K1212_STATE_DSP_COMPLETE,            // the card has finished the DSP download
61    K1212_STATE_READY,                   // the card can be opened by an application.  Any application
62                                         //    requests prior to this state should fail.  Only an open
63                                         //    request can be made at this state.
64    K1212_STATE_OPEN,                    // an application has opened the card
65    K1212_STATE_SETUP,                   // the card has been setup for play
66    K1212_STATE_PLAYING,                 // the card is playing
67    K1212_STATE_MONITOR,                 // the card is in the monitor mode
68    K1212_STATE_CALIBRATING,             // the card is currently calibrating
69    K1212_STATE_ERRORSTOP,               // the card has stopped itself because of an error and we
70                                         //    are in the process of cleaning things up.
71    K1212_STATE_MAX_STATE                // state values of this and beyond are invalid
72 } CardState;
73
74 // ----------------------------------------------------------------------------
75 // The following enumeration defines the constants written to the card's
76 // host-to-card doorbell to initiate a command.
77 // ----------------------------------------------------------------------------
78 typedef enum {
79    K1212_DB_RequestForData        = 0,    // sent by the card to request a buffer fill.
80    K1212_DB_TriggerPlay           = 1,    // starts playback/record on the card.
81    K1212_DB_SelectPlayMode        = 2,    // select monitor, playback setup, or stop.
82    K1212_DB_ConfigureBufferMemory = 3,    // tells card where the host audio buffers are.
83    K1212_DB_RequestAdatTimecode   = 4,    // asks the card for the latest ADAT timecode value.
84    K1212_DB_SetClockSourceRate    = 5,    // sets the clock source and rate for the card.
85    K1212_DB_ConfigureMiscMemory   = 6,    // tells card where other buffers are.
86    K1212_DB_TriggerFromAdat       = 7,    // tells card to trigger from Adat at a specific
87                                           //    timecode value.
88    K1212_DB_RebootCard            = 0xA0, // instructs the card to reboot.
89    K1212_DB_BootFromDSPPage4      = 0xA4, // instructs the card to boot from the DSP microcode
90                                           //    on page 4 (local page to card).
91    K1212_DB_DSPDownloadDone       = 0xAE, // sent by the card to indicate the download has
92                                           //    completed.
93    K1212_DB_StartDSPDownload      = 0xAF  // tells the card to download its DSP firmware.
94 } korg1212_dbcnst_t;
95
96 #define K1212_ISRCODE_DMAERROR      0x80
97 #define K1212_ISRCODE_CARDSTOPPED   0x81
98
99 // ----------------------------------------------------------------------------
100 // The following enumeration defines return codes for DeviceIoControl() calls
101 // to the Korg 1212 I/O driver.
102 // ----------------------------------------------------------------------------
103 typedef enum {
104    K1212_CMDRET_Success         = 0,   // command was successfully placed
105    K1212_CMDRET_DIOCFailure,           // the DeviceIoControl call failed
106    K1212_CMDRET_PMFailure,             // the protected mode call failed
107    K1212_CMDRET_FailUnspecified,       // unspecified failure
108    K1212_CMDRET_FailBadState,          // the specified command can not be given in
109                                        //    the card's current state. (or the wave device's
110                                        //    state)
111    K1212_CMDRET_CardUninitialized,     // the card is uninitialized and cannot be used
112    K1212_CMDRET_BadIndex,              // an out of range card index was specified
113    K1212_CMDRET_BadHandle,             // an invalid card handle was specified
114    K1212_CMDRET_NoFillRoutine,         // a play request has been made before a fill routine set
115    K1212_CMDRET_FillRoutineInUse,      // can't set a new fill routine while one is in use
116    K1212_CMDRET_NoAckFromCard,         // the card never acknowledged a command
117    K1212_CMDRET_BadParams,             // bad parameters were provided by the caller
118
119    // --------------------------------------------------------------
120    // the following return errors are specific to the wave device
121    // driver interface.  These will not be encountered by users of
122    // the 32 bit DIOC interface (a.k.a. custom or native API).
123    // --------------------------------------------------------------
124    K1212_CMDRET_BadDevice,             // the specified wave device was out of range
125    K1212_CMDRET_BadFormat              // the specified wave format is unsupported
126 } snd_korg1212rc;
127
128 // ----------------------------------------------------------------------------
129 // The following enumeration defines the constants used to select the play
130 // mode for the card in the SelectPlayMode command.
131 // ----------------------------------------------------------------------------
132 typedef enum {
133    K1212_MODE_SetupPlay  = 0x00000001,     // provides card with pre-play information
134    K1212_MODE_MonitorOn  = 0x00000002,     // tells card to turn on monitor mode
135    K1212_MODE_MonitorOff = 0x00000004,     // tells card to turn off monitor mode
136    K1212_MODE_StopPlay   = 0x00000008      // stops playback on the card
137 } PlayModeSelector;
138
139 // ----------------------------------------------------------------------------
140 // The following enumeration defines the constants used to select the monitor
141 // mode for the card in the SetMonitorMode command.
142 // ----------------------------------------------------------------------------
143 typedef enum {
144    K1212_MONMODE_Off  = 0,     // tells card to turn off monitor mode
145    K1212_MONMODE_On            // tells card to turn on monitor mode
146 } MonitorModeSelector;
147
148 #define MAILBOX0_OFFSET      0x40       // location of mailbox 0 relative to base address
149 #define MAILBOX1_OFFSET      0x44       // location of mailbox 1 relative to base address
150 #define MAILBOX2_OFFSET      0x48       // location of mailbox 2 relative to base address
151 #define MAILBOX3_OFFSET      0x4c       // location of mailbox 3 relative to base address
152 #define OUT_DOORBELL_OFFSET  0x60       // location of PCI to local doorbell
153 #define IN_DOORBELL_OFFSET   0x64       // location of local to PCI doorbell
154 #define STATUS_REG_OFFSET    0x68       // location of interrupt control/status register
155 #define PCI_CONTROL_OFFSET   0x6c       // location of the EEPROM, PCI, User I/O, init control
156                                         //    register
157 #define SENS_CONTROL_OFFSET  0x6e       // location of the input sensitivity setting register.
158                                         //    this is the upper word of the PCI control reg.
159 #define DEV_VEND_ID_OFFSET   0x70       // location of the device and vendor ID register
160
161 #define COMMAND_ACK_DELAY    13        // number of RTC ticks to wait for an acknowledgement
162                                         //    from the card after sending a command.
163 #define INTERCOMMAND_DELAY   40
164 #define MAX_COMMAND_RETRIES  5         // maximum number of times the driver will attempt
165                                        //    to send a command before giving up.
166 #define COMMAND_ACK_MASK     0x8000    // the MSB is set in the command acknowledgment from
167                                         //    the card.
168 #define DOORBELL_VAL_MASK    0x00FF    // the doorbell value is one byte
169
170 #define CARD_BOOT_DELAY_IN_MS  10
171
172 #define DSP_BOOT_DELAY_IN_MS   200
173
174 #define kNumBuffers             8
175 #define k1212MaxCards           4
176 #define k1212NumWaveDevices     6
177 #define k16BitChannels          10
178 #define k32BitChannels          2
179 #define kAudioChannels          (k16BitChannels + k32BitChannels)
180 #define kPlayBufferFrames       1024
181
182 #define K1212_ANALOG_CHANNELS   2
183 #define K1212_SPDIF_CHANNELS    2
184 #define K1212_ADAT_CHANNELS     8
185 #define K1212_CHANNELS          (K1212_ADAT_CHANNELS + K1212_ANALOG_CHANNELS)
186 #define K1212_MIN_CHANNELS      1
187 #define K1212_MAX_CHANNELS      K1212_CHANNELS
188 #define K1212_FRAME_SIZE        (sizeof(KorgAudioFrame))
189 #define K1212_MAX_SAMPLES       (kPlayBufferFrames*kNumBuffers)
190 #define K1212_PERIODS           (kNumBuffers)
191 #define K1212_PERIOD_BYTES      (K1212_FRAME_SIZE*kPlayBufferFrames)
192 #define K1212_BUF_SIZE          (K1212_PERIOD_BYTES*kNumBuffers)
193 #define K1212_ANALOG_BUF_SIZE   (K1212_ANALOG_CHANNELS * 2 * kPlayBufferFrames * kNumBuffers)
194 #define K1212_SPDIF_BUF_SIZE    (K1212_SPDIF_CHANNELS * 3 * kPlayBufferFrames * kNumBuffers)
195 #define K1212_ADAT_BUF_SIZE     (K1212_ADAT_CHANNELS * 2 * kPlayBufferFrames * kNumBuffers)
196 #define K1212_MAX_BUF_SIZE      (K1212_ANALOG_BUF_SIZE + K1212_ADAT_BUF_SIZE)
197
198 #define k1212MinADCSens     0x7f
199 #define k1212MaxADCSens     0x00
200 #define k1212MaxVolume      0x7fff
201 #define k1212MaxWaveVolume  0xffff
202 #define k1212MinVolume      0x0000
203 #define k1212MaxVolInverted 0x8000
204
205 // -----------------------------------------------------------------
206 // the following bits are used for controlling interrupts in the
207 // interrupt control/status reg
208 // -----------------------------------------------------------------
209 #define  PCI_INT_ENABLE_BIT               0x00000100
210 #define  PCI_DOORBELL_INT_ENABLE_BIT      0x00000200
211 #define  LOCAL_INT_ENABLE_BIT             0x00010000
212 #define  LOCAL_DOORBELL_INT_ENABLE_BIT    0x00020000
213 #define  LOCAL_DMA1_INT_ENABLE_BIT        0x00080000
214
215 // -----------------------------------------------------------------
216 // the following bits are defined for the PCI command register
217 // -----------------------------------------------------------------
218 #define  PCI_CMD_MEM_SPACE_ENABLE_BIT     0x0002
219 #define  PCI_CMD_IO_SPACE_ENABLE_BIT      0x0001
220 #define  PCI_CMD_BUS_MASTER_ENABLE_BIT    0x0004
221
222 // -----------------------------------------------------------------
223 // the following bits are defined for the PCI status register
224 // -----------------------------------------------------------------
225 #define  PCI_STAT_PARITY_ERROR_BIT        0x8000
226 #define  PCI_STAT_SYSTEM_ERROR_BIT        0x4000
227 #define  PCI_STAT_MASTER_ABORT_RCVD_BIT   0x2000
228 #define  PCI_STAT_TARGET_ABORT_RCVD_BIT   0x1000
229 #define  PCI_STAT_TARGET_ABORT_SENT_BIT   0x0800
230
231 // ------------------------------------------------------------------------
232 // the following constants are used in setting the 1212 I/O card's input
233 // sensitivity.
234 // ------------------------------------------------------------------------
235 #define  SET_SENS_LOCALINIT_BITPOS        15
236 #define  SET_SENS_DATA_BITPOS             10
237 #define  SET_SENS_CLOCK_BITPOS            8
238 #define  SET_SENS_LOADSHIFT_BITPOS        0
239
240 #define  SET_SENS_LEFTCHANID              0x00
241 #define  SET_SENS_RIGHTCHANID             0x01
242
243 #define  K1212SENSUPDATE_DELAY_IN_MS      50
244
245 // --------------------------------------------------------------------------
246 // WaitRTCTicks
247 //
248 //    This function waits the specified number of real time clock ticks.
249 //    According to the DDK, each tick is ~0.8 microseconds.
250 //    The defines following the function declaration can be used for the
251 //    numTicksToWait parameter.
252 // --------------------------------------------------------------------------
253 #define ONE_RTC_TICK         1
254 #define SENSCLKPULSE_WIDTH   4
255 #define LOADSHIFT_DELAY      4
256 #define INTERCOMMAND_DELAY  40
257 #define STOPCARD_DELAY      300        // max # RTC ticks for the card to stop once we write
258                                        //    the command register.  (could be up to 180 us)
259 #define COMMAND_ACK_DELAY   13         // number of RTC ticks to wait for an acknowledgement
260                                        //    from the card after sending a command.
261
262 #include "korg1212-firmware.h"
263
264 typedef struct _snd_korg1212 korg1212_t;
265
266 typedef u16 K1212Sample;          // channels 0-9 use 16 bit samples
267 typedef u32 K1212SpdifSample;     // channels 10-11 use 32 bits - only 20 are sent
268                                   //  across S/PDIF.
269 typedef u32 K1212TimeCodeSample;  // holds the ADAT timecode value
270
271 typedef enum {
272    K1212_CLKIDX_AdatAt44_1K = 0,    // selects source as ADAT at 44.1 kHz
273    K1212_CLKIDX_AdatAt48K,          // selects source as ADAT at 48 kHz
274    K1212_CLKIDX_WordAt44_1K,        // selects source as S/PDIF at 44.1 kHz
275    K1212_CLKIDX_WordAt48K,          // selects source as S/PDIF at 48 kHz
276    K1212_CLKIDX_LocalAt44_1K,       // selects source as local clock at 44.1 kHz
277    K1212_CLKIDX_LocalAt48K,         // selects source as local clock at 48 kHz
278    K1212_CLKIDX_Invalid             // used to check validity of the index
279 } ClockSourceIndex;
280
281 typedef enum {
282    K1212_CLKIDX_Adat = 0,    // selects source as ADAT
283    K1212_CLKIDX_Word,        // selects source as S/PDIF
284    K1212_CLKIDX_Local        // selects source as local clock
285 } ClockSourceType;
286
287 typedef struct KorgAudioFrame {
288    K1212Sample          frameData16[k16BitChannels];
289    K1212SpdifSample     frameData32[k32BitChannels];
290    K1212TimeCodeSample  timeCodeVal;
291 } KorgAudioFrame;
292
293 typedef struct KorgAudioBuffer {
294    KorgAudioFrame  bufferData[kPlayBufferFrames];     /* buffer definition */
295 } KorgAudioBuffer;
296
297 typedef struct KorgSharedBuffer {
298 #ifdef K1212_LARGEALLOC
299    KorgAudioBuffer   playDataBufs[kNumBuffers];
300    KorgAudioBuffer   recordDataBufs[kNumBuffers];
301 #endif
302    short             volumeData[kAudioChannels];
303    u32               cardCommand;
304    u16               routeData [kAudioChannels];
305    u32               AdatTimeCode;                 // ADAT timecode value
306 } KorgSharedBuffer;
307
308 typedef struct SensBits {
309    union {
310       struct {
311          unsigned int leftChanVal:8;
312          unsigned int leftChanId:8;
313       } v;
314       u16  leftSensBits;
315    } l;
316    union {
317       struct {
318          unsigned int rightChanVal:8;
319          unsigned int rightChanId:8;
320       } v;
321       u16  rightSensBits;
322    } r;
323 } SensBits;
324
325 struct _snd_korg1212 {
326         snd_card_t *card;
327         struct pci_dev *pci;
328         snd_pcm_t *pcm;
329         int irq;
330
331         spinlock_t    lock;
332         struct semaphore open_mutex;
333
334         struct timer_list timer;        /* timer callback for checking ack of stop request */
335         int stop_pending_cnt;           /* counter for stop pending check */
336
337         wait_queue_head_t wait;
338
339         unsigned long iomem;
340         unsigned long ioport;
341         unsigned long iomem2;
342         unsigned long irqcount;
343         unsigned long inIRQ;
344         unsigned long iobase;
345
346         struct snd_dma_buffer dma_dsp;
347         struct snd_dma_buffer dma_play;
348         struct snd_dma_buffer dma_rec;
349         struct snd_dma_buffer dma_shared;
350
351         u32 dspCodeSize;
352
353         u32 DataBufsSize;
354
355         KorgAudioBuffer  * playDataBufsPtr;
356         KorgAudioBuffer  * recordDataBufsPtr;
357
358         KorgSharedBuffer * sharedBufferPtr;
359
360         u32 RecDataPhy;
361         u32 PlayDataPhy;
362         unsigned long sharedBufferPhy;
363         u32 VolumeTablePhy;
364         u32 RoutingTablePhy;
365         u32 AdatTimeCodePhy;
366
367         u32 * statusRegPtr;          // address of the interrupt status/control register
368         u32 * outDoorbellPtr;        // address of the host->card doorbell register
369         u32 * inDoorbellPtr;         // address of the card->host doorbell register
370         u32 * mailbox0Ptr;           // address of mailbox 0 on the card
371         u32 * mailbox1Ptr;           // address of mailbox 1 on the card
372         u32 * mailbox2Ptr;           // address of mailbox 2 on the card
373         u32 * mailbox3Ptr;           // address of mailbox 3 on the card
374         u32 * controlRegPtr;         // address of the EEPROM, PCI, I/O, Init ctrl reg
375         u16 * sensRegPtr;            // address of the sensitivity setting register
376         u32 * idRegPtr;              // address of the device and vendor ID registers
377
378         size_t periodsize;
379         int channels;
380         int currentBuffer;
381
382         snd_pcm_substream_t *playback_substream;
383         snd_pcm_substream_t *capture_substream;
384
385         CardState cardState;
386         int running;
387         int idleMonitorOn;           // indicates whether the card is in idle monitor mode.
388         u32 cmdRetryCount;           // tracks how many times we have retried sending to the card.
389
390         ClockSourceIndex clkSrcRate; // sample rate and clock source
391
392         ClockSourceType clkSource;   // clock source
393         int clkRate;                 // clock rate
394
395         int volumePhase[kAudioChannels];
396
397         u16 leftADCInSens;           // ADC left channel input sensitivity
398         u16 rightADCInSens;          // ADC right channel input sensitivity
399
400         int opencnt;                    // Open/Close count
401         int setcnt;                     // SetupForPlay count
402         int playcnt;                    // TriggerPlay count
403
404 };
405
406 MODULE_DESCRIPTION("korg1212");
407 MODULE_LICENSE("GPL");
408 MODULE_SUPPORTED_DEVICE("{{KORG,korg1212}}");
409
410 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;     /* Index 0-MAX */
411 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;          /* ID for this card */
412 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */
413 static int boot_devs;
414
415 module_param_array(index, int, boot_devs, 0444);
416 MODULE_PARM_DESC(index, "Index value for Korg 1212 soundcard.");
417 module_param_array(id, charp, boot_devs, 0444);
418 MODULE_PARM_DESC(id, "ID string for Korg 1212 soundcard.");
419 module_param_array(enable, bool, boot_devs, 0444);
420 MODULE_PARM_DESC(enable, "Enable Korg 1212 soundcard.");
421 MODULE_AUTHOR("Haroldo Gamal <gamal@alternex.com.br>");
422
423 static struct pci_device_id snd_korg1212_ids[] = {
424         {
425                 .vendor    = 0x10b5,
426                 .device    = 0x906d,
427                 .subvendor = PCI_ANY_ID,
428                 .subdevice = PCI_ANY_ID,
429         },
430         { 0, },
431 };
432
433 static char* stateName[] = {
434                         "Non-existent",
435                         "Uninitialized",
436                         "DSP download in process",
437                         "DSP download complete",
438                         "Ready",
439                         "Open",
440                         "Setup for play",
441                         "Playing",
442                         "Monitor mode on",
443                         "Calibrating"
444                         "Invalid"
445 };
446
447 static char* clockSourceTypeName[] = { "ADAT", "S/PDIF", "local" };
448
449 static char* clockSourceName[] = {
450                         "ADAT at 44.1 kHz",
451                         "ADAT at 48 kHz",
452                         "S/PDIF at 44.1 kHz",
453                         "S/PDIF at 48 kHz",
454                         "local clock at 44.1 kHz",
455                         "local clock at 48 kHz"
456 };
457
458 static char* channelName[] = {
459                         "ADAT-1",
460                         "ADAT-2",
461                         "ADAT-3",
462                         "ADAT-4",
463                         "ADAT-5",
464                         "ADAT-6",
465                         "ADAT-7",
466                         "ADAT-8",
467                         "Analog-L",
468                         "Analog-R",
469                         "SPDIF-L",
470                         "SPDIF-R",
471 };
472
473 u16 ClockSourceSelector[] = {0x8000,   // selects source as ADAT at 44.1 kHz
474                              0x0000,   // selects source as ADAT at 48 kHz
475                              0x8001,   // selects source as S/PDIF at 44.1 kHz
476                              0x0001,   // selects source as S/PDIF at 48 kHz
477                              0x8002,   // selects source as local clock at 44.1 kHz
478                              0x0002    // selects source as local clock at 48 kHz
479                             };
480
481 static snd_korg1212rc rc;
482
483 MODULE_DEVICE_TABLE(pci, snd_korg1212_ids);
484
485 typedef union swap_u32 { unsigned char c[4]; u32 i; } swap_u32;
486
487 #ifdef SNDRV_BIG_ENDIAN
488 static u32 LowerWordSwap(u32 swappee)
489 #else
490 static u32 UpperWordSwap(u32 swappee)
491 #endif
492 {
493    swap_u32 retVal, swapper;
494
495    swapper.i = swappee;
496    retVal.c[2] = swapper.c[3];
497    retVal.c[3] = swapper.c[2];
498    retVal.c[1] = swapper.c[1];
499    retVal.c[0] = swapper.c[0];
500
501    return retVal.i;
502 }
503
504 #ifdef SNDRV_BIG_ENDIAN
505 static u32 UpperWordSwap(u32 swappee)
506 #else
507 static u32 LowerWordSwap(u32 swappee)
508 #endif
509 {
510    swap_u32 retVal, swapper;
511
512    swapper.i = swappee;
513    retVal.c[2] = swapper.c[2];
514    retVal.c[3] = swapper.c[3];
515    retVal.c[1] = swapper.c[0];
516    retVal.c[0] = swapper.c[1];
517
518    return retVal.i;
519 }
520
521 #if 0 /* not used */
522
523 static u32 EndianSwap(u32 swappee)
524 {
525    swap_u32 retVal, swapper;
526
527    swapper.i = swappee;
528    retVal.c[0] = swapper.c[3];
529    retVal.c[1] = swapper.c[2];
530    retVal.c[2] = swapper.c[1];
531    retVal.c[3] = swapper.c[0];
532
533    return retVal.i;
534 }
535
536 #endif /* not used */
537
538 #define SetBitInWord(theWord,bitPosition)       (*theWord) |= (0x0001 << bitPosition)
539 #define SetBitInDWord(theWord,bitPosition)      (*theWord) |= (0x00000001 << bitPosition)
540 #define ClearBitInWord(theWord,bitPosition)     (*theWord) &= ~(0x0001 << bitPosition)
541 #define ClearBitInDWord(theWord,bitPosition)    (*theWord) &= ~(0x00000001 << bitPosition)
542
543 static snd_korg1212rc snd_korg1212_Send1212Command(korg1212_t *korg1212, korg1212_dbcnst_t doorbellVal,
544                             u32 mailBox0Val, u32 mailBox1Val, u32 mailBox2Val, u32 mailBox3Val)
545 {
546         u32 retryCount;
547         u16 mailBox3Lo;
548         snd_korg1212rc rc = K1212_CMDRET_Success;
549
550         if (!korg1212->outDoorbellPtr) {
551 #if K1212_DEBUG_LEVEL > 1
552                 K1212_DEBUG_PRINTK("K1212_DEBUG: CardUninitialized\n");
553 #endif
554                 return K1212_CMDRET_CardUninitialized;
555         }
556
557 #if K1212_DEBUG_LEVEL > 0
558         K1212_DEBUG_PRINTK("K1212_DEBUG: Card <- 0x%08x 0x%08x [%s]\n", doorbellVal, mailBox0Val, stateName[korg1212->cardState]);
559 #endif
560         for (retryCount = 0; retryCount < MAX_COMMAND_RETRIES; retryCount++) {
561                 writel(mailBox3Val, korg1212->mailbox3Ptr);
562                 writel(mailBox2Val, korg1212->mailbox2Ptr);
563                 writel(mailBox1Val, korg1212->mailbox1Ptr);
564                 writel(mailBox0Val, korg1212->mailbox0Ptr);
565                 writel(doorbellVal, korg1212->outDoorbellPtr);  // interrupt the card
566
567                 // --------------------------------------------------------------
568                 // the reboot command will not give an acknowledgement.
569                 // --------------------------------------------------------------
570                 if ( doorbellVal == K1212_DB_RebootCard ||
571                         doorbellVal == K1212_DB_BootFromDSPPage4 ||
572                         doorbellVal == K1212_DB_StartDSPDownload ) {
573                         rc = K1212_CMDRET_Success;
574                         break;
575                 }
576
577                 // --------------------------------------------------------------
578                 // See if the card acknowledged the command.  Wait a bit, then
579                 // read in the low word of mailbox3.  If the MSB is set and the
580                 // low byte is equal to the doorbell value, then it ack'd.
581                 // --------------------------------------------------------------
582                 udelay(COMMAND_ACK_DELAY);
583                 mailBox3Lo = readl(korg1212->mailbox3Ptr);
584                 if (mailBox3Lo & COMMAND_ACK_MASK) {
585                         if ((mailBox3Lo & DOORBELL_VAL_MASK) == (doorbellVal & DOORBELL_VAL_MASK)) {
586 #if K1212_DEBUG_LEVEL > 1
587                                 K1212_DEBUG_PRINTK("K1212_DEBUG: Card <- Success\n");
588 #endif
589                                 rc = K1212_CMDRET_Success;
590                                 break;
591                         }
592                 }
593         }
594         korg1212->cmdRetryCount += retryCount;
595
596         if (retryCount >= MAX_COMMAND_RETRIES) {
597 #if K1212_DEBUG_LEVEL > 1
598                 K1212_DEBUG_PRINTK("K1212_DEBUG: Card <- NoAckFromCard\n");
599 #endif
600                 rc = K1212_CMDRET_NoAckFromCard;
601         }
602
603         return rc;
604 }
605
606 /* spinlock already held */
607 static void snd_korg1212_SendStop(korg1212_t *korg1212)
608 {
609         if (! korg1212->stop_pending_cnt) {
610                 writel(0xffffffff, &korg1212->sharedBufferPtr->cardCommand);
611                 /* program the timer */
612                 korg1212->stop_pending_cnt = HZ;
613                 korg1212->timer.expires = jiffies + 1;
614                 add_timer(&korg1212->timer);
615         }
616 }
617
618 static void snd_korg1212_SendStopAndWait(korg1212_t *korg1212)
619 {
620         unsigned long flags;
621         spin_lock_irqsave(&korg1212->lock, flags);
622         snd_korg1212_SendStop(korg1212);
623         spin_unlock_irqrestore(&korg1212->lock, flags);
624         sleep_on_timeout(&korg1212->wait, (HZ * 3) / 2);
625 }
626
627 /* timer callback for checking the ack of stop request */
628 static void snd_korg1212_timer_func(unsigned long data)
629 {
630         korg1212_t *korg1212 = (korg1212_t *) data;
631         
632         spin_lock(&korg1212->lock);
633         if (readl(&korg1212->sharedBufferPtr->cardCommand) == 0) {
634                 /* ack'ed */
635                 korg1212->stop_pending_cnt = 0;
636                 wake_up(&korg1212->wait);
637 #if K1212_DEBUG_LEVEL > 1
638                 K1212_DEBUG_PRINTK("K1212_DEBUG: Stop ack'ed [%s]\n", stateName[korg1212->cardState]);
639 #endif
640         } else {
641                 if (--korg1212->stop_pending_cnt > 0) {
642                         /* reprogram timer */
643                         korg1212->timer.expires = jiffies + 1;
644                         add_timer(&korg1212->timer);
645                 } else {
646                         snd_printd("korg1212_timer_func timeout\n");
647                         writel(0, &korg1212->sharedBufferPtr->cardCommand);
648                         wake_up(&korg1212->wait);
649 #if K1212_DEBUG_LEVEL > 0
650                         K1212_DEBUG_PRINTK("K1212_DEBUG: Stop timeout [%s]\n", stateName[korg1212->cardState]);
651 #endif
652                 }
653         }
654         spin_unlock(&korg1212->lock);
655 }
656
657 static void snd_korg1212_TurnOnIdleMonitor(korg1212_t *korg1212)
658 {
659         unsigned long flags;
660
661         udelay(INTERCOMMAND_DELAY);
662         spin_lock_irqsave(&korg1212->lock, flags);
663         korg1212->idleMonitorOn = 1;
664         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
665                                           K1212_MODE_MonitorOn, 0, 0, 0);
666         spin_unlock_irqrestore(&korg1212->lock, flags);
667 }
668
669 static void snd_korg1212_TurnOffIdleMonitor(korg1212_t *korg1212)
670 {
671         if (korg1212->idleMonitorOn) {
672                 snd_korg1212_SendStopAndWait(korg1212);
673                 korg1212->idleMonitorOn = 0;
674         }
675 }
676
677 static inline void snd_korg1212_setCardState(korg1212_t * korg1212, CardState csState)
678 {
679         korg1212->cardState = csState;
680 }
681
682 static int snd_korg1212_OpenCard(korg1212_t * korg1212)
683 {
684 #if K1212_DEBUG_LEVEL > 0
685         K1212_DEBUG_PRINTK("K1212_DEBUG: OpenCard [%s] %d\n", stateName[korg1212->cardState], korg1212->opencnt);
686 #endif
687         down(&korg1212->open_mutex);
688         if (korg1212->opencnt++ == 0) {
689                 snd_korg1212_TurnOffIdleMonitor(korg1212);
690                 snd_korg1212_setCardState(korg1212, K1212_STATE_OPEN);
691         }
692
693         up(&korg1212->open_mutex);
694         return 1;
695 }
696
697 static int snd_korg1212_CloseCard(korg1212_t * korg1212)
698 {
699 #if K1212_DEBUG_LEVEL > 0
700         K1212_DEBUG_PRINTK("K1212_DEBUG: CloseCard [%s] %d\n", stateName[korg1212->cardState], korg1212->opencnt);
701 #endif
702
703         down(&korg1212->open_mutex);
704         if (--(korg1212->opencnt)) {
705                 up(&korg1212->open_mutex);
706                 return 0;
707         }
708
709         if (korg1212->cardState == K1212_STATE_SETUP) {
710                 rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
711                                 K1212_MODE_StopPlay, 0, 0, 0);
712 #if K1212_DEBUG_LEVEL > 0
713         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: CloseCard - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
714 #endif
715
716                 if (rc != K1212_CMDRET_Success) {
717                         up(&korg1212->open_mutex);
718                         return 0;
719                 }
720         } else if (korg1212->cardState > K1212_STATE_SETUP) {
721                 snd_korg1212_SendStopAndWait(korg1212);
722         }
723
724         if (korg1212->cardState > K1212_STATE_READY) {
725                 snd_korg1212_TurnOnIdleMonitor(korg1212);
726                 snd_korg1212_setCardState(korg1212, K1212_STATE_READY);
727         }
728
729         up(&korg1212->open_mutex);
730         return 0;
731 }
732
733 /* spinlock already held */
734 static int snd_korg1212_SetupForPlay(korg1212_t * korg1212)
735 {
736 #if K1212_DEBUG_LEVEL > 0
737         K1212_DEBUG_PRINTK("K1212_DEBUG: SetupForPlay [%s] %d\n", stateName[korg1212->cardState], korg1212->setcnt);
738 #endif
739
740         if (korg1212->setcnt++)
741                 return 0;
742
743         snd_korg1212_setCardState(korg1212, K1212_STATE_SETUP);
744         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
745                                         K1212_MODE_SetupPlay, 0, 0, 0);
746
747 #if K1212_DEBUG_LEVEL > 0
748         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: SetupForPlay - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
749 #endif
750         if (rc != K1212_CMDRET_Success) {
751                 return 1;
752         }
753         return 0;
754 }
755
756 /* spinlock already held */
757 static int snd_korg1212_TriggerPlay(korg1212_t * korg1212)
758 {
759 #if K1212_DEBUG_LEVEL > 0
760         K1212_DEBUG_PRINTK("K1212_DEBUG: TriggerPlay [%s] %d\n", stateName[korg1212->cardState], korg1212->playcnt);
761 #endif
762
763         if (korg1212->playcnt++)
764                 return 0;
765
766         snd_korg1212_setCardState(korg1212, K1212_STATE_PLAYING);
767         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_TriggerPlay, 0, 0, 0, 0);
768
769 #if K1212_DEBUG_LEVEL > 0
770         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: TriggerPlay - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
771 #endif
772
773         if (rc != K1212_CMDRET_Success) {
774                 return 1;
775         }
776         return 0;
777 }
778
779 /* spinlock already held */
780 static int snd_korg1212_StopPlay(korg1212_t * korg1212)
781 {
782 #if K1212_DEBUG_LEVEL > 0
783         K1212_DEBUG_PRINTK("K1212_DEBUG: StopPlay [%s] %d\n", stateName[korg1212->cardState], korg1212->playcnt);
784 #endif
785
786         if (--(korg1212->playcnt)) 
787                 return 0;
788
789         korg1212->setcnt = 0;
790
791         if (korg1212->cardState != K1212_STATE_ERRORSTOP)
792                 snd_korg1212_SendStop(korg1212);
793
794         snd_korg1212_setCardState(korg1212, K1212_STATE_OPEN);
795         return 0;
796 }
797
798 static void snd_korg1212_EnableCardInterrupts(korg1212_t * korg1212)
799 {
800         * korg1212->statusRegPtr = PCI_INT_ENABLE_BIT            |
801                                    PCI_DOORBELL_INT_ENABLE_BIT   |
802                                    LOCAL_INT_ENABLE_BIT          |
803                                    LOCAL_DOORBELL_INT_ENABLE_BIT |
804                                    LOCAL_DMA1_INT_ENABLE_BIT;
805 }
806
807 #if 0 /* not used */
808
809 static int snd_korg1212_SetMonitorMode(korg1212_t *korg1212, MonitorModeSelector mode)
810 {
811 #if K1212_DEBUG_LEVEL > 0
812         K1212_DEBUG_PRINTK("K1212_DEBUG: SetMonitorMode [%s]\n", stateName[korg1212->cardState]);
813 #endif
814
815         switch (mode) {
816                 case K1212_MONMODE_Off:
817                         if (korg1212->cardState != K1212_STATE_MONITOR) {
818                                 return 0;
819                         } else {
820                                 snd_korg1212_SendStopAndWait(korg1212);
821                                 snd_korg1212_setCardState(korg1212, K1212_STATE_OPEN);
822                         }
823                         break;
824
825                 case K1212_MONMODE_On:
826                         if (korg1212->cardState != K1212_STATE_OPEN) {
827                                 return 0;
828                         } else {
829                                 snd_korg1212_setCardState(korg1212, K1212_STATE_MONITOR);
830                                 rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
831                                                         K1212_MODE_MonitorOn, 0, 0, 0);
832                                 if (rc != K1212_CMDRET_Success) {
833                                         return 0;
834                                 }
835                         }
836                         break;
837
838                 default:
839                         return 0;
840         }
841
842         return 1;
843 }
844
845 #endif /* not used */
846
847 static int snd_korg1212_SetRate(korg1212_t *korg1212, int rate)
848 {
849         static ClockSourceIndex s44[] = { K1212_CLKIDX_AdatAt44_1K,
850                                           K1212_CLKIDX_WordAt44_1K,
851                                           K1212_CLKIDX_LocalAt44_1K };
852         static ClockSourceIndex s48[] = {
853                                           K1212_CLKIDX_AdatAt48K,
854                                           K1212_CLKIDX_WordAt48K,
855                                           K1212_CLKIDX_LocalAt48K };
856         int parm;
857
858         switch(rate) {
859                 case 44100:
860                 parm = s44[korg1212->clkSource];
861                 break;
862
863                 case 48000:
864                 parm = s48[korg1212->clkSource];
865                 break;
866
867                 default:
868                 return -EINVAL;
869         }
870
871         korg1212->clkSrcRate = parm;
872         korg1212->clkRate = rate;
873
874         udelay(INTERCOMMAND_DELAY);
875         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SetClockSourceRate,
876                                           ClockSourceSelector[korg1212->clkSrcRate],
877                                           0, 0, 0);
878
879 #if K1212_DEBUG_LEVEL > 0
880         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Set Clock Source Selector - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
881 #endif
882
883         return 0;
884 }
885
886 static int snd_korg1212_SetClockSource(korg1212_t *korg1212, int source)
887 {
888
889         if (source<0 || source >2)
890            return -EINVAL;
891
892         korg1212->clkSource = source;
893
894         snd_korg1212_SetRate(korg1212, korg1212->clkRate);
895
896         return 0;
897 }
898
899 static void snd_korg1212_DisableCardInterrupts(korg1212_t *korg1212)
900 {
901         * korg1212->statusRegPtr = 0;
902 }
903
904 static int snd_korg1212_WriteADCSensitivity(korg1212_t *korg1212)
905 {
906         SensBits  sensVals;
907         int       bitPosition;
908         int       channel;
909         int       clkIs48K;
910         int       monModeSet;
911         u16       controlValue;    // this keeps the current value to be written to
912                                    //  the card's eeprom control register.
913         u16       count;
914         unsigned long flags;
915
916 #if K1212_DEBUG_LEVEL > 0
917         K1212_DEBUG_PRINTK("K1212_DEBUG: WriteADCSensivity [%s]\n", stateName[korg1212->cardState]);
918 #endif
919
920         // ----------------------------------------------------------------------------
921         // initialize things.  The local init bit is always set when writing to the
922         // card's control register.
923         // ----------------------------------------------------------------------------
924         controlValue = 0;
925         SetBitInWord(&controlValue, SET_SENS_LOCALINIT_BITPOS);    // init the control value
926
927         // ----------------------------------------------------------------------------
928         // make sure the card is not in monitor mode when we do this update.
929         // ----------------------------------------------------------------------------
930         if (korg1212->cardState == K1212_STATE_MONITOR || korg1212->idleMonitorOn) {
931                 monModeSet = 1;
932                 snd_korg1212_SendStopAndWait(korg1212);
933         } else
934                 monModeSet = 0;
935
936         spin_lock_irqsave(&korg1212->lock, flags);
937
938         // ----------------------------------------------------------------------------
939         // we are about to send new values to the card, so clear the new values queued
940         // flag.  Also, clear out mailbox 3, so we don't lockup.
941         // ----------------------------------------------------------------------------
942         writel(0, korg1212->mailbox3Ptr);
943         udelay(LOADSHIFT_DELAY);
944
945         // ----------------------------------------------------------------------------
946         // determine whether we are running a 48K or 44.1K clock.  This info is used
947         // later when setting the SPDIF FF after the volume has been shifted in.
948         // ----------------------------------------------------------------------------
949         switch (korg1212->clkSrcRate) {
950                 case K1212_CLKIDX_AdatAt44_1K:
951                 case K1212_CLKIDX_WordAt44_1K:
952                 case K1212_CLKIDX_LocalAt44_1K:
953                         clkIs48K = 0;
954                         break;
955
956                 case K1212_CLKIDX_WordAt48K:
957                 case K1212_CLKIDX_AdatAt48K:
958                 case K1212_CLKIDX_LocalAt48K:
959                 default:
960                         clkIs48K = 1;
961                         break;
962         }
963
964         // ----------------------------------------------------------------------------
965         // start the update.  Setup the bit structure and then shift the bits.
966         // ----------------------------------------------------------------------------
967         sensVals.l.v.leftChanId   = SET_SENS_LEFTCHANID;
968         sensVals.r.v.rightChanId  = SET_SENS_RIGHTCHANID;
969         sensVals.l.v.leftChanVal  = korg1212->leftADCInSens;
970         sensVals.r.v.rightChanVal = korg1212->rightADCInSens;
971
972         // ----------------------------------------------------------------------------
973         // now start shifting the bits in.  Start with the left channel then the right.
974         // ----------------------------------------------------------------------------
975         for (channel = 0; channel < 2; channel++) {
976
977                 // ----------------------------------------------------------------------------
978                 // Bring the load/shift line low, then wait - the spec says >150ns from load/
979                 // shift low to the first rising edge of the clock.
980                 // ----------------------------------------------------------------------------
981                 ClearBitInWord(&controlValue, SET_SENS_LOADSHIFT_BITPOS);
982                 ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);
983                 writew(controlValue, korg1212->sensRegPtr);                          // load/shift goes low
984                 udelay(LOADSHIFT_DELAY);
985
986                 for (bitPosition = 15; bitPosition >= 0; bitPosition--) {       // for all the bits
987                         if (channel == 0) {
988                                 if (sensVals.l.leftSensBits & (0x0001 << bitPosition)) {
989                                         SetBitInWord(&controlValue, SET_SENS_DATA_BITPOS);     // data bit set high
990                                 } else {
991                                         ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);   // data bit set low
992                                 }
993                         } else {
994                                 if (sensVals.r.rightSensBits & (0x0001 << bitPosition)) {
995                                 SetBitInWord(&controlValue, SET_SENS_DATA_BITPOS);     // data bit set high
996                                 } else {
997                                 ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);   // data bit set low
998                                 }
999                         }
1000
1001                         ClearBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1002                         writew(controlValue, korg1212->sensRegPtr);                       // clock goes low
1003                         udelay(SENSCLKPULSE_WIDTH);
1004                         SetBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1005                         writew(controlValue, korg1212->sensRegPtr);                       // clock goes high
1006                         udelay(SENSCLKPULSE_WIDTH);
1007                 }
1008
1009                 // ----------------------------------------------------------------------------
1010                 // finish up SPDIF for left.  Bring the load/shift line high, then write a one
1011                 // bit if the clock rate is 48K otherwise write 0.
1012                 // ----------------------------------------------------------------------------
1013                 ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);
1014                 ClearBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1015                 SetBitInWord(&controlValue, SET_SENS_LOADSHIFT_BITPOS);
1016                 writew(controlValue, korg1212->sensRegPtr);                   // load shift goes high - clk low
1017                 udelay(SENSCLKPULSE_WIDTH);
1018
1019                 if (clkIs48K)
1020                         SetBitInWord(&controlValue, SET_SENS_DATA_BITPOS);
1021
1022                 writew(controlValue, korg1212->sensRegPtr);                   // set/clear data bit
1023                 udelay(ONE_RTC_TICK);
1024                 SetBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1025                 writew(controlValue, korg1212->sensRegPtr);                   // clock goes high
1026                 udelay(SENSCLKPULSE_WIDTH);
1027                 ClearBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1028                 writew(controlValue, korg1212->sensRegPtr);                   // clock goes low
1029                 udelay(SENSCLKPULSE_WIDTH);
1030         }
1031
1032         // ----------------------------------------------------------------------------
1033         // The update is complete.  Set a timeout.  This is the inter-update delay.
1034         // Also, if the card was in monitor mode, restore it.
1035         // ----------------------------------------------------------------------------
1036         for (count = 0; count < 10; count++)
1037                 udelay(SENSCLKPULSE_WIDTH);
1038
1039         if (monModeSet) {
1040                 rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
1041                                 K1212_MODE_MonitorOn, 0, 0, 0);
1042 #if K1212_DEBUG_LEVEL > 0
1043                 if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: WriteADCSensivity - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1044 #endif
1045
1046         }
1047
1048         spin_unlock_irqrestore(&korg1212->lock, flags);
1049
1050         return 1;
1051 }
1052
1053 static void snd_korg1212_OnDSPDownloadComplete(korg1212_t *korg1212)
1054 {
1055         int channel;
1056
1057 #if K1212_DEBUG_LEVEL > 0
1058         K1212_DEBUG_PRINTK("K1212_DEBUG: DSP download is complete. [%s]\n", stateName[korg1212->cardState]);
1059 #endif
1060
1061         // ----------------------------------------------------
1062         // tell the card to boot
1063         // ----------------------------------------------------
1064         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_BootFromDSPPage4, 0, 0, 0, 0);
1065
1066 #if K1212_DEBUG_LEVEL > 0
1067         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Boot from Page 4 - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1068 #endif
1069         mdelay(DSP_BOOT_DELAY_IN_MS);
1070
1071         // --------------------------------------------------------------------------------
1072         // Let the card know where all the buffers are.
1073         // --------------------------------------------------------------------------------
1074         rc = snd_korg1212_Send1212Command(korg1212,
1075                         K1212_DB_ConfigureBufferMemory,
1076                         LowerWordSwap(korg1212->PlayDataPhy),
1077                         LowerWordSwap(korg1212->RecDataPhy),
1078                         ((kNumBuffers * kPlayBufferFrames) / 2),   // size given to the card
1079                                                                    // is based on 2 buffers
1080                         0
1081         );
1082
1083 #if K1212_DEBUG_LEVEL > 0
1084         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Configure Buffer Memory - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1085 #endif
1086
1087         udelay(INTERCOMMAND_DELAY);
1088
1089         rc = snd_korg1212_Send1212Command(korg1212,
1090                         K1212_DB_ConfigureMiscMemory,
1091                         LowerWordSwap(korg1212->VolumeTablePhy),
1092                         LowerWordSwap(korg1212->RoutingTablePhy),
1093                         LowerWordSwap(korg1212->AdatTimeCodePhy),
1094                         0
1095         );
1096
1097 #if K1212_DEBUG_LEVEL > 0
1098         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Configure Misc Memory - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1099 #endif
1100
1101
1102         // --------------------------------------------------------------------------------
1103         // Initialize the routing and volume tables, then update the card's state.
1104         // --------------------------------------------------------------------------------
1105         udelay(INTERCOMMAND_DELAY);
1106
1107         for (channel = 0; channel < kAudioChannels; channel++) {
1108                 korg1212->sharedBufferPtr->volumeData[channel] = k1212MaxVolume;
1109                 //korg1212->sharedBufferPtr->routeData[channel] = channel;
1110                 korg1212->sharedBufferPtr->routeData[channel] = 8 + (channel & 1);
1111         }
1112
1113         snd_korg1212_WriteADCSensitivity(korg1212);
1114
1115         udelay(INTERCOMMAND_DELAY);
1116         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SetClockSourceRate,
1117                                           ClockSourceSelector[korg1212->clkSrcRate],
1118                                           0, 0, 0);
1119 #if K1212_DEBUG_LEVEL > 0
1120         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Set Clock Source Selector - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1121 #endif
1122
1123         snd_korg1212_TurnOnIdleMonitor(korg1212);
1124         snd_korg1212_setCardState(korg1212, K1212_STATE_READY);
1125
1126 #if K1212_DEBUG_LEVEL > 0
1127         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Set Monitor On - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1128 #endif
1129
1130         snd_korg1212_setCardState(korg1212, K1212_STATE_DSP_COMPLETE);
1131 }
1132
1133 static irqreturn_t snd_korg1212_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1134 {
1135         u32 doorbellValue;
1136         korg1212_t *korg1212 = dev_id;
1137
1138         if(irq != korg1212->irq)
1139                 return IRQ_NONE;
1140
1141         doorbellValue = readl(korg1212->inDoorbellPtr);
1142
1143         if (!doorbellValue)
1144                 return IRQ_NONE;
1145
1146         spin_lock(&korg1212->lock);
1147
1148         writel(doorbellValue, korg1212->inDoorbellPtr);
1149
1150         korg1212->irqcount++;
1151
1152         korg1212->inIRQ++;
1153
1154
1155         switch (doorbellValue) {
1156                 case K1212_DB_DSPDownloadDone:
1157 #if K1212_DEBUG_LEVEL > 0
1158                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ DNLD count - %ld, %x, [%s].\n", korg1212->irqcount, doorbellValue, stateName[korg1212->cardState]);
1159 #endif
1160                         if (korg1212->cardState == K1212_STATE_DSP_IN_PROCESS)
1161                                 wake_up(&korg1212->wait);
1162                         break;
1163
1164                 // ------------------------------------------------------------------------
1165                 // an error occurred - stop the card
1166                 // ------------------------------------------------------------------------
1167                 case K1212_ISRCODE_DMAERROR:
1168 #if K1212_DEBUG_LEVEL > 1
1169                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ DMAE count - %ld, %x, [%s].\n", korg1212->irqcount, doorbellValue, stateName[korg1212->cardState]);
1170 #endif
1171                         writel(0, &korg1212->sharedBufferPtr->cardCommand);
1172                         snd_korg1212_setCardState(korg1212, K1212_STATE_ERRORSTOP);
1173                         break;
1174
1175                 // ------------------------------------------------------------------------
1176                 // the card has stopped by our request.  Clear the command word and signal
1177                 // the semaphore in case someone is waiting for this.
1178                 // ------------------------------------------------------------------------
1179                 case K1212_ISRCODE_CARDSTOPPED:
1180 #if K1212_DEBUG_LEVEL > 1
1181                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ CSTP count - %ld, %x, [%s].\n", korg1212->irqcount, doorbellValue, stateName[korg1212->cardState]);
1182 #endif
1183                         writel(0, &korg1212->sharedBufferPtr->cardCommand);
1184                         break;
1185
1186                 default:
1187 #if K1212_DEBUG_LEVEL > 3
1188                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ DFLT count - %ld, %x, cpos=%d [%s].\n", korg1212->irqcount, doorbellValue, 
1189                                 korg1212->currentBuffer, stateName[korg1212->cardState]);
1190 #endif
1191                         if ((korg1212->cardState > K1212_STATE_SETUP) || korg1212->idleMonitorOn) {
1192                                 korg1212->currentBuffer++;
1193
1194                                 if (korg1212->currentBuffer >= kNumBuffers)
1195                                         korg1212->currentBuffer = 0;
1196
1197                                 if (!korg1212->running)
1198                                         break;
1199
1200                                 if (korg1212->capture_substream) {
1201                                         spin_unlock(&korg1212->lock);
1202                                         snd_pcm_period_elapsed(korg1212->capture_substream);
1203                                         spin_lock(&korg1212->lock);
1204                                 }
1205
1206                                 if (korg1212->playback_substream) {
1207                                         spin_unlock(&korg1212->lock);
1208                                         snd_pcm_period_elapsed(korg1212->playback_substream);
1209                                         spin_lock(&korg1212->lock);
1210                                 }
1211                         }
1212                         break;
1213         }
1214
1215         korg1212->inIRQ--;
1216
1217         spin_unlock(&korg1212->lock);
1218
1219         return IRQ_HANDLED;
1220 }
1221
1222 static int snd_korg1212_downloadDSPCode(korg1212_t *korg1212)
1223 {
1224
1225 #if K1212_DEBUG_LEVEL > 0
1226         K1212_DEBUG_PRINTK("K1212_DEBUG: DSP download is starting... [%s]\n", stateName[korg1212->cardState]);
1227 #endif
1228
1229         // ---------------------------------------------------------------
1230         // verify the state of the card before proceeding.
1231         // ---------------------------------------------------------------
1232         if (korg1212->cardState >= K1212_STATE_DSP_IN_PROCESS) {
1233                 return 1;
1234         }
1235
1236         snd_korg1212_setCardState(korg1212, K1212_STATE_DSP_IN_PROCESS);
1237
1238         memcpy(korg1212->dma_dsp.area, dspCode, korg1212->dspCodeSize);
1239
1240         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_StartDSPDownload,
1241                                      UpperWordSwap(korg1212->dma_dsp.addr),
1242                                      0, 0, 0);
1243
1244 #if K1212_DEBUG_LEVEL > 0
1245         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Start DSP Download RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1246 #endif
1247
1248         if (! sleep_on_timeout(&korg1212->wait, HZ * 4))
1249                 return -EBUSY; /* timeout */
1250
1251         snd_korg1212_OnDSPDownloadComplete(korg1212);
1252
1253         return 0;
1254 }
1255
1256 static snd_pcm_hardware_t snd_korg1212_playback_info =
1257 {
1258         .info =              (SNDRV_PCM_INFO_MMAP |
1259                               SNDRV_PCM_INFO_MMAP_VALID |
1260                               SNDRV_PCM_INFO_INTERLEAVED),
1261         .formats =            SNDRV_PCM_FMTBIT_S16_LE,
1262         .rates =              (SNDRV_PCM_RATE_44100 |
1263                               SNDRV_PCM_RATE_48000),
1264         .rate_min =           44100,
1265         .rate_max =           48000,
1266         .channels_min =       K1212_MIN_CHANNELS,
1267         .channels_max =       K1212_MAX_CHANNELS,
1268         .buffer_bytes_max =   K1212_MAX_BUF_SIZE,
1269         .period_bytes_min =   K1212_MIN_CHANNELS * 2 * kPlayBufferFrames,
1270         .period_bytes_max =   K1212_MAX_CHANNELS * 2 * kPlayBufferFrames,
1271         .periods_min =        K1212_PERIODS,
1272         .periods_max =        K1212_PERIODS,
1273         .fifo_size =          0,
1274 };
1275
1276 static snd_pcm_hardware_t snd_korg1212_capture_info =
1277 {
1278         .info =              (SNDRV_PCM_INFO_MMAP |
1279                               SNDRV_PCM_INFO_MMAP_VALID |
1280                               SNDRV_PCM_INFO_INTERLEAVED),
1281         .formats =            SNDRV_PCM_FMTBIT_S16_LE,
1282         .rates =              (SNDRV_PCM_RATE_44100 |
1283                               SNDRV_PCM_RATE_48000),
1284         .rate_min =           44100,
1285         .rate_max =           48000,
1286         .channels_min =       K1212_MIN_CHANNELS,
1287         .channels_max =       K1212_MAX_CHANNELS,
1288         .buffer_bytes_max =   K1212_MAX_BUF_SIZE,
1289         .period_bytes_min =   K1212_MIN_CHANNELS * 2 * kPlayBufferFrames,
1290         .period_bytes_max =   K1212_MAX_CHANNELS * 2 * kPlayBufferFrames,
1291         .periods_min =        K1212_PERIODS,
1292         .periods_max =        K1212_PERIODS,
1293         .fifo_size =          0,
1294 };
1295
1296 static int snd_korg1212_silence(korg1212_t *korg1212, int pos, int count, int offset, int size)
1297 {
1298         KorgAudioFrame * dst =  korg1212->playDataBufsPtr[0].bufferData + pos;
1299         int i;
1300
1301 #if K1212_DEBUG_LEVEL > 2
1302         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_silence pos=%d offset=%d size=%d count=%d\n", pos, offset, size, count);
1303 #endif
1304         snd_assert(pos + count <= K1212_MAX_SAMPLES, return -EINVAL);
1305
1306         for (i=0; i < count; i++) {
1307 #if K1212_DEBUG_LEVEL > 0
1308                 if ( (void *) dst < (void *) korg1212->playDataBufsPtr ||
1309                      (void *) dst > (void *) korg1212->playDataBufsPtr[8].bufferData ) {
1310                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_silence KERNEL EFAULT dst=%p iter=%d\n", dst, i);
1311                         return -EFAULT;
1312                 }
1313 #endif
1314                 memset((void*) dst + offset, 0, size);
1315                 dst++;
1316         }
1317
1318         return 0;
1319 }
1320
1321 static int snd_korg1212_copy_to(korg1212_t *korg1212, void __user *dst, int pos, int count, int offset, int size)
1322 {
1323         KorgAudioFrame * src =  korg1212->recordDataBufsPtr[0].bufferData + pos;
1324         int i, rc;
1325
1326 #if K1212_DEBUG_LEVEL > 2
1327         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_to pos=%d offset=%d size=%d\n", pos, offset, size);
1328 #endif
1329         snd_assert(pos + count <= K1212_MAX_SAMPLES, return -EINVAL);
1330
1331         for (i=0; i < count; i++) {
1332 #if K1212_DEBUG_LEVEL > 0
1333                 if ( (void *) src < (void *) korg1212->recordDataBufsPtr ||
1334                      (void *) src > (void *) korg1212->recordDataBufsPtr[8].bufferData ) {
1335                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_to KERNEL EFAULT, src=%p dst=%p iter=%d\n", src, dst, i);
1336                         return -EFAULT;
1337                 }
1338 #endif
1339                 rc = copy_to_user(dst + offset, src, size);
1340                 if (rc) {
1341 #if K1212_DEBUG_LEVEL > 0
1342                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_to USER EFAULT src=%p dst=%p iter=%d\n", src, dst, i);
1343 #endif
1344                         return -EFAULT;
1345                 }
1346                 src++;
1347                 dst += size;
1348         }
1349
1350         return 0;
1351 }
1352
1353 static int snd_korg1212_copy_from(korg1212_t *korg1212, void __user *src, int pos, int count, int offset, int size)
1354 {
1355         KorgAudioFrame * dst =  korg1212->playDataBufsPtr[0].bufferData + pos;
1356         int i, rc;
1357
1358 #if K1212_DEBUG_LEVEL > 2
1359         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_from pos=%d offset=%d size=%d count=%d\n", pos, offset, size, count);
1360 #endif
1361
1362         snd_assert(pos + count <= K1212_MAX_SAMPLES, return -EINVAL);
1363
1364         for (i=0; i < count; i++) {
1365 #if K1212_DEBUG_LEVEL > 0
1366                 if ( (void *) dst < (void *) korg1212->playDataBufsPtr ||
1367                      (void *) dst > (void *) korg1212->playDataBufsPtr[8].bufferData ) {
1368                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_from KERNEL EFAULT, src=%p dst=%p iter=%d\n", src, dst, i);
1369                         return -EFAULT;
1370                 }
1371 #endif
1372                 rc = copy_from_user((void*) dst + offset, src, size);
1373                 if (rc) {
1374 #if K1212_DEBUG_LEVEL > 0
1375                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_from USER EFAULT src=%p dst=%p iter=%d\n", src, dst, i);
1376 #endif
1377                         return -EFAULT;
1378                 }
1379                 dst++;
1380                 src += size;
1381         }
1382
1383         return 0;
1384 }
1385
1386 static void snd_korg1212_free_pcm(snd_pcm_t *pcm)
1387 {
1388         korg1212_t *korg1212 = (korg1212_t *) pcm->private_data;
1389
1390 #if K1212_DEBUG_LEVEL > 0
1391                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_free_pcm [%s]\n", stateName[korg1212->cardState]);
1392 #endif
1393
1394         korg1212->pcm = NULL;
1395 }
1396
1397 static int snd_korg1212_playback_open(snd_pcm_substream_t *substream)
1398 {
1399         unsigned long flags;
1400         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1401         snd_pcm_runtime_t *runtime = substream->runtime;
1402
1403 #if K1212_DEBUG_LEVEL > 0
1404                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_open [%s]\n", stateName[korg1212->cardState]);
1405 #endif
1406
1407         snd_pcm_set_sync(substream);    // ???
1408
1409         snd_korg1212_OpenCard(korg1212);
1410
1411         runtime->hw = snd_korg1212_playback_info;
1412         snd_pcm_set_runtime_buffer(substream, &korg1212->dma_play);
1413
1414         spin_lock_irqsave(&korg1212->lock, flags);
1415
1416         korg1212->playback_substream = substream;
1417         korg1212->periodsize = K1212_PERIODS;
1418         korg1212->channels = K1212_CHANNELS;
1419
1420         spin_unlock_irqrestore(&korg1212->lock, flags);
1421
1422         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, kPlayBufferFrames, kPlayBufferFrames);
1423         return 0;
1424 }
1425
1426
1427 static int snd_korg1212_capture_open(snd_pcm_substream_t *substream)
1428 {
1429         unsigned long flags;
1430         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1431         snd_pcm_runtime_t *runtime = substream->runtime;
1432
1433 #if K1212_DEBUG_LEVEL > 0
1434                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_open [%s]\n", stateName[korg1212->cardState]);
1435 #endif
1436
1437         snd_pcm_set_sync(substream);    // ???
1438
1439         snd_korg1212_OpenCard(korg1212);
1440
1441         runtime->hw = snd_korg1212_capture_info;
1442         snd_pcm_set_runtime_buffer(substream, &korg1212->dma_rec);
1443
1444         spin_lock_irqsave(&korg1212->lock, flags);
1445
1446         korg1212->capture_substream = substream;
1447         korg1212->periodsize = K1212_PERIODS;
1448         korg1212->channels = K1212_CHANNELS;
1449
1450         spin_unlock_irqrestore(&korg1212->lock, flags);
1451
1452         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, kPlayBufferFrames, kPlayBufferFrames);
1453         return 0;
1454 }
1455
1456 static int snd_korg1212_playback_close(snd_pcm_substream_t *substream)
1457 {
1458         unsigned long flags;
1459         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1460
1461 #if K1212_DEBUG_LEVEL > 0
1462                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_close [%s]\n", stateName[korg1212->cardState]);
1463 #endif
1464
1465         snd_korg1212_silence(korg1212, 0, K1212_MAX_SAMPLES, 0, korg1212->channels * 2);
1466
1467         spin_lock_irqsave(&korg1212->lock, flags);
1468
1469         korg1212->playback_substream = NULL;
1470         korg1212->periodsize = 0;
1471
1472         spin_unlock_irqrestore(&korg1212->lock, flags);
1473
1474         snd_korg1212_CloseCard(korg1212);
1475         return 0;
1476 }
1477
1478 static int snd_korg1212_capture_close(snd_pcm_substream_t *substream)
1479 {
1480         unsigned long flags;
1481         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1482
1483 #if K1212_DEBUG_LEVEL > 0
1484                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_close [%s]\n", stateName[korg1212->cardState]);
1485 #endif
1486
1487         spin_lock_irqsave(&korg1212->lock, flags);
1488
1489         korg1212->capture_substream = NULL;
1490         korg1212->periodsize = 0;
1491
1492         spin_unlock_irqrestore(&korg1212->lock, flags);
1493
1494         snd_korg1212_CloseCard(korg1212);
1495         return 0;
1496 }
1497
1498 static int snd_korg1212_ioctl(snd_pcm_substream_t *substream,
1499                              unsigned int cmd, void *arg)
1500 {
1501 #if K1212_DEBUG_LEVEL > 0
1502                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_ioctl: cmd=%d\n", cmd);
1503 #endif
1504
1505         if (cmd == SNDRV_PCM_IOCTL1_CHANNEL_INFO ) {
1506                 snd_pcm_channel_info_t *info = arg;
1507                 info->offset = 0;
1508                 info->first = info->channel * 16;
1509                 info->step = 256;
1510 #if K1212_DEBUG_LEVEL > 0
1511                 K1212_DEBUG_PRINTK("K1212_DEBUG: channel_info %d:, offset=%ld, first=%d, step=%d\n", info->channel, info->offset, info->first, info->step);
1512 #endif
1513                 return 0;
1514         }
1515
1516         return snd_pcm_lib_ioctl(substream, cmd, arg);
1517 }
1518
1519 static int snd_korg1212_hw_params(snd_pcm_substream_t *substream,
1520                              snd_pcm_hw_params_t *params)
1521 {
1522         unsigned long flags;
1523         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1524         int err;
1525
1526 #if K1212_DEBUG_LEVEL > 0
1527                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_hw_params [%s]\n", stateName[korg1212->cardState]);
1528 #endif
1529
1530         spin_lock_irqsave(&korg1212->lock, flags);
1531         if ((err = snd_korg1212_SetRate(korg1212, params_rate(params))) < 0) {
1532                 spin_unlock_irqrestore(&korg1212->lock, flags);
1533                 return err;
1534         }
1535 /*
1536         if (params_format(params) != SNDRV_PCM_FORMAT_S16_LE) {
1537                 spin_unlock_irqrestore(&korg1212->lock, flags);
1538                 return -EINVAL;
1539         }
1540 */
1541         korg1212->channels = params_channels(params);
1542         korg1212->periodsize = K1212_PERIOD_BYTES;
1543
1544         spin_unlock_irqrestore(&korg1212->lock, flags);
1545
1546         return 0;
1547 }
1548
1549 static int snd_korg1212_prepare(snd_pcm_substream_t *substream)
1550 {
1551         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1552         int rc;
1553
1554 #if K1212_DEBUG_LEVEL > 0
1555                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_prepare [%s]\n", stateName[korg1212->cardState]);
1556 #endif
1557
1558         spin_lock_irq(&korg1212->lock);
1559
1560         /* FIXME: we should wait for ack! */
1561         if (korg1212->stop_pending_cnt > 0) {
1562 #if K1212_DEBUG_LEVEL > 0
1563                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_prepare - Stop is pending... [%s]\n", stateName[korg1212->cardState]);
1564 #endif
1565                 spin_unlock_irq(&korg1212->lock);
1566                 return -EAGAIN;
1567                 /*
1568                 writel(0, &korg1212->sharedBufferPtr->cardCommand);
1569                 del_timer(&korg1212->timer);
1570                 korg1212->stop_pending_cnt = 0;
1571                 */
1572         }
1573
1574         rc = snd_korg1212_SetupForPlay(korg1212);
1575
1576         korg1212->currentBuffer = 0;
1577
1578         spin_unlock_irq(&korg1212->lock);
1579
1580         return rc ? -EINVAL : 0;
1581 }
1582
1583 static int snd_korg1212_trigger(snd_pcm_substream_t *substream,
1584                            int cmd)
1585 {
1586         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1587         int rc;
1588
1589 #if K1212_DEBUG_LEVEL > 0
1590                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_trigger [%s] cmd=%d\n", stateName[korg1212->cardState], cmd);
1591 #endif
1592
1593         spin_lock(&korg1212->lock);
1594         switch (cmd) {
1595                 case SNDRV_PCM_TRIGGER_START:
1596 /*
1597                         if (korg1212->running) {
1598 #if K1212_DEBUG_LEVEL > 1
1599                                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_trigger: Already running?\n");
1600 #endif
1601                                 break;
1602                         }
1603 */
1604                         korg1212->running++;
1605                         rc = snd_korg1212_TriggerPlay(korg1212);
1606                         break;
1607
1608                 case SNDRV_PCM_TRIGGER_STOP:
1609 /*
1610                         if (!korg1212->running) {
1611 #if K1212_DEBUG_LEVEL > 1
1612                                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_trigger: Already stopped?\n");
1613 #endif
1614                                 break;
1615                         }
1616 */
1617                         korg1212->running--;
1618                         rc = snd_korg1212_StopPlay(korg1212);
1619                         break;
1620
1621                 default:
1622                         rc = 1;
1623                         break;
1624         }
1625         spin_unlock(&korg1212->lock);
1626         return rc ? -EINVAL : 0;
1627 }
1628
1629 static snd_pcm_uframes_t snd_korg1212_playback_pointer(snd_pcm_substream_t *substream)
1630 {
1631         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1632         snd_pcm_uframes_t pos;
1633
1634         pos = korg1212->currentBuffer * kPlayBufferFrames;
1635
1636 #if K1212_DEBUG_LEVEL > 2
1637         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_pointer [%s] %ld\n", 
1638                         stateName[korg1212->cardState], pos);
1639 #endif
1640
1641         return pos;
1642 }
1643
1644 static snd_pcm_uframes_t snd_korg1212_capture_pointer(snd_pcm_substream_t *substream)
1645 {
1646         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1647         snd_pcm_uframes_t pos;
1648
1649         pos = korg1212->currentBuffer * kPlayBufferFrames;
1650
1651 #if K1212_DEBUG_LEVEL > 2
1652         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_pointer [%s] %ld\n",
1653                         stateName[korg1212->cardState], pos);
1654 #endif
1655
1656         return pos;
1657 }
1658
1659 static int snd_korg1212_playback_copy(snd_pcm_substream_t *substream,
1660                         int channel, /* not used (interleaved data) */
1661                         snd_pcm_uframes_t pos,
1662                         void __user *src,
1663                         snd_pcm_uframes_t count)
1664 {
1665         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1666
1667 #if K1212_DEBUG_LEVEL > 2
1668                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_copy [%s] %ld %ld\n", stateName[korg1212->cardState], pos, count);
1669 #endif
1670  
1671         return snd_korg1212_copy_from(korg1212, src, pos, count, 0, korg1212->channels * 2);
1672
1673 }
1674
1675 static int snd_korg1212_playback_silence(snd_pcm_substream_t *substream,
1676                            int channel, /* not used (interleaved data) */
1677                            snd_pcm_uframes_t pos,
1678                            snd_pcm_uframes_t count)
1679 {
1680         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1681
1682 #if K1212_DEBUG_LEVEL > 0
1683                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_silence [%s]\n", stateName[korg1212->cardState]);
1684 #endif
1685
1686         return snd_korg1212_silence(korg1212, pos, count, 0, korg1212->channels * 2);
1687 }
1688
1689 static int snd_korg1212_capture_copy(snd_pcm_substream_t *substream,
1690                         int channel, /* not used (interleaved data) */
1691                         snd_pcm_uframes_t pos,
1692                         void __user *dst,
1693                         snd_pcm_uframes_t count)
1694 {
1695         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1696
1697 #if K1212_DEBUG_LEVEL > 2
1698                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_copy [%s] %ld %ld\n", stateName[korg1212->cardState], pos, count);
1699 #endif
1700
1701         return snd_korg1212_copy_to(korg1212, dst, pos, count, 0, korg1212->channels * 2);
1702 }
1703
1704 static snd_pcm_ops_t snd_korg1212_playback_ops = {
1705         .open =         snd_korg1212_playback_open,
1706         .close =        snd_korg1212_playback_close,
1707         .ioctl =        snd_korg1212_ioctl,
1708         .hw_params =    snd_korg1212_hw_params,
1709         .prepare =      snd_korg1212_prepare,
1710         .trigger =      snd_korg1212_trigger,
1711         .pointer =      snd_korg1212_playback_pointer,
1712         .copy =         snd_korg1212_playback_copy,
1713         .silence =      snd_korg1212_playback_silence,
1714 };
1715
1716 static snd_pcm_ops_t snd_korg1212_capture_ops = {
1717         .open =         snd_korg1212_capture_open,
1718         .close =        snd_korg1212_capture_close,
1719         .ioctl =        snd_korg1212_ioctl,
1720         .hw_params =    snd_korg1212_hw_params,
1721         .prepare =      snd_korg1212_prepare,
1722         .trigger =      snd_korg1212_trigger,
1723         .pointer =      snd_korg1212_capture_pointer,
1724         .copy =         snd_korg1212_capture_copy,
1725 };
1726
1727 /*
1728  * Control Interface
1729  */
1730
1731 static int snd_korg1212_control_phase_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1732 {
1733         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
1734         uinfo->count = (kcontrol->private_value >= 8) ? 2 : 1;
1735         return 0;
1736 }
1737
1738 static int snd_korg1212_control_phase_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1739 {
1740         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1741         int i = kcontrol->private_value;
1742
1743         spin_lock_irq(&korg1212->lock);
1744
1745         u->value.integer.value[0] = korg1212->volumePhase[i];
1746
1747         if (i >= 8)
1748                 u->value.integer.value[1] = korg1212->volumePhase[i+1];
1749
1750         spin_unlock_irq(&korg1212->lock);
1751
1752         return 0;
1753 }
1754
1755 static int snd_korg1212_control_phase_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1756 {
1757         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1758         int change = 0;
1759         int i, val;
1760
1761         spin_lock_irq(&korg1212->lock);
1762
1763         i = kcontrol->private_value;
1764
1765         korg1212->volumePhase[i] = u->value.integer.value[0];
1766
1767         val = korg1212->sharedBufferPtr->volumeData[kcontrol->private_value];
1768
1769         if ((u->value.integer.value[0] > 0) != (val < 0)) {
1770                 val = abs(val) * (korg1212->volumePhase[i] > 0 ? -1 : 1);
1771                 korg1212->sharedBufferPtr->volumeData[i] = val;
1772                 change = 1;
1773         }
1774
1775         if (i >= 8) {
1776                 korg1212->volumePhase[i+1] = u->value.integer.value[1];
1777
1778                 val = korg1212->sharedBufferPtr->volumeData[kcontrol->private_value+1];
1779
1780                 if ((u->value.integer.value[1] > 0) != (val < 0)) {
1781                         val = abs(val) * (korg1212->volumePhase[i+1] > 0 ? -1 : 1);
1782                         korg1212->sharedBufferPtr->volumeData[i+1] = val;
1783                         change = 1;
1784                 }
1785         }
1786
1787         spin_unlock_irq(&korg1212->lock);
1788
1789         return change;
1790 }
1791
1792 static int snd_korg1212_control_volume_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1793 {
1794         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1795         uinfo->count = (kcontrol->private_value >= 8) ? 2 : 1;
1796         uinfo->value.integer.min = k1212MinVolume;
1797         uinfo->value.integer.max = k1212MaxVolume;
1798         return 0;
1799 }
1800
1801 static int snd_korg1212_control_volume_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1802 {
1803         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1804         int i;
1805
1806         spin_lock_irq(&korg1212->lock);
1807
1808         i = kcontrol->private_value;
1809         u->value.integer.value[0] = abs(korg1212->sharedBufferPtr->volumeData[i]);
1810
1811         if (i >= 8) 
1812                 u->value.integer.value[1] = abs(korg1212->sharedBufferPtr->volumeData[i+1]);
1813
1814         spin_unlock_irq(&korg1212->lock);
1815
1816         return 0;
1817 }
1818
1819 static int snd_korg1212_control_volume_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1820 {
1821         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1822         int change = 0;
1823         int i;
1824         int val;
1825
1826         spin_lock_irq(&korg1212->lock);
1827
1828         i = kcontrol->private_value;
1829
1830         if (u->value.integer.value[0] != abs(korg1212->sharedBufferPtr->volumeData[i])) {
1831                 val = korg1212->volumePhase[i] > 0 ? -1 : 1;
1832                 val *= u->value.integer.value[0];
1833                 korg1212->sharedBufferPtr->volumeData[i] = val;
1834                 change = 1;
1835         }
1836
1837         if (i >= 8) {
1838                 if (u->value.integer.value[1] != abs(korg1212->sharedBufferPtr->volumeData[i+1])) {
1839                         val = korg1212->volumePhase[i+1] > 0 ? -1 : 1;
1840                         val *= u->value.integer.value[1];
1841                         korg1212->sharedBufferPtr->volumeData[i+1] = val;
1842                         change = 1;
1843                 }
1844         }
1845
1846         spin_unlock_irq(&korg1212->lock);
1847
1848         return change;
1849 }
1850
1851 static int snd_korg1212_control_route_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1852 {
1853         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
1854         uinfo->count = (kcontrol->private_value >= 8) ? 2 : 1;
1855         uinfo->value.enumerated.items = kAudioChannels;
1856         if (uinfo->value.enumerated.item > kAudioChannels-1) {
1857                 uinfo->value.enumerated.item = kAudioChannels-1;
1858         }
1859         strcpy(uinfo->value.enumerated.name, channelName[uinfo->value.enumerated.item]);
1860         return 0;
1861 }
1862
1863 static int snd_korg1212_control_route_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1864 {
1865         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1866         int i;
1867
1868         spin_lock_irq(&korg1212->lock);
1869
1870         i = kcontrol->private_value;
1871         u->value.enumerated.item[0] = korg1212->sharedBufferPtr->routeData[i];
1872
1873         if (i >= 8) 
1874                 u->value.enumerated.item[1] = korg1212->sharedBufferPtr->routeData[i+1];
1875
1876         spin_unlock_irq(&korg1212->lock);
1877
1878         return 0;
1879 }
1880
1881 static int snd_korg1212_control_route_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1882 {
1883         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1884         int change = 0, i;
1885
1886         spin_lock_irq(&korg1212->lock);
1887
1888         i = kcontrol->private_value;
1889
1890         if (u->value.enumerated.item[0] != (unsigned) korg1212->sharedBufferPtr->volumeData[i]) {
1891                 korg1212->sharedBufferPtr->routeData[i] = u->value.enumerated.item[0];
1892                 change = 1;
1893         }
1894
1895         if (i >= 8) {
1896                 if (u->value.enumerated.item[1] != (unsigned) korg1212->sharedBufferPtr->volumeData[i+1]) {
1897                         korg1212->sharedBufferPtr->routeData[i+1] = u->value.enumerated.item[1];
1898                         change = 1;
1899                 }
1900         }
1901
1902         spin_unlock_irq(&korg1212->lock);
1903
1904         return change;
1905 }
1906
1907 static int snd_korg1212_control_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1908 {
1909         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1910         uinfo->count = 2;
1911         uinfo->value.integer.min = k1212MaxADCSens;
1912         uinfo->value.integer.max = k1212MinADCSens;
1913         return 0;
1914 }
1915
1916 static int snd_korg1212_control_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1917 {
1918         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1919
1920         spin_lock_irq(&korg1212->lock);
1921
1922         u->value.integer.value[0] = korg1212->leftADCInSens;
1923         u->value.integer.value[1] = korg1212->rightADCInSens;
1924
1925         spin_unlock_irq(&korg1212->lock);
1926
1927         return 0;
1928 }
1929
1930 static int snd_korg1212_control_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1931 {
1932         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1933         int change = 0;
1934
1935         spin_lock_irq(&korg1212->lock);
1936
1937         if (u->value.integer.value[0] != korg1212->leftADCInSens) {
1938                 korg1212->leftADCInSens = u->value.integer.value[0];
1939                 change = 1;
1940         }
1941         if (u->value.integer.value[1] != korg1212->rightADCInSens) {
1942                 korg1212->rightADCInSens = u->value.integer.value[1];
1943                 change = 1;
1944         }
1945
1946         spin_unlock_irq(&korg1212->lock);
1947
1948         if (change)
1949                 snd_korg1212_WriteADCSensitivity(korg1212);
1950
1951         return change;
1952 }
1953
1954 static int snd_korg1212_control_sync_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1955 {
1956         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
1957         uinfo->count = 1;
1958         uinfo->value.enumerated.items = 3;
1959         if (uinfo->value.enumerated.item > 2) {
1960                 uinfo->value.enumerated.item = 2;
1961         }
1962         strcpy(uinfo->value.enumerated.name, clockSourceTypeName[uinfo->value.enumerated.item]);
1963         return 0;
1964 }
1965
1966 static int snd_korg1212_control_sync_get(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
1967 {
1968         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1969
1970         spin_lock_irq(&korg1212->lock);
1971
1972         ucontrol->value.enumerated.item[0] = korg1212->clkSource;
1973
1974         spin_unlock_irq(&korg1212->lock);
1975         return 0;
1976 }
1977
1978 static int snd_korg1212_control_sync_put(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
1979 {
1980         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1981         unsigned int val;
1982         int change;
1983
1984         val = ucontrol->value.enumerated.item[0] % 3;
1985         spin_lock_irq(&korg1212->lock);
1986         change = val != korg1212->clkSource;
1987         snd_korg1212_SetClockSource(korg1212, val);
1988         spin_unlock_irq(&korg1212->lock);
1989         return change;
1990 }
1991
1992 #define MON_MIXER(ord,c_name)                                                                   \
1993         {                                                                                       \
1994                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,       \
1995                 .iface =        SNDRV_CTL_ELEM_IFACE_MIXER,                                     \
1996                 .name =         c_name " Monitor Volume",                                       \
1997                 .info =         snd_korg1212_control_volume_info,                               \
1998                 .get =          snd_korg1212_control_volume_get,                                \
1999                 .put =          snd_korg1212_control_volume_put,                                \
2000                 .private_value = ord,                                                           \
2001         },                                                                                      \
2002         {                                                                                       \
2003                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,       \
2004                 .iface =        SNDRV_CTL_ELEM_IFACE_MIXER,                                     \
2005                 .name =         c_name " Monitor Route",                                        \
2006                 .info =         snd_korg1212_control_route_info,                                \
2007                 .get =          snd_korg1212_control_route_get,                                 \
2008                 .put =          snd_korg1212_control_route_put,                                 \
2009                 .private_value = ord,                                                           \
2010         },                                                                                      \
2011         {                                                                                       \
2012                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,       \
2013                 .iface =        SNDRV_CTL_ELEM_IFACE_PCM,                                       \
2014                 .name =         c_name " Monitor Phase Invert",                                 \
2015                 .info =         snd_korg1212_control_phase_info,                                \
2016                 .get =          snd_korg1212_control_phase_get,                                 \
2017                 .put =          snd_korg1212_control_phase_put,                                 \
2018                 .private_value = ord,                                                           \
2019         }
2020
2021 static snd_kcontrol_new_t snd_korg1212_controls[] = {
2022         MON_MIXER(8, "Analog"),
2023         MON_MIXER(10, "SPDIF"), 
2024         MON_MIXER(0, "ADAT-1"), MON_MIXER(1, "ADAT-2"), MON_MIXER(2, "ADAT-3"), MON_MIXER(3, "ADAT-4"),
2025         MON_MIXER(4, "ADAT-5"), MON_MIXER(5, "ADAT-6"), MON_MIXER(6, "ADAT-7"), MON_MIXER(7, "ADAT-8"),
2026         {
2027                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,
2028                 .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
2029                 .name =         "Sync Source",
2030                 .info =         snd_korg1212_control_sync_info,
2031                 .get =          snd_korg1212_control_sync_get,
2032                 .put =          snd_korg1212_control_sync_put,
2033         },
2034         {
2035                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,
2036                 .iface =        SNDRV_CTL_ELEM_IFACE_MIXER,
2037                 .name =         "ADC Attenuation",
2038                 .info =         snd_korg1212_control_info,
2039                 .get =          snd_korg1212_control_get,
2040                 .put =          snd_korg1212_control_put,
2041         }
2042 };
2043
2044 /*
2045  * proc interface
2046  */
2047
2048 static void snd_korg1212_proc_read(snd_info_entry_t *entry, snd_info_buffer_t *buffer)
2049 {
2050         int n;
2051         korg1212_t *korg1212 = (korg1212_t *)entry->private_data;
2052
2053         snd_iprintf(buffer, korg1212->card->longname);
2054         snd_iprintf(buffer, " (index #%d)\n", korg1212->card->number + 1);
2055         snd_iprintf(buffer, "\nGeneral settings\n");
2056         snd_iprintf(buffer, "    period size: %Zd bytes\n", K1212_PERIOD_BYTES);
2057         snd_iprintf(buffer, "     clock mode: %s\n", clockSourceName[korg1212->clkSrcRate] );
2058         snd_iprintf(buffer, "  left ADC Sens: %d\n", korg1212->leftADCInSens );
2059         snd_iprintf(buffer, " right ADC Sens: %d\n", korg1212->rightADCInSens );
2060         snd_iprintf(buffer, "    Volume Info:\n");
2061         for (n=0; n<kAudioChannels; n++)
2062                 snd_iprintf(buffer, " Channel %d: %s -> %s [%d]\n", n,
2063                                     channelName[n],
2064                                     channelName[korg1212->sharedBufferPtr->routeData[n]],
2065                                     korg1212->sharedBufferPtr->volumeData[n]);
2066         snd_iprintf(buffer, "\nGeneral status\n");
2067         snd_iprintf(buffer, " ADAT Time Code: %d\n", korg1212->sharedBufferPtr->AdatTimeCode);
2068         snd_iprintf(buffer, "     Card State: %s\n", stateName[korg1212->cardState]);
2069         snd_iprintf(buffer, "Idle mon. State: %d\n", korg1212->idleMonitorOn);
2070         snd_iprintf(buffer, "Cmd retry count: %d\n", korg1212->cmdRetryCount);
2071         snd_iprintf(buffer, "      Irq count: %ld\n", korg1212->irqcount);
2072 }
2073
2074 static void __devinit snd_korg1212_proc_init(korg1212_t *korg1212)
2075 {
2076         snd_info_entry_t *entry;
2077
2078         if (! snd_card_proc_new(korg1212->card, "korg1212", &entry))
2079                 snd_info_set_text_ops(entry, korg1212, 1024, snd_korg1212_proc_read);
2080 }
2081
2082 static int
2083 snd_korg1212_free(korg1212_t *korg1212)
2084 {
2085         snd_korg1212_TurnOffIdleMonitor(korg1212);
2086
2087         if (korg1212->irq >= 0) {
2088                 synchronize_irq(korg1212->irq);                
2089                 snd_korg1212_DisableCardInterrupts(korg1212);
2090                 free_irq(korg1212->irq, (void *)korg1212);
2091                 korg1212->irq = -1;
2092         }
2093         
2094         if (korg1212->iobase != 0) {
2095                 iounmap((void *)korg1212->iobase);
2096                 korg1212->iobase = 0;
2097         }
2098         
2099         pci_release_regions(korg1212->pci);
2100
2101         // ----------------------------------------------------
2102         // free up memory resources used for the DSP download.
2103         // ----------------------------------------------------
2104         if (korg1212->dma_dsp.area) {
2105                 snd_dma_free_pages(&korg1212->dma_dsp);
2106                 korg1212->dma_dsp.area = NULL;
2107         }
2108
2109 #ifndef K1212_LARGEALLOC
2110
2111         // ------------------------------------------------------
2112         // free up memory resources used for the Play/Rec Buffers
2113         // ------------------------------------------------------
2114         if (korg1212->dma_play.area) {
2115                 snd_dma_free_pages(&korg1212->dma_play);
2116                 korg1212->dma_play.area = NULL;
2117         }
2118
2119         if (korg1212->dma_rec.area) {
2120                 snd_dma_free_pages(&korg1212->dma_rec);
2121                 korg1212->dma_rec.area = NULL;
2122         }
2123
2124 #endif
2125
2126         // ----------------------------------------------------
2127         // free up memory resources used for the Shared Buffers
2128         // ----------------------------------------------------
2129         if (korg1212->dma_shared.area) {
2130                 snd_dma_free_pages(&korg1212->dma_shared);
2131                 korg1212->dma_shared.area = NULL;
2132         }
2133         
2134         kfree(korg1212);
2135         return 0;
2136 }
2137
2138 static int snd_korg1212_dev_free(snd_device_t *device)
2139 {
2140         korg1212_t *korg1212 = device->device_data;
2141 #if K1212_DEBUG_LEVEL > 0
2142         K1212_DEBUG_PRINTK("K1212_DEBUG: Freeing device\n");
2143 #endif
2144         return snd_korg1212_free(korg1212);
2145 }
2146
2147 static int __devinit snd_korg1212_create(snd_card_t * card, struct pci_dev *pci,
2148                                          korg1212_t ** rchip)
2149
2150 {
2151         int err;
2152         unsigned int i;
2153         unsigned ioport_size, iomem_size, iomem2_size;
2154         korg1212_t * korg1212;
2155
2156         static snd_device_ops_t ops = {
2157                 .dev_free = snd_korg1212_dev_free,
2158         };
2159
2160         * rchip = NULL;
2161         if ((err = pci_enable_device(pci)) < 0)
2162                 return err;
2163
2164         korg1212 = kcalloc(1, sizeof(*korg1212), GFP_KERNEL);
2165         if (korg1212 == NULL)
2166                 return -ENOMEM;
2167
2168         korg1212->card = card;
2169         korg1212->pci = pci;
2170
2171         init_waitqueue_head(&korg1212->wait);
2172         spin_lock_init(&korg1212->lock);
2173         init_MUTEX(&korg1212->open_mutex);
2174         init_timer(&korg1212->timer);
2175         korg1212->timer.function = snd_korg1212_timer_func;
2176         korg1212->timer.data = (unsigned long)korg1212;
2177
2178         korg1212->irq = -1;
2179         korg1212->clkSource = K1212_CLKIDX_Local;
2180         korg1212->clkRate = 44100;
2181         korg1212->inIRQ = 0;
2182         korg1212->running = 0;
2183         korg1212->opencnt = 0;
2184         korg1212->playcnt = 0;
2185         korg1212->setcnt = 0;
2186         snd_korg1212_setCardState(korg1212, K1212_STATE_UNINITIALIZED);
2187         korg1212->idleMonitorOn = 0;
2188         korg1212->clkSrcRate = K1212_CLKIDX_LocalAt44_1K;
2189         korg1212->leftADCInSens = k1212MaxADCSens;
2190         korg1212->rightADCInSens = k1212MaxADCSens;
2191
2192         for (i=0; i<kAudioChannels; i++)
2193                 korg1212->volumePhase[i] = 0;
2194
2195         if ((err = pci_request_regions(pci, "korg1212")) < 0) {
2196                 kfree(korg1212);
2197                 return err;
2198         }
2199
2200         korg1212->iomem = pci_resource_start(korg1212->pci, 0);
2201         korg1212->ioport = pci_resource_start(korg1212->pci, 1);
2202         korg1212->iomem2 = pci_resource_start(korg1212->pci, 2);
2203
2204         iomem_size = pci_resource_len(korg1212->pci, 0);
2205         ioport_size = pci_resource_len(korg1212->pci, 1);
2206         iomem2_size = pci_resource_len(korg1212->pci, 2);
2207
2208 #if K1212_DEBUG_LEVEL > 0
2209         K1212_DEBUG_PRINTK("K1212_DEBUG: resources:\n"
2210                    "    iomem = 0x%lx (%d)\n"
2211                    "    ioport  = 0x%lx (%d)\n"
2212                    "    iomem = 0x%lx (%d)\n"
2213                    "    [%s]\n",
2214                    korg1212->iomem, iomem_size,
2215                    korg1212->ioport, ioport_size,
2216                    korg1212->iomem2, iomem2_size,
2217                    stateName[korg1212->cardState]);
2218 #endif
2219
2220         if ((korg1212->iobase = (unsigned long) ioremap(korg1212->iomem, iomem_size)) == 0) {
2221                 snd_printk(KERN_ERR "unable to remap memory region 0x%lx-0x%lx\n", korg1212->iobase,
2222                            korg1212->iobase + iomem_size - 1);
2223                 return -EBUSY;
2224         }
2225
2226         err = request_irq(pci->irq, snd_korg1212_interrupt,
2227                           SA_INTERRUPT|SA_SHIRQ,
2228                           "korg1212", (void *) korg1212);
2229
2230         if (err) {
2231                 snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
2232                 return -EBUSY;
2233         }
2234
2235         korg1212->irq = pci->irq;
2236
2237         pci_set_master(korg1212->pci);
2238
2239         korg1212->statusRegPtr = (u32 *) (korg1212->iobase + STATUS_REG_OFFSET);
2240         korg1212->outDoorbellPtr = (u32 *) (korg1212->iobase + OUT_DOORBELL_OFFSET);
2241         korg1212->inDoorbellPtr = (u32 *) (korg1212->iobase + IN_DOORBELL_OFFSET);
2242         korg1212->mailbox0Ptr = (u32 *) (korg1212->iobase + MAILBOX0_OFFSET);
2243         korg1212->mailbox1Ptr = (u32 *) (korg1212->iobase + MAILBOX1_OFFSET);
2244         korg1212->mailbox2Ptr = (u32 *) (korg1212->iobase + MAILBOX2_OFFSET);
2245         korg1212->mailbox3Ptr = (u32 *) (korg1212->iobase + MAILBOX3_OFFSET);
2246         korg1212->controlRegPtr = (u32 *) (korg1212->iobase + PCI_CONTROL_OFFSET);
2247         korg1212->sensRegPtr = (u16 *) (korg1212->iobase + SENS_CONTROL_OFFSET);
2248         korg1212->idRegPtr = (u32 *) (korg1212->iobase + DEV_VEND_ID_OFFSET);
2249
2250 #if K1212_DEBUG_LEVEL > 0
2251         K1212_DEBUG_PRINTK("K1212_DEBUG: card registers:\n"
2252                    "    Status register = 0x%p\n"
2253                    "    OutDoorbell     = 0x%p\n"
2254                    "    InDoorbell      = 0x%p\n"
2255                    "    Mailbox0        = 0x%p\n"
2256                    "    Mailbox1        = 0x%p\n"
2257                    "    Mailbox2        = 0x%p\n"
2258                    "    Mailbox3        = 0x%p\n"
2259                    "    ControlReg      = 0x%p\n"
2260                    "    SensReg         = 0x%p\n"
2261                    "    IDReg           = 0x%p\n"
2262                    "    [%s]\n",
2263                    korg1212->statusRegPtr,
2264                    korg1212->outDoorbellPtr,
2265                    korg1212->inDoorbellPtr,
2266                    korg1212->mailbox0Ptr,
2267                    korg1212->mailbox1Ptr,
2268                    korg1212->mailbox2Ptr,
2269                    korg1212->mailbox3Ptr,
2270                    korg1212->controlRegPtr,
2271                    korg1212->sensRegPtr,
2272                    korg1212->idRegPtr,
2273                    stateName[korg1212->cardState]);
2274 #endif
2275
2276         if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2277                                 sizeof(KorgSharedBuffer), &korg1212->dma_shared) < 0) {
2278                 snd_printk(KERN_ERR "can not allocate shared buffer memory (%Zd bytes)\n", sizeof(KorgSharedBuffer));
2279                 return -ENOMEM;
2280         }
2281         korg1212->sharedBufferPtr = (KorgSharedBuffer *)korg1212->dma_shared.area;
2282         korg1212->sharedBufferPhy = korg1212->dma_shared.addr;
2283
2284 #if K1212_DEBUG_LEVEL > 0
2285         K1212_DEBUG_PRINTK("K1212_DEBUG: Shared Buffer Area = 0x%p (0x%08lx), %d bytes\n", korg1212->sharedBufferPtr, korg1212->sharedBufferPhy, sizeof(KorgSharedBuffer));
2286 #endif
2287
2288 #ifndef K1212_LARGEALLOC
2289
2290         korg1212->DataBufsSize = sizeof(KorgAudioBuffer) * kNumBuffers;
2291
2292         if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2293                                 korg1212->DataBufsSize, &korg1212->dma_play) < 0) {
2294                 snd_printk(KERN_ERR "can not allocate play data buffer memory (%d bytes)\n", korg1212->DataBufsSize);
2295                 return -ENOMEM;
2296         }
2297         korg1212->playDataBufsPtr = (KorgAudioBuffer *)korg1212->dma_play.area;
2298         korg1212->PlayDataPhy = korg1212->dma_play.addr;
2299
2300 #if K1212_DEBUG_LEVEL > 0
2301         K1212_DEBUG_PRINTK("K1212_DEBUG: Play Data Area = 0x%p (0x%08x), %d bytes\n",
2302                 korg1212->playDataBufsPtr, korg1212->PlayDataPhy, korg1212->DataBufsSize);
2303 #endif
2304
2305         if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2306                                 korg1212->DataBufsSize, &korg1212->dma_rec) < 0) {
2307                 snd_printk(KERN_ERR "can not allocate record data buffer memory (%d bytes)\n", korg1212->DataBufsSize);
2308                 return -ENOMEM;
2309         }
2310         korg1212->recordDataBufsPtr = (KorgAudioBuffer *)korg1212->dma_rec.area;
2311         korg1212->RecDataPhy = korg1212->dma_rec.addr;
2312
2313 #if K1212_DEBUG_LEVEL > 0
2314         K1212_DEBUG_PRINTK("K1212_DEBUG: Record Data Area = 0x%p (0x%08x), %d bytes\n",
2315                 korg1212->recordDataBufsPtr, korg1212->RecDataBufsPhy, korg1212->DataBufsSize);
2316 #endif
2317
2318 #else // K1212_LARGEALLOC
2319
2320         korg1212->recordDataBufsPtr = korg1212->sharedBufferPtr->recordDataBufs;
2321         korg1212->playDataBufsPtr = korg1212->sharedBufferPtr->playDataBufs;
2322         korg1212->PlayDataPhy = (u32) &((KorgSharedBuffer *) korg1212->sharedBufferPhy)->playDataBufs;
2323         korg1212->RecDataPhy  = (u32) &((KorgSharedBuffer *) korg1212->sharedBufferPhy)->recordDataBufs;
2324
2325 #endif // K1212_LARGEALLOC
2326
2327         korg1212->dspCodeSize = sizeof (dspCode);
2328
2329         korg1212->VolumeTablePhy = korg1212->sharedBufferPhy +
2330                 offsetof(KorgSharedBuffer, volumeData);
2331         korg1212->RoutingTablePhy = korg1212->sharedBufferPhy +
2332                 offsetof(KorgSharedBuffer, routeData);
2333         korg1212->AdatTimeCodePhy = korg1212->sharedBufferPhy +
2334                 offsetof(KorgSharedBuffer, AdatTimeCode);
2335
2336         if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2337                                 korg1212->dspCodeSize, &korg1212->dma_dsp) < 0) {
2338                 snd_printk(KERN_ERR "can not allocate dsp code memory (%d bytes)\n", korg1212->dspCodeSize);
2339                 return -ENOMEM;
2340         }
2341
2342 #if K1212_DEBUG_LEVEL > 0
2343         K1212_DEBUG_PRINTK("K1212_DEBUG: DSP Code area = 0x%p (0x%08x) %d bytes [%s]\n",
2344                    korg1212->dma_dsp.area, korg1212->dma_dsp.addr, korg1212->dspCodeSize,
2345                    stateName[korg1212->cardState]);
2346 #endif
2347
2348         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_RebootCard, 0, 0, 0, 0);
2349
2350 #if K1212_DEBUG_LEVEL > 0
2351         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Reboot Card - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
2352 #endif
2353
2354         snd_korg1212_EnableCardInterrupts(korg1212);
2355
2356         mdelay(CARD_BOOT_DELAY_IN_MS);
2357
2358         if (snd_korg1212_downloadDSPCode(korg1212)) 
2359                 return -EBUSY;
2360
2361         printk(KERN_INFO "dspMemPhy       = %08x U[%08x]\n"
2362                "PlayDataPhy     = %08x L[%08x]\n"
2363                "RecDataPhy      = %08x L[%08x]\n"
2364                "VolumeTablePhy  = %08x L[%08x]\n"
2365                "RoutingTablePhy = %08x L[%08x]\n"
2366                "AdatTimeCodePhy = %08x L[%08x]\n",
2367                (int)korg1212->dma_dsp.addr,    UpperWordSwap(korg1212->dma_dsp.addr),
2368                korg1212->PlayDataPhy,     LowerWordSwap(korg1212->PlayDataPhy),
2369                korg1212->RecDataPhy,      LowerWordSwap(korg1212->RecDataPhy),
2370                korg1212->VolumeTablePhy,  LowerWordSwap(korg1212->VolumeTablePhy),
2371                korg1212->RoutingTablePhy, LowerWordSwap(korg1212->RoutingTablePhy),
2372                korg1212->AdatTimeCodePhy, LowerWordSwap(korg1212->AdatTimeCodePhy));
2373
2374         if ((err = snd_pcm_new(korg1212->card, "korg1212", 0, 1, 1, &korg1212->pcm)) < 0)
2375                 return err;
2376
2377         korg1212->pcm->private_data = korg1212;
2378         korg1212->pcm->private_free = snd_korg1212_free_pcm;
2379         strcpy(korg1212->pcm->name, "korg1212");
2380
2381         snd_pcm_set_ops(korg1212->pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_korg1212_playback_ops);
2382         
2383         snd_pcm_set_ops(korg1212->pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_korg1212_capture_ops);
2384
2385         korg1212->pcm->info_flags = SNDRV_PCM_INFO_JOINT_DUPLEX;
2386
2387         //snd_pcm_lib_preallocate_pages_for_all(korg1212->pcm,
2388         //                      K1212_MAX_BUF_SIZE, K1212_MAX_BUF_SIZE, GFP_KERNEL);
2389
2390         for (i = 0; i < ARRAY_SIZE(snd_korg1212_controls); i++) {
2391                 err = snd_ctl_add(korg1212->card, snd_ctl_new1(&snd_korg1212_controls[i], korg1212));
2392                 if (err < 0)
2393                         return err;
2394         }
2395
2396         snd_korg1212_proc_init(korg1212);
2397         
2398         if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, korg1212, &ops)) < 0) {
2399                 snd_korg1212_free(korg1212);
2400                 return err;
2401         }
2402         
2403         snd_card_set_dev(card, &pci->dev);
2404
2405         * rchip = korg1212;
2406         return 0;
2407
2408 }
2409
2410 /*
2411  * Card initialisation
2412  */
2413
2414 static int __devinit
2415 snd_korg1212_probe(struct pci_dev *pci,
2416                 const struct pci_device_id *pci_id)
2417 {
2418         static int dev;
2419         korg1212_t *korg1212;
2420         snd_card_t *card;
2421         int err;
2422
2423         if (dev >= SNDRV_CARDS) {
2424                 return -ENODEV;
2425         }
2426         if (!enable[dev]) {
2427                 dev++;
2428                 return -ENOENT;
2429         }
2430         card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
2431         if (card == NULL)
2432                 return -ENOMEM;
2433
2434         if ((err = snd_korg1212_create(card, pci, &korg1212)) < 0) {
2435                 snd_card_free(card);
2436                 return err;
2437         }
2438
2439         strcpy(card->driver, "korg1212");
2440         strcpy(card->shortname, "korg1212");
2441         sprintf(card->longname, "%s at 0x%lx, irq %d", card->shortname,
2442                 korg1212->iomem, korg1212->irq);
2443
2444 #if K1212_DEBUG_LEVEL > 0
2445         K1212_DEBUG_PRINTK("K1212_DEBUG: %s\n", card->longname);
2446 #endif
2447
2448         if ((err = snd_card_register(card)) < 0) {
2449                 snd_card_free(card);
2450                 return err;
2451         }
2452         pci_set_drvdata(pci, card);
2453         dev++;
2454         return 0;
2455 }
2456
2457 static void __devexit snd_korg1212_remove(struct pci_dev *pci)
2458 {
2459         snd_card_free(pci_get_drvdata(pci));
2460         pci_set_drvdata(pci, NULL);
2461 }
2462
2463 static struct pci_driver driver = {
2464         .name = "korg1212",
2465         .id_table = snd_korg1212_ids,
2466         .probe = snd_korg1212_probe,
2467         .remove = __devexit_p(snd_korg1212_remove),
2468 };
2469
2470 static int __init alsa_card_korg1212_init(void)
2471 {
2472         return pci_module_init(&driver);
2473 }
2474
2475 static void __exit alsa_card_korg1212_exit(void)
2476 {
2477         pci_unregister_driver(&driver);
2478 }
2479
2480 module_init(alsa_card_korg1212_init)
2481 module_exit(alsa_card_korg1212_exit)