• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  Driver core for serial ports
4  *
5  *  Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
6  *
7  *  Copyright 1999 ARM Limited
8  *  Copyright (C) 2000-2001 Deep Blue Solutions Ltd.
9  */
10 #include <linux/module.h>
11 #include <linux/tty.h>
12 #include <linux/tty_flip.h>
13 #include <linux/slab.h>
14 #include <linux/sched/signal.h>
15 #include <linux/init.h>
16 #include <linux/console.h>
17 #include <linux/gpio/consumer.h>
18 #include <linux/of.h>
19 #include <linux/proc_fs.h>
20 #include <linux/seq_file.h>
21 #include <linux/device.h>
22 #include <linux/serial.h> /* for serial_state and serial_icounter_struct */
23 #include <linux/serial_core.h>
24 #include <linux/sysrq.h>
25 #include <linux/delay.h>
26 #include <linux/mutex.h>
27 #include <linux/math64.h>
28 #include <linux/security.h>
29 
30 #include <linux/irq.h>
31 #include <linux/uaccess.h>
32 
33 /*
34  * This is used to lock changes in serial line configuration.
35  */
36 static DEFINE_MUTEX(port_mutex);
37 
38 /*
39  * lockdep: port->lock is initialized in two places, but we
40  *          want only one lock-class:
41  */
42 static struct lock_class_key port_lock_key;
43 
44 #define HIGH_BITS_OFFSET	((sizeof(long)-sizeof(int))*8)
45 
46 /*
47  * Max time with active RTS before/after data is sent.
48  */
49 #define RS485_MAX_RTS_DELAY	100 /* msecs */
50 
51 static void uart_wait_until_sent(struct tty_struct *tty, int timeout);
52 static void uart_change_pm(struct uart_state *state,
53 			   enum uart_pm_state pm_state);
54 
55 static void uart_port_shutdown(struct tty_port *port);
56 
uart_dcd_enabled(struct uart_port * uport)57 static int uart_dcd_enabled(struct uart_port *uport)
58 {
59 	return !!(uport->status & UPSTAT_DCD_ENABLE);
60 }
61 
uart_port_ref(struct uart_state * state)62 static inline struct uart_port *uart_port_ref(struct uart_state *state)
63 {
64 	if (atomic_add_unless(&state->refcount, 1, 0))
65 		return state->uart_port;
66 	return NULL;
67 }
68 
uart_port_deref(struct uart_port * uport)69 static inline void uart_port_deref(struct uart_port *uport)
70 {
71 	if (atomic_dec_and_test(&uport->state->refcount))
72 		wake_up(&uport->state->remove_wait);
73 }
74 
75 #define uart_port_lock(state, flags)					\
76 	({								\
77 		struct uart_port *__uport = uart_port_ref(state);	\
78 		if (__uport)						\
79 			spin_lock_irqsave(&__uport->lock, flags);	\
80 		__uport;						\
81 	})
82 
83 #define uart_port_unlock(uport, flags)					\
84 	({								\
85 		struct uart_port *__uport = uport;			\
86 		if (__uport) {						\
87 			spin_unlock_irqrestore(&__uport->lock, flags);	\
88 			uart_port_deref(__uport);			\
89 		}							\
90 	})
91 
uart_port_check(struct uart_state * state)92 static inline struct uart_port *uart_port_check(struct uart_state *state)
93 {
94 	lockdep_assert_held(&state->port.mutex);
95 	return state->uart_port;
96 }
97 
98 /**
99  * uart_write_wakeup - schedule write processing
100  * @port: port to be processed
101  *
102  * This routine is used by the interrupt handler to schedule processing in the
103  * software interrupt portion of the driver. A driver is expected to call this
104  * function when the number of characters in the transmit buffer have dropped
105  * below a threshold.
106  *
107  * Locking: @port->lock should be held
108  */
uart_write_wakeup(struct uart_port * port)109 void uart_write_wakeup(struct uart_port *port)
110 {
111 	struct uart_state *state = port->state;
112 	/*
113 	 * This means you called this function _after_ the port was
114 	 * closed.  No cookie for you.
115 	 */
116 	BUG_ON(!state);
117 	tty_port_tty_wakeup(&state->port);
118 }
119 EXPORT_SYMBOL(uart_write_wakeup);
120 
uart_stop(struct tty_struct * tty)121 static void uart_stop(struct tty_struct *tty)
122 {
123 	struct uart_state *state = tty->driver_data;
124 	struct uart_port *port;
125 	unsigned long flags;
126 
127 	port = uart_port_lock(state, flags);
128 	if (port)
129 		port->ops->stop_tx(port);
130 	uart_port_unlock(port, flags);
131 }
132 
__uart_start(struct tty_struct * tty)133 static void __uart_start(struct tty_struct *tty)
134 {
135 	struct uart_state *state = tty->driver_data;
136 	struct uart_port *port = state->uart_port;
137 
138 	if (port && !uart_tx_stopped(port))
139 		port->ops->start_tx(port);
140 }
141 
uart_start(struct tty_struct * tty)142 static void uart_start(struct tty_struct *tty)
143 {
144 	struct uart_state *state = tty->driver_data;
145 	struct uart_port *port;
146 	unsigned long flags;
147 
148 	port = uart_port_lock(state, flags);
149 	__uart_start(tty);
150 	uart_port_unlock(port, flags);
151 }
152 
153 static void
uart_update_mctrl(struct uart_port * port,unsigned int set,unsigned int clear)154 uart_update_mctrl(struct uart_port *port, unsigned int set, unsigned int clear)
155 {
156 	unsigned long flags;
157 	unsigned int old;
158 
159 	spin_lock_irqsave(&port->lock, flags);
160 	old = port->mctrl;
161 	port->mctrl = (old & ~clear) | set;
162 	if (old != port->mctrl && !(port->rs485.flags & SER_RS485_ENABLED))
163 		port->ops->set_mctrl(port, port->mctrl);
164 	spin_unlock_irqrestore(&port->lock, flags);
165 }
166 
167 #define uart_set_mctrl(port, set)	uart_update_mctrl(port, set, 0)
168 #define uart_clear_mctrl(port, clear)	uart_update_mctrl(port, 0, clear)
169 
uart_port_dtr_rts(struct uart_port * uport,int raise)170 static void uart_port_dtr_rts(struct uart_port *uport, int raise)
171 {
172 	if (raise)
173 		uart_set_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
174 	else
175 		uart_clear_mctrl(uport, TIOCM_DTR | TIOCM_RTS);
176 }
177 
178 /* Caller holds port mutex */
uart_change_line_settings(struct tty_struct * tty,struct uart_state * state,const struct ktermios * old_termios)179 static void uart_change_line_settings(struct tty_struct *tty, struct uart_state *state,
180 				      const struct ktermios *old_termios)
181 {
182 	struct uart_port *uport = uart_port_check(state);
183 	struct ktermios *termios;
184 	int hw_stopped;
185 
186 	/*
187 	 * If we have no tty, termios, or the port does not exist,
188 	 * then we can't set the parameters for this port.
189 	 */
190 	if (!tty || uport->type == PORT_UNKNOWN)
191 		return;
192 
193 	termios = &tty->termios;
194 	uport->ops->set_termios(uport, termios, old_termios);
195 
196 	/*
197 	 * Set modem status enables based on termios cflag
198 	 */
199 	spin_lock_irq(&uport->lock);
200 	if (termios->c_cflag & CRTSCTS)
201 		uport->status |= UPSTAT_CTS_ENABLE;
202 	else
203 		uport->status &= ~UPSTAT_CTS_ENABLE;
204 
205 	if (termios->c_cflag & CLOCAL)
206 		uport->status &= ~UPSTAT_DCD_ENABLE;
207 	else
208 		uport->status |= UPSTAT_DCD_ENABLE;
209 
210 	/* reset sw-assisted CTS flow control based on (possibly) new mode */
211 	hw_stopped = uport->hw_stopped;
212 	uport->hw_stopped = uart_softcts_mode(uport) &&
213 			    !(uport->ops->get_mctrl(uport) & TIOCM_CTS);
214 	if (uport->hw_stopped) {
215 		if (!hw_stopped)
216 			uport->ops->stop_tx(uport);
217 	} else {
218 		if (hw_stopped)
219 			__uart_start(tty);
220 	}
221 	spin_unlock_irq(&uport->lock);
222 }
223 
224 /*
225  * Startup the port.  This will be called once per open.  All calls
226  * will be serialised by the per-port mutex.
227  */
uart_port_startup(struct tty_struct * tty,struct uart_state * state,int init_hw)228 static int uart_port_startup(struct tty_struct *tty, struct uart_state *state,
229 		int init_hw)
230 {
231 	struct uart_port *uport = uart_port_check(state);
232 	unsigned long flags;
233 	unsigned long page;
234 	int retval = 0;
235 
236 	if (uport->type == PORT_UNKNOWN)
237 		return 1;
238 
239 	/*
240 	 * Make sure the device is in D0 state.
241 	 */
242 	uart_change_pm(state, UART_PM_STATE_ON);
243 
244 	/*
245 	 * Initialise and allocate the transmit and temporary
246 	 * buffer.
247 	 */
248 	page = get_zeroed_page(GFP_KERNEL);
249 	if (!page)
250 		return -ENOMEM;
251 
252 	uart_port_lock(state, flags);
253 	if (!state->xmit.buf) {
254 		state->xmit.buf = (unsigned char *) page;
255 		uart_circ_clear(&state->xmit);
256 		uart_port_unlock(uport, flags);
257 	} else {
258 		uart_port_unlock(uport, flags);
259 		/*
260 		 * Do not free() the page under the port lock, see
261 		 * uart_shutdown().
262 		 */
263 		free_page(page);
264 	}
265 
266 	retval = uport->ops->startup(uport);
267 	if (retval == 0) {
268 		if (uart_console(uport) && uport->cons->cflag) {
269 			tty->termios.c_cflag = uport->cons->cflag;
270 			tty->termios.c_ispeed = uport->cons->ispeed;
271 			tty->termios.c_ospeed = uport->cons->ospeed;
272 			uport->cons->cflag = 0;
273 			uport->cons->ispeed = 0;
274 			uport->cons->ospeed = 0;
275 		}
276 		/*
277 		 * Initialise the hardware port settings.
278 		 */
279 		uart_change_line_settings(tty, state, NULL);
280 
281 		/*
282 		 * Setup the RTS and DTR signals once the
283 		 * port is open and ready to respond.
284 		 */
285 		if (init_hw && C_BAUD(tty))
286 			uart_port_dtr_rts(uport, 1);
287 	}
288 
289 	/*
290 	 * This is to allow setserial on this port. People may want to set
291 	 * port/irq/type and then reconfigure the port properly if it failed
292 	 * now.
293 	 */
294 	if (retval && capable(CAP_SYS_ADMIN))
295 		return 1;
296 
297 	return retval;
298 }
299 
uart_startup(struct tty_struct * tty,struct uart_state * state,int init_hw)300 static int uart_startup(struct tty_struct *tty, struct uart_state *state,
301 		int init_hw)
302 {
303 	struct tty_port *port = &state->port;
304 	int retval;
305 
306 	if (tty_port_initialized(port))
307 		return 0;
308 
309 	retval = uart_port_startup(tty, state, init_hw);
310 	if (retval)
311 		set_bit(TTY_IO_ERROR, &tty->flags);
312 
313 	return retval;
314 }
315 
316 /*
317  * This routine will shutdown a serial port; interrupts are disabled, and
318  * DTR is dropped if the hangup on close termio flag is on.  Calls to
319  * uart_shutdown are serialised by the per-port semaphore.
320  *
321  * uport == NULL if uart_port has already been removed
322  */
uart_shutdown(struct tty_struct * tty,struct uart_state * state)323 static void uart_shutdown(struct tty_struct *tty, struct uart_state *state)
324 {
325 	struct uart_port *uport = uart_port_check(state);
326 	struct tty_port *port = &state->port;
327 	unsigned long flags;
328 	char *xmit_buf = NULL;
329 
330 	/*
331 	 * Set the TTY IO error marker
332 	 */
333 	if (tty)
334 		set_bit(TTY_IO_ERROR, &tty->flags);
335 
336 	if (tty_port_initialized(port)) {
337 		tty_port_set_initialized(port, 0);
338 
339 		/*
340 		 * Turn off DTR and RTS early.
341 		 */
342 		if (uport && uart_console(uport) && tty) {
343 			uport->cons->cflag = tty->termios.c_cflag;
344 			uport->cons->ispeed = tty->termios.c_ispeed;
345 			uport->cons->ospeed = tty->termios.c_ospeed;
346 		}
347 
348 		if (!tty || C_HUPCL(tty))
349 			uart_port_dtr_rts(uport, 0);
350 
351 		uart_port_shutdown(port);
352 	}
353 
354 	/*
355 	 * It's possible for shutdown to be called after suspend if we get
356 	 * a DCD drop (hangup) at just the right time.  Clear suspended bit so
357 	 * we don't try to resume a port that has been shutdown.
358 	 */
359 	tty_port_set_suspended(port, 0);
360 
361 	/*
362 	 * Do not free() the transmit buffer page under the port lock since
363 	 * this can create various circular locking scenarios. For instance,
364 	 * console driver may need to allocate/free a debug object, which
365 	 * can endup in printk() recursion.
366 	 */
367 	uart_port_lock(state, flags);
368 	xmit_buf = state->xmit.buf;
369 	state->xmit.buf = NULL;
370 	uart_port_unlock(uport, flags);
371 
372 	free_page((unsigned long)xmit_buf);
373 }
374 
375 /**
376  * uart_update_timeout - update per-port frame timing information
377  * @port: uart_port structure describing the port
378  * @cflag: termios cflag value
379  * @baud: speed of the port
380  *
381  * Set the @port frame timing information from which the FIFO timeout value is
382  * derived. The @cflag value should reflect the actual hardware settings as
383  * number of bits, parity, stop bits and baud rate is taken into account here.
384  *
385  * Locking: caller is expected to take @port->lock
386  */
387 void
uart_update_timeout(struct uart_port * port,unsigned int cflag,unsigned int baud)388 uart_update_timeout(struct uart_port *port, unsigned int cflag,
389 		    unsigned int baud)
390 {
391 	unsigned int size = tty_get_frame_size(cflag);
392 	u64 frame_time;
393 
394 	frame_time = (u64)size * NSEC_PER_SEC;
395 	port->frame_time = DIV64_U64_ROUND_UP(frame_time, baud);
396 }
397 EXPORT_SYMBOL(uart_update_timeout);
398 
399 /**
400  * uart_get_baud_rate - return baud rate for a particular port
401  * @port: uart_port structure describing the port in question.
402  * @termios: desired termios settings
403  * @old: old termios (or %NULL)
404  * @min: minimum acceptable baud rate
405  * @max: maximum acceptable baud rate
406  *
407  * Decode the termios structure into a numeric baud rate, taking account of the
408  * magic 38400 baud rate (with spd_* flags), and mapping the %B0 rate to 9600
409  * baud.
410  *
411  * If the new baud rate is invalid, try the @old termios setting. If it's still
412  * invalid, we try 9600 baud.
413  *
414  * The @termios structure is updated to reflect the baud rate we're actually
415  * going to be using. Don't do this for the case where B0 is requested ("hang
416  * up").
417  *
418  * Locking: caller dependent
419  */
420 unsigned int
uart_get_baud_rate(struct uart_port * port,struct ktermios * termios,const struct ktermios * old,unsigned int min,unsigned int max)421 uart_get_baud_rate(struct uart_port *port, struct ktermios *termios,
422 		   const struct ktermios *old, unsigned int min, unsigned int max)
423 {
424 	unsigned int try;
425 	unsigned int baud;
426 	unsigned int altbaud;
427 	int hung_up = 0;
428 	upf_t flags = port->flags & UPF_SPD_MASK;
429 
430 	switch (flags) {
431 	case UPF_SPD_HI:
432 		altbaud = 57600;
433 		break;
434 	case UPF_SPD_VHI:
435 		altbaud = 115200;
436 		break;
437 	case UPF_SPD_SHI:
438 		altbaud = 230400;
439 		break;
440 	case UPF_SPD_WARP:
441 		altbaud = 460800;
442 		break;
443 	default:
444 		altbaud = 38400;
445 		break;
446 	}
447 
448 	for (try = 0; try < 2; try++) {
449 		baud = tty_termios_baud_rate(termios);
450 
451 		/*
452 		 * The spd_hi, spd_vhi, spd_shi, spd_warp kludge...
453 		 * Die! Die! Die!
454 		 */
455 		if (try == 0 && baud == 38400)
456 			baud = altbaud;
457 
458 		/*
459 		 * Special case: B0 rate.
460 		 */
461 		if (baud == 0) {
462 			hung_up = 1;
463 			baud = 9600;
464 		}
465 
466 		if (baud >= min && baud <= max)
467 			return baud;
468 
469 		/*
470 		 * Oops, the quotient was zero.  Try again with
471 		 * the old baud rate if possible.
472 		 */
473 		termios->c_cflag &= ~CBAUD;
474 		if (old) {
475 			baud = tty_termios_baud_rate(old);
476 			if (!hung_up)
477 				tty_termios_encode_baud_rate(termios,
478 								baud, baud);
479 			old = NULL;
480 			continue;
481 		}
482 
483 		/*
484 		 * As a last resort, if the range cannot be met then clip to
485 		 * the nearest chip supported rate.
486 		 */
487 		if (!hung_up) {
488 			if (baud <= min)
489 				tty_termios_encode_baud_rate(termios,
490 							min + 1, min + 1);
491 			else
492 				tty_termios_encode_baud_rate(termios,
493 							max - 1, max - 1);
494 		}
495 	}
496 	/* Should never happen */
497 	WARN_ON(1);
498 	return 0;
499 }
500 EXPORT_SYMBOL(uart_get_baud_rate);
501 
502 /**
503  * uart_get_divisor - return uart clock divisor
504  * @port: uart_port structure describing the port
505  * @baud: desired baud rate
506  *
507  * Calculate the divisor (baud_base / baud) for the specified @baud,
508  * appropriately rounded.
509  *
510  * If 38400 baud and custom divisor is selected, return the custom divisor
511  * instead.
512  *
513  * Locking: caller dependent
514  */
515 unsigned int
uart_get_divisor(struct uart_port * port,unsigned int baud)516 uart_get_divisor(struct uart_port *port, unsigned int baud)
517 {
518 	unsigned int quot;
519 
520 	/*
521 	 * Old custom speed handling.
522 	 */
523 	if (baud == 38400 && (port->flags & UPF_SPD_MASK) == UPF_SPD_CUST)
524 		quot = port->custom_divisor;
525 	else
526 		quot = DIV_ROUND_CLOSEST(port->uartclk, 16 * baud);
527 
528 	return quot;
529 }
530 EXPORT_SYMBOL(uart_get_divisor);
531 
uart_put_char(struct tty_struct * tty,unsigned char c)532 static int uart_put_char(struct tty_struct *tty, unsigned char c)
533 {
534 	struct uart_state *state = tty->driver_data;
535 	struct uart_port *port;
536 	struct circ_buf *circ;
537 	unsigned long flags;
538 	int ret = 0;
539 
540 	circ = &state->xmit;
541 	port = uart_port_lock(state, flags);
542 	if (!circ->buf) {
543 		uart_port_unlock(port, flags);
544 		return 0;
545 	}
546 
547 	if (port && uart_circ_chars_free(circ) != 0) {
548 		circ->buf[circ->head] = c;
549 		circ->head = (circ->head + 1) & (UART_XMIT_SIZE - 1);
550 		ret = 1;
551 	}
552 	uart_port_unlock(port, flags);
553 	return ret;
554 }
555 
uart_flush_chars(struct tty_struct * tty)556 static void uart_flush_chars(struct tty_struct *tty)
557 {
558 	uart_start(tty);
559 }
560 
uart_write(struct tty_struct * tty,const unsigned char * buf,int count)561 static int uart_write(struct tty_struct *tty,
562 					const unsigned char *buf, int count)
563 {
564 	struct uart_state *state = tty->driver_data;
565 	struct uart_port *port;
566 	struct circ_buf *circ;
567 	unsigned long flags;
568 	int c, ret = 0;
569 
570 	/*
571 	 * This means you called this function _after_ the port was
572 	 * closed.  No cookie for you.
573 	 */
574 	if (!state) {
575 		WARN_ON(1);
576 		return -EL3HLT;
577 	}
578 
579 	port = uart_port_lock(state, flags);
580 	circ = &state->xmit;
581 	if (!circ->buf) {
582 		uart_port_unlock(port, flags);
583 		return 0;
584 	}
585 
586 	while (port) {
587 		c = CIRC_SPACE_TO_END(circ->head, circ->tail, UART_XMIT_SIZE);
588 		if (count < c)
589 			c = count;
590 		if (c <= 0)
591 			break;
592 		memcpy(circ->buf + circ->head, buf, c);
593 		circ->head = (circ->head + c) & (UART_XMIT_SIZE - 1);
594 		buf += c;
595 		count -= c;
596 		ret += c;
597 	}
598 
599 	__uart_start(tty);
600 	uart_port_unlock(port, flags);
601 	return ret;
602 }
603 
uart_write_room(struct tty_struct * tty)604 static unsigned int uart_write_room(struct tty_struct *tty)
605 {
606 	struct uart_state *state = tty->driver_data;
607 	struct uart_port *port;
608 	unsigned long flags;
609 	unsigned int ret;
610 
611 	port = uart_port_lock(state, flags);
612 	ret = uart_circ_chars_free(&state->xmit);
613 	uart_port_unlock(port, flags);
614 	return ret;
615 }
616 
uart_chars_in_buffer(struct tty_struct * tty)617 static unsigned int uart_chars_in_buffer(struct tty_struct *tty)
618 {
619 	struct uart_state *state = tty->driver_data;
620 	struct uart_port *port;
621 	unsigned long flags;
622 	unsigned int ret;
623 
624 	port = uart_port_lock(state, flags);
625 	ret = uart_circ_chars_pending(&state->xmit);
626 	uart_port_unlock(port, flags);
627 	return ret;
628 }
629 
uart_flush_buffer(struct tty_struct * tty)630 static void uart_flush_buffer(struct tty_struct *tty)
631 {
632 	struct uart_state *state = tty->driver_data;
633 	struct uart_port *port;
634 	unsigned long flags;
635 
636 	/*
637 	 * This means you called this function _after_ the port was
638 	 * closed.  No cookie for you.
639 	 */
640 	if (!state) {
641 		WARN_ON(1);
642 		return;
643 	}
644 
645 	pr_debug("uart_flush_buffer(%d) called\n", tty->index);
646 
647 	port = uart_port_lock(state, flags);
648 	if (!port)
649 		return;
650 	uart_circ_clear(&state->xmit);
651 	if (port->ops->flush_buffer)
652 		port->ops->flush_buffer(port);
653 	uart_port_unlock(port, flags);
654 	tty_port_tty_wakeup(&state->port);
655 }
656 
657 /*
658  * This function performs low-level write of high-priority XON/XOFF
659  * character and accounting for it.
660  *
661  * Requires uart_port to implement .serial_out().
662  */
uart_xchar_out(struct uart_port * uport,int offset)663 void uart_xchar_out(struct uart_port *uport, int offset)
664 {
665 	serial_port_out(uport, offset, uport->x_char);
666 	uport->icount.tx++;
667 	uport->x_char = 0;
668 }
669 EXPORT_SYMBOL_GPL(uart_xchar_out);
670 
671 /*
672  * This function is used to send a high-priority XON/XOFF character to
673  * the device
674  */
uart_send_xchar(struct tty_struct * tty,char ch)675 static void uart_send_xchar(struct tty_struct *tty, char ch)
676 {
677 	struct uart_state *state = tty->driver_data;
678 	struct uart_port *port;
679 	unsigned long flags;
680 
681 	port = uart_port_ref(state);
682 	if (!port)
683 		return;
684 
685 	if (port->ops->send_xchar)
686 		port->ops->send_xchar(port, ch);
687 	else {
688 		spin_lock_irqsave(&port->lock, flags);
689 		port->x_char = ch;
690 		if (ch)
691 			port->ops->start_tx(port);
692 		spin_unlock_irqrestore(&port->lock, flags);
693 	}
694 	uart_port_deref(port);
695 }
696 
uart_throttle(struct tty_struct * tty)697 static void uart_throttle(struct tty_struct *tty)
698 {
699 	struct uart_state *state = tty->driver_data;
700 	upstat_t mask = UPSTAT_SYNC_FIFO;
701 	struct uart_port *port;
702 
703 	port = uart_port_ref(state);
704 	if (!port)
705 		return;
706 
707 	if (I_IXOFF(tty))
708 		mask |= UPSTAT_AUTOXOFF;
709 	if (C_CRTSCTS(tty))
710 		mask |= UPSTAT_AUTORTS;
711 
712 	if (port->status & mask) {
713 		port->ops->throttle(port);
714 		mask &= ~port->status;
715 	}
716 
717 	if (mask & UPSTAT_AUTORTS)
718 		uart_clear_mctrl(port, TIOCM_RTS);
719 
720 	if (mask & UPSTAT_AUTOXOFF)
721 		uart_send_xchar(tty, STOP_CHAR(tty));
722 
723 	uart_port_deref(port);
724 }
725 
uart_unthrottle(struct tty_struct * tty)726 static void uart_unthrottle(struct tty_struct *tty)
727 {
728 	struct uart_state *state = tty->driver_data;
729 	upstat_t mask = UPSTAT_SYNC_FIFO;
730 	struct uart_port *port;
731 
732 	port = uart_port_ref(state);
733 	if (!port)
734 		return;
735 
736 	if (I_IXOFF(tty))
737 		mask |= UPSTAT_AUTOXOFF;
738 	if (C_CRTSCTS(tty))
739 		mask |= UPSTAT_AUTORTS;
740 
741 	if (port->status & mask) {
742 		port->ops->unthrottle(port);
743 		mask &= ~port->status;
744 	}
745 
746 	if (mask & UPSTAT_AUTORTS)
747 		uart_set_mctrl(port, TIOCM_RTS);
748 
749 	if (mask & UPSTAT_AUTOXOFF)
750 		uart_send_xchar(tty, START_CHAR(tty));
751 
752 	uart_port_deref(port);
753 }
754 
uart_get_info(struct tty_port * port,struct serial_struct * retinfo)755 static int uart_get_info(struct tty_port *port, struct serial_struct *retinfo)
756 {
757 	struct uart_state *state = container_of(port, struct uart_state, port);
758 	struct uart_port *uport;
759 	int ret = -ENODEV;
760 
761 	/*
762 	 * Ensure the state we copy is consistent and no hardware changes
763 	 * occur as we go
764 	 */
765 	mutex_lock(&port->mutex);
766 	uport = uart_port_check(state);
767 	if (!uport)
768 		goto out;
769 
770 	retinfo->type	    = uport->type;
771 	retinfo->line	    = uport->line;
772 	retinfo->port	    = uport->iobase;
773 	if (HIGH_BITS_OFFSET)
774 		retinfo->port_high = (long) uport->iobase >> HIGH_BITS_OFFSET;
775 	retinfo->irq		    = uport->irq;
776 	retinfo->flags	    = (__force int)uport->flags;
777 	retinfo->xmit_fifo_size  = uport->fifosize;
778 	retinfo->baud_base	    = uport->uartclk / 16;
779 	retinfo->close_delay	    = jiffies_to_msecs(port->close_delay) / 10;
780 	retinfo->closing_wait    = port->closing_wait == ASYNC_CLOSING_WAIT_NONE ?
781 				ASYNC_CLOSING_WAIT_NONE :
782 				jiffies_to_msecs(port->closing_wait) / 10;
783 	retinfo->custom_divisor  = uport->custom_divisor;
784 	retinfo->hub6	    = uport->hub6;
785 	retinfo->io_type         = uport->iotype;
786 	retinfo->iomem_reg_shift = uport->regshift;
787 	retinfo->iomem_base      = (void *)(unsigned long)uport->mapbase;
788 
789 	ret = 0;
790 out:
791 	mutex_unlock(&port->mutex);
792 	return ret;
793 }
794 
uart_get_info_user(struct tty_struct * tty,struct serial_struct * ss)795 static int uart_get_info_user(struct tty_struct *tty,
796 			 struct serial_struct *ss)
797 {
798 	struct uart_state *state = tty->driver_data;
799 	struct tty_port *port = &state->port;
800 
801 	return uart_get_info(port, ss) < 0 ? -EIO : 0;
802 }
803 
uart_set_info(struct tty_struct * tty,struct tty_port * port,struct uart_state * state,struct serial_struct * new_info)804 static int uart_set_info(struct tty_struct *tty, struct tty_port *port,
805 			 struct uart_state *state,
806 			 struct serial_struct *new_info)
807 {
808 	struct uart_port *uport = uart_port_check(state);
809 	unsigned long new_port;
810 	unsigned int change_irq, change_port, closing_wait;
811 	unsigned int old_custom_divisor, close_delay;
812 	upf_t old_flags, new_flags;
813 	int retval = 0;
814 
815 	if (!uport)
816 		return -EIO;
817 
818 	new_port = new_info->port;
819 	if (HIGH_BITS_OFFSET)
820 		new_port += (unsigned long) new_info->port_high << HIGH_BITS_OFFSET;
821 
822 	new_info->irq = irq_canonicalize(new_info->irq);
823 	close_delay = msecs_to_jiffies(new_info->close_delay * 10);
824 	closing_wait = new_info->closing_wait == ASYNC_CLOSING_WAIT_NONE ?
825 			ASYNC_CLOSING_WAIT_NONE :
826 			msecs_to_jiffies(new_info->closing_wait * 10);
827 
828 
829 	change_irq  = !(uport->flags & UPF_FIXED_PORT)
830 		&& new_info->irq != uport->irq;
831 
832 	/*
833 	 * Since changing the 'type' of the port changes its resource
834 	 * allocations, we should treat type changes the same as
835 	 * IO port changes.
836 	 */
837 	change_port = !(uport->flags & UPF_FIXED_PORT)
838 		&& (new_port != uport->iobase ||
839 		    (unsigned long)new_info->iomem_base != uport->mapbase ||
840 		    new_info->hub6 != uport->hub6 ||
841 		    new_info->io_type != uport->iotype ||
842 		    new_info->iomem_reg_shift != uport->regshift ||
843 		    new_info->type != uport->type);
844 
845 	old_flags = uport->flags;
846 	new_flags = (__force upf_t)new_info->flags;
847 	old_custom_divisor = uport->custom_divisor;
848 
849 	if (!capable(CAP_SYS_ADMIN)) {
850 		retval = -EPERM;
851 		if (change_irq || change_port ||
852 		    (new_info->baud_base != uport->uartclk / 16) ||
853 		    (close_delay != port->close_delay) ||
854 		    (closing_wait != port->closing_wait) ||
855 		    (new_info->xmit_fifo_size &&
856 		     new_info->xmit_fifo_size != uport->fifosize) ||
857 		    (((new_flags ^ old_flags) & ~UPF_USR_MASK) != 0))
858 			goto exit;
859 		uport->flags = ((uport->flags & ~UPF_USR_MASK) |
860 			       (new_flags & UPF_USR_MASK));
861 		uport->custom_divisor = new_info->custom_divisor;
862 		goto check_and_exit;
863 	}
864 
865 	if (change_irq || change_port) {
866 		retval = security_locked_down(LOCKDOWN_TIOCSSERIAL);
867 		if (retval)
868 			goto exit;
869 	}
870 
871 	/*
872 	 * Ask the low level driver to verify the settings.
873 	 */
874 	if (uport->ops->verify_port)
875 		retval = uport->ops->verify_port(uport, new_info);
876 
877 	if ((new_info->irq >= nr_irqs) || (new_info->irq < 0) ||
878 	    (new_info->baud_base < 9600))
879 		retval = -EINVAL;
880 
881 	if (retval)
882 		goto exit;
883 
884 	if (change_port || change_irq) {
885 		retval = -EBUSY;
886 
887 		/*
888 		 * Make sure that we are the sole user of this port.
889 		 */
890 		if (tty_port_users(port) > 1)
891 			goto exit;
892 
893 		/*
894 		 * We need to shutdown the serial port at the old
895 		 * port/type/irq combination.
896 		 */
897 		uart_shutdown(tty, state);
898 	}
899 
900 	if (change_port) {
901 		unsigned long old_iobase, old_mapbase;
902 		unsigned int old_type, old_iotype, old_hub6, old_shift;
903 
904 		old_iobase = uport->iobase;
905 		old_mapbase = uport->mapbase;
906 		old_type = uport->type;
907 		old_hub6 = uport->hub6;
908 		old_iotype = uport->iotype;
909 		old_shift = uport->regshift;
910 
911 		/*
912 		 * Free and release old regions
913 		 */
914 		if (old_type != PORT_UNKNOWN && uport->ops->release_port)
915 			uport->ops->release_port(uport);
916 
917 		uport->iobase = new_port;
918 		uport->type = new_info->type;
919 		uport->hub6 = new_info->hub6;
920 		uport->iotype = new_info->io_type;
921 		uport->regshift = new_info->iomem_reg_shift;
922 		uport->mapbase = (unsigned long)new_info->iomem_base;
923 
924 		/*
925 		 * Claim and map the new regions
926 		 */
927 		if (uport->type != PORT_UNKNOWN && uport->ops->request_port) {
928 			retval = uport->ops->request_port(uport);
929 		} else {
930 			/* Always success - Jean II */
931 			retval = 0;
932 		}
933 
934 		/*
935 		 * If we fail to request resources for the
936 		 * new port, try to restore the old settings.
937 		 */
938 		if (retval) {
939 			uport->iobase = old_iobase;
940 			uport->type = old_type;
941 			uport->hub6 = old_hub6;
942 			uport->iotype = old_iotype;
943 			uport->regshift = old_shift;
944 			uport->mapbase = old_mapbase;
945 
946 			if (old_type != PORT_UNKNOWN) {
947 				retval = uport->ops->request_port(uport);
948 				/*
949 				 * If we failed to restore the old settings,
950 				 * we fail like this.
951 				 */
952 				if (retval)
953 					uport->type = PORT_UNKNOWN;
954 
955 				/*
956 				 * We failed anyway.
957 				 */
958 				retval = -EBUSY;
959 			}
960 
961 			/* Added to return the correct error -Ram Gupta */
962 			goto exit;
963 		}
964 	}
965 
966 	if (change_irq)
967 		uport->irq      = new_info->irq;
968 	if (!(uport->flags & UPF_FIXED_PORT))
969 		uport->uartclk  = new_info->baud_base * 16;
970 	uport->flags            = (uport->flags & ~UPF_CHANGE_MASK) |
971 				 (new_flags & UPF_CHANGE_MASK);
972 	uport->custom_divisor   = new_info->custom_divisor;
973 	port->close_delay     = close_delay;
974 	port->closing_wait    = closing_wait;
975 	if (new_info->xmit_fifo_size)
976 		uport->fifosize = new_info->xmit_fifo_size;
977 
978  check_and_exit:
979 	retval = 0;
980 	if (uport->type == PORT_UNKNOWN)
981 		goto exit;
982 	if (tty_port_initialized(port)) {
983 		if (((old_flags ^ uport->flags) & UPF_SPD_MASK) ||
984 		    old_custom_divisor != uport->custom_divisor) {
985 			/*
986 			 * If they're setting up a custom divisor or speed,
987 			 * instead of clearing it, then bitch about it.
988 			 */
989 			if (uport->flags & UPF_SPD_MASK) {
990 				dev_notice_ratelimited(uport->dev,
991 				       "%s sets custom speed on %s. This is deprecated.\n",
992 				      current->comm,
993 				      tty_name(port->tty));
994 			}
995 			uart_change_line_settings(tty, state, NULL);
996 		}
997 	} else {
998 		retval = uart_startup(tty, state, 1);
999 		if (retval == 0)
1000 			tty_port_set_initialized(port, true);
1001 		if (retval > 0)
1002 			retval = 0;
1003 	}
1004  exit:
1005 	return retval;
1006 }
1007 
uart_set_info_user(struct tty_struct * tty,struct serial_struct * ss)1008 static int uart_set_info_user(struct tty_struct *tty, struct serial_struct *ss)
1009 {
1010 	struct uart_state *state = tty->driver_data;
1011 	struct tty_port *port = &state->port;
1012 	int retval;
1013 
1014 	down_write(&tty->termios_rwsem);
1015 	/*
1016 	 * This semaphore protects port->count.  It is also
1017 	 * very useful to prevent opens.  Also, take the
1018 	 * port configuration semaphore to make sure that a
1019 	 * module insertion/removal doesn't change anything
1020 	 * under us.
1021 	 */
1022 	mutex_lock(&port->mutex);
1023 	retval = uart_set_info(tty, port, state, ss);
1024 	mutex_unlock(&port->mutex);
1025 	up_write(&tty->termios_rwsem);
1026 	return retval;
1027 }
1028 
1029 /**
1030  * uart_get_lsr_info - get line status register info
1031  * @tty: tty associated with the UART
1032  * @state: UART being queried
1033  * @value: returned modem value
1034  */
uart_get_lsr_info(struct tty_struct * tty,struct uart_state * state,unsigned int __user * value)1035 static int uart_get_lsr_info(struct tty_struct *tty,
1036 			struct uart_state *state, unsigned int __user *value)
1037 {
1038 	struct uart_port *uport = uart_port_check(state);
1039 	unsigned int result;
1040 
1041 	result = uport->ops->tx_empty(uport);
1042 
1043 	/*
1044 	 * If we're about to load something into the transmit
1045 	 * register, we'll pretend the transmitter isn't empty to
1046 	 * avoid a race condition (depending on when the transmit
1047 	 * interrupt happens).
1048 	 */
1049 	if (uport->x_char ||
1050 	    ((uart_circ_chars_pending(&state->xmit) > 0) &&
1051 	     !uart_tx_stopped(uport)))
1052 		result &= ~TIOCSER_TEMT;
1053 
1054 	return put_user(result, value);
1055 }
1056 
uart_tiocmget(struct tty_struct * tty)1057 static int uart_tiocmget(struct tty_struct *tty)
1058 {
1059 	struct uart_state *state = tty->driver_data;
1060 	struct tty_port *port = &state->port;
1061 	struct uart_port *uport;
1062 	int result = -EIO;
1063 
1064 	mutex_lock(&port->mutex);
1065 	uport = uart_port_check(state);
1066 	if (!uport)
1067 		goto out;
1068 
1069 	if (!tty_io_error(tty)) {
1070 		result = uport->mctrl;
1071 		spin_lock_irq(&uport->lock);
1072 		result |= uport->ops->get_mctrl(uport);
1073 		spin_unlock_irq(&uport->lock);
1074 	}
1075 out:
1076 	mutex_unlock(&port->mutex);
1077 	return result;
1078 }
1079 
1080 static int
uart_tiocmset(struct tty_struct * tty,unsigned int set,unsigned int clear)1081 uart_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
1082 {
1083 	struct uart_state *state = tty->driver_data;
1084 	struct tty_port *port = &state->port;
1085 	struct uart_port *uport;
1086 	int ret = -EIO;
1087 
1088 	mutex_lock(&port->mutex);
1089 	uport = uart_port_check(state);
1090 	if (!uport)
1091 		goto out;
1092 
1093 	if (!tty_io_error(tty)) {
1094 		uart_update_mctrl(uport, set, clear);
1095 		ret = 0;
1096 	}
1097 out:
1098 	mutex_unlock(&port->mutex);
1099 	return ret;
1100 }
1101 
uart_break_ctl(struct tty_struct * tty,int break_state)1102 static int uart_break_ctl(struct tty_struct *tty, int break_state)
1103 {
1104 	struct uart_state *state = tty->driver_data;
1105 	struct tty_port *port = &state->port;
1106 	struct uart_port *uport;
1107 	int ret = -EIO;
1108 
1109 	mutex_lock(&port->mutex);
1110 	uport = uart_port_check(state);
1111 	if (!uport)
1112 		goto out;
1113 
1114 	if (uport->type != PORT_UNKNOWN && uport->ops->break_ctl)
1115 		uport->ops->break_ctl(uport, break_state);
1116 	ret = 0;
1117 out:
1118 	mutex_unlock(&port->mutex);
1119 	return ret;
1120 }
1121 
uart_do_autoconfig(struct tty_struct * tty,struct uart_state * state)1122 static int uart_do_autoconfig(struct tty_struct *tty, struct uart_state *state)
1123 {
1124 	struct tty_port *port = &state->port;
1125 	struct uart_port *uport;
1126 	int flags, ret;
1127 
1128 	if (!capable(CAP_SYS_ADMIN))
1129 		return -EPERM;
1130 
1131 	/*
1132 	 * Take the per-port semaphore.  This prevents count from
1133 	 * changing, and hence any extra opens of the port while
1134 	 * we're auto-configuring.
1135 	 */
1136 	if (mutex_lock_interruptible(&port->mutex))
1137 		return -ERESTARTSYS;
1138 
1139 	uport = uart_port_check(state);
1140 	if (!uport) {
1141 		ret = -EIO;
1142 		goto out;
1143 	}
1144 
1145 	ret = -EBUSY;
1146 	if (tty_port_users(port) == 1) {
1147 		uart_shutdown(tty, state);
1148 
1149 		/*
1150 		 * If we already have a port type configured,
1151 		 * we must release its resources.
1152 		 */
1153 		if (uport->type != PORT_UNKNOWN && uport->ops->release_port)
1154 			uport->ops->release_port(uport);
1155 
1156 		flags = UART_CONFIG_TYPE;
1157 		if (uport->flags & UPF_AUTO_IRQ)
1158 			flags |= UART_CONFIG_IRQ;
1159 
1160 		/*
1161 		 * This will claim the ports resources if
1162 		 * a port is found.
1163 		 */
1164 		uport->ops->config_port(uport, flags);
1165 
1166 		ret = uart_startup(tty, state, 1);
1167 		if (ret == 0)
1168 			tty_port_set_initialized(port, true);
1169 		if (ret > 0)
1170 			ret = 0;
1171 	}
1172 out:
1173 	mutex_unlock(&port->mutex);
1174 	return ret;
1175 }
1176 
uart_enable_ms(struct uart_port * uport)1177 static void uart_enable_ms(struct uart_port *uport)
1178 {
1179 	/*
1180 	 * Force modem status interrupts on
1181 	 */
1182 	if (uport->ops->enable_ms)
1183 		uport->ops->enable_ms(uport);
1184 }
1185 
1186 /*
1187  * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
1188  * - mask passed in arg for lines of interest
1189  *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
1190  * Caller should use TIOCGICOUNT to see which one it was
1191  *
1192  * FIXME: This wants extracting into a common all driver implementation
1193  * of TIOCMWAIT using tty_port.
1194  */
uart_wait_modem_status(struct uart_state * state,unsigned long arg)1195 static int uart_wait_modem_status(struct uart_state *state, unsigned long arg)
1196 {
1197 	struct uart_port *uport;
1198 	struct tty_port *port = &state->port;
1199 	DECLARE_WAITQUEUE(wait, current);
1200 	struct uart_icount cprev, cnow;
1201 	int ret;
1202 
1203 	/*
1204 	 * note the counters on entry
1205 	 */
1206 	uport = uart_port_ref(state);
1207 	if (!uport)
1208 		return -EIO;
1209 	spin_lock_irq(&uport->lock);
1210 	memcpy(&cprev, &uport->icount, sizeof(struct uart_icount));
1211 	uart_enable_ms(uport);
1212 	spin_unlock_irq(&uport->lock);
1213 
1214 	add_wait_queue(&port->delta_msr_wait, &wait);
1215 	for (;;) {
1216 		spin_lock_irq(&uport->lock);
1217 		memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1218 		spin_unlock_irq(&uport->lock);
1219 
1220 		set_current_state(TASK_INTERRUPTIBLE);
1221 
1222 		if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
1223 		    ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
1224 		    ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
1225 		    ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
1226 			ret = 0;
1227 			break;
1228 		}
1229 
1230 		schedule();
1231 
1232 		/* see if a signal did it */
1233 		if (signal_pending(current)) {
1234 			ret = -ERESTARTSYS;
1235 			break;
1236 		}
1237 
1238 		cprev = cnow;
1239 	}
1240 	__set_current_state(TASK_RUNNING);
1241 	remove_wait_queue(&port->delta_msr_wait, &wait);
1242 	uart_port_deref(uport);
1243 
1244 	return ret;
1245 }
1246 
1247 /*
1248  * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1249  * Return: write counters to the user passed counter struct
1250  * NB: both 1->0 and 0->1 transitions are counted except for
1251  *     RI where only 0->1 is counted.
1252  */
uart_get_icount(struct tty_struct * tty,struct serial_icounter_struct * icount)1253 static int uart_get_icount(struct tty_struct *tty,
1254 			  struct serial_icounter_struct *icount)
1255 {
1256 	struct uart_state *state = tty->driver_data;
1257 	struct uart_icount cnow;
1258 	struct uart_port *uport;
1259 
1260 	uport = uart_port_ref(state);
1261 	if (!uport)
1262 		return -EIO;
1263 	spin_lock_irq(&uport->lock);
1264 	memcpy(&cnow, &uport->icount, sizeof(struct uart_icount));
1265 	spin_unlock_irq(&uport->lock);
1266 	uart_port_deref(uport);
1267 
1268 	icount->cts         = cnow.cts;
1269 	icount->dsr         = cnow.dsr;
1270 	icount->rng         = cnow.rng;
1271 	icount->dcd         = cnow.dcd;
1272 	icount->rx          = cnow.rx;
1273 	icount->tx          = cnow.tx;
1274 	icount->frame       = cnow.frame;
1275 	icount->overrun     = cnow.overrun;
1276 	icount->parity      = cnow.parity;
1277 	icount->brk         = cnow.brk;
1278 	icount->buf_overrun = cnow.buf_overrun;
1279 
1280 	return 0;
1281 }
1282 
1283 #define SER_RS485_LEGACY_FLAGS	(SER_RS485_ENABLED | SER_RS485_RTS_ON_SEND | \
1284 				 SER_RS485_RTS_AFTER_SEND | SER_RS485_RX_DURING_TX | \
1285 				 SER_RS485_TERMINATE_BUS)
1286 
uart_check_rs485_flags(struct uart_port * port,struct serial_rs485 * rs485)1287 static int uart_check_rs485_flags(struct uart_port *port, struct serial_rs485 *rs485)
1288 {
1289 	u32 flags = rs485->flags;
1290 
1291 	/* Don't return -EINVAL for unsupported legacy flags */
1292 	flags &= ~SER_RS485_LEGACY_FLAGS;
1293 
1294 	/*
1295 	 * For any bit outside of the legacy ones that is not supported by
1296 	 * the driver, return -EINVAL.
1297 	 */
1298 	if (flags & ~port->rs485_supported.flags)
1299 		return -EINVAL;
1300 
1301 	/* Asking for address w/o addressing mode? */
1302 	if (!(rs485->flags & SER_RS485_ADDRB) &&
1303 	    (rs485->flags & (SER_RS485_ADDR_RECV|SER_RS485_ADDR_DEST)))
1304 		return -EINVAL;
1305 
1306 	/* Address given but not enabled? */
1307 	if (!(rs485->flags & SER_RS485_ADDR_RECV) && rs485->addr_recv)
1308 		return -EINVAL;
1309 	if (!(rs485->flags & SER_RS485_ADDR_DEST) && rs485->addr_dest)
1310 		return -EINVAL;
1311 
1312 	return 0;
1313 }
1314 
uart_sanitize_serial_rs485_delays(struct uart_port * port,struct serial_rs485 * rs485)1315 static void uart_sanitize_serial_rs485_delays(struct uart_port *port,
1316 					      struct serial_rs485 *rs485)
1317 {
1318 	if (!port->rs485_supported.delay_rts_before_send) {
1319 		if (rs485->delay_rts_before_send) {
1320 			dev_warn_ratelimited(port->dev,
1321 				"%s (%d): RTS delay before sending not supported\n",
1322 				port->name, port->line);
1323 		}
1324 		rs485->delay_rts_before_send = 0;
1325 	} else if (rs485->delay_rts_before_send > RS485_MAX_RTS_DELAY) {
1326 		rs485->delay_rts_before_send = RS485_MAX_RTS_DELAY;
1327 		dev_warn_ratelimited(port->dev,
1328 			"%s (%d): RTS delay before sending clamped to %u ms\n",
1329 			port->name, port->line, rs485->delay_rts_before_send);
1330 	}
1331 
1332 	if (!port->rs485_supported.delay_rts_after_send) {
1333 		if (rs485->delay_rts_after_send) {
1334 			dev_warn_ratelimited(port->dev,
1335 				"%s (%d): RTS delay after sending not supported\n",
1336 				port->name, port->line);
1337 		}
1338 		rs485->delay_rts_after_send = 0;
1339 	} else if (rs485->delay_rts_after_send > RS485_MAX_RTS_DELAY) {
1340 		rs485->delay_rts_after_send = RS485_MAX_RTS_DELAY;
1341 		dev_warn_ratelimited(port->dev,
1342 			"%s (%d): RTS delay after sending clamped to %u ms\n",
1343 			port->name, port->line, rs485->delay_rts_after_send);
1344 	}
1345 }
1346 
uart_sanitize_serial_rs485(struct uart_port * port,struct serial_rs485 * rs485)1347 static void uart_sanitize_serial_rs485(struct uart_port *port, struct serial_rs485 *rs485)
1348 {
1349 	u32 supported_flags = port->rs485_supported.flags;
1350 
1351 	if (!(rs485->flags & SER_RS485_ENABLED)) {
1352 		memset(rs485, 0, sizeof(*rs485));
1353 		return;
1354 	}
1355 
1356 	rs485->flags &= supported_flags;
1357 
1358 	/* Pick sane settings if the user hasn't */
1359 	if (!(rs485->flags & SER_RS485_RTS_ON_SEND) ==
1360 	    !(rs485->flags & SER_RS485_RTS_AFTER_SEND)) {
1361 		if (supported_flags & SER_RS485_RTS_ON_SEND) {
1362 			rs485->flags |= SER_RS485_RTS_ON_SEND;
1363 			rs485->flags &= ~SER_RS485_RTS_AFTER_SEND;
1364 
1365 			dev_warn_ratelimited(port->dev,
1366 				"%s (%d): invalid RTS setting, using RTS_ON_SEND instead\n",
1367 				port->name, port->line);
1368 		} else {
1369 			rs485->flags |= SER_RS485_RTS_AFTER_SEND;
1370 			rs485->flags &= ~SER_RS485_RTS_ON_SEND;
1371 
1372 			dev_warn_ratelimited(port->dev,
1373 				"%s (%d): invalid RTS setting, using RTS_AFTER_SEND instead\n",
1374 				port->name, port->line);
1375 		}
1376 	}
1377 
1378 	uart_sanitize_serial_rs485_delays(port, rs485);
1379 
1380 	/* Return clean padding area to userspace */
1381 	memset(rs485->padding0, 0, sizeof(rs485->padding0));
1382 	memset(rs485->padding1, 0, sizeof(rs485->padding1));
1383 }
1384 
uart_set_rs485_termination(struct uart_port * port,const struct serial_rs485 * rs485)1385 static void uart_set_rs485_termination(struct uart_port *port,
1386 				       const struct serial_rs485 *rs485)
1387 {
1388 	if (!(rs485->flags & SER_RS485_ENABLED))
1389 		return;
1390 
1391 	gpiod_set_value_cansleep(port->rs485_term_gpio,
1392 				 !!(rs485->flags & SER_RS485_TERMINATE_BUS));
1393 }
1394 
uart_rs485_config(struct uart_port * port)1395 static int uart_rs485_config(struct uart_port *port)
1396 {
1397 	struct serial_rs485 *rs485 = &port->rs485;
1398 	unsigned long flags;
1399 	int ret;
1400 
1401 	if (!(rs485->flags & SER_RS485_ENABLED))
1402 		return 0;
1403 
1404 	uart_sanitize_serial_rs485(port, rs485);
1405 	uart_set_rs485_termination(port, rs485);
1406 
1407 	spin_lock_irqsave(&port->lock, flags);
1408 	ret = port->rs485_config(port, NULL, rs485);
1409 	spin_unlock_irqrestore(&port->lock, flags);
1410 	if (ret)
1411 		memset(rs485, 0, sizeof(*rs485));
1412 
1413 	return ret;
1414 }
1415 
uart_get_rs485_config(struct uart_port * port,struct serial_rs485 __user * rs485)1416 static int uart_get_rs485_config(struct uart_port *port,
1417 			 struct serial_rs485 __user *rs485)
1418 {
1419 	unsigned long flags;
1420 	struct serial_rs485 aux;
1421 
1422 	spin_lock_irqsave(&port->lock, flags);
1423 	aux = port->rs485;
1424 	spin_unlock_irqrestore(&port->lock, flags);
1425 
1426 	if (copy_to_user(rs485, &aux, sizeof(aux)))
1427 		return -EFAULT;
1428 
1429 	return 0;
1430 }
1431 
uart_set_rs485_config(struct tty_struct * tty,struct uart_port * port,struct serial_rs485 __user * rs485_user)1432 static int uart_set_rs485_config(struct tty_struct *tty, struct uart_port *port,
1433 			 struct serial_rs485 __user *rs485_user)
1434 {
1435 	struct serial_rs485 rs485;
1436 	int ret;
1437 	unsigned long flags;
1438 
1439 	if (!(port->rs485_supported.flags & SER_RS485_ENABLED))
1440 		return -ENOTTY;
1441 
1442 	if (copy_from_user(&rs485, rs485_user, sizeof(*rs485_user)))
1443 		return -EFAULT;
1444 
1445 	ret = uart_check_rs485_flags(port, &rs485);
1446 	if (ret)
1447 		return ret;
1448 	uart_sanitize_serial_rs485(port, &rs485);
1449 	uart_set_rs485_termination(port, &rs485);
1450 
1451 	spin_lock_irqsave(&port->lock, flags);
1452 	ret = port->rs485_config(port, &tty->termios, &rs485);
1453 	if (!ret) {
1454 		port->rs485 = rs485;
1455 
1456 		/* Reset RTS and other mctrl lines when disabling RS485 */
1457 		if (!(rs485.flags & SER_RS485_ENABLED))
1458 			port->ops->set_mctrl(port, port->mctrl);
1459 	}
1460 	spin_unlock_irqrestore(&port->lock, flags);
1461 	if (ret)
1462 		return ret;
1463 
1464 	if (copy_to_user(rs485_user, &port->rs485, sizeof(port->rs485)))
1465 		return -EFAULT;
1466 
1467 	return 0;
1468 }
1469 
uart_get_iso7816_config(struct uart_port * port,struct serial_iso7816 __user * iso7816)1470 static int uart_get_iso7816_config(struct uart_port *port,
1471 				   struct serial_iso7816 __user *iso7816)
1472 {
1473 	unsigned long flags;
1474 	struct serial_iso7816 aux;
1475 
1476 	if (!port->iso7816_config)
1477 		return -ENOTTY;
1478 
1479 	spin_lock_irqsave(&port->lock, flags);
1480 	aux = port->iso7816;
1481 	spin_unlock_irqrestore(&port->lock, flags);
1482 
1483 	if (copy_to_user(iso7816, &aux, sizeof(aux)))
1484 		return -EFAULT;
1485 
1486 	return 0;
1487 }
1488 
uart_set_iso7816_config(struct uart_port * port,struct serial_iso7816 __user * iso7816_user)1489 static int uart_set_iso7816_config(struct uart_port *port,
1490 				   struct serial_iso7816 __user *iso7816_user)
1491 {
1492 	struct serial_iso7816 iso7816;
1493 	int i, ret;
1494 	unsigned long flags;
1495 
1496 	if (!port->iso7816_config)
1497 		return -ENOTTY;
1498 
1499 	if (copy_from_user(&iso7816, iso7816_user, sizeof(*iso7816_user)))
1500 		return -EFAULT;
1501 
1502 	/*
1503 	 * There are 5 words reserved for future use. Check that userspace
1504 	 * doesn't put stuff in there to prevent breakages in the future.
1505 	 */
1506 	for (i = 0; i < 5; i++)
1507 		if (iso7816.reserved[i])
1508 			return -EINVAL;
1509 
1510 	spin_lock_irqsave(&port->lock, flags);
1511 	ret = port->iso7816_config(port, &iso7816);
1512 	spin_unlock_irqrestore(&port->lock, flags);
1513 	if (ret)
1514 		return ret;
1515 
1516 	if (copy_to_user(iso7816_user, &port->iso7816, sizeof(port->iso7816)))
1517 		return -EFAULT;
1518 
1519 	return 0;
1520 }
1521 
1522 /*
1523  * Called via sys_ioctl.  We can use spin_lock_irq() here.
1524  */
1525 static int
uart_ioctl(struct tty_struct * tty,unsigned int cmd,unsigned long arg)1526 uart_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)
1527 {
1528 	struct uart_state *state = tty->driver_data;
1529 	struct tty_port *port = &state->port;
1530 	struct uart_port *uport;
1531 	void __user *uarg = (void __user *)arg;
1532 	int ret = -ENOIOCTLCMD;
1533 
1534 
1535 	/*
1536 	 * These ioctls don't rely on the hardware to be present.
1537 	 */
1538 	switch (cmd) {
1539 	case TIOCSERCONFIG:
1540 		down_write(&tty->termios_rwsem);
1541 		ret = uart_do_autoconfig(tty, state);
1542 		up_write(&tty->termios_rwsem);
1543 		break;
1544 	}
1545 
1546 	if (ret != -ENOIOCTLCMD)
1547 		goto out;
1548 
1549 	if (tty_io_error(tty)) {
1550 		ret = -EIO;
1551 		goto out;
1552 	}
1553 
1554 	/*
1555 	 * The following should only be used when hardware is present.
1556 	 */
1557 	switch (cmd) {
1558 	case TIOCMIWAIT:
1559 		ret = uart_wait_modem_status(state, arg);
1560 		break;
1561 	}
1562 
1563 	if (ret != -ENOIOCTLCMD)
1564 		goto out;
1565 
1566 	/* rs485_config requires more locking than others */
1567 	if (cmd == TIOCSRS485)
1568 		down_write(&tty->termios_rwsem);
1569 
1570 	mutex_lock(&port->mutex);
1571 	uport = uart_port_check(state);
1572 
1573 	if (!uport || tty_io_error(tty)) {
1574 		ret = -EIO;
1575 		goto out_up;
1576 	}
1577 
1578 	/*
1579 	 * All these rely on hardware being present and need to be
1580 	 * protected against the tty being hung up.
1581 	 */
1582 
1583 	switch (cmd) {
1584 	case TIOCSERGETLSR: /* Get line status register */
1585 		ret = uart_get_lsr_info(tty, state, uarg);
1586 		break;
1587 
1588 	case TIOCGRS485:
1589 		ret = uart_get_rs485_config(uport, uarg);
1590 		break;
1591 
1592 	case TIOCSRS485:
1593 		ret = uart_set_rs485_config(tty, uport, uarg);
1594 		break;
1595 
1596 	case TIOCSISO7816:
1597 		ret = uart_set_iso7816_config(state->uart_port, uarg);
1598 		break;
1599 
1600 	case TIOCGISO7816:
1601 		ret = uart_get_iso7816_config(state->uart_port, uarg);
1602 		break;
1603 	default:
1604 		if (uport->ops->ioctl)
1605 			ret = uport->ops->ioctl(uport, cmd, arg);
1606 		break;
1607 	}
1608 out_up:
1609 	mutex_unlock(&port->mutex);
1610 	if (cmd == TIOCSRS485)
1611 		up_write(&tty->termios_rwsem);
1612 out:
1613 	return ret;
1614 }
1615 
uart_set_ldisc(struct tty_struct * tty)1616 static void uart_set_ldisc(struct tty_struct *tty)
1617 {
1618 	struct uart_state *state = tty->driver_data;
1619 	struct uart_port *uport;
1620 	struct tty_port *port = &state->port;
1621 
1622 	if (!tty_port_initialized(port))
1623 		return;
1624 
1625 	mutex_lock(&state->port.mutex);
1626 	uport = uart_port_check(state);
1627 	if (uport && uport->ops->set_ldisc)
1628 		uport->ops->set_ldisc(uport, &tty->termios);
1629 	mutex_unlock(&state->port.mutex);
1630 }
1631 
uart_set_termios(struct tty_struct * tty,const struct ktermios * old_termios)1632 static void uart_set_termios(struct tty_struct *tty,
1633 			     const struct ktermios *old_termios)
1634 {
1635 	struct uart_state *state = tty->driver_data;
1636 	struct uart_port *uport;
1637 	unsigned int cflag = tty->termios.c_cflag;
1638 	unsigned int iflag_mask = IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK;
1639 	bool sw_changed = false;
1640 
1641 	mutex_lock(&state->port.mutex);
1642 	uport = uart_port_check(state);
1643 	if (!uport)
1644 		goto out;
1645 
1646 	/*
1647 	 * Drivers doing software flow control also need to know
1648 	 * about changes to these input settings.
1649 	 */
1650 	if (uport->flags & UPF_SOFT_FLOW) {
1651 		iflag_mask |= IXANY|IXON|IXOFF;
1652 		sw_changed =
1653 		   tty->termios.c_cc[VSTART] != old_termios->c_cc[VSTART] ||
1654 		   tty->termios.c_cc[VSTOP] != old_termios->c_cc[VSTOP];
1655 	}
1656 
1657 	/*
1658 	 * These are the bits that are used to setup various
1659 	 * flags in the low level driver. We can ignore the Bfoo
1660 	 * bits in c_cflag; c_[io]speed will always be set
1661 	 * appropriately by set_termios() in tty_ioctl.c
1662 	 */
1663 	if ((cflag ^ old_termios->c_cflag) == 0 &&
1664 	    tty->termios.c_ospeed == old_termios->c_ospeed &&
1665 	    tty->termios.c_ispeed == old_termios->c_ispeed &&
1666 	    ((tty->termios.c_iflag ^ old_termios->c_iflag) & iflag_mask) == 0 &&
1667 	    !sw_changed) {
1668 		goto out;
1669 	}
1670 
1671 	uart_change_line_settings(tty, state, old_termios);
1672 	/* reload cflag from termios; port driver may have overridden flags */
1673 	cflag = tty->termios.c_cflag;
1674 
1675 	/* Handle transition to B0 status */
1676 	if ((old_termios->c_cflag & CBAUD) && !(cflag & CBAUD))
1677 		uart_clear_mctrl(uport, TIOCM_RTS | TIOCM_DTR);
1678 	/* Handle transition away from B0 status */
1679 	else if (!(old_termios->c_cflag & CBAUD) && (cflag & CBAUD)) {
1680 		unsigned int mask = TIOCM_DTR;
1681 
1682 		if (!(cflag & CRTSCTS) || !tty_throttled(tty))
1683 			mask |= TIOCM_RTS;
1684 		uart_set_mctrl(uport, mask);
1685 	}
1686 out:
1687 	mutex_unlock(&state->port.mutex);
1688 }
1689 
1690 /*
1691  * Calls to uart_close() are serialised via the tty_lock in
1692  *   drivers/tty/tty_io.c:tty_release()
1693  *   drivers/tty/tty_io.c:do_tty_hangup()
1694  */
uart_close(struct tty_struct * tty,struct file * filp)1695 static void uart_close(struct tty_struct *tty, struct file *filp)
1696 {
1697 	struct uart_state *state = tty->driver_data;
1698 
1699 	if (!state) {
1700 		struct uart_driver *drv = tty->driver->driver_state;
1701 		struct tty_port *port;
1702 
1703 		state = drv->state + tty->index;
1704 		port = &state->port;
1705 		spin_lock_irq(&port->lock);
1706 		--port->count;
1707 		spin_unlock_irq(&port->lock);
1708 		return;
1709 	}
1710 
1711 	pr_debug("uart_close(%d) called\n", tty->index);
1712 
1713 	tty_port_close(tty->port, tty, filp);
1714 }
1715 
uart_tty_port_shutdown(struct tty_port * port)1716 static void uart_tty_port_shutdown(struct tty_port *port)
1717 {
1718 	struct uart_state *state = container_of(port, struct uart_state, port);
1719 	struct uart_port *uport = uart_port_check(state);
1720 	char *buf;
1721 
1722 	/*
1723 	 * At this point, we stop accepting input.  To do this, we
1724 	 * disable the receive line status interrupts.
1725 	 */
1726 	if (WARN(!uport, "detached port still initialized!\n"))
1727 		return;
1728 
1729 	spin_lock_irq(&uport->lock);
1730 	uport->ops->stop_rx(uport);
1731 	spin_unlock_irq(&uport->lock);
1732 
1733 	uart_port_shutdown(port);
1734 
1735 	/*
1736 	 * It's possible for shutdown to be called after suspend if we get
1737 	 * a DCD drop (hangup) at just the right time.  Clear suspended bit so
1738 	 * we don't try to resume a port that has been shutdown.
1739 	 */
1740 	tty_port_set_suspended(port, 0);
1741 
1742 	/*
1743 	 * Free the transmit buffer.
1744 	 */
1745 	spin_lock_irq(&uport->lock);
1746 	buf = state->xmit.buf;
1747 	state->xmit.buf = NULL;
1748 	spin_unlock_irq(&uport->lock);
1749 
1750 	free_page((unsigned long)buf);
1751 
1752 	uart_change_pm(state, UART_PM_STATE_OFF);
1753 }
1754 
uart_wait_until_sent(struct tty_struct * tty,int timeout)1755 static void uart_wait_until_sent(struct tty_struct *tty, int timeout)
1756 {
1757 	struct uart_state *state = tty->driver_data;
1758 	struct uart_port *port;
1759 	unsigned long char_time, expire, fifo_timeout;
1760 
1761 	port = uart_port_ref(state);
1762 	if (!port)
1763 		return;
1764 
1765 	if (port->type == PORT_UNKNOWN || port->fifosize == 0) {
1766 		uart_port_deref(port);
1767 		return;
1768 	}
1769 
1770 	/*
1771 	 * Set the check interval to be 1/5 of the estimated time to
1772 	 * send a single character, and make it at least 1.  The check
1773 	 * interval should also be less than the timeout.
1774 	 *
1775 	 * Note: we have to use pretty tight timings here to satisfy
1776 	 * the NIST-PCTS.
1777 	 */
1778 	char_time = max(nsecs_to_jiffies(port->frame_time / 5), 1UL);
1779 
1780 	if (timeout && timeout < char_time)
1781 		char_time = timeout;
1782 
1783 	if (!uart_cts_enabled(port)) {
1784 		/*
1785 		 * If the transmitter hasn't cleared in twice the approximate
1786 		 * amount of time to send the entire FIFO, it probably won't
1787 		 * ever clear.  This assumes the UART isn't doing flow
1788 		 * control, which is currently the case.  Hence, if it ever
1789 		 * takes longer than FIFO timeout, this is probably due to a
1790 		 * UART bug of some kind.  So, we clamp the timeout parameter at
1791 		 * 2 * FIFO timeout.
1792 		 */
1793 		fifo_timeout = uart_fifo_timeout(port);
1794 		if (timeout == 0 || timeout > 2 * fifo_timeout)
1795 			timeout = 2 * fifo_timeout;
1796 	}
1797 
1798 	expire = jiffies + timeout;
1799 
1800 	pr_debug("uart_wait_until_sent(%d), jiffies=%lu, expire=%lu...\n",
1801 		port->line, jiffies, expire);
1802 
1803 	/*
1804 	 * Check whether the transmitter is empty every 'char_time'.
1805 	 * 'timeout' / 'expire' give us the maximum amount of time
1806 	 * we wait.
1807 	 */
1808 	while (!port->ops->tx_empty(port)) {
1809 		msleep_interruptible(jiffies_to_msecs(char_time));
1810 		if (signal_pending(current))
1811 			break;
1812 		if (timeout && time_after(jiffies, expire))
1813 			break;
1814 	}
1815 	uart_port_deref(port);
1816 }
1817 
1818 /*
1819  * Calls to uart_hangup() are serialised by the tty_lock in
1820  *   drivers/tty/tty_io.c:do_tty_hangup()
1821  * This runs from a workqueue and can sleep for a _short_ time only.
1822  */
uart_hangup(struct tty_struct * tty)1823 static void uart_hangup(struct tty_struct *tty)
1824 {
1825 	struct uart_state *state = tty->driver_data;
1826 	struct tty_port *port = &state->port;
1827 	struct uart_port *uport;
1828 	unsigned long flags;
1829 
1830 	pr_debug("uart_hangup(%d)\n", tty->index);
1831 
1832 	mutex_lock(&port->mutex);
1833 	uport = uart_port_check(state);
1834 	WARN(!uport, "hangup of detached port!\n");
1835 
1836 	if (tty_port_active(port)) {
1837 		uart_flush_buffer(tty);
1838 		uart_shutdown(tty, state);
1839 		spin_lock_irqsave(&port->lock, flags);
1840 		port->count = 0;
1841 		spin_unlock_irqrestore(&port->lock, flags);
1842 		tty_port_set_active(port, 0);
1843 		tty_port_tty_set(port, NULL);
1844 		if (uport && !uart_console(uport))
1845 			uart_change_pm(state, UART_PM_STATE_OFF);
1846 		wake_up_interruptible(&port->open_wait);
1847 		wake_up_interruptible(&port->delta_msr_wait);
1848 	}
1849 	mutex_unlock(&port->mutex);
1850 }
1851 
1852 /* uport == NULL if uart_port has already been removed */
uart_port_shutdown(struct tty_port * port)1853 static void uart_port_shutdown(struct tty_port *port)
1854 {
1855 	struct uart_state *state = container_of(port, struct uart_state, port);
1856 	struct uart_port *uport = uart_port_check(state);
1857 
1858 	/*
1859 	 * clear delta_msr_wait queue to avoid mem leaks: we may free
1860 	 * the irq here so the queue might never be woken up.  Note
1861 	 * that we won't end up waiting on delta_msr_wait again since
1862 	 * any outstanding file descriptors should be pointing at
1863 	 * hung_up_tty_fops now.
1864 	 */
1865 	wake_up_interruptible(&port->delta_msr_wait);
1866 
1867 	if (uport) {
1868 		/* Free the IRQ and disable the port. */
1869 		uport->ops->shutdown(uport);
1870 
1871 		/* Ensure that the IRQ handler isn't running on another CPU. */
1872 		synchronize_irq(uport->irq);
1873 	}
1874 }
1875 
uart_carrier_raised(struct tty_port * port)1876 static int uart_carrier_raised(struct tty_port *port)
1877 {
1878 	struct uart_state *state = container_of(port, struct uart_state, port);
1879 	struct uart_port *uport;
1880 	int mctrl;
1881 
1882 	uport = uart_port_ref(state);
1883 	/*
1884 	 * Should never observe uport == NULL since checks for hangup should
1885 	 * abort the tty_port_block_til_ready() loop before checking for carrier
1886 	 * raised -- but report carrier raised if it does anyway so open will
1887 	 * continue and not sleep
1888 	 */
1889 	if (WARN_ON(!uport))
1890 		return 1;
1891 	spin_lock_irq(&uport->lock);
1892 	uart_enable_ms(uport);
1893 	mctrl = uport->ops->get_mctrl(uport);
1894 	spin_unlock_irq(&uport->lock);
1895 	uart_port_deref(uport);
1896 	if (mctrl & TIOCM_CAR)
1897 		return 1;
1898 	return 0;
1899 }
1900 
uart_dtr_rts(struct tty_port * port,int raise)1901 static void uart_dtr_rts(struct tty_port *port, int raise)
1902 {
1903 	struct uart_state *state = container_of(port, struct uart_state, port);
1904 	struct uart_port *uport;
1905 
1906 	uport = uart_port_ref(state);
1907 	if (!uport)
1908 		return;
1909 	uart_port_dtr_rts(uport, raise);
1910 	uart_port_deref(uport);
1911 }
1912 
uart_install(struct tty_driver * driver,struct tty_struct * tty)1913 static int uart_install(struct tty_driver *driver, struct tty_struct *tty)
1914 {
1915 	struct uart_driver *drv = driver->driver_state;
1916 	struct uart_state *state = drv->state + tty->index;
1917 
1918 	tty->driver_data = state;
1919 
1920 	return tty_standard_install(driver, tty);
1921 }
1922 
1923 /*
1924  * Calls to uart_open are serialised by the tty_lock in
1925  *   drivers/tty/tty_io.c:tty_open()
1926  * Note that if this fails, then uart_close() _will_ be called.
1927  *
1928  * In time, we want to scrap the "opening nonpresent ports"
1929  * behaviour and implement an alternative way for setserial
1930  * to set base addresses/ports/types.  This will allow us to
1931  * get rid of a certain amount of extra tests.
1932  */
uart_open(struct tty_struct * tty,struct file * filp)1933 static int uart_open(struct tty_struct *tty, struct file *filp)
1934 {
1935 	struct uart_state *state = tty->driver_data;
1936 	int retval;
1937 
1938 	retval = tty_port_open(&state->port, tty, filp);
1939 	if (retval > 0)
1940 		retval = 0;
1941 
1942 	return retval;
1943 }
1944 
uart_port_activate(struct tty_port * port,struct tty_struct * tty)1945 static int uart_port_activate(struct tty_port *port, struct tty_struct *tty)
1946 {
1947 	struct uart_state *state = container_of(port, struct uart_state, port);
1948 	struct uart_port *uport;
1949 	int ret;
1950 
1951 	uport = uart_port_check(state);
1952 	if (!uport || uport->flags & UPF_DEAD)
1953 		return -ENXIO;
1954 
1955 	/*
1956 	 * Start up the serial port.
1957 	 */
1958 	ret = uart_startup(tty, state, 0);
1959 	if (ret > 0)
1960 		tty_port_set_active(port, 1);
1961 
1962 	return ret;
1963 }
1964 
uart_type(struct uart_port * port)1965 static const char *uart_type(struct uart_port *port)
1966 {
1967 	const char *str = NULL;
1968 
1969 	if (port->ops->type)
1970 		str = port->ops->type(port);
1971 
1972 	if (!str)
1973 		str = "unknown";
1974 
1975 	return str;
1976 }
1977 
1978 #ifdef CONFIG_PROC_FS
1979 
uart_line_info(struct seq_file * m,struct uart_driver * drv,int i)1980 static void uart_line_info(struct seq_file *m, struct uart_driver *drv, int i)
1981 {
1982 	struct uart_state *state = drv->state + i;
1983 	struct tty_port *port = &state->port;
1984 	enum uart_pm_state pm_state;
1985 	struct uart_port *uport;
1986 	char stat_buf[32];
1987 	unsigned int status;
1988 	int mmio;
1989 
1990 	mutex_lock(&port->mutex);
1991 	uport = uart_port_check(state);
1992 	if (!uport)
1993 		goto out;
1994 
1995 	mmio = uport->iotype >= UPIO_MEM;
1996 	seq_printf(m, "%d: uart:%s %s%08llX irq:%d",
1997 			uport->line, uart_type(uport),
1998 			mmio ? "mmio:0x" : "port:",
1999 			mmio ? (unsigned long long)uport->mapbase
2000 			     : (unsigned long long)uport->iobase,
2001 			uport->irq);
2002 
2003 	if (uport->type == PORT_UNKNOWN) {
2004 		seq_putc(m, '\n');
2005 		goto out;
2006 	}
2007 
2008 	if (capable(CAP_SYS_ADMIN)) {
2009 		pm_state = state->pm_state;
2010 		if (pm_state != UART_PM_STATE_ON)
2011 			uart_change_pm(state, UART_PM_STATE_ON);
2012 		spin_lock_irq(&uport->lock);
2013 		status = uport->ops->get_mctrl(uport);
2014 		spin_unlock_irq(&uport->lock);
2015 		if (pm_state != UART_PM_STATE_ON)
2016 			uart_change_pm(state, pm_state);
2017 
2018 		seq_printf(m, " tx:%d rx:%d",
2019 				uport->icount.tx, uport->icount.rx);
2020 		if (uport->icount.frame)
2021 			seq_printf(m, " fe:%d",	uport->icount.frame);
2022 		if (uport->icount.parity)
2023 			seq_printf(m, " pe:%d",	uport->icount.parity);
2024 		if (uport->icount.brk)
2025 			seq_printf(m, " brk:%d", uport->icount.brk);
2026 		if (uport->icount.overrun)
2027 			seq_printf(m, " oe:%d", uport->icount.overrun);
2028 		if (uport->icount.buf_overrun)
2029 			seq_printf(m, " bo:%d", uport->icount.buf_overrun);
2030 
2031 #define INFOBIT(bit, str) \
2032 	if (uport->mctrl & (bit)) \
2033 		strncat(stat_buf, (str), sizeof(stat_buf) - \
2034 			strlen(stat_buf) - 2)
2035 #define STATBIT(bit, str) \
2036 	if (status & (bit)) \
2037 		strncat(stat_buf, (str), sizeof(stat_buf) - \
2038 		       strlen(stat_buf) - 2)
2039 
2040 		stat_buf[0] = '\0';
2041 		stat_buf[1] = '\0';
2042 		INFOBIT(TIOCM_RTS, "|RTS");
2043 		STATBIT(TIOCM_CTS, "|CTS");
2044 		INFOBIT(TIOCM_DTR, "|DTR");
2045 		STATBIT(TIOCM_DSR, "|DSR");
2046 		STATBIT(TIOCM_CAR, "|CD");
2047 		STATBIT(TIOCM_RNG, "|RI");
2048 		if (stat_buf[0])
2049 			stat_buf[0] = ' ';
2050 
2051 		seq_puts(m, stat_buf);
2052 	}
2053 	seq_putc(m, '\n');
2054 #undef STATBIT
2055 #undef INFOBIT
2056 out:
2057 	mutex_unlock(&port->mutex);
2058 }
2059 
uart_proc_show(struct seq_file * m,void * v)2060 static int uart_proc_show(struct seq_file *m, void *v)
2061 {
2062 	struct tty_driver *ttydrv = m->private;
2063 	struct uart_driver *drv = ttydrv->driver_state;
2064 	int i;
2065 
2066 	seq_printf(m, "serinfo:1.0 driver%s%s revision:%s\n", "", "", "");
2067 	for (i = 0; i < drv->nr; i++)
2068 		uart_line_info(m, drv, i);
2069 	return 0;
2070 }
2071 #endif
2072 
uart_port_spin_lock_init(struct uart_port * port)2073 static void uart_port_spin_lock_init(struct uart_port *port)
2074 {
2075 	spin_lock_init(&port->lock);
2076 	lockdep_set_class(&port->lock, &port_lock_key);
2077 }
2078 
2079 #if defined(CONFIG_SERIAL_CORE_CONSOLE) || defined(CONFIG_CONSOLE_POLL)
2080 /**
2081  * uart_console_write - write a console message to a serial port
2082  * @port: the port to write the message
2083  * @s: array of characters
2084  * @count: number of characters in string to write
2085  * @putchar: function to write character to port
2086  */
uart_console_write(struct uart_port * port,const char * s,unsigned int count,void (* putchar)(struct uart_port *,unsigned char))2087 void uart_console_write(struct uart_port *port, const char *s,
2088 			unsigned int count,
2089 			void (*putchar)(struct uart_port *, unsigned char))
2090 {
2091 	unsigned int i;
2092 
2093 	for (i = 0; i < count; i++, s++) {
2094 		if (*s == '\n')
2095 			putchar(port, '\r');
2096 		putchar(port, *s);
2097 	}
2098 }
2099 EXPORT_SYMBOL_GPL(uart_console_write);
2100 
2101 /**
2102  * uart_get_console - get uart port for console
2103  * @ports: ports to search in
2104  * @nr: number of @ports
2105  * @co: console to search for
2106  * Returns: uart_port for the console @co
2107  *
2108  * Check whether an invalid uart number has been specified (as @co->index), and
2109  * if so, search for the first available port that does have console support.
2110  */
2111 struct uart_port * __init
uart_get_console(struct uart_port * ports,int nr,struct console * co)2112 uart_get_console(struct uart_port *ports, int nr, struct console *co)
2113 {
2114 	int idx = co->index;
2115 
2116 	if (idx < 0 || idx >= nr || (ports[idx].iobase == 0 &&
2117 				     ports[idx].membase == NULL))
2118 		for (idx = 0; idx < nr; idx++)
2119 			if (ports[idx].iobase != 0 ||
2120 			    ports[idx].membase != NULL)
2121 				break;
2122 
2123 	co->index = idx;
2124 
2125 	return ports + idx;
2126 }
2127 
2128 /**
2129  * uart_parse_earlycon - Parse earlycon options
2130  * @p:	     ptr to 2nd field (ie., just beyond '<name>,')
2131  * @iotype:  ptr for decoded iotype (out)
2132  * @addr:    ptr for decoded mapbase/iobase (out)
2133  * @options: ptr for <options> field; %NULL if not present (out)
2134  *
2135  * Decodes earlycon kernel command line parameters of the form:
2136  *  * earlycon=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
2137  *  * console=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
2138  *
2139  * The optional form:
2140  *  * earlycon=<name>,0x<addr>,<options>
2141  *  * console=<name>,0x<addr>,<options>
2142  *
2143  * is also accepted; the returned @iotype will be %UPIO_MEM.
2144  *
2145  * Returns: 0 on success or -%EINVAL on failure
2146  */
uart_parse_earlycon(char * p,unsigned char * iotype,resource_size_t * addr,char ** options)2147 int uart_parse_earlycon(char *p, unsigned char *iotype, resource_size_t *addr,
2148 			char **options)
2149 {
2150 	if (strncmp(p, "mmio,", 5) == 0) {
2151 		*iotype = UPIO_MEM;
2152 		p += 5;
2153 	} else if (strncmp(p, "mmio16,", 7) == 0) {
2154 		*iotype = UPIO_MEM16;
2155 		p += 7;
2156 	} else if (strncmp(p, "mmio32,", 7) == 0) {
2157 		*iotype = UPIO_MEM32;
2158 		p += 7;
2159 	} else if (strncmp(p, "mmio32be,", 9) == 0) {
2160 		*iotype = UPIO_MEM32BE;
2161 		p += 9;
2162 	} else if (strncmp(p, "mmio32native,", 13) == 0) {
2163 		*iotype = IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) ?
2164 			UPIO_MEM32BE : UPIO_MEM32;
2165 		p += 13;
2166 	} else if (strncmp(p, "io,", 3) == 0) {
2167 		*iotype = UPIO_PORT;
2168 		p += 3;
2169 	} else if (strncmp(p, "0x", 2) == 0) {
2170 		*iotype = UPIO_MEM;
2171 	} else {
2172 		return -EINVAL;
2173 	}
2174 
2175 	/*
2176 	 * Before you replace it with kstrtoull(), think about options separator
2177 	 * (',') it will not tolerate
2178 	 */
2179 	*addr = simple_strtoull(p, NULL, 0);
2180 	p = strchr(p, ',');
2181 	if (p)
2182 		p++;
2183 
2184 	*options = p;
2185 	return 0;
2186 }
2187 EXPORT_SYMBOL_GPL(uart_parse_earlycon);
2188 
2189 /**
2190  * uart_parse_options - Parse serial port baud/parity/bits/flow control.
2191  * @options: pointer to option string
2192  * @baud: pointer to an 'int' variable for the baud rate.
2193  * @parity: pointer to an 'int' variable for the parity.
2194  * @bits: pointer to an 'int' variable for the number of data bits.
2195  * @flow: pointer to an 'int' variable for the flow control character.
2196  *
2197  * uart_parse_options() decodes a string containing the serial console
2198  * options. The format of the string is <baud><parity><bits><flow>,
2199  * eg: 115200n8r
2200  */
2201 void
uart_parse_options(const char * options,int * baud,int * parity,int * bits,int * flow)2202 uart_parse_options(const char *options, int *baud, int *parity,
2203 		   int *bits, int *flow)
2204 {
2205 	const char *s = options;
2206 
2207 	*baud = simple_strtoul(s, NULL, 10);
2208 	while (*s >= '0' && *s <= '9')
2209 		s++;
2210 	if (*s)
2211 		*parity = *s++;
2212 	if (*s)
2213 		*bits = *s++ - '0';
2214 	if (*s)
2215 		*flow = *s;
2216 }
2217 EXPORT_SYMBOL_GPL(uart_parse_options);
2218 
2219 /**
2220  * uart_set_options - setup the serial console parameters
2221  * @port: pointer to the serial ports uart_port structure
2222  * @co: console pointer
2223  * @baud: baud rate
2224  * @parity: parity character - 'n' (none), 'o' (odd), 'e' (even)
2225  * @bits: number of data bits
2226  * @flow: flow control character - 'r' (rts)
2227  */
2228 int
uart_set_options(struct uart_port * port,struct console * co,int baud,int parity,int bits,int flow)2229 uart_set_options(struct uart_port *port, struct console *co,
2230 		 int baud, int parity, int bits, int flow)
2231 {
2232 	struct ktermios termios;
2233 	static struct ktermios dummy;
2234 
2235 	/*
2236 	 * Ensure that the serial-console lock is initialised early.
2237 	 *
2238 	 * Note that the console-enabled check is needed because of kgdboc,
2239 	 * which can end up calling uart_set_options() for an already enabled
2240 	 * console via tty_find_polling_driver() and uart_poll_init().
2241 	 */
2242 	if (!uart_console_enabled(port) && !port->console_reinit)
2243 		uart_port_spin_lock_init(port);
2244 
2245 	memset(&termios, 0, sizeof(struct ktermios));
2246 
2247 	termios.c_cflag |= CREAD | HUPCL | CLOCAL;
2248 	tty_termios_encode_baud_rate(&termios, baud, baud);
2249 
2250 	if (bits == 7)
2251 		termios.c_cflag |= CS7;
2252 	else
2253 		termios.c_cflag |= CS8;
2254 
2255 	switch (parity) {
2256 	case 'o': case 'O':
2257 		termios.c_cflag |= PARODD;
2258 		fallthrough;
2259 	case 'e': case 'E':
2260 		termios.c_cflag |= PARENB;
2261 		break;
2262 	}
2263 
2264 	if (flow == 'r')
2265 		termios.c_cflag |= CRTSCTS;
2266 
2267 	/*
2268 	 * some uarts on other side don't support no flow control.
2269 	 * So we set * DTR in host uart to make them happy
2270 	 */
2271 	port->mctrl |= TIOCM_DTR;
2272 
2273 	port->ops->set_termios(port, &termios, &dummy);
2274 	/*
2275 	 * Allow the setting of the UART parameters with a NULL console
2276 	 * too:
2277 	 */
2278 	if (co) {
2279 		co->cflag = termios.c_cflag;
2280 		co->ispeed = termios.c_ispeed;
2281 		co->ospeed = termios.c_ospeed;
2282 	}
2283 
2284 	return 0;
2285 }
2286 EXPORT_SYMBOL_GPL(uart_set_options);
2287 #endif /* CONFIG_SERIAL_CORE_CONSOLE */
2288 
2289 /**
2290  * uart_change_pm - set power state of the port
2291  *
2292  * @state: port descriptor
2293  * @pm_state: new state
2294  *
2295  * Locking: port->mutex has to be held
2296  */
uart_change_pm(struct uart_state * state,enum uart_pm_state pm_state)2297 static void uart_change_pm(struct uart_state *state,
2298 			   enum uart_pm_state pm_state)
2299 {
2300 	struct uart_port *port = uart_port_check(state);
2301 
2302 	if (state->pm_state != pm_state) {
2303 		if (port && port->ops->pm)
2304 			port->ops->pm(port, pm_state, state->pm_state);
2305 		state->pm_state = pm_state;
2306 	}
2307 }
2308 
2309 struct uart_match {
2310 	struct uart_port *port;
2311 	struct uart_driver *driver;
2312 };
2313 
serial_match_port(struct device * dev,void * data)2314 static int serial_match_port(struct device *dev, void *data)
2315 {
2316 	struct uart_match *match = data;
2317 	struct tty_driver *tty_drv = match->driver->tty_driver;
2318 	dev_t devt = MKDEV(tty_drv->major, tty_drv->minor_start) +
2319 		match->port->line;
2320 
2321 	return dev->devt == devt; /* Actually, only one tty per port */
2322 }
2323 
uart_suspend_port(struct uart_driver * drv,struct uart_port * uport)2324 int uart_suspend_port(struct uart_driver *drv, struct uart_port *uport)
2325 {
2326 	struct uart_state *state = drv->state + uport->line;
2327 	struct tty_port *port = &state->port;
2328 	struct device *tty_dev;
2329 	struct uart_match match = {uport, drv};
2330 
2331 	mutex_lock(&port->mutex);
2332 
2333 	tty_dev = device_find_child(uport->dev, &match, serial_match_port);
2334 	if (tty_dev && device_may_wakeup(tty_dev)) {
2335 		enable_irq_wake(uport->irq);
2336 		put_device(tty_dev);
2337 		mutex_unlock(&port->mutex);
2338 		return 0;
2339 	}
2340 	put_device(tty_dev);
2341 
2342 	/*
2343 	 * Nothing to do if the console is not suspending
2344 	 * except stop_rx to prevent any asynchronous data
2345 	 * over RX line. However ensure that we will be
2346 	 * able to Re-start_rx later.
2347 	 */
2348 	if (!console_suspend_enabled && uart_console(uport)) {
2349 		if (uport->ops->start_rx) {
2350 			spin_lock_irq(&uport->lock);
2351 			uport->ops->stop_rx(uport);
2352 			spin_unlock_irq(&uport->lock);
2353 		}
2354 		goto unlock;
2355 	}
2356 
2357 	uport->suspended = 1;
2358 
2359 	if (tty_port_initialized(port)) {
2360 		const struct uart_ops *ops = uport->ops;
2361 		int tries;
2362 		unsigned int mctrl;
2363 
2364 		tty_port_set_suspended(port, 1);
2365 		tty_port_set_initialized(port, 0);
2366 
2367 		spin_lock_irq(&uport->lock);
2368 		ops->stop_tx(uport);
2369 		if (!(uport->rs485.flags & SER_RS485_ENABLED))
2370 			ops->set_mctrl(uport, 0);
2371 		/* save mctrl so it can be restored on resume */
2372 		mctrl = uport->mctrl;
2373 		uport->mctrl = 0;
2374 		ops->stop_rx(uport);
2375 		spin_unlock_irq(&uport->lock);
2376 
2377 		/*
2378 		 * Wait for the transmitter to empty.
2379 		 */
2380 		for (tries = 3; !ops->tx_empty(uport) && tries; tries--)
2381 			msleep(10);
2382 		if (!tries)
2383 			dev_err(uport->dev, "%s: Unable to drain transmitter\n",
2384 				uport->name);
2385 
2386 		ops->shutdown(uport);
2387 		uport->mctrl = mctrl;
2388 	}
2389 
2390 	/*
2391 	 * Disable the console device before suspending.
2392 	 */
2393 	if (uart_console(uport))
2394 		console_stop(uport->cons);
2395 
2396 	uart_change_pm(state, UART_PM_STATE_OFF);
2397 unlock:
2398 	mutex_unlock(&port->mutex);
2399 
2400 	return 0;
2401 }
2402 EXPORT_SYMBOL(uart_suspend_port);
2403 
uart_resume_port(struct uart_driver * drv,struct uart_port * uport)2404 int uart_resume_port(struct uart_driver *drv, struct uart_port *uport)
2405 {
2406 	struct uart_state *state = drv->state + uport->line;
2407 	struct tty_port *port = &state->port;
2408 	struct device *tty_dev;
2409 	struct uart_match match = {uport, drv};
2410 	struct ktermios termios;
2411 
2412 	mutex_lock(&port->mutex);
2413 
2414 	tty_dev = device_find_child(uport->dev, &match, serial_match_port);
2415 	if (!uport->suspended && device_may_wakeup(tty_dev)) {
2416 		if (irqd_is_wakeup_set(irq_get_irq_data((uport->irq))))
2417 			disable_irq_wake(uport->irq);
2418 		put_device(tty_dev);
2419 		mutex_unlock(&port->mutex);
2420 		return 0;
2421 	}
2422 	put_device(tty_dev);
2423 	uport->suspended = 0;
2424 
2425 	/*
2426 	 * Re-enable the console device after suspending.
2427 	 */
2428 	if (uart_console(uport)) {
2429 		/*
2430 		 * First try to use the console cflag setting.
2431 		 */
2432 		memset(&termios, 0, sizeof(struct ktermios));
2433 		termios.c_cflag = uport->cons->cflag;
2434 		termios.c_ispeed = uport->cons->ispeed;
2435 		termios.c_ospeed = uport->cons->ospeed;
2436 
2437 		/*
2438 		 * If that's unset, use the tty termios setting.
2439 		 */
2440 		if (port->tty && termios.c_cflag == 0)
2441 			termios = port->tty->termios;
2442 
2443 		if (console_suspend_enabled)
2444 			uart_change_pm(state, UART_PM_STATE_ON);
2445 		uport->ops->set_termios(uport, &termios, NULL);
2446 		if (!console_suspend_enabled && uport->ops->start_rx) {
2447 			spin_lock_irq(&uport->lock);
2448 			uport->ops->start_rx(uport);
2449 			spin_unlock_irq(&uport->lock);
2450 		}
2451 		if (console_suspend_enabled)
2452 			console_start(uport->cons);
2453 	}
2454 
2455 	if (tty_port_suspended(port)) {
2456 		const struct uart_ops *ops = uport->ops;
2457 		int ret;
2458 
2459 		uart_change_pm(state, UART_PM_STATE_ON);
2460 		spin_lock_irq(&uport->lock);
2461 		if (!(uport->rs485.flags & SER_RS485_ENABLED))
2462 			ops->set_mctrl(uport, 0);
2463 		spin_unlock_irq(&uport->lock);
2464 		if (console_suspend_enabled || !uart_console(uport)) {
2465 			/* Protected by port mutex for now */
2466 			struct tty_struct *tty = port->tty;
2467 
2468 			ret = ops->startup(uport);
2469 			if (ret == 0) {
2470 				if (tty)
2471 					uart_change_line_settings(tty, state, NULL);
2472 				uart_rs485_config(uport);
2473 				spin_lock_irq(&uport->lock);
2474 				if (!(uport->rs485.flags & SER_RS485_ENABLED))
2475 					ops->set_mctrl(uport, uport->mctrl);
2476 				ops->start_tx(uport);
2477 				spin_unlock_irq(&uport->lock);
2478 				tty_port_set_initialized(port, 1);
2479 			} else {
2480 				/*
2481 				 * Failed to resume - maybe hardware went away?
2482 				 * Clear the "initialized" flag so we won't try
2483 				 * to call the low level drivers shutdown method.
2484 				 */
2485 				uart_shutdown(tty, state);
2486 			}
2487 		}
2488 
2489 		tty_port_set_suspended(port, 0);
2490 	}
2491 
2492 	mutex_unlock(&port->mutex);
2493 
2494 	return 0;
2495 }
2496 EXPORT_SYMBOL(uart_resume_port);
2497 
2498 static inline void
uart_report_port(struct uart_driver * drv,struct uart_port * port)2499 uart_report_port(struct uart_driver *drv, struct uart_port *port)
2500 {
2501 	char address[64];
2502 
2503 	switch (port->iotype) {
2504 	case UPIO_PORT:
2505 		snprintf(address, sizeof(address), "I/O 0x%lx", port->iobase);
2506 		break;
2507 	case UPIO_HUB6:
2508 		snprintf(address, sizeof(address),
2509 			 "I/O 0x%lx offset 0x%x", port->iobase, port->hub6);
2510 		break;
2511 	case UPIO_MEM:
2512 	case UPIO_MEM16:
2513 	case UPIO_MEM32:
2514 	case UPIO_MEM32BE:
2515 	case UPIO_AU:
2516 	case UPIO_TSI:
2517 		snprintf(address, sizeof(address),
2518 			 "MMIO 0x%llx", (unsigned long long)port->mapbase);
2519 		break;
2520 	default:
2521 		strscpy(address, "*unknown*", sizeof(address));
2522 		break;
2523 	}
2524 
2525 	pr_info("%s%s%s at %s (irq = %d, base_baud = %d) is a %s\n",
2526 	       port->dev ? dev_name(port->dev) : "",
2527 	       port->dev ? ": " : "",
2528 	       port->name,
2529 	       address, port->irq, port->uartclk / 16, uart_type(port));
2530 
2531 	/* The magic multiplier feature is a bit obscure, so report it too.  */
2532 	if (port->flags & UPF_MAGIC_MULTIPLIER)
2533 		pr_info("%s%s%s extra baud rates supported: %d, %d",
2534 			port->dev ? dev_name(port->dev) : "",
2535 			port->dev ? ": " : "",
2536 			port->name,
2537 			port->uartclk / 8, port->uartclk / 4);
2538 }
2539 
2540 static void
uart_configure_port(struct uart_driver * drv,struct uart_state * state,struct uart_port * port)2541 uart_configure_port(struct uart_driver *drv, struct uart_state *state,
2542 		    struct uart_port *port)
2543 {
2544 	unsigned int flags;
2545 
2546 	/*
2547 	 * If there isn't a port here, don't do anything further.
2548 	 */
2549 	if (!port->iobase && !port->mapbase && !port->membase)
2550 		return;
2551 
2552 	/*
2553 	 * Now do the auto configuration stuff.  Note that config_port
2554 	 * is expected to claim the resources and map the port for us.
2555 	 */
2556 	flags = 0;
2557 	if (port->flags & UPF_AUTO_IRQ)
2558 		flags |= UART_CONFIG_IRQ;
2559 	if (port->flags & UPF_BOOT_AUTOCONF) {
2560 		if (!(port->flags & UPF_FIXED_TYPE)) {
2561 			port->type = PORT_UNKNOWN;
2562 			flags |= UART_CONFIG_TYPE;
2563 		}
2564 		port->ops->config_port(port, flags);
2565 	}
2566 
2567 	if (port->type != PORT_UNKNOWN) {
2568 		unsigned long flags;
2569 
2570 		uart_report_port(drv, port);
2571 
2572 		/* Power up port for set_mctrl() */
2573 		uart_change_pm(state, UART_PM_STATE_ON);
2574 
2575 		/*
2576 		 * Ensure that the modem control lines are de-activated.
2577 		 * keep the DTR setting that is set in uart_set_options()
2578 		 * We probably don't need a spinlock around this, but
2579 		 */
2580 		spin_lock_irqsave(&port->lock, flags);
2581 		port->mctrl &= TIOCM_DTR;
2582 		if (!(port->rs485.flags & SER_RS485_ENABLED))
2583 			port->ops->set_mctrl(port, port->mctrl);
2584 		spin_unlock_irqrestore(&port->lock, flags);
2585 
2586 		uart_rs485_config(port);
2587 
2588 		/*
2589 		 * If this driver supports console, and it hasn't been
2590 		 * successfully registered yet, try to re-register it.
2591 		 * It may be that the port was not available.
2592 		 */
2593 		if (port->cons && !(port->cons->flags & CON_ENABLED))
2594 			register_console(port->cons);
2595 
2596 		/*
2597 		 * Power down all ports by default, except the
2598 		 * console if we have one.
2599 		 */
2600 		if (!uart_console(port))
2601 			uart_change_pm(state, UART_PM_STATE_OFF);
2602 	}
2603 }
2604 
2605 #ifdef CONFIG_CONSOLE_POLL
2606 
uart_poll_init(struct tty_driver * driver,int line,char * options)2607 static int uart_poll_init(struct tty_driver *driver, int line, char *options)
2608 {
2609 	struct uart_driver *drv = driver->driver_state;
2610 	struct uart_state *state = drv->state + line;
2611 	struct tty_port *tport;
2612 	struct uart_port *port;
2613 	int baud = 9600;
2614 	int bits = 8;
2615 	int parity = 'n';
2616 	int flow = 'n';
2617 	int ret = 0;
2618 
2619 	tport = &state->port;
2620 	mutex_lock(&tport->mutex);
2621 
2622 	port = uart_port_check(state);
2623 	if (!port || !(port->ops->poll_get_char && port->ops->poll_put_char)) {
2624 		ret = -1;
2625 		goto out;
2626 	}
2627 
2628 	if (port->ops->poll_init) {
2629 		/*
2630 		 * We don't set initialized as we only initialized the hw,
2631 		 * e.g. state->xmit is still uninitialized.
2632 		 */
2633 		if (!tty_port_initialized(tport))
2634 			ret = port->ops->poll_init(port);
2635 	}
2636 
2637 	if (!ret && options) {
2638 		uart_parse_options(options, &baud, &parity, &bits, &flow);
2639 		ret = uart_set_options(port, NULL, baud, parity, bits, flow);
2640 	}
2641 out:
2642 	mutex_unlock(&tport->mutex);
2643 	return ret;
2644 }
2645 
uart_poll_get_char(struct tty_driver * driver,int line)2646 static int uart_poll_get_char(struct tty_driver *driver, int line)
2647 {
2648 	struct uart_driver *drv = driver->driver_state;
2649 	struct uart_state *state = drv->state + line;
2650 	struct uart_port *port;
2651 	int ret = -1;
2652 
2653 	port = uart_port_ref(state);
2654 	if (port) {
2655 		ret = port->ops->poll_get_char(port);
2656 		uart_port_deref(port);
2657 	}
2658 
2659 	return ret;
2660 }
2661 
uart_poll_put_char(struct tty_driver * driver,int line,char ch)2662 static void uart_poll_put_char(struct tty_driver *driver, int line, char ch)
2663 {
2664 	struct uart_driver *drv = driver->driver_state;
2665 	struct uart_state *state = drv->state + line;
2666 	struct uart_port *port;
2667 
2668 	port = uart_port_ref(state);
2669 	if (!port)
2670 		return;
2671 
2672 	if (ch == '\n')
2673 		port->ops->poll_put_char(port, '\r');
2674 	port->ops->poll_put_char(port, ch);
2675 	uart_port_deref(port);
2676 }
2677 #endif
2678 
2679 static const struct tty_operations uart_ops = {
2680 	.install	= uart_install,
2681 	.open		= uart_open,
2682 	.close		= uart_close,
2683 	.write		= uart_write,
2684 	.put_char	= uart_put_char,
2685 	.flush_chars	= uart_flush_chars,
2686 	.write_room	= uart_write_room,
2687 	.chars_in_buffer= uart_chars_in_buffer,
2688 	.flush_buffer	= uart_flush_buffer,
2689 	.ioctl		= uart_ioctl,
2690 	.throttle	= uart_throttle,
2691 	.unthrottle	= uart_unthrottle,
2692 	.send_xchar	= uart_send_xchar,
2693 	.set_termios	= uart_set_termios,
2694 	.set_ldisc	= uart_set_ldisc,
2695 	.stop		= uart_stop,
2696 	.start		= uart_start,
2697 	.hangup		= uart_hangup,
2698 	.break_ctl	= uart_break_ctl,
2699 	.wait_until_sent= uart_wait_until_sent,
2700 #ifdef CONFIG_PROC_FS
2701 	.proc_show	= uart_proc_show,
2702 #endif
2703 	.tiocmget	= uart_tiocmget,
2704 	.tiocmset	= uart_tiocmset,
2705 	.set_serial	= uart_set_info_user,
2706 	.get_serial	= uart_get_info_user,
2707 	.get_icount	= uart_get_icount,
2708 #ifdef CONFIG_CONSOLE_POLL
2709 	.poll_init	= uart_poll_init,
2710 	.poll_get_char	= uart_poll_get_char,
2711 	.poll_put_char	= uart_poll_put_char,
2712 #endif
2713 };
2714 
2715 static const struct tty_port_operations uart_port_ops = {
2716 	.carrier_raised = uart_carrier_raised,
2717 	.dtr_rts	= uart_dtr_rts,
2718 	.activate	= uart_port_activate,
2719 	.shutdown	= uart_tty_port_shutdown,
2720 };
2721 
2722 /**
2723  * uart_register_driver - register a driver with the uart core layer
2724  * @drv: low level driver structure
2725  *
2726  * Register a uart driver with the core driver. We in turn register with the
2727  * tty layer, and initialise the core driver per-port state.
2728  *
2729  * We have a proc file in /proc/tty/driver which is named after the normal
2730  * driver.
2731  *
2732  * @drv->port should be %NULL, and the per-port structures should be registered
2733  * using uart_add_one_port() after this call has succeeded.
2734  *
2735  * Locking: none, Interrupts: enabled
2736  */
uart_register_driver(struct uart_driver * drv)2737 int uart_register_driver(struct uart_driver *drv)
2738 {
2739 	struct tty_driver *normal;
2740 	int i, retval = -ENOMEM;
2741 
2742 	BUG_ON(drv->state);
2743 
2744 	/*
2745 	 * Maybe we should be using a slab cache for this, especially if
2746 	 * we have a large number of ports to handle.
2747 	 */
2748 	drv->state = kcalloc(drv->nr, sizeof(struct uart_state), GFP_KERNEL);
2749 	if (!drv->state)
2750 		goto out;
2751 
2752 	normal = tty_alloc_driver(drv->nr, TTY_DRIVER_REAL_RAW |
2753 			TTY_DRIVER_DYNAMIC_DEV);
2754 	if (IS_ERR(normal)) {
2755 		retval = PTR_ERR(normal);
2756 		goto out_kfree;
2757 	}
2758 
2759 	drv->tty_driver = normal;
2760 
2761 	normal->driver_name	= drv->driver_name;
2762 	normal->name		= drv->dev_name;
2763 	normal->major		= drv->major;
2764 	normal->minor_start	= drv->minor;
2765 	normal->type		= TTY_DRIVER_TYPE_SERIAL;
2766 	normal->subtype		= SERIAL_TYPE_NORMAL;
2767 	normal->init_termios	= tty_std_termios;
2768 	normal->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
2769 	normal->init_termios.c_ispeed = normal->init_termios.c_ospeed = 9600;
2770 	normal->driver_state    = drv;
2771 	tty_set_operations(normal, &uart_ops);
2772 
2773 	/*
2774 	 * Initialise the UART state(s).
2775 	 */
2776 	for (i = 0; i < drv->nr; i++) {
2777 		struct uart_state *state = drv->state + i;
2778 		struct tty_port *port = &state->port;
2779 
2780 		tty_port_init(port);
2781 		port->ops = &uart_port_ops;
2782 	}
2783 
2784 	retval = tty_register_driver(normal);
2785 	if (retval >= 0)
2786 		return retval;
2787 
2788 	for (i = 0; i < drv->nr; i++)
2789 		tty_port_destroy(&drv->state[i].port);
2790 	tty_driver_kref_put(normal);
2791 out_kfree:
2792 	kfree(drv->state);
2793 out:
2794 	return retval;
2795 }
2796 EXPORT_SYMBOL(uart_register_driver);
2797 
2798 /**
2799  * uart_unregister_driver - remove a driver from the uart core layer
2800  * @drv: low level driver structure
2801  *
2802  * Remove all references to a driver from the core driver. The low level
2803  * driver must have removed all its ports via the uart_remove_one_port() if it
2804  * registered them with uart_add_one_port(). (I.e. @drv->port is %NULL.)
2805  *
2806  * Locking: none, Interrupts: enabled
2807  */
uart_unregister_driver(struct uart_driver * drv)2808 void uart_unregister_driver(struct uart_driver *drv)
2809 {
2810 	struct tty_driver *p = drv->tty_driver;
2811 	unsigned int i;
2812 
2813 	tty_unregister_driver(p);
2814 	tty_driver_kref_put(p);
2815 	for (i = 0; i < drv->nr; i++)
2816 		tty_port_destroy(&drv->state[i].port);
2817 	kfree(drv->state);
2818 	drv->state = NULL;
2819 	drv->tty_driver = NULL;
2820 }
2821 EXPORT_SYMBOL(uart_unregister_driver);
2822 
uart_console_device(struct console * co,int * index)2823 struct tty_driver *uart_console_device(struct console *co, int *index)
2824 {
2825 	struct uart_driver *p = co->data;
2826 	*index = co->index;
2827 	return p->tty_driver;
2828 }
2829 EXPORT_SYMBOL_GPL(uart_console_device);
2830 
uartclk_show(struct device * dev,struct device_attribute * attr,char * buf)2831 static ssize_t uartclk_show(struct device *dev,
2832 	struct device_attribute *attr, char *buf)
2833 {
2834 	struct serial_struct tmp;
2835 	struct tty_port *port = dev_get_drvdata(dev);
2836 
2837 	uart_get_info(port, &tmp);
2838 	return sprintf(buf, "%d\n", tmp.baud_base * 16);
2839 }
2840 
type_show(struct device * dev,struct device_attribute * attr,char * buf)2841 static ssize_t type_show(struct device *dev,
2842 	struct device_attribute *attr, char *buf)
2843 {
2844 	struct serial_struct tmp;
2845 	struct tty_port *port = dev_get_drvdata(dev);
2846 
2847 	uart_get_info(port, &tmp);
2848 	return sprintf(buf, "%d\n", tmp.type);
2849 }
2850 
line_show(struct device * dev,struct device_attribute * attr,char * buf)2851 static ssize_t line_show(struct device *dev,
2852 	struct device_attribute *attr, char *buf)
2853 {
2854 	struct serial_struct tmp;
2855 	struct tty_port *port = dev_get_drvdata(dev);
2856 
2857 	uart_get_info(port, &tmp);
2858 	return sprintf(buf, "%d\n", tmp.line);
2859 }
2860 
port_show(struct device * dev,struct device_attribute * attr,char * buf)2861 static ssize_t port_show(struct device *dev,
2862 	struct device_attribute *attr, char *buf)
2863 {
2864 	struct serial_struct tmp;
2865 	struct tty_port *port = dev_get_drvdata(dev);
2866 	unsigned long ioaddr;
2867 
2868 	uart_get_info(port, &tmp);
2869 	ioaddr = tmp.port;
2870 	if (HIGH_BITS_OFFSET)
2871 		ioaddr |= (unsigned long)tmp.port_high << HIGH_BITS_OFFSET;
2872 	return sprintf(buf, "0x%lX\n", ioaddr);
2873 }
2874 
irq_show(struct device * dev,struct device_attribute * attr,char * buf)2875 static ssize_t irq_show(struct device *dev,
2876 	struct device_attribute *attr, char *buf)
2877 {
2878 	struct serial_struct tmp;
2879 	struct tty_port *port = dev_get_drvdata(dev);
2880 
2881 	uart_get_info(port, &tmp);
2882 	return sprintf(buf, "%d\n", tmp.irq);
2883 }
2884 
flags_show(struct device * dev,struct device_attribute * attr,char * buf)2885 static ssize_t flags_show(struct device *dev,
2886 	struct device_attribute *attr, char *buf)
2887 {
2888 	struct serial_struct tmp;
2889 	struct tty_port *port = dev_get_drvdata(dev);
2890 
2891 	uart_get_info(port, &tmp);
2892 	return sprintf(buf, "0x%X\n", tmp.flags);
2893 }
2894 
xmit_fifo_size_show(struct device * dev,struct device_attribute * attr,char * buf)2895 static ssize_t xmit_fifo_size_show(struct device *dev,
2896 	struct device_attribute *attr, char *buf)
2897 {
2898 	struct serial_struct tmp;
2899 	struct tty_port *port = dev_get_drvdata(dev);
2900 
2901 	uart_get_info(port, &tmp);
2902 	return sprintf(buf, "%d\n", tmp.xmit_fifo_size);
2903 }
2904 
close_delay_show(struct device * dev,struct device_attribute * attr,char * buf)2905 static ssize_t close_delay_show(struct device *dev,
2906 	struct device_attribute *attr, char *buf)
2907 {
2908 	struct serial_struct tmp;
2909 	struct tty_port *port = dev_get_drvdata(dev);
2910 
2911 	uart_get_info(port, &tmp);
2912 	return sprintf(buf, "%d\n", tmp.close_delay);
2913 }
2914 
closing_wait_show(struct device * dev,struct device_attribute * attr,char * buf)2915 static ssize_t closing_wait_show(struct device *dev,
2916 	struct device_attribute *attr, char *buf)
2917 {
2918 	struct serial_struct tmp;
2919 	struct tty_port *port = dev_get_drvdata(dev);
2920 
2921 	uart_get_info(port, &tmp);
2922 	return sprintf(buf, "%d\n", tmp.closing_wait);
2923 }
2924 
custom_divisor_show(struct device * dev,struct device_attribute * attr,char * buf)2925 static ssize_t custom_divisor_show(struct device *dev,
2926 	struct device_attribute *attr, char *buf)
2927 {
2928 	struct serial_struct tmp;
2929 	struct tty_port *port = dev_get_drvdata(dev);
2930 
2931 	uart_get_info(port, &tmp);
2932 	return sprintf(buf, "%d\n", tmp.custom_divisor);
2933 }
2934 
io_type_show(struct device * dev,struct device_attribute * attr,char * buf)2935 static ssize_t io_type_show(struct device *dev,
2936 	struct device_attribute *attr, char *buf)
2937 {
2938 	struct serial_struct tmp;
2939 	struct tty_port *port = dev_get_drvdata(dev);
2940 
2941 	uart_get_info(port, &tmp);
2942 	return sprintf(buf, "%d\n", tmp.io_type);
2943 }
2944 
iomem_base_show(struct device * dev,struct device_attribute * attr,char * buf)2945 static ssize_t iomem_base_show(struct device *dev,
2946 	struct device_attribute *attr, char *buf)
2947 {
2948 	struct serial_struct tmp;
2949 	struct tty_port *port = dev_get_drvdata(dev);
2950 
2951 	uart_get_info(port, &tmp);
2952 	return sprintf(buf, "0x%lX\n", (unsigned long)tmp.iomem_base);
2953 }
2954 
iomem_reg_shift_show(struct device * dev,struct device_attribute * attr,char * buf)2955 static ssize_t iomem_reg_shift_show(struct device *dev,
2956 	struct device_attribute *attr, char *buf)
2957 {
2958 	struct serial_struct tmp;
2959 	struct tty_port *port = dev_get_drvdata(dev);
2960 
2961 	uart_get_info(port, &tmp);
2962 	return sprintf(buf, "%d\n", tmp.iomem_reg_shift);
2963 }
2964 
console_show(struct device * dev,struct device_attribute * attr,char * buf)2965 static ssize_t console_show(struct device *dev,
2966 	struct device_attribute *attr, char *buf)
2967 {
2968 	struct tty_port *port = dev_get_drvdata(dev);
2969 	struct uart_state *state = container_of(port, struct uart_state, port);
2970 	struct uart_port *uport;
2971 	bool console = false;
2972 
2973 	mutex_lock(&port->mutex);
2974 	uport = uart_port_check(state);
2975 	if (uport)
2976 		console = uart_console_enabled(uport);
2977 	mutex_unlock(&port->mutex);
2978 
2979 	return sprintf(buf, "%c\n", console ? 'Y' : 'N');
2980 }
2981 
console_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2982 static ssize_t console_store(struct device *dev,
2983 	struct device_attribute *attr, const char *buf, size_t count)
2984 {
2985 	struct tty_port *port = dev_get_drvdata(dev);
2986 	struct uart_state *state = container_of(port, struct uart_state, port);
2987 	struct uart_port *uport;
2988 	bool oldconsole, newconsole;
2989 	int ret;
2990 
2991 	ret = kstrtobool(buf, &newconsole);
2992 	if (ret)
2993 		return ret;
2994 
2995 	mutex_lock(&port->mutex);
2996 	uport = uart_port_check(state);
2997 	if (uport) {
2998 		oldconsole = uart_console_enabled(uport);
2999 		if (oldconsole && !newconsole) {
3000 			ret = unregister_console(uport->cons);
3001 		} else if (!oldconsole && newconsole) {
3002 			if (uart_console(uport)) {
3003 				uport->console_reinit = 1;
3004 				register_console(uport->cons);
3005 			} else {
3006 				ret = -ENOENT;
3007 			}
3008 		}
3009 	} else {
3010 		ret = -ENXIO;
3011 	}
3012 	mutex_unlock(&port->mutex);
3013 
3014 	return ret < 0 ? ret : count;
3015 }
3016 
3017 static DEVICE_ATTR_RO(uartclk);
3018 static DEVICE_ATTR_RO(type);
3019 static DEVICE_ATTR_RO(line);
3020 static DEVICE_ATTR_RO(port);
3021 static DEVICE_ATTR_RO(irq);
3022 static DEVICE_ATTR_RO(flags);
3023 static DEVICE_ATTR_RO(xmit_fifo_size);
3024 static DEVICE_ATTR_RO(close_delay);
3025 static DEVICE_ATTR_RO(closing_wait);
3026 static DEVICE_ATTR_RO(custom_divisor);
3027 static DEVICE_ATTR_RO(io_type);
3028 static DEVICE_ATTR_RO(iomem_base);
3029 static DEVICE_ATTR_RO(iomem_reg_shift);
3030 static DEVICE_ATTR_RW(console);
3031 
3032 static struct attribute *tty_dev_attrs[] = {
3033 	&dev_attr_uartclk.attr,
3034 	&dev_attr_type.attr,
3035 	&dev_attr_line.attr,
3036 	&dev_attr_port.attr,
3037 	&dev_attr_irq.attr,
3038 	&dev_attr_flags.attr,
3039 	&dev_attr_xmit_fifo_size.attr,
3040 	&dev_attr_close_delay.attr,
3041 	&dev_attr_closing_wait.attr,
3042 	&dev_attr_custom_divisor.attr,
3043 	&dev_attr_io_type.attr,
3044 	&dev_attr_iomem_base.attr,
3045 	&dev_attr_iomem_reg_shift.attr,
3046 	&dev_attr_console.attr,
3047 	NULL
3048 };
3049 
3050 static const struct attribute_group tty_dev_attr_group = {
3051 	.attrs = tty_dev_attrs,
3052 };
3053 
3054 /**
3055  * uart_add_one_port - attach a driver-defined port structure
3056  * @drv: pointer to the uart low level driver structure for this port
3057  * @uport: uart port structure to use for this port.
3058  *
3059  * Context: task context, might sleep
3060  *
3061  * This allows the driver @drv to register its own uart_port structure with the
3062  * core driver. The main purpose is to allow the low level uart drivers to
3063  * expand uart_port, rather than having yet more levels of structures.
3064  */
uart_add_one_port(struct uart_driver * drv,struct uart_port * uport)3065 int uart_add_one_port(struct uart_driver *drv, struct uart_port *uport)
3066 {
3067 	struct uart_state *state;
3068 	struct tty_port *port;
3069 	int ret = 0;
3070 	struct device *tty_dev;
3071 	int num_groups;
3072 
3073 	if (uport->line >= drv->nr)
3074 		return -EINVAL;
3075 
3076 	state = drv->state + uport->line;
3077 	port = &state->port;
3078 
3079 	mutex_lock(&port_mutex);
3080 	mutex_lock(&port->mutex);
3081 	if (state->uart_port) {
3082 		ret = -EINVAL;
3083 		goto out;
3084 	}
3085 
3086 	/* Link the port to the driver state table and vice versa */
3087 	atomic_set(&state->refcount, 1);
3088 	init_waitqueue_head(&state->remove_wait);
3089 	state->uart_port = uport;
3090 	uport->state = state;
3091 
3092 	state->pm_state = UART_PM_STATE_UNDEFINED;
3093 	uport->cons = drv->cons;
3094 	uport->minor = drv->tty_driver->minor_start + uport->line;
3095 	uport->name = kasprintf(GFP_KERNEL, "%s%d", drv->dev_name,
3096 				drv->tty_driver->name_base + uport->line);
3097 	if (!uport->name) {
3098 		ret = -ENOMEM;
3099 		goto out;
3100 	}
3101 
3102 	/*
3103 	 * If this port is in use as a console then the spinlock is already
3104 	 * initialised.
3105 	 */
3106 	if (!uart_console_enabled(uport))
3107 		uart_port_spin_lock_init(uport);
3108 
3109 	if (uport->cons && uport->dev)
3110 		of_console_check(uport->dev->of_node, uport->cons->name, uport->line);
3111 
3112 	tty_port_link_device(port, drv->tty_driver, uport->line);
3113 	uart_configure_port(drv, state, uport);
3114 
3115 	port->console = uart_console(uport);
3116 
3117 	num_groups = 2;
3118 	if (uport->attr_group)
3119 		num_groups++;
3120 
3121 	uport->tty_groups = kcalloc(num_groups, sizeof(*uport->tty_groups),
3122 				    GFP_KERNEL);
3123 	if (!uport->tty_groups) {
3124 		ret = -ENOMEM;
3125 		goto out;
3126 	}
3127 	uport->tty_groups[0] = &tty_dev_attr_group;
3128 	if (uport->attr_group)
3129 		uport->tty_groups[1] = uport->attr_group;
3130 
3131 	/*
3132 	 * Register the port whether it's detected or not.  This allows
3133 	 * setserial to be used to alter this port's parameters.
3134 	 */
3135 	tty_dev = tty_port_register_device_attr_serdev(port, drv->tty_driver,
3136 			uport->line, uport->dev, port, uport->tty_groups);
3137 	if (!IS_ERR(tty_dev)) {
3138 		device_set_wakeup_capable(tty_dev, 1);
3139 	} else {
3140 		dev_err(uport->dev, "Cannot register tty device on line %d\n",
3141 		       uport->line);
3142 	}
3143 
3144 	/*
3145 	 * Ensure UPF_DEAD is not set.
3146 	 */
3147 	uport->flags &= ~UPF_DEAD;
3148 
3149  out:
3150 	mutex_unlock(&port->mutex);
3151 	mutex_unlock(&port_mutex);
3152 
3153 	return ret;
3154 }
3155 EXPORT_SYMBOL(uart_add_one_port);
3156 
3157 /**
3158  * uart_remove_one_port - detach a driver defined port structure
3159  * @drv: pointer to the uart low level driver structure for this port
3160  * @uport: uart port structure for this port
3161  *
3162  * Context: task context, might sleep
3163  *
3164  * This unhooks (and hangs up) the specified port structure from the core
3165  * driver. No further calls will be made to the low-level code for this port.
3166  */
uart_remove_one_port(struct uart_driver * drv,struct uart_port * uport)3167 int uart_remove_one_port(struct uart_driver *drv, struct uart_port *uport)
3168 {
3169 	struct uart_state *state = drv->state + uport->line;
3170 	struct tty_port *port = &state->port;
3171 	struct uart_port *uart_port;
3172 	struct tty_struct *tty;
3173 	int ret = 0;
3174 
3175 	mutex_lock(&port_mutex);
3176 
3177 	/*
3178 	 * Mark the port "dead" - this prevents any opens from
3179 	 * succeeding while we shut down the port.
3180 	 */
3181 	mutex_lock(&port->mutex);
3182 	uart_port = uart_port_check(state);
3183 	if (uart_port != uport)
3184 		dev_alert(uport->dev, "Removing wrong port: %p != %p\n",
3185 			  uart_port, uport);
3186 
3187 	if (!uart_port) {
3188 		mutex_unlock(&port->mutex);
3189 		ret = -EINVAL;
3190 		goto out;
3191 	}
3192 	uport->flags |= UPF_DEAD;
3193 	mutex_unlock(&port->mutex);
3194 
3195 	/*
3196 	 * Remove the devices from the tty layer
3197 	 */
3198 	tty_port_unregister_device(port, drv->tty_driver, uport->line);
3199 
3200 	tty = tty_port_tty_get(port);
3201 	if (tty) {
3202 		tty_vhangup(port->tty);
3203 		tty_kref_put(tty);
3204 	}
3205 
3206 	/*
3207 	 * If the port is used as a console, unregister it
3208 	 */
3209 	if (uart_console(uport))
3210 		unregister_console(uport->cons);
3211 
3212 	/*
3213 	 * Free the port IO and memory resources, if any.
3214 	 */
3215 	if (uport->type != PORT_UNKNOWN && uport->ops->release_port)
3216 		uport->ops->release_port(uport);
3217 	kfree(uport->tty_groups);
3218 	kfree(uport->name);
3219 
3220 	/*
3221 	 * Indicate that there isn't a port here anymore.
3222 	 */
3223 	uport->type = PORT_UNKNOWN;
3224 
3225 	mutex_lock(&port->mutex);
3226 	WARN_ON(atomic_dec_return(&state->refcount) < 0);
3227 	wait_event(state->remove_wait, !atomic_read(&state->refcount));
3228 	state->uart_port = NULL;
3229 	mutex_unlock(&port->mutex);
3230 out:
3231 	mutex_unlock(&port_mutex);
3232 
3233 	return ret;
3234 }
3235 EXPORT_SYMBOL(uart_remove_one_port);
3236 
3237 /**
3238  * uart_match_port - are the two ports equivalent?
3239  * @port1: first port
3240  * @port2: second port
3241  *
3242  * This utility function can be used to determine whether two uart_port
3243  * structures describe the same port.
3244  */
uart_match_port(const struct uart_port * port1,const struct uart_port * port2)3245 bool uart_match_port(const struct uart_port *port1,
3246 		const struct uart_port *port2)
3247 {
3248 	if (port1->iotype != port2->iotype)
3249 		return false;
3250 
3251 	switch (port1->iotype) {
3252 	case UPIO_PORT:
3253 		return port1->iobase == port2->iobase;
3254 	case UPIO_HUB6:
3255 		return port1->iobase == port2->iobase &&
3256 		       port1->hub6   == port2->hub6;
3257 	case UPIO_MEM:
3258 	case UPIO_MEM16:
3259 	case UPIO_MEM32:
3260 	case UPIO_MEM32BE:
3261 	case UPIO_AU:
3262 	case UPIO_TSI:
3263 		return port1->mapbase == port2->mapbase;
3264 	}
3265 
3266 	return false;
3267 }
3268 EXPORT_SYMBOL(uart_match_port);
3269 
3270 /**
3271  * uart_handle_dcd_change - handle a change of carrier detect state
3272  * @uport: uart_port structure for the open port
3273  * @status: new carrier detect status, nonzero if active
3274  *
3275  * Caller must hold uport->lock.
3276  */
uart_handle_dcd_change(struct uart_port * uport,unsigned int status)3277 void uart_handle_dcd_change(struct uart_port *uport, unsigned int status)
3278 {
3279 	struct tty_port *port = &uport->state->port;
3280 	struct tty_struct *tty = port->tty;
3281 	struct tty_ldisc *ld;
3282 
3283 	lockdep_assert_held_once(&uport->lock);
3284 
3285 	if (tty) {
3286 		ld = tty_ldisc_ref(tty);
3287 		if (ld) {
3288 			if (ld->ops->dcd_change)
3289 				ld->ops->dcd_change(tty, status);
3290 			tty_ldisc_deref(ld);
3291 		}
3292 	}
3293 
3294 	uport->icount.dcd++;
3295 
3296 	if (uart_dcd_enabled(uport)) {
3297 		if (status)
3298 			wake_up_interruptible(&port->open_wait);
3299 		else if (tty)
3300 			tty_hangup(tty);
3301 	}
3302 }
3303 EXPORT_SYMBOL_GPL(uart_handle_dcd_change);
3304 
3305 /**
3306  * uart_handle_cts_change - handle a change of clear-to-send state
3307  * @uport: uart_port structure for the open port
3308  * @status: new clear to send status, nonzero if active
3309  *
3310  * Caller must hold uport->lock.
3311  */
uart_handle_cts_change(struct uart_port * uport,unsigned int status)3312 void uart_handle_cts_change(struct uart_port *uport, unsigned int status)
3313 {
3314 	lockdep_assert_held_once(&uport->lock);
3315 
3316 	uport->icount.cts++;
3317 
3318 	if (uart_softcts_mode(uport)) {
3319 		if (uport->hw_stopped) {
3320 			if (status) {
3321 				uport->hw_stopped = 0;
3322 				uport->ops->start_tx(uport);
3323 				uart_write_wakeup(uport);
3324 			}
3325 		} else {
3326 			if (!status) {
3327 				uport->hw_stopped = 1;
3328 				uport->ops->stop_tx(uport);
3329 			}
3330 		}
3331 
3332 	}
3333 }
3334 EXPORT_SYMBOL_GPL(uart_handle_cts_change);
3335 
3336 /**
3337  * uart_insert_char - push a char to the uart layer
3338  *
3339  * User is responsible to call tty_flip_buffer_push when they are done with
3340  * insertion.
3341  *
3342  * @port: corresponding port
3343  * @status: state of the serial port RX buffer (LSR for 8250)
3344  * @overrun: mask of overrun bits in @status
3345  * @ch: character to push
3346  * @flag: flag for the character (see TTY_NORMAL and friends)
3347  */
uart_insert_char(struct uart_port * port,unsigned int status,unsigned int overrun,unsigned int ch,unsigned int flag)3348 void uart_insert_char(struct uart_port *port, unsigned int status,
3349 		 unsigned int overrun, unsigned int ch, unsigned int flag)
3350 {
3351 	struct tty_port *tport = &port->state->port;
3352 
3353 	if ((status & port->ignore_status_mask & ~overrun) == 0)
3354 		if (tty_insert_flip_char(tport, ch, flag) == 0)
3355 			++port->icount.buf_overrun;
3356 
3357 	/*
3358 	 * Overrun is special.  Since it's reported immediately,
3359 	 * it doesn't affect the current character.
3360 	 */
3361 	if (status & ~port->ignore_status_mask & overrun)
3362 		if (tty_insert_flip_char(tport, 0, TTY_OVERRUN) == 0)
3363 			++port->icount.buf_overrun;
3364 }
3365 EXPORT_SYMBOL_GPL(uart_insert_char);
3366 
3367 #ifdef CONFIG_MAGIC_SYSRQ_SERIAL
3368 static const char sysrq_toggle_seq[] = CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE;
3369 
uart_sysrq_on(struct work_struct * w)3370 static void uart_sysrq_on(struct work_struct *w)
3371 {
3372 	int sysrq_toggle_seq_len = strlen(sysrq_toggle_seq);
3373 
3374 	sysrq_toggle_support(1);
3375 	pr_info("SysRq is enabled by magic sequence '%*pE' on serial\n",
3376 		sysrq_toggle_seq_len, sysrq_toggle_seq);
3377 }
3378 static DECLARE_WORK(sysrq_enable_work, uart_sysrq_on);
3379 
3380 /**
3381  * uart_try_toggle_sysrq - Enables SysRq from serial line
3382  * @port: uart_port structure where char(s) after BREAK met
3383  * @ch: new character in the sequence after received BREAK
3384  *
3385  * Enables magic SysRq when the required sequence is met on port
3386  * (see CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE).
3387  *
3388  * Returns: %false if @ch is out of enabling sequence and should be
3389  * handled some other way, %true if @ch was consumed.
3390  */
uart_try_toggle_sysrq(struct uart_port * port,unsigned int ch)3391 bool uart_try_toggle_sysrq(struct uart_port *port, unsigned int ch)
3392 {
3393 	int sysrq_toggle_seq_len = strlen(sysrq_toggle_seq);
3394 
3395 	if (!sysrq_toggle_seq_len)
3396 		return false;
3397 
3398 	BUILD_BUG_ON(ARRAY_SIZE(sysrq_toggle_seq) >= U8_MAX);
3399 	if (sysrq_toggle_seq[port->sysrq_seq] != ch) {
3400 		port->sysrq_seq = 0;
3401 		return false;
3402 	}
3403 
3404 	if (++port->sysrq_seq < sysrq_toggle_seq_len) {
3405 		port->sysrq = jiffies + SYSRQ_TIMEOUT;
3406 		return true;
3407 	}
3408 
3409 	schedule_work(&sysrq_enable_work);
3410 
3411 	port->sysrq = 0;
3412 	return true;
3413 }
3414 EXPORT_SYMBOL_GPL(uart_try_toggle_sysrq);
3415 #endif
3416 
3417 /**
3418  * uart_get_rs485_mode() - retrieve rs485 properties for given uart
3419  * @port: uart device's target port
3420  *
3421  * This function implements the device tree binding described in
3422  * Documentation/devicetree/bindings/serial/rs485.txt.
3423  */
uart_get_rs485_mode(struct uart_port * port)3424 int uart_get_rs485_mode(struct uart_port *port)
3425 {
3426 	struct serial_rs485 *rs485conf = &port->rs485;
3427 	struct device *dev = port->dev;
3428 	u32 rs485_delay[2];
3429 	int ret;
3430 
3431 	if (!(port->rs485_supported.flags & SER_RS485_ENABLED))
3432 		return 0;
3433 
3434 	ret = device_property_read_u32_array(dev, "rs485-rts-delay",
3435 					     rs485_delay, 2);
3436 	if (!ret) {
3437 		rs485conf->delay_rts_before_send = rs485_delay[0];
3438 		rs485conf->delay_rts_after_send = rs485_delay[1];
3439 	} else {
3440 		rs485conf->delay_rts_before_send = 0;
3441 		rs485conf->delay_rts_after_send = 0;
3442 	}
3443 
3444 	uart_sanitize_serial_rs485_delays(port, rs485conf);
3445 
3446 	/*
3447 	 * Clear full-duplex and enabled flags, set RTS polarity to active high
3448 	 * to get to a defined state with the following properties:
3449 	 */
3450 	rs485conf->flags &= ~(SER_RS485_RX_DURING_TX | SER_RS485_ENABLED |
3451 			      SER_RS485_TERMINATE_BUS |
3452 			      SER_RS485_RTS_AFTER_SEND);
3453 	rs485conf->flags |= SER_RS485_RTS_ON_SEND;
3454 
3455 	if (device_property_read_bool(dev, "rs485-rx-during-tx"))
3456 		rs485conf->flags |= SER_RS485_RX_DURING_TX;
3457 
3458 	if (device_property_read_bool(dev, "linux,rs485-enabled-at-boot-time"))
3459 		rs485conf->flags |= SER_RS485_ENABLED;
3460 
3461 	if (device_property_read_bool(dev, "rs485-rts-active-low")) {
3462 		rs485conf->flags &= ~SER_RS485_RTS_ON_SEND;
3463 		rs485conf->flags |= SER_RS485_RTS_AFTER_SEND;
3464 	}
3465 
3466 	/*
3467 	 * Disabling termination by default is the safe choice:  Else if many
3468 	 * bus participants enable it, no communication is possible at all.
3469 	 * Works fine for short cables and users may enable for longer cables.
3470 	 */
3471 	port->rs485_term_gpio = devm_gpiod_get_optional(dev, "rs485-term",
3472 							GPIOD_OUT_LOW);
3473 	if (IS_ERR(port->rs485_term_gpio)) {
3474 		ret = PTR_ERR(port->rs485_term_gpio);
3475 		port->rs485_term_gpio = NULL;
3476 		return dev_err_probe(dev, ret, "Cannot get rs485-term-gpios\n");
3477 	}
3478 	if (port->rs485_term_gpio)
3479 		port->rs485_supported.flags |= SER_RS485_TERMINATE_BUS;
3480 
3481 	return 0;
3482 }
3483 EXPORT_SYMBOL_GPL(uart_get_rs485_mode);
3484 
3485 /* Compile-time assertions for serial_rs485 layout */
3486 static_assert(offsetof(struct serial_rs485, padding) ==
3487               (offsetof(struct serial_rs485, delay_rts_after_send) + sizeof(__u32)));
3488 static_assert(offsetof(struct serial_rs485, padding1) ==
3489 	      offsetof(struct serial_rs485, padding[1]));
3490 static_assert((offsetof(struct serial_rs485, padding[4]) + sizeof(__u32)) ==
3491 	      sizeof(struct serial_rs485));
3492 
3493 MODULE_DESCRIPTION("Serial driver core");
3494 MODULE_LICENSE("GPL");
3495