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