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