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