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