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