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