ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / sound / isa / sscape.c
1 /*
2  *   Low-level ALSA driver for the ENSONIQ SoundScape PnP
3  *   Copyright (c) by Chris Rankin
4  *
5  *   This driver was written in part using information obtained from
6  *   the OSS/Free SoundScape driver, written by Hannu Savolainen.
7  *
8  *
9  *   This program is free software; you can redistribute it and/or modify
10  *   it under the terms of the GNU General Public License as published by
11  *   the Free Software Foundation; either version 2 of the License, or
12  *   (at your option) any later version.
13  *
14  *   This program is distributed in the hope that it will be useful,
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *   GNU General Public License for more details.
18  *
19  *   You should have received a copy of the GNU General Public License
20  *   along with this program; if not, write to the Free Software
21  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
22  */
23
24 #include <sound/driver.h>
25 #include <linux/init.h>
26 #include <linux/delay.h>
27 #include <linux/pnp.h>
28 #include <linux/spinlock.h>
29 #include <asm/dma.h>
30 #include <sound/core.h>
31 #include <sound/hwdep.h>
32 #include <sound/cs4231.h>
33 #include <sound/mpu401.h>
34 #define SNDRV_GET_ID
35 #include <sound/initval.h>
36
37 #include <sound/sscape_ioctl.h>
38
39 #define chip_t cs4231_t
40
41
42 MODULE_AUTHOR("Chris Rankin");
43 MODULE_DESCRIPTION("ENSONIQ SoundScape PnP driver");
44 MODULE_LICENSE("GPL");
45
46 static int index[SNDRV_CARDS] __devinitdata = SNDRV_DEFAULT_IDX;
47 static char* id[SNDRV_CARDS] __devinitdata = SNDRV_DEFAULT_STR;
48 static long port[SNDRV_CARDS] __devinitdata = { [0 ... (SNDRV_CARDS-1)] = SNDRV_AUTO_PORT };
49 static int irq[SNDRV_CARDS] __devinitdata = SNDRV_DEFAULT_IRQ;
50 static int mpu_irq[SNDRV_CARDS] __devinitdata = SNDRV_DEFAULT_IRQ;
51 static int dma[SNDRV_CARDS] __devinitdata = SNDRV_DEFAULT_DMA;
52
53 MODULE_PARM(index, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
54 MODULE_PARM_DESC(index, "Index number for SoundScape soundcard");
55 MODULE_PARM_SYNTAX(index, SNDRV_INDEX_DESC);
56
57 MODULE_PARM(id, "1-" __MODULE_STRING(SNDRV_CARDS) "s");
58 MODULE_PARM_DESC(id, "Description for SoundScape card");
59 MODULE_PARM_SYNTAX(id, SNDRV_ID_DESC);
60
61 MODULE_PARM(port, "1-" __MODULE_STRING(SNDRV_CARDS) "l");
62 MODULE_PARM_DESC(port, "Port # for SoundScape driver.");
63 MODULE_PARM_SYNTAX(port, SNDRV_ENABLED);
64
65 MODULE_PARM(irq, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
66 MODULE_PARM_DESC(irq, "IRQ # for SoundScape driver.");
67 MODULE_PARM_SYNTAX(irq, SNDRV_IRQ_DESC);
68
69 MODULE_PARM(mpu_irq, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
70 MODULE_PARM_DESC(mpu_irq, "MPU401 IRQ # for SoundScape driver.");
71 MODULE_PARM_SYNTAX(mpu_irq, SNDRV_IRQ_DESC);
72
73 MODULE_PARM(dma, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
74 MODULE_PARM_DESC(dma, "DMA # for SoundScape driver.");
75 MODULE_PARM_SYNTAX(dma, SNDRV_DMA8_DESC);
76   
77 #ifdef CONFIG_PNP
78 static struct pnp_card_device_id sscape_pnpids[] = {
79         { .id = "ENS3081", .devs = { { "ENS0000" } } },
80         { .id = "" }    /* end */
81 };
82
83 MODULE_DEVICE_TABLE(pnp_card, sscape_pnpids);
84 #endif
85
86 static snd_card_t *sscape_card[SNDRV_CARDS];
87
88
89 #define MPU401_IO(i)     ((i) + 0)
90 #define MIDI_DATA_IO(i)  ((i) + 0)
91 #define MIDI_CTRL_IO(i)  ((i) + 1)
92 #define HOST_CTRL_IO(i)  ((i) + 2)
93 #define HOST_DATA_IO(i)  ((i) + 3)
94 #define ODIE_ADDR_IO(i)  ((i) + 4)
95 #define ODIE_DATA_IO(i)  ((i) + 5)
96 #define CODEC_IO(i)      ((i) + 8)
97
98 #define IC_ODIE  1
99 #define IC_OPUS  2
100
101 #define RX_READY 0x01
102 #define TX_READY 0x02
103
104 #define CMD_ACK           0x80
105 #define CMD_SET_MIDI_VOL  0x84
106 #define CMD_GET_MIDI_VOL  0x85
107 #define CMD_XXX_MIDI_VOL  0x86
108 #define CMD_SET_EXTMIDI   0x8a
109 #define CMD_GET_EXTMIDI   0x8b
110 #define CMD_SET_MT32      0x8c
111 #define CMD_GET_MT32      0x8d
112
113 enum GA_REG {
114         GA_INTSTAT_REG = 0,
115         GA_INTENA_REG,
116         GA_DMAA_REG,
117         GA_DMAB_REG,
118         GA_INTCFG_REG,
119         GA_DMACFG_REG,
120         GA_CDCFG_REG,
121         GA_SMCFGA_REG,
122         GA_SMCFGB_REG,
123         GA_HMCTL_REG
124 };
125
126 #define DMA_8BIT  0x80
127
128
129 #define AD1845_FREQ_SEL_MSB    0x16
130 #define AD1845_FREQ_SEL_LSB    0x17
131
132 struct soundscape {
133         spinlock_t lock;
134         unsigned io_base;
135         int codec_type;
136         int ic_type;
137         struct resource *io_res;
138         cs4231_t *chip;
139         mpu401_t *mpu;
140         snd_hwdep_t *hw;
141
142         /*
143          * The MIDI device won't work until we've loaded
144          * its firmware via a hardware-dependent device IOCTL
145          */
146         spinlock_t fwlock;
147         int hw_in_use;
148         unsigned long midi_usage;
149         unsigned char midi_vol;
150 };
151
152 #define INVALID_IRQ  ((unsigned)-1)
153
154
155 static inline struct soundscape *get_card_soundscape(snd_card_t * c)
156 {
157         return (struct soundscape *) (c->private_data);
158 }
159
160 static inline struct soundscape *get_mpu401_soundscape(mpu401_t * mpu)
161 {
162         return (struct soundscape *) (mpu->private_data);
163 }
164
165 static inline struct soundscape *get_hwdep_soundscape(snd_hwdep_t * hw)
166 {
167         return (struct soundscape *) (hw->private_data);
168 }
169
170
171 /*
172  * Allocates some kernel memory that we can use for DMA.
173  * I think this means that the memory has to map to
174  * contiguous pages of physical memory.
175  */
176 static struct snd_dma_buffer *get_dmabuf(struct snd_dma_buffer *buf, unsigned long size)
177 {
178         if (buf) {
179                 struct snd_dma_device dev;
180                 memset(&dev, 0, sizeof(dev));
181                 dev.type = SNDRV_DMA_TYPE_DEV;
182                 dev.dev = snd_dma_isa_data();
183                 if (snd_dma_alloc_pages_fallback(&dev, size, buf) < 0) {
184                         snd_printk(KERN_ERR "sscape: Failed to allocate %lu bytes for DMA\n", size);
185                         return NULL;
186                 }
187         }
188
189         return buf;
190 }
191
192 /*
193  * Release the DMA-able kernel memory ...
194  */
195 static void free_dmabuf(struct snd_dma_buffer *buf)
196 {
197         if (buf && buf->area) {
198                 struct snd_dma_device dev;
199                 memset(&dev, 0, sizeof(dev));
200                 dev.type = SNDRV_DMA_TYPE_DEV;
201                 dev.dev = snd_dma_isa_data();
202                 snd_dma_free_pages(&dev, buf);
203         }
204 }
205
206
207 /*
208  * This function writes to the SoundScape's control registers,
209  * but doesn't do any locking. It's up to the caller to do that.
210  * This is why this function is "unsafe" ...
211  */
212 static inline void sscape_write_unsafe(unsigned io_base, enum GA_REG reg, unsigned char val)
213 {
214         outb(reg, ODIE_ADDR_IO(io_base));
215         outb(val, ODIE_DATA_IO(io_base));
216 }
217
218 /*
219  * Write to the SoundScape's control registers, and do the
220  * necessary locking ...
221  */
222 static void sscape_write(struct soundscape *s, enum GA_REG reg, unsigned char val)
223 {
224         unsigned long flags;
225
226         spin_lock_irqsave(&s->lock, flags);
227         sscape_write_unsafe(s->io_base, reg, val);
228         spin_unlock_irqrestore(&s->lock, flags);
229 }
230
231 /*
232  * Read from the SoundScape's control registers, but leave any
233  * locking to the caller. This is why the function is "unsafe" ...
234  */
235 static inline unsigned char sscape_read_unsafe(unsigned io_base, enum GA_REG reg)
236 {
237         outb(reg, ODIE_ADDR_IO(io_base));
238         return inb(ODIE_DATA_IO(io_base));
239 }
240
241 /*
242  * Puts the SoundScape into "host" mode, as compared to "MIDI" mode
243  */
244 static inline void set_host_mode_unsafe(unsigned io_base)
245 {
246         outb(0x0, HOST_CTRL_IO(io_base));
247 }
248
249 /*
250  * Puts the SoundScape into "MIDI" mode, as compared to "host" mode
251  */
252 static inline void set_midi_mode_unsafe(unsigned io_base)
253 {
254         outb(0x3, HOST_CTRL_IO(io_base));
255 }
256
257 /*
258  * Read the SoundScape's host-mode control register, but leave
259  * any locking issues to the caller ...
260  */
261 static inline int host_read_unsafe(unsigned io_base)
262 {
263         int data = -1;
264         if ((inb(HOST_CTRL_IO(io_base)) & RX_READY) != 0) {
265                 data = inb(HOST_DATA_IO(io_base));
266         }
267
268         return data;
269 }
270
271 /*
272  * Read the SoundScape's host-mode control register, performing
273  * a limited amount of busy-waiting if the register isn't ready.
274  * Also leaves all locking-issues to the caller ...
275  */
276 static int host_read_ctrl_unsafe(unsigned io_base, unsigned timeout)
277 {
278         int data;
279
280         while (((data = host_read_unsafe(io_base)) < 0) && (timeout != 0)) {
281                 udelay(100);
282                 --timeout;
283         } /* while */
284
285         return data;
286 }
287
288 /*
289  * Write to the SoundScape's host-mode control registers, but
290  * leave any locking issues to the caller ...
291  */
292 static inline int host_write_unsafe(unsigned io_base, unsigned char data)
293 {
294         if ((inb(HOST_CTRL_IO(io_base)) & TX_READY) != 0) {
295                 outb(data, HOST_DATA_IO(io_base));
296                 return 1;
297         }
298
299         return 0;
300 }
301
302 /*
303  * Write to the SoundScape's host-mode control registers, performing
304  * a limited amount of busy-waiting if the register isn't ready.
305  * Also leaves all locking-issues to the caller ...
306  */
307 static int host_write_ctrl_unsafe(unsigned io_base, unsigned char data,
308                                   unsigned timeout)
309 {
310         int err;
311
312         while (!(err = host_write_unsafe(io_base, data)) && (timeout != 0)) {
313                 udelay(100);
314                 --timeout;
315         } /* while */
316
317         return err;
318 }
319
320
321 /*
322  * Check that the MIDI subsystem is operational. If it isn't,
323  * then we will hang the computer if we try to use it ...
324  *
325  * NOTE: This check is based upon observation, not documentation.
326  */
327 static inline int verify_mpu401(const mpu401_t * mpu)
328 {
329         return ((inb(MIDI_CTRL_IO(mpu->port)) & 0xc0) == 0x80);
330 }
331
332 /*
333  * This is apparently the standard way to initailise an MPU-401
334  */
335 static inline void initialise_mpu401(const mpu401_t * mpu)
336 {
337         outb(0, MIDI_DATA_IO(mpu->port));
338 }
339
340 /*
341  * Tell the SoundScape to activate the AD1845 chip (I think).
342  * The AD1845 detection fails if we *don't* do this, so I
343  * think that this is a good idea ...
344  */
345 static inline void activate_ad1845_unsafe(unsigned io_base)
346 {
347         sscape_write_unsafe(io_base, GA_HMCTL_REG, (sscape_read_unsafe(io_base, GA_HMCTL_REG) & 0xcf) | 0x10);
348         sscape_write_unsafe(io_base, GA_CDCFG_REG, 0x80);
349 }
350
351 /*
352  * Do the necessary ALSA-level cleanup to deallocate our driver ...
353  */
354 static void soundscape_free(snd_card_t * c)
355 {
356         register struct soundscape *sscape = get_card_soundscape(c);
357         release_resource(sscape->io_res);
358         kfree_nocheck(sscape->io_res);
359         free_dma(sscape->chip->dma1);
360 }
361
362 /*
363  * Put this process into an idle wait-state for a certain number
364  * of "jiffies". The process can almost certainly be rescheduled
365  * while we're waiting, and so we must NOT be holding any spinlocks
366  * when we call this function. If we are then we risk DEADLOCK in
367  * SMP (Ha!) or pre-emptible kernels.
368  */
369 static inline void sleep(long jiffs, int state)
370 {
371         set_current_state(state);
372         schedule_timeout(jiffs);
373 }
374
375 /*
376  * Tell the SoundScape to begin a DMA tranfer using the given channel.
377  * All locking issues are left to the caller.
378  */
379 static inline void sscape_start_dma_unsafe(unsigned io_base, enum GA_REG reg)
380 {
381         sscape_write_unsafe(io_base, reg, sscape_read_unsafe(io_base, reg) | 0x01);
382         sscape_write_unsafe(io_base, reg, sscape_read_unsafe(io_base, reg) & 0xfe);
383 }
384
385 /*
386  * Wait for a DMA transfer to complete. This is a "limited busy-wait",
387  * and all locking issues are left to the caller.
388  */
389 static int sscape_wait_dma_unsafe(unsigned io_base, enum GA_REG reg, unsigned timeout)
390 {
391         while (!(sscape_read_unsafe(io_base, reg) & 0x01) && (timeout != 0)) {
392                 udelay(100);
393                 --timeout;
394         } /* while */
395
396         return (sscape_read_unsafe(io_base, reg) & 0x01);
397 }
398
399 /*
400  * Wait for the On-Board Processor to return its start-up
401  * acknowledgement sequence. This wait is too long for
402  * us to perform "busy-waiting", and so we must sleep.
403  * This in turn means that we must not be holding any
404  * spinlocks when we call this function.
405  */
406 static int obp_startup_ack(struct soundscape *s, unsigned timeout)
407 {
408         while (timeout != 0) {
409                 unsigned long flags;
410                 unsigned char x;
411
412                 sleep(1, TASK_INTERRUPTIBLE);
413
414                 spin_lock_irqsave(&s->lock, flags);
415                 x = inb(HOST_DATA_IO(s->io_base));
416                 spin_unlock_irqrestore(&s->lock, flags);
417                 if ((x & 0xfe) == 0xfe)
418                         return 1;
419
420                 --timeout;
421         } /* while */
422
423         return 0;
424 }
425
426 /*
427  * Wait for the host to return its start-up acknowledgement
428  * sequence. This wait is too long for us to perform
429  * "busy-waiting", and so we must sleep. This in turn means
430  * that we must not be holding any spinlocks when we call
431  * this function.
432  */
433 static int host_startup_ack(struct soundscape *s, unsigned timeout)
434 {
435         while (timeout != 0) {
436                 unsigned long flags;
437                 unsigned char x;
438
439                 sleep(1, TASK_INTERRUPTIBLE);
440
441                 spin_lock_irqsave(&s->lock, flags);
442                 x = inb(HOST_DATA_IO(s->io_base));
443                 spin_unlock_irqrestore(&s->lock, flags);
444                 if (x == 0xfe)
445                         return 1;
446
447                 --timeout;
448         } /* while */
449
450         return 0;
451 }
452
453 /*
454  * Upload a byte-stream into the SoundScape using DMA channel A.
455  */
456 static int upload_dma_data(struct soundscape *s,
457                            const unsigned char *data,
458                            size_t size)
459 {
460         unsigned long flags;
461         struct snd_dma_buffer dma;
462         int ret;
463
464         if (!get_dmabuf(&dma, PAGE_ALIGN(size)))
465                 return -ENOMEM;
466
467         spin_lock_irqsave(&s->lock, flags);
468
469         /*
470          * Reset the board ...
471          */
472         sscape_write_unsafe(s->io_base, GA_HMCTL_REG, sscape_read_unsafe(s->io_base, GA_HMCTL_REG) & 0x3f);
473
474         /*
475          * Enable the DMA channels and configure them ...
476          */
477         sscape_write_unsafe(s->io_base, GA_DMACFG_REG, 0x50);
478         sscape_write_unsafe(s->io_base, GA_DMAA_REG, (s->chip->dma1 << 4) | DMA_8BIT);
479         sscape_write_unsafe(s->io_base, GA_DMAB_REG, 0x20);
480
481         /*
482          * Take the board out of reset ...
483          */
484         sscape_write_unsafe(s->io_base, GA_HMCTL_REG, sscape_read_unsafe(s->io_base, GA_HMCTL_REG) | 0x80);
485
486         /*
487          * Upload the user's data (firmware?) to the SoundScape
488          * board through the DMA channel ...
489          */
490         while (size != 0) {
491                 unsigned long len;
492
493                 /*
494                  * Apparently, copying to/from userspace can sleep.
495                  * We are therefore forbidden from holding any
496                  * spinlocks while we copy ...
497                  */
498                 spin_unlock_irqrestore(&s->lock, flags);
499
500                 /*
501                  * Remember that the data that we want to DMA
502                  * comes from USERSPACE. We have already verified
503                  * the userspace pointer ...
504                  */
505                 len = min(size, dma.bytes);
506                 __copy_from_user(dma.area, data, len);
507                 data += len;
508                 size -= len;
509
510                 /*
511                  * Grab that spinlock again, now that we've
512                  * finished copying!
513                  */
514                 spin_lock_irqsave(&s->lock, flags);
515
516                 snd_dma_program(s->chip->dma1, dma.addr, len, DMA_MODE_WRITE);
517                 sscape_start_dma_unsafe(s->io_base, GA_DMAA_REG);
518                 if (!sscape_wait_dma_unsafe(s->io_base, GA_DMAA_REG, 5000)) {
519                         /*
520                          * Don't forget to release this spinlock we're holding ...
521                          */
522                         spin_unlock_irqrestore(&s->lock, flags);
523
524                         snd_printk(KERN_ERR "sscape: DMA upload has timed out\n");
525                         ret = -EAGAIN;
526                         goto _release_dma;
527                 }
528         } /* while */
529
530         set_host_mode_unsafe(s->io_base);
531
532         /*
533          * Boot the board ... (I think)
534          */
535         sscape_write_unsafe(s->io_base, GA_HMCTL_REG, sscape_read_unsafe(s->io_base, GA_HMCTL_REG) | 0x40);
536         spin_unlock_irqrestore(&s->lock, flags);
537
538         /*
539          * If all has gone well, then the board should acknowledge
540          * the new upload and tell us that it has rebooted OK. We
541          * give it 5 seconds (max) ...
542          */
543         ret = 0;
544         if (!obp_startup_ack(s, 5)) {
545                 snd_printk(KERN_ERR "sscape: No response from on-board processor after upload\n");
546                 ret = -EAGAIN;
547         } else if (!host_startup_ack(s, 5)) {
548                 snd_printk(KERN_ERR "sscape: SoundScape failed to initialise\n");
549                 ret = -EAGAIN;
550         }
551
552         _release_dma:
553         /*
554          * NOTE!!! We are NOT holding any spinlocks at this point !!!
555          */
556         sscape_write(s, GA_DMAA_REG, (s->ic_type == IC_ODIE ? 0x70 : 0x40));
557         free_dmabuf(&dma);
558
559         return ret;
560 }
561
562 /*
563  * Upload the bootblock(?) into the SoundScape. The only
564  * purpose of this block of code seems to be to tell
565  * us which version of the microcode we should be using.
566  *
567  * NOTE: The boot-block data resides in USER-SPACE!!!
568  *       However, we have already verified its memory
569  *       addresses by the time we get here.
570  */
571 static int sscape_upload_bootblock(struct soundscape *sscape, struct sscape_bootblock *bb)
572 {
573         unsigned long flags;
574         int data = 0;
575         int ret;
576
577         ret = upload_dma_data(sscape, bb->code, sizeof(bb->code));
578
579         spin_lock_irqsave(&sscape->lock, flags);
580         if (ret == 0) {
581                 data = host_read_ctrl_unsafe(sscape->io_base, 100);
582         }
583         set_midi_mode_unsafe(sscape->io_base);
584         spin_unlock_irqrestore(&sscape->lock, flags);
585
586         if (ret == 0) {
587                 if (data < 0) {
588                         snd_printk(KERN_ERR "sscape: timeout reading firmware version\n");
589                         ret = -EAGAIN;
590                 } else {
591                         __copy_to_user(&bb->version, &data, sizeof(bb->version));
592                 }
593         }
594
595         return ret;
596 }
597
598 /*
599  * Upload the microcode into the SoundScape. The
600  * microcode is 64K of data, and if we try to copy
601  * it into a local variable then we will SMASH THE
602  * KERNEL'S STACK! We therefore leave it in USER
603  * SPACE, and save ourselves from copying it at all.
604  */
605 static int sscape_upload_microcode(struct soundscape *sscape,
606                                    const struct sscape_microcode *mc)
607 {
608         unsigned long flags;
609         char *code;
610         int err, ret;
611
612         /*
613          * We are going to have to copy this data into a special
614          * DMA-able buffer before we can upload it. We shall therefore
615          * just check that the data pointer is valid for now.
616          *
617          * NOTE: This buffer is 64K long! That's WAY too big to
618          *       copy into a stack-temporary anyway.
619          */
620         if (get_user(code, &mc->code))
621                 return -EFAULT;
622         if ((err = verify_area(VERIFY_READ, code, SSCAPE_MICROCODE_SIZE)) != 0)
623                 return err;
624
625         if ((ret = upload_dma_data(sscape, code, SSCAPE_MICROCODE_SIZE)) == 0) {
626                 snd_printk(KERN_INFO "sscape: MIDI firmware loaded\n");
627         }
628
629         spin_lock_irqsave(&sscape->lock, flags);
630         set_midi_mode_unsafe(sscape->io_base);
631         spin_unlock_irqrestore(&sscape->lock, flags);
632
633         initialise_mpu401(sscape->mpu);
634
635         return ret;
636 }
637
638 /*
639  * Hardware-specific device functions, to implement special
640  * IOCTLs for the SoundScape card. This is how we upload
641  * the microcode into the card, for example, and so we
642  * must ensure that no two processes can open this device
643  * simultaneously, and that we can't open it at all if
644  * someone is using the MIDI device.
645  */
646 static int sscape_hw_open(snd_hwdep_t * hw, struct file *file)
647 {
648         register struct soundscape *sscape = get_hwdep_soundscape(hw);
649         unsigned long flags;
650         int err;
651
652         spin_lock_irqsave(&sscape->fwlock, flags);
653
654         if ((sscape->midi_usage != 0) || sscape->hw_in_use) {
655                 err = -EBUSY;
656         } else {
657                 sscape->hw_in_use = 1;
658                 err = 0;
659         }
660
661         spin_unlock_irqrestore(&sscape->fwlock, flags);
662         return err;
663 }
664
665 static int sscape_hw_release(snd_hwdep_t * hw, struct file *file)
666 {
667         register struct soundscape *sscape = get_hwdep_soundscape(hw);
668         unsigned long flags;
669
670         spin_lock_irqsave(&sscape->fwlock, flags);
671         sscape->hw_in_use = 0;
672         spin_unlock_irqrestore(&sscape->fwlock, flags);
673         return 0;
674 }
675
676 static int sscape_hw_ioctl(snd_hwdep_t * hw, struct file *file,
677                            unsigned int cmd, unsigned long arg)
678 {
679         struct soundscape *sscape = get_hwdep_soundscape(hw);
680         int err = -EBUSY;
681
682         switch (cmd) {
683         case SND_SSCAPE_LOAD_BOOTB:
684                 {
685                         register struct sscape_bootblock *bb = (struct sscape_bootblock *) arg;
686
687                         /*
688                          * We are going to have to copy this data into a special
689                          * DMA-able buffer before we can upload it. We shall therefore
690                          * just check that the data pointer is valid for now ...
691                          */
692                         if ((err = verify_area(VERIFY_READ, bb->code, sizeof(bb->code))) != 0)
693                                 return err;
694
695                         /*
696                          * Now check that we can write the firmware version number too...
697                          */
698                         if ((err = verify_area(VERIFY_WRITE, &bb->version, sizeof(bb->version))) != 0)
699                                 return err;
700
701                         err = sscape_upload_bootblock(sscape, bb);
702                 }
703                 break;
704
705         case SND_SSCAPE_LOAD_MCODE:
706                 {
707                         register const struct sscape_microcode *mc = (const struct sscape_microcode *) arg;
708
709                         err = sscape_upload_microcode(sscape, mc);
710                 }
711                 break;
712
713         default:
714                 err = -EINVAL;
715                 break;
716         } /* switch */
717
718         return err;
719 }
720
721
722 /*
723  * Mixer control for the SoundScape's MIDI device.
724  */
725 static int sscape_midi_info(snd_kcontrol_t * ctl,
726                             snd_ctl_elem_info_t * uinfo)
727 {
728         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
729         uinfo->count = 1;
730         uinfo->value.integer.min = 0;
731         uinfo->value.integer.max = 127;
732         return 0;
733 }
734
735 static int sscape_midi_get(snd_kcontrol_t * kctl,
736                            snd_ctl_elem_value_t * uctl)
737 {
738         cs4231_t *chip = snd_kcontrol_chip(kctl);
739         snd_card_t *card = chip->card;
740         register struct soundscape *s = get_card_soundscape(card);
741         unsigned long flags;
742
743         spin_lock_irqsave(&s->lock, flags);
744         set_host_mode_unsafe(s->io_base);
745
746         if (host_write_ctrl_unsafe(s->io_base, CMD_GET_MIDI_VOL, 100)) {
747                 uctl->value.integer.value[0] = host_read_ctrl_unsafe(s->io_base, 100);
748         }
749
750         set_midi_mode_unsafe(s->io_base);
751         spin_unlock_irqrestore(&s->lock, flags);
752         return 0;
753 }
754
755 static int sscape_midi_put(snd_kcontrol_t * kctl,
756                            snd_ctl_elem_value_t * uctl)
757 {
758         cs4231_t *chip = snd_kcontrol_chip(kctl);
759         snd_card_t *card = chip->card;
760         register struct soundscape *s = get_card_soundscape(card);
761         unsigned long flags;
762         int change;
763
764         spin_lock_irqsave(&s->lock, flags);
765
766         /*
767          * We need to put the board into HOST mode before we
768          * can send any volume-changing HOST commands ...
769          */
770         set_host_mode_unsafe(s->io_base);
771
772         /*
773          * To successfully change the MIDI volume setting, you seem to
774          * have to write a volume command, write the new volume value,
775          * and then perform another volume-related command. Perhaps the
776          * first command is an "open" and the second command is a "close"?
777          */
778         if (s->midi_vol == ((unsigned char) uctl->value.integer. value[0] & 127)) {
779                 change = 0;
780                 goto __skip_change;
781         }
782         change = (host_write_ctrl_unsafe(s->io_base, CMD_SET_MIDI_VOL, 100)
783                   && host_write_ctrl_unsafe(s->io_base, ((unsigned char) uctl->value.integer. value[0]) & 127, 100)
784                   && host_write_ctrl_unsafe(s->io_base, CMD_XXX_MIDI_VOL, 100));
785       __skip_change:
786
787         /*
788          * Take the board out of HOST mode and back into MIDI mode ...
789          */
790         set_midi_mode_unsafe(s->io_base);
791
792         spin_unlock_irqrestore(&s->lock, flags);
793         return change;
794 }
795
796 static snd_kcontrol_new_t midi_mixer_ctl = {
797         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
798         .name = "MIDI",
799         .info = sscape_midi_info,
800         .get = sscape_midi_get,
801         .put = sscape_midi_put
802 };
803
804 /*
805  * The SoundScape can use two IRQs from a possible set of four.
806  * These IRQs are encoded as bit patterns so that they can be
807  * written to the control registers.
808  */
809 static unsigned __devinit get_irq_config(int irq)
810 {
811         static const int valid_irq[] = { 9, 5, 7, 10 };
812         unsigned cfg;
813
814         for (cfg = 0; cfg < ARRAY_SIZE(valid_irq); ++cfg) {
815                 if (irq == valid_irq[cfg])
816                         return cfg;
817         } /* for */
818
819         return INVALID_IRQ;
820 }
821
822
823 /*
824  * Perform certain arcane port-checks to see whether there
825  * is a SoundScape board lurking behind the given ports.
826  */
827 static int __devinit detect_sscape(struct soundscape *s)
828 {
829         unsigned long flags;
830         unsigned d;
831         int retval = 0;
832
833         spin_lock_irqsave(&s->lock, flags);
834
835         /*
836          * The following code is lifted from the original OSS driver,
837          * and as I don't have a datasheet I cannot really comment
838          * on what it is doing...
839          */
840         if ((inb(HOST_CTRL_IO(s->io_base)) & 0x78) != 0)
841                 goto _done;
842
843         d = inb(ODIE_ADDR_IO(s->io_base)) & 0xf0;
844         if ((d & 0x80) != 0)
845                 goto _done;
846
847         if (d == 0) {
848                 s->codec_type = 1;
849                 s->ic_type = IC_ODIE;
850         } else if ((d & 0x60) != 0) {
851                 s->codec_type = 2;
852                 s->ic_type = IC_OPUS;
853         } else
854                 goto _done;
855
856         outb(0xfa, ODIE_ADDR_IO(s->io_base));
857         if ((inb(ODIE_ADDR_IO(s->io_base)) & 0x9f) != 0x0a)
858                 goto _done;
859
860         outb(0xfe, ODIE_ADDR_IO(s->io_base));
861         if ((inb(ODIE_ADDR_IO(s->io_base)) & 0x9f) != 0x0e)
862                 goto _done;
863         if ((inb(ODIE_DATA_IO(s->io_base)) & 0x9f) != 0x0e)
864                 goto _done;
865
866         /*
867          * SoundScape successfully detected!
868          */
869         retval = 1;
870
871         _done:
872         spin_unlock_irqrestore(&s->lock, flags);
873         return retval;
874 }
875
876 /*
877  * ALSA callback function, called when attempting to open the MIDI device.
878  * Check that the MIDI firmware has been loaded, because we don't want
879  * to crash the machine. Also check that someone isn't using the hardware
880  * IOCTL device.
881  */
882 static int mpu401_open(mpu401_t * mpu)
883 {
884         int err;
885
886         if (!verify_mpu401(mpu)) {
887                 snd_printk(KERN_ERR "sscape: MIDI disabled, please load firmware\n");
888                 err = -ENODEV;
889         } else {
890                 register struct soundscape *sscape = get_mpu401_soundscape(mpu);
891                 unsigned long flags;
892
893                 spin_lock_irqsave(&sscape->fwlock, flags);
894
895                 if (sscape->hw_in_use || (sscape->midi_usage == ULONG_MAX)) {
896                         err = -EBUSY;
897                 } else {
898                         ++(sscape->midi_usage);
899                         err = 0;
900                 }
901
902                 spin_unlock_irqrestore(&sscape->fwlock, flags);
903         }
904
905         return err;
906 }
907
908 static void mpu401_close(mpu401_t * mpu)
909 {
910         register struct soundscape *sscape = get_mpu401_soundscape(mpu);
911         unsigned long flags;
912
913         spin_lock_irqsave(&sscape->fwlock, flags);
914         --(sscape->midi_usage);
915         spin_unlock_irqrestore(&sscape->fwlock, flags);
916 }
917
918 /*
919  * Initialse an MPU-401 subdevice for MIDI support on the SoundScape.
920  */
921 static int __devinit create_mpu401(snd_card_t * card, int devnum, unsigned long port, int irq)
922 {
923         struct soundscape *sscape = get_card_soundscape(card);
924         snd_rawmidi_t *rawmidi;
925         int err;
926
927 #define MPU401_SHARE_HARDWARE  1
928         if ((err = snd_mpu401_uart_new(card, devnum,
929                                        MPU401_HW_MPU401,
930                                        port, MPU401_SHARE_HARDWARE,
931                                        irq, SA_INTERRUPT,
932                                        &rawmidi)) == 0) {
933                 mpu401_t *mpu = (mpu401_t *) rawmidi->private_data;
934                 mpu->open_input = mpu401_open;
935                 mpu->open_output = mpu401_open;
936                 mpu->close_input = mpu401_close;
937                 mpu->close_output = mpu401_close;
938                 mpu->private_data = sscape;
939                 sscape->mpu = mpu;
940
941                 initialise_mpu401(mpu);
942         }
943
944         return err;
945 }
946
947
948 /*
949  * Override for the CS4231 playback format function.
950  * The AD1845 has much simpler format and rate selection.
951  */
952 static void ad1845_playback_format(cs4231_t * chip, snd_pcm_hw_params_t * params, unsigned char format)
953 {
954         unsigned long flags;
955         unsigned rate = params_rate(params);
956
957         /*
958          * The AD1845 can't handle sample frequencies
959          * outside of 4 kHZ to 50 kHZ
960          */
961         if (rate > 50000)
962                 rate = 50000;
963         else if (rate < 4000)
964                 rate = 4000;
965
966         spin_lock_irqsave(&chip->reg_lock, flags);
967
968         /*
969          * Program the AD1845 correctly for the playback stream.
970          * Note that we do NOT need to toggle the MCE bit because
971          * the PLAYBACK_ENABLE bit of the Interface Configuration
972          * register is set.
973          * 
974          * NOTE: We seem to need to write to the MSB before the LSB
975          *       to get the correct sample frequency.
976          */
977         snd_cs4231_out(chip, CS4231_PLAYBK_FORMAT, (format & 0xf0));
978         snd_cs4231_out(chip, AD1845_FREQ_SEL_MSB, (unsigned char) (rate >> 8));
979         snd_cs4231_out(chip, AD1845_FREQ_SEL_LSB, (unsigned char) rate);
980
981         spin_unlock_irqrestore(&chip->reg_lock, flags);
982 }
983
984 /*
985  * Override for the CS4231 capture format function. 
986  * The AD1845 has much simpler format and rate selection.
987  */
988 static void ad1845_capture_format(cs4231_t * chip, snd_pcm_hw_params_t * params, unsigned char format)
989 {
990         unsigned long flags;
991         unsigned rate = params_rate(params);
992
993         /*
994          * The AD1845 can't handle sample frequencies 
995          * outside of 4 kHZ to 50 kHZ
996          */
997         if (rate > 50000)
998                 rate = 50000;
999         else if (rate < 4000)
1000                 rate = 4000;
1001
1002         spin_lock_irqsave(&chip->reg_lock, flags);
1003
1004         /*
1005          * Program the AD1845 correctly for the playback stream.
1006          * Note that we do NOT need to toggle the MCE bit because
1007          * the CAPTURE_ENABLE bit of the Interface Configuration
1008          * register is set.
1009          *
1010          * NOTE: We seem to need to write to the MSB before the LSB
1011          *       to get the correct sample frequency.
1012          */
1013         snd_cs4231_out(chip, CS4231_REC_FORMAT, (format & 0xf0));
1014         snd_cs4231_out(chip, AD1845_FREQ_SEL_MSB, (unsigned char) (rate >> 8));
1015         snd_cs4231_out(chip, AD1845_FREQ_SEL_LSB, (unsigned char) rate);
1016
1017         spin_unlock_irqrestore(&chip->reg_lock, flags);
1018 }
1019
1020 /*
1021  * Create an AD1845 PCM subdevice on the SoundScape. The AD1845
1022  * is very much like a CS4231, with a few extra bits. We will
1023  * try to support at least some of the extra bits by overriding
1024  * some of the CS4231 callback.
1025  */
1026 static int __devinit create_ad1845(snd_card_t * card, unsigned port, int irq, int dma1)
1027 {
1028         register struct soundscape *sscape = get_card_soundscape(card);
1029         cs4231_t *chip;
1030         int err;
1031
1032 #define CS4231_SHARE_HARDWARE  (CS4231_HWSHARE_DMA1 | CS4231_HWSHARE_DMA2)
1033         /*
1034          * The AD1845 PCM device is only half-duplex, and so
1035          * we only give it one DMA channel ...
1036          */
1037         if ((err = snd_cs4231_create(card,
1038                                      port, -1, irq, dma1, dma1,
1039                                      CS4231_HW_DETECT,
1040                                      CS4231_HWSHARE_DMA1, &chip)) == 0) {
1041                 unsigned long flags;
1042                 snd_pcm_t *pcm;
1043
1044 #define AD1845_FREQ_SEL_ENABLE  0x08
1045
1046 #define AD1845_PWR_DOWN_CTRL   0x1b
1047 #define AD1845_CRYS_CLOCK_SEL  0x1d
1048
1049 /*
1050  * It turns out that the PLAYBACK_ENABLE bit is set
1051  * by the lowlevel driver ...
1052  *
1053 #define AD1845_IFACE_CONFIG  \
1054            (CS4231_AUTOCALIB | CS4231_RECORD_ENABLE | CS4231_PLAYBACK_ENABLE)
1055     snd_cs4231_mce_up(chip);
1056     spin_lock_irqsave(&chip->reg_lock, flags);
1057     snd_cs4231_out(chip, CS4231_IFACE_CTRL, AD1845_IFACE_CONFIG);
1058     spin_unlock_irqrestore(&chip->reg_lock, flags);
1059     snd_cs4231_mce_down(chip);
1060  */
1061
1062                 /*
1063                  * The input clock frequency on the SoundScape must
1064                  * be 14.31818 MHz, because we must set this register
1065                  * to get the playback to sound correct ...
1066                  */
1067                 snd_cs4231_mce_up(chip);
1068                 spin_lock_irqsave(&chip->reg_lock, flags);
1069                 snd_cs4231_out(chip, AD1845_CRYS_CLOCK_SEL, 0x20);
1070                 spin_unlock_irqrestore(&chip->reg_lock, flags);
1071                 snd_cs4231_mce_down(chip);
1072
1073                 /*
1074                  * More custom configuration:
1075                  * a) select "mode 2", and provide a current drive of 8 mA
1076                  * b) enable frequency selection (for capture/playback)
1077                  */
1078                 spin_lock_irqsave(&chip->reg_lock, flags);
1079                 snd_cs4231_out(chip, CS4231_MISC_INFO, (CS4231_MODE2 | 0x10));
1080                 snd_cs4231_out(chip, AD1845_PWR_DOWN_CTRL, snd_cs4231_in(chip, AD1845_PWR_DOWN_CTRL) | AD1845_FREQ_SEL_ENABLE);
1081                 spin_unlock_irqrestore(&chip->reg_lock, flags);
1082
1083                 if ((err = snd_cs4231_pcm(chip, 0, &pcm)) < 0) {
1084                         snd_printk(KERN_ERR "sscape: No PCM device for AD1845 chip\n");
1085                         goto _error;
1086                 }
1087
1088                 if ((err = snd_cs4231_mixer(chip)) < 0) {
1089                         snd_printk(KERN_ERR "sscape: No mixer device for AD1845 chip\n");
1090                         goto _error;
1091                 }
1092
1093                 if ((err = snd_ctl_add(card, snd_ctl_new1(&midi_mixer_ctl, chip))) < 0) {
1094                         snd_printk(KERN_ERR "sscape: Could not create MIDI mixer control\n");
1095                         goto _error;
1096                 }
1097
1098                 strcpy(card->driver, "SoundScape");
1099                 strcpy(card->shortname, pcm->name);
1100                 snprintf(card->longname, sizeof(card->longname),
1101                          "%s at 0x%lx, IRQ %d, DMA %d\n",
1102                          pcm->name, chip->port, chip->irq, chip->dma1);
1103                 chip->set_playback_format = ad1845_playback_format;
1104                 chip->set_capture_format = ad1845_capture_format;
1105                 sscape->chip = chip;
1106         }
1107
1108         _error:
1109         return err;
1110 }
1111
1112
1113 struct params
1114 {
1115         int index;
1116         const char *id;
1117         unsigned port;
1118         int irq;
1119         int mpu_irq;
1120         int dma1;
1121 };
1122
1123
1124 static inline struct params*
1125 init_params(struct params *params,
1126             int index,
1127             const char *id,
1128             unsigned port,
1129             int irq,
1130             int mpu_irq,
1131             int dma1)
1132 {
1133         params->index = index;
1134         params->id = id;
1135         params->port = port;
1136         params->irq = irq;
1137         params->mpu_irq = mpu_irq;  
1138         params->dma1 = (dma1 & 0x03);
1139
1140         return params;
1141 }
1142
1143
1144 /*
1145  * Create an ALSA soundcard entry for the SoundScape, using
1146  * the given list of port, IRQ and DMA resources.
1147  */
1148 static int __devinit create_sscape(const struct params *params, snd_card_t **rcardp)
1149 {
1150         snd_card_t *card;
1151         register struct soundscape *sscape;
1152         register unsigned dma_cfg;
1153         unsigned irq_cfg;
1154         unsigned mpu_irq_cfg;
1155         struct resource *io_res;
1156         unsigned long flags;
1157         int err;
1158
1159         /*
1160          * Check that the user didn't pass us garbage data ...
1161          */
1162         irq_cfg = get_irq_config(params->irq);
1163         if (irq_cfg == INVALID_IRQ) {
1164                 snd_printk(KERN_ERR "sscape: Invalid IRQ %d\n", params->irq);
1165                 return -ENXIO;
1166         }
1167
1168         mpu_irq_cfg = get_irq_config(params->mpu_irq);
1169         if (mpu_irq_cfg == INVALID_IRQ) {
1170                 printk(KERN_ERR "sscape: Invalid IRQ %d\n", params->mpu_irq);
1171                 return -ENXIO;
1172         }
1173
1174         /*
1175          * Grab IO ports that we will need to probe so that we
1176          * can detect and control this hardware ...
1177          */
1178         if ((io_res = request_region(params->port, 8, "SoundScape")) == NULL) {
1179                 snd_printk(KERN_ERR "sscape: can't grab port 0x%x\n", params->port);
1180                 return -EBUSY;
1181         }
1182
1183         /*
1184          * Grab both DMA channels (OK, only one for now) ...
1185          */
1186         if ((err = request_dma(params->dma1, "SoundScape")) < 0) {
1187                 snd_printk(KERN_ERR "sscape: can't grab DMA %d\n", params->dma1);
1188                 goto _release_region;
1189         }
1190
1191         /*
1192          * Create a new ALSA sound card entry, in anticipation
1193          * of detecting our hardware ...
1194          */
1195         if ((card = snd_card_new(params->index, params->id, THIS_MODULE, sizeof(struct soundscape))) == NULL) {
1196                 err = -ENOMEM;
1197                 goto _release_dma;
1198         }
1199
1200         sscape = get_card_soundscape(card);
1201         spin_lock_init(&sscape->lock);
1202         spin_lock_init(&sscape->fwlock);
1203         sscape->io_res = io_res;
1204         sscape->io_base = params->port;
1205
1206         if (!detect_sscape(sscape)) {
1207                 printk(KERN_ERR "sscape: hardware not detected at 0x%x\n", sscape->io_base);
1208                 err = -ENODEV;
1209                 goto _release_card;
1210         }
1211
1212         printk(KERN_INFO "sscape: hardware detected at 0x%x, using IRQ %d, DMA %d\n",
1213                          sscape->io_base, params->irq, params->dma1);
1214
1215         /*
1216          * Now create the hardware-specific device so that we can
1217          * load the microcode into the on-board processor.
1218          * We cannot use the MPU-401 MIDI system until this firmware
1219          * has been loaded into the card.
1220          */
1221         if ((err = snd_hwdep_new(card, "MC68EC000", 0, &(sscape->hw))) < 0) {
1222                 printk(KERN_ERR "sscape: Failed to create firmware device\n");
1223                 goto _release_card;
1224         }
1225         strlcpy(sscape->hw->name, "SoundScape M68K", sizeof(sscape->hw->name));
1226         sscape->hw->name[sizeof(sscape->hw->name) - 1] = '\0';
1227         sscape->hw->iface = SNDRV_HWDEP_IFACE_SSCAPE;
1228         sscape->hw->ops.open = sscape_hw_open;
1229         sscape->hw->ops.release = sscape_hw_release;
1230         sscape->hw->ops.ioctl = sscape_hw_ioctl;
1231         sscape->hw->private_data = sscape;
1232
1233         /*
1234          * Tell the on-board devices where their resources are (I think -
1235          * I can't be sure without a datasheet ... So many magic values!)
1236          */
1237         spin_lock_irqsave(&sscape->lock, flags);
1238
1239         activate_ad1845_unsafe(sscape->io_base);
1240
1241         sscape_write_unsafe(sscape->io_base, GA_INTENA_REG, 0x00); /* disable */
1242         sscape_write_unsafe(sscape->io_base, GA_SMCFGA_REG, 0x2e);
1243         sscape_write_unsafe(sscape->io_base, GA_SMCFGB_REG, 0x00);
1244
1245         /*
1246          * Enable and configure the DMA channels ...
1247          */
1248         sscape_write_unsafe(sscape->io_base, GA_DMACFG_REG, 0x50);
1249         dma_cfg = (sscape->ic_type == IC_ODIE ? 0x70 : 0x40);
1250         sscape_write_unsafe(sscape->io_base, GA_DMAA_REG, dma_cfg);
1251         sscape_write_unsafe(sscape->io_base, GA_DMAB_REG, 0x20);
1252
1253         sscape_write_unsafe(sscape->io_base,
1254                             GA_INTCFG_REG, 0xf0 | (mpu_irq_cfg << 2) | mpu_irq_cfg);
1255         sscape_write_unsafe(sscape->io_base,
1256                             GA_CDCFG_REG, 0x09 | DMA_8BIT | (params->dma1 << 4) | (irq_cfg << 1));
1257
1258         spin_unlock_irqrestore(&sscape->lock, flags);
1259
1260         /*
1261          * We have now enabled the codec chip, and so we should
1262          * detect the AD1845 device ...
1263          */
1264         if ((err = create_ad1845(card, CODEC_IO(params->port), params->irq, params->dma1)) < 0) {
1265                 printk(KERN_ERR "sscape: No AD1845 device at 0x%x, IRQ %d\n",
1266                                 CODEC_IO(params->port), params->irq);
1267                 goto _release_card;
1268         }
1269 #define MIDI_DEVNUM  0
1270         if ((err = create_mpu401(card, MIDI_DEVNUM, MPU401_IO(params->port), params->mpu_irq)) < 0) {
1271                 printk(KERN_ERR "sscape: Failed to create MPU-401 device at 0x%x\n",
1272                                 MPU401_IO(params->port));
1273                 goto _release_card;
1274         }
1275
1276         /*
1277          * Enable the master IRQ ...
1278          */
1279         sscape_write(sscape, GA_INTENA_REG, 0x80);
1280
1281         if ((err = snd_card_register(card)) < 0) {
1282                 printk(KERN_ERR "sscape: Failed to register sound card\n");
1283                 goto _release_card;
1284         }
1285
1286         /*
1287          * Initialize mixer
1288          */
1289         sscape->midi_vol = 0;
1290         host_write_ctrl_unsafe(sscape->io_base, CMD_SET_MIDI_VOL, 100);
1291         host_write_ctrl_unsafe(sscape->io_base, 0, 100);
1292         host_write_ctrl_unsafe(sscape->io_base, CMD_XXX_MIDI_VOL, 100);
1293
1294         /*
1295          * Now that we have successfully created this sound card,
1296          * it is safe to store the pointer.
1297          * NOTE: we only register the sound card's "destructor"
1298          *       function now that our "constructor" has completed.
1299          */
1300         card->private_free = soundscape_free;
1301         *rcardp = card;
1302
1303         return 0;
1304
1305         _release_card:
1306         snd_card_free(card);
1307
1308         _release_dma:
1309         free_dma(params->dma1);
1310
1311         _release_region:
1312         release_resource(io_res);
1313         kfree_nocheck(io_res);
1314
1315         return err;
1316 }
1317
1318
1319 static int sscape_cards __devinitdata;
1320 static struct params sscape_params[SNDRV_CARDS] __devinitdata;
1321
1322 #ifdef CONFIG_PNP
1323 static inline int __devinit get_next_autoindex(int i)
1324 {
1325         while ((i < SNDRV_CARDS) && (port[i] != SNDRV_AUTO_PORT)) {
1326                 ++i;
1327         } /* while */
1328
1329         return i;
1330 }
1331
1332
1333 static inline int __devinit is_port_known(unsigned io, struct params *params, int cards)
1334 {
1335         while (--cards >= 0) {
1336                 if (params[cards].port == io)
1337                         return 1;
1338         } /* while */
1339
1340         return 0;
1341 }
1342
1343 static int __devinit sscape_pnp_detect(struct pnp_card_link *pcard,
1344                                        const struct pnp_card_device_id *pid)
1345 {
1346         struct pnp_dev *dev;
1347         static int idx = 0;
1348         int ret;
1349
1350         /*
1351          * Allow this function to fail *quietly* if all the ISA PnP
1352          * devices were configured using module parameters instead.
1353          */
1354         if ((idx = get_next_autoindex(idx)) >= SNDRV_CARDS) {
1355                 return -ENOSPC;
1356         }
1357
1358         /*
1359          * We have found a candidate ISA PnP card. Now we
1360          * have to check that it has the devices that we
1361          * expect it to have.
1362          *
1363          * We will NOT try and autoconfigure all of the resources
1364          * needed and then activate the card as we are assuming that
1365          * has already been done at boot-time using /proc/isapnp.
1366          * We shall simply try to give each active card the resources
1367          * that it wants. This is a sensible strategy for a modular
1368          * system where unused modules are unloaded regularly.
1369          *
1370          * This strategy is utterly useless if we compile the driver
1371          * into the kernel, of course.
1372          */
1373         // printk(KERN_INFO "sscape: %s\n", card->name);
1374
1375         /*
1376          * Check that we still have room for another sound card ...
1377          */
1378         if (sscape_cards >= SNDRV_CARDS) {
1379                 printk(KERN_ERR "sscape: No room for another ALSA device\n");
1380                 return -ENOSPC;
1381         }
1382
1383         ret = -ENODEV;
1384
1385         dev = pnp_request_card_device(pcard, pid->devs[0].id, NULL);
1386         if (dev) {
1387                 struct params *this;
1388                 if (!pnp_is_active(dev)) {
1389                         if (pnp_activate_dev(dev) < 0) {
1390                                 printk(KERN_INFO "sscape: device is inactive\n");
1391                                 return -EBUSY;
1392                         }
1393                 }
1394                 /*
1395                  * Read the correct parameters off the ISA PnP bus ...
1396                  */
1397                 this = init_params(&sscape_params[sscape_cards],
1398                                    index[idx],
1399                                    id[idx],
1400                                    pnp_port_start(dev, 0),
1401                                    pnp_irq(dev, 0),
1402                                    pnp_irq(dev, 1),
1403                                    pnp_dma(dev, 0));
1404
1405                 /*
1406                  * Do we know about this sound card already?
1407                  */
1408                 if ( !is_port_known(this->port, sscape_params, sscape_cards) ) {
1409                         snd_card_t *card;
1410
1411                         ret = create_sscape(this, &card);
1412                         if (ret < 0)
1413                                 return ret;
1414                         snd_card_set_dev(card, &pcard->card->dev);
1415                         pnp_set_card_drvdata(pcard, card);
1416                         ++sscape_cards;
1417                         ++idx;
1418                 }
1419         }
1420
1421         return ret;
1422 }
1423
1424 static void __devexit sscape_pnp_remove(struct pnp_card_link * pcard)
1425 {
1426         snd_card_t *card = (snd_card_t *) pnp_get_card_drvdata(pcard);
1427         
1428         pnp_set_card_drvdata(pcard, NULL);
1429         snd_card_disconnect(card);
1430         snd_card_free_in_thread(card);
1431 }
1432
1433 static struct pnp_card_driver sscape_pnpc_driver = {
1434         .flags = PNP_DRIVER_RES_DO_NOT_CHANGE,
1435         .name = "sscape",
1436         .id_table = sscape_pnpids,
1437         .probe = sscape_pnp_detect,
1438         .remove = __devexit_p(sscape_pnp_remove),
1439 };
1440
1441 #endif /* CONFIG_PNP */
1442
1443 static int __init sscape_manual_probe(struct params *params)
1444 {
1445         int ret;
1446         unsigned i;
1447         snd_card_t *card;
1448
1449         for (i = 0; i < SNDRV_CARDS; ++i) {
1450                 /*
1451                  * We do NOT probe for ports.
1452                  * If we're not given a port number for this
1453                  * card then we completely ignore this line
1454                  * of parameters.
1455                  */
1456                 if (port[i] == SNDRV_AUTO_PORT)
1457                         continue;
1458
1459                 /*
1460                  * Make sure we were given ALL of the other parameters.
1461                  */
1462                 if ( (irq[i] == SNDRV_AUTO_IRQ) ||
1463                      (mpu_irq[i] == SNDRV_AUTO_IRQ) ||
1464                      (dma[i] == SNDRV_AUTO_DMA) ) {
1465                         printk(KERN_INFO
1466                                "sscape: insufficient parameters, need IO, IRQ, MPU-IRQ and DMA\n");
1467                         return -ENXIO;
1468                 }
1469
1470                 /*
1471                  * This cards looks OK ...
1472                  */
1473                 init_params(params, index[i], id[i], port[i], irq[i], mpu_irq[i], dma[i]);
1474
1475                 ret = create_sscape(params, &card);
1476                 if (ret < 0)
1477                         return ret;
1478
1479                 sscape_card[sscape_cards] = card;
1480                 params++;
1481                 sscape_cards++;
1482         } /* for */
1483
1484         return 0;
1485 }
1486
1487
1488 static void sscape_exit(void)
1489 {
1490         unsigned i;
1491
1492 #ifdef CONFIG_PNP
1493         pnp_unregister_card_driver(&sscape_pnpc_driver);
1494 #endif
1495         for (i = 0; i < ARRAY_SIZE(sscape_card); ++i) {
1496                 snd_card_free(sscape_card[i]);
1497         } /* for */
1498 }
1499
1500
1501 static int __init sscape_init(void)
1502 {
1503         int ret;
1504
1505         /*
1506          * First check whether we were passed any parameters.
1507          * These MUST take precedence over ANY automatic way
1508          * of allocating cards, because the operator is
1509          * S-P-E-L-L-I-N-G it out for us...
1510          */
1511         ret = sscape_manual_probe(sscape_params);
1512         if (ret < 0) {
1513                 int i;
1514                 for (i = 0; i < sscape_cards; ++i)
1515                         snd_card_free(sscape_card[i]);
1516                 return ret;
1517         }
1518
1519 #ifdef CONFIG_PNP
1520         if (sscape_cards < SNDRV_CARDS) {
1521                 ret = pnp_register_card_driver(&sscape_pnpc_driver);
1522                 if (ret < 0) {
1523                         sscape_exit();
1524                         return ret;
1525                 }
1526         }
1527 #endif
1528
1529         return 0;
1530 }
1531
1532 module_init(sscape_init);
1533 module_exit(sscape_exit);
1534
1535 #ifndef MODULE
1536
1537 /* format is: snd-sscape=index,id,port,irq,mpu_irq,dma */
1538
1539 static int __init builtin_sscape_setup(char *str)
1540 {
1541         static unsigned __initdata nr_dev;
1542
1543         if (nr_dev >= SNDRV_CARDS)
1544                 return 0;
1545
1546         (void)((get_option(&str, &index[nr_dev]) == 2) &&
1547                (get_id(&str, &id[nr_dev]) == 2) &&
1548                (get_option_long(&str, &port[nr_dev]) == 2) &&
1549                (get_option(&str, &irq[nr_dev]) == 2) &&
1550                (get_option(&str, &mpu_irq[nr_dev]) == 2) &&
1551                (get_option(&str, &dma[nr_dev]) == 2)); 
1552  
1553         ++nr_dev;
1554         return 1;
1555 }
1556
1557 __setup("snd-sscape=", builtin_sscape_setup);
1558
1559 #endif
1560