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