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