upgrade to linux 2.6.10-1.12_FC2
[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 #define CARD_BOOT_TIMEOUT      10
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         void __iomem *iobase;
345
346         struct snd_dma_buffer dma_dsp;
347         struct snd_dma_buffer dma_play;
348         struct snd_dma_buffer dma_rec;
349         struct snd_dma_buffer dma_shared;
350
351         u32 dspCodeSize;
352
353         u32 DataBufsSize;
354
355         KorgAudioBuffer  * playDataBufsPtr;
356         KorgAudioBuffer  * recordDataBufsPtr;
357
358         KorgSharedBuffer * sharedBufferPtr;
359
360         u32 RecDataPhy;
361         u32 PlayDataPhy;
362         unsigned long sharedBufferPhy;
363         u32 VolumeTablePhy;
364         u32 RoutingTablePhy;
365         u32 AdatTimeCodePhy;
366
367         u32 __iomem * statusRegPtr;          // address of the interrupt status/control register
368         u32 __iomem * outDoorbellPtr;        // address of the host->card doorbell register
369         u32 __iomem * inDoorbellPtr;         // address of the card->host doorbell register
370         u32 __iomem * mailbox0Ptr;           // address of mailbox 0 on the card
371         u32 __iomem * mailbox1Ptr;           // address of mailbox 1 on the card
372         u32 __iomem * mailbox2Ptr;           // address of mailbox 2 on the card
373         u32 __iomem * mailbox3Ptr;           // address of mailbox 3 on the card
374         u32 __iomem * controlRegPtr;         // address of the EEPROM, PCI, I/O, Init ctrl reg
375         u16 __iomem * sensRegPtr;            // address of the sensitivity setting register
376         u32 __iomem * idRegPtr;              // address of the device and vendor ID registers
377
378         size_t periodsize;
379         int channels;
380         int currentBuffer;
381
382         snd_pcm_substream_t *playback_substream;
383         snd_pcm_substream_t *capture_substream;
384
385         pid_t capture_pid;
386         pid_t playback_pid;
387
388         CardState cardState;
389         int running;
390         int idleMonitorOn;           // indicates whether the card is in idle monitor mode.
391         u32 cmdRetryCount;           // tracks how many times we have retried sending to the card.
392
393         ClockSourceIndex clkSrcRate; // sample rate and clock source
394
395         ClockSourceType clkSource;   // clock source
396         int clkRate;                 // clock rate
397
398         int volumePhase[kAudioChannels];
399
400         u16 leftADCInSens;           // ADC left channel input sensitivity
401         u16 rightADCInSens;          // ADC right channel input sensitivity
402
403         int opencnt;                    // Open/Close count
404         int setcnt;                     // SetupForPlay count
405         int playcnt;                    // TriggerPlay count
406
407 };
408
409 MODULE_DESCRIPTION("korg1212");
410 MODULE_LICENSE("GPL");
411 MODULE_SUPPORTED_DEVICE("{{KORG,korg1212}}");
412
413 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;     /* Index 0-MAX */
414 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;          /* ID for this card */
415 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */
416
417 module_param_array(index, int, NULL, 0444);
418 MODULE_PARM_DESC(index, "Index value for Korg 1212 soundcard.");
419 module_param_array(id, charp, NULL, 0444);
420 MODULE_PARM_DESC(id, "ID string for Korg 1212 soundcard.");
421 module_param_array(enable, bool, NULL, 0444);
422 MODULE_PARM_DESC(enable, "Enable Korg 1212 soundcard.");
423 MODULE_AUTHOR("Haroldo Gamal <gamal@alternex.com.br>");
424
425 static struct pci_device_id snd_korg1212_ids[] = {
426         {
427                 .vendor    = 0x10b5,
428                 .device    = 0x906d,
429                 .subvendor = PCI_ANY_ID,
430                 .subdevice = PCI_ANY_ID,
431         },
432         { 0, },
433 };
434
435 static char* stateName[] = {
436                         "Non-existent",
437                         "Uninitialized",
438                         "DSP download in process",
439                         "DSP download complete",
440                         "Ready",
441                         "Open",
442                         "Setup for play",
443                         "Playing",
444                         "Monitor mode on",
445                         "Calibrating"
446                         "Invalid"
447 };
448
449 static char* clockSourceTypeName[] = { "ADAT", "S/PDIF", "local" };
450
451 static char* clockSourceName[] = {
452                         "ADAT at 44.1 kHz",
453                         "ADAT at 48 kHz",
454                         "S/PDIF at 44.1 kHz",
455                         "S/PDIF at 48 kHz",
456                         "local clock at 44.1 kHz",
457                         "local clock at 48 kHz"
458 };
459
460 static char* channelName[] = {
461                         "ADAT-1",
462                         "ADAT-2",
463                         "ADAT-3",
464                         "ADAT-4",
465                         "ADAT-5",
466                         "ADAT-6",
467                         "ADAT-7",
468                         "ADAT-8",
469                         "Analog-L",
470                         "Analog-R",
471                         "SPDIF-L",
472                         "SPDIF-R",
473 };
474
475 u16 ClockSourceSelector[] = {0x8000,   // selects source as ADAT at 44.1 kHz
476                              0x0000,   // selects source as ADAT at 48 kHz
477                              0x8001,   // selects source as S/PDIF at 44.1 kHz
478                              0x0001,   // selects source as S/PDIF at 48 kHz
479                              0x8002,   // selects source as local clock at 44.1 kHz
480                              0x0002    // selects source as local clock at 48 kHz
481                             };
482
483 static snd_korg1212rc rc;
484
485 MODULE_DEVICE_TABLE(pci, snd_korg1212_ids);
486
487 typedef union swap_u32 { unsigned char c[4]; u32 i; } swap_u32;
488
489 #ifdef SNDRV_BIG_ENDIAN
490 static u32 LowerWordSwap(u32 swappee)
491 #else
492 static u32 UpperWordSwap(u32 swappee)
493 #endif
494 {
495    swap_u32 retVal, swapper;
496
497    swapper.i = swappee;
498    retVal.c[2] = swapper.c[3];
499    retVal.c[3] = swapper.c[2];
500    retVal.c[1] = swapper.c[1];
501    retVal.c[0] = swapper.c[0];
502
503    return retVal.i;
504 }
505
506 #ifdef SNDRV_BIG_ENDIAN
507 static u32 UpperWordSwap(u32 swappee)
508 #else
509 static u32 LowerWordSwap(u32 swappee)
510 #endif
511 {
512    swap_u32 retVal, swapper;
513
514    swapper.i = swappee;
515    retVal.c[2] = swapper.c[2];
516    retVal.c[3] = swapper.c[3];
517    retVal.c[1] = swapper.c[0];
518    retVal.c[0] = swapper.c[1];
519
520    return retVal.i;
521 }
522
523 #if 0 /* not used */
524
525 static u32 EndianSwap(u32 swappee)
526 {
527    swap_u32 retVal, swapper;
528
529    swapper.i = swappee;
530    retVal.c[0] = swapper.c[3];
531    retVal.c[1] = swapper.c[2];
532    retVal.c[2] = swapper.c[1];
533    retVal.c[3] = swapper.c[0];
534
535    return retVal.i;
536 }
537
538 #endif /* not used */
539
540 #define SetBitInWord(theWord,bitPosition)       (*theWord) |= (0x0001 << bitPosition)
541 #define SetBitInDWord(theWord,bitPosition)      (*theWord) |= (0x00000001 << bitPosition)
542 #define ClearBitInWord(theWord,bitPosition)     (*theWord) &= ~(0x0001 << bitPosition)
543 #define ClearBitInDWord(theWord,bitPosition)    (*theWord) &= ~(0x00000001 << bitPosition)
544
545 static snd_korg1212rc snd_korg1212_Send1212Command(korg1212_t *korg1212, korg1212_dbcnst_t doorbellVal,
546                             u32 mailBox0Val, u32 mailBox1Val, u32 mailBox2Val, u32 mailBox3Val)
547 {
548         u32 retryCount;
549         u16 mailBox3Lo;
550         snd_korg1212rc rc = K1212_CMDRET_Success;
551
552         if (!korg1212->outDoorbellPtr) {
553 #if K1212_DEBUG_LEVEL > 1
554                 K1212_DEBUG_PRINTK("K1212_DEBUG: CardUninitialized\n");
555 #endif
556                 return K1212_CMDRET_CardUninitialized;
557         }
558
559 #if K1212_DEBUG_LEVEL > 0
560         K1212_DEBUG_PRINTK("K1212_DEBUG: Card <- 0x%08x 0x%08x [%s]\n", doorbellVal, mailBox0Val, stateName[korg1212->cardState]);
561 #endif
562         for (retryCount = 0; retryCount < MAX_COMMAND_RETRIES; retryCount++) {
563                 writel(mailBox3Val, korg1212->mailbox3Ptr);
564                 writel(mailBox2Val, korg1212->mailbox2Ptr);
565                 writel(mailBox1Val, korg1212->mailbox1Ptr);
566                 writel(mailBox0Val, korg1212->mailbox0Ptr);
567                 writel(doorbellVal, korg1212->outDoorbellPtr);  // interrupt the card
568
569                 // --------------------------------------------------------------
570                 // the reboot command will not give an acknowledgement.
571                 // --------------------------------------------------------------
572                 if ( doorbellVal == K1212_DB_RebootCard ||
573                         doorbellVal == K1212_DB_BootFromDSPPage4 ||
574                         doorbellVal == K1212_DB_StartDSPDownload ) {
575                         rc = K1212_CMDRET_Success;
576                         break;
577                 }
578
579                 // --------------------------------------------------------------
580                 // See if the card acknowledged the command.  Wait a bit, then
581                 // read in the low word of mailbox3.  If the MSB is set and the
582                 // low byte is equal to the doorbell value, then it ack'd.
583                 // --------------------------------------------------------------
584                 udelay(COMMAND_ACK_DELAY);
585                 mailBox3Lo = readl(korg1212->mailbox3Ptr);
586                 if (mailBox3Lo & COMMAND_ACK_MASK) {
587                         if ((mailBox3Lo & DOORBELL_VAL_MASK) == (doorbellVal & DOORBELL_VAL_MASK)) {
588 #if K1212_DEBUG_LEVEL > 1
589                                 K1212_DEBUG_PRINTK("K1212_DEBUG: Card <- Success\n");
590 #endif
591                                 rc = K1212_CMDRET_Success;
592                                 break;
593                         }
594                 }
595         }
596         korg1212->cmdRetryCount += retryCount;
597
598         if (retryCount >= MAX_COMMAND_RETRIES) {
599 #if K1212_DEBUG_LEVEL > 1
600                 K1212_DEBUG_PRINTK("K1212_DEBUG: Card <- NoAckFromCard\n");
601 #endif
602                 rc = K1212_CMDRET_NoAckFromCard;
603         }
604
605         return rc;
606 }
607
608 /* spinlock already held */
609 static void snd_korg1212_SendStop(korg1212_t *korg1212)
610 {
611         if (! korg1212->stop_pending_cnt) {
612                 writel(0xffffffff, &korg1212->sharedBufferPtr->cardCommand);
613                 /* program the timer */
614                 korg1212->stop_pending_cnt = HZ;
615                 korg1212->timer.expires = jiffies + 1;
616                 add_timer(&korg1212->timer);
617         }
618 }
619
620 static void snd_korg1212_SendStopAndWait(korg1212_t *korg1212)
621 {
622         unsigned long flags;
623         spin_lock_irqsave(&korg1212->lock, flags);
624         snd_korg1212_SendStop(korg1212);
625         spin_unlock_irqrestore(&korg1212->lock, flags);
626         sleep_on_timeout(&korg1212->wait, (HZ * 3) / 2);
627 }
628
629 /* timer callback for checking the ack of stop request */
630 static void snd_korg1212_timer_func(unsigned long data)
631 {
632         korg1212_t *korg1212 = (korg1212_t *) data;
633         
634         spin_lock(&korg1212->lock);
635         if (readl(&korg1212->sharedBufferPtr->cardCommand) == 0) {
636                 /* ack'ed */
637                 korg1212->stop_pending_cnt = 0;
638                 wake_up(&korg1212->wait);
639 #if K1212_DEBUG_LEVEL > 1
640                 K1212_DEBUG_PRINTK("K1212_DEBUG: Stop ack'ed [%s]\n", stateName[korg1212->cardState]);
641 #endif
642         } else {
643                 if (--korg1212->stop_pending_cnt > 0) {
644                         /* reprogram timer */
645                         korg1212->timer.expires = jiffies + 1;
646                         add_timer(&korg1212->timer);
647                 } else {
648                         snd_printd("korg1212_timer_func timeout\n");
649                         writel(0, &korg1212->sharedBufferPtr->cardCommand);
650                         wake_up(&korg1212->wait);
651 #if K1212_DEBUG_LEVEL > 0
652                         K1212_DEBUG_PRINTK("K1212_DEBUG: Stop timeout [%s]\n", stateName[korg1212->cardState]);
653 #endif
654                 }
655         }
656         spin_unlock(&korg1212->lock);
657 }
658
659 static void snd_korg1212_TurnOnIdleMonitor(korg1212_t *korg1212)
660 {
661         unsigned long flags;
662
663         udelay(INTERCOMMAND_DELAY);
664         spin_lock_irqsave(&korg1212->lock, flags);
665         korg1212->idleMonitorOn = 1;
666         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
667                                           K1212_MODE_MonitorOn, 0, 0, 0);
668         spin_unlock_irqrestore(&korg1212->lock, flags);
669 }
670
671 static void snd_korg1212_TurnOffIdleMonitor(korg1212_t *korg1212)
672 {
673         if (korg1212->idleMonitorOn) {
674                 snd_korg1212_SendStopAndWait(korg1212);
675                 korg1212->idleMonitorOn = 0;
676         }
677 }
678
679 static inline void snd_korg1212_setCardState(korg1212_t * korg1212, CardState csState)
680 {
681         korg1212->cardState = csState;
682 }
683
684 static int snd_korg1212_OpenCard(korg1212_t * korg1212)
685 {
686 #if K1212_DEBUG_LEVEL > 0
687         K1212_DEBUG_PRINTK("K1212_DEBUG: OpenCard [%s] %d\n", stateName[korg1212->cardState], korg1212->opencnt);
688 #endif
689         down(&korg1212->open_mutex);
690         if (korg1212->opencnt++ == 0) {
691                 snd_korg1212_TurnOffIdleMonitor(korg1212);
692                 snd_korg1212_setCardState(korg1212, K1212_STATE_OPEN);
693         }
694
695         up(&korg1212->open_mutex);
696         return 1;
697 }
698
699 static int snd_korg1212_CloseCard(korg1212_t * korg1212)
700 {
701 #if K1212_DEBUG_LEVEL > 0
702         K1212_DEBUG_PRINTK("K1212_DEBUG: CloseCard [%s] %d\n", stateName[korg1212->cardState], korg1212->opencnt);
703 #endif
704
705         down(&korg1212->open_mutex);
706         if (--(korg1212->opencnt)) {
707                 up(&korg1212->open_mutex);
708                 return 0;
709         }
710
711         if (korg1212->cardState == K1212_STATE_SETUP) {
712                 rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
713                                 K1212_MODE_StopPlay, 0, 0, 0);
714 #if K1212_DEBUG_LEVEL > 0
715         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: CloseCard - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
716 #endif
717
718                 if (rc != K1212_CMDRET_Success) {
719                         up(&korg1212->open_mutex);
720                         return 0;
721                 }
722         } else if (korg1212->cardState > K1212_STATE_SETUP) {
723                 snd_korg1212_SendStopAndWait(korg1212);
724         }
725
726         if (korg1212->cardState > K1212_STATE_READY) {
727                 snd_korg1212_TurnOnIdleMonitor(korg1212);
728                 snd_korg1212_setCardState(korg1212, K1212_STATE_READY);
729         }
730
731         up(&korg1212->open_mutex);
732         return 0;
733 }
734
735 /* spinlock already held */
736 static int snd_korg1212_SetupForPlay(korg1212_t * korg1212)
737 {
738 #if K1212_DEBUG_LEVEL > 0
739         K1212_DEBUG_PRINTK("K1212_DEBUG: SetupForPlay [%s] %d\n", stateName[korg1212->cardState], korg1212->setcnt);
740 #endif
741
742         if (korg1212->setcnt++)
743                 return 0;
744
745         snd_korg1212_setCardState(korg1212, K1212_STATE_SETUP);
746         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
747                                         K1212_MODE_SetupPlay, 0, 0, 0);
748
749 #if K1212_DEBUG_LEVEL > 0
750         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: SetupForPlay - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
751 #endif
752         if (rc != K1212_CMDRET_Success) {
753                 return 1;
754         }
755         return 0;
756 }
757
758 /* spinlock already held */
759 static int snd_korg1212_TriggerPlay(korg1212_t * korg1212)
760 {
761 #if K1212_DEBUG_LEVEL > 0
762         K1212_DEBUG_PRINTK("K1212_DEBUG: TriggerPlay [%s] %d\n", stateName[korg1212->cardState], korg1212->playcnt);
763 #endif
764
765         if (korg1212->playcnt++)
766                 return 0;
767
768         snd_korg1212_setCardState(korg1212, K1212_STATE_PLAYING);
769         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_TriggerPlay, 0, 0, 0, 0);
770
771 #if K1212_DEBUG_LEVEL > 0
772         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: TriggerPlay - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
773 #endif
774
775         if (rc != K1212_CMDRET_Success) {
776                 return 1;
777         }
778         return 0;
779 }
780
781 /* spinlock already held */
782 static int snd_korg1212_StopPlay(korg1212_t * korg1212)
783 {
784 #if K1212_DEBUG_LEVEL > 0
785         K1212_DEBUG_PRINTK("K1212_DEBUG: StopPlay [%s] %d\n", stateName[korg1212->cardState], korg1212->playcnt);
786 #endif
787
788         if (--(korg1212->playcnt)) 
789                 return 0;
790
791         korg1212->setcnt = 0;
792
793         if (korg1212->cardState != K1212_STATE_ERRORSTOP)
794                 snd_korg1212_SendStop(korg1212);
795
796         snd_korg1212_setCardState(korg1212, K1212_STATE_OPEN);
797         return 0;
798 }
799
800 static void snd_korg1212_EnableCardInterrupts(korg1212_t * korg1212)
801 {
802         writel(PCI_INT_ENABLE_BIT            |
803                PCI_DOORBELL_INT_ENABLE_BIT   |
804                LOCAL_INT_ENABLE_BIT          |
805                LOCAL_DOORBELL_INT_ENABLE_BIT |
806                LOCAL_DMA1_INT_ENABLE_BIT,
807                korg1212->statusRegPtr);
808 }
809
810 #if 0 /* not used */
811
812 static int snd_korg1212_SetMonitorMode(korg1212_t *korg1212, MonitorModeSelector mode)
813 {
814 #if K1212_DEBUG_LEVEL > 0
815         K1212_DEBUG_PRINTK("K1212_DEBUG: SetMonitorMode [%s]\n", stateName[korg1212->cardState]);
816 #endif
817
818         switch (mode) {
819                 case K1212_MONMODE_Off:
820                         if (korg1212->cardState != K1212_STATE_MONITOR) {
821                                 return 0;
822                         } else {
823                                 snd_korg1212_SendStopAndWait(korg1212);
824                                 snd_korg1212_setCardState(korg1212, K1212_STATE_OPEN);
825                         }
826                         break;
827
828                 case K1212_MONMODE_On:
829                         if (korg1212->cardState != K1212_STATE_OPEN) {
830                                 return 0;
831                         } else {
832                                 snd_korg1212_setCardState(korg1212, K1212_STATE_MONITOR);
833                                 rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
834                                                         K1212_MODE_MonitorOn, 0, 0, 0);
835                                 if (rc != K1212_CMDRET_Success) {
836                                         return 0;
837                                 }
838                         }
839                         break;
840
841                 default:
842                         return 0;
843         }
844
845         return 1;
846 }
847
848 #endif /* not used */
849
850 static inline int snd_korg1212_use_is_exclusive(korg1212_t *korg1212)
851 {
852         unsigned long flags;
853         int ret = 1;
854
855         spin_lock_irqsave(&korg1212->lock, flags);
856         if ((korg1212->playback_pid != korg1212->capture_pid) &&
857             (korg1212->playback_pid >= 0) && (korg1212->capture_pid >= 0)) {
858                 ret = 0;
859         }
860         spin_unlock_irqrestore(&korg1212->lock, flags);
861         return ret;
862 }
863
864 static int snd_korg1212_SetRate(korg1212_t *korg1212, int rate)
865 {
866         static ClockSourceIndex s44[] = { K1212_CLKIDX_AdatAt44_1K,
867                                           K1212_CLKIDX_WordAt44_1K,
868                                           K1212_CLKIDX_LocalAt44_1K };
869         static ClockSourceIndex s48[] = {
870                                           K1212_CLKIDX_AdatAt48K,
871                                           K1212_CLKIDX_WordAt48K,
872                                           K1212_CLKIDX_LocalAt48K };
873         int parm;
874
875         if (!snd_korg1212_use_is_exclusive (korg1212)) {
876                 return -EBUSY;
877         }
878
879         switch(rate) {
880                 case 44100:
881                 parm = s44[korg1212->clkSource];
882                 break;
883
884                 case 48000:
885                 parm = s48[korg1212->clkSource];
886                 break;
887
888                 default:
889                 return -EINVAL;
890         }
891
892         korg1212->clkSrcRate = parm;
893         korg1212->clkRate = rate;
894
895         udelay(INTERCOMMAND_DELAY);
896         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SetClockSourceRate,
897                                           ClockSourceSelector[korg1212->clkSrcRate],
898                                           0, 0, 0);
899
900 #if K1212_DEBUG_LEVEL > 0
901         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Set Clock Source Selector - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
902 #endif
903
904         return 0;
905 }
906
907 static int snd_korg1212_SetClockSource(korg1212_t *korg1212, int source)
908 {
909
910         if (source<0 || source >2)
911            return -EINVAL;
912
913         korg1212->clkSource = source;
914
915         snd_korg1212_SetRate(korg1212, korg1212->clkRate);
916
917         return 0;
918 }
919
920 static void snd_korg1212_DisableCardInterrupts(korg1212_t *korg1212)
921 {
922         writel(0, korg1212->statusRegPtr);
923 }
924
925 static int snd_korg1212_WriteADCSensitivity(korg1212_t *korg1212)
926 {
927         SensBits  sensVals;
928         int       bitPosition;
929         int       channel;
930         int       clkIs48K;
931         int       monModeSet;
932         u16       controlValue;    // this keeps the current value to be written to
933                                    //  the card's eeprom control register.
934         u16       count;
935         unsigned long flags;
936
937 #if K1212_DEBUG_LEVEL > 0
938         K1212_DEBUG_PRINTK("K1212_DEBUG: WriteADCSensivity [%s]\n", stateName[korg1212->cardState]);
939 #endif
940
941         // ----------------------------------------------------------------------------
942         // initialize things.  The local init bit is always set when writing to the
943         // card's control register.
944         // ----------------------------------------------------------------------------
945         controlValue = 0;
946         SetBitInWord(&controlValue, SET_SENS_LOCALINIT_BITPOS);    // init the control value
947
948         // ----------------------------------------------------------------------------
949         // make sure the card is not in monitor mode when we do this update.
950         // ----------------------------------------------------------------------------
951         if (korg1212->cardState == K1212_STATE_MONITOR || korg1212->idleMonitorOn) {
952                 monModeSet = 1;
953                 snd_korg1212_SendStopAndWait(korg1212);
954         } else
955                 monModeSet = 0;
956
957         spin_lock_irqsave(&korg1212->lock, flags);
958
959         // ----------------------------------------------------------------------------
960         // we are about to send new values to the card, so clear the new values queued
961         // flag.  Also, clear out mailbox 3, so we don't lockup.
962         // ----------------------------------------------------------------------------
963         writel(0, korg1212->mailbox3Ptr);
964         udelay(LOADSHIFT_DELAY);
965
966         // ----------------------------------------------------------------------------
967         // determine whether we are running a 48K or 44.1K clock.  This info is used
968         // later when setting the SPDIF FF after the volume has been shifted in.
969         // ----------------------------------------------------------------------------
970         switch (korg1212->clkSrcRate) {
971                 case K1212_CLKIDX_AdatAt44_1K:
972                 case K1212_CLKIDX_WordAt44_1K:
973                 case K1212_CLKIDX_LocalAt44_1K:
974                         clkIs48K = 0;
975                         break;
976
977                 case K1212_CLKIDX_WordAt48K:
978                 case K1212_CLKIDX_AdatAt48K:
979                 case K1212_CLKIDX_LocalAt48K:
980                 default:
981                         clkIs48K = 1;
982                         break;
983         }
984
985         // ----------------------------------------------------------------------------
986         // start the update.  Setup the bit structure and then shift the bits.
987         // ----------------------------------------------------------------------------
988         sensVals.l.v.leftChanId   = SET_SENS_LEFTCHANID;
989         sensVals.r.v.rightChanId  = SET_SENS_RIGHTCHANID;
990         sensVals.l.v.leftChanVal  = korg1212->leftADCInSens;
991         sensVals.r.v.rightChanVal = korg1212->rightADCInSens;
992
993         // ----------------------------------------------------------------------------
994         // now start shifting the bits in.  Start with the left channel then the right.
995         // ----------------------------------------------------------------------------
996         for (channel = 0; channel < 2; channel++) {
997
998                 // ----------------------------------------------------------------------------
999                 // Bring the load/shift line low, then wait - the spec says >150ns from load/
1000                 // shift low to the first rising edge of the clock.
1001                 // ----------------------------------------------------------------------------
1002                 ClearBitInWord(&controlValue, SET_SENS_LOADSHIFT_BITPOS);
1003                 ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);
1004                 writew(controlValue, korg1212->sensRegPtr);                          // load/shift goes low
1005                 udelay(LOADSHIFT_DELAY);
1006
1007                 for (bitPosition = 15; bitPosition >= 0; bitPosition--) {       // for all the bits
1008                         if (channel == 0) {
1009                                 if (sensVals.l.leftSensBits & (0x0001 << bitPosition)) {
1010                                         SetBitInWord(&controlValue, SET_SENS_DATA_BITPOS);     // data bit set high
1011                                 } else {
1012                                         ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);   // data bit set low
1013                                 }
1014                         } else {
1015                                 if (sensVals.r.rightSensBits & (0x0001 << bitPosition)) {
1016                                 SetBitInWord(&controlValue, SET_SENS_DATA_BITPOS);     // data bit set high
1017                                 } else {
1018                                 ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);   // data bit set low
1019                                 }
1020                         }
1021
1022                         ClearBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1023                         writew(controlValue, korg1212->sensRegPtr);                       // clock goes low
1024                         udelay(SENSCLKPULSE_WIDTH);
1025                         SetBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1026                         writew(controlValue, korg1212->sensRegPtr);                       // clock goes high
1027                         udelay(SENSCLKPULSE_WIDTH);
1028                 }
1029
1030                 // ----------------------------------------------------------------------------
1031                 // finish up SPDIF for left.  Bring the load/shift line high, then write a one
1032                 // bit if the clock rate is 48K otherwise write 0.
1033                 // ----------------------------------------------------------------------------
1034                 ClearBitInWord(&controlValue, SET_SENS_DATA_BITPOS);
1035                 ClearBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1036                 SetBitInWord(&controlValue, SET_SENS_LOADSHIFT_BITPOS);
1037                 writew(controlValue, korg1212->sensRegPtr);                   // load shift goes high - clk low
1038                 udelay(SENSCLKPULSE_WIDTH);
1039
1040                 if (clkIs48K)
1041                         SetBitInWord(&controlValue, SET_SENS_DATA_BITPOS);
1042
1043                 writew(controlValue, korg1212->sensRegPtr);                   // set/clear data bit
1044                 udelay(ONE_RTC_TICK);
1045                 SetBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1046                 writew(controlValue, korg1212->sensRegPtr);                   // clock goes high
1047                 udelay(SENSCLKPULSE_WIDTH);
1048                 ClearBitInWord(&controlValue, SET_SENS_CLOCK_BITPOS);
1049                 writew(controlValue, korg1212->sensRegPtr);                   // clock goes low
1050                 udelay(SENSCLKPULSE_WIDTH);
1051         }
1052
1053         // ----------------------------------------------------------------------------
1054         // The update is complete.  Set a timeout.  This is the inter-update delay.
1055         // Also, if the card was in monitor mode, restore it.
1056         // ----------------------------------------------------------------------------
1057         for (count = 0; count < 10; count++)
1058                 udelay(SENSCLKPULSE_WIDTH);
1059
1060         if (monModeSet) {
1061                 rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SelectPlayMode,
1062                                 K1212_MODE_MonitorOn, 0, 0, 0);
1063 #if K1212_DEBUG_LEVEL > 0
1064                 if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: WriteADCSensivity - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1065 #endif
1066
1067         }
1068
1069         spin_unlock_irqrestore(&korg1212->lock, flags);
1070
1071         return 1;
1072 }
1073
1074 static void snd_korg1212_OnDSPDownloadComplete(korg1212_t *korg1212)
1075 {
1076         int channel;
1077
1078 #if K1212_DEBUG_LEVEL > 0
1079         K1212_DEBUG_PRINTK("K1212_DEBUG: DSP download is complete. [%s]\n", stateName[korg1212->cardState]);
1080 #endif
1081
1082         // ----------------------------------------------------
1083         // tell the card to boot
1084         // ----------------------------------------------------
1085         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_BootFromDSPPage4, 0, 0, 0, 0);
1086
1087 #if K1212_DEBUG_LEVEL > 0
1088         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Boot from Page 4 - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1089 #endif
1090         mdelay(DSP_BOOT_DELAY_IN_MS);
1091
1092         // --------------------------------------------------------------------------------
1093         // Let the card know where all the buffers are.
1094         // --------------------------------------------------------------------------------
1095         rc = snd_korg1212_Send1212Command(korg1212,
1096                         K1212_DB_ConfigureBufferMemory,
1097                         LowerWordSwap(korg1212->PlayDataPhy),
1098                         LowerWordSwap(korg1212->RecDataPhy),
1099                         ((kNumBuffers * kPlayBufferFrames) / 2),   // size given to the card
1100                                                                    // is based on 2 buffers
1101                         0
1102         );
1103
1104 #if K1212_DEBUG_LEVEL > 0
1105         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Configure Buffer Memory - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1106 #endif
1107
1108         udelay(INTERCOMMAND_DELAY);
1109
1110         rc = snd_korg1212_Send1212Command(korg1212,
1111                         K1212_DB_ConfigureMiscMemory,
1112                         LowerWordSwap(korg1212->VolumeTablePhy),
1113                         LowerWordSwap(korg1212->RoutingTablePhy),
1114                         LowerWordSwap(korg1212->AdatTimeCodePhy),
1115                         0
1116         );
1117
1118 #if K1212_DEBUG_LEVEL > 0
1119         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Configure Misc Memory - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1120 #endif
1121
1122
1123         // --------------------------------------------------------------------------------
1124         // Initialize the routing and volume tables, then update the card's state.
1125         // --------------------------------------------------------------------------------
1126         udelay(INTERCOMMAND_DELAY);
1127
1128         for (channel = 0; channel < kAudioChannels; channel++) {
1129                 korg1212->sharedBufferPtr->volumeData[channel] = k1212MaxVolume;
1130                 //korg1212->sharedBufferPtr->routeData[channel] = channel;
1131                 korg1212->sharedBufferPtr->routeData[channel] = 8 + (channel & 1);
1132         }
1133
1134         snd_korg1212_WriteADCSensitivity(korg1212);
1135
1136         udelay(INTERCOMMAND_DELAY);
1137         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_SetClockSourceRate,
1138                                           ClockSourceSelector[korg1212->clkSrcRate],
1139                                           0, 0, 0);
1140 #if K1212_DEBUG_LEVEL > 0
1141         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Set Clock Source Selector - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1142 #endif
1143
1144         snd_korg1212_TurnOnIdleMonitor(korg1212);
1145         snd_korg1212_setCardState(korg1212, K1212_STATE_READY);
1146
1147 #if K1212_DEBUG_LEVEL > 0
1148         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Set Monitor On - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1149 #endif
1150
1151         snd_korg1212_setCardState(korg1212, K1212_STATE_DSP_COMPLETE);
1152 }
1153
1154 static irqreturn_t snd_korg1212_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1155 {
1156         u32 doorbellValue;
1157         korg1212_t *korg1212 = dev_id;
1158
1159         if(irq != korg1212->irq)
1160                 return IRQ_NONE;
1161
1162         doorbellValue = readl(korg1212->inDoorbellPtr);
1163
1164         if (!doorbellValue)
1165                 return IRQ_NONE;
1166
1167         spin_lock(&korg1212->lock);
1168
1169         writel(doorbellValue, korg1212->inDoorbellPtr);
1170
1171         korg1212->irqcount++;
1172
1173         korg1212->inIRQ++;
1174
1175
1176         switch (doorbellValue) {
1177                 case K1212_DB_DSPDownloadDone:
1178 #if K1212_DEBUG_LEVEL > 0
1179                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ DNLD count - %ld, %x, [%s].\n", korg1212->irqcount, doorbellValue, stateName[korg1212->cardState]);
1180 #endif
1181                         if (korg1212->cardState == K1212_STATE_DSP_IN_PROCESS)
1182                                 wake_up(&korg1212->wait);
1183                         break;
1184
1185                 // ------------------------------------------------------------------------
1186                 // an error occurred - stop the card
1187                 // ------------------------------------------------------------------------
1188                 case K1212_ISRCODE_DMAERROR:
1189 #if K1212_DEBUG_LEVEL > 1
1190                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ DMAE count - %ld, %x, [%s].\n", korg1212->irqcount, doorbellValue, stateName[korg1212->cardState]);
1191 #endif
1192                         writel(0, &korg1212->sharedBufferPtr->cardCommand);
1193                         snd_korg1212_setCardState(korg1212, K1212_STATE_ERRORSTOP);
1194                         break;
1195
1196                 // ------------------------------------------------------------------------
1197                 // the card has stopped by our request.  Clear the command word and signal
1198                 // the semaphore in case someone is waiting for this.
1199                 // ------------------------------------------------------------------------
1200                 case K1212_ISRCODE_CARDSTOPPED:
1201 #if K1212_DEBUG_LEVEL > 1
1202                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ CSTP count - %ld, %x, [%s].\n", korg1212->irqcount, doorbellValue, stateName[korg1212->cardState]);
1203 #endif
1204                         writel(0, &korg1212->sharedBufferPtr->cardCommand);
1205                         break;
1206
1207                 default:
1208 #if K1212_DEBUG_LEVEL > 3
1209                         K1212_DEBUG_PRINTK("K1212_DEBUG: IRQ DFLT count - %ld, %x, cpos=%d [%s].\n", korg1212->irqcount, doorbellValue, 
1210                                 korg1212->currentBuffer, stateName[korg1212->cardState]);
1211 #endif
1212                         if ((korg1212->cardState > K1212_STATE_SETUP) || korg1212->idleMonitorOn) {
1213                                 korg1212->currentBuffer++;
1214
1215                                 if (korg1212->currentBuffer >= kNumBuffers)
1216                                         korg1212->currentBuffer = 0;
1217
1218                                 if (!korg1212->running)
1219                                         break;
1220
1221                                 if (korg1212->capture_substream) {
1222                                         spin_unlock(&korg1212->lock);
1223                                         snd_pcm_period_elapsed(korg1212->capture_substream);
1224                                         spin_lock(&korg1212->lock);
1225                                 }
1226
1227                                 if (korg1212->playback_substream) {
1228                                         spin_unlock(&korg1212->lock);
1229                                         snd_pcm_period_elapsed(korg1212->playback_substream);
1230                                         spin_lock(&korg1212->lock);
1231                                 }
1232                         }
1233                         break;
1234         }
1235
1236         korg1212->inIRQ--;
1237
1238         spin_unlock(&korg1212->lock);
1239
1240         return IRQ_HANDLED;
1241 }
1242
1243 static int snd_korg1212_downloadDSPCode(korg1212_t *korg1212)
1244 {
1245
1246 #if K1212_DEBUG_LEVEL > 0
1247         K1212_DEBUG_PRINTK("K1212_DEBUG: DSP download is starting... [%s]\n", stateName[korg1212->cardState]);
1248 #endif
1249
1250         // ---------------------------------------------------------------
1251         // verify the state of the card before proceeding.
1252         // ---------------------------------------------------------------
1253         if (korg1212->cardState >= K1212_STATE_DSP_IN_PROCESS) {
1254                 return 1;
1255         }
1256
1257         snd_korg1212_setCardState(korg1212, K1212_STATE_DSP_IN_PROCESS);
1258
1259         memcpy(korg1212->dma_dsp.area, dspCode, korg1212->dspCodeSize);
1260
1261         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_StartDSPDownload,
1262                                      UpperWordSwap(korg1212->dma_dsp.addr),
1263                                      0, 0, 0);
1264
1265 #if K1212_DEBUG_LEVEL > 0
1266         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Start DSP Download RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
1267 #endif
1268
1269         if (! sleep_on_timeout(&korg1212->wait, HZ * CARD_BOOT_TIMEOUT))
1270                 return -EBUSY; /* timeout */
1271
1272         snd_korg1212_OnDSPDownloadComplete(korg1212);
1273
1274         return 0;
1275 }
1276
1277 static snd_pcm_hardware_t snd_korg1212_playback_info =
1278 {
1279         .info =              (SNDRV_PCM_INFO_MMAP |
1280                               SNDRV_PCM_INFO_MMAP_VALID |
1281                               SNDRV_PCM_INFO_INTERLEAVED),
1282         .formats =            SNDRV_PCM_FMTBIT_S16_LE,
1283         .rates =              (SNDRV_PCM_RATE_44100 |
1284                               SNDRV_PCM_RATE_48000),
1285         .rate_min =           44100,
1286         .rate_max =           48000,
1287         .channels_min =       K1212_MIN_CHANNELS,
1288         .channels_max =       K1212_MAX_CHANNELS,
1289         .buffer_bytes_max =   K1212_MAX_BUF_SIZE,
1290         .period_bytes_min =   K1212_MIN_CHANNELS * 2 * kPlayBufferFrames,
1291         .period_bytes_max =   K1212_MAX_CHANNELS * 2 * kPlayBufferFrames,
1292         .periods_min =        K1212_PERIODS,
1293         .periods_max =        K1212_PERIODS,
1294         .fifo_size =          0,
1295 };
1296
1297 static snd_pcm_hardware_t snd_korg1212_capture_info =
1298 {
1299         .info =              (SNDRV_PCM_INFO_MMAP |
1300                               SNDRV_PCM_INFO_MMAP_VALID |
1301                               SNDRV_PCM_INFO_INTERLEAVED),
1302         .formats =            SNDRV_PCM_FMTBIT_S16_LE,
1303         .rates =              (SNDRV_PCM_RATE_44100 |
1304                               SNDRV_PCM_RATE_48000),
1305         .rate_min =           44100,
1306         .rate_max =           48000,
1307         .channels_min =       K1212_MIN_CHANNELS,
1308         .channels_max =       K1212_MAX_CHANNELS,
1309         .buffer_bytes_max =   K1212_MAX_BUF_SIZE,
1310         .period_bytes_min =   K1212_MIN_CHANNELS * 2 * kPlayBufferFrames,
1311         .period_bytes_max =   K1212_MAX_CHANNELS * 2 * kPlayBufferFrames,
1312         .periods_min =        K1212_PERIODS,
1313         .periods_max =        K1212_PERIODS,
1314         .fifo_size =          0,
1315 };
1316
1317 static int snd_korg1212_silence(korg1212_t *korg1212, int pos, int count, int offset, int size)
1318 {
1319         KorgAudioFrame * dst =  korg1212->playDataBufsPtr[0].bufferData + pos;
1320         int i;
1321
1322 #if K1212_DEBUG_LEVEL > 2
1323         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_silence pos=%d offset=%d size=%d count=%d\n", pos, offset, size, count);
1324 #endif
1325         snd_assert(pos + count <= K1212_MAX_SAMPLES, return -EINVAL);
1326
1327         for (i=0; i < count; i++) {
1328 #if K1212_DEBUG_LEVEL > 0
1329                 if ( (void *) dst < (void *) korg1212->playDataBufsPtr ||
1330                      (void *) dst > (void *) korg1212->playDataBufsPtr[8].bufferData ) {
1331                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_silence KERNEL EFAULT dst=%p iter=%d\n", dst, i);
1332                         return -EFAULT;
1333                 }
1334 #endif
1335                 memset((void*) dst + offset, 0, size);
1336                 dst++;
1337         }
1338
1339         return 0;
1340 }
1341
1342 static int snd_korg1212_copy_to(korg1212_t *korg1212, void __user *dst, int pos, int count, int offset, int size)
1343 {
1344         KorgAudioFrame * src =  korg1212->recordDataBufsPtr[0].bufferData + pos;
1345         int i, rc;
1346
1347 #if K1212_DEBUG_LEVEL > 2
1348         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_to pos=%d offset=%d size=%d\n", pos, offset, size);
1349 #endif
1350         snd_assert(pos + count <= K1212_MAX_SAMPLES, return -EINVAL);
1351
1352         for (i=0; i < count; i++) {
1353 #if K1212_DEBUG_LEVEL > 0
1354                 if ( (void *) src < (void *) korg1212->recordDataBufsPtr ||
1355                      (void *) src > (void *) korg1212->recordDataBufsPtr[8].bufferData ) {
1356                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_to KERNEL EFAULT, src=%p dst=%p iter=%d\n", src, dst, i);
1357                         return -EFAULT;
1358                 }
1359 #endif
1360                 rc = copy_to_user(dst + offset, src, size);
1361                 if (rc) {
1362 #if K1212_DEBUG_LEVEL > 0
1363                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_to USER EFAULT src=%p dst=%p iter=%d\n", src, dst, i);
1364 #endif
1365                         return -EFAULT;
1366                 }
1367                 src++;
1368                 dst += size;
1369         }
1370
1371         return 0;
1372 }
1373
1374 static int snd_korg1212_copy_from(korg1212_t *korg1212, void __user *src, int pos, int count, int offset, int size)
1375 {
1376         KorgAudioFrame * dst =  korg1212->playDataBufsPtr[0].bufferData + pos;
1377         int i, rc;
1378
1379 #if K1212_DEBUG_LEVEL > 2
1380         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_from pos=%d offset=%d size=%d count=%d\n", pos, offset, size, count);
1381 #endif
1382
1383         snd_assert(pos + count <= K1212_MAX_SAMPLES, return -EINVAL);
1384
1385         for (i=0; i < count; i++) {
1386 #if K1212_DEBUG_LEVEL > 0
1387                 if ( (void *) dst < (void *) korg1212->playDataBufsPtr ||
1388                      (void *) dst > (void *) korg1212->playDataBufsPtr[8].bufferData ) {
1389                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_from KERNEL EFAULT, src=%p dst=%p iter=%d\n", src, dst, i);
1390                         return -EFAULT;
1391                 }
1392 #endif
1393                 rc = copy_from_user((void*) dst + offset, src, size);
1394                 if (rc) {
1395 #if K1212_DEBUG_LEVEL > 0
1396                         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_copy_from USER EFAULT src=%p dst=%p iter=%d\n", src, dst, i);
1397 #endif
1398                         return -EFAULT;
1399                 }
1400                 dst++;
1401                 src += size;
1402         }
1403
1404         return 0;
1405 }
1406
1407 static void snd_korg1212_free_pcm(snd_pcm_t *pcm)
1408 {
1409         korg1212_t *korg1212 = (korg1212_t *) pcm->private_data;
1410
1411 #if K1212_DEBUG_LEVEL > 0
1412                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_free_pcm [%s]\n", stateName[korg1212->cardState]);
1413 #endif
1414
1415         korg1212->pcm = NULL;
1416 }
1417
1418 static int snd_korg1212_playback_open(snd_pcm_substream_t *substream)
1419 {
1420         unsigned long flags;
1421         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1422         snd_pcm_runtime_t *runtime = substream->runtime;
1423
1424 #if K1212_DEBUG_LEVEL > 0
1425                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_open [%s]\n", stateName[korg1212->cardState]);
1426 #endif
1427
1428         snd_pcm_set_sync(substream);    // ???
1429
1430         snd_korg1212_OpenCard(korg1212);
1431
1432         runtime->hw = snd_korg1212_playback_info;
1433         snd_pcm_set_runtime_buffer(substream, &korg1212->dma_play);
1434
1435         spin_lock_irqsave(&korg1212->lock, flags);
1436
1437         korg1212->playback_substream = substream;
1438         korg1212->playback_pid = current->pid;
1439         korg1212->periodsize = K1212_PERIODS;
1440         korg1212->channels = K1212_CHANNELS;
1441
1442         spin_unlock_irqrestore(&korg1212->lock, flags);
1443
1444         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, kPlayBufferFrames, kPlayBufferFrames);
1445         return 0;
1446 }
1447
1448
1449 static int snd_korg1212_capture_open(snd_pcm_substream_t *substream)
1450 {
1451         unsigned long flags;
1452         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1453         snd_pcm_runtime_t *runtime = substream->runtime;
1454
1455 #if K1212_DEBUG_LEVEL > 0
1456                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_open [%s]\n", stateName[korg1212->cardState]);
1457 #endif
1458
1459         snd_pcm_set_sync(substream);    // ???
1460
1461         snd_korg1212_OpenCard(korg1212);
1462
1463         runtime->hw = snd_korg1212_capture_info;
1464         snd_pcm_set_runtime_buffer(substream, &korg1212->dma_rec);
1465
1466         spin_lock_irqsave(&korg1212->lock, flags);
1467
1468         korg1212->capture_substream = substream;
1469         korg1212->capture_pid = current->pid;
1470         korg1212->periodsize = K1212_PERIODS;
1471         korg1212->channels = K1212_CHANNELS;
1472
1473         spin_unlock_irqrestore(&korg1212->lock, flags);
1474
1475         snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, kPlayBufferFrames, kPlayBufferFrames);
1476         return 0;
1477 }
1478
1479 static int snd_korg1212_playback_close(snd_pcm_substream_t *substream)
1480 {
1481         unsigned long flags;
1482         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1483
1484 #if K1212_DEBUG_LEVEL > 0
1485                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_close [%s]\n", stateName[korg1212->cardState]);
1486 #endif
1487
1488         snd_korg1212_silence(korg1212, 0, K1212_MAX_SAMPLES, 0, korg1212->channels * 2);
1489
1490         spin_lock_irqsave(&korg1212->lock, flags);
1491
1492         korg1212->playback_pid = -1;
1493         korg1212->playback_substream = NULL;
1494         korg1212->periodsize = 0;
1495
1496         spin_unlock_irqrestore(&korg1212->lock, flags);
1497
1498         snd_korg1212_CloseCard(korg1212);
1499         return 0;
1500 }
1501
1502 static int snd_korg1212_capture_close(snd_pcm_substream_t *substream)
1503 {
1504         unsigned long flags;
1505         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1506
1507 #if K1212_DEBUG_LEVEL > 0
1508                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_close [%s]\n", stateName[korg1212->cardState]);
1509 #endif
1510
1511         spin_lock_irqsave(&korg1212->lock, flags);
1512
1513         korg1212->capture_pid = -1;
1514         korg1212->capture_substream = NULL;
1515         korg1212->periodsize = 0;
1516
1517         spin_unlock_irqrestore(&korg1212->lock, flags);
1518
1519         snd_korg1212_CloseCard(korg1212);
1520         return 0;
1521 }
1522
1523 static int snd_korg1212_ioctl(snd_pcm_substream_t *substream,
1524                              unsigned int cmd, void *arg)
1525 {
1526 #if K1212_DEBUG_LEVEL > 0
1527                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_ioctl: cmd=%d\n", cmd);
1528 #endif
1529
1530         if (cmd == SNDRV_PCM_IOCTL1_CHANNEL_INFO ) {
1531                 snd_pcm_channel_info_t *info = arg;
1532                 info->offset = 0;
1533                 info->first = info->channel * 16;
1534                 info->step = 256;
1535 #if K1212_DEBUG_LEVEL > 0
1536                 K1212_DEBUG_PRINTK("K1212_DEBUG: channel_info %d:, offset=%ld, first=%d, step=%d\n", info->channel, info->offset, info->first, info->step);
1537 #endif
1538                 return 0;
1539         }
1540
1541         return snd_pcm_lib_ioctl(substream, cmd, arg);
1542 }
1543
1544 static int snd_korg1212_hw_params(snd_pcm_substream_t *substream,
1545                              snd_pcm_hw_params_t *params)
1546 {
1547         unsigned long flags;
1548         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1549         int err;
1550         pid_t this_pid;
1551         pid_t other_pid;
1552
1553 #if K1212_DEBUG_LEVEL > 0
1554                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_hw_params [%s]\n", stateName[korg1212->cardState]);
1555 #endif
1556
1557         spin_lock_irqsave(&korg1212->lock, flags);
1558
1559         if (substream->pstr->stream == SNDRV_PCM_STREAM_PLAYBACK) {
1560                 this_pid = korg1212->playback_pid;
1561                 other_pid = korg1212->capture_pid;
1562         } else {
1563                 this_pid = korg1212->capture_pid;
1564                 other_pid = korg1212->playback_pid;
1565         }
1566
1567         if ((other_pid > 0) && (this_pid != other_pid)) {
1568
1569                 /* The other stream is open, and not by the same
1570                    task as this one. Make sure that the parameters
1571                    that matter are the same.
1572                  */
1573
1574                 if ((int)params_rate(params) != korg1212->clkRate) {
1575                         spin_unlock_irqrestore(&korg1212->lock, flags);
1576                         _snd_pcm_hw_param_setempty(params, SNDRV_PCM_HW_PARAM_RATE);
1577                         return -EBUSY;
1578                 }
1579
1580                 spin_unlock_irqrestore(&korg1212->lock, flags);
1581                 return 0;
1582         }
1583
1584         if ((err = snd_korg1212_SetRate(korg1212, params_rate(params))) < 0) {
1585                 spin_unlock_irqrestore(&korg1212->lock, flags);
1586                 return err;
1587         }
1588
1589         korg1212->channels = params_channels(params);
1590         korg1212->periodsize = K1212_PERIOD_BYTES;
1591
1592         spin_unlock_irqrestore(&korg1212->lock, flags);
1593
1594         return 0;
1595 }
1596
1597 static int snd_korg1212_prepare(snd_pcm_substream_t *substream)
1598 {
1599         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1600         int rc;
1601
1602 #if K1212_DEBUG_LEVEL > 0
1603                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_prepare [%s]\n", stateName[korg1212->cardState]);
1604 #endif
1605
1606         spin_lock_irq(&korg1212->lock);
1607
1608         /* FIXME: we should wait for ack! */
1609         if (korg1212->stop_pending_cnt > 0) {
1610 #if K1212_DEBUG_LEVEL > 0
1611                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_prepare - Stop is pending... [%s]\n", stateName[korg1212->cardState]);
1612 #endif
1613                 spin_unlock_irq(&korg1212->lock);
1614                 return -EAGAIN;
1615                 /*
1616                 writel(0, &korg1212->sharedBufferPtr->cardCommand);
1617                 del_timer(&korg1212->timer);
1618                 korg1212->stop_pending_cnt = 0;
1619                 */
1620         }
1621
1622         rc = snd_korg1212_SetupForPlay(korg1212);
1623
1624         korg1212->currentBuffer = 0;
1625
1626         spin_unlock_irq(&korg1212->lock);
1627
1628         return rc ? -EINVAL : 0;
1629 }
1630
1631 static int snd_korg1212_trigger(snd_pcm_substream_t *substream,
1632                            int cmd)
1633 {
1634         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1635         int rc;
1636
1637 #if K1212_DEBUG_LEVEL > 0
1638                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_trigger [%s] cmd=%d\n", stateName[korg1212->cardState], cmd);
1639 #endif
1640
1641         spin_lock(&korg1212->lock);
1642         switch (cmd) {
1643                 case SNDRV_PCM_TRIGGER_START:
1644 /*
1645                         if (korg1212->running) {
1646 #if K1212_DEBUG_LEVEL > 1
1647                                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_trigger: Already running?\n");
1648 #endif
1649                                 break;
1650                         }
1651 */
1652                         korg1212->running++;
1653                         rc = snd_korg1212_TriggerPlay(korg1212);
1654                         break;
1655
1656                 case SNDRV_PCM_TRIGGER_STOP:
1657 /*
1658                         if (!korg1212->running) {
1659 #if K1212_DEBUG_LEVEL > 1
1660                                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_trigger: Already stopped?\n");
1661 #endif
1662                                 break;
1663                         }
1664 */
1665                         korg1212->running--;
1666                         rc = snd_korg1212_StopPlay(korg1212);
1667                         break;
1668
1669                 default:
1670                         rc = 1;
1671                         break;
1672         }
1673         spin_unlock(&korg1212->lock);
1674         return rc ? -EINVAL : 0;
1675 }
1676
1677 static snd_pcm_uframes_t snd_korg1212_playback_pointer(snd_pcm_substream_t *substream)
1678 {
1679         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1680         snd_pcm_uframes_t pos;
1681
1682         pos = korg1212->currentBuffer * kPlayBufferFrames;
1683
1684 #if K1212_DEBUG_LEVEL > 2
1685         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_pointer [%s] %ld\n", 
1686                         stateName[korg1212->cardState], pos);
1687 #endif
1688
1689         return pos;
1690 }
1691
1692 static snd_pcm_uframes_t snd_korg1212_capture_pointer(snd_pcm_substream_t *substream)
1693 {
1694         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1695         snd_pcm_uframes_t pos;
1696
1697         pos = korg1212->currentBuffer * kPlayBufferFrames;
1698
1699 #if K1212_DEBUG_LEVEL > 2
1700         K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_pointer [%s] %ld\n",
1701                         stateName[korg1212->cardState], pos);
1702 #endif
1703
1704         return pos;
1705 }
1706
1707 static int snd_korg1212_playback_copy(snd_pcm_substream_t *substream,
1708                         int channel, /* not used (interleaved data) */
1709                         snd_pcm_uframes_t pos,
1710                         void __user *src,
1711                         snd_pcm_uframes_t count)
1712 {
1713         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1714
1715 #if K1212_DEBUG_LEVEL > 2
1716                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_copy [%s] %ld %ld\n", stateName[korg1212->cardState], pos, count);
1717 #endif
1718  
1719         return snd_korg1212_copy_from(korg1212, src, pos, count, 0, korg1212->channels * 2);
1720
1721 }
1722
1723 static int snd_korg1212_playback_silence(snd_pcm_substream_t *substream,
1724                            int channel, /* not used (interleaved data) */
1725                            snd_pcm_uframes_t pos,
1726                            snd_pcm_uframes_t count)
1727 {
1728         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1729
1730 #if K1212_DEBUG_LEVEL > 0
1731                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_playback_silence [%s]\n", stateName[korg1212->cardState]);
1732 #endif
1733
1734         return snd_korg1212_silence(korg1212, pos, count, 0, korg1212->channels * 2);
1735 }
1736
1737 static int snd_korg1212_capture_copy(snd_pcm_substream_t *substream,
1738                         int channel, /* not used (interleaved data) */
1739                         snd_pcm_uframes_t pos,
1740                         void __user *dst,
1741                         snd_pcm_uframes_t count)
1742 {
1743         korg1212_t *korg1212 = snd_pcm_substream_chip(substream);
1744
1745 #if K1212_DEBUG_LEVEL > 2
1746                 K1212_DEBUG_PRINTK("K1212_DEBUG: snd_korg1212_capture_copy [%s] %ld %ld\n", stateName[korg1212->cardState], pos, count);
1747 #endif
1748
1749         return snd_korg1212_copy_to(korg1212, dst, pos, count, 0, korg1212->channels * 2);
1750 }
1751
1752 static snd_pcm_ops_t snd_korg1212_playback_ops = {
1753         .open =         snd_korg1212_playback_open,
1754         .close =        snd_korg1212_playback_close,
1755         .ioctl =        snd_korg1212_ioctl,
1756         .hw_params =    snd_korg1212_hw_params,
1757         .prepare =      snd_korg1212_prepare,
1758         .trigger =      snd_korg1212_trigger,
1759         .pointer =      snd_korg1212_playback_pointer,
1760         .copy =         snd_korg1212_playback_copy,
1761         .silence =      snd_korg1212_playback_silence,
1762 };
1763
1764 static snd_pcm_ops_t snd_korg1212_capture_ops = {
1765         .open =         snd_korg1212_capture_open,
1766         .close =        snd_korg1212_capture_close,
1767         .ioctl =        snd_korg1212_ioctl,
1768         .hw_params =    snd_korg1212_hw_params,
1769         .prepare =      snd_korg1212_prepare,
1770         .trigger =      snd_korg1212_trigger,
1771         .pointer =      snd_korg1212_capture_pointer,
1772         .copy =         snd_korg1212_capture_copy,
1773 };
1774
1775 /*
1776  * Control Interface
1777  */
1778
1779 static int snd_korg1212_control_phase_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1780 {
1781         uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
1782         uinfo->count = (kcontrol->private_value >= 8) ? 2 : 1;
1783         return 0;
1784 }
1785
1786 static int snd_korg1212_control_phase_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1787 {
1788         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1789         int i = kcontrol->private_value;
1790
1791         spin_lock_irq(&korg1212->lock);
1792
1793         u->value.integer.value[0] = korg1212->volumePhase[i];
1794
1795         if (i >= 8)
1796                 u->value.integer.value[1] = korg1212->volumePhase[i+1];
1797
1798         spin_unlock_irq(&korg1212->lock);
1799
1800         return 0;
1801 }
1802
1803 static int snd_korg1212_control_phase_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1804 {
1805         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1806         int change = 0;
1807         int i, val;
1808
1809         spin_lock_irq(&korg1212->lock);
1810
1811         i = kcontrol->private_value;
1812
1813         korg1212->volumePhase[i] = u->value.integer.value[0];
1814
1815         val = korg1212->sharedBufferPtr->volumeData[kcontrol->private_value];
1816
1817         if ((u->value.integer.value[0] > 0) != (val < 0)) {
1818                 val = abs(val) * (korg1212->volumePhase[i] > 0 ? -1 : 1);
1819                 korg1212->sharedBufferPtr->volumeData[i] = val;
1820                 change = 1;
1821         }
1822
1823         if (i >= 8) {
1824                 korg1212->volumePhase[i+1] = u->value.integer.value[1];
1825
1826                 val = korg1212->sharedBufferPtr->volumeData[kcontrol->private_value+1];
1827
1828                 if ((u->value.integer.value[1] > 0) != (val < 0)) {
1829                         val = abs(val) * (korg1212->volumePhase[i+1] > 0 ? -1 : 1);
1830                         korg1212->sharedBufferPtr->volumeData[i+1] = val;
1831                         change = 1;
1832                 }
1833         }
1834
1835         spin_unlock_irq(&korg1212->lock);
1836
1837         return change;
1838 }
1839
1840 static int snd_korg1212_control_volume_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1841 {
1842         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1843         uinfo->count = (kcontrol->private_value >= 8) ? 2 : 1;
1844         uinfo->value.integer.min = k1212MinVolume;
1845         uinfo->value.integer.max = k1212MaxVolume;
1846         return 0;
1847 }
1848
1849 static int snd_korg1212_control_volume_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1850 {
1851         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1852         int i;
1853
1854         spin_lock_irq(&korg1212->lock);
1855
1856         i = kcontrol->private_value;
1857         u->value.integer.value[0] = abs(korg1212->sharedBufferPtr->volumeData[i]);
1858
1859         if (i >= 8) 
1860                 u->value.integer.value[1] = abs(korg1212->sharedBufferPtr->volumeData[i+1]);
1861
1862         spin_unlock_irq(&korg1212->lock);
1863
1864         return 0;
1865 }
1866
1867 static int snd_korg1212_control_volume_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1868 {
1869         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1870         int change = 0;
1871         int i;
1872         int val;
1873
1874         spin_lock_irq(&korg1212->lock);
1875
1876         i = kcontrol->private_value;
1877
1878         if (u->value.integer.value[0] != abs(korg1212->sharedBufferPtr->volumeData[i])) {
1879                 val = korg1212->volumePhase[i] > 0 ? -1 : 1;
1880                 val *= u->value.integer.value[0];
1881                 korg1212->sharedBufferPtr->volumeData[i] = val;
1882                 change = 1;
1883         }
1884
1885         if (i >= 8) {
1886                 if (u->value.integer.value[1] != abs(korg1212->sharedBufferPtr->volumeData[i+1])) {
1887                         val = korg1212->volumePhase[i+1] > 0 ? -1 : 1;
1888                         val *= u->value.integer.value[1];
1889                         korg1212->sharedBufferPtr->volumeData[i+1] = val;
1890                         change = 1;
1891                 }
1892         }
1893
1894         spin_unlock_irq(&korg1212->lock);
1895
1896         return change;
1897 }
1898
1899 static int snd_korg1212_control_route_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1900 {
1901         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
1902         uinfo->count = (kcontrol->private_value >= 8) ? 2 : 1;
1903         uinfo->value.enumerated.items = kAudioChannels;
1904         if (uinfo->value.enumerated.item > kAudioChannels-1) {
1905                 uinfo->value.enumerated.item = kAudioChannels-1;
1906         }
1907         strcpy(uinfo->value.enumerated.name, channelName[uinfo->value.enumerated.item]);
1908         return 0;
1909 }
1910
1911 static int snd_korg1212_control_route_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1912 {
1913         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1914         int i;
1915
1916         spin_lock_irq(&korg1212->lock);
1917
1918         i = kcontrol->private_value;
1919         u->value.enumerated.item[0] = korg1212->sharedBufferPtr->routeData[i];
1920
1921         if (i >= 8) 
1922                 u->value.enumerated.item[1] = korg1212->sharedBufferPtr->routeData[i+1];
1923
1924         spin_unlock_irq(&korg1212->lock);
1925
1926         return 0;
1927 }
1928
1929 static int snd_korg1212_control_route_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1930 {
1931         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1932         int change = 0, i;
1933
1934         spin_lock_irq(&korg1212->lock);
1935
1936         i = kcontrol->private_value;
1937
1938         if (u->value.enumerated.item[0] != (unsigned) korg1212->sharedBufferPtr->volumeData[i]) {
1939                 korg1212->sharedBufferPtr->routeData[i] = u->value.enumerated.item[0];
1940                 change = 1;
1941         }
1942
1943         if (i >= 8) {
1944                 if (u->value.enumerated.item[1] != (unsigned) korg1212->sharedBufferPtr->volumeData[i+1]) {
1945                         korg1212->sharedBufferPtr->routeData[i+1] = u->value.enumerated.item[1];
1946                         change = 1;
1947                 }
1948         }
1949
1950         spin_unlock_irq(&korg1212->lock);
1951
1952         return change;
1953 }
1954
1955 static int snd_korg1212_control_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
1956 {
1957         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
1958         uinfo->count = 2;
1959         uinfo->value.integer.min = k1212MaxADCSens;
1960         uinfo->value.integer.max = k1212MinADCSens;
1961         return 0;
1962 }
1963
1964 static int snd_korg1212_control_get(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1965 {
1966         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1967
1968         spin_lock_irq(&korg1212->lock);
1969
1970         u->value.integer.value[0] = korg1212->leftADCInSens;
1971         u->value.integer.value[1] = korg1212->rightADCInSens;
1972
1973         spin_unlock_irq(&korg1212->lock);
1974
1975         return 0;
1976 }
1977
1978 static int snd_korg1212_control_put(snd_kcontrol_t *kcontrol, snd_ctl_elem_value_t *u)
1979 {
1980         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
1981         int change = 0;
1982
1983         spin_lock_irq(&korg1212->lock);
1984
1985         if (u->value.integer.value[0] != korg1212->leftADCInSens) {
1986                 korg1212->leftADCInSens = u->value.integer.value[0];
1987                 change = 1;
1988         }
1989         if (u->value.integer.value[1] != korg1212->rightADCInSens) {
1990                 korg1212->rightADCInSens = u->value.integer.value[1];
1991                 change = 1;
1992         }
1993
1994         spin_unlock_irq(&korg1212->lock);
1995
1996         if (change)
1997                 snd_korg1212_WriteADCSensitivity(korg1212);
1998
1999         return change;
2000 }
2001
2002 static int snd_korg1212_control_sync_info(snd_kcontrol_t *kcontrol, snd_ctl_elem_info_t * uinfo)
2003 {
2004         uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
2005         uinfo->count = 1;
2006         uinfo->value.enumerated.items = 3;
2007         if (uinfo->value.enumerated.item > 2) {
2008                 uinfo->value.enumerated.item = 2;
2009         }
2010         strcpy(uinfo->value.enumerated.name, clockSourceTypeName[uinfo->value.enumerated.item]);
2011         return 0;
2012 }
2013
2014 static int snd_korg1212_control_sync_get(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2015 {
2016         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
2017
2018         spin_lock_irq(&korg1212->lock);
2019
2020         ucontrol->value.enumerated.item[0] = korg1212->clkSource;
2021
2022         spin_unlock_irq(&korg1212->lock);
2023         return 0;
2024 }
2025
2026 static int snd_korg1212_control_sync_put(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
2027 {
2028         korg1212_t *korg1212 = snd_kcontrol_chip(kcontrol);
2029         unsigned int val;
2030         int change;
2031
2032         val = ucontrol->value.enumerated.item[0] % 3;
2033         spin_lock_irq(&korg1212->lock);
2034         change = val != korg1212->clkSource;
2035         snd_korg1212_SetClockSource(korg1212, val);
2036         spin_unlock_irq(&korg1212->lock);
2037         return change;
2038 }
2039
2040 #define MON_MIXER(ord,c_name)                                                                   \
2041         {                                                                                       \
2042                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,       \
2043                 .iface =        SNDRV_CTL_ELEM_IFACE_MIXER,                                     \
2044                 .name =         c_name " Monitor Volume",                                       \
2045                 .info =         snd_korg1212_control_volume_info,                               \
2046                 .get =          snd_korg1212_control_volume_get,                                \
2047                 .put =          snd_korg1212_control_volume_put,                                \
2048                 .private_value = ord,                                                           \
2049         },                                                                                      \
2050         {                                                                                       \
2051                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,       \
2052                 .iface =        SNDRV_CTL_ELEM_IFACE_MIXER,                                     \
2053                 .name =         c_name " Monitor Route",                                        \
2054                 .info =         snd_korg1212_control_route_info,                                \
2055                 .get =          snd_korg1212_control_route_get,                                 \
2056                 .put =          snd_korg1212_control_route_put,                                 \
2057                 .private_value = ord,                                                           \
2058         },                                                                                      \
2059         {                                                                                       \
2060                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,       \
2061                 .iface =        SNDRV_CTL_ELEM_IFACE_PCM,                                       \
2062                 .name =         c_name " Monitor Phase Invert",                                 \
2063                 .info =         snd_korg1212_control_phase_info,                                \
2064                 .get =          snd_korg1212_control_phase_get,                                 \
2065                 .put =          snd_korg1212_control_phase_put,                                 \
2066                 .private_value = ord,                                                           \
2067         }
2068
2069 static snd_kcontrol_new_t snd_korg1212_controls[] = {
2070         MON_MIXER(8, "Analog"),
2071         MON_MIXER(10, "SPDIF"), 
2072         MON_MIXER(0, "ADAT-1"), MON_MIXER(1, "ADAT-2"), MON_MIXER(2, "ADAT-3"), MON_MIXER(3, "ADAT-4"),
2073         MON_MIXER(4, "ADAT-5"), MON_MIXER(5, "ADAT-6"), MON_MIXER(6, "ADAT-7"), MON_MIXER(7, "ADAT-8"),
2074         {
2075                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,
2076                 .iface =        SNDRV_CTL_ELEM_IFACE_PCM,
2077                 .name =         "Sync Source",
2078                 .info =         snd_korg1212_control_sync_info,
2079                 .get =          snd_korg1212_control_sync_get,
2080                 .put =          snd_korg1212_control_sync_put,
2081         },
2082         {
2083                 .access =       SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_WRITE,
2084                 .iface =        SNDRV_CTL_ELEM_IFACE_MIXER,
2085                 .name =         "ADC Attenuation",
2086                 .info =         snd_korg1212_control_info,
2087                 .get =          snd_korg1212_control_get,
2088                 .put =          snd_korg1212_control_put,
2089         }
2090 };
2091
2092 /*
2093  * proc interface
2094  */
2095
2096 static void snd_korg1212_proc_read(snd_info_entry_t *entry, snd_info_buffer_t *buffer)
2097 {
2098         int n;
2099         korg1212_t *korg1212 = (korg1212_t *)entry->private_data;
2100
2101         snd_iprintf(buffer, korg1212->card->longname);
2102         snd_iprintf(buffer, " (index #%d)\n", korg1212->card->number + 1);
2103         snd_iprintf(buffer, "\nGeneral settings\n");
2104         snd_iprintf(buffer, "    period size: %Zd bytes\n", K1212_PERIOD_BYTES);
2105         snd_iprintf(buffer, "     clock mode: %s\n", clockSourceName[korg1212->clkSrcRate] );
2106         snd_iprintf(buffer, "  left ADC Sens: %d\n", korg1212->leftADCInSens );
2107         snd_iprintf(buffer, " right ADC Sens: %d\n", korg1212->rightADCInSens );
2108         snd_iprintf(buffer, "    Volume Info:\n");
2109         for (n=0; n<kAudioChannels; n++)
2110                 snd_iprintf(buffer, " Channel %d: %s -> %s [%d]\n", n,
2111                                     channelName[n],
2112                                     channelName[korg1212->sharedBufferPtr->routeData[n]],
2113                                     korg1212->sharedBufferPtr->volumeData[n]);
2114         snd_iprintf(buffer, "\nGeneral status\n");
2115         snd_iprintf(buffer, " ADAT Time Code: %d\n", korg1212->sharedBufferPtr->AdatTimeCode);
2116         snd_iprintf(buffer, "     Card State: %s\n", stateName[korg1212->cardState]);
2117         snd_iprintf(buffer, "Idle mon. State: %d\n", korg1212->idleMonitorOn);
2118         snd_iprintf(buffer, "Cmd retry count: %d\n", korg1212->cmdRetryCount);
2119         snd_iprintf(buffer, "      Irq count: %ld\n", korg1212->irqcount);
2120 }
2121
2122 static void __devinit snd_korg1212_proc_init(korg1212_t *korg1212)
2123 {
2124         snd_info_entry_t *entry;
2125
2126         if (! snd_card_proc_new(korg1212->card, "korg1212", &entry))
2127                 snd_info_set_text_ops(entry, korg1212, 1024, snd_korg1212_proc_read);
2128 }
2129
2130 static int
2131 snd_korg1212_free(korg1212_t *korg1212)
2132 {
2133         snd_korg1212_TurnOffIdleMonitor(korg1212);
2134
2135         if (korg1212->irq >= 0) {
2136                 synchronize_irq(korg1212->irq);                
2137                 snd_korg1212_DisableCardInterrupts(korg1212);
2138                 free_irq(korg1212->irq, (void *)korg1212);
2139                 korg1212->irq = -1;
2140         }
2141         
2142         if (korg1212->iobase != NULL) {
2143                 iounmap(korg1212->iobase);
2144                 korg1212->iobase = NULL;
2145         }
2146         
2147         pci_release_regions(korg1212->pci);
2148
2149         // ----------------------------------------------------
2150         // free up memory resources used for the DSP download.
2151         // ----------------------------------------------------
2152         if (korg1212->dma_dsp.area) {
2153                 snd_dma_free_pages(&korg1212->dma_dsp);
2154                 korg1212->dma_dsp.area = NULL;
2155         }
2156
2157 #ifndef K1212_LARGEALLOC
2158
2159         // ------------------------------------------------------
2160         // free up memory resources used for the Play/Rec Buffers
2161         // ------------------------------------------------------
2162         if (korg1212->dma_play.area) {
2163                 snd_dma_free_pages(&korg1212->dma_play);
2164                 korg1212->dma_play.area = NULL;
2165         }
2166
2167         if (korg1212->dma_rec.area) {
2168                 snd_dma_free_pages(&korg1212->dma_rec);
2169                 korg1212->dma_rec.area = NULL;
2170         }
2171
2172 #endif
2173
2174         // ----------------------------------------------------
2175         // free up memory resources used for the Shared Buffers
2176         // ----------------------------------------------------
2177         if (korg1212->dma_shared.area) {
2178                 snd_dma_free_pages(&korg1212->dma_shared);
2179                 korg1212->dma_shared.area = NULL;
2180         }
2181         
2182         pci_disable_device(korg1212->pci);
2183         kfree(korg1212);
2184         return 0;
2185 }
2186
2187 static int snd_korg1212_dev_free(snd_device_t *device)
2188 {
2189         korg1212_t *korg1212 = device->device_data;
2190 #if K1212_DEBUG_LEVEL > 0
2191         K1212_DEBUG_PRINTK("K1212_DEBUG: Freeing device\n");
2192 #endif
2193         return snd_korg1212_free(korg1212);
2194 }
2195
2196 static int __devinit snd_korg1212_create(snd_card_t * card, struct pci_dev *pci,
2197                                          korg1212_t ** rchip)
2198
2199 {
2200         int err;
2201         unsigned int i;
2202         unsigned ioport_size, iomem_size, iomem2_size;
2203         korg1212_t * korg1212;
2204
2205         static snd_device_ops_t ops = {
2206                 .dev_free = snd_korg1212_dev_free,
2207         };
2208
2209         * rchip = NULL;
2210         if ((err = pci_enable_device(pci)) < 0)
2211                 return err;
2212
2213         korg1212 = kcalloc(1, sizeof(*korg1212), GFP_KERNEL);
2214         if (korg1212 == NULL) {
2215                 pci_disable_device(pci);
2216                 return -ENOMEM;
2217         }
2218
2219         korg1212->card = card;
2220         korg1212->pci = pci;
2221
2222         init_waitqueue_head(&korg1212->wait);
2223         spin_lock_init(&korg1212->lock);
2224         init_MUTEX(&korg1212->open_mutex);
2225         init_timer(&korg1212->timer);
2226         korg1212->timer.function = snd_korg1212_timer_func;
2227         korg1212->timer.data = (unsigned long)korg1212;
2228
2229         korg1212->irq = -1;
2230         korg1212->clkSource = K1212_CLKIDX_Local;
2231         korg1212->clkRate = 44100;
2232         korg1212->inIRQ = 0;
2233         korg1212->running = 0;
2234         korg1212->opencnt = 0;
2235         korg1212->playcnt = 0;
2236         korg1212->setcnt = 0;
2237         korg1212->playback_pid = -1;
2238         korg1212->capture_pid = -1;
2239         snd_korg1212_setCardState(korg1212, K1212_STATE_UNINITIALIZED);
2240         korg1212->idleMonitorOn = 0;
2241         korg1212->clkSrcRate = K1212_CLKIDX_LocalAt44_1K;
2242         korg1212->leftADCInSens = k1212MaxADCSens;
2243         korg1212->rightADCInSens = k1212MaxADCSens;
2244
2245         for (i=0; i<kAudioChannels; i++)
2246                 korg1212->volumePhase[i] = 0;
2247
2248         if ((err = pci_request_regions(pci, "korg1212")) < 0) {
2249                 kfree(korg1212);
2250                 pci_disable_device(pci);
2251                 return err;
2252         }
2253
2254         korg1212->iomem = pci_resource_start(korg1212->pci, 0);
2255         korg1212->ioport = pci_resource_start(korg1212->pci, 1);
2256         korg1212->iomem2 = pci_resource_start(korg1212->pci, 2);
2257
2258         iomem_size = pci_resource_len(korg1212->pci, 0);
2259         ioport_size = pci_resource_len(korg1212->pci, 1);
2260         iomem2_size = pci_resource_len(korg1212->pci, 2);
2261
2262 #if K1212_DEBUG_LEVEL > 0
2263         K1212_DEBUG_PRINTK("K1212_DEBUG: resources:\n"
2264                    "    iomem = 0x%lx (%d)\n"
2265                    "    ioport  = 0x%lx (%d)\n"
2266                    "    iomem = 0x%lx (%d)\n"
2267                    "    [%s]\n",
2268                    korg1212->iomem, iomem_size,
2269                    korg1212->ioport, ioport_size,
2270                    korg1212->iomem2, iomem2_size,
2271                    stateName[korg1212->cardState]);
2272 #endif
2273
2274         if ((korg1212->iobase = ioremap(korg1212->iomem, iomem_size)) == NULL) {
2275                 snd_printk(KERN_ERR "unable to remap memory region 0x%lx-0x%lx\n", korg1212->iomem,
2276                            korg1212->iomem + iomem_size - 1);
2277                 snd_korg1212_free(korg1212);
2278                 return -EBUSY;
2279         }
2280
2281         err = request_irq(pci->irq, snd_korg1212_interrupt,
2282                           SA_INTERRUPT|SA_SHIRQ,
2283                           "korg1212", (void *) korg1212);
2284
2285         if (err) {
2286                 snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
2287                 snd_korg1212_free(korg1212);
2288                 return -EBUSY;
2289         }
2290
2291         korg1212->irq = pci->irq;
2292
2293         pci_set_master(korg1212->pci);
2294
2295         korg1212->statusRegPtr = (u32 __iomem *) (korg1212->iobase + STATUS_REG_OFFSET);
2296         korg1212->outDoorbellPtr = (u32 __iomem *) (korg1212->iobase + OUT_DOORBELL_OFFSET);
2297         korg1212->inDoorbellPtr = (u32 __iomem *) (korg1212->iobase + IN_DOORBELL_OFFSET);
2298         korg1212->mailbox0Ptr = (u32 __iomem *) (korg1212->iobase + MAILBOX0_OFFSET);
2299         korg1212->mailbox1Ptr = (u32 __iomem *) (korg1212->iobase + MAILBOX1_OFFSET);
2300         korg1212->mailbox2Ptr = (u32 __iomem *) (korg1212->iobase + MAILBOX2_OFFSET);
2301         korg1212->mailbox3Ptr = (u32 __iomem *) (korg1212->iobase + MAILBOX3_OFFSET);
2302         korg1212->controlRegPtr = (u32 __iomem *) (korg1212->iobase + PCI_CONTROL_OFFSET);
2303         korg1212->sensRegPtr = (u16 __iomem *) (korg1212->iobase + SENS_CONTROL_OFFSET);
2304         korg1212->idRegPtr = (u32 __iomem *) (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         if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2333                                 sizeof(KorgSharedBuffer), &korg1212->dma_shared) < 0) {
2334                 snd_printk(KERN_ERR "can not allocate shared buffer memory (%Zd bytes)\n", sizeof(KorgSharedBuffer));
2335                 snd_korg1212_free(korg1212);
2336                 return -ENOMEM;
2337         }
2338         korg1212->sharedBufferPtr = (KorgSharedBuffer *)korg1212->dma_shared.area;
2339         korg1212->sharedBufferPhy = korg1212->dma_shared.addr;
2340
2341 #if K1212_DEBUG_LEVEL > 0
2342         K1212_DEBUG_PRINTK("K1212_DEBUG: Shared Buffer Area = 0x%p (0x%08lx), %d bytes\n", korg1212->sharedBufferPtr, korg1212->sharedBufferPhy, sizeof(KorgSharedBuffer));
2343 #endif
2344
2345 #ifndef K1212_LARGEALLOC
2346
2347         korg1212->DataBufsSize = sizeof(KorgAudioBuffer) * kNumBuffers;
2348
2349         if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2350                                 korg1212->DataBufsSize, &korg1212->dma_play) < 0) {
2351                 snd_printk(KERN_ERR "can not allocate play data buffer memory (%d bytes)\n", korg1212->DataBufsSize);
2352                 snd_korg1212_free(korg1212);
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(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2364                                 korg1212->DataBufsSize, &korg1212->dma_rec) < 0) {
2365                 snd_printk(KERN_ERR "can not allocate record data buffer memory (%d bytes)\n", korg1212->DataBufsSize);
2366                 snd_korg1212_free(korg1212);
2367                 return -ENOMEM;
2368         }
2369         korg1212->recordDataBufsPtr = (KorgAudioBuffer *)korg1212->dma_rec.area;
2370         korg1212->RecDataPhy = korg1212->dma_rec.addr;
2371
2372 #if K1212_DEBUG_LEVEL > 0
2373         K1212_DEBUG_PRINTK("K1212_DEBUG: Record Data Area = 0x%p (0x%08x), %d bytes\n",
2374                 korg1212->recordDataBufsPtr, korg1212->RecDataPhy, korg1212->DataBufsSize);
2375 #endif
2376
2377 #else // K1212_LARGEALLOC
2378
2379         korg1212->recordDataBufsPtr = korg1212->sharedBufferPtr->recordDataBufs;
2380         korg1212->playDataBufsPtr = korg1212->sharedBufferPtr->playDataBufs;
2381         korg1212->PlayDataPhy = (u32) &((KorgSharedBuffer *) korg1212->sharedBufferPhy)->playDataBufs;
2382         korg1212->RecDataPhy  = (u32) &((KorgSharedBuffer *) korg1212->sharedBufferPhy)->recordDataBufs;
2383
2384 #endif // K1212_LARGEALLOC
2385
2386         korg1212->dspCodeSize = sizeof (dspCode);
2387
2388         korg1212->VolumeTablePhy = korg1212->sharedBufferPhy +
2389                 offsetof(KorgSharedBuffer, volumeData);
2390         korg1212->RoutingTablePhy = korg1212->sharedBufferPhy +
2391                 offsetof(KorgSharedBuffer, routeData);
2392         korg1212->AdatTimeCodePhy = korg1212->sharedBufferPhy +
2393                 offsetof(KorgSharedBuffer, AdatTimeCode);
2394
2395         if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
2396                                 korg1212->dspCodeSize, &korg1212->dma_dsp) < 0) {
2397                 snd_printk(KERN_ERR "can not allocate dsp code memory (%d bytes)\n", korg1212->dspCodeSize);
2398                 snd_korg1212_free(korg1212);
2399                 return -ENOMEM;
2400         }
2401
2402 #if K1212_DEBUG_LEVEL > 0
2403         K1212_DEBUG_PRINTK("K1212_DEBUG: DSP Code area = 0x%p (0x%08x) %d bytes [%s]\n",
2404                    korg1212->dma_dsp.area, korg1212->dma_dsp.addr, korg1212->dspCodeSize,
2405                    stateName[korg1212->cardState]);
2406 #endif
2407
2408         rc = snd_korg1212_Send1212Command(korg1212, K1212_DB_RebootCard, 0, 0, 0, 0);
2409
2410 #if K1212_DEBUG_LEVEL > 0
2411         if (rc) K1212_DEBUG_PRINTK("K1212_DEBUG: Reboot Card - RC = %d [%s]\n", rc, stateName[korg1212->cardState]);
2412 #endif
2413
2414         if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, korg1212, &ops)) < 0) {
2415                 snd_korg1212_free(korg1212);
2416                 return err;
2417         }
2418         
2419         snd_korg1212_EnableCardInterrupts(korg1212);
2420
2421         mdelay(CARD_BOOT_DELAY_IN_MS);
2422
2423         if (snd_korg1212_downloadDSPCode(korg1212))
2424                 return -EBUSY;
2425
2426         printk(KERN_INFO "dspMemPhy       = %08x U[%08x]\n"
2427                "PlayDataPhy     = %08x L[%08x]\n"
2428                "RecDataPhy      = %08x L[%08x]\n"
2429                "VolumeTablePhy  = %08x L[%08x]\n"
2430                "RoutingTablePhy = %08x L[%08x]\n"
2431                "AdatTimeCodePhy = %08x L[%08x]\n",
2432                (int)korg1212->dma_dsp.addr,    UpperWordSwap(korg1212->dma_dsp.addr),
2433                korg1212->PlayDataPhy,     LowerWordSwap(korg1212->PlayDataPhy),
2434                korg1212->RecDataPhy,      LowerWordSwap(korg1212->RecDataPhy),
2435                korg1212->VolumeTablePhy,  LowerWordSwap(korg1212->VolumeTablePhy),
2436                korg1212->RoutingTablePhy, LowerWordSwap(korg1212->RoutingTablePhy),
2437                korg1212->AdatTimeCodePhy, LowerWordSwap(korg1212->AdatTimeCodePhy));
2438
2439         if ((err = snd_pcm_new(korg1212->card, "korg1212", 0, 1, 1, &korg1212->pcm)) < 0)
2440                 return err;
2441
2442         korg1212->pcm->private_data = korg1212;
2443         korg1212->pcm->private_free = snd_korg1212_free_pcm;
2444         strcpy(korg1212->pcm->name, "korg1212");
2445
2446         snd_pcm_set_ops(korg1212->pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_korg1212_playback_ops);
2447         
2448         snd_pcm_set_ops(korg1212->pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_korg1212_capture_ops);
2449
2450         korg1212->pcm->info_flags = SNDRV_PCM_INFO_JOINT_DUPLEX;
2451
2452         //snd_pcm_lib_preallocate_pages_for_all(korg1212->pcm,
2453         //                      K1212_MAX_BUF_SIZE, K1212_MAX_BUF_SIZE, GFP_KERNEL);
2454
2455         for (i = 0; i < ARRAY_SIZE(snd_korg1212_controls); i++) {
2456                 err = snd_ctl_add(korg1212->card, snd_ctl_new1(&snd_korg1212_controls[i], korg1212));
2457                 if (err < 0)
2458                         return err;
2459         }
2460
2461         snd_korg1212_proc_init(korg1212);
2462         
2463         snd_card_set_dev(card, &pci->dev);
2464
2465         * rchip = korg1212;
2466         return 0;
2467
2468 }
2469
2470 /*
2471  * Card initialisation
2472  */
2473
2474 static int __devinit
2475 snd_korg1212_probe(struct pci_dev *pci,
2476                 const struct pci_device_id *pci_id)
2477 {
2478         static int dev;
2479         korg1212_t *korg1212;
2480         snd_card_t *card;
2481         int err;
2482
2483         if (dev >= SNDRV_CARDS) {
2484                 return -ENODEV;
2485         }
2486         if (!enable[dev]) {
2487                 dev++;
2488                 return -ENOENT;
2489         }
2490         card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
2491         if (card == NULL)
2492                 return -ENOMEM;
2493
2494         if ((err = snd_korg1212_create(card, pci, &korg1212)) < 0) {
2495                 snd_card_free(card);
2496                 return err;
2497         }
2498
2499         strcpy(card->driver, "korg1212");
2500         strcpy(card->shortname, "korg1212");
2501         sprintf(card->longname, "%s at 0x%lx, irq %d", card->shortname,
2502                 korg1212->iomem, korg1212->irq);
2503
2504 #if K1212_DEBUG_LEVEL > 0
2505         K1212_DEBUG_PRINTK("K1212_DEBUG: %s\n", card->longname);
2506 #endif
2507
2508         if ((err = snd_card_register(card)) < 0) {
2509                 snd_card_free(card);
2510                 return err;
2511         }
2512         pci_set_drvdata(pci, card);
2513         dev++;
2514         return 0;
2515 }
2516
2517 static void __devexit snd_korg1212_remove(struct pci_dev *pci)
2518 {
2519         snd_card_free(pci_get_drvdata(pci));
2520         pci_set_drvdata(pci, NULL);
2521 }
2522
2523 static struct pci_driver driver = {
2524         .name = "korg1212",
2525         .id_table = snd_korg1212_ids,
2526         .probe = snd_korg1212_probe,
2527         .remove = __devexit_p(snd_korg1212_remove),
2528 };
2529
2530 static int __init alsa_card_korg1212_init(void)
2531 {
2532         return pci_module_init(&driver);
2533 }
2534
2535 static void __exit alsa_card_korg1212_exit(void)
2536 {
2537         pci_unregister_driver(&driver);
2538 }
2539
2540 module_init(alsa_card_korg1212_init)
2541 module_exit(alsa_card_korg1212_exit)