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