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