Low Level Serial API

This document is meant as a brief overview of some aspects of the new serialdriver. It is not complete, any questions you have should be directed to<rmk@arm.linux.org.uk>

The reference implementation is contained within amba-pl011.c.

Low Level Serial Hardware Driver

The low level serial hardware driver is responsible for supplying portinformation (defined by uart_port) and a set of control methods (definedby uart_ops) to the core serial driver. The low level driver is alsoresponsible for handling interrupts for the port, and providing anyconsole support.

Console Support

The serial core provides a few helper functions. This includes identifingthe correct port structure (via uart_get_console) and decoding command linearguments (uart_parse_options).

There is also a helper function (uart_console_write) which performs acharacter by character write, translating newlines to CRLF sequences.Driver writers are recommended to use this function rather than implementingtheir own version.

Locking

It is the responsibility of the low level hardware driver to perform thenecessary locking using port->lock. There are some exceptions (whichare described in the uart_ops listing below.)

There are two locks. A per-port spinlock, and an overall semaphore.

From the core driver perspective, the port->lock locks the followingdata:

port->mctrlport->icountport->state->xmit.head (circ_buf->head)port->state->xmit.tail (circ_buf->tail)

The low level driver is free to use this lock to provide any additionallocking.

The port_sem semaphore is used to protect against ports being added/removed or reconfigured at inappropriate times. Since v2.6.27, thissemaphore has been the ‘mutex’ member of the tty_port struct, andcommonly referred to as the port mutex.

uart_ops

The uart_ops structure is the main interface between serial_core and thehardware specific driver. It contains all the methods to control thehardware.

tx_empty(port)

This function tests whether the transmitter fifo and shifterfor the port described by ‘port’ is empty. If it is empty,this function should return TIOCSER_TEMT, otherwise return 0.If the port does not support this operation, then it shouldreturn TIOCSER_TEMT.

Locking: none.

Interrupts: caller dependent.

This call must not sleep

set_mctrl(port, mctrl)

This function sets the modem control lines for port describedby ‘port’ to the state described by mctrl. The relevant bitsof mctrl are:

  • TIOCM_RTS RTS signal.
  • TIOCM_DTR DTR signal.
  • TIOCM_OUT1 OUT1 signal.
  • TIOCM_OUT2 OUT2 signal.
  • TIOCM_LOOP Set the port into loopback mode.

If the appropriate bit is set, the signal should be drivenactive. If the bit is clear, the signal should be driveninactive.

Locking: port->lock taken.

Interrupts: locally disabled.

This call must not sleep

get_mctrl(port)

Returns the current state of modem control inputs. The stateof the outputs should not be returned, since the core keepstrack of their state. The state information should include:

  • TIOCM_CAR state of DCD signal
  • TIOCM_CTS state of CTS signal
  • TIOCM_DSR state of DSR signal
  • TIOCM_RI state of RI signal

The bit is set if the signal is currently driven active. Ifthe port does not support CTS, DCD or DSR, the driver shouldindicate that the signal is permanently active. If RI isnot available, the signal should not be indicated as active.

Locking: port->lock taken.

Interrupts: locally disabled.

This call must not sleep

stop_tx(port)

Stop transmitting characters. This might be due to the CTSline becoming inactive or the tty layer indicating we wantto stop transmission due to an XOFF character.

The driver should stop transmitting characters as soon aspossible.

Locking: port->lock taken.

Interrupts: locally disabled.

This call must not sleep

start_tx(port)

Start transmitting characters.

Locking: port->lock taken.

Interrupts: locally disabled.

This call must not sleep

throttle(port)

Notify the serial driver that input buffers for the line discipline areclose to full, and it should somehow signal that no more charactersshould be sent to the serial port.This will be called only if hardware assisted flow control is enabled.

Locking: serialized with .unthrottle() and termios modification by thetty layer.

unthrottle(port)

Notify the serial driver that characters can now be sent to the serialport without fear of overrunning the input buffers of the linedisciplines.

This will be called only if hardware assisted flow control is enabled.

Locking: serialized with .throttle() and termios modification by thetty layer.

send_xchar(port,ch)

Transmit a high priority character, even if the port is stopped.This is used to implement XON/XOFF flow control and tcflow(). Ifthe serial driver does not implement this function, the tty corewill append the character to the circular buffer and then callstart_tx() / stop_tx() to flush the data out.

Do not transmit if ch == ‘0’ (__DISABLED_CHAR).

Locking: none.

