Merge branch 'devel' of master.kernel.org:/home/rmk/linux-2.6-arm
[linux-2.6] / drivers / serial / serial_core.c
1 /*
2  *  linux/drivers/char/core.c
3  *
4  *  Driver core for serial ports
5  *
6  *  Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
7  *
8  *  Copyright 1999 ARM Limited
9  *  Copyright (C) 2000-2001 Deep Blue Solutions Ltd.
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25 #include <linux/module.h>
26 #include <linux/tty.h>
27 #include <linux/slab.h>
28 #include <linux/init.h>
29 #include <linux/console.h>
30 #include <linux/serial_core.h>
31 #include <linux/smp_lock.h>
32 #include <linux/device.h>
33 #include <linux/serial.h> /* for serial_state and serial_icounter_struct */
34 #include <linux/delay.h>
35 #include <linux/mutex.h>
36
37 #include <asm/irq.h>
38 #include <asm/uaccess.h>
39
40 #undef  DEBUG
41 #ifdef DEBUG
42 #define DPRINTK(x...)   printk(x)
43 #else
44 #define DPRINTK(x...)   do { } while (0)
45 #endif
46
47 /*
48  * This is used to lock changes in serial line configuration.
49  */
50 static DEFINE_MUTEX(port_mutex);
51
52 #define HIGH_BITS_OFFSET        ((sizeof(long)-sizeof(int))*8)
53
54 #define uart_users(state)       ((state)->count + ((state)->info ? (state)->info->blocked_open : 0))
55
56 #ifdef CONFIG_SERIAL_CORE_CONSOLE
57 #define uart_console(port)      ((port)->cons && (port)->cons->index == (port)->line)
58 #else
59 #define uart_console(port)      (0)
60 #endif
61
62 static void uart_change_speed(struct uart_state *state, struct termios *old_termios);
63 static void uart_wait_until_sent(struct tty_struct *tty, int timeout);
64 static void uart_change_pm(struct uart_state *state, int pm_state);
65
66 /*
67  * This routine is used by the interrupt handler to schedule processing in
68  * the software interrupt portion of the driver.
69  */
70 void uart_write_wakeup(struct uart_port *port)
71 {
72         struct uart_info *info = port->info;
73         /*
74          * This means you called this function _after_ the port was
75          * closed.  No cookie for you.
76          */
77         BUG_ON(!info);
78         tasklet_schedule(&info->tlet);
79 }
80
81 static void uart_stop(struct tty_struct *tty)
82 {
83         struct uart_state *state = tty->driver_data;
84         struct uart_port *port = state->port;
85         unsigned long flags;
86
87         spin_lock_irqsave(&port->lock, flags);
88         port->ops->stop_tx(port);
89         spin_unlock_irqrestore(&port->lock, flags);
90 }
91
92 static void __uart_start(struct tty_struct *tty)
93 {
94         struct uart_state *state = tty->driver_data;
95         struct uart_port *port = state->port;
96
97         if (!uart_circ_empty(&state->info->xmit) && state->info->xmit.buf &&
98             !tty->stopped && !tty->hw_stopped)
99                 port->ops->start_tx(port);
100 }
101
102 static void uart_start(struct tty_struct *tty)
103 {
104         struct uart_state *state = tty->driver_data;
105         struct uart_port *port = state->port;
106         unsigned long flags;
107
108         spin_lock_irqsave(&port->lock, flags);
109         __uart_start(tty);
110         spin_unlock_irqrestore(&port->lock, flags);
111 }
112
113 static void uart_tasklet_action(unsigned long data)
114 {
115         struct uart_state *state = (struct uart_state *)data;
116         tty_wakeup(state->info->tty);
117 }
118
119 static inline void
120 uart_update_mctrl(struct uart_port *port, unsigned int set, unsigned int clear)
121 {
122         unsigned long flags;
123         unsigned int old;
124
125         spin_lock_irqsave(&port->lock, flags);
126         old = port->mctrl;
127         port->mctrl = (old & ~clear) | set;
128         if (old != port->mctrl)
129                 port->ops->set_mctrl(port, port->mctrl);
130         spin_unlock_irqrestore(&port->lock, flags);
131 }
132
133 #define uart_set_mctrl(port,set)        uart_update_mctrl(port,set,0)
134 #define uart_clear_mctrl(port,clear)    uart_update_mctrl(port,0,clear)
135
136 /*
137  * Startup the port.  This will be called once per open.  All calls
138  * will be serialised by the per-port semaphore.
139  */
140 static int uart_startup(struct uart_state *state, int init_hw)
141 {
142         struct uart_info *info = state->info;
143         struct uart_port *port = state->port;
144         unsigned long page;
145         int retval = 0;
146
147         if (info->flags & UIF_INITIALIZED)
148                 return 0;
149
150         /*
151          * Set the TTY IO error marker - we will only clear this
152          * once we have successfully opened the port.  Also set
153          * up the tty->alt_speed kludge
154          */
155         set_bit(TTY_IO_ERROR, &info->tty->flags);
156
157         if (port->type == PORT_UNKNOWN)
158                 return 0;
159
160         /*
161          * Initialise and allocate the transmit and temporary
162          * buffer.
163          */
164         if (!info->xmit.buf) {
165                 page = get_zeroed_page(GFP_KERNEL);
166                 if (!page)
167                         return -ENOMEM;
168
169                 info->xmit.buf = (unsigned char *) page;
170                 uart_circ_clear(&info->xmit);
171         }
172
173         retval = port->ops->startup(port);
174         if (retval == 0) {
175                 if (init_hw) {
176                         /*
177                          * Initialise the hardware port settings.
178                          */
179                         uart_change_speed(state, NULL);
180
181                         /*
182                          * Setup the RTS and DTR signals once the
183                          * port is open and ready to respond.
184                          */
185                         if (info->tty->termios->c_cflag & CBAUD)
186                                 uart_set_mctrl(port, TIOCM_RTS | TIOCM_DTR);
187                 }
188
189                 if (info->flags & UIF_CTS_FLOW) {
190                         spin_lock_irq(&port->lock);
191                         if (!(port->ops->get_mctrl(port) & TIOCM_CTS))
192                                 info->tty->hw_stopped = 1;
193                         spin_unlock_irq(&port->lock);
194                 }
195
196                 info->flags |= UIF_INITIALIZED;
197
198                 clear_bit(TTY_IO_ERROR, &info->tty->flags);
199         }
200
201         if (retval && capable(CAP_SYS_ADMIN))
202                 retval = 0;
203
204         return retval;
205 }
206
207 /*
208  * This routine will shutdown a serial port; interrupts are disabled, and
209  * DTR is dropped if the hangup on close termio flag is on.  Calls to
210  * uart_shutdown are serialised by the per-port semaphore.
211  */
212 static void uart_shutdown(struct uart_state *state)
213 {
214         struct uart_info *info = state->info;
215         struct uart_port *port = state->port;
216
217         /*
218          * Set the TTY IO error marker
219          */
220         if (info->tty)
221                 set_bit(TTY_IO_ERROR, &info->tty->flags);
222
223         if (info->flags & UIF_INITIALIZED) {
224                 info->flags &= ~UIF_INITIALIZED;
225
226                 /*
227                  * Turn off DTR and RTS early.
228                  */
229                 if (!info->tty || (info->tty->termios->c_cflag & HUPCL))
230                         uart_clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
231
232                 /*
233                  * clear delta_msr_wait queue to avoid mem leaks: we may free
234                  * the irq here so the queue might never be woken up.  Note
235                  * that we won't end up waiting on delta_msr_wait again since
236                  * any outstanding file descriptors should be pointing at
237                  * hung_up_tty_fops now.
238                  */
239                 wake_up_interruptible(&info->delta_msr_wait);
240
241                 /*
242                  * Free the IRQ and disable the port.
243                  */
244                 port->ops->shutdown(port);
245
246                 /*
247                  * Ensure that the IRQ handler isn't running on another CPU.
248                  */
249                 synchronize_irq(port->irq);
250         }
251
252         /*
253          * kill off our tasklet
254          */
255         tasklet_kill(&info->tlet);
256
257         /*
258          * Free the transmit buffer page.
259          */
260         if (info->xmit.buf) {
261                 free_page((unsigned long)info->xmit.buf);
262                 info->xmit.buf = NULL;
263         }
264 }
265
266 /**
267  *      uart_update_timeout - update per-port FIFO timeout.
268  *      @port:  uart_port structure describing the port
269  *      @cflag: termios cflag value
270  *      @baud:  speed of the port
271  *
272  *      Set the port FIFO timeout value.  The @cflag value should
273  *      reflect the actual hardware settings.
274  */
275 void
276 uart_update_timeout(struct uart_port *port, unsigned int cflag,
277                     unsigned int baud)
278 {
279         unsigned int bits;
280
281         /* byte size and parity */
282         switch (cflag & CSIZE) {
283         case CS5:
284                 bits = 7;
285                 break;
286         case CS6:
287                 bits = 8;
288                 break;
289         case CS7:
290                 bits = 9;
291                 break;
292         default:
293                 bits = 10;
294                 break; // CS8
295         }
296
297         if (cflag & CSTOPB)
298                 bits++;
299         if (cflag & PARENB)
300                 bits++;
301
302         /*
303          * The total number of bits to be transmitted in the fifo.
304          */
305         bits = bits * port->fifosize;
306
307         /*
308          * Figure the timeout to send the above number of bits.
309          * Add .02 seconds of slop
310          */
311         port->timeout = (HZ * bits) / baud + HZ/50;
312 }
313
314 EXPORT_SYMBOL(uart_update_timeout);
315
316 /**
317  *      uart_get_baud_rate - return baud rate for a particular port
318  *      @port: uart_port structure describing the port in question.
319  *      @termios: desired termios settings.
320  *      @old: old termios (or NULL)
321  *      @min: minimum acceptable baud rate
322  *      @max: maximum acceptable baud rate
323  *
324  *      Decode the termios structure into a numeric baud rate,
325  *      taking account of the magic 38400 baud rate (with spd_*
326  *      flags), and mapping the %B0 rate to 9600 baud.
327  *
328  *      If the new baud rate is invalid, try the old termios setting.
329  *      If it's still invalid, we try 9600 baud.
330  *
331  *      Update the @termios structure to reflect the baud rate
332  *      we're actually going to be using.
333  */
334 unsigned int
335 uart_get_baud_rate(struct uart_port *port, struct termios *termios,
336                    struct termios *old, unsigned int min, unsigned int max)
337 {
338         unsigned int try, baud, altbaud = 38400;
339         upf_t flags = port->flags & UPF_SPD_MASK;
340
341         if (flags == UPF_SPD_HI)
342                 altbaud = 57600;
343         if (flags == UPF_SPD_VHI)
344                 altbaud = 115200;
345         if (flags == UPF_SPD_SHI)
346                 altbaud = 230400;
347         if (flags == UPF_SPD_WARP)
348                 altbaud = 460800;
349
350         for (try = 0; try < 2; try++) {
351                 baud = tty_termios_baud_rate(termios);
352
353                 /*
354                  * The spd_hi, spd_vhi, spd_shi, spd_warp kludge...
355                  * Die! Die! Die!
356                  */
357                 if (baud == 38400)
358                         baud = altbaud;
359
360                 /*
361                  * Special case: B0 rate.
362                  */
363                 if (baud == 0)
364                         baud = 9600;
365
366                 if (baud >= min && baud <= max)
367                         return baud;
368
369                 /*
370                  * Oops, the quotient was zero.  Try again with
371                  * the old baud rate if possible.
372                  */
373                 termios->c_cflag &= ~CBAUD;
374                 if (old) {
375                         termios->c_cflag |= old->c_cflag & CBAUD;
376                         old = NULL;
377                         continue;
378                 }
379
380                 /*
381                  * As a last resort, if the quotient is zero,
382                  * default to 9600 bps
383                  */
384                 termios->c_cflag |= B9600;
385         }
386
387         return 0;
388 }
389
390 EXPORT_SYMBOL(uart_get_baud_rate);
391
392 /**
393  *      uart_get_divisor - return uart clock divisor
394  *      @port: uart_port structure describing the port.
395  *      @baud: desired baud rate
396  *
397  *      Calculate the uart clock divisor for the port.
398  */
399 unsigned int
400 uart_get_divisor(struct uart_port *port, unsigned int baud)
401 {
402         unsigned int quot;
403
404         /*
405          * Old custom speed handling.
406          */
407         if (baud == 38400 && (port->flags & UPF_SPD_MASK) == UPF_SPD_CUST)
408                 quot = port->custom_divisor;
409         else
410                 quot = (port->uartclk + (8 * baud)) / (16 * baud);
411
412         return quot;
413 }
414
415 EXPORT_SYMBOL(uart_get_divisor);
416
417 static void
418 uart_change_speed(struct uart_state *state, struct termios *old_termios)
419 {
420         struct tty_struct *tty = state->info->tty;
421         struct uart_port *port = state->port;
422         struct termios *termios;
423
424         /*
425          * If we have no tty, termios, or the port does not exist,
426          * then we can't set the parameters for this port.
427          */
428         if (!tty || !tty->termios || port->type == PORT_UNKNOWN)
429                 return;
430
431         termios = tty->termios;
432
433         /*
434          * Set flags based on termios cflag
435          */
436         if (termios->c_cflag & CRTSCTS)
437                 state->info->flags |= UIF_CTS_FLOW;
438         else
439                 state->info->flags &= ~UIF_CTS_FLOW;
440
441         if (termios->c_cflag & CLOCAL)
442                 state->info->flags &= ~UIF_CHECK_CD;
443         else
444                 state->info->flags |= UIF_CHECK_CD;
445
446         port->ops->set_termios(port, termios, old_termios);
447 }
448
449 static inline void
450 __uart_put_char(struct uart_port *port, struct circ_buf *circ, unsigned char c)
451 {
452         unsigned long flags;
453
454         if (!circ->buf)
455                 return;
456
457         spin_lock_irqsave(&port->lock, flags);
458         if (uart_circ_chars_free(circ) != 0) {
459                 circ->buf[circ->head] = c;
460                 circ->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);
461         }
462         spin_unlock_irqrestore(&port->lock, flags);
463 }
464
465 static void uart_put_char(struct tty_struct *tty, unsigned char ch)
466 {
467         struct uart_state *state = tty->driver_data;
468
469         __uart_put_char(state->port, &state->info->xmit, ch);
470 }
471
472 static void uart_flush_chars(struct tty_struct *tty)
473 {
474         uart_start(tty);
475 }
476
477 static int
478 uart_write(struct tty_struct *tty, const unsigned char *buf, int count)
479 {
480         struct uart_state *state = tty->driver_data;
481         struct uart_port *port;
482         struct circ_buf *circ;
483         unsigned long flags;
484         int c, ret = 0;
485
486         /*
487          * This means you called this function _after_ the port was
488          * closed.  No cookie for you.
489          */
490         if (!state || !state->info) {
491                 WARN_ON(1);
492                 return -EL3HLT;
493         }
494
495         port = state->port;
496         circ = &state->info->xmit;
497
498         if (!circ->buf)
499                 return 0;
500
501         spin_lock_irqsave(&port->lock, flags);
502         while (1) {
503                 c = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);
504                 if (count < c)
505                         c = count;
506                 if (c <= 0)
507                         break;
508                 memcpy(circ->buf + circ->head, buf, c);
509                 circ->head = (circ->head + c) & (UART_XMIT_SIZE - 1);
510                 buf += c;
511                 count -= c;
512                 ret += c;
513         }
514         spin_unlock_irqrestore(&port->lock, flags);
515
516         uart_start(tty);
517         return ret;
518 }
519
520 static int uart_write_room(struct tty_struct *tty)
521 {
522         struct uart_state *state = tty->driver_data;
523
524         return uart_circ_chars_free(&state->info->xmit);
525 }
526
527 static int uart_chars_in_buffer(struct tty_struct *tty)
528 {
529         struct uart_state *state = tty->driver_data;
530
531         return uart_circ_chars_pending(&state->info->xmit);
532 }
533
534 static void uart_flush_buffer(struct tty_struct *tty)
535 {
536         struct uart_state *state = tty->driver_data;
537         struct uart_port *port = state->port;
538         unsigned long flags;
539
540         /*
541          * This means you called this function _after_ the port was
542          * closed.  No cookie for you.
543          */
544         if (!state || !state->info) {
545                 WARN_ON(1);
546                 return;
547         }
548
549         DPRINTK("uart_flush_buffer(%d) called\n", tty->index);
550
551         spin_lock_irqsave(&port->lock, flags);
552         uart_circ_clear(&state->info->xmit);
553         spin_unlock_irqrestore(&port->lock, flags);
554         tty_wakeup(tty);
555 }
556
557 /*
558  * This function is used to send a high-priority XON/XOFF character to
559  * the device
560  */
561 static void uart_send_xchar(struct tty_struct *tty, char ch)
562 {
563         struct uart_state *state = tty->driver_data;
564         struct uart_port *port = state->port;
565         unsigned long flags;
566
567         if (port->ops->send_xchar)
568                 port->ops->send_xchar(port, ch);
569         else {
570                 port->x_char = ch;
571                 if (ch) {
572                         spin_lock_irqsave(&port->lock, flags);
573                         port->ops->start_tx(port);
574                         spin_unlock_irqrestore(&port->lock, flags);
575                 }
576         }
577 }
578
579 static void uart_throttle(struct tty_struct *tty)
580 {
581         struct uart_state *state = tty->driver_data;
582
583         if (I_IXOFF(tty))
584                 uart_send_xchar(tty, STOP_CHAR(tty));
585
586         if (tty->termios->c_cflag & CRTSCTS)
587                 uart_clear_mctrl(state->port, TIOCM_RTS);
588 }
589
590 static void uart_unthrottle(struct tty_struct *tty)
591 {
592         struct uart_state *state = tty->driver_data;
593         struct uart_port *port = state->port;
594
595         if (I_IXOFF(tty)) {
596                 if (port->x_char)
597                         port->x_char = 0;
598                 else
599                         uart_send_xchar(tty, START_CHAR(tty));
600         }
601
602         if (tty->termios->c_cflag & CRTSCTS)
603                 uart_set_mctrl(port, TIOCM_RTS);
604 }
605
606 static int uart_get_info(struct uart_state *state,
607                          struct serial_struct __user *retinfo)
608 {
609         struct uart_port *port = state->port;
610         struct serial_struct tmp;
611
612         memset(&tmp, 0, sizeof(tmp));
613         tmp.type            = port->type;
614         tmp.line            = port->line;
615         tmp.port            = port->iobase;
616         if (HIGH_BITS_OFFSET)
617                 tmp.port_high = (long) port->iobase >> HIGH_BITS_OFFSET;
618         tmp.irq             = port->irq;
619         tmp.flags           = port->flags;
620         tmp.xmit_fifo_size  = port->fifosize;
621         tmp.baud_base       = port->uartclk / 16;
622         tmp.close_delay     = state->close_delay / 10;
623         tmp.closing_wait    = state->closing_wait == USF_CLOSING_WAIT_NONE ?
624                                 ASYNC_CLOSING_WAIT_NONE :
625                                 state->closing_wait / 10;
626         tmp.custom_divisor  = port->custom_divisor;
627         tmp.hub6            = port->hub6;
628         tmp.io_type         = port->iotype;
629         tmp.iomem_reg_shift = port->regshift;
630         tmp.iomem_base      = (void *)port->mapbase;
631
632         if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
633                 return -EFAULT;
634         return 0;
635 }
636
637 static int uart_set_info(struct uart_state *state,
638                          struct serial_struct __user *newinfo)
639 {
640         struct serial_struct new_serial;
641         struct uart_port *port = state->port;
642         unsigned long new_port;
643         unsigned int change_irq, change_port, closing_wait;
644         unsigned int old_custom_divisor, close_delay;
645         upf_t old_flags, new_flags;
646         int retval = 0;
647
648         if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
649                 return -EFAULT;
650
651         new_port = new_serial.port;
652         if (HIGH_BITS_OFFSET)
653                 new_port += (unsigned long) new_serial.port_high << HIGH_BITS_OFFSET;
654
655         new_serial.irq = irq_canonicalize(new_serial.irq);
656         close_delay = new_serial.close_delay * 10;
657         closing_wait = new_serial.closing_wait == ASYNC_CLOSING_WAIT_NONE ?
658                         USF_CLOSING_WAIT_NONE : new_serial.closing_wait * 10;
659
660         /*
661          * This semaphore protects state->count.  It is also
662          * very useful to prevent opens.  Also, take the
663          * port configuration semaphore to make sure that a
664          * module insertion/removal doesn't change anything
665          * under us.
666          */
667         mutex_lock(&state->mutex);
668
669         change_irq  = new_serial.irq != port->irq;
670
671         /*
672          * Since changing the 'type' of the port changes its resource
673          * allocations, we should treat type changes the same as
674          * IO port changes.
675          */
676         change_port = new_port != port->iobase ||
677                       (unsigned long)new_serial.iomem_base != port->mapbase ||
678                       new_serial.hub6 != port->hub6 ||
679                       new_serial.io_type != port->iotype ||
680                       new_serial.iomem_reg_shift != port->regshift ||
681                       new_serial.type != port->type;
682
683         old_flags = port->flags;
684         new_flags = new_serial.flags;
685         old_custom_divisor = port->custom_divisor;
686
687         if (!capable(CAP_SYS_ADMIN)) {
688                 retval = -EPERM;
689                 if (change_irq || change_port ||
690                     (new_serial.baud_base != port->uartclk / 16) ||
691                     (close_delay != state->close_delay) ||
692                     (closing_wait != state->closing_wait) ||
693                     (new_serial.xmit_fifo_size != port->fifosize) ||
694                     (((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))
695                         goto exit;
696                 port->flags = ((port->flags & ~UPF_USR_MASK) |
697                                (new_flags & UPF_USR_MASK));
698                 port->custom_divisor = new_serial.custom_divisor;
699                 goto check_and_exit;
700         }
701
702         /*
703          * Ask the low level driver to verify the settings.
704          */
705         if (port->ops->verify_port)
706                 retval = port->ops->verify_port(port, &new_serial);
707
708         if ((new_serial.irq >= NR_IRQS) || (new_serial.irq < 0) ||
709             (new_serial.baud_base < 9600))
710                 retval = -EINVAL;
711
712         if (retval)
713                 goto exit;
714
715         if (change_port || change_irq) {
716                 retval = -EBUSY;
717
718                 /*
719                  * Make sure that we are the sole user of this port.
720                  */
721                 if (uart_users(state) > 1)
722                         goto exit;
723
724                 /*
725                  * We need to shutdown the serial port at the old
726                  * port/type/irq combination.
727                  */
728                 uart_shutdown(state);
729         }
730
731         if (change_port) {
732                 unsigned long old_iobase, old_mapbase;
733                 unsigned int old_type, old_iotype, old_hub6, old_shift;
734
735                 old_iobase = port->iobase;
736                 old_mapbase = port->mapbase;
737                 old_type = port->type;
738                 old_hub6 = port->hub6;
739                 old_iotype = port->iotype;
740                 old_shift = port->regshift;
741
742                 /*
743                  * Free and release old regions
744                  */
745                 if (old_type != PORT_UNKNOWN)
746                         port->ops->release_port(port);
747
748                 port->iobase = new_port;
749                 port->type = new_serial.type;
750                 port->hub6 = new_serial.hub6;
751                 port->iotype = new_serial.io_type;
752                 port->regshift = new_serial.iomem_reg_shift;
753                 port->mapbase = (unsigned long)new_serial.iomem_base;
754
755                 /*
756                  * Claim and map the new regions
757                  */
758                 if (port->type != PORT_UNKNOWN) {
759                         retval = port->ops->request_port(port);
760                 } else {
761                         /* Always success - Jean II */
762                         retval = 0;
763                 }
764
765                 /*
766                  * If we fail to request resources for the
767                  * new port, try to restore the old settings.
768                  */
769                 if (retval && old_type != PORT_UNKNOWN) {
770                         port->iobase = old_iobase;
771                         port->type = old_type;
772                         port->hub6 = old_hub6;
773                         port->iotype = old_iotype;
774                         port->regshift = old_shift;
775                         port->mapbase = old_mapbase;
776                         retval = port->ops->request_port(port);
777                         /*
778                          * If we failed to restore the old settings,
779                          * we fail like this.
780                          */
781                         if (retval)
782                                 port->type = PORT_UNKNOWN;
783
784                         /*
785                          * We failed anyway.
786                          */
787                         retval = -EBUSY;
788                 }
789         }
790
791         port->irq              = new_serial.irq;
792         port->uartclk          = new_serial.baud_base * 16;
793         port->flags            = (port->flags & ~UPF_CHANGE_MASK) |
794                                  (new_flags & UPF_CHANGE_MASK);
795         port->custom_divisor   = new_serial.custom_divisor;
796         state->close_delay     = close_delay;
797         state->closing_wait    = closing_wait;
798         port->fifosize         = new_serial.xmit_fifo_size;
799         if (state->info->tty)
800                 state->info->tty->low_latency =
801                         (port->flags & UPF_LOW_LATENCY) ? 1 : 0;
802
803  check_and_exit:
804         retval = 0;
805         if (port->type == PORT_UNKNOWN)
806                 goto exit;
807         if (state->info->flags & UIF_INITIALIZED) {
808                 if (((old_flags ^ port->flags) & UPF_SPD_MASK) ||
809                     old_custom_divisor != port->custom_divisor) {
810                         /*
811                          * If they're setting up a custom divisor or speed,
812                          * instead of clearing it, then bitch about it. No
813                          * need to rate-limit; it's CAP_SYS_ADMIN only.
814                          */
815                         if (port->flags & UPF_SPD_MASK) {
816                                 char buf[64];
817                                 printk(KERN_NOTICE
818                                        "%s sets custom speed on %s. This "
819                                        "is deprecated.\n", current->comm,
820                                        tty_name(state->info->tty, buf));
821                         }
822                         uart_change_speed(state, NULL);
823                 }
824         } else
825                 retval = uart_startup(state, 1);
826  exit:
827         mutex_unlock(&state->mutex);
828         return retval;
829 }
830
831
832 /*
833  * uart_get_lsr_info - get line status register info.
834  * Note: uart_ioctl protects us against hangups.
835  */
836 static int uart_get_lsr_info(struct uart_state *state,
837                              unsigned int __user *value)
838 {
839         struct uart_port *port = state->port;
840         unsigned int result;
841
842         result = port->ops->tx_empty(port);
843
844         /*
845          * If we're about to load something into the transmit
846          * register, we'll pretend the transmitter isn't empty to
847          * avoid a race condition (depending on when the transmit
848          * interrupt happens).
849          */
850         if (port->x_char ||
851             ((uart_circ_chars_pending(&state->info->xmit) > 0) &&
852              !state->info->tty->stopped && !state->info->tty->hw_stopped))
853                 result &= ~TIOCSER_TEMT;
854         
855         return put_user(result, value);
856 }
857
858 static int uart_tiocmget(struct tty_struct *tty, struct file *file)
859 {
860         struct uart_state *state = tty->driver_data;
861         struct uart_port *port = state->port;
862         int result = -EIO;
863
864         mutex_lock(&state->mutex);
865         if ((!file || !tty_hung_up_p(file)) &&
866             !(tty->flags & (1 << TTY_IO_ERROR))) {
867                 result = port->mctrl;
868
869                 spin_lock_irq(&port->lock);
870                 result |= port->ops->get_mctrl(port);
871                 spin_unlock_irq(&port->lock);
872         }
873         mutex_unlock(&state->mutex);
874
875         return result;
876 }
877
878 static int
879 uart_tiocmset(struct tty_struct *tty, struct file *file,
880               unsigned int set, unsigned int clear)
881 {
882         struct uart_state *state = tty->driver_data;
883         struct uart_port *port = state->port;
884         int ret = -EIO;
885
886         mutex_lock(&state->mutex);
887         if ((!file || !tty_hung_up_p(file)) &&
888             !(tty->flags & (1 << TTY_IO_ERROR))) {
889                 uart_update_mctrl(port, set, clear);
890                 ret = 0;
891         }
892         mutex_unlock(&state->mutex);
893         return ret;
894 }
895
896 static void uart_break_ctl(struct tty_struct *tty, int break_state)
897 {
898         struct uart_state *state = tty->driver_data;
899         struct uart_port *port = state->port;
900
901         BUG_ON(!kernel_locked());
902
903         mutex_lock(&state->mutex);
904
905         if (port->type != PORT_UNKNOWN)
906                 port->ops->break_ctl(port, break_state);
907
908         mutex_unlock(&state->mutex);
909 }
910
911 static int uart_do_autoconfig(struct uart_state *state)
912 {
913         struct uart_port *port = state->port;
914         int flags, ret;
915
916         if (!capable(CAP_SYS_ADMIN))
917                 return -EPERM;
918
919         /*
920          * Take the per-port semaphore.  This prevents count from
921          * changing, and hence any extra opens of the port while
922          * we're auto-configuring.
923          */
924         if (mutex_lock_interruptible(&state->mutex))
925                 return -ERESTARTSYS;
926
927         ret = -EBUSY;
928         if (uart_users(state) == 1) {
929                 uart_shutdown(state);
930
931                 /*
932                  * If we already have a port type configured,
933                  * we must release its resources.
934                  */
935                 if (port->type != PORT_UNKNOWN)
936                         port->ops->release_port(port);
937
938                 flags = UART_CONFIG_TYPE;
939                 if (port->flags & UPF_AUTO_IRQ)
940                         flags |= UART_CONFIG_IRQ;
941
942                 /*
943                  * This will claim the ports resources if
944                  * a port is found.
945                  */
946                 port->ops->config_port(port, flags);
947
948                 ret = uart_startup(state, 1);
949         }
950         mutex_unlock(&state->mutex);
951         return ret;
952 }
953
954 /*
955  * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
956  * - mask passed in arg for lines of interest
957  *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
958  * Caller should use TIOCGICOUNT to see which one it was
959  */
960 static int
961 uart_wait_modem_status(struct uart_state *state, unsigned long arg)
962 {
963         struct uart_port *port = state->port;
964         DECLARE_WAITQUEUE(wait, current);
965         struct uart_icount cprev, cnow;
966         int ret;
967
968         /*
969          * note the counters on entry
970          */
971         spin_lock_irq(&port->lock);
972         memcpy(&cprev, &port->icount, sizeof(struct uart_icount));
973
974         /*
975          * Force modem status interrupts on
976          */
977         port->ops->enable_ms(port);
978         spin_unlock_irq(&port->lock);
979
980         add_wait_queue(&state->info->delta_msr_wait, &wait);
981         for (;;) {
982                 spin_lock_irq(&port->lock);
983                 memcpy(&cnow, &port->icount, sizeof(struct uart_icount));
984                 spin_unlock_irq(&port->lock);
985
986                 set_current_state(TASK_INTERRUPTIBLE);
987
988                 if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
989                     ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
990                     ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
991                     ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
992                         ret = 0;
993                         break;
994                 }
995
996                 schedule();
997
998                 /* see if a signal did it */
999                 if (signal_pending(current)) {
1000                         ret = -ERESTARTSYS;
1001                         break;
1002                 }
1003
1004                 cprev = cnow;
1005         }
1006
1007         current->state = TASK_RUNNING;
1008         remove_wait_queue(&state->info->delta_msr_wait, &wait);
1009
1010         return ret;
1011 }
1012
1013 /*
1014  * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1015  * Return: write counters to the user passed counter struct
1016  * NB: both 1->0 and 0->1 transitions are counted except for
1017  *     RI where only 0->1 is counted.
1018  */
1019 static int uart_get_count(struct uart_state *state,
1020                           struct serial_icounter_struct __user *icnt)
1021 {
1022         struct serial_icounter_struct icount;
1023         struct uart_icount cnow;
1024         struct uart_port *port = state->port;
1025
1026         spin_lock_irq(&port->lock);
1027         memcpy(&cnow, &port->icount, sizeof(struct uart_icount));
1028         spin_unlock_irq(&port->lock);
1029
1030         icount.cts         = cnow.cts;
1031         icount.dsr         = cnow.dsr;
1032         icount.rng         = cnow.rng;
1033         icount.dcd         = cnow.dcd;
1034         icount.rx          = cnow.rx;
1035         icount.tx          = cnow.tx;
1036         icount.frame       = cnow.frame;
1037         icount.overrun     = cnow.overrun;
1038         icount.parity      = cnow.parity;
1039         icount.brk         = cnow.brk;
1040         icount.buf_overrun = cnow.buf_overrun;
1041
1042         return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0;
1043 }
1044
1045 /*
1046  * Called via sys_ioctl under the BKL.  We can use spin_lock_irq() here.
1047  */
1048 static int
1049 uart_ioctl(struct tty_struct *tty, struct file *filp, unsigned int cmd,
1050            unsigned long arg)
1051 {
1052         struct uart_state *state = tty->driver_data;
1053         void __user *uarg = (void __user *)arg;
1054         int ret = -ENOIOCTLCMD;
1055
1056         BUG_ON(!kernel_locked());
1057
1058         /*
1059          * These ioctls don't rely on the hardware to be present.
1060          */
1061         switch (cmd) {
1062         case TIOCGSERIAL:
1063                 ret = uart_get_info(state, uarg);
1064                 break;
1065
1066         case TIOCSSERIAL:
1067                 ret = uart_set_info(state, uarg);
1068                 break;
1069
1070         case TIOCSERCONFIG:
1071                 ret = uart_do_autoconfig(state);
1072                 break;
1073
1074         case TIOCSERGWILD: /* obsolete */
1075         case TIOCSERSWILD: /* obsolete */
1076                 ret = 0;
1077                 break;
1078         }
1079
1080         if (ret != -ENOIOCTLCMD)
1081                 goto out;
1082
1083         if (tty->flags & (1 << TTY_IO_ERROR)) {
1084                 ret = -EIO;
1085                 goto out;
1086         }
1087
1088         /*
1089          * The following should only be used when hardware is present.
1090          */
1091         switch (cmd) {
1092         case TIOCMIWAIT:
1093                 ret = uart_wait_modem_status(state, arg);
1094                 break;
1095
1096         case TIOCGICOUNT:
1097                 ret = uart_get_count(state, uarg);
1098                 break;
1099         }
1100
1101         if (ret != -ENOIOCTLCMD)
1102                 goto out;
1103
1104         mutex_lock(&state->mutex);
1105
1106         if (tty_hung_up_p(filp)) {
1107                 ret = -EIO;
1108                 goto out_up;
1109         }
1110
1111         /*
1112          * All these rely on hardware being present and need to be
1113          * protected against the tty being hung up.
1114          */
1115         switch (cmd) {
1116         case TIOCSERGETLSR: /* Get line status register */
1117                 ret = uart_get_lsr_info(state, uarg);
1118                 break;
1119
1120         default: {
1121                 struct uart_port *port = state->port;
1122                 if (port->ops->ioctl)
1123                         ret = port->ops->ioctl(port, cmd, arg);
1124                 break;
1125         }
1126         }
1127  out_up:
1128         mutex_unlock(&state->mutex);
1129  out:
1130         return ret;
1131 }
1132
1133 static void uart_set_termios(struct tty_struct *tty, struct termios *old_termios)
1134 {
1135         struct uart_state *state = tty->driver_data;
1136         unsigned long flags;
1137         unsigned int cflag = tty->termios->c_cflag;
1138
1139         BUG_ON(!kernel_locked());
1140
1141         /*
1142          * These are the bits that are used to setup various
1143          * flags in the low level driver.
1144          */
1145 #define RELEVANT_IFLAG(iflag)   ((iflag) & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
1146
1147         if ((cflag ^ old_termios->c_cflag) == 0 &&
1148             RELEVANT_IFLAG(tty->termios->c_iflag ^ old_termios->c_iflag) == 0)
1149                 return;
1150
1151         uart_change_speed(state, old_termios);
1152
1153         /* Handle transition to B0 status */
1154         if ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))
1155                 uart_clear_mctrl(state->port, TIOCM_RTS | TIOCM_DTR);
1156
1157         /* Handle transition away from B0 status */
1158         if (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {
1159                 unsigned int mask = TIOCM_DTR;
1160                 if (!(cflag & CRTSCTS) ||
1161                     !test_bit(TTY_THROTTLED, &tty->flags))
1162                         mask |= TIOCM_RTS;
1163                 uart_set_mctrl(state->port, mask);
1164         }
1165
1166         /* Handle turning off CRTSCTS */
1167         if ((old_termios->c_cflag & CRTSCTS) && !(cflag & CRTSCTS)) {
1168                 spin_lock_irqsave(&state->port->lock, flags);
1169                 tty->hw_stopped = 0;
1170                 __uart_start(tty);
1171                 spin_unlock_irqrestore(&state->port->lock, flags);
1172         }
1173
1174         /* Handle turning on CRTSCTS */
1175         if (!(old_termios->c_cflag & CRTSCTS) && (cflag & CRTSCTS)) {
1176                 spin_lock_irqsave(&state->port->lock, flags);
1177                 if (!(state->port->ops->get_mctrl(state->port) & TIOCM_CTS)) {
1178                         tty->hw_stopped = 1;
1179                         state->port->ops->stop_tx(state->port);
1180                 }
1181                 spin_unlock_irqrestore(&state->port->lock, flags);
1182         }
1183
1184 #if 0
1185         /*
1186          * No need to wake up processes in open wait, since they
1187          * sample the CLOCAL flag once, and don't recheck it.
1188          * XXX  It's not clear whether the current behavior is correct
1189          * or not.  Hence, this may change.....
1190          */
1191         if (!(old_termios->c_cflag & CLOCAL) &&
1192             (tty->termios->c_cflag & CLOCAL))
1193                 wake_up_interruptible(&state->info->open_wait);
1194 #endif
1195 }
1196
1197 /*
1198  * In 2.4.5, calls to this will be serialized via the BKL in
1199  *  linux/drivers/char/tty_io.c:tty_release()
1200  *  linux/drivers/char/tty_io.c:do_tty_handup()
1201  */
1202 static void uart_close(struct tty_struct *tty, struct file *filp)
1203 {
1204         struct uart_state *state = tty->driver_data;
1205         struct uart_port *port;
1206         
1207         BUG_ON(!kernel_locked());
1208
1209         if (!state || !state->port)
1210                 return;
1211
1212         port = state->port;
1213
1214         DPRINTK("uart_close(%d) called\n", port->line);
1215
1216         mutex_lock(&state->mutex);
1217
1218         if (tty_hung_up_p(filp))
1219                 goto done;
1220
1221         if ((tty->count == 1) && (state->count != 1)) {
1222                 /*
1223                  * Uh, oh.  tty->count is 1, which means that the tty
1224                  * structure will be freed.  state->count should always
1225                  * be one in these conditions.  If it's greater than
1226                  * one, we've got real problems, since it means the
1227                  * serial port won't be shutdown.
1228                  */
1229                 printk(KERN_ERR "uart_close: bad serial port count; tty->count is 1, "
1230                        "state->count is %d\n", state->count);
1231                 state->count = 1;
1232         }
1233         if (--state->count < 0) {
1234                 printk(KERN_ERR "uart_close: bad serial port count for %s: %d\n",
1235                        tty->name, state->count);
1236                 state->count = 0;
1237         }
1238         if (state->count)
1239                 goto done;
1240
1241         /*
1242          * Now we wait for the transmit buffer to clear; and we notify
1243          * the line discipline to only process XON/XOFF characters by
1244          * setting tty->closing.
1245          */
1246         tty->closing = 1;
1247
1248         if (state->closing_wait != USF_CLOSING_WAIT_NONE)
1249                 tty_wait_until_sent(tty, msecs_to_jiffies(state->closing_wait));
1250
1251         /*
1252          * At this point, we stop accepting input.  To do this, we
1253          * disable the receive line status interrupts.
1254          */
1255         if (state->info->flags & UIF_INITIALIZED) {
1256                 unsigned long flags;
1257                 spin_lock_irqsave(&port->lock, flags);
1258                 port->ops->stop_rx(port);
1259                 spin_unlock_irqrestore(&port->lock, flags);
1260                 /*
1261                  * Before we drop DTR, make sure the UART transmitter
1262                  * has completely drained; this is especially
1263                  * important if there is a transmit FIFO!
1264                  */
1265                 uart_wait_until_sent(tty, port->timeout);
1266         }
1267
1268         uart_shutdown(state);
1269         uart_flush_buffer(tty);
1270
1271         tty_ldisc_flush(tty);   
1272         
1273         tty->closing = 0;
1274         state->info->tty = NULL;
1275
1276         if (state->info->blocked_open) {
1277                 if (state->close_delay)
1278                         msleep_interruptible(state->close_delay);
1279         } else if (!uart_console(port)) {
1280                 uart_change_pm(state, 3);
1281         }
1282
1283         /*
1284          * Wake up anyone trying to open this port.
1285          */
1286         state->info->flags &= ~UIF_NORMAL_ACTIVE;
1287         wake_up_interruptible(&state->info->open_wait);
1288
1289  done:
1290         mutex_unlock(&state->mutex);
1291 }
1292
1293 static void uart_wait_until_sent(struct tty_struct *tty, int timeout)
1294 {
1295         struct uart_state *state = tty->driver_data;
1296         struct uart_port *port = state->port;
1297         unsigned long char_time, expire;
1298
1299         BUG_ON(!kernel_locked());
1300
1301         if (port->type == PORT_UNKNOWN || port->fifosize == 0)
1302                 return;
1303
1304         /*
1305          * Set the check interval to be 1/5 of the estimated time to
1306          * send a single character, and make it at least 1.  The check
1307          * interval should also be less than the timeout.
1308          *
1309          * Note: we have to use pretty tight timings here to satisfy
1310          * the NIST-PCTS.
1311          */
1312         char_time = (port->timeout - HZ/50) / port->fifosize;
1313         char_time = char_time / 5;
1314         if (char_time == 0)
1315                 char_time = 1;
1316         if (timeout && timeout < char_time)
1317                 char_time = timeout;
1318
1319         /*
1320          * If the transmitter hasn't cleared in twice the approximate
1321          * amount of time to send the entire FIFO, it probably won't
1322          * ever clear.  This assumes the UART isn't doing flow
1323          * control, which is currently the case.  Hence, if it ever
1324          * takes longer than port->timeout, this is probably due to a
1325          * UART bug of some kind.  So, we clamp the timeout parameter at
1326          * 2*port->timeout.
1327          */
1328         if (timeout == 0 || timeout > 2 * port->timeout)
1329                 timeout = 2 * port->timeout;
1330
1331         expire = jiffies + timeout;
1332
1333         DPRINTK("uart_wait_until_sent(%d), jiffies=%lu, expire=%lu...\n",
1334                 port->line, jiffies, expire);
1335
1336         /*
1337          * Check whether the transmitter is empty every 'char_time'.
1338          * 'timeout' / 'expire' give us the maximum amount of time
1339          * we wait.
1340          */
1341         while (!port->ops->tx_empty(port)) {
1342                 msleep_interruptible(jiffies_to_msecs(char_time));
1343                 if (signal_pending(current))
1344                         break;
1345                 if (time_after(jiffies, expire))
1346                         break;
1347         }
1348         set_current_state(TASK_RUNNING); /* might not be needed */
1349 }
1350
1351 /*
1352  * This is called with the BKL held in
1353  *  linux/drivers/char/tty_io.c:do_tty_hangup()
1354  * We're called from the eventd thread, so we can sleep for
1355  * a _short_ time only.
1356  */
1357 static void uart_hangup(struct tty_struct *tty)
1358 {
1359         struct uart_state *state = tty->driver_data;
1360
1361         BUG_ON(!kernel_locked());
1362         DPRINTK("uart_hangup(%d)\n", state->port->line);
1363
1364         mutex_lock(&state->mutex);
1365         if (state->info && state->info->flags & UIF_NORMAL_ACTIVE) {
1366                 uart_flush_buffer(tty);
1367                 uart_shutdown(state);
1368                 state->count = 0;
1369                 state->info->flags &= ~UIF_NORMAL_ACTIVE;
1370                 state->info->tty = NULL;
1371                 wake_up_interruptible(&state->info->open_wait);
1372                 wake_up_interruptible(&state->info->delta_msr_wait);
1373         }
1374         mutex_unlock(&state->mutex);
1375 }
1376
1377 /*
1378  * Copy across the serial console cflag setting into the termios settings
1379  * for the initial open of the port.  This allows continuity between the
1380  * kernel settings, and the settings init adopts when it opens the port
1381  * for the first time.
1382  */
1383 static void uart_update_termios(struct uart_state *state)
1384 {
1385         struct tty_struct *tty = state->info->tty;
1386         struct uart_port *port = state->port;
1387
1388         if (uart_console(port) && port->cons->cflag) {
1389                 tty->termios->c_cflag = port->cons->cflag;
1390                 port->cons->cflag = 0;
1391         }
1392
1393         /*
1394          * If the device failed to grab its irq resources,
1395          * or some other error occurred, don't try to talk
1396          * to the port hardware.
1397          */
1398         if (!(tty->flags & (1 << TTY_IO_ERROR))) {
1399                 /*
1400                  * Make termios settings take effect.
1401                  */
1402                 uart_change_speed(state, NULL);
1403
1404                 /*
1405                  * And finally enable the RTS and DTR signals.
1406                  */
1407                 if (tty->termios->c_cflag & CBAUD)
1408                         uart_set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
1409         }
1410 }
1411
1412 /*
1413  * Block the open until the port is ready.  We must be called with
1414  * the per-port semaphore held.
1415  */
1416 static int
1417 uart_block_til_ready(struct file *filp, struct uart_state *state)
1418 {
1419         DECLARE_WAITQUEUE(wait, current);
1420         struct uart_info *info = state->info;
1421         struct uart_port *port = state->port;
1422         unsigned int mctrl;
1423
1424         info->blocked_open++;
1425         state->count--;
1426
1427         add_wait_queue(&info->open_wait, &wait);
1428         while (1) {
1429                 set_current_state(TASK_INTERRUPTIBLE);
1430
1431                 /*
1432                  * If we have been hung up, tell userspace/restart open.
1433                  */
1434                 if (tty_hung_up_p(filp) || info->tty == NULL)
1435                         break;
1436
1437                 /*
1438                  * If the port has been closed, tell userspace/restart open.
1439                  */
1440                 if (!(info->flags & UIF_INITIALIZED))
1441                         break;
1442
1443                 /*
1444                  * If non-blocking mode is set, or CLOCAL mode is set,
1445                  * we don't want to wait for the modem status lines to
1446                  * indicate that the port is ready.
1447                  *
1448                  * Also, if the port is not enabled/configured, we want
1449                  * to allow the open to succeed here.  Note that we will
1450                  * have set TTY_IO_ERROR for a non-existant port.
1451                  */
1452                 if ((filp->f_flags & O_NONBLOCK) ||
1453                     (info->tty->termios->c_cflag & CLOCAL) ||
1454                     (info->tty->flags & (1 << TTY_IO_ERROR))) {
1455                         break;
1456                 }
1457
1458                 /*
1459                  * Set DTR to allow modem to know we're waiting.  Do
1460                  * not set RTS here - we want to make sure we catch
1461                  * the data from the modem.
1462                  */
1463                 if (info->tty->termios->c_cflag & CBAUD)
1464                         uart_set_mctrl(port, TIOCM_DTR);
1465
1466                 /*
1467                  * and wait for the carrier to indicate that the
1468                  * modem is ready for us.
1469                  */
1470                 spin_lock_irq(&port->lock);
1471                 port->ops->enable_ms(port);
1472                 mctrl = port->ops->get_mctrl(port);
1473                 spin_unlock_irq(&port->lock);
1474                 if (mctrl & TIOCM_CAR)
1475                         break;
1476
1477                 mutex_unlock(&state->mutex);
1478                 schedule();
1479                 mutex_lock(&state->mutex);
1480
1481                 if (signal_pending(current))
1482                         break;
1483         }
1484         set_current_state(TASK_RUNNING);
1485         remove_wait_queue(&info->open_wait, &wait);
1486
1487         state->count++;
1488         info->blocked_open--;
1489
1490         if (signal_pending(current))
1491                 return -ERESTARTSYS;
1492
1493         if (!info->tty || tty_hung_up_p(filp))
1494                 return -EAGAIN;
1495
1496         return 0;
1497 }
1498
1499 static struct uart_state *uart_get(struct uart_driver *drv, int line)
1500 {
1501         struct uart_state *state;
1502         int ret = 0;
1503
1504         state = drv->state + line;
1505         if (mutex_lock_interruptible(&state->mutex)) {
1506                 ret = -ERESTARTSYS;
1507                 goto err;
1508         }
1509
1510         state->count++;
1511         if (!state->port || state->port->flags & UPF_DEAD) {
1512                 ret = -ENXIO;
1513                 goto err_unlock;
1514         }
1515
1516         if (!state->info) {
1517                 state->info = kmalloc(sizeof(struct uart_info), GFP_KERNEL);
1518                 if (state->info) {
1519                         memset(state->info, 0, sizeof(struct uart_info));
1520                         init_waitqueue_head(&state->info->open_wait);
1521                         init_waitqueue_head(&state->info->delta_msr_wait);
1522
1523                         /*
1524                          * Link the info into the other structures.
1525                          */
1526                         state->port->info = state->info;
1527
1528                         tasklet_init(&state->info->tlet, uart_tasklet_action,
1529                                      (unsigned long)state);
1530                 } else {
1531                         ret = -ENOMEM;
1532                         goto err_unlock;
1533                 }
1534         }
1535         return state;
1536
1537  err_unlock:
1538         state->count--;
1539         mutex_unlock(&state->mutex);
1540  err:
1541         return ERR_PTR(ret);
1542 }
1543
1544 /*
1545  * In 2.4.5, calls to uart_open are serialised by the BKL in
1546  *   linux/fs/devices.c:chrdev_open()
1547  * Note that if this fails, then uart_close() _will_ be called.
1548  *
1549  * In time, we want to scrap the "opening nonpresent ports"
1550  * behaviour and implement an alternative way for setserial
1551  * to set base addresses/ports/types.  This will allow us to
1552  * get rid of a certain amount of extra tests.
1553  */
1554 static int uart_open(struct tty_struct *tty, struct file *filp)
1555 {
1556         struct uart_driver *drv = (struct uart_driver *)tty->driver->driver_state;
1557         struct uart_state *state;
1558         int retval, line = tty->index;
1559
1560         BUG_ON(!kernel_locked());
1561         DPRINTK("uart_open(%d) called\n", line);
1562
1563         /*
1564          * tty->driver->num won't change, so we won't fail here with
1565          * tty->driver_data set to something non-NULL (and therefore
1566          * we won't get caught by uart_close()).
1567          */
1568         retval = -ENODEV;
1569         if (line >= tty->driver->num)
1570                 goto fail;
1571
1572         /*
1573          * We take the semaphore inside uart_get to guarantee that we won't
1574          * be re-entered while allocating the info structure, or while we
1575          * request any IRQs that the driver may need.  This also has the nice
1576          * side-effect that it delays the action of uart_hangup, so we can
1577          * guarantee that info->tty will always contain something reasonable.
1578          */
1579         state = uart_get(drv, line);
1580         if (IS_ERR(state)) {
1581                 retval = PTR_ERR(state);
1582                 goto fail;
1583         }
1584
1585         /*
1586          * Once we set tty->driver_data here, we are guaranteed that
1587          * uart_close() will decrement the driver module use count.
1588          * Any failures from here onwards should not touch the count.
1589          */
1590         tty->driver_data = state;
1591         tty->low_latency = (state->port->flags & UPF_LOW_LATENCY) ? 1 : 0;
1592         tty->alt_speed = 0;
1593         state->info->tty = tty;
1594
1595         /*
1596          * If the port is in the middle of closing, bail out now.
1597          */
1598         if (tty_hung_up_p(filp)) {
1599                 retval = -EAGAIN;
1600                 state->count--;
1601                 mutex_unlock(&state->mutex);
1602                 goto fail;
1603         }
1604
1605         /*
1606          * Make sure the device is in D0 state.
1607          */
1608         if (state->count == 1)
1609                 uart_change_pm(state, 0);
1610
1611         /*
1612          * Start up the serial port.
1613          */
1614         retval = uart_startup(state, 0);
1615
1616         /*
1617          * If we succeeded, wait until the port is ready.
1618          */
1619         if (retval == 0)
1620                 retval = uart_block_til_ready(filp, state);
1621         mutex_unlock(&state->mutex);
1622
1623         /*
1624          * If this is the first open to succeed, adjust things to suit.
1625          */
1626         if (retval == 0 && !(state->info->flags & UIF_NORMAL_ACTIVE)) {
1627                 state->info->flags |= UIF_NORMAL_ACTIVE;
1628
1629                 uart_update_termios(state);
1630         }
1631
1632  fail:
1633         return retval;
1634 }
1635
1636 static const char *uart_type(struct uart_port *port)
1637 {
1638         const char *str = NULL;
1639
1640         if (port->ops->type)
1641                 str = port->ops->type(port);
1642
1643         if (!str)
1644                 str = "unknown";
1645
1646         return str;
1647 }
1648
1649 #ifdef CONFIG_PROC_FS
1650
1651 static int uart_line_info(char *buf, struct uart_driver *drv, int i)
1652 {
1653         struct uart_state *state = drv->state + i;
1654         struct uart_port *port = state->port;
1655         char stat_buf[32];
1656         unsigned int status;
1657         int ret;
1658
1659         if (!port)
1660                 return 0;
1661
1662         ret = sprintf(buf, "%d: uart:%s %s%08lX irq:%d",
1663                         port->line, uart_type(port),
1664                         port->iotype == UPIO_MEM ? "mmio:0x" : "port:",
1665                         port->iotype == UPIO_MEM ? port->mapbase :
1666                                                 (unsigned long) port->iobase,
1667                         port->irq);
1668
1669         if (port->type == PORT_UNKNOWN) {
1670                 strcat(buf, "\n");
1671                 return ret + 1;
1672         }
1673
1674         if(capable(CAP_SYS_ADMIN))
1675         {
1676                 spin_lock_irq(&port->lock);
1677                 status = port->ops->get_mctrl(port);
1678                 spin_unlock_irq(&port->lock);
1679
1680                 ret += sprintf(buf + ret, " tx:%d rx:%d",
1681                                 port->icount.tx, port->icount.rx);
1682                 if (port->icount.frame)
1683                         ret += sprintf(buf + ret, " fe:%d",
1684                                 port->icount.frame);
1685                 if (port->icount.parity)
1686                         ret += sprintf(buf + ret, " pe:%d",
1687                                 port->icount.parity);
1688                 if (port->icount.brk)
1689                         ret += sprintf(buf + ret, " brk:%d",
1690                                 port->icount.brk);
1691                 if (port->icount.overrun)
1692                         ret += sprintf(buf + ret, " oe:%d",
1693                                 port->icount.overrun);
1694         
1695 #define INFOBIT(bit,str) \
1696         if (port->mctrl & (bit)) \
1697                 strncat(stat_buf, (str), sizeof(stat_buf) - \
1698                         strlen(stat_buf) - 2)
1699 #define STATBIT(bit,str) \
1700         if (status & (bit)) \
1701                 strncat(stat_buf, (str), sizeof(stat_buf) - \
1702                        strlen(stat_buf) - 2)
1703
1704                 stat_buf[0] = '\0';
1705                 stat_buf[1] = '\0';
1706                 INFOBIT(TIOCM_RTS, "|RTS");
1707                 STATBIT(TIOCM_CTS, "|CTS");
1708                 INFOBIT(TIOCM_DTR, "|DTR");
1709                 STATBIT(TIOCM_DSR, "|DSR");
1710                 STATBIT(TIOCM_CAR, "|CD");
1711                 STATBIT(TIOCM_RNG, "|RI");
1712                 if (stat_buf[0])
1713                         stat_buf[0] = ' ';
1714                 strcat(stat_buf, "\n");
1715         
1716                 ret += sprintf(buf + ret, stat_buf);
1717         } else {
1718                 strcat(buf, "\n");
1719                 ret++;
1720         }
1721 #undef STATBIT
1722 #undef INFOBIT
1723         return ret;
1724 }
1725
1726 static int uart_read_proc(char *page, char **start, off_t off,
1727                           int count, int *eof, void *data)
1728 {
1729         struct tty_driver *ttydrv = data;
1730         struct uart_driver *drv = ttydrv->driver_state;
1731         int i, len = 0, l;
1732         off_t begin = 0;
1733
1734         len += sprintf(page, "serinfo:1.0 driver%s%s revision:%s\n",
1735                         "", "", "");
1736         for (i = 0; i < drv->nr && len < PAGE_SIZE - 96; i++) {
1737                 l = uart_line_info(page + len, drv, i);
1738                 len += l;
1739                 if (len + begin > off + count)
1740                         goto done;
1741                 if (len + begin < off) {
1742                         begin += len;
1743                         len = 0;
1744                 }
1745         }
1746         *eof = 1;
1747  done:
1748         if (off >= len + begin)
1749                 return 0;
1750         *start = page + (off - begin);
1751         return (count < begin + len - off) ? count : (begin + len - off);
1752 }
1753 #endif
1754
1755 #ifdef CONFIG_SERIAL_CORE_CONSOLE
1756 /*
1757  *      uart_console_write - write a console message to a serial port
1758  *      @port: the port to write the message
1759  *      @s: array of characters
1760  *      @count: number of characters in string to write
1761  *      @write: function to write character to port
1762  */
1763 void uart_console_write(struct uart_port *port, const char *s,
1764                         unsigned int count,
1765                         void (*putchar)(struct uart_port *, int))
1766 {
1767         unsigned int i;
1768
1769         for (i = 0; i < count; i++, s++) {
1770                 if (*s == '\n')
1771                         putchar(port, '\r');
1772                 putchar(port, *s);
1773         }
1774 }
1775 EXPORT_SYMBOL_GPL(uart_console_write);
1776
1777 /*
1778  *      Check whether an invalid uart number has been specified, and
1779  *      if so, search for the first available port that does have
1780  *      console support.
1781  */
1782 struct uart_port * __init
1783 uart_get_console(struct uart_port *ports, int nr, struct console *co)
1784 {
1785         int idx = co->index;
1786
1787         if (idx < 0 || idx >= nr || (ports[idx].iobase == 0 &&
1788                                      ports[idx].membase == NULL))
1789                 for (idx = 0; idx < nr; idx++)
1790                         if (ports[idx].iobase != 0 ||
1791                             ports[idx].membase != NULL)
1792                                 break;
1793
1794         co->index = idx;
1795
1796         return ports + idx;
1797 }
1798
1799 /**
1800  *      uart_parse_options - Parse serial port baud/parity/bits/flow contro.
1801  *      @options: pointer to option string
1802  *      @baud: pointer to an 'int' variable for the baud rate.
1803  *      @parity: pointer to an 'int' variable for the parity.
1804  *      @bits: pointer to an 'int' variable for the number of data bits.
1805  *      @flow: pointer to an 'int' variable for the flow control character.
1806  *
1807  *      uart_parse_options decodes a string containing the serial console
1808  *      options.  The format of the string is <baud><parity><bits><flow>,
1809  *      eg: 115200n8r
1810  */
1811 void __init
1812 uart_parse_options(char *options, int *baud, int *parity, int *bits, int *flow)
1813 {
1814         char *s = options;
1815
1816         *baud = simple_strtoul(s, NULL, 10);
1817         while (*s >= '0' && *s <= '9')
1818                 s++;
1819         if (*s)
1820                 *parity = *s++;
1821         if (*s)
1822                 *bits = *s++ - '0';
1823         if (*s)
1824                 *flow = *s;
1825 }
1826
1827 struct baud_rates {
1828         unsigned int rate;
1829         unsigned int cflag;
1830 };
1831
1832 static const struct baud_rates baud_rates[] = {
1833         { 921600, B921600 },
1834         { 460800, B460800 },
1835         { 230400, B230400 },
1836         { 115200, B115200 },
1837         {  57600, B57600  },
1838         {  38400, B38400  },
1839         {  19200, B19200  },
1840         {   9600, B9600   },
1841         {   4800, B4800   },
1842         {   2400, B2400   },
1843         {   1200, B1200   },
1844         {      0, B38400  }
1845 };
1846
1847 /**
1848  *      uart_set_options - setup the serial console parameters
1849  *      @port: pointer to the serial ports uart_port structure
1850  *      @co: console pointer
1851  *      @baud: baud rate
1852  *      @parity: parity character - 'n' (none), 'o' (odd), 'e' (even)
1853  *      @bits: number of data bits
1854  *      @flow: flow control character - 'r' (rts)
1855  */
1856 int __init
1857 uart_set_options(struct uart_port *port, struct console *co,
1858                  int baud, int parity, int bits, int flow)
1859 {
1860         struct termios termios;
1861         int i;
1862
1863         /*
1864          * Ensure that the serial console lock is initialised
1865          * early.
1866          */
1867         spin_lock_init(&port->lock);
1868
1869         memset(&termios, 0, sizeof(struct termios));
1870
1871         termios.c_cflag = CREAD | HUPCL | CLOCAL;
1872
1873         /*
1874          * Construct a cflag setting.
1875          */
1876         for (i = 0; baud_rates[i].rate; i++)
1877                 if (baud_rates[i].rate <= baud)
1878                         break;
1879
1880         termios.c_cflag |= baud_rates[i].cflag;
1881
1882         if (bits == 7)
1883                 termios.c_cflag |= CS7;
1884         else
1885                 termios.c_cflag |= CS8;
1886
1887         switch (parity) {
1888         case 'o': case 'O':
1889                 termios.c_cflag |= PARODD;
1890                 /*fall through*/
1891         case 'e': case 'E':
1892                 termios.c_cflag |= PARENB;
1893                 break;
1894         }
1895
1896         if (flow == 'r')
1897                 termios.c_cflag |= CRTSCTS;
1898
1899         port->ops->set_termios(port, &termios, NULL);
1900         co->cflag = termios.c_cflag;
1901
1902         return 0;
1903 }
1904 #endif /* CONFIG_SERIAL_CORE_CONSOLE */
1905
1906 static void uart_change_pm(struct uart_state *state, int pm_state)
1907 {
1908         struct uart_port *port = state->port;
1909
1910         if (state->pm_state != pm_state) {
1911                 if (port->ops->pm)
1912                         port->ops->pm(port, pm_state, state->pm_state);
1913                 state->pm_state = pm_state;
1914         }
1915 }
1916
1917 int uart_suspend_port(struct uart_driver *drv, struct uart_port *port)
1918 {
1919         struct uart_state *state = drv->state + port->line;
1920
1921         mutex_lock(&state->mutex);
1922
1923         if (state->info && state->info->flags & UIF_INITIALIZED) {
1924                 const struct uart_ops *ops = port->ops;
1925
1926                 spin_lock_irq(&port->lock);
1927                 ops->stop_tx(port);
1928                 ops->set_mctrl(port, 0);
1929                 ops->stop_rx(port);
1930                 spin_unlock_irq(&port->lock);
1931
1932                 /*
1933                  * Wait for the transmitter to empty.
1934                  */
1935                 while (!ops->tx_empty(port)) {
1936                         msleep(10);
1937                 }
1938
1939                 ops->shutdown(port);
1940         }
1941
1942         /*
1943          * Disable the console device before suspending.
1944          */
1945         if (uart_console(port))
1946                 console_stop(port->cons);
1947
1948         uart_change_pm(state, 3);
1949
1950         mutex_unlock(&state->mutex);
1951
1952         return 0;
1953 }
1954
1955 int uart_resume_port(struct uart_driver *drv, struct uart_port *port)
1956 {
1957         struct uart_state *state = drv->state + port->line;
1958
1959         mutex_lock(&state->mutex);
1960
1961         uart_change_pm(state, 0);
1962
1963         /*
1964          * Re-enable the console device after suspending.
1965          */
1966         if (uart_console(port)) {
1967                 struct termios termios;
1968
1969                 /*
1970                  * First try to use the console cflag setting.
1971                  */
1972                 memset(&termios, 0, sizeof(struct termios));
1973                 termios.c_cflag = port->cons->cflag;
1974
1975                 /*
1976                  * If that's unset, use the tty termios setting.
1977                  */
1978                 if (state->info && state->info->tty && termios.c_cflag == 0)
1979                         termios = *state->info->tty->termios;
1980
1981                 port->ops->set_termios(port, &termios, NULL);
1982                 console_start(port->cons);
1983         }
1984
1985         if (state->info && state->info->flags & UIF_INITIALIZED) {
1986                 const struct uart_ops *ops = port->ops;
1987                 int ret;
1988
1989                 ops->set_mctrl(port, 0);
1990                 ret = ops->startup(port);
1991                 if (ret == 0) {
1992                         uart_change_speed(state, NULL);
1993                         spin_lock_irq(&port->lock);
1994                         ops->set_mctrl(port, port->mctrl);
1995                         ops->start_tx(port);
1996                         spin_unlock_irq(&port->lock);
1997                 } else {
1998                         /*
1999                          * Failed to resume - maybe hardware went away?
2000                          * Clear the "initialized" flag so we won't try
2001                          * to call the low level drivers shutdown method.
2002                          */
2003                         state->info->flags &= ~UIF_INITIALIZED;
2004                         uart_shutdown(state);
2005                 }
2006         }
2007
2008         mutex_unlock(&state->mutex);
2009
2010         return 0;
2011 }
2012
2013 static inline void
2014 uart_report_port(struct uart_driver *drv, struct uart_port *port)
2015 {
2016         char address[64];
2017
2018         switch (port->iotype) {
2019         case UPIO_PORT:
2020                 snprintf(address, sizeof(address),
2021                          "I/O 0x%x", port->iobase);
2022                 break;
2023         case UPIO_HUB6:
2024                 snprintf(address, sizeof(address),
2025                          "I/O 0x%x offset 0x%x", port->iobase, port->hub6);
2026                 break;
2027         case UPIO_MEM:
2028         case UPIO_MEM32:
2029         case UPIO_AU:
2030                 snprintf(address, sizeof(address),
2031                          "MMIO 0x%lx", port->mapbase);
2032                 break;
2033         default:
2034                 strlcpy(address, "*unknown*", sizeof(address));
2035                 break;
2036         }
2037
2038         printk(KERN_INFO "%s%s%s%d at %s (irq = %d) is a %s\n",
2039                port->dev ? port->dev->bus_id : "",
2040                port->dev ? ": " : "",
2041                drv->dev_name, port->line, address, port->irq, uart_type(port));
2042 }
2043
2044 static void
2045 uart_configure_port(struct uart_driver *drv, struct uart_state *state,
2046                     struct uart_port *port)
2047 {
2048         unsigned int flags;
2049
2050         /*
2051          * If there isn't a port here, don't do anything further.
2052          */
2053         if (!port->iobase && !port->mapbase && !port->membase)
2054                 return;
2055
2056         /*
2057          * Now do the auto configuration stuff.  Note that config_port
2058          * is expected to claim the resources and map the port for us.
2059          */
2060         flags = UART_CONFIG_TYPE;
2061         if (port->flags & UPF_AUTO_IRQ)
2062                 flags |= UART_CONFIG_IRQ;
2063         if (port->flags & UPF_BOOT_AUTOCONF) {
2064                 port->type = PORT_UNKNOWN;
2065                 port->ops->config_port(port, flags);
2066         }
2067
2068         if (port->type != PORT_UNKNOWN) {
2069                 unsigned long flags;
2070
2071                 uart_report_port(drv, port);
2072
2073                 /*
2074                  * Ensure that the modem control lines are de-activated.
2075                  * We probably don't need a spinlock around this, but
2076                  */
2077                 spin_lock_irqsave(&port->lock, flags);
2078                 port->ops->set_mctrl(port, 0);
2079                 spin_unlock_irqrestore(&port->lock, flags);
2080
2081                 /*
2082                  * Power down all ports by default, except the
2083                  * console if we have one.
2084                  */
2085                 if (!uart_console(port))
2086                         uart_change_pm(state, 3);
2087         }
2088 }
2089
2090 static struct tty_operations uart_ops = {
2091         .open           = uart_open,
2092         .close          = uart_close,
2093         .write          = uart_write,
2094         .put_char       = uart_put_char,
2095         .flush_chars    = uart_flush_chars,
2096         .write_room     = uart_write_room,
2097         .chars_in_buffer= uart_chars_in_buffer,
2098         .flush_buffer   = uart_flush_buffer,
2099         .ioctl          = uart_ioctl,
2100         .throttle       = uart_throttle,
2101         .unthrottle     = uart_unthrottle,
2102         .send_xchar     = uart_send_xchar,
2103         .set_termios    = uart_set_termios,
2104         .stop           = uart_stop,
2105         .start          = uart_start,
2106         .hangup         = uart_hangup,
2107         .break_ctl      = uart_break_ctl,
2108         .wait_until_sent= uart_wait_until_sent,
2109 #ifdef CONFIG_PROC_FS
2110         .read_proc      = uart_read_proc,
2111 #endif
2112         .tiocmget       = uart_tiocmget,
2113         .tiocmset       = uart_tiocmset,
2114 };
2115
2116 /**
2117  *      uart_register_driver - register a driver with the uart core layer
2118  *      @drv: low level driver structure
2119  *
2120  *      Register a uart driver with the core driver.  We in turn register
2121  *      with the tty layer, and initialise the core driver per-port state.
2122  *
2123  *      We have a proc file in /proc/tty/driver which is named after the
2124  *      normal driver.
2125  *
2126  *      drv->port should be NULL, and the per-port structures should be
2127  *      registered using uart_add_one_port after this call has succeeded.
2128  */
2129 int uart_register_driver(struct uart_driver *drv)
2130 {
2131         struct tty_driver *normal = NULL;
2132         int i, retval;
2133
2134         BUG_ON(drv->state);
2135
2136         /*
2137          * Maybe we should be using a slab cache for this, especially if
2138          * we have a large number of ports to handle.
2139          */
2140         drv->state = kmalloc(sizeof(struct uart_state) * drv->nr, GFP_KERNEL);
2141         retval = -ENOMEM;
2142         if (!drv->state)
2143                 goto out;
2144
2145         memset(drv->state, 0, sizeof(struct uart_state) * drv->nr);
2146
2147         normal  = alloc_tty_driver(drv->nr);
2148         if (!normal)
2149                 goto out;
2150
2151         drv->tty_driver = normal;
2152
2153         normal->owner           = drv->owner;
2154         normal->driver_name     = drv->driver_name;
2155         normal->name            = drv->dev_name;
2156         normal->major           = drv->major;
2157         normal->minor_start     = drv->minor;
2158         normal->type            = TTY_DRIVER_TYPE_SERIAL;
2159         normal->subtype         = SERIAL_TYPE_NORMAL;
2160         normal->init_termios    = tty_std_termios;
2161         normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
2162         normal->flags           = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
2163         normal->driver_state    = drv;
2164         tty_set_operations(normal, &uart_ops);
2165
2166         /*
2167          * Initialise the UART state(s).
2168          */
2169         for (i = 0; i < drv->nr; i++) {
2170                 struct uart_state *state = drv->state + i;
2171
2172                 state->close_delay     = 500;   /* .5 seconds */
2173                 state->closing_wait    = 30000; /* 30 seconds */
2174
2175                 mutex_init(&state->mutex);
2176         }
2177
2178         retval = tty_register_driver(normal);
2179  out:
2180         if (retval < 0) {
2181                 put_tty_driver(normal);
2182                 kfree(drv->state);
2183         }
2184         return retval;
2185 }
2186
2187 /**
2188  *      uart_unregister_driver - remove a driver from the uart core layer
2189  *      @drv: low level driver structure
2190  *
2191  *      Remove all references to a driver from the core driver.  The low
2192  *      level driver must have removed all its ports via the
2193  *      uart_remove_one_port() if it registered them with uart_add_one_port().
2194  *      (ie, drv->port == NULL)
2195  */
2196 void uart_unregister_driver(struct uart_driver *drv)
2197 {
2198         struct tty_driver *p = drv->tty_driver;
2199         tty_unregister_driver(p);
2200         put_tty_driver(p);
2201         kfree(drv->state);
2202         drv->tty_driver = NULL;
2203 }
2204
2205 struct tty_driver *uart_console_device(struct console *co, int *index)
2206 {
2207         struct uart_driver *p = co->data;
2208         *index = co->index;
2209         return p->tty_driver;
2210 }
2211
2212 /**
2213  *      uart_add_one_port - attach a driver-defined port structure
2214  *      @drv: pointer to the uart low level driver structure for this port
2215  *      @port: uart port structure to use for this port.
2216  *
2217  *      This allows the driver to register its own uart_port structure
2218  *      with the core driver.  The main purpose is to allow the low
2219  *      level uart drivers to expand uart_port, rather than having yet
2220  *      more levels of structures.
2221  */
2222 int uart_add_one_port(struct uart_driver *drv, struct uart_port *port)
2223 {
2224         struct uart_state *state;
2225         int ret = 0;
2226
2227         BUG_ON(in_interrupt());
2228
2229         if (port->line >= drv->nr)
2230                 return -EINVAL;
2231
2232         state = drv->state + port->line;
2233
2234         mutex_lock(&port_mutex);
2235         mutex_lock(&state->mutex);
2236         if (state->port) {
2237                 ret = -EINVAL;
2238                 goto out;
2239         }
2240
2241         state->port = port;
2242
2243         port->cons = drv->cons;
2244         port->info = state->info;
2245
2246         /*
2247          * If this port is a console, then the spinlock is already
2248          * initialised.
2249          */
2250         if (!(uart_console(port) && (port->cons->flags & CON_ENABLED)))
2251                 spin_lock_init(&port->lock);
2252
2253         uart_configure_port(drv, state, port);
2254
2255         /*
2256          * Register the port whether it's detected or not.  This allows
2257          * setserial to be used to alter this ports parameters.
2258          */
2259         tty_register_device(drv->tty_driver, port->line, port->dev);
2260
2261         /*
2262          * If this driver supports console, and it hasn't been
2263          * successfully registered yet, try to re-register it.
2264          * It may be that the port was not available.
2265          */
2266         if (port->type != PORT_UNKNOWN &&
2267             port->cons && !(port->cons->flags & CON_ENABLED))
2268                 register_console(port->cons);
2269
2270         /*
2271          * Ensure UPF_DEAD is not set.
2272          */
2273         port->flags &= ~UPF_DEAD;
2274
2275  out:
2276         mutex_unlock(&state->mutex);
2277         mutex_unlock(&port_mutex);
2278
2279         return ret;
2280 }
2281
2282 /**
2283  *      uart_remove_one_port - detach a driver defined port structure
2284  *      @drv: pointer to the uart low level driver structure for this port
2285  *      @port: uart port structure for this port
2286  *
2287  *      This unhooks (and hangs up) the specified port structure from the
2288  *      core driver.  No further calls will be made to the low-level code
2289  *      for this port.
2290  */
2291 int uart_remove_one_port(struct uart_driver *drv, struct uart_port *port)
2292 {
2293         struct uart_state *state = drv->state + port->line;
2294         struct uart_info *info;
2295
2296         BUG_ON(in_interrupt());
2297
2298         if (state->port != port)
2299                 printk(KERN_ALERT "Removing wrong port: %p != %p\n",
2300                         state->port, port);
2301
2302         mutex_lock(&port_mutex);
2303
2304         /*
2305          * Mark the port "dead" - this prevents any opens from
2306          * succeeding while we shut down the port.
2307          */
2308         mutex_lock(&state->mutex);
2309         port->flags |= UPF_DEAD;
2310         mutex_unlock(&state->mutex);
2311
2312         /*
2313          * Remove the devices from the tty layer
2314          */
2315         tty_unregister_device(drv->tty_driver, port->line);
2316
2317         info = state->info;
2318         if (info && info->tty)
2319                 tty_vhangup(info->tty);
2320
2321         /*
2322          * All users of this port should now be disconnected from
2323          * this driver, and the port shut down.  We should be the
2324          * only thread fiddling with this port from now on.
2325          */
2326         state->info = NULL;
2327
2328         /*
2329          * Free the port IO and memory resources, if any.
2330          */
2331         if (port->type != PORT_UNKNOWN)
2332                 port->ops->release_port(port);
2333
2334         /*
2335          * Indicate that there isn't a port here anymore.
2336          */
2337         port->type = PORT_UNKNOWN;
2338
2339         /*
2340          * Kill the tasklet, and free resources.
2341          */
2342         if (info) {
2343                 tasklet_kill(&info->tlet);
2344                 kfree(info);
2345         }
2346
2347         state->port = NULL;
2348         mutex_unlock(&port_mutex);
2349
2350         return 0;
2351 }
2352
2353 /*
2354  *      Are the two ports equivalent?
2355  */
2356 int uart_match_port(struct uart_port *port1, struct uart_port *port2)
2357 {
2358         if (port1->iotype != port2->iotype)
2359                 return 0;
2360
2361         switch (port1->iotype) {
2362         case UPIO_PORT:
2363                 return (port1->iobase == port2->iobase);
2364         case UPIO_HUB6:
2365                 return (port1->iobase == port2->iobase) &&
2366                        (port1->hub6   == port2->hub6);
2367         case UPIO_MEM:
2368                 return (port1->mapbase == port2->mapbase);
2369         }
2370         return 0;
2371 }
2372 EXPORT_SYMBOL(uart_match_port);
2373
2374 EXPORT_SYMBOL(uart_write_wakeup);
2375 EXPORT_SYMBOL(uart_register_driver);
2376 EXPORT_SYMBOL(uart_unregister_driver);
2377 EXPORT_SYMBOL(uart_suspend_port);
2378 EXPORT_SYMBOL(uart_resume_port);
2379 EXPORT_SYMBOL(uart_add_one_port);
2380 EXPORT_SYMBOL(uart_remove_one_port);
2381
2382 MODULE_DESCRIPTION("Serial driver core");
2383 MODULE_LICENSE("GPL");