vserver 1.9.5.x5
[linux-2.6.git] / sound / drivers / serial-u16550.c
1 /*
2  *   serial.c
3  *   Copyright (c) by Jaroslav Kysela <perex@suse.cz>,
4  *                    Isaku Yamahata <yamahata@private.email.ne.jp>,
5  *                    George Hansper <ghansper@apana.org.au>,
6  *                    Hannu Savolainen
7  *
8  *   This code is based on the code from ALSA 0.5.9, but heavily rewritten.
9  *
10  *   This program is free software; you can redistribute it and/or modify
11  *   it under the terms of the GNU General Public License as published by
12  *   the Free Software Foundation; either version 2 of the License, or
13  *   (at your option) any later version.
14  *
15  *   This program is distributed in the hope that it will be useful,
16  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *   GNU General Public License for more details.
19  *
20  *   You should have received a copy of the GNU General Public License
21  *   along with this program; if not, write to the Free Software
22  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
23  *
24  * Sat Mar 31 17:27:57 PST 2001 tim.mann@compaq.com 
25  *      Added support for the Midiator MS-124T and for the MS-124W in
26  *      Single Addressed (S/A) or Multiple Burst (M/B) mode, with
27  *      power derived either parasitically from the serial port or
28  *      from a separate power supply.
29  *
30  *      More documentation can be found in serial-u16550.txt.
31  */
32
33 #include <sound/driver.h>
34 #include <linux/init.h>
35 #include <linux/interrupt.h>
36 #include <linux/slab.h>
37 #include <linux/ioport.h>
38 #include <linux/moduleparam.h>
39 #include <sound/core.h>
40 #include <sound/rawmidi.h>
41 #include <sound/initval.h>
42
43 #include <linux/serial_reg.h>
44
45 #include <asm/io.h>
46
47 MODULE_DESCRIPTION("MIDI serial u16550");
48 MODULE_LICENSE("GPL");
49 MODULE_SUPPORTED_DEVICE("{{ALSA, MIDI serial u16550}}");
50
51 #define SNDRV_SERIAL_SOUNDCANVAS 0 /* Roland Soundcanvas; F5 NN selects part */
52 #define SNDRV_SERIAL_MS124T 1      /* Midiator MS-124T */
53 #define SNDRV_SERIAL_MS124W_SA 2   /* Midiator MS-124W in S/A mode */
54 #define SNDRV_SERIAL_MS124W_MB 3   /* Midiator MS-124W in M/B mode */
55 #define SNDRV_SERIAL_GENERIC 4     /* Generic Interface */
56 #define SNDRV_SERIAL_MAX_ADAPTOR SNDRV_SERIAL_GENERIC
57 static char *adaptor_names[] = {
58         "Soundcanvas",
59         "MS-124T",
60         "MS-124W S/A",
61         "MS-124W M/B",
62         "Generic"
63 };
64
65 #define SNDRV_SERIAL_NORMALBUFF 0 /* Normal blocking buffer operation */
66 #define SNDRV_SERIAL_DROPBUFF   1 /* Non-blocking discard operation */
67
68 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;      /* Index 0-MAX */
69 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;       /* ID for this card */
70 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */
71 static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x3f8,0x2f8,0x3e8,0x2e8 */
72 static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ;        /* 3,4,5,7,9,10,11,14,15 */
73 static int speed[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 38400}; /* 9600,19200,38400,57600,115200 */
74 static int base[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 115200}; /* baud base */
75 static int outs[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};  /* 1 to 16 */
76 static int ins[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};  /* 1 to 16 */
77 static int adaptor[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = SNDRV_SERIAL_SOUNDCANVAS};
78 static int droponfull[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS -1)] = SNDRV_SERIAL_NORMALBUFF };
79
80 module_param_array(index, int, NULL, 0444);
81 MODULE_PARM_DESC(index, "Index value for Serial MIDI.");
82 module_param_array(id, charp, NULL, 0444);
83 MODULE_PARM_DESC(id, "ID string for Serial MIDI.");
84 module_param_array(enable, bool, NULL, 0444);
85 MODULE_PARM_DESC(enable, "Enable UART16550A chip.");
86 module_param_array(port, long, NULL, 0444);
87 MODULE_PARM_DESC(port, "Port # for UART16550A chip.");
88 module_param_array(irq, int, NULL, 0444);
89 MODULE_PARM_DESC(irq, "IRQ # for UART16550A chip.");
90 module_param_array(speed, int, NULL, 0444);
91 MODULE_PARM_DESC(speed, "Speed in bauds.");
92 module_param_array(base, int, NULL, 0444);
93 MODULE_PARM_DESC(base, "Base for divisor in bauds.");
94 module_param_array(outs, int, NULL, 0444);
95 MODULE_PARM_DESC(outs, "Number of MIDI outputs.");
96 module_param_array(ins, int, NULL, 0444);
97 MODULE_PARM_DESC(ins, "Number of MIDI inputs.");
98 module_param_array(droponfull, bool, NULL, 0444);
99 MODULE_PARM_DESC(droponfull, "Flag to enable drop-on-full buffer mode");
100
101 module_param_array(adaptor, int, NULL, 0444);
102 MODULE_PARM_DESC(adaptor, "Type of adaptor.");
103
104 /*#define SNDRV_SERIAL_MS124W_MB_NOCOMBO 1*/  /* Address outs as 0-3 instead of bitmap */
105
106 #define SNDRV_SERIAL_MAX_OUTS   16              /* max 64, min 16 */
107 #define SNDRV_SERIAL_MAX_INS    16              /* max 64, min 16 */
108
109 #define TX_BUFF_SIZE            (1<<15)         /* Must be 2^n */
110 #define TX_BUFF_MASK            (TX_BUFF_SIZE - 1)
111
112 #define SERIAL_MODE_NOT_OPENED          (0)
113 #define SERIAL_MODE_INPUT_OPEN          (1 << 0)
114 #define SERIAL_MODE_OUTPUT_OPEN         (1 << 1)
115 #define SERIAL_MODE_INPUT_TRIGGERED     (1 << 2)
116 #define SERIAL_MODE_OUTPUT_TRIGGERED    (1 << 3)
117
118 typedef struct _snd_uart16550 {
119         snd_card_t *card;
120         snd_rawmidi_t *rmidi;
121         snd_rawmidi_substream_t *midi_output[SNDRV_SERIAL_MAX_OUTS];
122         snd_rawmidi_substream_t *midi_input[SNDRV_SERIAL_MAX_INS];
123
124         int filemode;           //open status of file
125
126         spinlock_t open_lock;
127
128         int irq;
129
130         unsigned long base;
131         struct resource *res_base;
132
133         unsigned int speed;
134         unsigned int speed_base;
135         unsigned char divisor;
136
137         unsigned char old_divisor_lsb;
138         unsigned char old_divisor_msb;
139         unsigned char old_line_ctrl_reg;
140
141         // parameter for using of write loop
142         short int fifo_limit;   //used in uart16550
143         short int fifo_count;   //used in uart16550
144
145         // type of adaptor
146         int adaptor;
147
148         // inputs
149         int prev_in;
150         unsigned char rstatus;
151
152         // outputs
153         int prev_out;
154         unsigned char prev_status[SNDRV_SERIAL_MAX_OUTS];
155
156         // write buffer and its writing/reading position
157         unsigned char tx_buff[TX_BUFF_SIZE];
158         int buff_in_count;
159         int buff_in;
160         int buff_out;
161         int drop_on_full;
162
163         // wait timer
164         unsigned int timer_running:1;
165         struct timer_list buffer_timer;
166
167 } snd_uart16550_t;
168
169 static snd_card_t *snd_serial_cards[SNDRV_CARDS] = SNDRV_DEFAULT_PTR;
170
171 inline static void snd_uart16550_add_timer(snd_uart16550_t *uart)
172 {
173         if (! uart->timer_running) {
174                 /* timer 38600bps * 10bit * 16byte */
175                 uart->buffer_timer.expires = jiffies + (HZ+255)/256;
176                 uart->timer_running = 1;
177                 add_timer(&uart->buffer_timer);
178         }
179 }
180
181 inline static void snd_uart16550_del_timer(snd_uart16550_t *uart)
182 {
183         if (uart->timer_running) {
184                 del_timer(&uart->buffer_timer);
185                 uart->timer_running = 0;
186         }
187 }
188
189 /* This macro is only used in snd_uart16550_io_loop */
190 inline static void snd_uart16550_buffer_output(snd_uart16550_t *uart)
191 {
192         unsigned short buff_out = uart->buff_out;
193         if( uart->buff_in_count > 0 ) {
194                 outb(uart->tx_buff[buff_out], uart->base + UART_TX);
195                 uart->fifo_count++;
196                 buff_out++;
197                 buff_out &= TX_BUFF_MASK;
198                 uart->buff_out = buff_out;
199                 uart->buff_in_count--;
200         }
201 }
202
203 /* This loop should be called with interrupts disabled
204  * We don't want to interrupt this, 
205  * as we're already handling an interrupt 
206  */
207 static void snd_uart16550_io_loop(snd_uart16550_t * uart)
208 {
209         unsigned char c, status;
210         int substream;
211
212         /* recall previous stream */
213         substream = uart->prev_in;
214
215         /* Read Loop */
216         while ((status = inb(uart->base + UART_LSR)) & UART_LSR_DR) {
217                 /* while receive data ready */
218                 c = inb(uart->base + UART_RX);
219
220                 /* keep track of last status byte */
221                 if (c & 0x80) {
222                         uart->rstatus = c;
223                 }
224
225                 /* handle stream switch */
226                 if (uart->adaptor == SNDRV_SERIAL_GENERIC) {
227                         if (uart->rstatus == 0xf5) {
228                                 if (c <= SNDRV_SERIAL_MAX_INS && c > 0)
229                                         substream = c - 1;
230                                 if (c != 0xf5)
231                                         uart->rstatus = 0; /* prevent future bytes from being interpreted as streams */
232                         }
233                         else if ((uart->filemode & SERIAL_MODE_INPUT_OPEN) && (uart->midi_input[substream] != NULL)) {
234                                 snd_rawmidi_receive(uart->midi_input[substream], &c, 1);
235                 }
236                 } else if ((uart->filemode & SERIAL_MODE_INPUT_OPEN) && (uart->midi_input[substream] != NULL)) {
237                         snd_rawmidi_receive(uart->midi_input[substream], &c, 1);
238                 }
239
240                 if (status & UART_LSR_OE)
241                         snd_printk("%s: Overrun on device at 0x%lx\n",
242                                uart->rmidi->name, uart->base);
243         }
244
245         /* remember the last stream */
246         uart->prev_in = substream;
247
248         /* no need of check SERIAL_MODE_OUTPUT_OPEN because if not,
249            buffer is never filled. */
250         /* Check write status */
251         if (status & UART_LSR_THRE) {
252                 uart->fifo_count = 0;
253         }
254         if (uart->adaptor == SNDRV_SERIAL_MS124W_SA
255            || uart->adaptor == SNDRV_SERIAL_GENERIC) {
256                 /* Can't use FIFO, must send only when CTS is true */
257                 status = inb(uart->base + UART_MSR);
258                 while( (uart->fifo_count == 0) && (status & UART_MSR_CTS) &&
259                       (uart->buff_in_count > 0) ) {
260                        snd_uart16550_buffer_output(uart);
261                        status = inb( uart->base + UART_MSR );
262                 }
263         } else {
264                 /* Write loop */
265                 while (uart->fifo_count < uart->fifo_limit      /* Can we write ? */
266                        && uart->buff_in_count > 0)      /* Do we want to? */
267                         snd_uart16550_buffer_output(uart);
268         }
269         if (uart->irq < 0 && uart->buff_in_count > 0)
270                 snd_uart16550_add_timer(uart);
271 }
272
273 /* NOTES ON SERVICING INTERUPTS
274  * ---------------------------
275  * After receiving a interrupt, it is important to indicate to the UART that
276  * this has been done. 
277  * For a Rx interrupt, this is done by reading the received byte.
278  * For a Tx interrupt this is done by either:
279  * a) Writing a byte
280  * b) Reading the IIR
281  * It is particularly important to read the IIR if a Tx interrupt is received
282  * when there is no data in tx_buff[], as in this case there no other
283  * indication that the interrupt has been serviced, and it remains outstanding
284  * indefinitely. This has the curious side effect that and no further interrupts
285  * will be generated from this device AT ALL!!.
286  * It is also desirable to clear outstanding interrupts when the device is
287  * opened/closed.
288  *
289  *
290  * Note that some devices need OUT2 to be set before they will generate
291  * interrupts at all. (Possibly tied to an internal pull-up on CTS?)
292  */
293 static irqreturn_t snd_uart16550_interrupt(int irq, void *dev_id, struct pt_regs *regs)
294 {
295         snd_uart16550_t *uart;
296
297         uart = (snd_uart16550_t *) dev_id;
298         spin_lock(&uart->open_lock);
299         if (uart->filemode == SERIAL_MODE_NOT_OPENED) {
300                 spin_unlock(&uart->open_lock);
301                 return IRQ_NONE;
302         }
303         inb(uart->base + UART_IIR);             /* indicate to the UART that the interrupt has been serviced */
304         snd_uart16550_io_loop(uart);
305         spin_unlock(&uart->open_lock);
306         return IRQ_HANDLED;
307 }
308
309 /* When the polling mode, this function calls snd_uart16550_io_loop. */
310 static void snd_uart16550_buffer_timer(unsigned long data)
311 {
312         snd_uart16550_t *uart;
313
314         uart = (snd_uart16550_t *)data;
315         spin_lock(&uart->open_lock);
316         snd_uart16550_del_timer(uart);
317         snd_uart16550_io_loop(uart);
318         spin_unlock(&uart->open_lock);
319 }
320
321 /*
322  *  this method probes, if an uart sits on given port
323  *  return 0 if found
324  *  return negative error if not found
325  */
326 static int __init snd_uart16550_detect(snd_uart16550_t *uart)
327 {
328         unsigned long io_base = uart->base;
329         int ok;
330         unsigned char c;
331
332         /* Do some vague tests for the presence of the uart */
333         if (io_base == 0 || io_base == SNDRV_AUTO_PORT) {
334                 return -ENODEV; /* Not configured */
335         }
336
337         uart->res_base = request_region(io_base, 8, "Serial MIDI");
338         if (uart->res_base == NULL) {
339                 snd_printk(KERN_ERR "u16550: can't grab port 0x%lx\n", io_base);
340                 return -EBUSY;
341         }
342
343         ok = 1;                 /* uart detected unless one of the following tests should fail */
344         /* 8 data-bits, 1 stop-bit, parity off, DLAB = 0 */
345         outb(UART_LCR_WLEN8, io_base + UART_LCR); /* Line Control Register */
346         c = inb(io_base + UART_IER);
347         /* The top four bits of the IER should always == 0 */
348         if ((c & 0xf0) != 0)
349                 ok = 0;         /* failed */
350
351         outb(0xaa, io_base + UART_SCR);
352         /* Write arbitrary data into the scratch reg */
353         c = inb(io_base + UART_SCR);
354         /* If it comes back, it's OK */
355         if (c != 0xaa)
356                 ok = 0;         /* failed */
357
358         outb(0x55, io_base + UART_SCR);
359         /* Write arbitrary data into the scratch reg */
360         c = inb(io_base + UART_SCR);
361         /* If it comes back, it's OK */
362         if (c != 0x55)
363                 ok = 0;         /* failed */
364
365         return ok;
366 }
367
368 static void snd_uart16550_do_open(snd_uart16550_t * uart)
369 {
370         char byte;
371
372         /* Initialize basic variables */
373         uart->buff_in_count = 0;
374         uart->buff_in = 0;
375         uart->buff_out = 0;
376         uart->fifo_limit = 1;
377         uart->fifo_count = 0;
378         uart->timer_running = 0;
379
380         outb(UART_FCR_ENABLE_FIFO       /* Enable FIFO's (if available) */
381              | UART_FCR_CLEAR_RCVR      /* Clear receiver FIFO */
382              | UART_FCR_CLEAR_XMIT      /* Clear transmitter FIFO */
383              | UART_FCR_TRIGGER_4       /* Set FIFO trigger at 4-bytes */
384         /* NOTE: interrupt generated after T=(time)4-bytes
385          * if less than UART_FCR_TRIGGER bytes received
386          */
387              ,uart->base + UART_FCR);   /* FIFO Control Register */
388
389         if ((inb(uart->base + UART_IIR) & 0xf0) == 0xc0)
390                 uart->fifo_limit = 16;
391         if (uart->divisor != 0) {
392                 uart->old_line_ctrl_reg = inb(uart->base + UART_LCR);
393                 outb(UART_LCR_DLAB      /* Divisor latch access bit */
394                      ,uart->base + UART_LCR);   /* Line Control Register */
395                 uart->old_divisor_lsb = inb(uart->base + UART_DLL);
396                 uart->old_divisor_msb = inb(uart->base + UART_DLM);
397
398                 outb(uart->divisor
399                      ,uart->base + UART_DLL);   /* Divisor Latch Low */
400                 outb(0
401                      ,uart->base + UART_DLM);   /* Divisor Latch High */
402                 /* DLAB is reset to 0 in next outb() */
403         }
404         /* Set serial parameters (parity off, etc) */
405         outb(UART_LCR_WLEN8     /* 8 data-bits */
406              | 0                /* 1 stop-bit */
407              | 0                /* parity off */
408              | 0                /* DLAB = 0 */
409              ,uart->base + UART_LCR);   /* Line Control Register */
410
411         switch (uart->adaptor) {
412         default:
413                 outb(UART_MCR_RTS       /* Set Request-To-Send line active */
414                      | UART_MCR_DTR     /* Set Data-Terminal-Ready line active */
415                      | UART_MCR_OUT2    /* Set OUT2 - not always required, but when
416                                          * it is, it is ESSENTIAL for enabling interrupts
417                                  */
418                      ,uart->base + UART_MCR);   /* Modem Control Register */
419                 break;
420         case SNDRV_SERIAL_MS124W_SA:
421         case SNDRV_SERIAL_MS124W_MB:
422                 /* MS-124W can draw power from RTS and DTR if they
423                    are in opposite states. */ 
424                 outb(UART_MCR_RTS | (0&UART_MCR_DTR) | UART_MCR_OUT2,
425                      uart->base + UART_MCR);
426                 break;
427         case SNDRV_SERIAL_MS124T:
428                 /* MS-124T can draw power from RTS and/or DTR (preferably
429                    both) if they are both asserted. */
430                 outb(UART_MCR_RTS | UART_MCR_DTR | UART_MCR_OUT2,
431                      uart->base + UART_MCR);
432                 break;
433         }
434
435         if (uart->irq < 0) {
436                 byte = (0 & UART_IER_RDI)       /* Disable Receiver data interrupt */
437                     |(0 & UART_IER_THRI)        /* Disable Transmitter holding register empty interrupt */
438                     ;
439         } else if (uart->adaptor == SNDRV_SERIAL_MS124W_SA) {
440                 byte = UART_IER_RDI     /* Enable Receiver data interrupt */
441                     | UART_IER_MSI      /* Enable Modem status interrupt */
442                     ;
443         } else if (uart->adaptor == SNDRV_SERIAL_GENERIC) {
444                 byte = UART_IER_RDI     /* Enable Receiver data interrupt */
445                     | UART_IER_MSI      /* Enable Modem status interrupt */
446                     | UART_IER_THRI     /* Enable Transmitter holding register empty interrupt */
447                     ;
448         } else {
449                 byte = UART_IER_RDI     /* Enable Receiver data interrupt */
450                     | UART_IER_THRI     /* Enable Transmitter holding register empty interrupt */
451                     ;
452         }
453         outb(byte, uart->base + UART_IER);      /* Interupt enable Register */
454
455         inb(uart->base + UART_LSR);     /* Clear any pre-existing overrun indication */
456         inb(uart->base + UART_IIR);     /* Clear any pre-existing transmit interrupt */
457         inb(uart->base + UART_RX);      /* Clear any pre-existing receive interrupt */
458 }
459
460 static void snd_uart16550_do_close(snd_uart16550_t * uart)
461 {
462         if (uart->irq < 0)
463                 snd_uart16550_del_timer(uart);
464
465         /* NOTE: may need to disable interrupts before de-registering out handler.
466          * For now, the consequences are harmless.
467          */
468
469         outb((0 & UART_IER_RDI)         /* Disable Receiver data interrupt */
470              |(0 & UART_IER_THRI)       /* Disable Transmitter holding register empty interrupt */
471              ,uart->base + UART_IER);   /* Interupt enable Register */
472
473         switch (uart->adaptor) {
474         default:
475                 outb((0 & UART_MCR_RTS)         /* Deactivate Request-To-Send line  */
476                      |(0 & UART_MCR_DTR)        /* Deactivate Data-Terminal-Ready line */
477                      |(0 & UART_MCR_OUT2)       /* Deactivate OUT2 */
478                      ,uart->base + UART_MCR);   /* Modem Control Register */
479           break;
480         case SNDRV_SERIAL_MS124W_SA:
481         case SNDRV_SERIAL_MS124W_MB:
482                 /* MS-124W can draw power from RTS and DTR if they
483                    are in opposite states; leave it powered. */ 
484                 outb(UART_MCR_RTS | (0&UART_MCR_DTR) | (0&UART_MCR_OUT2),
485                      uart->base + UART_MCR);
486                 break;
487         case SNDRV_SERIAL_MS124T:
488                 /* MS-124T can draw power from RTS and/or DTR (preferably
489                    both) if they are both asserted; leave it powered. */
490                 outb(UART_MCR_RTS | UART_MCR_DTR | (0&UART_MCR_OUT2),
491                      uart->base + UART_MCR);
492                 break;
493         }
494
495         inb(uart->base + UART_IIR);     /* Clear any outstanding interrupts */
496
497         /* Restore old divisor */
498         if (uart->divisor != 0) {
499                 outb(UART_LCR_DLAB              /* Divisor latch access bit */
500                      ,uart->base + UART_LCR);   /* Line Control Register */
501                 outb(uart->old_divisor_lsb
502                      ,uart->base + UART_DLL);   /* Divisor Latch Low */
503                 outb(uart->old_divisor_msb
504                      ,uart->base + UART_DLM);   /* Divisor Latch High */
505                 /* Restore old LCR (data bits, stop bits, parity, DLAB) */
506                 outb(uart->old_line_ctrl_reg
507                      ,uart->base + UART_LCR);   /* Line Control Register */
508         }
509 }
510
511 static int snd_uart16550_input_open(snd_rawmidi_substream_t * substream)
512 {
513         unsigned long flags;
514         snd_uart16550_t *uart = substream->rmidi->private_data;
515
516         spin_lock_irqsave(&uart->open_lock, flags);
517         if (uart->filemode == SERIAL_MODE_NOT_OPENED)
518                 snd_uart16550_do_open(uart);
519         uart->filemode |= SERIAL_MODE_INPUT_OPEN;
520         uart->midi_input[substream->number] = substream;
521         spin_unlock_irqrestore(&uart->open_lock, flags);
522         return 0;
523 }
524
525 static int snd_uart16550_input_close(snd_rawmidi_substream_t * substream)
526 {
527         unsigned long flags;
528         snd_uart16550_t *uart = substream->rmidi->private_data;
529
530         spin_lock_irqsave(&uart->open_lock, flags);
531         uart->filemode &= ~SERIAL_MODE_INPUT_OPEN;
532         uart->midi_input[substream->number] = NULL;
533         if (uart->filemode == SERIAL_MODE_NOT_OPENED)
534                 snd_uart16550_do_close(uart);
535         spin_unlock_irqrestore(&uart->open_lock, flags);
536         return 0;
537 }
538
539 static void snd_uart16550_input_trigger(snd_rawmidi_substream_t * substream, int up)
540 {
541         unsigned long flags;
542         snd_uart16550_t *uart = substream->rmidi->private_data;
543
544         spin_lock_irqsave(&uart->open_lock, flags);
545         if (up) {
546                 uart->filemode |= SERIAL_MODE_INPUT_TRIGGERED;
547         } else {
548                 uart->filemode &= ~SERIAL_MODE_INPUT_TRIGGERED;
549         }
550         spin_unlock_irqrestore(&uart->open_lock, flags);
551 }
552
553 static int snd_uart16550_output_open(snd_rawmidi_substream_t * substream)
554 {
555         unsigned long flags;
556         snd_uart16550_t *uart = substream->rmidi->private_data;
557
558         spin_lock_irqsave(&uart->open_lock, flags);
559         if (uart->filemode == SERIAL_MODE_NOT_OPENED)
560                 snd_uart16550_do_open(uart);
561         uart->filemode |= SERIAL_MODE_OUTPUT_OPEN;
562         uart->midi_output[substream->number] = substream;
563         spin_unlock_irqrestore(&uart->open_lock, flags);
564         return 0;
565 };
566
567 static int snd_uart16550_output_close(snd_rawmidi_substream_t * substream)
568 {
569         unsigned long flags;
570         snd_uart16550_t *uart = substream->rmidi->private_data;
571
572         spin_lock_irqsave(&uart->open_lock, flags);
573         uart->filemode &= ~SERIAL_MODE_OUTPUT_OPEN;
574         uart->midi_output[substream->number] = NULL;
575         if (uart->filemode == SERIAL_MODE_NOT_OPENED)
576                 snd_uart16550_do_close(uart);
577         spin_unlock_irqrestore(&uart->open_lock, flags);
578         return 0;
579 };
580
581 inline static int snd_uart16550_buffer_can_write( snd_uart16550_t *uart, int Num )
582 {
583         if( uart->buff_in_count + Num < TX_BUFF_SIZE )
584                 return 1;
585         else
586                 return 0;
587 }
588
589 inline static int snd_uart16550_write_buffer(snd_uart16550_t *uart, unsigned char byte)
590 {
591         unsigned short buff_in = uart->buff_in;
592         if( uart->buff_in_count < TX_BUFF_SIZE ) {
593                 uart->tx_buff[buff_in] = byte;
594                 buff_in++;
595                 buff_in &= TX_BUFF_MASK;
596                 uart->buff_in = buff_in;
597                 uart->buff_in_count++;
598                 if (uart->irq < 0) /* polling mode */
599                         snd_uart16550_add_timer(uart);
600                 return 1;
601         } else
602                 return 0;
603 }
604
605 static int snd_uart16550_output_byte(snd_uart16550_t *uart, snd_rawmidi_substream_t * substream, unsigned char midi_byte)
606 {
607         if (uart->buff_in_count == 0                            /* Buffer empty? */
608             && ((uart->adaptor != SNDRV_SERIAL_MS124W_SA &&
609             uart->adaptor != SNDRV_SERIAL_GENERIC) ||
610                 (uart->fifo_count == 0                               /* FIFO empty? */
611                  && (inb(uart->base + UART_MSR) & UART_MSR_CTS)))) { /* CTS? */
612
613                 /* Tx Buffer Empty - try to write immediately */
614                 if ((inb(uart->base + UART_LSR) & UART_LSR_THRE) != 0) {
615                         /* Transmitter holding register (and Tx FIFO) empty */
616                         uart->fifo_count = 1;
617                         outb(midi_byte, uart->base + UART_TX);
618                 } else {
619                         if (uart->fifo_count < uart->fifo_limit) {
620                                 uart->fifo_count++;
621                                 outb(midi_byte, uart->base + UART_TX);
622                         } else {
623                                 /* Cannot write (buffer empty) - put char in buffer */
624                                 snd_uart16550_write_buffer(uart, midi_byte);
625                         }
626                 }
627         } else {
628                 if( !snd_uart16550_write_buffer(uart, midi_byte) ) {
629                         snd_printk("%s: Buffer overrun on device at 0x%lx\n",
630                                    uart->rmidi->name, uart->base);
631                         return 0;
632                 }
633         }
634
635         return 1;
636 }
637
638 static void snd_uart16550_output_write(snd_rawmidi_substream_t * substream)
639 {
640         unsigned long flags;
641         unsigned char midi_byte, addr_byte;
642         snd_uart16550_t *uart = substream->rmidi->private_data;
643         char first;
644         static unsigned long lasttime=0;
645         
646         /* Interupts are disabled during the updating of the tx_buff,
647          * since it is 'bad' to have two processes updating the same
648          * variables (ie buff_in & buff_out)
649          */
650
651         spin_lock_irqsave(&uart->open_lock, flags);
652
653         if (uart->irq < 0)      //polling
654                 snd_uart16550_io_loop(uart);
655
656         if (uart->adaptor == SNDRV_SERIAL_MS124W_MB) {
657                 while (1) {
658                         /* buffer full? */
659                         /* in this mode we need two bytes of space */
660                         if (uart->buff_in_count > TX_BUFF_SIZE - 2)
661                                 break;
662                         if (snd_rawmidi_transmit(substream, &midi_byte, 1) != 1)
663                                 break;
664 #ifdef SNDRV_SERIAL_MS124W_MB_NOCOMBO
665                         /* select exactly one of the four ports */
666                         addr_byte = (1 << (substream->number + 4)) | 0x08;
667 #else
668                         /* select any combination of the four ports */
669                         addr_byte = (substream->number << 4) | 0x08;
670                         /* ...except none */
671                         if (addr_byte == 0x08) addr_byte = 0xf8;
672 #endif
673                         snd_uart16550_output_byte(uart, substream, addr_byte);
674                         /* send midi byte */
675                         snd_uart16550_output_byte(uart, substream, midi_byte);
676                 }
677         } else {
678                 first = 0;
679                 while( 1 == snd_rawmidi_transmit_peek(substream, &midi_byte, 1) ) {
680                         /* Also send F5 after 3 seconds with no data to handle device disconnect */
681                         if (first == 0 && (uart->adaptor == SNDRV_SERIAL_SOUNDCANVAS ||
682                                 uart->adaptor == SNDRV_SERIAL_GENERIC) &&
683                            (uart->prev_out != substream->number || jiffies-lasttime > 3*HZ)) {
684
685                                 if( snd_uart16550_buffer_can_write( uart, 3 ) ) {
686                                         /* Roland Soundcanvas part selection */
687                                         /* If this substream of the data is different previous
688                                            substream in this uart, send the change part event */
689                                         uart->prev_out = substream->number;
690                                         /* change part */
691                                         snd_uart16550_output_byte(uart, substream, 0xf5);
692                                         /* data */
693                                         snd_uart16550_output_byte(uart, substream, uart->prev_out + 1);
694                                         /* If midi_byte is a data byte, send the previous status byte */
695                                         if ((midi_byte < 0x80) && (uart->adaptor == SNDRV_SERIAL_SOUNDCANVAS))
696                                                 snd_uart16550_output_byte(uart, substream, uart->prev_status[uart->prev_out]);
697                                 } else if( !uart->drop_on_full )
698                                         break;
699
700                         }
701
702                         /* send midi byte */
703                         if( !snd_uart16550_output_byte(uart, substream, midi_byte) && !uart->drop_on_full )
704                                 break;
705
706                         if (midi_byte >= 0x80 && midi_byte < 0xf0)
707                                 uart->prev_status[uart->prev_out] = midi_byte;
708                         first = 1;
709
710                         snd_rawmidi_transmit_ack( substream, 1 );
711                 }
712                 lasttime = jiffies;
713         }
714         spin_unlock_irqrestore(&uart->open_lock, flags);
715 }
716
717 static void snd_uart16550_output_trigger(snd_rawmidi_substream_t * substream, int up)
718 {
719         unsigned long flags;
720         snd_uart16550_t *uart = substream->rmidi->private_data;
721
722         spin_lock_irqsave(&uart->open_lock, flags);
723         if (up) {
724                 uart->filemode |= SERIAL_MODE_OUTPUT_TRIGGERED;
725         } else {
726                 uart->filemode &= ~SERIAL_MODE_OUTPUT_TRIGGERED;
727         }
728         spin_unlock_irqrestore(&uart->open_lock, flags);
729         if (up)
730                 snd_uart16550_output_write(substream);
731 }
732
733 static snd_rawmidi_ops_t snd_uart16550_output =
734 {
735         .open =         snd_uart16550_output_open,
736         .close =        snd_uart16550_output_close,
737         .trigger =      snd_uart16550_output_trigger,
738 };
739
740 static snd_rawmidi_ops_t snd_uart16550_input =
741 {
742         .open =         snd_uart16550_input_open,
743         .close =        snd_uart16550_input_close,
744         .trigger =      snd_uart16550_input_trigger,
745 };
746
747 static int snd_uart16550_free(snd_uart16550_t *uart)
748 {
749         if (uart->irq >= 0)
750                 free_irq(uart->irq, (void *)uart);
751         if (uart->res_base) {
752                 release_resource(uart->res_base);
753                 kfree_nocheck(uart->res_base);
754         }
755         kfree(uart);
756         return 0;
757 };
758
759 static int snd_uart16550_dev_free(snd_device_t *device)
760 {
761         snd_uart16550_t *uart = device->device_data;
762         return snd_uart16550_free(uart);
763 }
764
765 static int __init snd_uart16550_create(snd_card_t * card,
766                                        unsigned long iobase,
767                                        int irq,
768                                        unsigned int speed,
769                                        unsigned int base,
770                                        int adaptor,
771                                        int droponfull,
772                                        snd_uart16550_t **ruart)
773 {
774         static snd_device_ops_t ops = {
775                 .dev_free =     snd_uart16550_dev_free,
776         };
777         snd_uart16550_t *uart;
778         int err;
779
780
781         if ((uart = kcalloc(1, sizeof(*uart), GFP_KERNEL)) == NULL)
782                 return -ENOMEM;
783         uart->adaptor = adaptor;
784         uart->card = card;
785         spin_lock_init(&uart->open_lock);
786         uart->irq = -1;
787         uart->base = iobase;
788         uart->drop_on_full = droponfull;
789
790         if ((err = snd_uart16550_detect(uart)) <= 0) {
791                 printk(KERN_ERR "no UART detected at 0x%lx\n", iobase);
792                 return err;
793         }
794
795         if (irq >= 0 && irq != SNDRV_AUTO_IRQ) {
796                 if (request_irq(irq, snd_uart16550_interrupt,
797                                 SA_INTERRUPT, "Serial MIDI", (void *) uart)) {
798                         snd_printk("irq %d busy. Using Polling.\n", irq);
799                 } else {
800                         uart->irq = irq;
801                 }
802         }
803         uart->divisor = base / speed;
804         uart->speed = base / (unsigned int)uart->divisor;
805         uart->speed_base = base;
806         uart->prev_out = -1;
807         uart->prev_in = 0;
808         uart->rstatus = 0;
809         memset(uart->prev_status, 0x80, sizeof(unsigned char) * SNDRV_SERIAL_MAX_OUTS);
810         init_timer(&uart->buffer_timer);
811         uart->buffer_timer.function = snd_uart16550_buffer_timer;
812         uart->buffer_timer.data = (unsigned long)uart;
813         uart->timer_running = 0;
814
815         /* Register device */
816         if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, uart, &ops)) < 0) {
817                 snd_uart16550_free(uart);
818                 return err;
819         }
820
821         switch (uart->adaptor) {
822         case SNDRV_SERIAL_MS124W_SA:
823         case SNDRV_SERIAL_MS124W_MB:
824                 /* MS-124W can draw power from RTS and DTR if they
825                    are in opposite states. */ 
826                 outb(UART_MCR_RTS | (0&UART_MCR_DTR), uart->base + UART_MCR);
827                 break;
828         case SNDRV_SERIAL_MS124T:
829                 /* MS-124T can draw power from RTS and/or DTR (preferably
830                    both) if they are asserted. */
831                 outb(UART_MCR_RTS | UART_MCR_DTR, uart->base + UART_MCR);
832                 break;
833         default:
834                 break;
835         }
836
837         if (ruart)
838                 *ruart = uart;
839
840         return 0;
841 }
842
843 static int __init snd_uart16550_rmidi(snd_uart16550_t *uart, int device, int outs, int ins, snd_rawmidi_t **rmidi)
844 {
845         snd_rawmidi_t *rrawmidi;
846         int err;
847
848         if ((err = snd_rawmidi_new(uart->card, "UART Serial MIDI", device, outs, ins, &rrawmidi)) < 0)
849                 return err;
850         snd_rawmidi_set_ops(rrawmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_uart16550_input);
851         snd_rawmidi_set_ops(rrawmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_uart16550_output);
852         sprintf(rrawmidi->name, "uart16550 MIDI #%d", device);
853         rrawmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
854                                SNDRV_RAWMIDI_INFO_INPUT |
855                                SNDRV_RAWMIDI_INFO_DUPLEX;
856         rrawmidi->private_data = uart;
857         if (rmidi)
858                 *rmidi = rrawmidi;
859         return 0;
860 }
861
862 static int __init snd_serial_probe(int dev)
863 {
864         snd_card_t *card;
865         snd_uart16550_t *uart;
866         int err;
867
868         if (!enable[dev])
869                 return -ENOENT;
870
871         switch (adaptor[dev]) {
872         case SNDRV_SERIAL_SOUNDCANVAS:
873                 ins[dev] = 1;
874                 break;
875         case SNDRV_SERIAL_MS124T:
876         case SNDRV_SERIAL_MS124W_SA:
877                 outs[dev] = 1;
878                 ins[dev] = 1;
879                 break;
880         case SNDRV_SERIAL_MS124W_MB:
881                 outs[dev] = 16;
882                 ins[dev] = 1;
883                 break;
884         case SNDRV_SERIAL_GENERIC:
885                 break;
886         default:
887                 snd_printk("Adaptor type is out of range 0-%d (%d)\n",
888                            SNDRV_SERIAL_MAX_ADAPTOR, adaptor[dev]);
889                 return -ENODEV;
890         }
891
892         if (outs[dev] < 1 || outs[dev] > SNDRV_SERIAL_MAX_OUTS) {
893                 snd_printk("Count of outputs is out of range 1-%d (%d)\n",
894                            SNDRV_SERIAL_MAX_OUTS, outs[dev]);
895                 return -ENODEV;
896         }
897
898         if (ins[dev] < 1 || ins[dev] > SNDRV_SERIAL_MAX_INS) {
899                 snd_printk("Count of inputs is out of range 1-%d (%d)\n",
900                            SNDRV_SERIAL_MAX_INS, ins[dev]);
901                 return -ENODEV;
902         }
903
904         card  = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
905         if (card == NULL)
906                 return -ENOMEM;
907
908         strcpy(card->driver, "Serial");
909         strcpy(card->shortname, "Serial midi (uart16550A)");
910
911         if ((err = snd_uart16550_create(card,
912                                         port[dev],
913                                         irq[dev],
914                                         speed[dev],
915                                         base[dev],
916                                         adaptor[dev],
917                                         droponfull[dev],
918                                         &uart)) < 0) {
919                 snd_card_free(card);
920                 return err;
921         }
922
923         if ((err = snd_uart16550_rmidi(uart, 0, outs[dev], ins[dev], &uart->rmidi)) < 0) {
924                 snd_card_free(card);
925                 return err;
926         }
927
928         sprintf(card->longname, "%s at 0x%lx, irq %d speed %d div %d outs %d ins %d adaptor %s droponfull %d",
929                 card->shortname,
930                 uart->base,
931                 uart->irq,
932                 uart->speed,
933                 (int)uart->divisor,
934                 outs[dev],
935                 ins[dev],
936                 adaptor_names[uart->adaptor],
937                 uart->drop_on_full);
938
939         if ((err = snd_card_register(card)) < 0) {
940                 snd_card_free(card);
941                 return err;
942         }
943         snd_serial_cards[dev] = card;
944         return 0;
945 }
946
947 static int __init alsa_card_serial_init(void)
948 {
949         int dev = 0;
950         int cards = 0;
951
952         for (dev = 0; dev < SNDRV_CARDS; dev++) {
953                 if (snd_serial_probe(dev) == 0)
954                         cards++;
955         }
956
957         if (cards == 0) {
958 #ifdef MODULE
959                 printk(KERN_ERR "serial midi soundcard not found or device busy\n");
960 #endif
961                 return -ENODEV;
962         }
963         return 0;
964 }
965
966 static void __exit alsa_card_serial_exit(void)
967 {
968         int dev;
969
970         for (dev = 0; dev < SNDRV_CARDS; dev++) {
971                 if (snd_serial_cards[dev] != NULL)
972                         snd_card_free(snd_serial_cards[dev]);
973         }
974 }
975
976 module_init(alsa_card_serial_init)
977 module_exit(alsa_card_serial_exit)