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 includesdecoding command line arguments (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 thestructuart_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¶
- structuart_ops¶
interface between serial_core and the driver
Definition:
struct uart_ops { unsigned int (*tx_empty)(struct uart_port *); void (*set_mctrl)(struct uart_port *, unsigned int mctrl); unsigned int (*get_mctrl)(struct uart_port *); void (*stop_tx)(struct uart_port *); void (*start_tx)(struct uart_port *); void (*throttle)(struct uart_port *); void (*unthrottle)(struct uart_port *); void (*send_xchar)(struct uart_port *, char ch); void (*stop_rx)(struct uart_port *); void (*start_rx)(struct uart_port *); void (*enable_ms)(struct uart_port *); void (*break_ctl)(struct uart_port *, int ctl); int (*startup)(struct uart_port *); void (*shutdown)(struct uart_port *); void (*flush_buffer)(struct uart_port *); void (*set_termios)(struct uart_port *, struct ktermios *new, const struct ktermios *old); void (*set_ldisc)(struct uart_port *, struct ktermios *); void (*pm)(struct uart_port *, unsigned int state, unsigned int oldstate); const char *(*type)(struct uart_port *); void (*release_port)(struct uart_port *); int (*request_port)(struct uart_port *); void (*config_port)(struct uart_port *, int); int (*verify_port)(struct uart_port *, struct serial_struct *); int (*ioctl)(struct uart_port *, unsigned int, unsigned long);#ifdef CONFIG_CONSOLE_POLL; int (*poll_init)(struct uart_port *); void (*poll_put_char)(struct uart_port *, unsigned char); int (*poll_get_char)(struct uart_port *);#endif;};Members
tx_emptyunsignedint()(structuart_port*port)set_mctrlvoid()(structuart_port*port,unsignedintmctrl)get_mctrlunsignedint()(structuart_port*port)stop_txvoid()(structuart_port*port)start_txvoid()(structuart_port*port)throttlevoid()(structuart_port*port)unthrottlevoid()(structuart_port*port)send_xcharvoid()(structuart_port*port,charch)stop_rxvoid()(structuart_port*port)start_rxvoid()(structuart_port*port)enable_msvoid()(structuart_port*port)break_ctlvoid()(structuart_port*port,intctl)startupint()(structuart_port*port)shutdownvoid()(structuart_port*port)flush_buffervoid()(structuart_port*port)set_termiosvoid()(structuart_port*port,structktermios*new,structktermios*old)set_ldiscvoid()(structuart_port*port,structktermios*termios)pmvoid()(structuart_port*port,unsignedintstate,unsignedintoldstate)typeconstchar*()(structuart_port*port)release_portvoid()(structuart_port*port)request_portint()(structuart_port*port)config_portvoid()(structuart_port*port,inttype)verify_portint()(structuart_port*port,structserial_struct*serinfo)ioctlint()(structuart_port*port,unsignedintcmd,unsignedlongarg)poll_initint()(structuart_port*port)poll_put_charvoid()(structuart_port*port,unsignedcharch)poll_get_charint()(structuart_port*port)
Description
This structure describes all the operations that can be done on thephysical hardware.
This function tests whether the transmitter fifo and shifter for theport is empty. If it is empty, this function should return
TIOCSER_TEMT, otherwise return 0. If the port does not support thisoperation, then it should returnTIOCSER_TEMT.Locking: none.Interrupts: caller dependent.This call must not sleep
This function sets the modem control lines forport to the statedescribed bymctrl. The relevant bits ofmctrl are:
TIOCM_RTSRTS signal.
TIOCM_DTRDTR signal.
TIOCM_OUT1OUT1 signal.
TIOCM_OUT2OUT2 signal.
TIOCM_LOOPSet 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
Returns the current state of modem control inputs ofport. The stateof the outputs should not be returned, since the core keeps track oftheir state. The state information should include:
TIOCM_CARstate of DCD signal
TIOCM_CTSstate of CTS signal
TIOCM_DSRstate of DSR signal
TIOCM_RIstate of RI signalThe 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 transmitting characters. This might be due to the CTS linebecoming inactive or the tty layer indicating we want to stoptransmission due to an
XOFFcharacter.The driver should stop transmitting characters as soon as possible.
Locking:port->lock taken.Interrupts: locally disabled.This call must not sleep
Start transmitting characters.
Locking:port->lock taken.Interrupts: locally disabled.This call must not sleep
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.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.Transmit a high priority character, even if the port is stopped. Thisis used to implement XON/XOFF flow control and
tcflow(). If the serialdriver does not implement this function, the tty core will append thecharacter to the circular buffer and then callstart_tx()/stop_tx()to flush the data out.Do not transmit ifch == ‘0’ (
__DISABLED_CHAR).Locking: none.Interrupts: caller dependent.
Start receiving characters.
Locking:port->lock taken.Interrupts: locally disabled.This call must not sleep
Stop receiving characters; theport is in the process of being closed.
Locking:port->lock taken.Interrupts: locally disabled.This call must not sleep
Enable the modem status interrupts.
This method may be called multiple times. Modem status interruptsshould be disabled when the
shutdown()method is called.Locking:port->lock taken.Interrupts: locally disabled.This call must not sleep
Control the transmission of a break signal. Ifctl is nonzero, thebreak signal should be transmitted. The signal should be terminatedwhen another call is made with a zeroctl.
Locking: caller holds tty_port->mutex
Grab any interrupt resources and initialise any low level driver state.Enable the port for reception. It should not activate RTS 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.
Disable theport, disable any break condition that may be in effect,and free any interrupt resources. It should not disable RTS nor DTR;this will have already been done via a separate call to
set_mctrl().Drivers must not accessport->state once this call has completed.
This method will only be called when there are no more users of thisport.
Locking: port_sem taken.Interrupts: caller dependent.
Flush any write buffers, reset any DMA state and stop any ongoing DMAtransfers.
This will be called whenever theport->state->xmit circular buffer iscleared.
Locking:port->lock taken.Interrupts: locally disabled.This call must not sleep
Change theport parameters, including word length, parity, stop bits.Updateport->read_status_mask andport->ignore_status_mask toindicate the types of events we are interested in receiving. Relevantktermios::c_cflag bits are:
CSIZE- word size
CSTOPB- 2 stop bits
PARENB- parity enable
PARODD- odd parity (whenPARENBis in force)
ADDRB- address bit (changed through uart_port::rs485_config()).
CREAD- enable reception of characters (if not set, still receivecharacters from the port, but throw them away).
CRTSCTS- if set, enable CTS status change reporting.
CLOCAL- if not set, enable modem status change reporting.Relevant ktermios::c_iflag bits are:
INPCK- enable frame and parity error events to be passed to the TTYlayer.
BRKINT/PARMRK- both of these enable break events to be passed tothe TTY layer.
IGNPAR- ignore parity and framing errors.
IGNBRK- ignore break errors. IfIGNPARis also set, ignore overrunerrors as well.The interaction of the ktermios::c_iflag bits is as follows (parityerror given as an example):
Parity error
INPCK
IGNPAR
n/a
0
n/a
character received, marked as
TTY_NORMALNone
1
n/a
character received, marked as
TTY_NORMALYes
1
0
character received, marked as
TTY_PARITYYes
1
1
character discarded
Other flags may be used (eg, xon/xoff characters) if your hardwaresupports hardware “soft” flow control.
Locking: caller holds tty_port->mutexInterrupts: caller dependent.This call must not sleep
Notifier for discipline change. SeeTTY Line Discipline.
Locking: caller holds tty_port->mutex
Perform any power management related activities on the specifiedport.state indicates the new state (defined by
enumuart_pm_state),oldstate indicates the previous state.This function should not be used to grab any resources.
This will be called when theport is initially opened and finallyclosed, except when theport is also the system console. This willoccur even if
CONFIG_PMis not set.Locking: none.Interrupts: caller dependent.
Return a pointer to a string constant describing the specifiedport,or return
NULL, in which case the string ‘unknown’ is substituted.Locking: none.Interrupts: caller dependent.
Release any memory and IO region resources currently in use by theport.
Locking: none.Interrupts: caller dependent.
Request any memory and IO region resources required by the port. If anyfail, no resources should be registered when this function returns, andit should return -
EBUSYon failure.Locking: none.Interrupts: caller dependent.
Perform any autoconfiguration steps required for theport.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, orPORT_UNKNOWNif noport was detected.
UART_CONFIG_IRQindicates 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 the new serial port information contained withinserinfo issuitable for this port type.
Locking: none.Interrupts: caller dependent.
Perform any port specific IOCTLs. IOCTL commands must be defined usingthe standard numbering system found in <asm/ioctl.h>.
Locking: none.Interrupts: caller dependent.
Called by kgdb to perform the minimal hardware initialization needed tosupport
poll_put_char()andpoll_get_char(). Unlikestartup(), thisshould not request interrupts.Locking:
tty_mutexand tty_port->mutex taken.Interrupts: n/a.Called by kgdb to write a single characterch 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
Called by kgdb to read a single character directly from the serialport. If data is available, it should be returned; otherwise thefunction should return
NO_POLL_CHARimmediately.Locking: none.Interrupts: caller dependent.This call must not sleep
Other functions¶
- voiduart_write_wakeup(structuart_port*port)¶
schedule write processing
Parameters
structuart_port*portport to be processed
Description
This routine is used by the interrupt handler to schedule processing in thesoftware interrupt portion of the driver. A driver is expected to call thisfunction when the number of characters in the transmit buffer have droppedbelow a threshold.
Locking:port->lock should be held
- voiduart_update_timeout(structuart_port*port,unsignedintcflag,unsignedintbaud)¶
update per-port frame timing information
Parameters
structuart_port*portuart_port structure describing the port
unsignedintcflagtermios cflag value
unsignedintbaudspeed of the port
Description
Set theport frame timing information from which the FIFO timeout value isderived. Thecflag value should reflect the actual hardware settings asnumber of bits, parity, stop bits and baud rate is taken into account here.
Locking: caller is expected to takeport->lock
- unsignedintuart_get_baud_rate(structuart_port*port,structktermios*termios,conststructktermios*old,unsignedintmin,unsignedintmax)¶
return baud rate for a particular port
Parameters
structuart_port*portuart_port structure describing the port in question.
structktermios*termiosdesired termios settings
conststructktermios*oldold termios (or
NULL)unsignedintminminimum acceptable baud rate
unsignedintmaxmaximum acceptable baud rate
Description
Decode the termios structure into a numeric baud rate, taking account of themagic 38400 baud rate (with spd_* flags), and mapping theB0 rate to 9600baud.
If the new baud rate is invalid, try theold termios setting. If it’s stillinvalid, we try 9600 baud. If that is also invalid 0 is returned.
Thetermios structure is updated to reflect the baud rate we’re actuallygoing to be using. Don’t do this for the case where B0 is requested (“hangup”).
Locking: caller dependent
- unsignedintuart_get_divisor(structuart_port*port,unsignedintbaud)¶
return uart clock divisor
Parameters
structuart_port*portuart_port structure describing the port
unsignedintbauddesired baud rate
Description
Calculate the divisor (baud_base / baud) for the specifiedbaud,appropriately rounded.
If 38400 baud and custom divisor is selected, return the custom divisorinstead.
Locking: caller dependent
- intuart_get_lsr_info(structtty_struct*tty,structuart_state*state,unsignedint__user*value)¶
get line status register info
Parameters
structtty_struct*ttytty associated with the UART
structuart_state*stateUART being queried
unsignedint__user*valuereturned modem value
- voiduart_console_write(structuart_port*port,constchar*s,unsignedintcount,void(*putchar)(structuart_port*,unsignedchar))¶
write a console message to a serial port
Parameters
structuart_port*portthe port to write the message
constchar*sarray of characters
unsignedintcountnumber of characters in string to write
void(*putchar)(structuart_port*,unsignedchar)function to write character to port
- intuart_parse_earlycon(char*p,enumuart_iotype*iotype,resource_size_t*addr,char**options)¶
Parse earlycon options
Parameters
char*pptr to 2nd field (ie., just beyond ‘<name>,’)
enumuart_iotype*iotypeptr for decoded iotype (out)
resource_size_t*addrptr for decoded mapbase/iobase (out)
char**optionsptr for <options> field;
NULLif not present (out)
Description
- Decodes earlycon kernel command line parameters of the form:
earlycon=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
console=<name>,io|mmio|mmio16|mmio32|mmio32be|mmio32native,<addr>,<options>
- The optional form:
earlycon=<name>,0x<addr>,<options>
console=<name>,0x<addr>,<options>
is also accepted; the returnediotype will beUPIO_MEM.
Return
0 on success or -EINVAL on failure
- voiduart_parse_options(constchar*options,int*baud,int*parity,int*bits,int*flow)¶
Parse serial port baud/parity/bits/flow control.
Parameters
constchar*optionspointer to option string
int*baudpointer to an ‘int’ variable for the baud rate.
int*paritypointer to an ‘int’ variable for the parity.
int*bitspointer to an ‘int’ variable for the number of data bits.
int*flowpointer to an ‘int’ variable for the flow control character.
Description
uart_parse_options() decodes a string containing the serial consoleoptions. The format of the string is <baud><parity><bits><flow>,eg: 115200n8r
- intuart_set_options(structuart_port*port,structconsole*co,intbaud,intparity,intbits,intflow)¶
setup the serial console parameters
Parameters
structuart_port*portpointer to the serial ports uart_port structure
structconsole*coconsole pointer
intbaudbaud rate
intparityparity character - ‘n’ (none), ‘o’ (odd), ‘e’ (even)
intbitsnumber of data bits
intflowflow control character - ‘r’ (rts)
Description
Locking: Caller must hold console_list_lock in order to serializeearly initialization of the serial-console lock.
- intuart_register_driver(structuart_driver*drv)¶
register a driver with the uart core layer
Parameters
structuart_driver*drvlow level driver structure
Description
Register a uart driver with the core driver. We in turn register with thetty layer, and initialise the core driver per-port state.
We have a proc file in /proc/tty/driver which is named after the normaldriver.
drv->port should beNULL, and the per-port structures should be registeredusinguart_add_one_port() after this call has succeeded.
Locking: none, Interrupts: enabled
- voiduart_unregister_driver(structuart_driver*drv)¶
remove a driver from the uart core layer
Parameters
structuart_driver*drvlow level driver structure
Description
Remove all references to a driver from the core driver. The low leveldriver must have removed all its ports via theuart_remove_one_port() if itregistered them withuart_add_one_port(). (I.e.drv->port isNULL.)
Locking: none, Interrupts: enabled
- booluart_match_port(conststructuart_port*port1,conststructuart_port*port2)¶
are the two ports equivalent?
Parameters
conststructuart_port*port1first port
conststructuart_port*port2second port
Description
This utility function can be used to determine whether two uart_portstructures describe the same port.
- voiduart_handle_dcd_change(structuart_port*uport,boolactive)¶
handle a change of carrier detect state
Parameters
structuart_port*uportuart_port structure for the open port
boolactivenew carrier detect status
Description
Caller must hold uport->lock.
- voiduart_handle_cts_change(structuart_port*uport,boolactive)¶
handle a change of clear-to-send state
Parameters
structuart_port*uportuart_port structure for the open port
boolactivenew clear-to-send status
Description
Caller must hold uport->lock.
- booluart_try_toggle_sysrq(structuart_port*port,u8ch)¶
Enables SysRq from serial line
Parameters
structuart_port*portuart_port structure where char(s) after BREAK met
u8chnew character in the sequence after received BREAK
Description
Enables magic SysRq when the required sequence is met on port(see CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE).
Return
false ifch is out of enabling sequence and should behandled some other way,true ifch was consumed.
- uart_port_tx_limited¶
uart_port_tx_limited(port,ch,count,tx_ready,put_char,tx_done)
transmit helper for uart_port with count limiting
Parameters
portuart port
chvariable to store a character to be written to the HW
counta limit of characters to send
tx_readycan HW accept more data function
put_charfunction to write a character
tx_donefunction to call after the loop is done
Description
This helper transmits characters from the xmit buffer to the hardware usingput_char(). It does so untilcount characters are sent and whiletx_readyevaluates to true.
- The expression in macro parameters shall be designed as follows:
tx_ready: should evaluate to true if the HW can accept more data tobe sent. This parameter can be
true, which means the HW is always ready.put_char: shall writech to the device ofport.
tx_done: when the write loop is done, this can perform arbitraryaction before potential invocation of ops->
stop_tx()happens. If thedriver does not need to do anything, use e.g. ({}).
For all of them,port->lock is held, interrupts are locally disabled andthe expressions must not sleep.
Return
the number of characters in the xmit buffer when done.
- uart_port_tx¶
uart_port_tx(port,ch,tx_ready,put_char)
transmit helper for uart_port
Parameters
portuart port
chvariable to store a character to be written to the HW
tx_readycan HW accept more data function
put_charfunction to write a character
Description
Seeuart_port_tx_limited() for more details.
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.
- voidmctrl_gpio_set(structmctrl_gpios*gpios,unsignedintmctrl)¶
set gpios according to mctrl state
Parameters
structmctrl_gpios*gpiosgpios to set
unsignedintmctrlstate to set
Description
Set the gpios according to the mctrl state.
- structgpio_desc*mctrl_gpio_to_gpiod(structmctrl_gpios*gpios,enummctrl_gpio_idxgidx)¶
obtain gpio_desc of modem line index
Parameters
structmctrl_gpios*gpiosgpios to look into
enummctrl_gpio_idxgidxindex of the modem line
Return
the gpio_desc structure associated to the modem line index
- unsignedintmctrl_gpio_get(structmctrl_gpios*gpios,unsignedint*mctrl)¶
update mctrl with the gpios values.
Parameters
structmctrl_gpios*gpiosgpios to get the info from
unsignedint*mctrlmctrl to set
Return
modified mctrl (the same value as inmctrl)
Description
Update mctrl with the gpios values.
- structmctrl_gpios*mctrl_gpio_init(structuart_port*port,unsignedintidx)¶
initialize uart gpios
Parameters
structuart_port*portport to initialize gpios for
unsignedintidxindex of the gpio in theport’s device
Description
This will get the {cts,rts,...}-gpios from device tree if they are presentand request them, set direction etc, and return an allocated structure.devm_* functions are used, so there’s no need to explicitly free.As this sets up the irq handling, make sure to not handle changes to thegpio input lines in your driver, too.
- voidmctrl_gpio_enable_ms(structmctrl_gpios*gpios)¶
enable irqs and handling of changes to the ms lines
Parameters
structmctrl_gpios*gpiosgpios to enable
- voidmctrl_gpio_disable_ms_sync(structmctrl_gpios*gpios)¶
disable irqs and handling of changes to the ms lines, and wait for any pending IRQ to be processed
Parameters
structmctrl_gpios*gpiosgpios to disable
- voidmctrl_gpio_disable_ms_no_sync(structmctrl_gpios*gpios)¶
disable irqs and handling of changes to the ms lines, and return immediately
Parameters
structmctrl_gpios*gpiosgpios to disable