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