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