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