Linux Audio

Check our new training course

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