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