File Index
Files and directories
Sign in
FILE

serial_core.c

File preview with syntax highlighting.

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