]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - sound/oss/mpu401.c
Merge master.kernel.org:/pub/scm/linux/kernel/git/lethal/sh-2.6
[linux-2.6-omap-h63xx.git] / sound / oss / mpu401.c
1 /*
2  * sound/oss/mpu401.c
3  *
4  * The low level driver for Roland MPU-401 compatible Midi cards.
5  */
6 /*
7  * Copyright (C) by Hannu Savolainen 1993-1997
8  *
9  * OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
10  * Version 2 (June 1991). See the "COPYING" file distributed with this software
11  * for more info.
12  *
13  *
14  * Thomas Sailer        ioctl code reworked (vmalloc/vfree removed)
15  * Alan Cox             modularisation, use normal request_irq, use dev_id
16  * Bartlomiej Zolnierkiewicz    removed some __init to allow using many drivers
17  * Chris Rankin         Update the module-usage counter for the coprocessor
18  * Zwane Mwaikambo      Changed attach/unload resource freeing
19  */
20
21 #include <linux/module.h>
22 #include <linux/init.h>
23 #include <linux/interrupt.h>
24 #include <linux/spinlock.h>
25 #define USE_SEQ_MACROS
26 #define USE_SIMPLE_MACROS
27
28 #include "sound_config.h"
29
30 #include "coproc.h"
31 #include "mpu401.h"
32
33 static int      timer_mode = TMR_INTERNAL, timer_caps = TMR_INTERNAL;
34
35 struct mpu_config
36 {
37         int             base;   /*
38                                  * I/O base
39                                  */
40         int             irq;
41         int             opened; /*
42                                  * Open mode
43                                  */
44         int             devno;
45         int             synthno;
46         int             uart_mode;
47         int             initialized;
48         int             mode;
49 #define MODE_MIDI       1
50 #define MODE_SYNTH      2
51         unsigned char   version, revision;
52         unsigned int    capabilities;
53 #define MPU_CAP_INTLG   0x10000000
54 #define MPU_CAP_SYNC    0x00000010
55 #define MPU_CAP_FSK     0x00000020
56 #define MPU_CAP_CLS     0x00000040
57 #define MPU_CAP_SMPTE   0x00000080
58 #define MPU_CAP_2PORT   0x00000001
59         int             timer_flag;
60
61 #define MBUF_MAX        10
62 #define BUFTEST(dc) if (dc->m_ptr >= MBUF_MAX || dc->m_ptr < 0) \
63         {printk( "MPU: Invalid buffer pointer %d/%d, s=%d\n",  dc->m_ptr,  dc->m_left,  dc->m_state);dc->m_ptr--;}
64           int             m_busy;
65           unsigned char   m_buf[MBUF_MAX];
66           int             m_ptr;
67           int             m_state;
68           int             m_left;
69           unsigned char   last_status;
70           void            (*inputintr) (int dev, unsigned char data);
71           int             shared_irq;
72           int            *osp;
73           spinlock_t    lock;
74   };
75
76 #define DATAPORT(base)   (base)
77 #define COMDPORT(base)   (base+1)
78 #define STATPORT(base)   (base+1)
79
80
81 static void mpu401_close(int dev);
82
83 static inline int mpu401_status(struct mpu_config *devc)
84 {
85         return inb(STATPORT(devc->base));
86 }
87
88 #define input_avail(devc)               (!(mpu401_status(devc)&INPUT_AVAIL))
89 #define output_ready(devc)              (!(mpu401_status(devc)&OUTPUT_READY))
90
91 static inline void write_command(struct mpu_config *devc, unsigned char cmd)
92 {
93         outb(cmd, COMDPORT(devc->base));
94 }
95
96 static inline int read_data(struct mpu_config *devc)
97 {
98         return inb(DATAPORT(devc->base));
99 }
100
101 static inline void write_data(struct mpu_config *devc, unsigned char byte)
102 {
103         outb(byte, DATAPORT(devc->base));
104 }
105
106 #define OUTPUT_READY    0x40
107 #define INPUT_AVAIL     0x80
108 #define MPU_ACK         0xFE
109 #define MPU_RESET       0xFF
110 #define UART_MODE_ON    0x3F
111
112 static struct mpu_config dev_conf[MAX_MIDI_DEV];
113
114 static int n_mpu_devs;
115
116 static int reset_mpu401(struct mpu_config *devc);
117 static void set_uart_mode(int dev, struct mpu_config *devc, int arg);
118
119 static int mpu_timer_init(int midi_dev);
120 static void mpu_timer_interrupt(void);
121 static void timer_ext_event(struct mpu_config *devc, int event, int parm);
122
123 static struct synth_info mpu_synth_info_proto = {
124         "MPU-401 MIDI interface", 
125         0, 
126         SYNTH_TYPE_MIDI, 
127         MIDI_TYPE_MPU401, 
128         0, 128, 
129         0, 128, 
130         SYNTH_CAP_INPUT
131 };
132
133 static struct synth_info mpu_synth_info[MAX_MIDI_DEV];
134
135 /*
136  * States for the input scanner
137  */
138
139 #define ST_INIT                 0       /* Ready for timing byte or msg */
140 #define ST_TIMED                1       /* Leading timing byte rcvd */
141 #define ST_DATABYTE             2       /* Waiting for (nr_left) data bytes */
142
143 #define ST_SYSMSG               100     /* System message (sysx etc). */
144 #define ST_SYSEX                101     /* System exclusive msg */
145 #define ST_MTC                  102     /* Midi Time Code (MTC) qframe msg */
146 #define ST_SONGSEL              103     /* Song select */
147 #define ST_SONGPOS              104     /* Song position pointer */
148
149 static unsigned char len_tab[] =        /* # of data bytes following a status
150                                          */
151 {
152         2,                      /* 8x */
153         2,                      /* 9x */
154         2,                      /* Ax */
155         2,                      /* Bx */
156         1,                      /* Cx */
157         1,                      /* Dx */
158         2,                      /* Ex */
159         0                       /* Fx */
160 };
161
162 #define STORE(cmd) \
163 { \
164         int len; \
165         unsigned char obuf[8]; \
166         cmd; \
167         seq_input_event(obuf, len); \
168 }
169
170 #define _seqbuf obuf
171 #define _seqbufptr 0
172 #define _SEQ_ADVBUF(x) len=x
173
174 static int mpu_input_scanner(struct mpu_config *devc, unsigned char midic)
175 {
176
177         switch (devc->m_state)
178         {
179                 case ST_INIT:
180                         switch (midic)
181                         {
182                                 case 0xf8:
183                                 /* Timer overflow */
184                                         break;
185
186                                 case 0xfc:
187                                         printk("<all end>");
188                                         break;
189
190                                 case 0xfd:
191                                         if (devc->timer_flag)
192                                                 mpu_timer_interrupt();
193                                         break;
194
195                                 case 0xfe:
196                                         return MPU_ACK;
197
198                                 case 0xf0:
199                                 case 0xf1:
200                                 case 0xf2:
201                                 case 0xf3:
202                                 case 0xf4:
203                                 case 0xf5:
204                                 case 0xf6:
205                                 case 0xf7:
206                                         printk("<Trk data rq #%d>", midic & 0x0f);
207                                         break;
208
209                                 case 0xf9:
210                                         printk("<conductor rq>");
211                                         break;
212
213                                 case 0xff:
214                                         devc->m_state = ST_SYSMSG;
215                                         break;
216
217                                 default:
218                                         if (midic <= 0xef)
219                                         {
220                                                 /* printk( "mpu time: %d ",  midic); */
221                                                 devc->m_state = ST_TIMED;
222                                         }
223                                         else
224                                                 printk("<MPU: Unknown event %02x> ", midic);
225                         }
226                         break;
227
228                 case ST_TIMED:
229                         {
230                                 int msg = ((int) (midic & 0xf0) >> 4);
231
232                                 devc->m_state = ST_DATABYTE;
233
234                                 if (msg < 8)    /* Data byte */
235                                 {
236                                         /* printk( "midi msg (running status) "); */
237                                         msg = ((int) (devc->last_status & 0xf0) >> 4);
238                                         msg -= 8;
239                                         devc->m_left = len_tab[msg] - 1;
240
241                                         devc->m_ptr = 2;
242                                         devc->m_buf[0] = devc->last_status;
243                                         devc->m_buf[1] = midic;
244
245                                         if (devc->m_left <= 0)
246                                         {
247                                                 devc->m_state = ST_INIT;
248                                                 do_midi_msg(devc->synthno, devc->m_buf, devc->m_ptr);
249                                                 devc->m_ptr = 0;
250                                         }
251                                 }
252                                 else if (msg == 0xf)    /* MPU MARK */
253                                 {
254                                         devc->m_state = ST_INIT;
255
256                                         switch (midic)
257                                         {
258                                                 case 0xf8:
259                                                         /* printk( "NOP "); */
260                                                         break;
261
262                                                 case 0xf9:
263                                                         /* printk( "meas end "); */
264                                                         break;
265
266                                                 case 0xfc:
267                                                         /* printk( "data end "); */
268                                                         break;
269
270                                                 default:
271                                                         printk("Unknown MPU mark %02x\n", midic);
272                                         }
273                                 }
274                                 else
275                                 {
276                                         devc->last_status = midic;
277                                         /* printk( "midi msg "); */
278                                         msg -= 8;
279                                         devc->m_left = len_tab[msg];
280
281                                         devc->m_ptr = 1;
282                                         devc->m_buf[0] = midic;
283
284                                         if (devc->m_left <= 0)
285                                         {
286                                                 devc->m_state = ST_INIT;
287                                                 do_midi_msg(devc->synthno, devc->m_buf, devc->m_ptr);
288                                                 devc->m_ptr = 0;
289                                         }
290                                 }
291                         }
292                         break;
293
294                 case ST_SYSMSG:
295                         switch (midic)
296                         {
297                                 case 0xf0:
298                                         printk("<SYX>");
299                                         devc->m_state = ST_SYSEX;
300                                         break;
301
302                                 case 0xf1:
303                                         devc->m_state = ST_MTC;
304                                         break;
305
306                                 case 0xf2:
307                                         devc->m_state = ST_SONGPOS;
308                                         devc->m_ptr = 0;
309                                         break;
310
311                                 case 0xf3:
312                                         devc->m_state = ST_SONGSEL;
313                                         break;
314
315                                 case 0xf6:
316                                         /* printk( "tune_request\n"); */
317                                         devc->m_state = ST_INIT;
318
319                                         /*
320                                          *    Real time messages
321                                          */
322                                 case 0xf8:
323                                         /* midi clock */
324                                         devc->m_state = ST_INIT;
325                                         timer_ext_event(devc, TMR_CLOCK, 0);
326                                         break;
327
328                                 case 0xfA:
329                                         devc->m_state = ST_INIT;
330                                         timer_ext_event(devc, TMR_START, 0);
331                                         break;
332
333                                 case 0xFB:
334                                         devc->m_state = ST_INIT;
335                                         timer_ext_event(devc, TMR_CONTINUE, 0);
336                                         break;
337
338                                 case 0xFC:
339                                         devc->m_state = ST_INIT;
340                                         timer_ext_event(devc, TMR_STOP, 0);
341                                         break;
342
343                                 case 0xFE:
344                                         /* active sensing */
345                                         devc->m_state = ST_INIT;
346                                         break;
347
348                                 case 0xff:
349                                         /* printk( "midi hard reset"); */
350                                         devc->m_state = ST_INIT;
351                                         break;
352
353                                 default:
354                                         printk("unknown MIDI sysmsg %0x\n", midic);
355                                         devc->m_state = ST_INIT;
356                         }
357                         break;
358
359                 case ST_MTC:
360                         devc->m_state = ST_INIT;
361                         printk("MTC frame %x02\n", midic);
362                         break;
363
364                 case ST_SYSEX:
365                         if (midic == 0xf7)
366                         {
367                                 printk("<EOX>");
368                                 devc->m_state = ST_INIT;
369                         }
370                         else
371                                 printk("%02x ", midic);
372                         break;
373
374                 case ST_SONGPOS:
375                         BUFTEST(devc);
376                         devc->m_buf[devc->m_ptr++] = midic;
377                         if (devc->m_ptr == 2)
378                         {
379                                 devc->m_state = ST_INIT;
380                                 devc->m_ptr = 0;
381                                 timer_ext_event(devc, TMR_SPP,
382                                         ((devc->m_buf[1] & 0x7f) << 7) |
383                                         (devc->m_buf[0] & 0x7f));
384                         }
385                         break;
386
387                 case ST_DATABYTE:
388                         BUFTEST(devc);
389                         devc->m_buf[devc->m_ptr++] = midic;
390                         if ((--devc->m_left) <= 0)
391                         {
392                                 devc->m_state = ST_INIT;
393                                 do_midi_msg(devc->synthno, devc->m_buf, devc->m_ptr);
394                                 devc->m_ptr = 0;
395                         }
396                         break;
397
398                 default:
399                         printk("Bad state %d ", devc->m_state);
400                         devc->m_state = ST_INIT;
401         }
402         return 1;
403 }
404
405 static void mpu401_input_loop(struct mpu_config *devc)
406 {
407         unsigned long flags;
408         int busy;
409         int n;
410
411         spin_lock_irqsave(&devc->lock,flags);
412         busy = devc->m_busy;
413         devc->m_busy = 1;
414         spin_unlock_irqrestore(&devc->lock,flags);
415
416         if (busy)               /* Already inside the scanner */
417                 return;
418
419         n = 50;
420
421         while (input_avail(devc) && n-- > 0)
422         {
423                 unsigned char c = read_data(devc);
424
425                 if (devc->mode == MODE_SYNTH)
426                 {
427                         mpu_input_scanner(devc, c);
428                 }
429                 else if (devc->opened & OPEN_READ && devc->inputintr != NULL)
430                         devc->inputintr(devc->devno, c);
431         }
432         devc->m_busy = 0;
433 }
434
435 static irqreturn_t mpuintr(int irq, void *dev_id)
436 {
437         struct mpu_config *devc;
438         int dev = (int)(unsigned long) dev_id;
439         int handled = 0;
440
441         devc = &dev_conf[dev];
442
443         if (input_avail(devc))
444         {
445                 handled = 1;
446                 if (devc->base != 0 && (devc->opened & OPEN_READ || devc->mode == MODE_SYNTH))
447                         mpu401_input_loop(devc);
448                 else
449                 {
450                         /* Dummy read (just to acknowledge the interrupt) */
451                         read_data(devc);
452                 }
453         }
454         return IRQ_RETVAL(handled);
455 }
456
457 static int mpu401_open(int dev, int mode,
458             void            (*input) (int dev, unsigned char data),
459             void            (*output) (int dev)
460 )
461 {
462         int err;
463         struct mpu_config *devc;
464         struct coproc_operations *coprocessor;
465
466         if (dev < 0 || dev >= num_midis || midi_devs[dev] == NULL)
467                 return -ENXIO;
468
469         devc = &dev_conf[dev];
470
471         if (devc->opened)
472                   return -EBUSY;
473         /*
474          *  Verify that the device is really running.
475          *  Some devices (such as Ensoniq SoundScape don't
476          *  work before the on board processor (OBP) is initialized
477          *  by downloading its microcode.
478          */
479
480         if (!devc->initialized)
481         {
482                 if (mpu401_status(devc) == 0xff)        /* Bus float */
483                 {
484                         printk(KERN_ERR "mpu401: Device not initialized properly\n");
485                         return -EIO;
486                 }
487                 reset_mpu401(devc);
488         }
489
490         if ( (coprocessor = midi_devs[dev]->coproc) != NULL )
491         {
492                 if (!try_module_get(coprocessor->owner)) {
493                         mpu401_close(dev);
494                         return -ENODEV;
495                 }
496
497                 if ((err = coprocessor->open(coprocessor->devc, COPR_MIDI)) < 0)
498                 {
499                         printk(KERN_WARNING "MPU-401: Can't access coprocessor device\n");
500                         mpu401_close(dev);
501                         return err;
502                 }
503         }
504         
505         set_uart_mode(dev, devc, 1);
506         devc->mode = MODE_MIDI;
507         devc->synthno = 0;
508
509         mpu401_input_loop(devc);
510
511         devc->inputintr = input;
512         devc->opened = mode;
513
514         return 0;
515 }
516
517 static void mpu401_close(int dev)
518 {
519         struct mpu_config *devc;
520         struct coproc_operations *coprocessor;
521
522         devc = &dev_conf[dev];
523         if (devc->uart_mode)
524                 reset_mpu401(devc);     /*
525                                          * This disables the UART mode
526                                          */
527         devc->mode = 0;
528         devc->inputintr = NULL;
529
530         coprocessor = midi_devs[dev]->coproc;
531         if (coprocessor) {
532                 coprocessor->close(coprocessor->devc, COPR_MIDI);
533                 module_put(coprocessor->owner);
534         }
535         devc->opened = 0;
536 }
537
538 static int mpu401_out(int dev, unsigned char midi_byte)
539 {
540         int timeout;
541         unsigned long flags;
542
543         struct mpu_config *devc;
544
545         devc = &dev_conf[dev];
546
547         /*
548          * Sometimes it takes about 30000 loops before the output becomes ready
549          * (After reset). Normally it takes just about 10 loops.
550          */
551
552         for (timeout = 30000; timeout > 0 && !output_ready(devc); timeout--);
553
554         spin_lock_irqsave(&devc->lock,flags);
555         if (!output_ready(devc))
556         {
557                 printk(KERN_WARNING "mpu401: Send data timeout\n");
558                 spin_unlock_irqrestore(&devc->lock,flags);
559                 return 0;
560         }
561         write_data(devc, midi_byte);
562         spin_unlock_irqrestore(&devc->lock,flags);
563         return 1;
564 }
565
566 static int mpu401_command(int dev, mpu_command_rec * cmd)
567 {
568         int i, timeout, ok;
569         int ret = 0;
570         unsigned long   flags;
571         struct mpu_config *devc;
572
573         devc = &dev_conf[dev];
574
575         if (devc->uart_mode)    /*
576                                  * Not possible in UART mode
577                                  */
578         {
579                 printk(KERN_WARNING "mpu401: commands not possible in the UART mode\n");
580                 return -EINVAL;
581         }
582         /*
583          * Test for input since pending input seems to block the output.
584          */
585         if (input_avail(devc))
586                 mpu401_input_loop(devc);
587
588         /*
589          * Sometimes it takes about 50000 loops before the output becomes ready
590          * (After reset). Normally it takes just about 10 loops.
591          */
592
593         timeout = 50000;
594 retry:
595         if (timeout-- <= 0)
596         {
597                 printk(KERN_WARNING "mpu401: Command (0x%x) timeout\n", (int) cmd->cmd);
598                 return -EIO;
599         }
600         spin_lock_irqsave(&devc->lock,flags);
601
602         if (!output_ready(devc))
603         {
604                 spin_unlock_irqrestore(&devc->lock,flags);
605                 goto retry;
606         }
607         write_command(devc, cmd->cmd);
608
609         ok = 0;
610         for (timeout = 50000; timeout > 0 && !ok; timeout--)
611         {
612                 if (input_avail(devc))
613                 {
614                         if (devc->opened && devc->mode == MODE_SYNTH)
615                         {
616                                 if (mpu_input_scanner(devc, read_data(devc)) == MPU_ACK)
617                                         ok = 1;
618                         }
619                         else
620                         {
621                                 /* Device is not currently open. Use simpler method */
622                                 if (read_data(devc) == MPU_ACK)
623                                         ok = 1;
624                         }
625                 }
626         }
627         if (!ok)
628         {
629                 spin_unlock_irqrestore(&devc->lock,flags);
630                 return -EIO;
631         }
632         if (cmd->nr_args)
633         {
634                 for (i = 0; i < cmd->nr_args; i++)
635                 {
636                         for (timeout = 3000; timeout > 0 && !output_ready(devc); timeout--);
637
638                         if (!mpu401_out(dev, cmd->data[i]))
639                         {
640                                 spin_unlock_irqrestore(&devc->lock,flags);
641                                 printk(KERN_WARNING "mpu401: Command (0x%x), parm send failed.\n", (int) cmd->cmd);
642                                 return -EIO;
643                         }
644                 }
645         }
646         ret = 0;
647         cmd->data[0] = 0;
648
649         if (cmd->nr_returns)
650         {
651                 for (i = 0; i < cmd->nr_returns; i++)
652                 {
653                         ok = 0;
654                         for (timeout = 5000; timeout > 0 && !ok; timeout--)
655                                 if (input_avail(devc))
656                                 {
657                                         cmd->data[i] = read_data(devc);
658                                         ok = 1;
659                                 }
660                         if (!ok)
661                         {
662                                 spin_unlock_irqrestore(&devc->lock,flags);
663                                 return -EIO;
664                         }
665                 }
666         }
667         spin_unlock_irqrestore(&devc->lock,flags);
668         return ret;
669 }
670
671 static int mpu_cmd(int dev, int cmd, int data)
672 {
673         int ret;
674
675         static mpu_command_rec rec;
676
677         rec.cmd = cmd & 0xff;
678         rec.nr_args = ((cmd & 0xf0) == 0xE0);
679         rec.nr_returns = ((cmd & 0xf0) == 0xA0);
680         rec.data[0] = data & 0xff;
681
682         if ((ret = mpu401_command(dev, &rec)) < 0)
683                 return ret;
684         return (unsigned char) rec.data[0];
685 }
686
687 static int mpu401_prefix_cmd(int dev, unsigned char status)
688 {
689         struct mpu_config *devc = &dev_conf[dev];
690
691         if (devc->uart_mode)
692                 return 1;
693
694         if (status < 0xf0)
695         {
696                 if (mpu_cmd(dev, 0xD0, 0) < 0)
697                         return 0;
698                 return 1;
699         }
700         switch (status)
701         {
702                 case 0xF0:
703                         if (mpu_cmd(dev, 0xDF, 0) < 0)
704                                 return 0;
705                         return 1;
706
707                 default:
708                         return 0;
709         }
710 }
711
712 static int mpu401_start_read(int dev)
713 {
714         return 0;
715 }
716
717 static int mpu401_end_read(int dev)
718 {
719         return 0;
720 }
721
722 static int mpu401_ioctl(int dev, unsigned cmd, void __user *arg)
723 {
724         struct mpu_config *devc;
725         mpu_command_rec rec;
726         int val, ret;
727
728         devc = &dev_conf[dev];
729         switch (cmd) 
730         {
731                 case SNDCTL_MIDI_MPUMODE:
732                         if (!(devc->capabilities & MPU_CAP_INTLG)) { /* No intelligent mode */
733                                 printk(KERN_WARNING "mpu401: Intelligent mode not supported by the HW\n");
734                                 return -EINVAL;
735                         }
736                         if (get_user(val, (int __user *)arg))
737                                 return -EFAULT;
738                         set_uart_mode(dev, devc, !val);
739                         return 0;
740
741                 case SNDCTL_MIDI_MPUCMD:
742                         if (copy_from_user(&rec, arg, sizeof(rec)))
743                                 return -EFAULT;
744                         if ((ret = mpu401_command(dev, &rec)) < 0)
745                                 return ret;
746                         if (copy_to_user(arg, &rec, sizeof(rec)))
747                                 return -EFAULT;
748                         return 0;
749
750                 default:
751                         return -EINVAL;
752         }
753 }
754
755 static void mpu401_kick(int dev)
756 {
757 }
758
759 static int mpu401_buffer_status(int dev)
760 {
761         return 0;               /*
762                                  * No data in buffers
763                                  */
764 }
765
766 static int mpu_synth_ioctl(int dev, unsigned int cmd, void __user *arg)
767 {
768         int midi_dev;
769         struct mpu_config *devc;
770
771         midi_dev = synth_devs[dev]->midi_dev;
772
773         if (midi_dev < 0 || midi_dev > num_midis || midi_devs[midi_dev] == NULL)
774                 return -ENXIO;
775
776         devc = &dev_conf[midi_dev];
777
778         switch (cmd)
779         {
780
781                 case SNDCTL_SYNTH_INFO:
782                         if (copy_to_user(arg, &mpu_synth_info[midi_dev],
783                                         sizeof(struct synth_info)))
784                                 return -EFAULT;
785                         return 0;
786
787                 case SNDCTL_SYNTH_MEMAVL:
788                         return 0x7fffffff;
789
790                 default:
791                         return -EINVAL;
792         }
793 }
794
795 static int mpu_synth_open(int dev, int mode)
796 {
797         int midi_dev, err;
798         struct mpu_config *devc;
799         struct coproc_operations *coprocessor;
800
801         midi_dev = synth_devs[dev]->midi_dev;
802
803         if (midi_dev < 0 || midi_dev > num_midis || midi_devs[midi_dev] == NULL)
804                 return -ENXIO;
805
806         devc = &dev_conf[midi_dev];
807
808         /*
809          *  Verify that the device is really running.
810          *  Some devices (such as Ensoniq SoundScape don't
811          *  work before the on board processor (OBP) is initialized
812          *  by downloading its microcode.
813          */
814
815         if (!devc->initialized)
816         {
817                 if (mpu401_status(devc) == 0xff)        /* Bus float */
818                 {
819                         printk(KERN_ERR "mpu401: Device not initialized properly\n");
820                         return -EIO;
821                 }
822                 reset_mpu401(devc);
823         }
824         if (devc->opened)
825                 return -EBUSY;
826         devc->mode = MODE_SYNTH;
827         devc->synthno = dev;
828
829         devc->inputintr = NULL;
830
831         coprocessor = midi_devs[midi_dev]->coproc;
832         if (coprocessor) {
833                 if (!try_module_get(coprocessor->owner))
834                         return -ENODEV;
835
836                 if ((err = coprocessor->open(coprocessor->devc, COPR_MIDI)) < 0)
837                 {
838                         printk(KERN_WARNING "mpu401: Can't access coprocessor device\n");
839                         return err;
840                 }
841         }
842         devc->opened = mode;
843         reset_mpu401(devc);
844
845         if (mode & OPEN_READ)
846         {
847                 mpu_cmd(midi_dev, 0x8B, 0);     /* Enable data in stop mode */
848                 mpu_cmd(midi_dev, 0x34, 0);     /* Return timing bytes in stop mode */
849                 mpu_cmd(midi_dev, 0x87, 0);     /* Enable pitch & controller */
850         }
851         return 0;
852 }
853
854 static void mpu_synth_close(int dev)
855
856         int midi_dev;
857         struct mpu_config *devc;
858         struct coproc_operations *coprocessor;
859
860         midi_dev = synth_devs[dev]->midi_dev;
861
862         devc = &dev_conf[midi_dev];
863         mpu_cmd(midi_dev, 0x15, 0);     /* Stop recording, playback and MIDI */
864         mpu_cmd(midi_dev, 0x8a, 0);     /* Disable data in stopped mode */
865
866         devc->inputintr = NULL;
867
868         coprocessor = midi_devs[midi_dev]->coproc;
869         if (coprocessor) {
870                 coprocessor->close(coprocessor->devc, COPR_MIDI);
871                 module_put(coprocessor->owner);
872         }
873         devc->opened = 0;
874         devc->mode = 0;
875 }
876
877 #define MIDI_SYNTH_NAME "MPU-401 UART Midi"
878 #define MIDI_SYNTH_CAPS SYNTH_CAP_INPUT
879 #include "midi_synth.h"
880
881 static struct synth_operations mpu401_synth_proto =
882 {
883         .owner          = THIS_MODULE,
884         .id             = "MPU401",
885         .info           = NULL,
886         .midi_dev       = 0,
887         .synth_type     = SYNTH_TYPE_MIDI,
888         .synth_subtype  = 0,
889         .open           = mpu_synth_open,
890         .close          = mpu_synth_close,
891         .ioctl          = mpu_synth_ioctl,
892         .kill_note      = midi_synth_kill_note,
893         .start_note     = midi_synth_start_note,
894         .set_instr      = midi_synth_set_instr,
895         .reset          = midi_synth_reset,
896         .hw_control     = midi_synth_hw_control,
897         .load_patch     = midi_synth_load_patch,
898         .aftertouch     = midi_synth_aftertouch,
899         .controller     = midi_synth_controller,
900         .panning        = midi_synth_panning,
901         .bender         = midi_synth_bender,
902         .setup_voice    = midi_synth_setup_voice,
903         .send_sysex     = midi_synth_send_sysex
904 };
905
906 static struct synth_operations *mpu401_synth_operations[MAX_MIDI_DEV];
907
908 static struct midi_operations mpu401_midi_proto =
909 {
910         .owner          = THIS_MODULE,
911         .info           = {"MPU-401 Midi", 0, MIDI_CAP_MPU401, SNDCARD_MPU401},
912         .in_info        = {0},
913         .open           = mpu401_open,
914         .close          = mpu401_close,
915         .ioctl          = mpu401_ioctl,
916         .outputc        = mpu401_out,
917         .start_read     = mpu401_start_read,
918         .end_read       = mpu401_end_read,
919         .kick           = mpu401_kick,
920         .buffer_status  = mpu401_buffer_status,
921         .prefix_cmd     = mpu401_prefix_cmd
922 };
923
924 static struct midi_operations mpu401_midi_operations[MAX_MIDI_DEV];
925
926 static void mpu401_chk_version(int n, struct mpu_config *devc)
927 {
928         int tmp;
929         unsigned long flags;
930
931         devc->version = devc->revision = 0;
932
933         spin_lock_irqsave(&devc->lock,flags);
934         if ((tmp = mpu_cmd(n, 0xAC, 0)) < 0)
935         {
936                 spin_unlock_irqrestore(&devc->lock,flags);
937                 return;
938         }
939         if ((tmp & 0xf0) > 0x20)        /* Why it's larger than 2.x ??? */
940         {
941                 spin_unlock_irqrestore(&devc->lock,flags);
942                 return;
943         }
944         devc->version = tmp;
945
946         if ((tmp = mpu_cmd(n, 0xAD, 0)) < 0)
947         {
948                 devc->version = 0;
949                 spin_unlock_irqrestore(&devc->lock,flags);
950                 return;
951         }
952         devc->revision = tmp;
953         spin_unlock_irqrestore(&devc->lock,flags);
954 }
955
956 int attach_mpu401(struct address_info *hw_config, struct module *owner)
957 {
958         unsigned long flags;
959         char revision_char;
960
961         int m, ret;
962         struct mpu_config *devc;
963
964         hw_config->slots[1] = -1;
965         m = sound_alloc_mididev();
966         if (m == -1)
967         {
968                 printk(KERN_WARNING "MPU-401: Too many midi devices detected\n");
969                 ret = -ENOMEM;
970                 goto out_err;
971         }
972         devc = &dev_conf[m];
973         devc->base = hw_config->io_base;
974         devc->osp = hw_config->osp;
975         devc->irq = hw_config->irq;
976         devc->opened = 0;
977         devc->uart_mode = 0;
978         devc->initialized = 0;
979         devc->version = 0;
980         devc->revision = 0;
981         devc->capabilities = 0;
982         devc->timer_flag = 0;
983         devc->m_busy = 0;
984         devc->m_state = ST_INIT;
985         devc->shared_irq = hw_config->always_detect;
986         devc->irq = hw_config->irq;
987         spin_lock_init(&devc->lock);
988
989         if (devc->irq < 0)
990         {
991                 devc->irq *= -1;
992                 devc->shared_irq = 1;
993         }
994
995         if (!hw_config->always_detect)
996         {
997                 /* Verify the hardware again */
998                 if (!reset_mpu401(devc))
999                 {
1000                         printk(KERN_WARNING "mpu401: Device didn't respond\n");
1001                         ret = -ENODEV;
1002                         goto out_mididev;
1003                 }
1004                 if (!devc->shared_irq)
1005                 {
1006                         if (request_irq(devc->irq, mpuintr, 0, "mpu401", (void *)m) < 0)
1007                         {
1008                                 printk(KERN_WARNING "mpu401: Failed to allocate IRQ%d\n", devc->irq);
1009                                 ret = -ENOMEM;
1010                                 goto out_mididev;
1011                         }
1012                 }
1013                 spin_lock_irqsave(&devc->lock,flags);
1014                 mpu401_chk_version(m, devc);
1015                 if (devc->version == 0)
1016                         mpu401_chk_version(m, devc);
1017                         spin_unlock_irqrestore(&devc->lock,flags);
1018         }
1019
1020         if (devc->version != 0)
1021                 if (mpu_cmd(m, 0xC5, 0) >= 0)   /* Set timebase OK */
1022                         if (mpu_cmd(m, 0xE0, 120) >= 0)         /* Set tempo OK */
1023                                 devc->capabilities |= MPU_CAP_INTLG;    /* Supports intelligent mode */
1024
1025
1026         mpu401_synth_operations[m] = (struct synth_operations *)kmalloc(sizeof(struct synth_operations), GFP_KERNEL);
1027
1028         if (mpu401_synth_operations[m] == NULL)
1029         {
1030                 printk(KERN_ERR "mpu401: Can't allocate memory\n");
1031                 ret = -ENOMEM;
1032                 goto out_irq;
1033         }
1034         if (!(devc->capabilities & MPU_CAP_INTLG))      /* No intelligent mode */
1035         {
1036                 memcpy((char *) mpu401_synth_operations[m],
1037                         (char *) &std_midi_synth,
1038                          sizeof(struct synth_operations));
1039         }
1040         else
1041         {
1042                 memcpy((char *) mpu401_synth_operations[m],
1043                         (char *) &mpu401_synth_proto,
1044                          sizeof(struct synth_operations));
1045         }
1046         if (owner)
1047                 mpu401_synth_operations[m]->owner = owner;
1048
1049         memcpy((char *) &mpu401_midi_operations[m],
1050                (char *) &mpu401_midi_proto,
1051                sizeof(struct midi_operations));
1052
1053         mpu401_midi_operations[m].converter = mpu401_synth_operations[m];
1054
1055         memcpy((char *) &mpu_synth_info[m],
1056                (char *) &mpu_synth_info_proto,
1057                sizeof(struct synth_info));
1058
1059         n_mpu_devs++;
1060
1061         if (devc->version == 0x20 && devc->revision >= 0x07)    /* MusicQuest interface */
1062         {
1063                 int ports = (devc->revision & 0x08) ? 32 : 16;
1064
1065                 devc->capabilities |= MPU_CAP_SYNC | MPU_CAP_SMPTE |
1066                                 MPU_CAP_CLS | MPU_CAP_2PORT;
1067
1068                 revision_char = (devc->revision == 0x7f) ? 'M' : ' ';
1069                 sprintf(mpu_synth_info[m].name, "MQX-%d%c MIDI Interface #%d",
1070                                 ports,
1071                                 revision_char,
1072                                 n_mpu_devs);
1073         }
1074         else
1075         {
1076                 revision_char = devc->revision ? devc->revision + '@' : ' ';
1077                 if ((int) devc->revision > ('Z' - '@'))
1078                         revision_char = '+';
1079
1080                 devc->capabilities |= MPU_CAP_SYNC | MPU_CAP_FSK;
1081
1082                 if (hw_config->name)
1083                         sprintf(mpu_synth_info[m].name, "%s (MPU401)", hw_config->name);
1084                 else
1085                         sprintf(mpu_synth_info[m].name,
1086                                 "MPU-401 %d.%d%c Midi interface #%d",
1087                                 (int) (devc->version & 0xf0) >> 4,
1088                                 devc->version & 0x0f,
1089                                 revision_char,
1090                                 n_mpu_devs);
1091         }
1092
1093         strcpy(mpu401_midi_operations[m].info.name,
1094                mpu_synth_info[m].name);
1095
1096         conf_printf(mpu_synth_info[m].name, hw_config);
1097
1098         mpu401_synth_operations[m]->midi_dev = devc->devno = m;
1099         mpu401_synth_operations[devc->devno]->info = &mpu_synth_info[devc->devno];
1100
1101         if (devc->capabilities & MPU_CAP_INTLG)         /* Intelligent mode */
1102                 hw_config->slots[2] = mpu_timer_init(m);
1103
1104         midi_devs[m] = &mpu401_midi_operations[devc->devno];
1105         
1106         if (owner)
1107                 midi_devs[m]->owner = owner;
1108
1109         hw_config->slots[1] = m;
1110         sequencer_init();
1111         
1112         return 0;
1113
1114 out_irq:
1115         free_irq(devc->irq, (void *)m);
1116 out_mididev:
1117         sound_unload_mididev(m);
1118 out_err:
1119         release_region(hw_config->io_base, 2);
1120         return ret;
1121 }
1122
1123 static int reset_mpu401(struct mpu_config *devc)
1124 {
1125         unsigned long flags;
1126         int ok, timeout, n;
1127         int timeout_limit;
1128
1129         /*
1130          * Send the RESET command. Try again if no success at the first time.
1131          * (If the device is in the UART mode, it will not ack the reset cmd).
1132          */
1133
1134         ok = 0;
1135
1136         timeout_limit = devc->initialized ? 30000 : 100000;
1137         devc->initialized = 1;
1138
1139         for (n = 0; n < 2 && !ok; n++)
1140         {
1141                 for (timeout = timeout_limit; timeout > 0 && !ok; timeout--)
1142                           ok = output_ready(devc);
1143
1144                 write_command(devc, MPU_RESET); /*
1145                                                            * Send MPU-401 RESET Command
1146                                                          */
1147
1148                 /*
1149                  * Wait at least 25 msec. This method is not accurate so let's make the
1150                  * loop bit longer. Cannot sleep since this is called during boot.
1151                  */
1152
1153                 for (timeout = timeout_limit * 2; timeout > 0 && !ok; timeout--)
1154                 {
1155                         spin_lock_irqsave(&devc->lock,flags);
1156                         if (input_avail(devc))
1157                                 if (read_data(devc) == MPU_ACK)
1158                                         ok = 1;
1159                         spin_unlock_irqrestore(&devc->lock,flags);
1160                 }
1161
1162         }
1163
1164         devc->m_state = ST_INIT;
1165         devc->m_ptr = 0;
1166         devc->m_left = 0;
1167         devc->last_status = 0;
1168         devc->uart_mode = 0;
1169
1170         return ok;
1171 }
1172
1173 static void set_uart_mode(int dev, struct mpu_config *devc, int arg)
1174 {
1175         if (!arg && (devc->capabilities & MPU_CAP_INTLG))
1176                 return;
1177         if ((devc->uart_mode == 0) == (arg == 0))
1178                 return;         /* Already set */
1179         reset_mpu401(devc);     /* This exits the uart mode */
1180
1181         if (arg)
1182         {
1183                 if (mpu_cmd(dev, UART_MODE_ON, 0) < 0)
1184                 {
1185                         printk(KERN_ERR "mpu401: Can't enter UART mode\n");
1186                         devc->uart_mode = 0;
1187                         return;
1188                 }
1189         }
1190         devc->uart_mode = arg;
1191
1192 }
1193
1194 int probe_mpu401(struct address_info *hw_config, struct resource *ports)
1195 {
1196         int ok = 0;
1197         struct mpu_config tmp_devc;
1198
1199         tmp_devc.base = hw_config->io_base;
1200         tmp_devc.irq = hw_config->irq;
1201         tmp_devc.initialized = 0;
1202         tmp_devc.opened = 0;
1203         tmp_devc.osp = hw_config->osp;
1204
1205         if (hw_config->always_detect)
1206                 return 1;
1207
1208         if (inb(hw_config->io_base + 1) == 0xff)
1209         {
1210                 DDB(printk("MPU401: Port %x looks dead.\n", hw_config->io_base));
1211                 return 0;       /* Just bus float? */
1212         }
1213         ok = reset_mpu401(&tmp_devc);
1214
1215         if (!ok)
1216         {
1217                 DDB(printk("MPU401: Reset failed on port %x\n", hw_config->io_base));
1218         }
1219         return ok;
1220 }
1221
1222 void unload_mpu401(struct address_info *hw_config)
1223 {
1224         void *p;
1225         int n=hw_config->slots[1];
1226                 
1227         if (n != -1) {
1228                 release_region(hw_config->io_base, 2);
1229                 if (hw_config->always_detect == 0 && hw_config->irq > 0)
1230                         free_irq(hw_config->irq, (void *)n);
1231                 p=mpu401_synth_operations[n];
1232                 sound_unload_mididev(n);
1233                 sound_unload_timerdev(hw_config->slots[2]);
1234                 kfree(p);
1235         }
1236 }
1237
1238 /*****************************************************
1239  *      Timer stuff
1240  ****************************************************/
1241
1242 static volatile int timer_initialized = 0, timer_open = 0, tmr_running = 0;
1243 static volatile int curr_tempo, curr_timebase, hw_timebase;
1244 static int      max_timebase = 8;       /* 8*24=192 ppqn */
1245 static volatile unsigned long next_event_time;
1246 static volatile unsigned long curr_ticks, curr_clocks;
1247 static unsigned long prev_event_time;
1248 static int      metronome_mode;
1249
1250 static unsigned long clocks2ticks(unsigned long clocks)
1251 {
1252         /*
1253          * The MPU-401 supports just a limited set of possible timebase values.
1254          * Since the applications require more choices, the driver has to
1255          * program the HW to do its best and to convert between the HW and
1256          * actual timebases.
1257          */
1258         return ((clocks * curr_timebase) + (hw_timebase / 2)) / hw_timebase;
1259 }
1260
1261 static void set_timebase(int midi_dev, int val)
1262 {
1263         int hw_val;
1264
1265         if (val < 48)
1266                 val = 48;
1267         if (val > 1000)
1268                 val = 1000;
1269
1270         hw_val = val;
1271         hw_val = (hw_val + 12) / 24;
1272         if (hw_val > max_timebase)
1273                 hw_val = max_timebase;
1274
1275         if (mpu_cmd(midi_dev, 0xC0 | (hw_val & 0x0f), 0) < 0)
1276         {
1277                 printk(KERN_WARNING "mpu401: Can't set HW timebase to %d\n", hw_val * 24);
1278                 return;
1279         }
1280         hw_timebase = hw_val * 24;
1281         curr_timebase = val;
1282
1283 }
1284
1285 static void tmr_reset(struct mpu_config *devc)
1286 {
1287         unsigned long flags;
1288
1289         spin_lock_irqsave(&devc->lock,flags);
1290         next_event_time = (unsigned long) -1;
1291         prev_event_time = 0;
1292         curr_ticks = curr_clocks = 0;
1293         spin_unlock_irqrestore(&devc->lock,flags);
1294 }
1295
1296 static void set_timer_mode(int midi_dev)
1297 {
1298         if (timer_mode & TMR_MODE_CLS)
1299                 mpu_cmd(midi_dev, 0x3c, 0);     /* Use CLS sync */
1300         else if (timer_mode & TMR_MODE_SMPTE)
1301                 mpu_cmd(midi_dev, 0x3d, 0);     /* Use SMPTE sync */
1302
1303         if (timer_mode & TMR_INTERNAL)
1304         {
1305                   mpu_cmd(midi_dev, 0x80, 0);   /* Use MIDI sync */
1306         }
1307         else
1308         {
1309                 if (timer_mode & (TMR_MODE_MIDI | TMR_MODE_CLS))
1310                 {
1311                         mpu_cmd(midi_dev, 0x82, 0);             /* Use MIDI sync */
1312                         mpu_cmd(midi_dev, 0x91, 0);             /* Enable ext MIDI ctrl */
1313                 }
1314                 else if (timer_mode & TMR_MODE_FSK)
1315                         mpu_cmd(midi_dev, 0x81, 0);     /* Use FSK sync */
1316         }
1317 }
1318
1319 static void stop_metronome(int midi_dev)
1320 {
1321         mpu_cmd(midi_dev, 0x84, 0);     /* Disable metronome */
1322 }
1323
1324 static void setup_metronome(int midi_dev)
1325 {
1326         int numerator, denominator;
1327         int clks_per_click, num_32nds_per_beat;
1328         int beats_per_measure;
1329
1330         numerator = ((unsigned) metronome_mode >> 24) & 0xff;
1331         denominator = ((unsigned) metronome_mode >> 16) & 0xff;
1332         clks_per_click = ((unsigned) metronome_mode >> 8) & 0xff;
1333         num_32nds_per_beat = (unsigned) metronome_mode & 0xff;
1334         beats_per_measure = (numerator * 4) >> denominator;
1335
1336         if (!metronome_mode)
1337                 mpu_cmd(midi_dev, 0x84, 0);     /* Disable metronome */
1338         else
1339         {
1340                 mpu_cmd(midi_dev, 0xE4, clks_per_click);
1341                 mpu_cmd(midi_dev, 0xE6, beats_per_measure);
1342                 mpu_cmd(midi_dev, 0x83, 0);     /* Enable metronome without accents */
1343         }
1344 }
1345
1346 static int mpu_start_timer(int midi_dev)
1347 {
1348         struct mpu_config *devc= &dev_conf[midi_dev];
1349
1350         tmr_reset(devc);
1351         set_timer_mode(midi_dev);
1352
1353         if (tmr_running)
1354                 return TIMER_NOT_ARMED;         /* Already running */
1355
1356         if (timer_mode & TMR_INTERNAL)
1357         {
1358                 mpu_cmd(midi_dev, 0x02, 0);     /* Send MIDI start */
1359                 tmr_running = 1;
1360                 return TIMER_NOT_ARMED;
1361         }
1362         else
1363         {
1364                 mpu_cmd(midi_dev, 0x35, 0);     /* Enable mode messages to PC */
1365                 mpu_cmd(midi_dev, 0x38, 0);     /* Enable sys common messages to PC */
1366                 mpu_cmd(midi_dev, 0x39, 0);     /* Enable real time messages to PC */
1367                 mpu_cmd(midi_dev, 0x97, 0);     /* Enable system exclusive messages to PC */
1368         }
1369         return TIMER_ARMED;
1370 }
1371
1372 static int mpu_timer_open(int dev, int mode)
1373 {
1374         int midi_dev = sound_timer_devs[dev]->devlink;
1375         struct mpu_config *devc= &dev_conf[midi_dev];
1376
1377         if (timer_open)
1378                 return -EBUSY;
1379
1380         tmr_reset(devc);
1381         curr_tempo = 50;
1382         mpu_cmd(midi_dev, 0xE0, 50);
1383         curr_timebase = hw_timebase = 120;
1384         set_timebase(midi_dev, 120);
1385         timer_open = 1;
1386         metronome_mode = 0;
1387         set_timer_mode(midi_dev);
1388
1389         mpu_cmd(midi_dev, 0xe7, 0x04);  /* Send all clocks to host */
1390         mpu_cmd(midi_dev, 0x95, 0);     /* Enable clock to host */
1391
1392         return 0;
1393 }
1394
1395 static void mpu_timer_close(int dev)
1396 {
1397         int midi_dev = sound_timer_devs[dev]->devlink;
1398
1399         timer_open = tmr_running = 0;
1400         mpu_cmd(midi_dev, 0x15, 0);     /* Stop all */
1401         mpu_cmd(midi_dev, 0x94, 0);     /* Disable clock to host */
1402         mpu_cmd(midi_dev, 0x8c, 0);     /* Disable measure end messages to host */
1403         stop_metronome(midi_dev);
1404 }
1405
1406 static int mpu_timer_event(int dev, unsigned char *event)
1407 {
1408         unsigned char command = event[1];
1409         unsigned long parm = *(unsigned int *) &event[4];
1410         int midi_dev = sound_timer_devs[dev]->devlink;
1411
1412         switch (command)
1413         {
1414                 case TMR_WAIT_REL:
1415                         parm += prev_event_time;
1416                 case TMR_WAIT_ABS:
1417                         if (parm > 0)
1418                         {
1419                                 long time;
1420
1421                                 if (parm <= curr_ticks) /* It's the time */
1422                                         return TIMER_NOT_ARMED;
1423                                 time = parm;
1424                                 next_event_time = prev_event_time = time;
1425
1426                                 return TIMER_ARMED;
1427                         }
1428                         break;
1429
1430                 case TMR_START:
1431                         if (tmr_running)
1432                                 break;
1433                         return mpu_start_timer(midi_dev);
1434
1435                 case TMR_STOP:
1436                         mpu_cmd(midi_dev, 0x01, 0);     /* Send MIDI stop */
1437                         stop_metronome(midi_dev);
1438                         tmr_running = 0;
1439                         break;
1440
1441                 case TMR_CONTINUE:
1442                         if (tmr_running)
1443                                 break;
1444                         mpu_cmd(midi_dev, 0x03, 0);     /* Send MIDI continue */
1445                         setup_metronome(midi_dev);
1446                         tmr_running = 1;
1447                         break;
1448
1449                 case TMR_TEMPO:
1450                         if (parm)
1451                         {
1452                                 if (parm < 8)
1453                                         parm = 8;
1454                                 if (parm > 250)
1455                                         parm = 250;
1456                                 if (mpu_cmd(midi_dev, 0xE0, parm) < 0)
1457                                         printk(KERN_WARNING "mpu401: Can't set tempo to %d\n", (int) parm);
1458                                 curr_tempo = parm;
1459                         }
1460                         break;
1461
1462                 case TMR_ECHO:
1463                         seq_copy_to_input(event, 8);
1464                         break;
1465
1466                 case TMR_TIMESIG:
1467                         if (metronome_mode)     /* Metronome enabled */
1468                         {
1469                                 metronome_mode = parm;
1470                                 setup_metronome(midi_dev);
1471                         }
1472                         break;
1473
1474                 default:;
1475         }
1476         return TIMER_NOT_ARMED;
1477 }
1478
1479 static unsigned long mpu_timer_get_time(int dev)
1480 {
1481         if (!timer_open)
1482                 return 0;
1483
1484         return curr_ticks;
1485 }
1486
1487 static int mpu_timer_ioctl(int dev, unsigned int command, void __user *arg)
1488 {
1489         int midi_dev = sound_timer_devs[dev]->devlink;
1490         int __user *p = (int __user *)arg;
1491
1492         switch (command)
1493         {
1494                 case SNDCTL_TMR_SOURCE:
1495                         {
1496                                 int parm;
1497
1498                                 if (get_user(parm, p))
1499                                         return -EFAULT;
1500                                 parm &= timer_caps;
1501
1502                                 if (parm != 0)
1503                                 {
1504                                         timer_mode = parm;
1505         
1506                                         if (timer_mode & TMR_MODE_CLS)
1507                                                 mpu_cmd(midi_dev, 0x3c, 0);             /* Use CLS sync */
1508                                         else if (timer_mode & TMR_MODE_SMPTE)
1509                                                 mpu_cmd(midi_dev, 0x3d, 0);             /* Use SMPTE sync */
1510                                 }
1511                                 if (put_user(timer_mode, p))
1512                                         return -EFAULT;
1513                                 return timer_mode;
1514                         }
1515                         break;
1516
1517                 case SNDCTL_TMR_START:
1518                         mpu_start_timer(midi_dev);
1519                         return 0;
1520
1521                 case SNDCTL_TMR_STOP:
1522                         tmr_running = 0;
1523                         mpu_cmd(midi_dev, 0x01, 0);     /* Send MIDI stop */
1524                         stop_metronome(midi_dev);
1525                         return 0;
1526
1527                 case SNDCTL_TMR_CONTINUE:
1528                         if (tmr_running)
1529                                 return 0;
1530                         tmr_running = 1;
1531                         mpu_cmd(midi_dev, 0x03, 0);     /* Send MIDI continue */
1532                         return 0;
1533
1534                 case SNDCTL_TMR_TIMEBASE:
1535                         {
1536                                 int val;
1537                                 if (get_user(val, p))
1538                                         return -EFAULT;
1539                                 if (val)
1540                                         set_timebase(midi_dev, val);
1541                                 if (put_user(curr_timebase, p))
1542                                         return -EFAULT;
1543                                 return curr_timebase;
1544                         }
1545                         break;
1546
1547                 case SNDCTL_TMR_TEMPO:
1548                         {
1549                                 int val;
1550                                 int ret;
1551
1552                                 if (get_user(val, p))
1553                                         return -EFAULT;
1554
1555                                 if (val)
1556                                 {
1557                                         if (val < 8)
1558                                                 val = 8;
1559                                         if (val > 250)
1560                                                 val = 250;
1561                                         if ((ret = mpu_cmd(midi_dev, 0xE0, val)) < 0)
1562                                         {
1563                                                 printk(KERN_WARNING "mpu401: Can't set tempo to %d\n", (int) val);
1564                                                 return ret;
1565                                         }
1566                                         curr_tempo = val;
1567                                 }
1568                                 if (put_user(curr_tempo, p))
1569                                         return -EFAULT;
1570                                 return curr_tempo;
1571                         }
1572                         break;
1573
1574                 case SNDCTL_SEQ_CTRLRATE:
1575                         {
1576                                 int val;
1577                                 if (get_user(val, p))
1578                                         return -EFAULT;
1579
1580                                 if (val != 0)           /* Can't change */
1581                                         return -EINVAL;
1582                                 val = ((curr_tempo * curr_timebase) + 30)/60;
1583                                 if (put_user(val, p))
1584                                         return -EFAULT;
1585                                 return val;
1586                         }
1587                         break;
1588
1589                 case SNDCTL_SEQ_GETTIME:
1590                         if (put_user(curr_ticks, p))
1591                                 return -EFAULT;
1592                         return curr_ticks;
1593
1594                 case SNDCTL_TMR_METRONOME:
1595                         if (get_user(metronome_mode, p))
1596                                 return -EFAULT;
1597                         setup_metronome(midi_dev);
1598                         return 0;
1599
1600                 default:;
1601         }
1602         return -EINVAL;
1603 }
1604
1605 static void mpu_timer_arm(int dev, long time)
1606 {
1607         if (time < 0)
1608                 time = curr_ticks + 1;
1609         else if (time <= curr_ticks)    /* It's the time */
1610                 return;
1611         next_event_time = prev_event_time = time;
1612         return;
1613 }
1614
1615 static struct sound_timer_operations mpu_timer =
1616 {
1617         .owner          = THIS_MODULE,
1618         .info           = {"MPU-401 Timer", 0},
1619         .priority       = 10,   /* Priority */
1620         .devlink        = 0,    /* Local device link */
1621         .open           = mpu_timer_open,
1622         .close          = mpu_timer_close,
1623         .event          = mpu_timer_event,
1624         .get_time       = mpu_timer_get_time,
1625         .ioctl          = mpu_timer_ioctl,
1626         .arm_timer      = mpu_timer_arm
1627 };
1628
1629 static void mpu_timer_interrupt(void)
1630 {
1631         if (!timer_open)
1632                 return;
1633
1634         if (!tmr_running)
1635                 return;
1636
1637         curr_clocks++;
1638         curr_ticks = clocks2ticks(curr_clocks);
1639
1640         if (curr_ticks >= next_event_time)
1641         {
1642                 next_event_time = (unsigned long) -1;
1643                 sequencer_timer(0);
1644         }
1645 }
1646
1647 static void timer_ext_event(struct mpu_config *devc, int event, int parm)
1648 {
1649         int midi_dev = devc->devno;
1650
1651         if (!devc->timer_flag)
1652                 return;
1653
1654         switch (event)
1655         {
1656                 case TMR_CLOCK:
1657                         printk("<MIDI clk>");
1658                         break;
1659
1660                 case TMR_START:
1661                         printk("Ext MIDI start\n");
1662                         if (!tmr_running)
1663                         {
1664                                 if (timer_mode & TMR_EXTERNAL)
1665                                 {
1666                                         tmr_running = 1;
1667                                         setup_metronome(midi_dev);
1668                                         next_event_time = 0;
1669                                         STORE(SEQ_START_TIMER());
1670                                 }
1671                         }
1672                         break;
1673
1674                 case TMR_STOP:
1675                         printk("Ext MIDI stop\n");
1676                         if (timer_mode & TMR_EXTERNAL)
1677                         {
1678                                 tmr_running = 0;
1679                                 stop_metronome(midi_dev);
1680                                 STORE(SEQ_STOP_TIMER());
1681                         }
1682                         break;
1683
1684                 case TMR_CONTINUE:
1685                         printk("Ext MIDI continue\n");
1686                         if (timer_mode & TMR_EXTERNAL)
1687                         {
1688                                 tmr_running = 1;
1689                                 setup_metronome(midi_dev);
1690                                 STORE(SEQ_CONTINUE_TIMER());
1691                         }
1692                         break;
1693
1694                 case TMR_SPP:
1695                         printk("Songpos: %d\n", parm);
1696                         if (timer_mode & TMR_EXTERNAL)
1697                         {
1698                                 STORE(SEQ_SONGPOS(parm));
1699                         }
1700                         break;
1701         }
1702 }
1703
1704 static int mpu_timer_init(int midi_dev)
1705 {
1706         struct mpu_config *devc;
1707         int n;
1708
1709         devc = &dev_conf[midi_dev];
1710
1711         if (timer_initialized)
1712                 return -1;      /* There is already a similar timer */
1713
1714         timer_initialized = 1;
1715
1716         mpu_timer.devlink = midi_dev;
1717         dev_conf[midi_dev].timer_flag = 1;
1718
1719         n = sound_alloc_timerdev();
1720         if (n == -1)
1721                 n = 0;
1722         sound_timer_devs[n] = &mpu_timer;
1723
1724         if (devc->version < 0x20)       /* Original MPU-401 */
1725                 timer_caps = TMR_INTERNAL | TMR_EXTERNAL | TMR_MODE_FSK | TMR_MODE_MIDI;
1726         else
1727         {
1728                 /*
1729                  * The version number 2.0 is used (at least) by the
1730                  * MusicQuest cards and the Roland Super-MPU.
1731                  *
1732                  * MusicQuest has given a special meaning to the bits of the
1733                  * revision number. The Super-MPU returns 0.
1734                  */
1735
1736                 if (devc->revision)
1737                         timer_caps |= TMR_EXTERNAL | TMR_MODE_MIDI;
1738
1739                 if (devc->revision & 0x02)
1740                         timer_caps |= TMR_MODE_CLS;
1741
1742
1743                 if (devc->revision & 0x40)
1744                         max_timebase = 10;      /* Has the 216 and 240 ppqn modes */
1745         }
1746
1747         timer_mode = (TMR_INTERNAL | TMR_MODE_MIDI) & timer_caps;
1748         return n;
1749
1750 }
1751
1752 EXPORT_SYMBOL(probe_mpu401);
1753 EXPORT_SYMBOL(attach_mpu401);
1754 EXPORT_SYMBOL(unload_mpu401);
1755
1756 static struct address_info cfg;
1757
1758 static int io = -1;
1759 static int irq = -1;
1760
1761 module_param(irq, int, 0);
1762 module_param(io, int, 0);
1763
1764 static int __init init_mpu401(void)
1765 {
1766         int ret;
1767         /* Can be loaded either for module use or to provide functions
1768            to others */
1769         if (io != -1 && irq != -1) {
1770                 struct resource *ports;
1771                 cfg.irq = irq;
1772                 cfg.io_base = io;
1773                 ports = request_region(io, 2, "mpu401");
1774                 if (!ports)
1775                         return -EBUSY;
1776                 if (probe_mpu401(&cfg, ports) == 0) {
1777                         release_region(io, 2);
1778                         return -ENODEV;
1779                 }
1780                 if ((ret = attach_mpu401(&cfg, THIS_MODULE)))
1781                         return ret;
1782         }
1783         
1784         return 0;
1785 }
1786
1787 static void __exit cleanup_mpu401(void)
1788 {
1789         if (io != -1 && irq != -1) {
1790                 /* Check for use by, for example, sscape driver */
1791                 unload_mpu401(&cfg);
1792         }
1793 }
1794
1795 module_init(init_mpu401);
1796 module_exit(cleanup_mpu401);
1797
1798 #ifndef MODULE
1799 static int __init setup_mpu401(char *str)
1800 {
1801         /* io, irq */
1802         int ints[3];
1803         
1804         str = get_options(str, ARRAY_SIZE(ints), ints);
1805         
1806         io = ints[1];
1807         irq = ints[2];
1808
1809         return 1;
1810 }
1811
1812 __setup("mpu401=", setup_mpu401);
1813 #endif
1814 MODULE_LICENSE("GPL");