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