Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0+
0002 /*
0003  *  Driver core for serial ports
0004  *
0005  *  Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
0006  *
0007  *  Copyright 1999 ARM Limited
0008  *  Copyright (C) 2000-2001 Deep Blue Solutions Ltd.
0009  */
0010 #include <linux/module.h>
0011 #include <linux/tty.h>
0012 #include <linux/tty_flip.h>
0013 #include <linux/slab.h>
0014 #include <linux/sched/signal.h>
0015 #include <linux/init.h>
0016 #include <linux/console.h>
0017 #include <linux/gpio/consumer.h>
0018 #include <linux/of.h>
0019 #include <linux/proc_fs.h>
0020 #include <linux/seq_file.h>
0021 #include <linux/device.h>
0022 #include <linux/serial.h> /* for serial_state and serial_icounter_struct */
0023 #include <linux/serial_core.h>
0024 #include <linux/sysrq.h>
0025 #include <linux/delay.h>
0026 #include <linux/mutex.h>
0027 #include <linux/math64.h>
0028 #include <linux/security.h>
0029 
0030 #include <linux/irq.h>
0031 #include <linux/uaccess.h>
0032 
0033 /*
0034  * This is used to lock changes in serial line configuration.
0035  */
0036 static DEFINE_MUTEX(port_mutex);
0037 
0038 /*
0039  * lockdep: port->lock is initialized in two places, but we
0040  *          want only one lock-class:
0041  */
0042 static struct lock_class_key port_lock_key;
0043 
0044 #define HIGH_BITS_OFFSET    ((sizeof(long)-sizeof(int))*8)
0045 
0046 /*
0047  * Max time with active RTS before/after data is sent.
0048  */
0049 #define RS485_MAX_RTS_DELAY 100 /* msecs */
0050 
0051 static void uart_change_speed(struct tty_struct *tty, struct uart_state *state,
0052                     struct ktermios *old_termios);
0053 static void uart_wait_until_sent(struct tty_struct *tty, int timeout);
0054 static void uart_change_pm(struct uart_state *state,
0055                enum uart_pm_state pm_state);
0056 
0057 static void uart_port_shutdown(struct tty_port *port);
0058 
0059 static int uart_dcd_enabled(struct uart_port *uport)
0060 {
0061     return !!(uport->status & UPSTAT_DCD_ENABLE);
0062 }
0063 
0064 static inline struct uart_port *uart_port_ref(struct uart_state *state)
0065 {
0066     if (atomic_add_unless(&state->refcount, 1, 0))
0067         return state->uart_port;
0068     return NULL;
0069 }
0070 
0071 static inline void uart_port_deref(struct uart_port *uport)
0072 {
0073     if (atomic_dec_and_test(&uport->state->refcount))
0074         wake_up(&uport->state->remove_wait);
0075 }
0076 
0077 #define uart_port_lock(state, flags)                    \
0078     ({                              \
0079         struct uart_port *__uport = uart_port_ref(state);   \
0080         if (__uport)                        \
0081             spin_lock_irqsave(&__uport->lock, flags);   \
0082         __uport;                        \
0083     })
0084 
0085 #define uart_port_unlock(uport, flags)                  \
0086     ({                              \
0087         struct uart_port *__uport = uport;          \
0088         if (__uport) {                      \
0089             spin_unlock_irqrestore(&__uport->lock, flags);  \
0090             uart_port_deref(__uport);           \
0091         }                           \
0092     })
0093 
0094 static inline struct uart_port *uart_port_check(struct uart_state *state)
0095 {
0096     lockdep_assert_held(&state->port.mutex);
0097     return state->uart_port;
0098 }
0099 
0100 /**
0101  * uart_write_wakeup - schedule write processing
0102  * @port: port to be processed
0103  *
0104  * This routine is used by the interrupt handler to schedule processing in the
0105  * software interrupt portion of the driver. A driver is expected to call this
0106  * function when the number of characters in the transmit buffer have dropped
0107  * below a threshold.
0108  *
0109  * Locking: @port->lock should be held
0110  */
0111 void uart_write_wakeup(struct uart_port *port)
0112 {
0113     struct uart_state *state = port->state;
0114     /*
0115      * This means you called this function _after_ the port was
0116      * closed.  No cookie for you.
0117      */
0118     BUG_ON(!state);
0119     tty_port_tty_wakeup(&state->port);
0120 }
0121 EXPORT_SYMBOL(uart_write_wakeup);
0122 
0123 static void uart_stop(struct tty_struct *tty)
0124 {
0125     struct uart_state *state = tty->driver_data;
0126     struct uart_port *port;
0127     unsigned long flags;
0128 
0129     port = uart_port_lock(state, flags);
0130     if (port)
0131         port->ops->stop_tx(port);
0132     uart_port_unlock(port, flags);
0133 }
0134 
0135 static void __uart_start(struct tty_struct *tty)
0136 {
0137     struct uart_state *state = tty->driver_data;
0138     struct uart_port *port = state->uart_port;
0139 
0140     if (port && !uart_tx_stopped(port))
0141         port->ops->start_tx(port);
0142 }
0143 
0144 static void uart_start(struct tty_struct *tty)
0145 {
0146     struct uart_state *state = tty->driver_data;
0147     struct uart_port *port;
0148     unsigned long flags;
0149 
0150     port = uart_port_lock(state, flags);
0151     __uart_start(tty);
0152     uart_port_unlock(port, flags);
0153 }
0154 
0155 static void
0156 uart_update_mctrl(struct uart_port *port, unsigned int set, unsigned int clear)
0157 {
0158     unsigned long flags;
0159     unsigned int old;
0160 
0161     if (port->rs485.flags & SER_RS485_ENABLED) {
0162         set &= ~TIOCM_RTS;
0163         clear &= ~TIOCM_RTS;
0164     }
0165 
0166     spin_lock_irqsave(&port->lock, flags);
0167     old = port->mctrl;
0168     port->mctrl = (old & ~clear) | set;
0169     if (old != port->mctrl)
0170         port->ops->set_mctrl(port, port->mctrl);
0171     spin_unlock_irqrestore(&port->lock, flags);
0172 }
0173 
0174 #define uart_set_mctrl(port, set)   uart_update_mctrl(port, set, 0)
0175 #define uart_clear_mctrl(port, clear)   uart_update_mctrl(port, 0, clear)
0176 
0177 static void uart_port_dtr_rts(struct uart_port *uport, int raise)
0178 {
0179     if (raise)
0180         uart_set_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
0181     else
0182         uart_clear_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
0183 }
0184 
0185 /*
0186  * Startup the port.  This will be called once per open.  All calls
0187  * will be serialised by the per-port mutex.
0188  */
0189 static int uart_port_startup(struct tty_struct *tty, struct uart_state *state,
0190         int init_hw)
0191 {
0192     struct uart_port *uport = uart_port_check(state);
0193     unsigned long flags;
0194     unsigned long page;
0195     int retval = 0;
0196 
0197     if (uport->type == PORT_UNKNOWN)
0198         return 1;
0199 
0200     /*
0201      * Make sure the device is in D0 state.
0202      */
0203     uart_change_pm(state, UART_PM_STATE_ON);
0204 
0205     /*
0206      * Initialise and allocate the transmit and temporary
0207      * buffer.
0208      */
0209     page = get_zeroed_page(GFP_KERNEL);
0210     if (!page)
0211         return -ENOMEM;
0212 
0213     uart_port_lock(state, flags);
0214     if (!state->xmit.buf) {
0215         state->xmit.buf = (unsigned char *) page;
0216         uart_circ_clear(&state->xmit);
0217         uart_port_unlock(uport, flags);
0218     } else {
0219         uart_port_unlock(uport, flags);
0220         /*
0221          * Do not free() the page under the port lock, see
0222          * uart_shutdown().
0223          */
0224         free_page(page);
0225     }
0226 
0227     retval = uport->ops->startup(uport);
0228     if (retval == 0) {
0229         if (uart_console(uport) && uport->cons->cflag) {
0230             tty->termios.c_cflag = uport->cons->cflag;
0231             tty->termios.c_ispeed = uport->cons->ispeed;
0232             tty->termios.c_ospeed = uport->cons->ospeed;
0233             uport->cons->cflag = 0;
0234             uport->cons->ispeed = 0;
0235             uport->cons->ospeed = 0;
0236         }
0237         /*
0238          * Initialise the hardware port settings.
0239          */
0240         uart_change_speed(tty, state, NULL);
0241 
0242         /*
0243          * Setup the RTS and DTR signals once the
0244          * port is open and ready to respond.
0245          */
0246         if (init_hw && C_BAUD(tty))
0247             uart_port_dtr_rts(uport, 1);
0248     }
0249 
0250     /*
0251      * This is to allow setserial on this port. People may want to set
0252      * port/irq/type and then reconfigure the port properly if it failed
0253      * now.
0254      */
0255     if (retval && capable(CAP_SYS_ADMIN))
0256         return 1;
0257 
0258     return retval;
0259 }
0260 
0261 static int uart_startup(struct tty_struct *tty, struct uart_state *state,
0262         int init_hw)
0263 {
0264     struct tty_port *port = &state->port;
0265     int retval;
0266 
0267     if (tty_port_initialized(port))
0268         return 0;
0269 
0270     retval = uart_port_startup(tty, state, init_hw);
0271     if (retval)
0272         set_bit(TTY_IO_ERROR, &tty->flags);
0273 
0274     return retval;
0275 }
0276 
0277 /*
0278  * This routine will shutdown a serial port; interrupts are disabled, and
0279  * DTR is dropped if the hangup on close termio flag is on.  Calls to
0280  * uart_shutdown are serialised by the per-port semaphore.
0281  *
0282  * uport == NULL if uart_port has already been removed
0283  */
0284 static void uart_shutdown(struct tty_struct *tty, struct uart_state *state)
0285 {
0286     struct uart_port *uport = uart_port_check(state);
0287     struct tty_port *port = &state->port;
0288     unsigned long flags;
0289     char *xmit_buf = NULL;
0290 
0291     /*
0292      * Set the TTY IO error marker
0293      */
0294     if (tty)
0295         set_bit(TTY_IO_ERROR, &tty->flags);
0296 
0297     if (tty_port_initialized(port)) {
0298         tty_port_set_initialized(port, 0);
0299 
0300         /*
0301          * Turn off DTR and RTS early.
0302          */
0303         if (uport && uart_console(uport) && tty) {
0304             uport->cons->cflag = tty->termios.c_cflag;
0305             uport->cons->ispeed = tty->termios.c_ispeed;
0306             uport->cons->ospeed = tty->termios.c_ospeed;
0307         }
0308 
0309         if (!tty || C_HUPCL(tty))
0310             uart_port_dtr_rts(uport, 0);
0311 
0312         uart_port_shutdown(port);
0313     }
0314 
0315     /*
0316      * It's possible for shutdown to be called after suspend if we get
0317      * a DCD drop (hangup) at just the right time.  Clear suspended bit so
0318      * we don't try to resume a port that has been shutdown.
0319      */
0320     tty_port_set_suspended(port, 0);
0321 
0322     /*
0323      * Do not free() the transmit buffer page under the port lock since
0324      * this can create various circular locking scenarios. For instance,
0325      * console driver may need to allocate/free a debug object, which
0326      * can endup in printk() recursion.
0327      */
0328     uart_port_lock(state, flags);
0329     xmit_buf = state->xmit.buf;
0330     state->xmit.buf = NULL;
0331     uart_port_unlock(uport, flags);
0332 
0333     free_page((unsigned long)xmit_buf);
0334 }
0335 
0336 /**
0337  * uart_update_timeout - update per-port frame timing information
0338  * @port: uart_port structure describing the port
0339  * @cflag: termios cflag value
0340  * @baud: speed of the port
0341  *
0342  * Set the @port frame timing information from which the FIFO timeout value is
0343  * derived. The @cflag value should reflect the actual hardware settings as
0344  * number of bits, parity, stop bits and baud rate is taken into account here.
0345  *
0346  * Locking: caller is expected to take @port->lock
0347  */
0348 void
0349 uart_update_timeout(struct uart_port *port, unsigned int cflag,
0350             unsigned int baud)
0351 {
0352     unsigned int size = tty_get_frame_size(cflag);
0353     u64 frame_time;
0354 
0355     frame_time = (u64)size * NSEC_PER_SEC;
0356     port->frame_time = DIV64_U64_ROUND_UP(frame_time, baud);
0357 }
0358 EXPORT_SYMBOL(uart_update_timeout);
0359 
0360 /**
0361  * uart_get_baud_rate - return baud rate for a particular port
0362  * @port: uart_port structure describing the port in question.
0363  * @termios: desired termios settings
0364  * @old: old termios (or %NULL)
0365  * @min: minimum acceptable baud rate
0366  * @max: maximum acceptable baud rate
0367  *
0368  * Decode the termios structure into a numeric baud rate, taking account of the
0369  * magic 38400 baud rate (with spd_* flags), and mapping the %B0 rate to 9600
0370  * baud.
0371  *
0372  * If the new baud rate is invalid, try the @old termios setting. If it's still
0373  * invalid, we try 9600 baud.
0374  *
0375  * The @termios structure is updated to reflect the baud rate we're actually
0376  * going to be using. Don't do this for the case where B0 is requested ("hang
0377  * up").
0378  *
0379  * Locking: caller dependent
0380  */
0381 unsigned int
0382 uart_get_baud_rate(struct uart_port *port, struct ktermios *termios,
0383            struct ktermios *old, unsigned int min, unsigned int max)
0384 {
0385     unsigned int try;
0386     unsigned int baud;
0387     unsigned int altbaud;
0388     int hung_up = 0;
0389     upf_t flags = port->flags & UPF_SPD_MASK;
0390 
0391     switch (flags) {
0392     case UPF_SPD_HI:
0393         altbaud = 57600;
0394         break;
0395     case UPF_SPD_VHI:
0396         altbaud = 115200;
0397         break;
0398     case UPF_SPD_SHI:
0399         altbaud = 230400;
0400         break;
0401     case UPF_SPD_WARP:
0402         altbaud = 460800;
0403         break;
0404     default:
0405         altbaud = 38400;
0406         break;
0407     }
0408 
0409     for (try = 0; try < 2; try++) {
0410         baud = tty_termios_baud_rate(termios);
0411 
0412         /*
0413          * The spd_hi, spd_vhi, spd_shi, spd_warp kludge...
0414          * Die! Die! Die!
0415          */
0416         if (try == 0 && baud == 38400)
0417             baud = altbaud;
0418 
0419         /*
0420          * Special case: B0 rate.
0421          */
0422         if (baud == 0) {
0423             hung_up = 1;
0424             baud = 9600;
0425         }
0426 
0427         if (baud >= min && baud <= max)
0428             return baud;
0429 
0430         /*
0431          * Oops, the quotient was zero.  Try again with
0432          * the old baud rate if possible.
0433          */
0434         termios->c_cflag &= ~CBAUD;
0435         if (old) {
0436             baud = tty_termios_baud_rate(old);
0437             if (!hung_up)
0438                 tty_termios_encode_baud_rate(termios,
0439                                 baud, baud);
0440             old = NULL;
0441             continue;
0442         }
0443 
0444         /*
0445          * As a last resort, if the range cannot be met then clip to
0446          * the nearest chip supported rate.
0447          */
0448         if (!hung_up) {
0449             if (baud <= min)
0450                 tty_termios_encode_baud_rate(termios,
0451                             min + 1, min + 1);
0452             else
0453                 tty_termios_encode_baud_rate(termios,
0454                             max - 1, max - 1);
0455         }
0456     }
0457     /* Should never happen */
0458     WARN_ON(1);
0459     return 0;
0460 }
0461 EXPORT_SYMBOL(uart_get_baud_rate);
0462 
0463 /**
0464  * uart_get_divisor - return uart clock divisor
0465  * @port: uart_port structure describing the port
0466  * @baud: desired baud rate
0467  *
0468  * Calculate the divisor (baud_base / baud) for the specified @baud,
0469  * appropriately rounded.
0470  *
0471  * If 38400 baud and custom divisor is selected, return the custom divisor
0472  * instead.
0473  *
0474  * Locking: caller dependent
0475  */
0476 unsigned int
0477 uart_get_divisor(struct uart_port *port, unsigned int baud)
0478 {
0479     unsigned int quot;
0480 
0481     /*
0482      * Old custom speed handling.
0483      */
0484     if (baud == 38400 && (port->flags & UPF_SPD_MASK) == UPF_SPD_CUST)
0485         quot = port->custom_divisor;
0486     else
0487         quot = DIV_ROUND_CLOSEST(port->uartclk, 16 * baud);
0488 
0489     return quot;
0490 }
0491 EXPORT_SYMBOL(uart_get_divisor);
0492 
0493 /* Caller holds port mutex */
0494 static void uart_change_speed(struct tty_struct *tty, struct uart_state *state,
0495                     struct ktermios *old_termios)
0496 {
0497     struct uart_port *uport = uart_port_check(state);
0498     struct ktermios *termios;
0499     int hw_stopped;
0500 
0501     /*
0502      * If we have no tty, termios, or the port does not exist,
0503      * then we can't set the parameters for this port.
0504      */
0505     if (!tty || uport->type == PORT_UNKNOWN)
0506         return;
0507 
0508     termios = &tty->termios;
0509     uport->ops->set_termios(uport, termios, old_termios);
0510 
0511     /*
0512      * Set modem status enables based on termios cflag
0513      */
0514     spin_lock_irq(&uport->lock);
0515     if (termios->c_cflag & CRTSCTS)
0516         uport->status |= UPSTAT_CTS_ENABLE;
0517     else
0518         uport->status &= ~UPSTAT_CTS_ENABLE;
0519 
0520     if (termios->c_cflag & CLOCAL)
0521         uport->status &= ~UPSTAT_DCD_ENABLE;
0522     else
0523         uport->status |= UPSTAT_DCD_ENABLE;
0524 
0525     /* reset sw-assisted CTS flow control based on (possibly) new mode */
0526     hw_stopped = uport->hw_stopped;
0527     uport->hw_stopped = uart_softcts_mode(uport) &&
0528                 !(uport->ops->get_mctrl(uport) & TIOCM_CTS);
0529     if (uport->hw_stopped) {
0530         if (!hw_stopped)
0531             uport->ops->stop_tx(uport);
0532     } else {
0533         if (hw_stopped)
0534             __uart_start(tty);
0535     }
0536     spin_unlock_irq(&uport->lock);
0537 }
0538 
0539 static int uart_put_char(struct tty_struct *tty, unsigned char c)
0540 {
0541     struct uart_state *state = tty->driver_data;
0542     struct uart_port *port;
0543     struct circ_buf *circ;
0544     unsigned long flags;
0545     int ret = 0;
0546 
0547     circ = &state->xmit;
0548     port = uart_port_lock(state, flags);
0549     if (!circ->buf) {
0550         uart_port_unlock(port, flags);
0551         return 0;
0552     }
0553 
0554     if (port && uart_circ_chars_free(circ) != 0) {
0555         circ->buf[circ->head] = c;
0556         circ->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);
0557         ret = 1;
0558     }
0559     uart_port_unlock(port, flags);
0560     return ret;
0561 }
0562 
0563 static void uart_flush_chars(struct tty_struct *tty)
0564 {
0565     uart_start(tty);
0566 }
0567 
0568 static int uart_write(struct tty_struct *tty,
0569                     const unsigned char *buf, int count)
0570 {
0571     struct uart_state *state = tty->driver_data;
0572     struct uart_port *port;
0573     struct circ_buf *circ;
0574     unsigned long flags;
0575     int c, ret = 0;
0576 
0577     /*
0578      * This means you called this function _after_ the port was
0579      * closed.  No cookie for you.
0580      */
0581     if (!state) {
0582         WARN_ON(1);
0583         return -EL3HLT;
0584     }
0585 
0586     port = uart_port_lock(state, flags);
0587     circ = &state->xmit;
0588     if (!circ->buf) {
0589         uart_port_unlock(port, flags);
0590         return 0;
0591     }
0592 
0593     while (port) {
0594         c = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);
0595         if (count < c)
0596             c = count;
0597         if (c <= 0)
0598             break;
0599         memcpy(circ->buf + circ->head, buf, c);
0600         circ->head = (circ->head + c) & (UART_XMIT_SIZE - 1);
0601         buf += c;
0602         count -= c;
0603         ret += c;
0604     }
0605 
0606     __uart_start(tty);
0607     uart_port_unlock(port, flags);
0608     return ret;
0609 }
0610 
0611 static unsigned int uart_write_room(struct tty_struct *tty)
0612 {
0613     struct uart_state *state = tty->driver_data;
0614     struct uart_port *port;
0615     unsigned long flags;
0616     unsigned int ret;
0617 
0618     port = uart_port_lock(state, flags);
0619     ret = uart_circ_chars_free(&state->xmit);
0620     uart_port_unlock(port, flags);
0621     return ret;
0622 }
0623 
0624 static unsigned int uart_chars_in_buffer(struct tty_struct *tty)
0625 {
0626     struct uart_state *state = tty->driver_data;
0627     struct uart_port *port;
0628     unsigned long flags;
0629     unsigned int ret;
0630 
0631     port = uart_port_lock(state, flags);
0632     ret = uart_circ_chars_pending(&state->xmit);
0633     uart_port_unlock(port, flags);
0634     return ret;
0635 }
0636 
0637 static void uart_flush_buffer(struct tty_struct *tty)
0638 {
0639     struct uart_state *state = tty->driver_data;
0640     struct uart_port *port;
0641     unsigned long flags;
0642 
0643     /*
0644      * This means you called this function _after_ the port was
0645      * closed.  No cookie for you.
0646      */
0647     if (!state) {
0648         WARN_ON(1);
0649         return;
0650     }
0651 
0652     pr_debug("uart_flush_buffer(%d) called\n", tty->index);
0653 
0654     port = uart_port_lock(state, flags);
0655     if (!port)
0656         return;
0657     uart_circ_clear(&state->xmit);
0658     if (port->ops->flush_buffer)
0659         port->ops->flush_buffer(port);
0660     uart_port_unlock(port, flags);
0661     tty_port_tty_wakeup(&state->port);
0662 }
0663 
0664 /*
0665  * This function performs low-level write of high-priority XON/XOFF
0666  * character and accounting for it.
0667  *
0668  * Requires uart_port to implement .serial_out().
0669  */
0670 void uart_xchar_out(struct uart_port *uport, int offset)
0671 {
0672     serial_port_out(uport, offset, uport->x_char);
0673     uport->icount.tx++;
0674     uport->x_char = 0;
0675 }
0676 EXPORT_SYMBOL_GPL(uart_xchar_out);
0677 
0678 /*
0679  * This function is used to send a high-priority XON/XOFF character to
0680  * the device
0681  */
0682 static void uart_send_xchar(struct tty_struct *tty, char ch)
0683 {
0684     struct uart_state *state = tty->driver_data;
0685     struct uart_port *port;
0686     unsigned long flags;
0687 
0688     port = uart_port_ref(state);
0689     if (!port)
0690         return;
0691 
0692     if (port->ops->send_xchar)
0693         port->ops->send_xchar(port, ch);
0694     else {
0695         spin_lock_irqsave(&port->lock, flags);
0696         port->x_char = ch;
0697         if (ch)
0698             port->ops->start_tx(port);
0699         spin_unlock_irqrestore(&port->lock, flags);
0700     }
0701     uart_port_deref(port);
0702 }
0703 
0704 static void uart_throttle(struct tty_struct *tty)
0705 {
0706     struct uart_state *state = tty->driver_data;
0707     upstat_t mask = UPSTAT_SYNC_FIFO;
0708     struct uart_port *port;
0709 
0710     port = uart_port_ref(state);
0711     if (!port)
0712         return;
0713 
0714     if (I_IXOFF(tty))
0715         mask |= UPSTAT_AUTOXOFF;
0716     if (C_CRTSCTS(tty))
0717         mask |= UPSTAT_AUTORTS;
0718 
0719     if (port->status & mask) {
0720         port->ops->throttle(port);
0721         mask &= ~port->status;
0722     }
0723 
0724     if (mask & UPSTAT_AUTORTS)
0725         uart_clear_mctrl(port, TIOCM_RTS);
0726 
0727     if (mask & UPSTAT_AUTOXOFF)
0728         uart_send_xchar(tty, STOP_CHAR(tty));
0729 
0730     uart_port_deref(port);
0731 }
0732 
0733 static void uart_unthrottle(struct tty_struct *tty)
0734 {
0735     struct uart_state *state = tty->driver_data;
0736     upstat_t mask = UPSTAT_SYNC_FIFO;
0737     struct uart_port *port;
0738 
0739     port = uart_port_ref(state);
0740     if (!port)
0741         return;
0742 
0743     if (I_IXOFF(tty))
0744         mask |= UPSTAT_AUTOXOFF;
0745     if (C_CRTSCTS(tty))
0746         mask |= UPSTAT_AUTORTS;
0747 
0748     if (port->status & mask) {
0749         port->ops->unthrottle(port);
0750         mask &= ~port->status;
0751     }
0752 
0753     if (mask & UPSTAT_AUTORTS)
0754         uart_set_mctrl(port, TIOCM_RTS);
0755 
0756     if (mask & UPSTAT_AUTOXOFF)
0757         uart_send_xchar(tty, START_CHAR(tty));
0758 
0759     uart_port_deref(port);
0760 }
0761 
0762 static int uart_get_info(struct tty_port *port, struct serial_struct *retinfo)
0763 {
0764     struct uart_state *state = container_of(port, struct uart_state, port);
0765     struct uart_port *uport;
0766     int ret = -ENODEV;
0767 
0768     /*
0769      * Ensure the state we copy is consistent and no hardware changes
0770      * occur as we go
0771      */
0772     mutex_lock(&port->mutex);
0773     uport = uart_port_check(state);
0774     if (!uport)
0775         goto out;
0776 
0777     retinfo->type       = uport->type;
0778     retinfo->line       = uport->line;
0779     retinfo->port       = uport->iobase;
0780     if (HIGH_BITS_OFFSET)
0781         retinfo->port_high = (long) uport->iobase >> HIGH_BITS_OFFSET;
0782     retinfo->irq            = uport->irq;
0783     retinfo->flags      = (__force int)uport->flags;
0784     retinfo->xmit_fifo_size  = uport->fifosize;
0785     retinfo->baud_base      = uport->uartclk / 16;
0786     retinfo->close_delay        = jiffies_to_msecs(port->close_delay) / 10;
0787     retinfo->closing_wait    = port->closing_wait == ASYNC_CLOSING_WAIT_NONE ?
0788                 ASYNC_CLOSING_WAIT_NONE :
0789                 jiffies_to_msecs(port->closing_wait) / 10;
0790     retinfo->custom_divisor  = uport->custom_divisor;
0791     retinfo->hub6       = uport->hub6;
0792     retinfo->io_type         = uport->iotype;
0793     retinfo->iomem_reg_shift = uport->regshift;
0794     retinfo->iomem_base      = (void *)(unsigned long)uport->mapbase;
0795 
0796     ret = 0;
0797 out:
0798     mutex_unlock(&port->mutex);
0799     return ret;
0800 }
0801 
0802 static int uart_get_info_user(struct tty_struct *tty,
0803              struct serial_struct *ss)
0804 {
0805     struct uart_state *state = tty->driver_data;
0806     struct tty_port *port = &state->port;
0807 
0808     return uart_get_info(port, ss) < 0 ? -EIO : 0;
0809 }
0810 
0811 static int uart_set_info(struct tty_struct *tty, struct tty_port *port,
0812              struct uart_state *state,
0813              struct serial_struct *new_info)
0814 {
0815     struct uart_port *uport = uart_port_check(state);
0816     unsigned long new_port;
0817     unsigned int change_irq, change_port, closing_wait;
0818     unsigned int old_custom_divisor, close_delay;
0819     upf_t old_flags, new_flags;
0820     int retval = 0;
0821 
0822     if (!uport)
0823         return -EIO;
0824 
0825     new_port = new_info->port;
0826     if (HIGH_BITS_OFFSET)
0827         new_port += (unsigned long) new_info->port_high << HIGH_BITS_OFFSET;
0828 
0829     new_info->irq = irq_canonicalize(new_info->irq);
0830     close_delay = msecs_to_jiffies(new_info->close_delay * 10);
0831     closing_wait = new_info->closing_wait == ASYNC_CLOSING_WAIT_NONE ?
0832             ASYNC_CLOSING_WAIT_NONE :
0833             msecs_to_jiffies(new_info->closing_wait * 10);
0834 
0835 
0836     change_irq  = !(uport->flags & UPF_FIXED_PORT)
0837         && new_info->irq != uport->irq;
0838 
0839     /*
0840      * Since changing the 'type' of the port changes its resource
0841      * allocations, we should treat type changes the same as
0842      * IO port changes.
0843      */
0844     change_port = !(uport->flags & UPF_FIXED_PORT)
0845         && (new_port != uport->iobase ||
0846             (unsigned long)new_info->iomem_base != uport->mapbase ||
0847             new_info->hub6 != uport->hub6 ||
0848             new_info->io_type != uport->iotype ||
0849             new_info->iomem_reg_shift != uport->regshift ||
0850             new_info->type != uport->type);
0851 
0852     old_flags = uport->flags;
0853     new_flags = (__force upf_t)new_info->flags;
0854     old_custom_divisor = uport->custom_divisor;
0855 
0856     if (!capable(CAP_SYS_ADMIN)) {
0857         retval = -EPERM;
0858         if (change_irq || change_port ||
0859             (new_info->baud_base != uport->uartclk / 16) ||
0860             (close_delay != port->close_delay) ||
0861             (closing_wait != port->closing_wait) ||
0862             (new_info->xmit_fifo_size &&
0863              new_info->xmit_fifo_size != uport->fifosize) ||
0864             (((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))
0865             goto exit;
0866         uport->flags = ((uport->flags & ~UPF_USR_MASK) |
0867                    (new_flags & UPF_USR_MASK));
0868         uport->custom_divisor = new_info->custom_divisor;
0869         goto check_and_exit;
0870     }
0871 
0872     if (change_irq || change_port) {
0873         retval = security_locked_down(LOCKDOWN_TIOCSSERIAL);
0874         if (retval)
0875             goto exit;
0876     }
0877 
0878     /*
0879      * Ask the low level driver to verify the settings.
0880      */
0881     if (uport->ops->verify_port)
0882         retval = uport->ops->verify_port(uport, new_info);
0883 
0884     if ((new_info->irq >= nr_irqs) || (new_info->irq < 0) ||
0885         (new_info->baud_base < 9600))
0886         retval = -EINVAL;
0887 
0888     if (retval)
0889         goto exit;
0890 
0891     if (change_port || change_irq) {
0892         retval = -EBUSY;
0893 
0894         /*
0895          * Make sure that we are the sole user of this port.
0896          */
0897         if (tty_port_users(port) > 1)
0898             goto exit;
0899 
0900         /*
0901          * We need to shutdown the serial port at the old
0902          * port/type/irq combination.
0903          */
0904         uart_shutdown(tty, state);
0905     }
0906 
0907     if (change_port) {
0908         unsigned long old_iobase, old_mapbase;
0909         unsigned int old_type, old_iotype, old_hub6, old_shift;
0910 
0911         old_iobase = uport->iobase;
0912         old_mapbase = uport->mapbase;
0913         old_type = uport->type;
0914         old_hub6 = uport->hub6;
0915         old_iotype = uport->iotype;
0916         old_shift = uport->regshift;
0917 
0918         /*
0919          * Free and release old regions
0920          */
0921         if (old_type != PORT_UNKNOWN && uport->ops->release_port)
0922             uport->ops->release_port(uport);
0923 
0924         uport->iobase = new_port;
0925         uport->type = new_info->type;
0926         uport->hub6 = new_info->hub6;
0927         uport->iotype = new_info->io_type;
0928         uport->regshift = new_info->iomem_reg_shift;
0929         uport->mapbase = (unsigned long)new_info->iomem_base;
0930 
0931         /*
0932          * Claim and map the new regions
0933          */
0934         if (uport->type != PORT_UNKNOWN && uport->ops->request_port) {
0935             retval = uport->ops->request_port(uport);
0936         } else {
0937             /* Always success - Jean II */
0938             retval = 0;
0939         }
0940 
0941         /*
0942          * If we fail to request resources for the
0943          * new port, try to restore the old settings.
0944          */
0945         if (retval) {
0946             uport->iobase = old_iobase;
0947             uport->type = old_type;
0948             uport->hub6 = old_hub6;
0949             uport->iotype = old_iotype;
0950             uport->regshift = old_shift;
0951             uport->mapbase = old_mapbase;
0952 
0953             if (old_type != PORT_UNKNOWN) {
0954                 retval = uport->ops->request_port(uport);
0955                 /*
0956                  * If we failed to restore the old settings,
0957                  * we fail like this.
0958                  */
0959                 if (retval)
0960                     uport->type = PORT_UNKNOWN;
0961 
0962                 /*
0963                  * We failed anyway.
0964                  */
0965                 retval = -EBUSY;
0966             }
0967 
0968             /* Added to return the correct error -Ram Gupta */
0969             goto exit;
0970         }
0971     }
0972 
0973     if (change_irq)
0974         uport->irq      = new_info->irq;
0975     if (!(uport->flags & UPF_FIXED_PORT))
0976         uport->uartclk  = new_info->baud_base * 16;
0977     uport->flags            = (uport->flags & ~UPF_CHANGE_MASK) |
0978                  (new_flags & UPF_CHANGE_MASK);
0979     uport->custom_divisor   = new_info->custom_divisor;
0980     port->close_delay     = close_delay;
0981     port->closing_wait    = closing_wait;
0982     if (new_info->xmit_fifo_size)
0983         uport->fifosize = new_info->xmit_fifo_size;
0984 
0985  check_and_exit:
0986     retval = 0;
0987     if (uport->type == PORT_UNKNOWN)
0988         goto exit;
0989     if (tty_port_initialized(port)) {
0990         if (((old_flags ^ uport->flags) & UPF_SPD_MASK) ||
0991             old_custom_divisor != uport->custom_divisor) {
0992             /*
0993              * If they're setting up a custom divisor or speed,
0994              * instead of clearing it, then bitch about it.
0995              */
0996             if (uport->flags & UPF_SPD_MASK) {
0997                 dev_notice_ratelimited(uport->dev,
0998                        "%s sets custom speed on %s. This is deprecated.\n",
0999                       current->comm,
1000                       tty_name(port->tty));
1001             }
1002             uart_change_speed(tty, state, NULL);
1003         }
1004     } else {
1005         retval = uart_startup(tty, state, 1);
1006         if (retval == 0)
1007             tty_port_set_initialized(port, true);
1008         if (retval > 0)
1009             retval = 0;
1010     }
1011  exit:
1012     return retval;
1013 }
1014 
1015 static int uart_set_info_user(struct tty_struct *tty, struct serial_struct *ss)
1016 {
1017     struct uart_state *state = tty->driver_data;
1018     struct tty_port *port = &state->port;
1019     int retval;
1020 
1021     down_write(&tty->termios_rwsem);
1022     /*
1023      * This semaphore protects port->count.  It is also
1024      * very useful to prevent opens.  Also, take the
1025      * port configuration semaphore to make sure that a
1026      * module insertion/removal doesn't change anything
1027      * under us.
1028      */
1029     mutex_lock(&port->mutex);
1030     retval = uart_set_info(tty, port, state, ss);
1031     mutex_unlock(&port->mutex);
1032     up_write(&tty->termios_rwsem);
1033     return retval;
1034 }
1035 
1036 /**
1037  * uart_get_lsr_info - get line status register info
1038  * @tty: tty associated with the UART
1039  * @state: UART being queried
1040  * @value: returned modem value
1041  */
1042 static int uart_get_lsr_info(struct tty_struct *tty,
1043             struct uart_state *state, unsigned int __user *value)
1044 {
1045     struct uart_port *uport = uart_port_check(state);
1046     unsigned int result;
1047 
1048     result = uport->ops->tx_empty(uport);
1049 
1050     /*
1051      * If we're about to load something into the transmit
1052      * register, we'll pretend the transmitter isn't empty to
1053      * avoid a race condition (depending on when the transmit
1054      * interrupt happens).
1055      */
1056     if (uport->x_char ||
1057         ((uart_circ_chars_pending(&state->xmit) > 0) &&
1058          !uart_tx_stopped(uport)))
1059         result &= ~TIOCSER_TEMT;
1060 
1061     return put_user(result, value);
1062 }
1063 
1064 static int uart_tiocmget(struct tty_struct *tty)
1065 {
1066     struct uart_state *state = tty->driver_data;
1067     struct tty_port *port = &state->port;
1068     struct uart_port *uport;
1069     int result = -EIO;
1070 
1071     mutex_lock(&port->mutex);
1072     uport = uart_port_check(state);
1073     if (!uport)
1074         goto out;
1075 
1076     if (!tty_io_error(tty)) {
1077         result = uport->mctrl;
1078         spin_lock_irq(&uport->lock);
1079         result |= uport->ops->get_mctrl(uport);
1080         spin_unlock_irq(&uport->lock);
1081     }
1082 out:
1083     mutex_unlock(&port->mutex);
1084     return result;
1085 }
1086 
1087 static int
1088 uart_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
1089 {
1090     struct uart_state *state = tty->driver_data;
1091     struct tty_port *port = &state->port;
1092     struct uart_port *uport;
1093     int ret = -EIO;
1094 
1095     mutex_lock(&port->mutex);
1096     uport = uart_port_check(state);
1097     if (!uport)
1098         goto out;
1099 
1100     if (!tty_io_error(tty)) {
1101         uart_update_mctrl(uport, set, clear);
1102         ret = 0;
1103     }
1104 out:
1105     mutex_unlock(&port->mutex);
1106     return ret;
1107 }
1108 
1109 static int uart_break_ctl(struct tty_struct *tty, int break_state)
1110 {
1111     struct uart_state *state = tty->driver_data;
1112     struct tty_port *port = &state->port;
1113     struct uart_port *uport;
1114     int ret = -EIO;
1115 
1116     mutex_lock(&port->mutex);
1117     uport = uart_port_check(state);
1118     if (!uport)
1119         goto out;
1120 
1121     if (uport->type != PORT_UNKNOWN && uport->ops->break_ctl)
1122         uport->ops->break_ctl(uport, break_state);
1123     ret = 0;
1124 out:
1125     mutex_unlock(&port->mutex);
1126     return ret;
1127 }
1128 
1129 static int uart_do_autoconfig(struct tty_struct *tty, struct uart_state *state)
1130 {
1131     struct tty_port *port = &state->port;
1132     struct uart_port *uport;
1133     int flags, ret;
1134 
1135     if (!capable(CAP_SYS_ADMIN))
1136         return -EPERM;
1137 
1138     /*
1139      * Take the per-port semaphore.  This prevents count from
1140      * changing, and hence any extra opens of the port while
1141      * we're auto-configuring.
1142      */
1143     if (mutex_lock_interruptible(&port->mutex))
1144         return -ERESTARTSYS;
1145 
1146     uport = uart_port_check(state);
1147     if (!uport) {
1148         ret = -EIO;
1149         goto out;
1150     }
1151 
1152     ret = -EBUSY;
1153     if (tty_port_users(port) == 1) {
1154         uart_shutdown(tty, state);
1155 
1156         /*
1157          * If we already have a port type configured,
1158          * we must release its resources.
1159          */
1160         if (uport->type != PORT_UNKNOWN && uport->ops->release_port)
1161             uport->ops->release_port(uport);
1162 
1163         flags = UART_CONFIG_TYPE;
1164         if (uport->flags & UPF_AUTO_IRQ)
1165             flags |= UART_CONFIG_IRQ;
1166 
1167         /*
1168          * This will claim the ports resources if
1169          * a port is found.
1170          */
1171         uport->ops->config_port(uport, flags);
1172 
1173         ret = uart_startup(tty, state, 1);
1174         if (ret == 0)
1175             tty_port_set_initialized(port, true);
1176         if (ret > 0)
1177             ret = 0;
1178     }
1179 out:
1180     mutex_unlock(&port->mutex);
1181     return ret;
1182 }
1183 
1184 static void uart_enable_ms(struct uart_port *uport)
1185 {
1186     /*
1187      * Force modem status interrupts on
1188      */
1189     if (uport->ops->enable_ms)
1190         uport->ops->enable_ms(uport);
1191 }
1192 
1193 /*
1194  * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
1195  * - mask passed in arg for lines of interest
1196  *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
1197  * Caller should use TIOCGICOUNT to see which one it was
1198  *
1199  * FIXME: This wants extracting into a common all driver implementation
1200  * of TIOCMWAIT using tty_port.
1201  */
1202 static int uart_wait_modem_status(struct uart_state *state, unsigned long arg)
1203 {
1204     struct uart_port *uport;
1205     struct tty_port *port = &state->port;
1206     DECLARE_WAITQUEUE(wait, current);
1207     struct uart_icount cprev, cnow;
1208     int ret;
1209 
1210     /*
1211      * note the counters on entry
1212      */
1213     uport = uart_port_ref(state);
1214     if (!uport)
1215         return -EIO;
1216     spin_lock_irq(&uport->lock);
1217     memcpy(&cprev, &uport->icount, sizeof(struct uart_icount));
1218     uart_enable_ms(uport);
1219     spin_unlock_irq(&uport->lock);
1220 
1221     add_wait_queue(&port->delta_msr_wait, &wait);
1222     for (;;) {
1223         spin_lock_irq(&uport->lock);
1224         memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1225         spin_unlock_irq(&uport->lock);
1226 
1227         set_current_state(TASK_INTERRUPTIBLE);
1228 
1229         if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
1230             ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
1231             ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
1232             ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
1233             ret = 0;
1234             break;
1235         }
1236 
1237         schedule();
1238 
1239         /* see if a signal did it */
1240         if (signal_pending(current)) {
1241             ret = -ERESTARTSYS;
1242             break;
1243         }
1244 
1245         cprev = cnow;
1246     }
1247     __set_current_state(TASK_RUNNING);
1248     remove_wait_queue(&port->delta_msr_wait, &wait);
1249     uart_port_deref(uport);
1250 
1251     return ret;
1252 }
1253 
1254 /*
1255  * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1256  * Return: write counters to the user passed counter struct
1257  * NB: both 1->0 and 0->1 transitions are counted except for
1258  *     RI where only 0->1 is counted.
1259  */
1260 static int uart_get_icount(struct tty_struct *tty,
1261               struct serial_icounter_struct *icount)
1262 {
1263     struct uart_state *state = tty->driver_data;
1264     struct uart_icount cnow;
1265     struct uart_port *uport;
1266 
1267     uport = uart_port_ref(state);
1268     if (!uport)
1269         return -EIO;
1270     spin_lock_irq(&uport->lock);
1271     memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1272     spin_unlock_irq(&uport->lock);
1273     uart_port_deref(uport);
1274 
1275     icount->cts         = cnow.cts;
1276     icount->dsr         = cnow.dsr;
1277     icount->rng         = cnow.rng;
1278     icount->dcd         = cnow.dcd;
1279     icount->rx          = cnow.rx;
1280     icount->tx          = cnow.tx;
1281     icount->frame       = cnow.frame;
1282     icount->overrun     = cnow.overrun;
1283     icount->parity      = cnow.parity;
1284     icount->brk         = cnow.brk;
1285     icount->buf_overrun = cnow.buf_overrun;
1286 
1287     return 0;
1288 }
1289 
1290 #define SER_RS485_LEGACY_FLAGS  (SER_RS485_ENABLED | SER_RS485_RTS_ON_SEND | \
1291                  SER_RS485_RTS_AFTER_SEND | SER_RS485_RX_DURING_TX | \
1292                  SER_RS485_TERMINATE_BUS)
1293 
1294 static int uart_check_rs485_flags(struct uart_port *port, struct serial_rs485 *rs485)
1295 {
1296     u32 flags = rs485->flags;
1297 
1298     /* Don't return -EINVAL for unsupported legacy flags */
1299     flags &= ~SER_RS485_LEGACY_FLAGS;
1300 
1301     /*
1302      * For any bit outside of the legacy ones that is not supported by
1303      * the driver, return -EINVAL.
1304      */
1305     if (flags & ~port->rs485_supported.flags)
1306         return -EINVAL;
1307 
1308     /* Asking for address w/o addressing mode? */
1309     if (!(rs485->flags & SER_RS485_ADDRB) &&
1310         (rs485->flags & (SER_RS485_ADDR_RECV|SER_RS485_ADDR_DEST)))
1311         return -EINVAL;
1312 
1313     /* Address given but not enabled? */
1314     if (!(rs485->flags & SER_RS485_ADDR_RECV) && rs485->addr_recv)
1315         return -EINVAL;
1316     if (!(rs485->flags & SER_RS485_ADDR_DEST) && rs485->addr_dest)
1317         return -EINVAL;
1318 
1319     return 0;
1320 }
1321 
1322 static void uart_sanitize_serial_rs485_delays(struct uart_port *port,
1323                           struct serial_rs485 *rs485)
1324 {
1325     if (!port->rs485_supported.delay_rts_before_send) {
1326         if (rs485->delay_rts_before_send) {
1327             dev_warn_ratelimited(port->dev,
1328                 "%s (%d): RTS delay before sending not supported\n",
1329                 port->name, port->line);
1330         }
1331         rs485->delay_rts_before_send = 0;
1332     } else if (rs485->delay_rts_before_send > RS485_MAX_RTS_DELAY) {
1333         rs485->delay_rts_before_send = RS485_MAX_RTS_DELAY;
1334         dev_warn_ratelimited(port->dev,
1335             "%s (%d): RTS delay before sending clamped to %u ms\n",
1336             port->name, port->line, rs485->delay_rts_before_send);
1337     }
1338 
1339     if (!port->rs485_supported.delay_rts_after_send) {
1340         if (rs485->delay_rts_after_send) {
1341             dev_warn_ratelimited(port->dev,
1342                 "%s (%d): RTS delay after sending not supported\n",
1343                 port->name, port->line);
1344         }
1345         rs485->delay_rts_after_send = 0;
1346     } else if (rs485->delay_rts_after_send > RS485_MAX_RTS_DELAY) {
1347         rs485->delay_rts_after_send = RS485_MAX_RTS_DELAY;
1348         dev_warn_ratelimited(port->dev,
1349             "%s (%d): RTS delay after sending clamped to %u ms\n",
1350             port->name, port->line, rs485->delay_rts_after_send);
1351     }
1352 }
1353 
1354 static void uart_sanitize_serial_rs485(struct uart_port *port, struct serial_rs485 *rs485)
1355 {
1356     u32 supported_flags = port->rs485_supported.flags;
1357 
1358     if (!(rs485->flags & SER_RS485_ENABLED)) {
1359         memset(rs485, 0, sizeof(*rs485));
1360         return;
1361     }
1362 
1363     /* Pick sane settings if the user hasn't */
1364     if ((supported_flags & (SER_RS485_RTS_ON_SEND|SER_RS485_RTS_AFTER_SEND)) &&
1365         !(rs485->flags & SER_RS485_RTS_ON_SEND) ==
1366         !(rs485->flags & SER_RS485_RTS_AFTER_SEND)) {
1367         dev_warn_ratelimited(port->dev,
1368             "%s (%d): invalid RTS setting, using RTS_ON_SEND instead\n",
1369             port->name, port->line);
1370         rs485->flags |= SER_RS485_RTS_ON_SEND;
1371         rs485->flags &= ~SER_RS485_RTS_AFTER_SEND;
1372         supported_flags |= SER_RS485_RTS_ON_SEND|SER_RS485_RTS_AFTER_SEND;
1373     }
1374 
1375     rs485->flags &= supported_flags;
1376 
1377     uart_sanitize_serial_rs485_delays(port, rs485);
1378 
1379     /* Return clean padding area to userspace */
1380     memset(rs485->padding0, 0, sizeof(rs485->padding0));
1381     memset(rs485->padding1, 0, sizeof(rs485->padding1));
1382 }
1383 
1384 static void uart_set_rs485_termination(struct uart_port *port,
1385                        const struct serial_rs485 *rs485)
1386 {
1387     if (!(rs485->flags & SER_RS485_ENABLED))
1388         return;
1389 
1390     gpiod_set_value_cansleep(port->rs485_term_gpio,
1391                  !!(rs485->flags & SER_RS485_TERMINATE_BUS));
1392 }
1393 
1394 int uart_rs485_config(struct uart_port *port)
1395 {
1396     struct serial_rs485 *rs485 = &port->rs485;
1397     int ret;
1398 
1399     uart_sanitize_serial_rs485(port, rs485);
1400     uart_set_rs485_termination(port, rs485);
1401 
1402     ret = port->rs485_config(port, NULL, rs485);
1403     if (ret)
1404         memset(rs485, 0, sizeof(*rs485));
1405 
1406     return ret;
1407 }
1408 EXPORT_SYMBOL_GPL(uart_rs485_config);
1409 
1410 static int uart_get_rs485_config(struct uart_port *port,
1411              struct serial_rs485 __user *rs485)
1412 {
1413     unsigned long flags;
1414     struct serial_rs485 aux;
1415 
1416     spin_lock_irqsave(&port->lock, flags);
1417     aux = port->rs485;
1418     spin_unlock_irqrestore(&port->lock, flags);
1419 
1420     if (copy_to_user(rs485, &aux, sizeof(aux)))
1421         return -EFAULT;
1422 
1423     return 0;
1424 }
1425 
1426 static int uart_set_rs485_config(struct tty_struct *tty, struct uart_port *port,
1427              struct serial_rs485 __user *rs485_user)
1428 {
1429     struct serial_rs485 rs485;
1430     int ret;
1431     unsigned long flags;
1432 
1433     if (!port->rs485_config)
1434         return -ENOTTY;
1435 
1436     if (copy_from_user(&rs485, rs485_user, sizeof(*rs485_user)))
1437         return -EFAULT;
1438 
1439     ret = uart_check_rs485_flags(port, &rs485);
1440     if (ret)
1441         return ret;
1442     uart_sanitize_serial_rs485(port, &rs485);
1443     uart_set_rs485_termination(port, &rs485);
1444 
1445     spin_lock_irqsave(&port->lock, flags);
1446     ret = port->rs485_config(port, &tty->termios, &rs485);
1447     if (!ret)
1448         port->rs485 = rs485;
1449     spin_unlock_irqrestore(&port->lock, flags);
1450     if (ret)
1451         return ret;
1452 
1453     if (copy_to_user(rs485_user, &port->rs485, sizeof(port->rs485)))
1454         return -EFAULT;
1455 
1456     return 0;
1457 }
1458 
1459 static int uart_get_iso7816_config(struct uart_port *port,
1460                    struct serial_iso7816 __user *iso7816)
1461 {
1462     unsigned long flags;
1463     struct serial_iso7816 aux;
1464 
1465     if (!port->iso7816_config)
1466         return -ENOTTY;
1467 
1468     spin_lock_irqsave(&port->lock, flags);
1469     aux = port->iso7816;
1470     spin_unlock_irqrestore(&port->lock, flags);
1471 
1472     if (copy_to_user(iso7816, &aux, sizeof(aux)))
1473         return -EFAULT;
1474 
1475     return 0;
1476 }
1477 
1478 static int uart_set_iso7816_config(struct uart_port *port,
1479                    struct serial_iso7816 __user *iso7816_user)
1480 {
1481     struct serial_iso7816 iso7816;
1482     int i, ret;
1483     unsigned long flags;
1484 
1485     if (!port->iso7816_config)
1486         return -ENOTTY;
1487 
1488     if (copy_from_user(&iso7816, iso7816_user, sizeof(*iso7816_user)))
1489         return -EFAULT;
1490 
1491     /*
1492      * There are 5 words reserved for future use. Check that userspace
1493      * doesn't put stuff in there to prevent breakages in the future.
1494      */
1495     for (i = 0; i < 5; i++)
1496         if (iso7816.reserved[i])
1497             return -EINVAL;
1498 
1499     spin_lock_irqsave(&port->lock, flags);
1500     ret = port->iso7816_config(port, &iso7816);
1501     spin_unlock_irqrestore(&port->lock, flags);
1502     if (ret)
1503         return ret;
1504 
1505     if (copy_to_user(iso7816_user, &port->iso7816, sizeof(port->iso7816)))
1506         return -EFAULT;
1507 
1508     return 0;
1509 }
1510 
1511 /*
1512  * Called via sys_ioctl.  We can use spin_lock_irq() here.
1513  */
1514 static int
1515 uart_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)
1516 {
1517     struct uart_state *state = tty->driver_data;
1518     struct tty_port *port = &state->port;
1519     struct uart_port *uport;
1520     void __user *uarg = (void __user *)arg;
1521     int ret = -ENOIOCTLCMD;
1522 
1523 
1524     /*
1525      * These ioctls don't rely on the hardware to be present.
1526      */
1527     switch (cmd) {
1528     case TIOCSERCONFIG:
1529         down_write(&tty->termios_rwsem);
1530         ret = uart_do_autoconfig(tty, state);
1531         up_write(&tty->termios_rwsem);
1532         break;
1533     }
1534 
1535     if (ret != -ENOIOCTLCMD)
1536         goto out;
1537 
1538     if (tty_io_error(tty)) {
1539         ret = -EIO;
1540         goto out;
1541     }
1542 
1543     /*
1544      * The following should only be used when hardware is present.
1545      */
1546     switch (cmd) {
1547     case TIOCMIWAIT:
1548         ret = uart_wait_modem_status(state, arg);
1549         break;
1550     }
1551 
1552     if (ret != -ENOIOCTLCMD)
1553         goto out;
1554 
1555     /* rs485_config requires more locking than others */
1556     if (cmd == TIOCGRS485)
1557         down_write(&tty->termios_rwsem);
1558 
1559     mutex_lock(&port->mutex);
1560     uport = uart_port_check(state);
1561 
1562     if (!uport || tty_io_error(tty)) {
1563         ret = -EIO;
1564         goto out_up;
1565     }
1566 
1567     /*
1568      * All these rely on hardware being present and need to be
1569      * protected against the tty being hung up.
1570      */
1571 
1572     switch (cmd) {
1573     case TIOCSERGETLSR: /* Get line status register */
1574         ret = uart_get_lsr_info(tty, state, uarg);
1575         break;
1576 
1577     case TIOCGRS485:
1578         ret = uart_get_rs485_config(uport, uarg);
1579         break;
1580 
1581     case TIOCSRS485:
1582         ret = uart_set_rs485_config(tty, uport, uarg);
1583         break;
1584 
1585     case TIOCSISO7816:
1586         ret = uart_set_iso7816_config(state->uart_port, uarg);
1587         break;
1588 
1589     case TIOCGISO7816:
1590         ret = uart_get_iso7816_config(state->uart_port, uarg);
1591         break;
1592     default:
1593         if (uport->ops->ioctl)
1594             ret = uport->ops->ioctl(uport, cmd, arg);
1595         break;
1596     }
1597 out_up:
1598     mutex_unlock(&port->mutex);
1599     if (cmd == TIOCGRS485)
1600         up_write(&tty->termios_rwsem);
1601 out:
1602     return ret;
1603 }
1604 
1605 static void uart_set_ldisc(struct tty_struct *tty)
1606 {
1607     struct uart_state *state = tty->driver_data;
1608     struct uart_port *uport;
1609     struct tty_port *port = &state->port;
1610 
1611     if (!tty_port_initialized(port))
1612         return;
1613 
1614     mutex_lock(&state->port.mutex);
1615     uport = uart_port_check(state);
1616     if (uport && uport->ops->set_ldisc)
1617         uport->ops->set_ldisc(uport, &tty->termios);
1618     mutex_unlock(&state->port.mutex);
1619 }
1620 
1621 static void uart_set_termios(struct tty_struct *tty,
1622                         struct ktermios *old_termios)
1623 {
1624     struct uart_state *state = tty->driver_data;
1625     struct uart_port *uport;
1626     unsigned int cflag = tty->termios.c_cflag;
1627     unsigned int iflag_mask = IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK;
1628     bool sw_changed = false;
1629 
1630     mutex_lock(&state->port.mutex);
1631     uport = uart_port_check(state);
1632     if (!uport)
1633         goto out;
1634 
1635     /*
1636      * Drivers doing software flow control also need to know
1637      * about changes to these input settings.
1638      */
1639     if (uport->flags & UPF_SOFT_FLOW) {
1640         iflag_mask |= IXANY|IXON|IXOFF;
1641         sw_changed =
1642            tty->termios.c_cc[VSTART] != old_termios->c_cc[VSTART] ||
1643            tty->termios.c_cc[VSTOP] != old_termios->c_cc[VSTOP];
1644     }
1645 
1646     /*
1647      * These are the bits that are used to setup various
1648      * flags in the low level driver. We can ignore the Bfoo
1649      * bits in c_cflag; c_[io]speed will always be set
1650      * appropriately by set_termios() in tty_ioctl.c
1651      */
1652     if ((cflag ^ old_termios->c_cflag) == 0 &&
1653         tty->termios.c_ospeed == old_termios->c_ospeed &&
1654         tty->termios.c_ispeed == old_termios->c_ispeed &&
1655         ((tty->termios.c_iflag ^ old_termios->c_iflag) & iflag_mask) == 0 &&
1656         !sw_changed) {
1657         goto out;
1658     }
1659 
1660     uart_change_speed(tty, state, old_termios);
1661     /* reload cflag from termios; port driver may have overridden flags */
1662     cflag = tty->termios.c_cflag;
1663 
1664     /* Handle transition to B0 status */
1665     if ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))
1666         uart_clear_mctrl(uport, TIOCM_RTS | TIOCM_DTR);
1667     /* Handle transition away from B0 status */
1668     else if (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {
1669         unsigned int mask = TIOCM_DTR;
1670 
1671         if (!(cflag & CRTSCTS) || !tty_throttled(tty))
1672             mask |= TIOCM_RTS;
1673         uart_set_mctrl(uport, mask);
1674     }
1675 out:
1676     mutex_unlock(&state->port.mutex);
1677 }
1678 
1679 /*
1680  * Calls to uart_close() are serialised via the tty_lock in
1681  *   drivers/tty/tty_io.c:tty_release()
1682  *   drivers/tty/tty_io.c:do_tty_hangup()
1683  */
1684 static void uart_close(struct tty_struct *tty, struct file *filp)
1685 {
1686     struct uart_state *state = tty->driver_data;
1687 
1688     if (!state) {
1689         struct uart_driver *drv = tty->driver->driver_state;
1690         struct tty_port *port;
1691 
1692         state = drv->state + tty->index;
1693         port = &state->port;
1694         spin_lock_irq(&port->lock);
1695         --port->count;
1696         spin_unlock_irq(&port->lock);
1697         return;
1698     }
1699 
1700     pr_debug("uart_close(%d) called\n", tty->index);
1701 
1702     tty_port_close(tty->port, tty, filp);
1703 }
1704 
1705 static void uart_tty_port_shutdown(struct tty_port *port)
1706 {
1707     struct uart_state *state = container_of(port, struct uart_state, port);
1708     struct uart_port *uport = uart_port_check(state);
1709     char *buf;
1710 
1711     /*
1712      * At this point, we stop accepting input.  To do this, we
1713      * disable the receive line status interrupts.
1714      */
1715     if (WARN(!uport, "detached port still initialized!\n"))
1716         return;
1717 
1718     spin_lock_irq(&uport->lock);
1719     uport->ops->stop_rx(uport);
1720     spin_unlock_irq(&uport->lock);
1721 
1722     uart_port_shutdown(port);
1723 
1724     /*
1725      * It's possible for shutdown to be called after suspend if we get
1726      * a DCD drop (hangup) at just the right time.  Clear suspended bit so
1727      * we don't try to resume a port that has been shutdown.
1728      */
1729     tty_port_set_suspended(port, 0);
1730 
1731     /*
1732      * Free the transmit buffer.
1733      */
1734     spin_lock_irq(&uport->lock);
1735     buf = state->xmit.buf;
1736     state->xmit.buf = NULL;
1737     spin_unlock_irq(&uport->lock);
1738 
1739     free_page((unsigned long)buf);
1740 
1741     uart_change_pm(state, UART_PM_STATE_OFF);
1742 }
1743 
1744 static void uart_wait_until_sent(struct tty_struct *tty, int timeout)
1745 {
1746     struct uart_state *state = tty->driver_data;
1747     struct uart_port *port;
1748     unsigned long char_time, expire, fifo_timeout;
1749 
1750     port = uart_port_ref(state);
1751     if (!port)
1752         return;
1753 
1754     if (port->type == PORT_UNKNOWN || port->fifosize == 0) {
1755         uart_port_deref(port);
1756         return;
1757     }
1758 
1759     /*
1760      * Set the check interval to be 1/5 of the estimated time to
1761      * send a single character, and make it at least 1.  The check
1762      * interval should also be less than the timeout.
1763      *
1764      * Note: we have to use pretty tight timings here to satisfy
1765      * the NIST-PCTS.
1766      */
1767     char_time = max(nsecs_to_jiffies(port->frame_time / 5), 1UL);
1768 
1769     if (timeout && timeout < char_time)
1770         char_time = timeout;
1771 
1772     if (!uart_cts_enabled(port)) {
1773         /*
1774          * If the transmitter hasn't cleared in twice the approximate
1775          * amount of time to send the entire FIFO, it probably won't
1776          * ever clear.  This assumes the UART isn't doing flow
1777          * control, which is currently the case.  Hence, if it ever
1778          * takes longer than FIFO timeout, this is probably due to a
1779          * UART bug of some kind.  So, we clamp the timeout parameter at
1780          * 2 * FIFO timeout.
1781          */
1782         fifo_timeout = uart_fifo_timeout(port);
1783         if (timeout == 0 || timeout > 2 * fifo_timeout)
1784             timeout = 2 * fifo_timeout;
1785     }
1786 
1787     expire = jiffies + timeout;
1788 
1789     pr_debug("uart_wait_until_sent(%d), jiffies=%lu, expire=%lu...\n",
1790         port->line, jiffies, expire);
1791 
1792     /*
1793      * Check whether the transmitter is empty every 'char_time'.
1794      * 'timeout' / 'expire' give us the maximum amount of time
1795      * we wait.
1796      */
1797     while (!port->ops->tx_empty(port)) {
1798         msleep_interruptible(jiffies_to_msecs(char_time));
1799         if (signal_pending(current))
1800             break;
1801         if (timeout && time_after(jiffies, expire))
1802             break;
1803     }
1804     uart_port_deref(port);
1805 }
1806 
1807 /*
1808  * Calls to uart_hangup() are serialised by the tty_lock in
1809  *   drivers/tty/tty_io.c:do_tty_hangup()
1810  * This runs from a workqueue and can sleep for a _short_ time only.
1811  */
1812 static void uart_hangup(struct tty_struct *tty)
1813 {
1814     struct uart_state *state = tty->driver_data;
1815     struct tty_port *port = &state->port;
1816     struct uart_port *uport;
1817     unsigned long flags;
1818 
1819     pr_debug("uart_hangup(%d)\n", tty->index);
1820 
1821     mutex_lock(&port->mutex);
1822     uport = uart_port_check(state);
1823     WARN(!uport, "hangup of detached port!\n");
1824 
1825     if (tty_port_active(port)) {
1826         uart_flush_buffer(tty);
1827         uart_shutdown(tty, state);
1828         spin_lock_irqsave(&port->lock, flags);
1829         port->count = 0;
1830         spin_unlock_irqrestore(&port->lock, flags);
1831         tty_port_set_active(port, 0);
1832         tty_port_tty_set(port, NULL);
1833         if (uport && !uart_console(uport))
1834             uart_change_pm(state, UART_PM_STATE_OFF);
1835         wake_up_interruptible(&port->open_wait);
1836         wake_up_interruptible(&port->delta_msr_wait);
1837     }
1838     mutex_unlock(&port->mutex);
1839 }
1840 
1841 /* uport == NULL if uart_port has already been removed */
1842 static void uart_port_shutdown(struct tty_port *port)
1843 {
1844     struct uart_state *state = container_of(port, struct uart_state, port);
1845     struct uart_port *uport = uart_port_check(state);
1846 
1847     /*
1848      * clear delta_msr_wait queue to avoid mem leaks: we may free
1849      * the irq here so the queue might never be woken up.  Note
1850      * that we won't end up waiting on delta_msr_wait again since
1851      * any outstanding file descriptors should be pointing at
1852      * hung_up_tty_fops now.
1853      */
1854     wake_up_interruptible(&port->delta_msr_wait);
1855 
1856     if (uport) {
1857         /* Free the IRQ and disable the port. */
1858         uport->ops->shutdown(uport);
1859 
1860         /* Ensure that the IRQ handler isn't running on another CPU. */
1861         synchronize_irq(uport->irq);
1862     }
1863 }
1864 
1865 static int uart_carrier_raised(struct tty_port *port)
1866 {
1867     struct uart_state *state = container_of(port, struct uart_state, port);
1868     struct uart_port *uport;
1869     int mctrl;
1870 
1871     uport = uart_port_ref(state);
1872     /*
1873      * Should never observe uport == NULL since checks for hangup should
1874      * abort the tty_port_block_til_ready() loop before checking for carrier
1875      * raised -- but report carrier raised if it does anyway so open will
1876      * continue and not sleep
1877      */
1878     if (WARN_ON(!uport))
1879         return 1;
1880     spin_lock_irq(&uport->lock);
1881     uart_enable_ms(uport);
1882     mctrl = uport->ops->get_mctrl(uport);
1883     spin_unlock_irq(&uport->lock);
1884     uart_port_deref(uport);
1885     if (mctrl & TIOCM_CAR)
1886         return 1;
1887     return 0;
1888 }
1889 
1890 static void uart_dtr_rts(struct tty_port *port, int raise)
1891 {
1892     struct uart_state *state = container_of(port, struct uart_state, port);
1893     struct uart_port *uport;
1894 
1895     uport = uart_port_ref(state);
1896     if (!uport)
1897         return;
1898     uart_port_dtr_rts(uport, raise);
1899     uart_port_deref(uport);
1900 }
1901 
1902 static int uart_install(struct tty_driver *driver, struct tty_struct *tty)
1903 {
1904     struct uart_driver *drv = driver->driver_state;
1905     struct uart_state *state = drv->state + tty->index;
1906 
1907     tty->driver_data = state;
1908 
1909     return tty_standard_install(driver, tty);
1910 }
1911 
1912 /*
1913  * Calls to uart_open are serialised by the tty_lock in
1914  *   drivers/tty/tty_io.c:tty_open()
1915  * Note that if this fails, then uart_close() _will_ be called.
1916  *
1917  * In time, we want to scrap the "opening nonpresent ports"
1918  * behaviour and implement an alternative way for setserial
1919  * to set base addresses/ports/types.  This will allow us to
1920  * get rid of a certain amount of extra tests.
1921  */
1922 static int uart_open(struct tty_struct *tty, struct file *filp)
1923 {
1924     struct uart_state *state = tty->driver_data;
1925     int retval;
1926 
1927     retval = tty_port_open(&state->port, tty, filp);
1928     if (retval > 0)
1929         retval = 0;
1930 
1931     return retval;
1932 }
1933 
1934 static int uart_port_activate(struct tty_port *port, struct tty_struct *tty)
1935 {
1936     struct uart_state *state = container_of(port, struct uart_state, port);
1937     struct uart_port *uport;
1938     int ret;
1939 
1940     uport = uart_port_check(state);
1941     if (!uport || uport->flags & UPF_DEAD)
1942         return -ENXIO;
1943 
1944     /*
1945      * Start up the serial port.
1946      */
1947     ret = uart_startup(tty, state, 0);
1948     if (ret > 0)
1949         tty_port_set_active(port, 1);
1950 
1951     return ret;
1952 }
1953 
1954 static const char *uart_type(struct uart_port *port)
1955 {
1956     const char *str = NULL;
1957 
1958     if (port->ops->type)
1959         str = port->ops->type(port);
1960 
1961     if (!str)
1962         str = "unknown";
1963 
1964     return str;
1965 }
1966 
1967 #ifdef CONFIG_PROC_FS
1968 
1969 static void uart_line_info(struct seq_file *m, struct uart_driver *drv, int i)
1970 {
1971     struct uart_state *state = drv->state + i;
1972     struct tty_port *port = &state->port;
1973     enum uart_pm_state pm_state;
1974     struct uart_port *uport;
1975     char stat_buf[32];
1976     unsigned int status;
1977     int mmio;
1978 
1979     mutex_lock(&port->mutex);
1980     uport = uart_port_check(state);
1981     if (!uport)
1982         goto out;
1983 
1984     mmio = uport->iotype >= UPIO_MEM;
1985     seq_printf(m, "%d: uart:%s %s%08llX irq:%d",
1986             uport->line, uart_type(uport),
1987             mmio ? "mmio:0x" : "port:",
1988             mmio ? (unsigned long long)uport->mapbase
1989                  : (unsigned long long)uport->iobase,
1990             uport->irq);
1991 
1992     if (uport->type == PORT_UNKNOWN) {
1993         seq_putc(m, '\n');
1994         goto out;
1995     }
1996 
1997     if (capable(CAP_SYS_ADMIN)) {
1998         pm_state = state->pm_state;
1999         if (pm_state != UART_PM_STATE_ON)
2000             uart_change_pm(state, UART_PM_STATE_ON);
2001         spin_lock_irq(&uport->lock);
2002         status = uport->ops->get_mctrl(uport);
2003         spin_unlock_irq(&uport->lock);
2004         if (pm_state != UART_PM_STATE_ON)
2005             uart_change_pm(state, pm_state);
2006 
2007         seq_printf(m, " tx:%d rx:%d",
2008                 uport->icount.tx, uport->icount.rx);
2009         if (uport->icount.frame)
2010             seq_printf(m, " fe:%d", uport->icount.frame);
2011         if (uport->icount.parity)
2012             seq_printf(m, " pe:%d", uport->icount.parity);
2013         if (uport->icount.brk)
2014             seq_printf(m, " brk:%d", uport->icount.brk);
2015         if (uport->icount.overrun)
2016             seq_printf(m, " oe:%d", uport->icount.overrun);
2017         if (uport->icount.buf_overrun)
2018             seq_printf(m, " bo:%d", uport->icount.buf_overrun);
2019 
2020 #define INFOBIT(bit, str) \
2021     if (uport->mctrl & (bit)) \
2022         strncat(stat_buf, (str), sizeof(stat_buf) - \
2023             strlen(stat_buf) - 2)
2024 #define STATBIT(bit, str) \
2025     if (status & (bit)) \
2026         strncat(stat_buf, (str), sizeof(stat_buf) - \
2027                strlen(stat_buf) - 2)
2028 
2029         stat_buf[0] = '\0';
2030         stat_buf[1] = '\0';
2031         INFOBIT(TIOCM_RTS, "|RTS");
2032         STATBIT(TIOCM_CTS, "|CTS");
2033         INFOBIT(TIOCM_DTR, "|DTR");
2034         STATBIT(TIOCM_DSR, "|DSR");
2035         STATBIT(TIOCM_CAR, "|CD");
2036         STATBIT(TIOCM_RNG, "|RI");
2037         if (stat_buf[0])
2038             stat_buf[0] = ' ';
2039 
2040         seq_puts(m, stat_buf);
2041     }
2042     seq_putc(m, '\n');
2043 #undef STATBIT
2044 #undef INFOBIT
2045 out:
2046     mutex_unlock(&port->mutex);
2047 }
2048 
2049 static int uart_proc_show(struct seq_file *m, void *v)
2050 {
2051     struct tty_driver *ttydrv = m->private;
2052     struct uart_driver *drv = ttydrv->driver_state;
2053     int i;
2054 
2055     seq_printf(m, "serinfo:1.0 driver%s%s revision:%s\n", "", "", "");
2056     for (i = 0; i < drv->nr; i++)
2057         uart_line_info(m, drv, i);
2058     return 0;
2059 }
2060 #endif
2061 
2062 static void uart_port_spin_lock_init(struct uart_port *port)
2063 {
2064     spin_lock_init(&port->lock);
2065     lockdep_set_class(&port->lock, &port_lock_key);
2066 }
2067 
2068 #if defined(CONFIG_SERIAL_CORE_CONSOLE) || defined(CONFIG_CONSOLE_POLL)
2069 /**
2070  * uart_console_write - write a console message to a serial port
2071  * @port: the port to write the message
2072  * @s: array of characters
2073  * @count: number of characters in string to write
2074  * @putchar: function to write character to port
2075  */
2076 void uart_console_write(struct uart_port *port, const char *s,
2077             unsigned int count,
2078             void (*putchar)(struct uart_port *, unsigned char))
2079 {
2080     unsigned int i;
2081 
2082     for (i = 0; i < count; i++, s++) {
2083         if (*s == '\n')
2084             putchar(port, '\r');
2085         putchar(port, *s);
2086     }
2087 }
2088 EXPORT_SYMBOL_GPL(uart_console_write);
2089 
2090 /**
2091  * uart_get_console - get uart port for console
2092  * @ports: ports to search in
2093  * @nr: number of @ports
2094  * @co: console to search for
2095  * Returns: uart_port for the console @co
2096  *
2097  * Check whether an invalid uart number has been specified (as @co->index), and
2098  * if so, search for the first available port that does have console support.
2099  */
2100 struct uart_port * __init
2101 uart_get_console(struct uart_port *ports, int nr, struct console *co)
2102 {
2103     int idx = co->index;
2104 
2105     if (idx < 0 || idx >= nr || (ports[idx].iobase == 0 &&
2106                      ports[idx].membase == NULL))
2107         for (idx = 0; idx < nr; idx++)
2108             if (ports[idx].iobase != 0 ||
2109                 ports[idx].membase != NULL)
2110                 break;
2111 
2112     co->index = idx;
2113 
2114     return ports + idx;
2115 }
2116 
2117 /**
2118  * uart_parse_earlycon - Parse earlycon options
2119  * @p:       ptr to 2nd field (ie., just beyond '<name>,')
2120  * @iotype:  ptr for decoded iotype (out)
2121  * @addr:    ptr for decoded mapbase/iobase (out)
2122  * @options: ptr for <options> field; %NULL if not present (out)
2123  *
2124  * Decodes earlycon kernel command line parameters of the form:
2125  *  * earlycon=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
2126  *  * console=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
2127  *
2128  * The optional form:
2129  *  * earlycon=<name>,0x<addr>,<options>
2130  *  * console=<name>,0x<addr>,<options>
2131  *
2132  * is also accepted; the returned @iotype will be %UPIO_MEM.
2133  *
2134  * Returns: 0 on success or -%EINVAL on failure
2135  */
2136 int uart_parse_earlycon(char *p, unsigned char *iotype, resource_size_t *addr,
2137             char **options)
2138 {
2139     if (strncmp(p, "mmio,", 5) == 0) {
2140         *iotype = UPIO_MEM;
2141         p += 5;
2142     } else if (strncmp(p, "mmio16,", 7) == 0) {
2143         *iotype = UPIO_MEM16;
2144         p += 7;
2145     } else if (strncmp(p, "mmio32,", 7) == 0) {
2146         *iotype = UPIO_MEM32;
2147         p += 7;
2148     } else if (strncmp(p, "mmio32be,", 9) == 0) {
2149         *iotype = UPIO_MEM32BE;
2150         p += 9;
2151     } else if (strncmp(p, "mmio32native,", 13) == 0) {
2152         *iotype = IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) ?
2153             UPIO_MEM32BE : UPIO_MEM32;
2154         p += 13;
2155     } else if (strncmp(p, "io,", 3) == 0) {
2156         *iotype = UPIO_PORT;
2157         p += 3;
2158     } else if (strncmp(p, "0x", 2) == 0) {
2159         *iotype = UPIO_MEM;
2160     } else {
2161         return -EINVAL;
2162     }
2163 
2164     /*
2165      * Before you replace it with kstrtoull(), think about options separator
2166      * (',') it will not tolerate
2167      */
2168     *addr = simple_strtoull(p, NULL, 0);
2169     p = strchr(p, ',');
2170     if (p)
2171         p++;
2172 
2173     *options = p;
2174     return 0;
2175 }
2176 EXPORT_SYMBOL_GPL(uart_parse_earlycon);
2177 
2178 /**
2179  * uart_parse_options - Parse serial port baud/parity/bits/flow control.
2180  * @options: pointer to option string
2181  * @baud: pointer to an 'int' variable for the baud rate.
2182  * @parity: pointer to an 'int' variable for the parity.
2183  * @bits: pointer to an 'int' variable for the number of data bits.
2184  * @flow: pointer to an 'int' variable for the flow control character.
2185  *
2186  * uart_parse_options() decodes a string containing the serial console
2187  * options. The format of the string is <baud><parity><bits><flow>,
2188  * eg: 115200n8r
2189  */
2190 void
2191 uart_parse_options(const char *options, int *baud, int *parity,
2192            int *bits, int *flow)
2193 {
2194     const char *s = options;
2195 
2196     *baud = simple_strtoul(s, NULL, 10);
2197     while (*s >= '0' && *s <= '9')
2198         s++;
2199     if (*s)
2200         *parity = *s++;
2201     if (*s)
2202         *bits = *s++ - '0';
2203     if (*s)
2204         *flow = *s;
2205 }
2206 EXPORT_SYMBOL_GPL(uart_parse_options);
2207 
2208 /**
2209  * uart_set_options - setup the serial console parameters
2210  * @port: pointer to the serial ports uart_port structure
2211  * @co: console pointer
2212  * @baud: baud rate
2213  * @parity: parity character - 'n' (none), 'o' (odd), 'e' (even)
2214  * @bits: number of data bits
2215  * @flow: flow control character - 'r' (rts)
2216  */
2217 int
2218 uart_set_options(struct uart_port *port, struct console *co,
2219          int baud, int parity, int bits, int flow)
2220 {
2221     struct ktermios termios;
2222     static struct ktermios dummy;
2223 
2224     /*
2225      * Ensure that the serial-console lock is initialised early.
2226      *
2227      * Note that the console-enabled check is needed because of kgdboc,
2228      * which can end up calling uart_set_options() for an already enabled
2229      * console via tty_find_polling_driver() and uart_poll_init().
2230      */
2231     if (!uart_console_enabled(port) && !port->console_reinit)
2232         uart_port_spin_lock_init(port);
2233 
2234     memset(&termios, 0, sizeof(struct ktermios));
2235 
2236     termios.c_cflag |= CREAD | HUPCL | CLOCAL;
2237     tty_termios_encode_baud_rate(&termios, baud, baud);
2238 
2239     if (bits == 7)
2240         termios.c_cflag |= CS7;
2241     else
2242         termios.c_cflag |= CS8;
2243 
2244     switch (parity) {
2245     case 'o': case 'O':
2246         termios.c_cflag |= PARODD;
2247         fallthrough;
2248     case 'e': case 'E':
2249         termios.c_cflag |= PARENB;
2250         break;
2251     }
2252 
2253     if (flow == 'r')
2254         termios.c_cflag |= CRTSCTS;
2255 
2256     /*
2257      * some uarts on other side don't support no flow control.
2258      * So we set * DTR in host uart to make them happy
2259      */
2260     port->mctrl |= TIOCM_DTR;
2261 
2262     port->ops->set_termios(port, &termios, &dummy);
2263     /*
2264      * Allow the setting of the UART parameters with a NULL console
2265      * too:
2266      */
2267     if (co) {
2268         co->cflag = termios.c_cflag;
2269         co->ispeed = termios.c_ispeed;
2270         co->ospeed = termios.c_ospeed;
2271     }
2272 
2273     return 0;
2274 }
2275 EXPORT_SYMBOL_GPL(uart_set_options);
2276 #endif /* CONFIG_SERIAL_CORE_CONSOLE */
2277 
2278 /**
2279  * uart_change_pm - set power state of the port
2280  *
2281  * @state: port descriptor
2282  * @pm_state: new state
2283  *
2284  * Locking: port->mutex has to be held
2285  */
2286 static void uart_change_pm(struct uart_state *state,
2287                enum uart_pm_state pm_state)
2288 {
2289     struct uart_port *port = uart_port_check(state);
2290 
2291     if (state->pm_state != pm_state) {
2292         if (port && port->ops->pm)
2293             port->ops->pm(port, pm_state, state->pm_state);
2294         state->pm_state = pm_state;
2295     }
2296 }
2297 
2298 struct uart_match {
2299     struct uart_port *port;
2300     struct uart_driver *driver;
2301 };
2302 
2303 static int serial_match_port(struct device *dev, void *data)
2304 {
2305     struct uart_match *match = data;
2306     struct tty_driver *tty_drv = match->driver->tty_driver;
2307     dev_t devt = MKDEV(tty_drv->major, tty_drv->minor_start) +
2308         match->port->line;
2309 
2310     return dev->devt == devt; /* Actually, only one tty per port */
2311 }
2312 
2313 int uart_suspend_port(struct uart_driver *drv, struct uart_port *uport)
2314 {
2315     struct uart_state *state = drv->state + uport->line;
2316     struct tty_port *port = &state->port;
2317     struct device *tty_dev;
2318     struct uart_match match = {uport, drv};
2319 
2320     mutex_lock(&port->mutex);
2321 
2322     tty_dev = device_find_child(uport->dev, &match, serial_match_port);
2323     if (tty_dev && device_may_wakeup(tty_dev)) {
2324         enable_irq_wake(uport->irq);
2325         put_device(tty_dev);
2326         mutex_unlock(&port->mutex);
2327         return 0;
2328     }
2329     put_device(tty_dev);
2330 
2331     /*
2332      * Nothing to do if the console is not suspending
2333      * except stop_rx to prevent any asynchronous data
2334      * over RX line. However ensure that we will be
2335      * able to Re-start_rx later.
2336      */
2337     if (!console_suspend_enabled && uart_console(uport)) {
2338         if (uport->ops->start_rx)
2339             uport->ops->stop_rx(uport);
2340         goto unlock;
2341     }
2342 
2343     uport->suspended = 1;
2344 
2345     if (tty_port_initialized(port)) {
2346         const struct uart_ops *ops = uport->ops;
2347         int tries;
2348         unsigned int mctrl;
2349 
2350         tty_port_set_suspended(port, 1);
2351         tty_port_set_initialized(port, 0);
2352 
2353         spin_lock_irq(&uport->lock);
2354         ops->stop_tx(uport);
2355         ops->set_mctrl(uport, 0);
2356         /* save mctrl so it can be restored on resume */
2357         mctrl = uport->mctrl;
2358         uport->mctrl = 0;
2359         ops->stop_rx(uport);
2360         spin_unlock_irq(&uport->lock);
2361 
2362         /*
2363          * Wait for the transmitter to empty.
2364          */
2365         for (tries = 3; !ops->tx_empty(uport) && tries; tries--)
2366             msleep(10);
2367         if (!tries)
2368             dev_err(uport->dev, "%s: Unable to drain transmitter\n",
2369                 uport->name);
2370 
2371         ops->shutdown(uport);
2372         uport->mctrl = mctrl;
2373     }
2374 
2375     /*
2376      * Disable the console device before suspending.
2377      */
2378     if (uart_console(uport))
2379         console_stop(uport->cons);
2380 
2381     uart_change_pm(state, UART_PM_STATE_OFF);
2382 unlock:
2383     mutex_unlock(&port->mutex);
2384 
2385     return 0;
2386 }
2387 EXPORT_SYMBOL(uart_suspend_port);
2388 
2389 int uart_resume_port(struct uart_driver *drv, struct uart_port *uport)
2390 {
2391     struct uart_state *state = drv->state + uport->line;
2392     struct tty_port *port = &state->port;
2393     struct device *tty_dev;
2394     struct uart_match match = {uport, drv};
2395     struct ktermios termios;
2396 
2397     mutex_lock(&port->mutex);
2398 
2399     tty_dev = device_find_child(uport->dev, &match, serial_match_port);
2400     if (!uport->suspended && device_may_wakeup(tty_dev)) {
2401         if (irqd_is_wakeup_set(irq_get_irq_data((uport->irq))))
2402             disable_irq_wake(uport->irq);
2403         put_device(tty_dev);
2404         mutex_unlock(&port->mutex);
2405         return 0;
2406     }
2407     put_device(tty_dev);
2408     uport->suspended = 0;
2409 
2410     /*
2411      * Re-enable the console device after suspending.
2412      */
2413     if (uart_console(uport)) {
2414         /*
2415          * First try to use the console cflag setting.
2416          */
2417         memset(&termios, 0, sizeof(struct ktermios));
2418         termios.c_cflag = uport->cons->cflag;
2419         termios.c_ispeed = uport->cons->ispeed;
2420         termios.c_ospeed = uport->cons->ospeed;
2421 
2422         /*
2423          * If that's unset, use the tty termios setting.
2424          */
2425         if (port->tty && termios.c_cflag == 0)
2426             termios = port->tty->termios;
2427 
2428         if (console_suspend_enabled)
2429             uart_change_pm(state, UART_PM_STATE_ON);
2430         uport->ops->set_termios(uport, &termios, NULL);
2431         if (!console_suspend_enabled && uport->ops->start_rx)
2432             uport->ops->start_rx(uport);
2433         if (console_suspend_enabled)
2434             console_start(uport->cons);
2435     }
2436 
2437     if (tty_port_suspended(port)) {
2438         const struct uart_ops *ops = uport->ops;
2439         int ret;
2440 
2441         uart_change_pm(state, UART_PM_STATE_ON);
2442         spin_lock_irq(&uport->lock);
2443         ops->set_mctrl(uport, 0);
2444         spin_unlock_irq(&uport->lock);
2445         if (console_suspend_enabled || !uart_console(uport)) {
2446             /* Protected by port mutex for now */
2447             struct tty_struct *tty = port->tty;
2448 
2449             ret = ops->startup(uport);
2450             if (ret == 0) {
2451                 if (tty)
2452                     uart_change_speed(tty, state, NULL);
2453                 spin_lock_irq(&uport->lock);
2454                 ops->set_mctrl(uport, uport->mctrl);
2455                 ops->start_tx(uport);
2456                 spin_unlock_irq(&uport->lock);
2457                 tty_port_set_initialized(port, 1);
2458             } else {
2459                 /*
2460                  * Failed to resume - maybe hardware went away?
2461                  * Clear the "initialized" flag so we won't try
2462                  * to call the low level drivers shutdown method.
2463                  */
2464                 uart_shutdown(tty, state);
2465             }
2466         }
2467 
2468         tty_port_set_suspended(port, 0);
2469     }
2470 
2471     mutex_unlock(&port->mutex);
2472 
2473     return 0;
2474 }
2475 EXPORT_SYMBOL(uart_resume_port);
2476 
2477 static inline void
2478 uart_report_port(struct uart_driver *drv, struct uart_port *port)
2479 {
2480     char address[64];
2481 
2482     switch (port->iotype) {
2483     case UPIO_PORT:
2484         snprintf(address, sizeof(address), "I/O 0x%lx", port->iobase);
2485         break;
2486     case UPIO_HUB6:
2487         snprintf(address, sizeof(address),
2488              "I/O 0x%lx offset 0x%x", port->iobase, port->hub6);
2489         break;
2490     case UPIO_MEM:
2491     case UPIO_MEM16:
2492     case UPIO_MEM32:
2493     case UPIO_MEM32BE:
2494     case UPIO_AU:
2495     case UPIO_TSI:
2496         snprintf(address, sizeof(address),
2497              "MMIO 0x%llx", (unsigned long long)port->mapbase);
2498         break;
2499     default:
2500         strlcpy(address, "*unknown*", sizeof(address));
2501         break;
2502     }
2503 
2504     pr_info("%s%s%s at %s (irq = %d, base_baud = %d) is a %s\n",
2505            port->dev ? dev_name(port->dev) : "",
2506            port->dev ? ": " : "",
2507            port->name,
2508            address, port->irq, port->uartclk / 16, uart_type(port));
2509 
2510     /* The magic multiplier feature is a bit obscure, so report it too.  */
2511     if (port->flags & UPF_MAGIC_MULTIPLIER)
2512         pr_info("%s%s%s extra baud rates supported: %d, %d",
2513             port->dev ? dev_name(port->dev) : "",
2514             port->dev ? ": " : "",
2515             port->name,
2516             port->uartclk / 8, port->uartclk / 4);
2517 }
2518 
2519 static void
2520 uart_configure_port(struct uart_driver *drv, struct uart_state *state,
2521             struct uart_port *port)
2522 {
2523     unsigned int flags;
2524 
2525     /*
2526      * If there isn't a port here, don't do anything further.
2527      */
2528     if (!port->iobase && !port->mapbase && !port->membase)
2529         return;
2530 
2531     /*
2532      * Now do the auto configuration stuff.  Note that config_port
2533      * is expected to claim the resources and map the port for us.
2534      */
2535     flags = 0;
2536     if (port->flags & UPF_AUTO_IRQ)
2537         flags |= UART_CONFIG_IRQ;
2538     if (port->flags & UPF_BOOT_AUTOCONF) {
2539         if (!(port->flags & UPF_FIXED_TYPE)) {
2540             port->type = PORT_UNKNOWN;
2541             flags |= UART_CONFIG_TYPE;
2542         }
2543         port->ops->config_port(port, flags);
2544     }
2545 
2546     if (port->type != PORT_UNKNOWN) {
2547         unsigned long flags;
2548 
2549         uart_report_port(drv, port);
2550 
2551         /* Power up port for set_mctrl() */
2552         uart_change_pm(state, UART_PM_STATE_ON);
2553 
2554         /*
2555          * Ensure that the modem control lines are de-activated.
2556          * keep the DTR setting that is set in uart_set_options()
2557          * We probably don't need a spinlock around this, but
2558          */
2559         spin_lock_irqsave(&port->lock, flags);
2560         port->mctrl &= TIOCM_DTR;
2561         if (port->rs485.flags & SER_RS485_ENABLED &&
2562             !(port->rs485.flags & SER_RS485_RTS_AFTER_SEND))
2563             port->mctrl |= TIOCM_RTS;
2564         port->ops->set_mctrl(port, port->mctrl);
2565         spin_unlock_irqrestore(&port->lock, flags);
2566 
2567         /*
2568          * If this driver supports console, and it hasn't been
2569          * successfully registered yet, try to re-register it.
2570          * It may be that the port was not available.
2571          */
2572         if (port->cons && !(port->cons->flags & CON_ENABLED))
2573             register_console(port->cons);
2574 
2575         /*
2576          * Power down all ports by default, except the
2577          * console if we have one.
2578          */
2579         if (!uart_console(port))
2580             uart_change_pm(state, UART_PM_STATE_OFF);
2581     }
2582 }
2583 
2584 #ifdef CONFIG_CONSOLE_POLL
2585 
2586 static int uart_poll_init(struct tty_driver *driver, int line, char *options)
2587 {
2588     struct uart_driver *drv = driver->driver_state;
2589     struct uart_state *state = drv->state + line;
2590     struct tty_port *tport;
2591     struct uart_port *port;
2592     int baud = 9600;
2593     int bits = 8;
2594     int parity = 'n';
2595     int flow = 'n';
2596     int ret = 0;
2597 
2598     tport = &state->port;
2599     mutex_lock(&tport->mutex);
2600 
2601     port = uart_port_check(state);
2602     if (!port || !(port->ops->poll_get_char && port->ops->poll_put_char)) {
2603         ret = -1;
2604         goto out;
2605     }
2606 
2607     if (port->ops->poll_init) {
2608         /*
2609          * We don't set initialized as we only initialized the hw,
2610          * e.g. state->xmit is still uninitialized.
2611          */
2612         if (!tty_port_initialized(tport))
2613             ret = port->ops->poll_init(port);
2614     }
2615 
2616     if (!ret && options) {
2617         uart_parse_options(options, &baud, &parity, &bits, &flow);
2618         ret = uart_set_options(port, NULL, baud, parity, bits, flow);
2619     }
2620 out:
2621     mutex_unlock(&tport->mutex);
2622     return ret;
2623 }
2624 
2625 static int uart_poll_get_char(struct tty_driver *driver, int line)
2626 {
2627     struct uart_driver *drv = driver->driver_state;
2628     struct uart_state *state = drv->state + line;
2629     struct uart_port *port;
2630     int ret = -1;
2631 
2632     port = uart_port_ref(state);
2633     if (port) {
2634         ret = port->ops->poll_get_char(port);
2635         uart_port_deref(port);
2636     }
2637 
2638     return ret;
2639 }
2640 
2641 static void uart_poll_put_char(struct tty_driver *driver, int line, char ch)
2642 {
2643     struct uart_driver *drv = driver->driver_state;
2644     struct uart_state *state = drv->state + line;
2645     struct uart_port *port;
2646 
2647     port = uart_port_ref(state);
2648     if (!port)
2649         return;
2650 
2651     if (ch == '\n')
2652         port->ops->poll_put_char(port, '\r');
2653     port->ops->poll_put_char(port, ch);
2654     uart_port_deref(port);
2655 }
2656 #endif
2657 
2658 static const struct tty_operations uart_ops = {
2659     .install    = uart_install,
2660     .open       = uart_open,
2661     .close      = uart_close,
2662     .write      = uart_write,
2663     .put_char   = uart_put_char,
2664     .flush_chars    = uart_flush_chars,
2665     .write_room = uart_write_room,
2666     .chars_in_buffer= uart_chars_in_buffer,
2667     .flush_buffer   = uart_flush_buffer,
2668     .ioctl      = uart_ioctl,
2669     .throttle   = uart_throttle,
2670     .unthrottle = uart_unthrottle,
2671     .send_xchar = uart_send_xchar,
2672     .set_termios    = uart_set_termios,
2673     .set_ldisc  = uart_set_ldisc,
2674     .stop       = uart_stop,
2675     .start      = uart_start,
2676     .hangup     = uart_hangup,
2677     .break_ctl  = uart_break_ctl,
2678     .wait_until_sent= uart_wait_until_sent,
2679 #ifdef CONFIG_PROC_FS
2680     .proc_show  = uart_proc_show,
2681 #endif
2682     .tiocmget   = uart_tiocmget,
2683     .tiocmset   = uart_tiocmset,
2684     .set_serial = uart_set_info_user,
2685     .get_serial = uart_get_info_user,
2686     .get_icount = uart_get_icount,
2687 #ifdef CONFIG_CONSOLE_POLL
2688     .poll_init  = uart_poll_init,
2689     .poll_get_char  = uart_poll_get_char,
2690     .poll_put_char  = uart_poll_put_char,
2691 #endif
2692 };
2693 
2694 static const struct tty_port_operations uart_port_ops = {
2695     .carrier_raised = uart_carrier_raised,
2696     .dtr_rts    = uart_dtr_rts,
2697     .activate   = uart_port_activate,
2698     .shutdown   = uart_tty_port_shutdown,
2699 };
2700 
2701 /**
2702  * uart_register_driver - register a driver with the uart core layer
2703  * @drv: low level driver structure
2704  *
2705  * Register a uart driver with the core driver. We in turn register with the
2706  * tty layer, and initialise the core driver per-port state.
2707  *
2708  * We have a proc file in /proc/tty/driver which is named after the normal
2709  * driver.
2710  *
2711  * @drv->port should be %NULL, and the per-port structures should be registered
2712  * using uart_add_one_port() after this call has succeeded.
2713  *
2714  * Locking: none, Interrupts: enabled
2715  */
2716 int uart_register_driver(struct uart_driver *drv)
2717 {
2718     struct tty_driver *normal;
2719     int i, retval = -ENOMEM;
2720 
2721     BUG_ON(drv->state);
2722 
2723     /*
2724      * Maybe we should be using a slab cache for this, especially if
2725      * we have a large number of ports to handle.
2726      */
2727     drv->state = kcalloc(drv->nr, sizeof(struct uart_state), GFP_KERNEL);
2728     if (!drv->state)
2729         goto out;
2730 
2731     normal = tty_alloc_driver(drv->nr, TTY_DRIVER_REAL_RAW |
2732             TTY_DRIVER_DYNAMIC_DEV);
2733     if (IS_ERR(normal)) {
2734         retval = PTR_ERR(normal);
2735         goto out_kfree;
2736     }
2737 
2738     drv->tty_driver = normal;
2739 
2740     normal->driver_name = drv->driver_name;
2741     normal->name        = drv->dev_name;
2742     normal->major       = drv->major;
2743     normal->minor_start = drv->minor;
2744     normal->type        = TTY_DRIVER_TYPE_SERIAL;
2745     normal->subtype     = SERIAL_TYPE_NORMAL;
2746     normal->init_termios    = tty_std_termios;
2747     normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
2748     normal->init_termios.c_ispeed = normal->init_termios.c_ospeed = 9600;
2749     normal->driver_state    = drv;
2750     tty_set_operations(normal, &uart_ops);
2751 
2752     /*
2753      * Initialise the UART state(s).
2754      */
2755     for (i = 0; i < drv->nr; i++) {
2756         struct uart_state *state = drv->state + i;
2757         struct tty_port *port = &state->port;
2758 
2759         tty_port_init(port);
2760         port->ops = &uart_port_ops;
2761     }
2762 
2763     retval = tty_register_driver(normal);
2764     if (retval >= 0)
2765         return retval;
2766 
2767     for (i = 0; i < drv->nr; i++)
2768         tty_port_destroy(&drv->state[i].port);
2769     tty_driver_kref_put(normal);
2770 out_kfree:
2771     kfree(drv->state);
2772 out:
2773     return retval;
2774 }
2775 EXPORT_SYMBOL(uart_register_driver);
2776 
2777 /**
2778  * uart_unregister_driver - remove a driver from the uart core layer
2779  * @drv: low level driver structure
2780  *
2781  * Remove all references to a driver from the core driver. The low level
2782  * driver must have removed all its ports via the uart_remove_one_port() if it
2783  * registered them with uart_add_one_port(). (I.e. @drv->port is %NULL.)
2784  *
2785  * Locking: none, Interrupts: enabled
2786  */
2787 void uart_unregister_driver(struct uart_driver *drv)
2788 {
2789     struct tty_driver *p = drv->tty_driver;
2790     unsigned int i;
2791 
2792     tty_unregister_driver(p);
2793     tty_driver_kref_put(p);
2794     for (i = 0; i < drv->nr; i++)
2795         tty_port_destroy(&drv->state[i].port);
2796     kfree(drv->state);
2797     drv->state = NULL;
2798     drv->tty_driver = NULL;
2799 }
2800 EXPORT_SYMBOL(uart_unregister_driver);
2801 
2802 struct tty_driver *uart_console_device(struct console *co, int *index)
2803 {
2804     struct uart_driver *p = co->data;
2805     *index = co->index;
2806     return p->tty_driver;
2807 }
2808 EXPORT_SYMBOL_GPL(uart_console_device);
2809 
2810 static ssize_t uartclk_show(struct device *dev,
2811     struct device_attribute *attr, char *buf)
2812 {
2813     struct serial_struct tmp;
2814     struct tty_port *port = dev_get_drvdata(dev);
2815 
2816     uart_get_info(port, &tmp);
2817     return sprintf(buf, "%d\n", tmp.baud_base * 16);
2818 }
2819 
2820 static ssize_t type_show(struct device *dev,
2821     struct device_attribute *attr, char *buf)
2822 {
2823     struct serial_struct tmp;
2824     struct tty_port *port = dev_get_drvdata(dev);
2825 
2826     uart_get_info(port, &tmp);
2827     return sprintf(buf, "%d\n", tmp.type);
2828 }
2829 
2830 static ssize_t line_show(struct device *dev,
2831     struct device_attribute *attr, char *buf)
2832 {
2833     struct serial_struct tmp;
2834     struct tty_port *port = dev_get_drvdata(dev);
2835 
2836     uart_get_info(port, &tmp);
2837     return sprintf(buf, "%d\n", tmp.line);
2838 }
2839 
2840 static ssize_t port_show(struct device *dev,
2841     struct device_attribute *attr, char *buf)
2842 {
2843     struct serial_struct tmp;
2844     struct tty_port *port = dev_get_drvdata(dev);
2845     unsigned long ioaddr;
2846 
2847     uart_get_info(port, &tmp);
2848     ioaddr = tmp.port;
2849     if (HIGH_BITS_OFFSET)
2850         ioaddr |= (unsigned long)tmp.port_high << HIGH_BITS_OFFSET;
2851     return sprintf(buf, "0x%lX\n", ioaddr);
2852 }
2853 
2854 static ssize_t irq_show(struct device *dev,
2855     struct device_attribute *attr, char *buf)
2856 {
2857     struct serial_struct tmp;
2858     struct tty_port *port = dev_get_drvdata(dev);
2859 
2860     uart_get_info(port, &tmp);
2861     return sprintf(buf, "%d\n", tmp.irq);
2862 }
2863 
2864 static ssize_t flags_show(struct device *dev,
2865     struct device_attribute *attr, char *buf)
2866 {
2867     struct serial_struct tmp;
2868     struct tty_port *port = dev_get_drvdata(dev);
2869 
2870     uart_get_info(port, &tmp);
2871     return sprintf(buf, "0x%X\n", tmp.flags);
2872 }
2873 
2874 static ssize_t xmit_fifo_size_show(struct device *dev,
2875     struct device_attribute *attr, char *buf)
2876 {
2877     struct serial_struct tmp;
2878     struct tty_port *port = dev_get_drvdata(dev);
2879 
2880     uart_get_info(port, &tmp);
2881     return sprintf(buf, "%d\n", tmp.xmit_fifo_size);
2882 }
2883 
2884 static ssize_t close_delay_show(struct device *dev,
2885     struct device_attribute *attr, char *buf)
2886 {
2887     struct serial_struct tmp;
2888     struct tty_port *port = dev_get_drvdata(dev);
2889 
2890     uart_get_info(port, &tmp);
2891     return sprintf(buf, "%d\n", tmp.close_delay);
2892 }
2893 
2894 static ssize_t closing_wait_show(struct device *dev,
2895     struct device_attribute *attr, char *buf)
2896 {
2897     struct serial_struct tmp;
2898     struct tty_port *port = dev_get_drvdata(dev);
2899 
2900     uart_get_info(port, &tmp);
2901     return sprintf(buf, "%d\n", tmp.closing_wait);
2902 }
2903 
2904 static ssize_t custom_divisor_show(struct device *dev,
2905     struct device_attribute *attr, char *buf)
2906 {
2907     struct serial_struct tmp;
2908     struct tty_port *port = dev_get_drvdata(dev);
2909 
2910     uart_get_info(port, &tmp);
2911     return sprintf(buf, "%d\n", tmp.custom_divisor);
2912 }
2913 
2914 static ssize_t io_type_show(struct device *dev,
2915     struct device_attribute *attr, char *buf)
2916 {
2917     struct serial_struct tmp;
2918     struct tty_port *port = dev_get_drvdata(dev);
2919 
2920     uart_get_info(port, &tmp);
2921     return sprintf(buf, "%d\n", tmp.io_type);
2922 }
2923 
2924 static ssize_t iomem_base_show(struct device *dev,
2925     struct device_attribute *attr, char *buf)
2926 {
2927     struct serial_struct tmp;
2928     struct tty_port *port = dev_get_drvdata(dev);
2929 
2930     uart_get_info(port, &tmp);
2931     return sprintf(buf, "0x%lX\n", (unsigned long)tmp.iomem_base);
2932 }
2933 
2934 static ssize_t iomem_reg_shift_show(struct device *dev,
2935     struct device_attribute *attr, char *buf)
2936 {
2937     struct serial_struct tmp;
2938     struct tty_port *port = dev_get_drvdata(dev);
2939 
2940     uart_get_info(port, &tmp);
2941     return sprintf(buf, "%d\n", tmp.iomem_reg_shift);
2942 }
2943 
2944 static ssize_t console_show(struct device *dev,
2945     struct device_attribute *attr, char *buf)
2946 {
2947     struct tty_port *port = dev_get_drvdata(dev);
2948     struct uart_state *state = container_of(port, struct uart_state, port);
2949     struct uart_port *uport;
2950     bool console = false;
2951 
2952     mutex_lock(&port->mutex);
2953     uport = uart_port_check(state);
2954     if (uport)
2955         console = uart_console_enabled(uport);
2956     mutex_unlock(&port->mutex);
2957 
2958     return sprintf(buf, "%c\n", console ? 'Y' : 'N');
2959 }
2960 
2961 static ssize_t console_store(struct device *dev,
2962     struct device_attribute *attr, const char *buf, size_t count)
2963 {
2964     struct tty_port *port = dev_get_drvdata(dev);
2965     struct uart_state *state = container_of(port, struct uart_state, port);
2966     struct uart_port *uport;
2967     bool oldconsole, newconsole;
2968     int ret;
2969 
2970     ret = kstrtobool(buf, &newconsole);
2971     if (ret)
2972         return ret;
2973 
2974     mutex_lock(&port->mutex);
2975     uport = uart_port_check(state);
2976     if (uport) {
2977         oldconsole = uart_console_enabled(uport);
2978         if (oldconsole && !newconsole) {
2979             ret = unregister_console(uport->cons);
2980         } else if (!oldconsole && newconsole) {
2981             if (uart_console(uport)) {
2982                 uport->console_reinit = 1;
2983                 register_console(uport->cons);
2984             } else {
2985                 ret = -ENOENT;
2986             }
2987         }
2988     } else {
2989         ret = -ENXIO;
2990     }
2991     mutex_unlock(&port->mutex);
2992 
2993     return ret < 0 ? ret : count;
2994 }
2995 
2996 static DEVICE_ATTR_RO(uartclk);
2997 static DEVICE_ATTR_RO(type);
2998 static DEVICE_ATTR_RO(line);
2999 static DEVICE_ATTR_RO(port);
3000 static DEVICE_ATTR_RO(irq);
3001 static DEVICE_ATTR_RO(flags);
3002 static DEVICE_ATTR_RO(xmit_fifo_size);
3003 static DEVICE_ATTR_RO(close_delay);
3004 static DEVICE_ATTR_RO(closing_wait);
3005 static DEVICE_ATTR_RO(custom_divisor);
3006 static DEVICE_ATTR_RO(io_type);
3007 static DEVICE_ATTR_RO(iomem_base);
3008 static DEVICE_ATTR_RO(iomem_reg_shift);
3009 static DEVICE_ATTR_RW(console);
3010 
3011 static struct attribute *tty_dev_attrs[] = {
3012     &dev_attr_uartclk.attr,
3013     &dev_attr_type.attr,
3014     &dev_attr_line.attr,
3015     &dev_attr_port.attr,
3016     &dev_attr_irq.attr,
3017     &dev_attr_flags.attr,
3018     &dev_attr_xmit_fifo_size.attr,
3019     &dev_attr_close_delay.attr,
3020     &dev_attr_closing_wait.attr,
3021     &dev_attr_custom_divisor.attr,
3022     &dev_attr_io_type.attr,
3023     &dev_attr_iomem_base.attr,
3024     &dev_attr_iomem_reg_shift.attr,
3025     &dev_attr_console.attr,
3026     NULL
3027 };
3028 
3029 static const struct attribute_group tty_dev_attr_group = {
3030     .attrs = tty_dev_attrs,
3031 };
3032 
3033 /**
3034  * uart_add_one_port - attach a driver-defined port structure
3035  * @drv: pointer to the uart low level driver structure for this port
3036  * @uport: uart port structure to use for this port.
3037  *
3038  * Context: task context, might sleep
3039  *
3040  * This allows the driver @drv to register its own uart_port structure with the
3041  * core driver. The main purpose is to allow the low level uart drivers to
3042  * expand uart_port, rather than having yet more levels of structures.
3043  */
3044 int uart_add_one_port(struct uart_driver *drv, struct uart_port *uport)
3045 {
3046     struct uart_state *state;
3047     struct tty_port *port;
3048     int ret = 0;
3049     struct device *tty_dev;
3050     int num_groups;
3051 
3052     if (uport->line >= drv->nr)
3053         return -EINVAL;
3054 
3055     state = drv->state + uport->line;
3056     port = &state->port;
3057 
3058     mutex_lock(&port_mutex);
3059     mutex_lock(&port->mutex);
3060     if (state->uart_port) {
3061         ret = -EINVAL;
3062         goto out;
3063     }
3064 
3065     /* Link the port to the driver state table and vice versa */
3066     atomic_set(&state->refcount, 1);
3067     init_waitqueue_head(&state->remove_wait);
3068     state->uart_port = uport;
3069     uport->state = state;
3070 
3071     state->pm_state = UART_PM_STATE_UNDEFINED;
3072     uport->cons = drv->cons;
3073     uport->minor = drv->tty_driver->minor_start + uport->line;
3074     uport->name = kasprintf(GFP_KERNEL, "%s%d", drv->dev_name,
3075                 drv->tty_driver->name_base + uport->line);
3076     if (!uport->name) {
3077         ret = -ENOMEM;
3078         goto out;
3079     }
3080 
3081     /*
3082      * If this port is in use as a console then the spinlock is already
3083      * initialised.
3084      */
3085     if (!uart_console_enabled(uport))
3086         uart_port_spin_lock_init(uport);
3087 
3088     if (uport->cons && uport->dev)
3089         of_console_check(uport->dev->of_node, uport->cons->name, uport->line);
3090 
3091     tty_port_link_device(port, drv->tty_driver, uport->line);
3092     uart_configure_port(drv, state, uport);
3093 
3094     port->console = uart_console(uport);
3095 
3096     num_groups = 2;
3097     if (uport->attr_group)
3098         num_groups++;
3099 
3100     uport->tty_groups = kcalloc(num_groups, sizeof(*uport->tty_groups),
3101                     GFP_KERNEL);
3102     if (!uport->tty_groups) {
3103         ret = -ENOMEM;
3104         goto out;
3105     }
3106     uport->tty_groups[0] = &tty_dev_attr_group;
3107     if (uport->attr_group)
3108         uport->tty_groups[1] = uport->attr_group;
3109 
3110     /*
3111      * Register the port whether it's detected or not.  This allows
3112      * setserial to be used to alter this port's parameters.
3113      */
3114     tty_dev = tty_port_register_device_attr_serdev(port, drv->tty_driver,
3115             uport->line, uport->dev, port, uport->tty_groups);
3116     if (!IS_ERR(tty_dev)) {
3117         device_set_wakeup_capable(tty_dev, 1);
3118     } else {
3119         dev_err(uport->dev, "Cannot register tty device on line %d\n",
3120                uport->line);
3121     }
3122 
3123     /*
3124      * Ensure UPF_DEAD is not set.
3125      */
3126     uport->flags &= ~UPF_DEAD;
3127 
3128  out:
3129     mutex_unlock(&port->mutex);
3130     mutex_unlock(&port_mutex);
3131 
3132     return ret;
3133 }
3134 EXPORT_SYMBOL(uart_add_one_port);
3135 
3136 /**
3137  * uart_remove_one_port - detach a driver defined port structure
3138  * @drv: pointer to the uart low level driver structure for this port
3139  * @uport: uart port structure for this port
3140  *
3141  * Context: task context, might sleep
3142  *
3143  * This unhooks (and hangs up) the specified port structure from the core
3144  * driver. No further calls will be made to the low-level code for this port.
3145  */
3146 int uart_remove_one_port(struct uart_driver *drv, struct uart_port *uport)
3147 {
3148     struct uart_state *state = drv->state + uport->line;
3149     struct tty_port *port = &state->port;
3150     struct uart_port *uart_port;
3151     struct tty_struct *tty;
3152     int ret = 0;
3153 
3154     mutex_lock(&port_mutex);
3155 
3156     /*
3157      * Mark the port "dead" - this prevents any opens from
3158      * succeeding while we shut down the port.
3159      */
3160     mutex_lock(&port->mutex);
3161     uart_port = uart_port_check(state);
3162     if (uart_port != uport)
3163         dev_alert(uport->dev, "Removing wrong port: %p != %p\n",
3164               uart_port, uport);
3165 
3166     if (!uart_port) {
3167         mutex_unlock(&port->mutex);
3168         ret = -EINVAL;
3169         goto out;
3170     }
3171     uport->flags |= UPF_DEAD;
3172     mutex_unlock(&port->mutex);
3173 
3174     /*
3175      * Remove the devices from the tty layer
3176      */
3177     tty_port_unregister_device(port, drv->tty_driver, uport->line);
3178 
3179     tty = tty_port_tty_get(port);
3180     if (tty) {
3181         tty_vhangup(port->tty);
3182         tty_kref_put(tty);
3183     }
3184 
3185     /*
3186      * If the port is used as a console, unregister it
3187      */
3188     if (uart_console(uport))
3189         unregister_console(uport->cons);
3190 
3191     /*
3192      * Free the port IO and memory resources, if any.
3193      */
3194     if (uport->type != PORT_UNKNOWN && uport->ops->release_port)
3195         uport->ops->release_port(uport);
3196     kfree(uport->tty_groups);
3197     kfree(uport->name);
3198 
3199     /*
3200      * Indicate that there isn't a port here anymore.
3201      */
3202     uport->type = PORT_UNKNOWN;
3203 
3204     mutex_lock(&port->mutex);
3205     WARN_ON(atomic_dec_return(&state->refcount) < 0);
3206     wait_event(state->remove_wait, !atomic_read(&state->refcount));
3207     state->uart_port = NULL;
3208     mutex_unlock(&port->mutex);
3209 out:
3210     mutex_unlock(&port_mutex);
3211 
3212     return ret;
3213 }
3214 EXPORT_SYMBOL(uart_remove_one_port);
3215 
3216 /**
3217  * uart_match_port - are the two ports equivalent?
3218  * @port1: first port
3219  * @port2: second port
3220  *
3221  * This utility function can be used to determine whether two uart_port
3222  * structures describe the same port.
3223  */
3224 bool uart_match_port(const struct uart_port *port1,
3225         const struct uart_port *port2)
3226 {
3227     if (port1->iotype != port2->iotype)
3228         return false;
3229 
3230     switch (port1->iotype) {
3231     case UPIO_PORT:
3232         return port1->iobase == port2->iobase;
3233     case UPIO_HUB6:
3234         return port1->iobase == port2->iobase &&
3235                port1->hub6   == port2->hub6;
3236     case UPIO_MEM:
3237     case UPIO_MEM16:
3238     case UPIO_MEM32:
3239     case UPIO_MEM32BE:
3240     case UPIO_AU:
3241     case UPIO_TSI:
3242         return port1->mapbase == port2->mapbase;
3243     }
3244 
3245     return false;
3246 }
3247 EXPORT_SYMBOL(uart_match_port);
3248 
3249 /**
3250  * uart_handle_dcd_change - handle a change of carrier detect state
3251  * @uport: uart_port structure for the open port
3252  * @status: new carrier detect status, nonzero if active
3253  *
3254  * Caller must hold uport->lock.
3255  */
3256 void uart_handle_dcd_change(struct uart_port *uport, unsigned int status)
3257 {
3258     struct tty_port *port = &uport->state->port;
3259     struct tty_struct *tty = port->tty;
3260     struct tty_ldisc *ld;
3261 
3262     lockdep_assert_held_once(&uport->lock);
3263 
3264     if (tty) {
3265         ld = tty_ldisc_ref(tty);
3266         if (ld) {
3267             if (ld->ops->dcd_change)
3268                 ld->ops->dcd_change(tty, status);
3269             tty_ldisc_deref(ld);
3270         }
3271     }
3272 
3273     uport->icount.dcd++;
3274 
3275     if (uart_dcd_enabled(uport)) {
3276         if (status)
3277             wake_up_interruptible(&port->open_wait);
3278         else if (tty)
3279             tty_hangup(tty);
3280     }
3281 }
3282 EXPORT_SYMBOL_GPL(uart_handle_dcd_change);
3283 
3284 /**
3285  * uart_handle_cts_change - handle a change of clear-to-send state
3286  * @uport: uart_port structure for the open port
3287  * @status: new clear to send status, nonzero if active
3288  *
3289  * Caller must hold uport->lock.
3290  */
3291 void uart_handle_cts_change(struct uart_port *uport, unsigned int status)
3292 {
3293     lockdep_assert_held_once(&uport->lock);
3294 
3295     uport->icount.cts++;
3296 
3297     if (uart_softcts_mode(uport)) {
3298         if (uport->hw_stopped) {
3299             if (status) {
3300                 uport->hw_stopped = 0;
3301                 uport->ops->start_tx(uport);
3302                 uart_write_wakeup(uport);
3303             }
3304         } else {
3305             if (!status) {
3306                 uport->hw_stopped = 1;
3307                 uport->ops->stop_tx(uport);
3308             }
3309         }
3310 
3311     }
3312 }
3313 EXPORT_SYMBOL_GPL(uart_handle_cts_change);
3314 
3315 /**
3316  * uart_insert_char - push a char to the uart layer
3317  *
3318  * User is responsible to call tty_flip_buffer_push when they are done with
3319  * insertion.
3320  *
3321  * @port: corresponding port
3322  * @status: state of the serial port RX buffer (LSR for 8250)
3323  * @overrun: mask of overrun bits in @status
3324  * @ch: character to push
3325  * @flag: flag for the character (see TTY_NORMAL and friends)
3326  */
3327 void uart_insert_char(struct uart_port *port, unsigned int status,
3328          unsigned int overrun, unsigned int ch, unsigned int flag)
3329 {
3330     struct tty_port *tport = &port->state->port;
3331 
3332     if ((status & port->ignore_status_mask & ~overrun) == 0)
3333         if (tty_insert_flip_char(tport, ch, flag) == 0)
3334             ++port->icount.buf_overrun;
3335 
3336     /*
3337      * Overrun is special.  Since it's reported immediately,
3338      * it doesn't affect the current character.
3339      */
3340     if (status & ~port->ignore_status_mask & overrun)
3341         if (tty_insert_flip_char(tport, 0, TTY_OVERRUN) == 0)
3342             ++port->icount.buf_overrun;
3343 }
3344 EXPORT_SYMBOL_GPL(uart_insert_char);
3345 
3346 #ifdef CONFIG_MAGIC_SYSRQ_SERIAL
3347 static const char sysrq_toggle_seq[] = CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE;
3348 
3349 static void uart_sysrq_on(struct work_struct *w)
3350 {
3351     int sysrq_toggle_seq_len = strlen(sysrq_toggle_seq);
3352 
3353     sysrq_toggle_support(1);
3354     pr_info("SysRq is enabled by magic sequence '%*pE' on serial\n",
3355         sysrq_toggle_seq_len, sysrq_toggle_seq);
3356 }
3357 static DECLARE_WORK(sysrq_enable_work, uart_sysrq_on);
3358 
3359 /**
3360  * uart_try_toggle_sysrq - Enables SysRq from serial line
3361  * @port: uart_port structure where char(s) after BREAK met
3362  * @ch: new character in the sequence after received BREAK
3363  *
3364  * Enables magic SysRq when the required sequence is met on port
3365  * (see CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE).
3366  *
3367  * Returns: %false if @ch is out of enabling sequence and should be
3368  * handled some other way, %true if @ch was consumed.
3369  */
3370 bool uart_try_toggle_sysrq(struct uart_port *port, unsigned int ch)
3371 {
3372     int sysrq_toggle_seq_len = strlen(sysrq_toggle_seq);
3373 
3374     if (!sysrq_toggle_seq_len)
3375         return false;
3376 
3377     BUILD_BUG_ON(ARRAY_SIZE(sysrq_toggle_seq) >= U8_MAX);
3378     if (sysrq_toggle_seq[port->sysrq_seq] != ch) {
3379         port->sysrq_seq = 0;
3380         return false;
3381     }
3382 
3383     if (++port->sysrq_seq < sysrq_toggle_seq_len) {
3384         port->sysrq = jiffies + SYSRQ_TIMEOUT;
3385         return true;
3386     }
3387 
3388     schedule_work(&sysrq_enable_work);
3389 
3390     port->sysrq = 0;
3391     return true;
3392 }
3393 EXPORT_SYMBOL_GPL(uart_try_toggle_sysrq);
3394 #endif
3395 
3396 /**
3397  * uart_get_rs485_mode() - retrieve rs485 properties for given uart
3398  * @port: uart device's target port
3399  *
3400  * This function implements the device tree binding described in
3401  * Documentation/devicetree/bindings/serial/rs485.txt.
3402  */
3403 int uart_get_rs485_mode(struct uart_port *port)
3404 {
3405     struct serial_rs485 *rs485conf = &port->rs485;
3406     struct device *dev = port->dev;
3407     u32 rs485_delay[2];
3408     int ret;
3409 
3410     ret = device_property_read_u32_array(dev, "rs485-rts-delay",
3411                          rs485_delay, 2);
3412     if (!ret) {
3413         rs485conf->delay_rts_before_send = rs485_delay[0];
3414         rs485conf->delay_rts_after_send = rs485_delay[1];
3415     } else {
3416         rs485conf->delay_rts_before_send = 0;
3417         rs485conf->delay_rts_after_send = 0;
3418     }
3419 
3420     uart_sanitize_serial_rs485_delays(port, rs485conf);
3421 
3422     /*
3423      * Clear full-duplex and enabled flags, set RTS polarity to active high
3424      * to get to a defined state with the following properties:
3425      */
3426     rs485conf->flags &= ~(SER_RS485_RX_DURING_TX | SER_RS485_ENABLED |
3427                   SER_RS485_TERMINATE_BUS |
3428                   SER_RS485_RTS_AFTER_SEND);
3429     rs485conf->flags |= SER_RS485_RTS_ON_SEND;
3430 
3431     if (device_property_read_bool(dev, "rs485-rx-during-tx"))
3432         rs485conf->flags |= SER_RS485_RX_DURING_TX;
3433 
3434     if (device_property_read_bool(dev, "linux,rs485-enabled-at-boot-time"))
3435         rs485conf->flags |= SER_RS485_ENABLED;
3436 
3437     if (device_property_read_bool(dev, "rs485-rts-active-low")) {
3438         rs485conf->flags &= ~SER_RS485_RTS_ON_SEND;
3439         rs485conf->flags |= SER_RS485_RTS_AFTER_SEND;
3440     }
3441 
3442     /*
3443      * Disabling termination by default is the safe choice:  Else if many
3444      * bus participants enable it, no communication is possible at all.
3445      * Works fine for short cables and users may enable for longer cables.
3446      */
3447     port->rs485_term_gpio = devm_gpiod_get_optional(dev, "rs485-term",
3448                             GPIOD_OUT_LOW);
3449     if (IS_ERR(port->rs485_term_gpio)) {
3450         ret = PTR_ERR(port->rs485_term_gpio);
3451         port->rs485_term_gpio = NULL;
3452         return dev_err_probe(dev, ret, "Cannot get rs485-term-gpios\n");
3453     }
3454     if (port->rs485_term_gpio)
3455         port->rs485_supported.flags |= SER_RS485_TERMINATE_BUS;
3456 
3457     return 0;
3458 }
3459 EXPORT_SYMBOL_GPL(uart_get_rs485_mode);
3460 
3461 /* Compile-time assertions for serial_rs485 layout */
3462 static_assert(offsetof(struct serial_rs485, padding) ==
3463               (offsetof(struct serial_rs485, delay_rts_after_send) + sizeof(__u32)));
3464 static_assert(offsetof(struct serial_rs485, padding1) ==
3465           offsetof(struct serial_rs485, padding[1]));
3466 static_assert((offsetof(struct serial_rs485, padding[4]) + sizeof(__u32)) ==
3467           sizeof(struct serial_rs485));
3468 
3469 MODULE_DESCRIPTION("Serial driver core");
3470 MODULE_LICENSE("GPL");