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