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