Interrupts: caller dependent.

stop_rx(port)

Stop receiving characters; the port is in the process ofbeing closed.

Locking: port->lock taken.

Interrupts: locally disabled.

This call must not sleep

enable_ms(port)

Enable the modem status interrupts.

This method may be called multiple times. Modem statusinterrupts should be disabled when the shutdown method iscalled.

Locking: port->lock taken.

Interrupts: locally disabled.

This call must not sleep

break_ctl(port,ctl)

Control the transmission of a break signal. If ctl isnonzero, the break signal should be transmitted. The signalshould be terminated when another call is made with a zeroctl.

Locking: caller holds tty_port->mutex

startup(port)

Grab any interrupt resources and initialise any low level driverstate. Enable the port for reception. It should not activateRTS nor DTR; this will be done via a separate call to set_mctrl.

This method will only be called when the port is initially opened.

Locking: port_sem taken.

Interrupts: globally disabled.

shutdown(port)

Disable the port, disable any break condition that may be ineffect, and free any interrupt resources. It should not disableRTS nor DTR; this will have already been done via a separatecall to set_mctrl.

Drivers must not access port->state once this call has completed.

This method will only be called when there are no more users ofthis port.

Locking: port_sem taken.

Interrupts: caller dependent.

flush_buffer(port)

Flush any write buffers, reset any DMA state and stop anyongoing DMA transfers.

This will be called whenever the port->state->xmit circularbuffer is cleared.

Locking: port->lock taken.

Interrupts: locally disabled.

This call must not sleep

set_termios(port,termios,oldtermios)

Change the port parameters, including word length, parity, stopbits. Update read_status_mask and ignore_status_mask to indicatethe types of events we are interested in receiving. Relevanttermios->c_cflag bits are:

CSIZE
  • word size
CSTOPB
  • 2 stop bits
PARENB
  • parity enable
PARODD
  • odd parity (when PARENB is in force)
