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