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