CREAD
  • enable reception of characters (if not set,still receive characters from the port, butthrow them away.
CRTSCTS
  • if set, enable CTS status change reporting
CLOCAL
  • if not set, enable modem status changereporting.

Relevant termios->c_iflag bits are:

INPCK
  • enable frame and parity error events to bepassed to the TTY layer.
BRKINT / PARMRK
  • both of these enable break events to bepassed to the TTY layer.
IGNPAR
  • ignore parity and framing errors
IGNBRK
  • ignore break errors, If IGNPAR is alsoset, ignore overrun errors as well.

The interaction of the iflag bits is as follows (parity errorgiven as an example):

Parity errorINPCKIGNPAR 
n/a0n/acharacter received, marked asTTY_NORMAL
None1n/acharacter received, marked asTTY_NORMAL
Yes10character received, marked asTTY_PARITY
Yes11character discarded

Other flags may be used (eg, xon/xoff characters) if yourhardware supports hardware “soft” flow control.

Locking: caller holds tty_port->mutex

Interrupts: caller dependent.

This call must not sleep

set_ldisc(port,termios)

Notifier for discipline change. See Documentation/driver-api/serial/tty.rst.

Locking: caller holds tty_port->mutex

pm(port,state,oldstate)

Perform any power management related activities on the specifiedport. State indicates the new state (defined byenum uart_pm_state), oldstate indicates the previous state.

This function should not be used to grab any resources.

This will be called when the port is initially opened and finallyclosed, except when the port is also the system console. Thiswill occur even if CONFIG_PM is not set.

Locking: none.

Interrupts: caller dependent.

type(port)

Return a pointer to a string constant describing the specifiedport, or return NULL, in which case the string ‘unknown’ issubstituted.

Locking: none.

Interrupts: caller dependent.

release_port(port)

Release any memory and IO region resources currently in use bythe port.

Locking: none.

Interrupts: caller dependent.

request_port(port)

Request any memory and IO region resources required by the port.If any fail, no resources should be registered when this functionreturns, and it should return -EBUSY on failure.

Locking: none.

Interrupts: caller dependent.

config_port(port,type)

Perform any autoconfiguration steps required for the port.typecontains a bit mask of the required configuration. UART_CONFIG_TYPEindicates that the port requires detection and identification.port->type should be set to the type found, or PORT_UNKNOWN ifno port was detected.

UART_CONFIG_IRQ indicates autoconfiguration of the interrupt signal,which should be probed using standard kernel autoprobing techniques.This is not necessary on platforms where ports have interruptsinternally hard wired (eg, system on a chip implementations).

Locking: none.

Interrupts: caller dependent.

verify_port(port,serinfo)

Verify the new serial port information contained within serinfo issuitable for this port type.

Locking: none.

Interrupts: caller dependent.

ioctl(port,cmd,arg)

Perform any port specific IOCTLs. IOCTL commands must be definedusing the standard numbering system found in <asm/ioctl.h>

Locking: none.

Interrupts: caller dependent.

poll_init(port)

Called by kgdb to perform the minimal hardware initialization neededto support poll_put_char() and poll_get_char(). Unlike ->startup()this should not request interrupts.

Locking: tty_mutex and tty_port->mutex taken.

Interrupts: n/a.

poll_put_char(port,ch)

Called by kgdb to write a single character directly to the serialport. It can and should block until there is space in the TX FIFO.

Locking: none.

Interrupts: caller dependent.

This call must not sleep

poll_get_char(port)

Called by kgdb to read a single character directly from the serialport. If data is available, it should be returned; otherwisethe function should return NO_POLL_CHAR immediately.

Locking: none.

Interrupts: caller dependent.

This call must not sleep

Other functions

uart_update_timeout(port,cflag,baud)

Update the FIFO drain timeout, port->timeout, according to thenumber of bits, parity, stop bits and baud rate.

Locking: caller is expected to take port->lock

Interrupts: n/a

uart_get_baud_rate(port,termios,old,min,max)

Return the numeric baud rate for the specified termios, takingaccount of the special 38400 baud “kludge”. The B0 baud rateis mapped to 9600 baud.

If the baud rate is not within min..max, then if old is non-NULL,the original baud rate will be tried. If that exceeds themin..max constraint, 9600 baud will be returned. termios willbe updated to the baud rate in use.

Note: min..max must always allow 9600 baud to be selected.

Locking: caller dependent.

Interrupts: n/a

uart_get_divisor(port,baud)

Return the divisor (baud_base / baud) for the specified baudrate, appropriately rounded.

If 38400 baud and custom divisor is selected, return thecustom divisor instead.

Locking: caller dependent.

Interrupts: n/a

uart_match_port(port1,port2)

This utility function can be used to determine whether twouart_port structures describe the same port.

Locking: n/a

Interrupts: n/a

uart_write_wakeup(port)

A driver is expected to call this function when the number ofcharacters in the transmit buffer have dropped below a threshold.

Locking: port->lock should be held.

Interrupts: n/a

uart_register_driver(drv)

Register a uart driver with the core driver. We in turn registerwith the tty layer, and initialise the core driver per-port state.

drv->port should be NULL, and the per-port structures should beregistered using uart_add_one_port after this call has succeeded.

Locking: none

Interrupts: enabled

uart_unregister_driver()

Remove all references to a driver from the core driver. The lowlevel driver must have removed all its ports via theuart_remove_one_port() if it registered them withuart_add_one_port().

Locking: none

Interrupts: enabled

uart_suspend_port()

uart_resume_port()

uart_add_one_port()

uart_remove_one_port()

Other notes

It is intended some day to drop the ‘unused’ entries from uart_port, andallow low level drivers to register their own individual uart_port’s withthe core. This will allow drivers to use uart_port as a pointer to astructure containing both the uart_port entry with their own extensions,thus:

struct my_port {        struct uart_port        port;        int                     my_stuff;};

Modem control lines via GPIO

Some helpers are provided in order to set/get modem control lines via GPIO.

mctrl_gpio_init(port, idx):
This will get the {cts,rts,…}-gpios from device tree if they arepresent and request them, set direction etc, and return anallocated structure.devm_* functions are used, so there’s no needto call mctrl_gpio_free().As this sets up the irq handling make sure to not handle changes to thegpio input lines in your driver, too.
mctrl_gpio_free(dev, gpios):
This will free the requested gpios in mctrl_gpio_init().Asdevm_* functions are used, there’s generally no need to callthis function.
mctrl_gpio_to_gpiod(gpios, gidx)
This returns the gpio_desc structure associated to the modem lineindex.
mctrl_gpio_set(gpios, mctrl):
This will sets the gpios according to the mctrl state.
mctrl_gpio_get(gpios, mctrl):
This will update mctrl with the gpios values.
mctrl_gpio_enable_ms(gpios):
Enables irqs and handling of changes to the ms lines.
mctrl_gpio_disable_ms(gpios):
Disables irqs and handling of changes to the ms lines.