TTY
Single-page view · as markdown
TTY
Peios Kernel / Hardware and drivers / Driver development / TTY
Teletypewriter (TTY) layer takes care of all those serial devices. Including the virtual ones like pseudoterminal (PTY).
TTY structures #
There are several major TTY structures. Every TTY device in a system has a corresponding struct tty_port. These devices are maintained by a TTY driver which is struct tty_driver. This structure describes the driver but also contains a reference to operations which could be performed on the TTYs. It is struct tty_operations. Then, upon open, a struct tty_struct is allocated and lives until the final close. During this time, several callbacks from struct tty_operations are invoked by the TTY layer.
Every character received by the kernel (both from devices and users) is passed through a preselected TTY Line Discipline (in short ldisc; in C, struct tty_ldisc_ops). Its task is to transform characters as defined by a particular ldisc or by user too. The default one is n_tty, implementing echoes, signal handling, jobs control, special characters processing, and more. The transformed characters are passed further to user/device, depending on the source.
In-detail description of the named TTY structures is in separate documents:
- TTY Driver and TTY Operations
- TTY Port
- TTY Struct
- TTY Line Discipline
- TTY Buffer
- TTY IOCTL Helpers
- TTY Internals
- Console
Writing TTY Driver #
Before one starts writing a TTY driver, they must consider Serial and USB Serial layers first. Drivers for serial devices can often use one of these specific layers to implement a serial driver. Only special devices should be handled directly by the TTY Layer. If you are about to write such a driver, read on.
A typical sequence a TTY driver performs is as follows:
-
Allocate and register a TTY driver (module init)
-
Create and register TTY devices as they are probed (probe function)
-
Handle TTY operations and events like interrupts (TTY core invokes the former, the device the latter)
-
Remove devices as they are going away (remove function)
-
Unregister and free the TTY driver (module exit)
Steps regarding driver, i.e. 1., 3., and 5. are described in detail in TTY Driver and TTY Operations. For the other two (devices handling), look into TTY Port.
Other Documentation #
Miscellaneous documentation can be further found in these documents:
Console
Peios Kernel / Hardware and drivers / Driver development / TTY
Struct Console #
enum cons_flags #
General console flags
Constants
CON_PRINTBUFFER: Used by newly registered consoles to avoid duplicate output of messages that were already shown by boot consoles or read by userspace viasyslog()syscall.CON_CONSDEV: Indicates that the console driver is backing /dev/console.CON_ENABLED: Indicates if a console is allowed to print records. If false, the console also will not advance to later records.CON_BOOT: Marks the console driver as early console driver which is used during boot before the real driver becomes available. It will be automatically unregistered when the real console driver is registered unless "keep_bootcon" parameter is used.CON_ANYTIME: A misnomed historical flag which tells the core code that the legacy console::write callback can be invoked on a CPU which is marked OFFLINE. That is misleading as it suggests that there is no contextual limit for invoking the callback. The original motivation was readiness of the per-CPU areas.CON_BRL: Indicates a braille device which is exempt from receiving the printk spam for obvious reasons.CON_EXTENDED: The console supports the extended output format of /dev/kmesg which requires a larger output buffer.CON_SUSPENDED: Indicates if a console is suspended. If true, the printing callbacks must not be called.CON_NBCON: Console can operate outside of the legacy style console_lock constraints.CON_NBCON_ATOMIC_UNSAFE: Thewrite_atomic()callback is not safe and is therefore only used bynbcon_atomic_flush_unsafe().
struct console #
The console descriptor structure
Definition
;
Members
-
name: The name of the console driver -
write: Legacy write callback to output messages (Optional) -
read: Read callback for console input (Optional) -
device: The underlying TTY device driver (Optional) -
unblank: Callback to unblank the console (Optional) -
setup: Callback for initializing the console (Optional) -
exit: Callback for teardown of the console (Optional) -
match: Callback for matching a console (Optional) -
flags: Console flags. See enum cons_flags -
index: Console index, e.g. port number -
cflag: TTY control mode flags -
ispeed: TTY input speed -
ospeed: TTY output speed -
seq: Sequence number of the next ringbuffer record to print -
dropped: Number of unreported dropped ringbuffer records -
data: Driver private data -
node: hlist node for the console list -
write_atomic: NBCON callback to write out text in any context. (Optional)This callback is called with the console already acquired. However, a higher priority context is allowed to take it over by default.
The callback must call
nbcon_enter_unsafe()andnbcon_exit_unsafe()around any code where the takeover is not safe, for example, when manipulating the serial port registers.nbcon_enter_unsafe()will fail if the context has lost the console ownership in the meantime. In this case, the callback is no longer allowed to go forward. It must back out immediately and carefully. The buffer content is also no longer trusted since it no longer belongs to the context.The callback should allow the takeover whenever it is safe. It increases the chance to see messages when the system is in trouble. If the driver must reacquire ownership in order to finalize or revert hardware changes,
nbcon_reacquire_nobuf()can be used. However, on reacquire the buffer content is no longer available. A reacquire cannot be used to resume printing.The callback can be called from any context (including NMI). Therefore it must avoid usage of any locking and instead rely on the console ownership for synchronization.
-
write_thread: NBCON callback to write out text in task context.This callback must be called only in task context with both
device_lock()and the nbcon console acquired with NBCON_PRIO_NORMAL.The same rules for console ownership verification and unsafe sections handling applies as with
write_atomic().The console ownership handling is necessary for synchronization against
write_atomic()which is synchronized only via the context.The
device_lock()provides the primary serialization for operations on the device. It might be as relaxed (mutex)[*] or as tight (disabled preemption and interrupts) as needed. It allows the kthread to operate in the least restrictive mode[**].-
[*] Standalone
nbcon_context_try_acquire()is not safe withthe preemption enabled, see
nbcon_owner_matches(). But it can be safe when always called in the preemptive context under thedevice_lock(). -
[**] The
device_lock()makes sure thatnbcon_context_try_acquire()would never need to spin which is important especially with PREEMPT_RT.
-
-
device_lock: NBCON callback to begin synchronization with driver code.Console drivers typically must deal with access to the hardware via user input/output (such as an interactive login shell) and output of kernel messages via
printk()calls. This callback is called by the printk-subsystem whenever it needs to synchronize with hardware access by the driver. It should be implemented to use whatever synchronization mechanism the driver is using for itself (for example, the port lock for uart serial consoles).The callback is always called from task context. It may use any synchronization method required by the driver.
-
IMPORTANT: The callback MUST disable migration. The console driver
may be using a synchronization mechanism that already takes care of this (such as spinlocks). Otherwise this function must explicitly call
migrate_disable().
The flags argument is provided as a convenience to the driver. It will be passed again to
device_unlock(). It can be ignored if the driver does not need it. -
-
device_unlock: NBCON callback to finish synchronization with driver code.It is the counterpart to
device_lock().This callback is always called from task context. It must appropriately re-enable migration (depending on how
device_lock()disabled migration).The flags argument is the value of the same variable that was passed to
device_lock(). -
nbcon_state: State for nbcon consoles -
nbcon_seq: Sequence number of the next record for nbcon to print -
nbcon_device_ctxt: Context available for non-printing operations -
nbcon_prev_seq: Seq num the previous nbcon owner was assigned to print -
pbufs: Pointer to nbcon private buffer -
kthread: Printer kthread for this console -
rcuwait: RCU-safe wait object for kthread waking -
irq_work: Defer kthread waking to IRQ work context
Internals #
struct nbcon_state #
console state for nbcon consoles
Definition
;
Members
{unnamed_union}: anonymousatom: Compound of the state fields for atomic operations{unnamed_struct}: anonymousprio: The priority of the current ownerreq_prio: The priority of a handover requestunsafe: Console is busy in a non takeover regionunsafe_takeover: A hostile takeover in an unsafe state happened in the past. The console cannot be safe until re-initialized.cpu: The CPU on which the owner runs
Description
To be used for reading and preparing of the value stored in the nbcon state variable console::nbcon_state.
The prio and req_prio fields are particularly important to allow spin-waiting to timeout and give up without the risk of a waiter being assigned the lock after giving up.
enum nbcon_prio #
console owner priority for nbcon consoles
Constants
NBCON_PRIO_NONE: UnusedNBCON_PRIO_NORMAL: Normal (non-emergency) usageNBCON_PRIO_EMERGENCY: Emergency output (WARN/OOPS...)NBCON_PRIO_PANIC: Panic outputNBCON_PRIO_MAX: The number of priority levels
Description
A higher priority context can takeover the console when it is
in the safe state. The final attempt to flush consoles in panic()
can be allowed to do so even in an unsafe state (Hope and pray).
struct nbcon_context #
Context for console acquire/release
Definition
;
Members
console: The associated consolespinwait_max_us: Limit for spin-wait acquireprio: Priority of the contextallow_unsafe_takeover: Allow performing takeover even if unsafe. Can be used only with NBCON_PRIO_PANIC prio. It might cause a system freeze when the console is used later.backlog: Ringbuffer has pending recordspbufs: Pointer to the text buffer for this contextseq: The sequence number to print for this context
struct nbcon_write_context #
Context handed to the nbcon write callbacks
Definition
;
Members
ctxt: The core console contextoutbuf: Pointer to the text buffer for outputlen: Length to writeunsafe_takeover: If a hostile takeover in an unsafe state has occurredcpu: CPU on which the message was generatedpid: PID of the task that generated the messagecomm: Name of the task that generated the message
Struct Consw #
struct consw #
callbacks for consoles
Definition
;
Members
owner: the module to get references of when this console is usedcon_startup: set up the console and return its name (like VGA, EGA, ...)con_init: initialize the console on vc. init is true for the very first call on this vc.con_deinit: deinitialize the console from vc.con_clear: erase count characters at [x, y] on vc. count >= 1.con_putc: emit one character with attributes ca to [x, y] on vc. (optional -- con_putcs would be called instead)con_putcs: emit count characters with attributes s to [x, y] on vc.con_cursor: enable/disable cursor depending on enablecon_scroll: move lines from top to bottom in direction dir by lines. Return true if no generic handling should be done. Invoked by csi_M and printing to the console.con_switch: notifier about the console switch; it is supposed to return true if a redraw is needed.con_blank: blank/unblank the console. The target mode is passed in blank. mode_switch is set if changing from/to text/graphics. The hook is supposed to return true if a redraw is needed.con_font_set: set console vc font to font with height vpitch. flags can beKD_FONT_FLAG_DONT_RECALC. (optional)con_font_get: fetch the current font on vc of height vpitch into font. (optional)con_font_default: set default font on vc. name can beNULLor font name to search for. font can be filled back. (optional)con_resize: resize the vc console to width x height. from_user is true when this change comes from the user space.con_set_palette: sets the palette of the console vc to table (optional)con_scrolldelta: the contents of the console should be scrolled by lines. Invoked by user. (optional)con_set_origin: set origin (seevc_data::vc_origin) of the vc. If not provided or returns false, the origin is set to vc->vc_screenbuf. (optional)con_save_screen: save screen content into vc->vc_screenbuf. Called e.g. upon entering graphics. (optional)con_build_attr: build attributes based on color, intensity and other parameters. The result is used for both normal and erase characters. (optional)con_invert_region: invert a region of length count on vc starting at p. (optional)
Console functions #
console_srcu_read_flags() #
short Locklessly read flags of a possibly registered console
Parameters
const struct console *con: struct console pointer of console to read flags from
Description
Locklessly reading con->flags provides a consistent read value because there is at most one CPU modifying con->flags and that CPU is using only read-modify-write operations to do so.
Requires console_srcu_read_lock to be held, which implies that con might be a registered console. The purpose of holding console_srcu_read_lock is to guarantee that the console state is valid (CON_SUSPENDED/CON_ENABLED) and that no exit/cleanup routines will run if the console is currently undergoing unregistration.
If the caller is holding the console_list_lock or it is certain that con is not and will not become registered, the caller may read con->flags directly instead.
Context
Any context.
Return
The current value of the con->flags field.
console_srcu_write_flags() #
void Write flags for a registered console
Parameters
struct console *con: struct console pointer of console to write flags toshort flags: new flags value to write
Description
Only use this function to write flags for registered consoles. It requires holding the console_list_lock.
Context
Any context.
for_each_console_srcu() #
Iterator over registered consoles
Parameters
con: struct console pointer used as loop cursor
Description
Although SRCU guarantees the console list will be consistent, the struct console fields may be updated by other CPUs while iterating.
Requires console_srcu_read_lock to be held. Can be invoked from any context.
for_each_console() #
Iterator over registered consoles
Parameters
con: struct console pointer used as loop cursor
Description
The console list and the console.flags are immutable while iterating.
Requires console_list_lock to be held.
clear_selection() #
void remove current selection
Parameters
void: no arguments
Description
Remove the current selection highlight, if any from the console holding the selection.
Locking: The caller must hold the console lock.
__vc_resize() #
int resize a VT
Parameters
struct vc_data *vc: virtual consoleunsigned int cols: columnsunsigned int rows: rowsbool from_user: invoked by a user?
Description
Resize a virtual console as seen from the console end of things. We use the
common vc_do_resize() method to update the structures.
Locking: The caller must hold the console sem to protect console internals and vc->port.tty.
con_is_bound() #
int checks if driver is bound to the console
Parameters
const struct consw *csw: console driver
Return
zero if unbound, nonzero if bound
Description
Drivers can call this and if zero, they should release
all resources allocated on consw.con_startup()
con_is_visible() #
bool checks whether the current console is visible
Parameters
const struct vc_data *vc: virtual console
Return
zero if not visible, nonzero if visible
con_debug_enter() #
void prepare the console for the kernel debugger
Parameters
struct vc_data *vc: virtual console
Description
Called when the console is taken over by the kernel debugger, this function needs to save the current console state, then put the console into a state suitable for the kernel debugger.
con_debug_leave() #
void restore console state
Parameters
void: no arguments
Description
Restore the console state to what it was before the kernel debugger was invoked.
do_unregister_con_driver() #
int unregister console driver from console layer
Parameters
const struct consw *csw: console driver
Description
All drivers that registers to the console layer must call this function upon exit, or if the console driver is in a state where it won't be able to handle console services, such as the framebuffer console without loaded framebuffer drivers.
The driver must unbind first prior to unregistration.
Internals #
sel_loadlut() #
int load the LUT table
Parameters
u32 __user *lut: user table
Description
Load the LUT table from user space. Make a temporary copy so a partial update doesn't make a mess.
Locking: The console lock is acquired.
set_selection_user() #
int set the current selection.
Parameters
const struct tiocl_selection __user *sel: user selection infostruct tty_struct *tty: the console tty
Description
Invoked by the ioctl handle for the vt layer.
Locking: The entire selection process is managed under the console_lock. It's a lot under the lock but its hardly a performance path.
vc_do_resize() #
int resizing method for the tty
Parameters
struct tty_struct *tty: tty being resizedstruct vc_data *vc: virtual console private dataunsigned int cols: columnsunsigned int lines: linesbool from_user: invoked by a user?
Description
Resize a virtual console, clipping according to the actual constraints. If the caller passes a tty structure then update the termios winsize information and perform any necessary signal handling.
Locking: Caller must hold the console semaphore. Takes the termios rwsem and ctrl.lock of the tty IFF a tty is passed.
vt_resize() #
int resize a VT
Parameters
struct tty_struct *tty: tty to resizestruct winsize *ws: winsize attributes
Description
Resize a virtual terminal. This is called by the tty layer as we register our own handler for resizing. The mutual helper does all the actual work.
Locking: Takes the console sem and the called methods then take the tty termios_rwsem and the tty ctrl.lock in that order.
enum vc_ctl_state #
control characters state of a vt
Constants
ESnormal: initial state, no control characters parsedESesc: ESC parsedESsquare: CSI parsed -- modifiers/parameters/ctrl chars expectedESgetpars: CSI parsed -- parameters/ctrl chars expectedESfunckey: CSI [ parsedEShash: ESC # parsedESsetG0: ESC ( parsedESsetG1: ESC ) parsedESpercent: ESC % parsedEScsiignore: CSI [0x20-0x3f] parsedESnonstd: OSC parsedESpalette: OSC P parsedESosc: OSC [0-9] parsedESANSI_first: first state for ignoring ansi control sequencesESapc: ESC _ parsedESpm: ESC ^ parsedESdcs: ESC P parsedESANSI_last: last state for ignoring ansi control sequences
vc_sanitize_unicode() #
int Replace invalid Unicode code points with U+FFFD
Parameters
const int c: the received code point
vc_translate_unicode() #
int Combine UTF-8 into Unicode in vc_data.vc_utf_char
Parameters
struct vc_data *vc: virtual consoleint c: UTF-8 byte to translatebool *rescan: set to true iff c wasn't consumed here and needs to be re-processed
Description
vc_data.vc_utf_charis the being-constructed Unicode code point.vc_data.vc_utf_countis the number of continuation bytes still expected to arrive.vc_data.vc_nparis the number of continuation bytes arrived so far.
Return
-1- Input OK so far, c consumed, further bytes expected.0xFFFD- Possibility 1: input invalid, c may have been consumed (see desc. of rescan). Possibility 2: input OK, c consumed,U+FFFDis the resulting code point.U+FFFDis valid,REPLACEMENT CHARACTER.- otherwise - Input OK, c consumed, resulting code point returned.
vt_kmsg_redirect() #
int sets/gets the kernel message console
Parameters
int new: the new virtual terminal number or -1 if the console should stay unchanged
Description
By default, the kernel messages are always printed on the current virtual
console. However, the user may modify that default with the
TIOCL_SETKMSGREDIRECT ioctl call.
This function sets the kernel message console to be new. It returns the old
virtual console number. The virtual terminal number 0 (both as parameter and
return value) means no redirection (i.e. always printed on the currently
active console).
The parameter -1 means that only the current console is returned, but the
value is not modified. You may use the macro vt_get_kmsg_redirect() in that
case to make the code more understandable.
When the kernel is compiled without CONFIG_VT_CONSOLE, this function ignores
the parameter and always returns 0.
MOXA Smartio/Industio Family Device Driver Installation Guide
Peios Kernel / Hardware and drivers / Driver development / TTY
Copyright (C) 2008, Moxa Inc. Copyright (C) 2021, Jiri Slaby
1. Introduction #
The Smartio/Industio/UPCI family Linux driver supports following multiport boards:
2 ports multiport board
CP-102U, CP-102UL, CP-102UF CP-132U-I, CP-132UL, CP-132, CP-132I, CP132S, CP-132IS, (CP-102, CP-102S)
4 ports multiport board
CP-104EL, CP-104UL, CP-104JU, CP-134U, CP-134U-I, C104H/PCI, C104HS/PCI, CP-114, CP-114I, CP-114S, CP-114IS, CP-114UL, (C114HI, CT-114I), POS-104UL, CB-114, CB-134I
8 ports multiport board
CP-118EL, CP-168EL, CP-118U, CP-168U, C168H/PCI, CB-108
If a compatibility problem occurs, please contact Moxa at support@moxa.com.tw.
In addition to device driver, useful utilities are also provided in this version. They are:
msdiag
Diagnostic program for displaying installed Moxa Smartio/Industio boards.
msmon
Monitor program to observe data count and line status signals.
msterm A simple terminal program which is useful in testing serial
ports.
All the drivers and utilities are published in form of source code under GNU General Public License in this version. Please refer to GNU General Public License announcement in each source code file for more detail.
In Moxa's Web sites, you may always find the latest driver at https://www.moxa.com/.
This version of driver can be installed as a Loadable Module (Module driver) or built-in into kernel (Static driver). Before you install the driver, please refer to hardware installation procedure in the User's Manual.
We assume the user should be familiar with following documents:
Serial-HOWTO
Kernel-HOWTO
2. System Requirement #
- Maximum 4 boards can be installed in combination
3. Installation #
3.1 Hardware installation #
PCI/UPCI board #
You may need to adjust IRQ usage in BIOS to avoid IRQ conflict with other ISA devices. Please refer to hardware installation procedure in User's Manual in advance.
PCI IRQ Sharing #
Each port within the same multiport board shares the same IRQ. Up to 4 Moxa Smartio/Industio PCI Family multiport boards can be installed together on one system and they can share the same IRQ.
3.2 Device naming convention #
The device node is named "ttyMxx".
Device naming when more than 2 boards installed #
Naming convention for each Smartio/Industio multiport board is pre-defined as below.
Board Num.
Device node
1st board
ttyM0 - ttyM7
2nd board
ttyM8 - ttyM15
3rd board
ttyM16 - ttyM23
4th board
ttyM24 - ttyM31
4. Utilities #
There are 3 utilities contained in this driver. They are msdiag, msmon and msterm. These 3 utilities are released in form of source code. They should be compiled into executable file and copied into /usr/bin.
msdiag - Diagnostic #
This utility provides the function to display what Moxa Smartio/Industio board was found by the driver in the system.
msmon - Port Monitoring #
This utility gives the user a quick view about all the MOXA ports' activities. One can easily learn each port's total received/transmitted (Rx/Tx) character count since the time when the monitoring is started.
Rx/Tx throughputs per second are also reported in interval basis (e.g. the last 5 seconds) and in average basis (since the time the monitoring is started). You can reset all ports' count by <HOME> key. <+> <-> (plus/minus) keys to change the displaying time interval. Press <ENTER> on the port, that cursor stay, to view the port's communication parameters, signal status, and input/output queue.
msterm - Terminal Emulation #
This utility provides data sending and receiving ability of all tty ports, especially for MOXA ports. It is quite useful for testing simple application, for example, sending AT command to a modem connected to the port or used as a terminal for login purpose. Note that this is only a dumb terminal emulation without handling full screen operation.
5. Setserial #
Supported Setserial parameters are listed as below.
uart
set UART type(16450 --> disable FIFO, 16550A --> enable FIFO)
close_delay
set the amount of time (in 1/100 of a second) that DTR should be kept low while being closed.
closing_wait
set the amount of time (in 1/100 of a second) that the serial port should wait for data to be drained while being closed, before the receiver is disabled.
spd_hi
Use 57.6kb when the application requests 38.4kb.
spd_vhi
Use 115.2kb when the application requests 38.4kb.
spd_shi
Use 230.4kb when the application requests 38.4kb.
spd_warp
Use 460.8kb when the application requests 38.4kb.
spd_normal
Use 38.4kb when the application requests 38.4kb.
spd_cust
Use the custom divisor to set the speed when the application requests 38.4kb.
divisor
This option sets the custom division.
baud_base
This option sets the base baud rate.
6. Troubleshooting #
The boot time error messages and solutions are stated as clearly as possible. If all the possible solutions fail, please contact our technical support team to get more help.
Error msg:
More than 4 Moxa Smartio/Industio family boards found. Fifth board and after are ignored.
Solution: To avoid this problem, please unplug fifth and after board, because Moxa driver supports up to 4 boards.
GSM 0710 tty multiplexor HOWTO
Peios Kernel / Hardware and drivers / Driver development / TTY
This line discipline implements the GSM 07.10 multiplexing protocol detailed in the following 3GPP document:
https://www.3gpp.org/ftp/Specs/archive/07_series/07.10/0710-720.zip
This document give some hints on how to use this driver with GPRS and 3G modems connected to a physical serial port.
How to use it #
Config Initiator #
-
Initialize the modem in 0710 mux mode (usually
AT+CMUX=command) through its serial port. Depending on the modem used, you can pass more or less parameters to this command. -
Switch the serial line to using the n_gsm line discipline by using
TIOCSETDioctl. -
Configure the mux using
GSMIOC_GETCONF_EXT/GSMIOC_SETCONF_EXTioctl if needed. -
Configure the mux using
GSMIOC_GETCONF/GSMIOC_SETCONFioctl. -
Configure DLCs using
GSMIOC_GETCONF_DLCI/GSMIOC_SETCONF_DLCIioctl for non-defaults. -
Obtain base gsmtty number for the used serial port.
Major parts of the initialization program (a good starting point is util-linux-ng/sys-utils/ldattach.c):
#include <stdio.h> #include <stdint.h> #include <linux/gsmmux.h> #include <linux/tty.h> #define DEFAULT_SPEED B115200 #define SERIAL_PORT /dev/ttyS0 int ldisc = N_GSM0710; struct gsm_config c; struct gsm_config_ext ce; struct gsm_dlci_config dc; struct termios configuration; uint32_t first; /* open the serial port connected to the modem */ fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY); /* configure the serial port : speed, flow control ... */ /* send the AT commands to switch the modem to CMUX mode and check that it's successful (should return OK) */ write(fd, "AT+CMUX=0\r", 10); /* experience showed that some modems need some time before being able to answer to the first MUX packet so a delay may be needed here in some case */ sleep(3); /* use n_gsm line discipline */ ioctl(fd, TIOCSETD, &ldisc); /* get n_gsm extended configuration */ ioctl(fd, GSMIOC_GETCONF_EXT, &ce); /* use keep-alive once every 5s for modem connection supervision */ ce.keep_alive = 500; /* set the new extended configuration */ ioctl(fd, GSMIOC_SETCONF_EXT, &ce); /* get n_gsm configuration */ ioctl(fd, GSMIOC_GETCONF, &c); /* we are initiator and need encoding 0 (basic) */ c.initiator = 1; c.encapsulation = 0; /* our modem defaults to a maximum size of 127 bytes */ c.mru = 127; c.mtu = 127; /* set the new configuration */ ioctl(fd, GSMIOC_SETCONF, &c); /* get DLC 1 configuration */ dc.channel = 1; ioctl(fd, GSMIOC_GETCONF_DLCI, &dc); /* the first user channel gets a higher priority */ dc.priority = 1; /* set the new DLC 1 specific configuration */ ioctl(fd, GSMIOC_SETCONF_DLCI, &dc); /* get first gsmtty device node */ ioctl(fd, GSMIOC_GETFIRST, &first); printf("first muxed line: /dev/gsmtty%i\n", first); /* and wait for ever to keep the line discipline enabled */ daemon(0,0); pause(); -
Use these devices as plain serial ports.
For example, it's possible:
-
to use gnokii to send / receive SMS on
ttygsm1 -
to use ppp to establish a datalink on
ttygsm2
-
-
First close all virtual ports before closing the physical port.
Note that after closing the physical port the modem is still in multiplexing mode. This may prevent a successful re-opening of the port later. To avoid this situation either reset the modem if your hardware allows that or send a disconnect command frame manually before initializing the multiplexing mode for the second time. The byte sequence for the disconnect command frame is:
0xf9, 0x03, 0xef, 0x03, 0xc3, 0x16, 0xf9
Config Requester #
-
Receive
AT+CMUX=command through its serial port, initialize mux mode config. -
Switch the serial line to using the n_gsm line discipline by using
TIOCSETDioctl. -
Configure the mux using
GSMIOC_GETCONF_EXT/GSMIOC_SETCONF_EXTioctl if needed. -
Configure the mux using
GSMIOC_GETCONF/GSMIOC_SETCONFioctl. -
Configure DLCs using
GSMIOC_GETCONF_DLCI/GSMIOC_SETCONF_DLCIioctl for non-defaults. -
Obtain base gsmtty number for the used serial port:
#include <stdio.h> #include <stdint.h> #include <linux/gsmmux.h> #include <linux/tty.h> #define DEFAULT_SPEED B115200 #define SERIAL_PORT /dev/ttyS0 int ldisc = N_GSM0710; struct gsm_config c; struct gsm_config_ext ce; struct gsm_dlci_config dc; struct termios configuration; uint32_t first; /* open the serial port */ fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY); /* configure the serial port : speed, flow control ... */ /* get serial data and check "AT+CMUX=command" parameter ... */ /* use n_gsm line discipline */ ioctl(fd, TIOCSETD, &ldisc); /* get n_gsm extended configuration */ ioctl(fd, GSMIOC_GETCONF_EXT, &ce); /* use keep-alive once every 5s for peer connection supervision */ ce.keep_alive = 500; /* set the new extended configuration */ ioctl(fd, GSMIOC_SETCONF_EXT, &ce); /* get n_gsm configuration */ ioctl(fd, GSMIOC_GETCONF, &c); /* we are requester and need encoding 0 (basic) */ c.initiator = 0; c.encapsulation = 0; /* our modem defaults to a maximum size of 127 bytes */ c.mru = 127; c.mtu = 127; /* set the new configuration */ ioctl(fd, GSMIOC_SETCONF, &c); /* get DLC 1 configuration */ dc.channel = 1; ioctl(fd, GSMIOC_GETCONF_DLCI, &dc); /* the first user channel gets a higher priority */ dc.priority = 1; /* set the new DLC 1 specific configuration */ ioctl(fd, GSMIOC_SETCONF_DLCI, &dc); /* get first gsmtty device node */ ioctl(fd, GSMIOC_GETFIRST, &first); printf("first muxed line: /dev/gsmtty%i\n", first); /* and wait for ever to keep the line discipline enabled */ daemon(0,0); pause();
11-03-08 - Eric Bénard - <eric@eukrea.com>
N_TTY
Peios Kernel / Hardware and drivers / Driver development / TTY
The default (and fallback) TTY line discipline. It tries to handle characters as per POSIX.
External Functions #
n_tty_inherit_ops() #
void inherit N_TTY methods
Parameters
struct tty_ldisc_ops *ops: struct tty_ldisc_ops where to save N_TTY methods
Description
Enables a 'subclass' line discipline to 'inherit' N_TTY methods.
Internal Functions #
n_tty_kick_worker() #
void start input worker (if required)
Parameters
const struct tty_struct *tty: terminal
Description
Re-schedules the flip buffer work if it may have stopped.
- Locking:
- Caller holds exclusive
termios_rwsem, or n_tty_read()/consumer path: holds non-exclusivetermios_rwsem
- Caller holds exclusive
n_tty_write_wakeup() #
void asynchronous I/O notifier
Parameters
struct tty_struct *tty: tty device
Description
Required for the ptys, serial driver etc. since processes that attach themselves to the master and rely on ASYNC IO must be woken up.
put_tty_queue() #
void add character to tty
Parameters
u8 c: characterstruct n_tty_data *ldata: n_tty data
Description
Add a character to the tty read_buf queue.
- Locking:
n_tty_receive_buf()/producer path: caller holds non-exclusivetermios_rwsem
reset_buffer_flags() #
void reset buffer state
Parameters
struct n_tty_data *ldata: line disc data to reset
Description
Reset the read buffer counters and clear the flags. Called from
n_tty_open() and n_tty_flush_buffer().
- Locking:
- caller holds exclusive
termios_rwsem, or - (locking is not required)
- caller holds exclusive
n_tty_flush_buffer() #
void clean input queue
Parameters
struct tty_struct *tty: terminal device
Description
Flush the input buffer. Called when the tty layer wants the buffer flushed
(eg at hangup) or when the N_TTY line discipline internally has to clean
the pending queue (for example some signals).
Holds termios_rwsem to exclude producer/consumer while buffer indices are
reset.
Locking: ctrl.lock, exclusive termios_rwsem
is_utf8_continuation() #
int utf8 multibyte check
Parameters
u8 c: byte to check
Return
true if the utf8 character c is a multibyte continuation character. We use this to correctly compute the on-screen size of the character when printing.
is_continuation() #
int multibyte check
Parameters
u8 c: byte to checkconst struct tty_struct *tty: terminal device
Return
true if the utf8 character c is a multibyte continuation character and the terminal is in unicode mode.
do_output_char() #
int output one character
Parameters
u8 c: character (or partial unicode symbol)struct tty_struct *tty: terminal deviceint space: space available in tty driver write buffer
Description
This is a helper function that handles one output character (including special characters like TAB, CR, LF, etc.), doing OPOST processing and putting the results in the tty driver's write buffer.
Note that Linux currently ignores TABDLY, CRDLY, VTDLY, FFDLY and NLDLY. They simply aren't relevant in the world today. If you ever need them, add them here.
Locking: should be called under the output_lock to protect the column state
and space left in the buffer.
Return
the number of bytes of buffer space used or -1 if no space left.
process_output() #
int output post processor
Parameters
u8 c: character (or partial unicode symbol)struct tty_struct *tty: terminal device
Description
Output one character with OPOST processing.
Locking: output_lock to protect column state and space left (also, this is
called from n_tty_write() under the tty layer write lock).
Return
-1 when the output device is full and the character must be retried.
process_output_block() #
ssize_t block post processor
Parameters
struct tty_struct *tty: terminal deviceconst u8 *buf: character bufferunsigned int nr: number of bytes to output
Description
Output a block of characters with OPOST processing.
This path is used to speed up block console writes, among other things when processing blocks of output data. It handles only the simple cases normally found and helps to generate blocks of symbols for the console driver and thus improve performance.
Locking: output_lock to protect column state and space left (also, this is
called from n_tty_write() under the tty layer write lock).
Return
the number of characters output.
__process_echoes() #
size_t write pending echo characters
Parameters
struct tty_struct *tty: terminal device
Description
Write previously buffered echo (and other ldisc-generated) characters to the tty.
Characters generated by the ldisc (including echoes) need to be buffered because the driver's write buffer can fill during heavy program output. Echoing straight to the driver will often fail under these conditions, causing lost characters and resulting mismatches of ldisc state information.
Since the ldisc state must represent the characters actually sent to the driver at the time of the write, operations like certain changes in column state are also saved in the buffer and executed here.
A circular fifo buffer is used so that the most recent characters are prioritized. Also, when control characters are echoed with a prefixed "^", the pair is treated atomically and thus not separated.
Locking: callers must hold output_lock.
add_echo_byte() #
void add a byte to the echo buffer
Parameters
u8 c: unicode byte to echostruct n_tty_data *ldata: n_tty data
Description
Add a character or operation byte to the echo buffer.
echo_move_back_col() #
void add operation to move back a column
Parameters
struct n_tty_data *ldata: n_tty data
Description
Add an operation to the echo buffer to move back one column.
echo_set_canon_col() #
void add operation to set the canon column
Parameters
struct n_tty_data *ldata: n_tty data
Description
Add an operation to the echo buffer to set the canon column to the current column.
echo_erase_tab() #
void add operation to erase a tab
Parameters
unsigned int num_chars: number of character columns already usedint after_tab: true if num_chars starts after a previous tabstruct n_tty_data *ldata: n_tty data
Description
Add an operation to the echo buffer to erase a tab.
Called by the eraser function, which knows how many character columns have been used since either a previous tab or the start of input. This information will be used later, along with canon column (if applicable), to go back the correct number of columns.
echo_char_raw() #
void echo a character raw
Parameters
u8 c: unicode byte to echostruct n_tty_data *ldata: line disc data
Description
Echo user input back onto the screen. This must be called only when
L_ECHO(tty) is true. Called from the tty_driver.receive_buf() path.
This variant does not treat control characters specially.
echo_char() #
void echo a character
Parameters
u8 c: unicode byte to echoconst struct tty_struct *tty: terminal device
Description
Echo user input back onto the screen. This must be called only when
L_ECHO(tty) is true. Called from the tty_driver.receive_buf() path.
This variant tags control characters to be echoed as "^X" (where X is the letter representing the control char).
finish_erasing() #
void complete erase
Parameters
struct n_tty_data *ldata: n_tty data
eraser() #
void handle erase function
Parameters
u8 c: character inputconst struct tty_struct *tty: terminal device
Description
Perform erase and necessary output when an erase character is present in the stream from the driver layer. Handles the complexities of UTF-8 multibyte symbols.
- Locking:
n_tty_receive_buf()/producer path: caller holds non-exclusivetermios_rwsem
isig() #
void handle the ISIG optio
Parameters
int sig: signalstruct tty_struct *tty: terminal
Description
Called when a signal is being sent due to terminal input. Called from the
tty_driver.receive_buf() path, so serialized.
Performs input and output flush if !NOFLSH. In this context, the echo buffer is 'output'. The signal is processed first to alert any current readers or writers to discontinue and exit their i/o loops.
Locking: ctrl.lock
n_tty_receive_break() #
void handle break
Parameters
struct tty_struct *tty: terminal
Description
An RS232 break event has been hit in the incoming bitstream. This can cause a variety of events depending upon the termios settings.
- Locking:
n_tty_receive_buf()/producer path: caller holds non-exclusive termios_rwsem
Note
may get exclusive termios_rwsem if flushing input buffer
n_tty_receive_overrun() #
void handle overrun reporting
Parameters
const struct tty_struct *tty: terminal
Description
Data arrived faster than we could process it. While the tty driver has flagged this the bits that were missed are gone forever.
Called from the receive_buf path so single threaded. Does not need locking as num_overrun and overrun_time are function private.
n_tty_receive_parity_error() #
void error notifier
Parameters
const struct tty_struct *tty: terminal deviceu8 c: character
Description
Process a parity error and queue the right data to indicate the error case if necessary.
- Locking:
n_tty_receive_buf()/producer path: caller holds non-exclusivetermios_rwsem
n_tty_receive_char_flow_ctrl() #
bool receive flow control chars
Parameters
struct tty_struct *tty: terminal deviceu8 c: characterbool lookahead_done: lookahead has processed this character already
Description
Receive and process flow control character actions.
In case lookahead for flow control chars already handled the character in advance to the normal receive, the actions are skipped during normal receive.
Returns true if c is consumed as flow-control character, the character must not be treated as normal character.
n_tty_receive_char() #
void perform processing
Parameters
struct tty_struct *tty: terminal deviceu8 c: character
Description
Process an individual character of input received from the driver. This is serialized with respect to itself by the rules for the driver above.
- Locking:
n_tty_receive_buf()/producer path: caller holds non-exclusivetermios_rwsempublishes canon_head if canonical mode is active
n_tty_receive_buf_common() #
size_t process input
Parameters
struct tty_struct *tty: device to receive inputconst u8 *cp: input charsconst u8 *fp: flags for each char (ifNULL, all chars areTTY_NORMAL)size_t count: number of input chars in cpbool flow: enable flow control
Description
Called by the terminal driver when a block of characters has been received.
This function must be called from soft contexts not from interrupt context.
The driver is responsible for making calls one at a time and in order (or
using flush_to_ldisc()).
In canonical mode, the maximum line length is 4096 chars (including the line termination char); lines longer than 4096 chars are truncated. After 4095 chars, input data is still processed but not stored. Overflow processing ensures the tty can always receive more input until at least one line can be read.
In non-canonical mode, the read buffer will only accept 4095 chars; this provides the necessary space for a newline char if the input mode is switched to canonical.
Note it is possible for the read buffer to contain 4096 chars in non-canonical mode: the read buffer could already contain the maximum canon line of 4096 chars when the mode is switched to non-canonical.
- Locking:
n_tty_receive_buf()/producer path: claims non-exclusivetermios_rwsempublishes commit_head or canon_head
Return
the # of input chars from cp which were processed.
n_tty_set_termios() #
void termios data changed
Parameters
struct tty_struct *tty: terminalconst struct ktermios *old: previous data
Description
Called by the tty layer when the user changes termios flags so that the line discipline can plan ahead. This function cannot sleep and is protected from re-entry by the tty layer. The user is guaranteed that this function will not be re-entered or in progress when the ldisc is closed.
Locking: Caller holds tty->termios_rwsem
n_tty_close() #
void close the ldisc for this tty
Parameters
struct tty_struct *tty: device
Description
Called from the terminal layer when this line discipline is being shut down, either because of a close or becsuse of a discipline change. The function will not be called while other ldisc methods are in progress.
n_tty_open() #
int open an ldisc
Parameters
struct tty_struct *tty: terminal to open
Description
Called when this line discipline is being attached to the terminal device. Can sleep. Called serialized so that no other events will occur in parallel. No further open will occur until a close.
copy_from_read_buf() #
bool copy read data directly
Parameters
const struct tty_struct *tty: terminal deviceu8 **kbp: datasize_t *nr: size of data
Description
Helper function to speed up n_tty_read(). It is only called when ICANON is
off; it copies characters straight from the tty queue.
- Locking:
- called under the ldata->atomic_read_lock sem
n_tty_read()/consumer path: caller holds non-exclusivetermios_rwsem; read_tail published
Return
true if it successfully copied data, but there is still more data to be had.
canon_copy_from_read_buf() #
bool copy read data in canonical mode
Parameters
const struct tty_struct *tty: terminal deviceu8 **kbp: datasize_t *nr: size of data
Description
Helper function for n_tty_read(). It is only called when ICANON is on; it
copies one line of input up to and including the line-delimiting character
into the result buffer.
Note
When termios is changed from non-canonical to canonical mode and the
read buffer contains data, n_tty_set_termios() simulates an EOF push (as if
C-d were input) without the DISABLED_CHAR in the buffer. This causes data
already processed as input to be immediately available as input although a
newline has not been received.
- Locking:
- called under the
atomic_read_lockmutex n_tty_read()/consumer path: caller holds non-exclusivetermios_rwsem; read_tail published
- called under the
job_control() #
int check job control
Parameters
struct tty_struct *tty: ttystruct file *file: file handle
Description
Perform job control management checks on this file/tty descriptor and if appropriate send any needed signals and return a negative error code if action should be taken.
- Locking:
- redirected write test is safe
- current->signal->tty check is safe
- ctrl.lock to safely reference tty->ctrl.pgrp
n_tty_read() #
ssize_t read function for tty
Parameters
struct tty_struct *tty: tty devicestruct file *file: file objectu8 *kbuf: kernelspace buffer pointersize_t nr: size of I/Ovoid **cookie: if non-NULL, this is a continuation readunsigned long offset: where to continue reading from (unused in n_tty)
Description
Perform reads for the line discipline. We are guaranteed that the line discipline will not be closed under us but we may get multiple parallel readers and must handle this ourselves. We may also get a hangup. Always called in user context, may sleep.
This code must be sure never to sleep through a hangup.
- Locking:
n_tty_read()/consumer path: claims non-exclusive termios_rwsem; publishes read_tail
n_tty_write() #
ssize_t write function for tty
Parameters
struct tty_struct *tty: tty devicestruct file *file: file objectconst u8 *buf: userspace buffer pointersize_t nr: size of I/O
Description
Write function of the terminal device. This is serialized with respect to
other write callers but not to termios changes, reads and other such events.
Since the receive code will echo characters, thus calling driver write
methods, the output_lock is used in the output processing functions called
here as well as in the echo processing function to protect the column state
and space left in the buffer.
This code must be sure never to sleep through a hangup.
-
Locking: output_lock to protect column state and space left
(note that the process_output*() functions take this lock themselves)
n_tty_poll() #
__poll_t poll method for N_TTY
Parameters
struct tty_struct *tty: terminal devicestruct file *file: file accessing itpoll_table *wait: poll table
Description
Called when the line discipline is asked to poll() for data or for special
events. This code is not serialized with respect to other events save
open/close.
This code must be sure never to sleep through a hangup.
Locking: called without the kernel lock held -- fine.
TTY Buffer
Peios Kernel / Hardware and drivers / Driver development / TTY
Here, we document functions for taking care of tty buffer and their flipping. Drivers are supposed to fill the buffer by one of those functions below and then flip the buffer, so that the data are passed to line discipline for further processing.
Flip Buffer Management #
tty_prepare_flip_string() #
size_t make room for characters
Parameters
struct tty_port *port: tty portu8 **chars: return pointer for character write areasize_t size: desired size
Description
Prepare a block of space in the buffer for data.
This is used for drivers that need their own block copy routines into the buffer. There is no guarantee the buffer is a DMA target!
Return
the length available and buffer pointer (chars) to the space which is now allocated and accounted for as ready for normal characters.
tty_ldisc_receive_buf() #
size_t forward data to line discipline
Parameters
struct tty_ldisc *ld: line discipline to process inputconst u8 *p: char bufferconst u8 *f:TTY_NORMAL,TTY_BREAK, etc. flags buffersize_t count: number of bytes to process
Description
Callers other than flush_to_ldisc() need to exclude the kworker from
concurrent use of the line discipline, see paste_selection().
Return
the number of bytes processed.
tty_flip_buffer_push() #
void push terminal buffers
Parameters
struct tty_port *port: tty port to push
Description
Queue a push of the terminal flip buffers to the line discipline. Can be called from IRQ/atomic context.
In the event of the queue being busy for flipping the work will be held off and retried later.
tty_insert_flip_string_fixed_flag() #
size_t add characters to the tty buffer
Parameters
struct tty_port *port: tty portconst u8 *chars: charactersu8 flag: flag value for each charactersize_t size: size
Description
Queue a series of bytes to the tty buffering. All the characters passed are marked with the supplied flag.
Return
the number added.
tty_insert_flip_string_flags() #
size_t add characters to the tty buffer
Parameters
struct tty_port *port: tty portconst u8 *chars: charactersconst u8 *flags: flag bytessize_t size: size
Description
Queue a series of bytes to the tty buffering. For each character the flags array indicates the status of the character.
Return
the number added.
tty_insert_flip_char() #
size_t add one character to the tty buffer
Parameters
struct tty_port *port: tty portu8 ch: characteru8 flag: flag byte
Description
Queue a single byte ch to the tty buffering, with an optional flag.
Other Functions #
tty_buffer_space_avail() #
unsigned int return unused buffer space
Parameters
struct tty_port *port: tty port owning the flip buffer
Return
the # of bytes which can be written by the driver without reaching the buffer limit.
Note
this does not guarantee that memory is available to write the returned
# of bytes (use tty_prepare_flip_string() to pre-allocate if memory
guarantee is required).
tty_buffer_set_limit() #
int change the tty buffer memory limit
Parameters
struct tty_port *port: tty port to changeint limit: memory limit to set
Description
Change the tty buffer memory limit.
Must be called before the other tty buffer functions are used.
Buffer Locking #
These are used only in special circumstances. Avoid them.
tty_buffer_lock_exclusive() #
void gain exclusive access to buffer
Parameters
struct tty_port *port: tty port owning the flip buffer
Description
Guarantees safe use of the tty_ldisc_ops.receive_buf() method by excluding
the buffer work and any pending flush from using the flip buffer. Data can
continue to be added concurrently to the flip buffer from the driver side.
See also tty_buffer_unlock_exclusive().
tty_buffer_unlock_exclusive() #
void release exclusive access
Parameters
struct tty_port *port: tty port owning the flip buffer
Description
The buffer work is restarted if there is data in the flip buffer.
See also tty_buffer_lock_exclusive().
Internal Functions #
tty_buffer_free_all() #
void free buffers used by a tty
Parameters
struct tty_port *port: tty port to free from
Description
Remove all the buffers pending on a tty whether queued with data or in the free ring. Must be called when the tty is no longer in use.
tty_buffer_alloc() #
struct tty_buffer * allocate a tty buffer
Parameters
struct tty_port *port: tty portsize_t size: desired size (characters)
Description
Allocate a new tty buffer to hold the desired number of characters. We round our buffers off in 256 character chunks to get better allocation behaviour.
Return
NULL if out of memory or the allocation would exceed the per
device queue.
tty_buffer_free() #
void free a tty buffer
Parameters
struct tty_port *port: tty port owning the bufferstruct tty_buffer *b: the buffer to free
Description
Free a tty buffer, or add it to the free list according to our internal strategy.
tty_buffer_flush() #
void flush full tty buffers
Parameters
struct tty_struct *tty: tty to flushstruct tty_ldisc *ld: optional ldisc ptr (must be referenced)
Description
Flush all the buffers containing receive data. If ld != NULL, flush the
ldisc input buffer.
Locking: takes buffer lock to ensure single-threaded flip buffer 'consumer'.
__tty_buffer_request_room() #
int grow tty buffer if needed
Parameters
struct tty_port *port: tty portsize_t size: size desiredbool flags: buffer has to store flags along character data
Description
Make at least size bytes of linear space available for the tty buffer.
Will change over to a new buffer if the current buffer is encoded as
TTY_NORMAL (so has no flags buffer) and the new buffer requires a flags
buffer.
Return
the size we managed to find.
flush_to_ldisc() #
void flush data from buffer to ldisc
Parameters
struct work_struct *work: tty structure passed from work queue.
Description
This routine is called out of the software interrupt to flush data from the buffer chain to the line discipline.
The receive_buf() method is single threaded for each tty instance.
Locking: takes buffer lock to ensure single-threaded flip buffer 'consumer'.
tty_insert_flip_string_and_push_buffer() #
int add characters to the tty buffer and push
Parameters
struct tty_port *port: tty portconst u8 *chars: characterssize_t size: size
Description
The function combines tty_insert_flip_string() and tty_flip_buffer_push()
with the exception of properly holding the port->lock.
To be used only internally (by pty currently).
Return
the number added.
tty_buffer_init() #
void prepare a tty buffer structure
Parameters
struct tty_port *port: tty port to initialise
Description
Set up the initial state of the buffer management for a tty device. Must be called before the other tty buffer functions are used.
TTY Driver and TTY Operations
Peios Kernel / Hardware and drivers / Driver development / TTY
Allocation #
The first thing a driver needs to do is to allocate a struct tty_driver. This is done by tty_alloc_driver() (or __tty_alloc_driver()). Next, the newly allocated structure is filled with information. See TTY Driver Reference at the end of this document on what actually shall be filled in.
The allocation routines expect a number of devices the driver can handle at most and flags. Flags are those starting TTY_DRIVER_ listed and described in TTY Driver Flags below.
When the driver is about to be freed, tty_driver_kref_put() is called on that. It will decrements the reference count and if it reaches zero, the driver is freed.
For reference, both allocation and deallocation functions are explained here in detail:
tty_alloc_driver() #
allocate tty driver
Parameters
lines: count of lines this driver can handle at mostflags: some of enum tty_driver_flag, will be set in driver->flags
Return
struct tty_driver or a PTR-encoded error (use IS_ERR() and friends).
__tty_alloc_driver() #
struct tty_driver * allocate tty driver
Parameters
unsigned int lines: count of lines this driver can handle at moststruct module *owner: module which is responsible for this driverunsigned long flags: some of enum tty_driver_flag, will be set in driver->flags
Description
This should not be called directly, tty_alloc_driver() should be used
instead.
Return
struct tty_driver or a PTR-encoded error (use IS_ERR() and friends).
tty_driver_kref_put() #
void drop a reference to a tty driver
Parameters
struct tty_driver *driver: driver of which to drop the reference
Description
The final put will destroy and free up the driver.
TTY Driver Flags #
Here comes the documentation of flags accepted by tty_alloc_driver() (or __tty_alloc_driver()):
enum tty_driver_flag #
- TTY Driver Flags
Constants
TTY_DRIVER_INSTALLED: Whether this driver was succesfully installed. This is a tty internal flag. Do not touch.TTY_DRIVER_RESET_TERMIOS: Requests the tty layer to reset the termios setting when the last process has closed the device. Used for PTYs, in particular.TTY_DRIVER_REAL_RAW: Indicates that the driver will guarantee not to set any special character handling flags if this is set for the tty:TTY_DRIVER_DYNAMIC_DEV: The individual tty devices need to be registered with a call totty_register_device()when the device is found in the system and unregistered with a call totty_unregister_device()so the devices will be show up properly in sysfs. If not set, alltty_driver.numentries will be created by the tty core in sysfs whentty_register_driver()is called. This is to be used by drivers that have tty devices that can appear and disappear while the main tty driver is registered with the tty core.TTY_DRIVER_DEVPTS_MEM: Don't use the standard arrays (tty_driver.ttysandtty_driver.termios), instead use dynamic memory keyed through the devpts filesystem. This is only applicable to the PTY driver.TTY_DRIVER_HARDWARE_BREAK: Hardware handles break signals. Pass the requested timeout to thetty_operations.break_ctlinstead of using a simple on/off interface.TTY_DRIVER_DYNAMIC_ALLOC: Do not allocate structures which are needed per line for this driver (tty_driver.ports) as it would waste memory. The driver will take care. This is only applicable to the PTY driver.TTY_DRIVER_UNNUMBERED_NODE: Do not create numbered/devnodes. For example, create/dev/ttyprintkand not/dev/ttyprintk0. Applicable only when a driver for a single tty device is being allocated.
Description
These are flags passed to tty_alloc_driver().
(IGNBRK || (!BRKINT && !PARMRK)) && (IGNPAR || !INPCK)
That is, if there is no reason for the driver to send notifications of parity and break characters up to the line driver, it won't do so. This allows the line driver to optimize for this case if this flag is set. (Note that there is also a promise, if the above case is true, not to signal overruns, either.)
Registration #
When a struct tty_driver is allocated and filled in, it can be registered using tty_register_driver(). It is recommended to pass TTY_DRIVER_DYNAMIC_DEV in flags of tty_alloc_driver(). If it is not passed, all devices are also registered during tty_register_driver() and the following paragraph of registering devices can be skipped for such drivers. However, the struct tty_port part in Registering Devices is still relevant there.
tty_register_driver() #
int register a tty driver
Parameters
struct tty_driver *driver: driver to register
Description
Called by a tty driver to register itself.
tty_unregister_driver() #
void unregister a tty driver
Parameters
struct tty_driver *driver: driver to unregister
Description
Called by a tty driver to unregister itself.
Registering Devices #
Every TTY device shall be backed by a struct tty_port. Usually, TTY drivers embed tty_port into device's private structures. Further details about handling tty_port can be found in TTY Port. The driver is also recommended to use tty_port's reference counting by tty_port_get() and tty_port_put(). The final put is supposed to free the tty_port including the device's private struct.
Unless TTY_DRIVER_DYNAMIC_DEV was passed as flags to tty_alloc_driver(), TTY driver is supposed to register every device discovered in the system (the latter is preferred). This is performed by tty_register_device(). Or by tty_register_device_attr() if the driver wants to expose some information through struct attribute_group. Both of them register index'th device and upon return, the device can be opened. There are also preferred tty_port variants described in Linking Devices to Ports later. It is up to driver to manage free indices and choosing the right one. The TTY layer only refuses to register more devices than passed to tty_alloc_driver().
When the device is opened, the TTY layer allocates struct tty_struct and starts calling operations from tty_driver.ops, see TTY Operations Reference.
The registration routines are documented as follows:
tty_register_device() #
struct device * register a tty device
Parameters
struct tty_driver *driver: the tty driver that describes the tty deviceunsigned index: the index in the tty driver for this tty devicestruct device *device: a struct device that is associated with this tty device. This field is optional, if there is no known struct device for this tty device it can be set to NULL safely.
Description
This call is required to be made to register an individual tty device
if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set. If
that bit is not set, this function should not be called by a tty
driver.
Locking: ??
Return
A pointer to the struct device for this tty device (or ERR_PTR(-EFOO) on error).
tty_register_device_attr() #
struct device * register a tty device
Parameters
struct tty_driver *driver: the tty driver that describes the tty deviceunsigned index: the index in the tty driver for this tty devicestruct device *device: a struct device that is associated with this tty device. This field is optional, if there is no known struct device for this tty device it can be set toNULLsafely.void *drvdata: Driver data to be set to device.const struct attribute_group **attr_grp: Attribute group to be set on device.
Description
This call is required to be made to register an individual tty device if the
tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set. If that bit is
not set, this function should not be called by a tty driver.
Locking: ??
Return
A pointer to the struct device for this tty device (or ERR_PTR(-EFOO) on error).
tty_unregister_device() #
void unregister a tty device
Parameters
struct tty_driver *driver: the tty driver that describes the tty deviceunsigned index: the index in the tty driver for this tty device
Description
If a tty device is registered with a call to tty_register_device() then
this function must be called when the tty device is gone.
Locking: ??
Linking Devices to Ports #
As stated earlier, every TTY device shall have a struct tty_port assigned to it. It must be known to the TTY layer at tty_driver.ops.install() at latest. There are few helpers to link the two. Ideally, the driver uses tty_port_register_device() or tty_port_register_device_attr() instead of tty_register_device() and tty_register_device_attr() at the registration time. This way, the driver needs not care about linking later on.
If that is not possible, the driver still can link the tty_port to a specific index before the actual registration by tty_port_link_device(). If it still does not fit, tty_port_install() can be used from the tty_driver.ops.install hook as a last resort. The last one is dedicated mostly for in-memory devices like PTY where tty_ports are allocated on demand.
The linking routines are documented here:
tty_port_link_device() #
void link tty and tty_port
Parameters
struct tty_port *port: tty_port of the devicestruct tty_driver *driver: tty_driver for this deviceunsigned index: index of the tty
Description
Provide the tty layer with a link from a tty (specified by index) to a
tty_port (port). Use this only if neither tty_port_register_device() nor
tty_port_install() is used in the driver. If used, this has to be called
before tty_register_driver().
tty_port_register_device() #
struct device * register tty device
Parameters
struct tty_port *port: tty_port of the devicestruct tty_driver *driver: tty_driver for this deviceunsigned index: index of the ttystruct device *device: parent if exists, otherwise NULL
Description
It is the same as tty_register_device() except the provided port is linked
to a concrete tty specified by index. Use this or tty_port_install() (or
both). Call tty_port_link_device() as a last resort.
tty_port_register_device_attr() #
struct device * register tty device
Parameters
struct tty_port *port: tty_port of the devicestruct tty_driver *driver: tty_driver for this deviceunsigned index: index of the ttystruct device *device: parent if exists, otherwise NULLvoid *drvdata: Driver data to be set to device.const struct attribute_group **attr_grp: Attribute group to be set on device.
Description
It is the same as tty_register_device_attr() except the provided port is
linked to a concrete tty specified by index. Use this or tty_port_install()
(or both). Call tty_port_link_device() as a last resort.
TTY Driver Reference #
All members of struct tty_driver are documented here. The required members are noted at the end. struct tty_operations are documented next.
struct tty_driver #
- driver for TTY devices
Definition
;
Members
kref: reference counting. Reaching zero frees all the internals and the driver.cdevs: allocated/registered character /dev devicesowner: modules owning this driver. Used drivers cannot be rmmod'ed. Automatically set bytty_alloc_driver().driver_name: name of the driver used in /proc/ttyname: used for constructing /dev node namename_base: used as a number base for constructing /dev node namemajor: major /dev device number (zero for autoassignment)minor_start: the first minor /dev device numbernum: number of devices allocatedtype: type of tty driver (enum tty_driver_type)subtype: subtype of tty driver (enum tty_driver_subtype)init_termios: termios to set to each tty initially (e.g.tty_std_termios)flags: tty driver flags (TTY_DRIVER_)proc_entry: proc fs entry, used internallyother: driver of the linked tty; only used for the PTY driverttys: array of activestruct tty_struct, set bytty_standard_install()ports: array ofstruct tty_port; can be set during initialization bytty_port_link_device()and similartermios: storage for termios at each TTY close for the next opendriver_state: pointer to driver's arbitrary dataops: driver hooks for TTYs. Set them usingtty_set_operations(). Usestruct tty_porthelpers in them as much as possible.tty_drivers: used internally to link tty_drivers together
Description
The usual handling of struct tty_driver is to allocate it by
tty_alloc_driver(), set up all the necessary members, and register it by
tty_register_driver(). At last, the driver is torn down by calling
tty_unregister_driver() followed by tty_driver_kref_put().
The fields required to be set before calling tty_register_driver() include
driver_name, name, type, subtype, init_termios, and ops.
TTY Operations Reference #
When a TTY is registered, these driver hooks can be invoked by the TTY layer:
struct tty_operations #
- interface between driver and tty
Definition
;
Members
lookup:struct tty_struct *()(struct tty_driver *self, struct file *, int idx)install:int ()(struct tty_driver *self, struct tty_struct *tty)remove:void ()(struct tty_driver *self, struct tty_struct *tty)open:int ()(struct tty_struct *tty, struct file *)close:void ()(struct tty_struct *tty, struct file *)shutdown:void ()(struct tty_struct *tty)cleanup:void ()(struct tty_struct *tty)write:ssize_t ()(struct tty_struct *tty, const u8 *buf, size_t count)put_char:int ()(struct tty_struct *tty, u8 ch)flush_chars:void ()(struct tty_struct *tty)write_room:unsigned int ()(struct tty_struct *tty)chars_in_buffer:unsigned int ()(struct tty_struct *tty)ioctl:int ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)compat_ioctl:long ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)set_termios:void ()(struct tty_struct *tty, const struct ktermios *old)throttle:void ()(struct tty_struct *tty)unthrottle:void ()(struct tty_struct *tty)stop:void ()(struct tty_struct *tty)start:void ()(struct tty_struct *tty)hangup:void ()(struct tty_struct *tty)break_ctl:int ()(struct tty_struct *tty, int state)flush_buffer:void ()(struct tty_struct *tty)ldisc_ok:int ()(struct tty_struct *tty, int ldisc)set_ldisc:void ()(struct tty_struct *tty)wait_until_sent:void ()(struct tty_struct *tty, int timeout)send_xchar:void ()(struct tty_struct *tty, u8 ch)tiocmget:int ()(struct tty_struct *tty)tiocmset:int ()(struct tty_struct *tty, unsigned int set, unsigned int clear)resize:int ()(struct tty_struct *tty, struct winsize *ws)get_icount:int ()(struct tty_struct *tty, struct serial_icounter *icount)get_serial:int ()(struct tty_struct *tty, struct serial_struct *p)set_serial:int ()(struct tty_struct *tty, struct serial_struct *p)show_fdinfo:void ()(struct tty_struct *tty, struct seq_file *m)poll_init:int ()(struct tty_driver *driver, int line, char *options)poll_get_char:int ()(struct tty_driver *driver, int line)poll_put_char:void ()(struct tty_driver *driver, int line, char ch)proc_show:int ()(struct seq_file *m, void *driver)
Description
Return the tty device corresponding to idx, NULL if there is not
one currently in use and an ERR_PTR value on error. Called under
tty_mutex (for now!)
Optional method. Default behaviour is to use the self->ttys array.
Install a new tty into the self's internal tables. Used in conjunction with lookup and remove methods.
Optional method. Default behaviour is to use the self->ttys array.
Remove a closed tty from the self's internal tables. Used in conjunction with lookup and remove methods.
Optional method. Default behaviour is to use the self->ttys array.
This routine is called when a particular tty device is opened. This
routine is mandatory; if this routine is not filled in, the attempted
open will fail with ENODEV.
Required method. Called with tty lock held. May sleep.
This routine is called when a particular tty device is closed. At the point of return from this call the driver must make no further ldisc calls of any kind.
Remark: called even if the corresponding open() failed.
Required method. Called with tty lock held. May sleep.
This routine is called under the tty lock when a particular tty device is closed for the last time. It executes before the tty resources are freed so may execute while another function holds a tty kref.
This routine is called asynchronously when a particular tty device is closed for the last time freeing up the resources. This is actually the second part of shutdown for routines that might sleep.
This routine is called by the kernel to write a series (count) of characters (buf) to the tty device. The characters may come from user space or kernel space. This routine will return the number of characters actually accepted for writing.
May occur in parallel in special cases. Because this includes panic paths drivers generally shouldn't try and do clever locking here.
Optional: Required for writable devices. May not sleep.
This routine is called by the kernel to write a single character ch to the tty device. If the kernel uses this routine, it must call the flush_chars() routine (if defined) when it is done stuffing characters into the driver. If there is no room in the queue, the character is ignored.
Optional: Kernel will use the write method if not provided. Do not
call this function directly, call tty_put_char().
This routine is called by the kernel after it has written a series of characters to the tty device using put_char().
Optional. Do not call this function directly, call
tty_driver_flush_chars().
This routine returns the numbers of characters the tty driver will accept for queuing to be written. This number is subject to change as output buffers get emptied, or if the output flow control is acted.
The ldisc is responsible for being intelligent about multi-threading of write_room/write calls
Required if write method is provided else not needed. Do not call this
function directly, call tty_write_room()
This routine returns the number of characters in the device private
output queue. Used in tty_wait_until_sent() and for poll()
implementation.
Optional: if not provided, it is assumed there is no queue on the
device. Do not call this function directly, call tty_chars_in_buffer().
This routine allows the tty driver to implement device-specific
ioctls. If the ioctl number passed in cmd is not recognized by the
driver, it should return ENOIOCTLCMD.
Optional.
Implement ioctl processing for 32 bit process on 64 bit system.
Optional.
This routine allows the tty driver to be notified when device's termios settings have changed. New settings are in tty->termios. Previous settings are passed in the old argument.
The API is defined such that the driver should return the actual modes selected. This means that the driver is responsible for modifying any bits in tty->termios it cannot fulfill to indicate the actual modes being used.
Optional. Called under the tty->termios_rwsem. May sleep.
This routine allows the tty driver to decide if it can deal with a particular ldisc.
Optional. Called under the tty->ldisc_sem and tty->termios_rwsem.
This routine allows the tty driver to be notified when the device's line discipline is being changed. At the point this is done the discipline is not yet usable.
Optional. Called under the tty->ldisc_sem and tty->termios_rwsem.
This routine notifies the tty driver that input buffers for the line discipline are close to full, and it should somehow signal that no more characters should be sent to the tty.
Serialization including with unthrottle() is the job of the ldisc layer.
Optional: Always invoke via tty_throttle_safe(). Called under the
tty->termios_rwsem.
This routine notifies the tty driver that it should signal that characters can now be sent to the tty without fear of overrunning the input buffers of the line disciplines.
Optional. Always invoke via tty_unthrottle(). Called under the
tty->termios_rwsem.
This routine notifies the tty driver that it should stop outputting characters to the tty device.
Called with tty->flow.lock held. Serialized with start() method.
Optional. Always invoke via stop_tty().
This routine notifies the tty driver that it resumed sending characters to the tty device.
Called with tty->flow.lock held. Serialized with stop() method.
Optional. Always invoke via start_tty().
This routine notifies the tty driver that it should hang up the tty device.
Optional. Called with tty lock held.
This optional routine requests the tty driver to turn on or off BREAK status on the RS-232 port. If state is -1, then the BREAK status should be turned on; if state is 0, then BREAK should be turned off.
If this routine is implemented, the high-level tty driver will handle
the following ioctls: TCSBRK, TCSBRKP, TIOCSBRK, TIOCCBRK.
If the driver sets TTY_DRIVER_HARDWARE_BREAK in tty_alloc_driver(),
then the interface will also be called with actual times and the
hardware is expected to do the delay work itself. 0 and -1 are still
used for on/off.
Optional: Required for TCSBRK/BRKP/etc. handling. May sleep.
This routine discards device private output buffer. Invoked on close,
hangup, to implement TCOFLUSH ioctl and similar.
Optional: if not provided, it is assumed there is no queue on the
device. Do not call this function directly, call
tty_driver_flush_buffer().
This routine waits until the device has written out all of the characters in its transmitter FIFO. Or until timeout (in jiffies) is reached.
Optional: If not provided, the device is assumed to have no FIFO.
Usually correct to invoke via tty_wait_until_sent(). May sleep.
This routine is used to send a high-priority XON/XOFF character (ch) to the tty device.
Optional: If not provided, then the write method is called under the tty->atomic_write_lock to keep it serialized with the ldisc.
This routine is used to obtain the modem status bits from the tty driver.
Optional: If not provided, then ENOTTY is returned from the TIOCMGET
ioctl. Do not call this function directly, call tty_tiocmget().
This routine is used to set the modem status bits to the tty driver. First, clear bits should be cleared, then set bits set.
Optional: If not provided, then ENOTTY is returned from the TIOCMSET
ioctl. Do not call this function directly, call tty_tiocmset().
Called when a termios request is issued which changes the requested terminal geometry to ws.
Optional: the default action is to update the termios structure
without error. This is usually the correct behaviour. Drivers should
not force errors here if they are not resizable objects (e.g. a serial
line). See tty_do_resize() if you need to wrap the standard method
in your own logic -- the usual case.
Called when the tty device receives a TIOCGICOUNT ioctl. Passed a
kernel structure icount to complete.
Optional: called only if provided, otherwise ENOTTY will be returned.
Called when the tty device receives a TIOCGSERIAL ioctl. Passed a
kernel structure p (struct serial_struct) to complete.
Optional: called only if provided, otherwise ENOTTY will be returned.
Do not call this function directly, call tty_tiocgserial().
Called when the tty device receives a TIOCSSERIAL ioctl. Passed a
kernel structure p (struct serial_struct) to set the values from.
Optional: called only if provided, otherwise ENOTTY will be returned.
Do not call this function directly, call tty_tiocsserial().
Called when the tty device file descriptor receives a fdinfo request from VFS (to show in /proc/<pid>/fdinfo/). m should be filled with information.
Optional: called only if provided, otherwise nothing is written to m.
Do not call this function directly, call tty_show_fdinfo().
kgdboc support (Documentation/process/debugging/kgdb.rst). This routine is called to initialize the HW for later use by calling poll_get_char or poll_put_char.
Optional: called only if provided, otherwise skipped as a non-polling driver.
kgdboc support (see poll_init). driver should read a character from a tty identified by line and return it.
Optional: called only if poll_init provided.
kgdboc support (see poll_init). driver should write character ch to a tty identified by line.
Optional: called only if poll_init provided.
Driver driver (cast to struct tty_driver) can show additional info in
/proc/tty/driver/<driver_name>. It is enough to fill in the information
into m.
Optional: called only if provided, otherwise no /proc entry created.
This structure defines the interface between the low-level tty driver and
the tty routines. These routines can be defined. Unless noted otherwise,
they are optional, and can be filled in with a NULL pointer.
TTY Internals
Peios Kernel / Hardware and drivers / Driver development / TTY
Kopen #
These functions serve for opening a TTY from the kernelspace:
tty_kclose() #
void closes tty opened by tty_kopen
Parameters
struct tty_struct *tty: tty device
Description
Performs the final steps to release and free a tty device. It is the same as
tty_release_struct() except that it also resets TTY_PORT_KOPENED flag on
tty->port.
tty_kopen_exclusive() #
struct tty_struct * open a tty device for kernel
Parameters
dev_t device: dev_t of device to open
Description
Opens tty exclusively for kernel. Performs the driver lookup, makes sure it's not already opened and performs the first-time tty initialization.
- Claims the global
tty_mutexto serialize:- concurrent first-time tty initialization
- concurrent tty driver removal w/ lookup
- concurrent tty removal from driver table
Return
the locked initialized tty_struct
tty_kopen_shared() #
struct tty_struct * open a tty device for shared in-kernel use
Parameters
dev_t device: dev_t of device to open
Description
Opens an already existing tty for in-kernel use. Compared to
tty_kopen_exclusive() above it doesn't ensure to be the only user.
Locking: identical to tty_kopen() above.
Exported Internal Functions #
tty_dev_name_to_number() #
int return dev_t for device name
Parameters
const char *name: user space name of device under /devdev_t *number: pointer to dev_t that this function will populate
Description
This function converts device names like ttyS0 or ttyUSB1 into dev_t like
(4, 64) or (188, 1). If no corresponding driver is registered then the
function returns -ENODEV.
-
Locking: this acquires tty_mutex to protect the tty_drivers list from
being modified while we are traversing it, and makes sure to release it before exiting.
tty_release_struct() #
void release a tty struct
Parameters
struct tty_struct *tty: tty deviceint idx: index of the tty
Description
Performs the final steps to release and free a tty device. It is roughly the
reverse of tty_init_dev().
tty_get_icount() #
int get tty statistics
Parameters
struct tty_struct *tty: tty devicestruct serial_icounter_struct *icount: output parameter
Description
Gets a copy of the tty's icount statistics.
Locking: none (up to the driver)
Internal Functions #
free_tty_struct() #
void free a disused tty
Parameters
struct tty_struct *tty: tty struct to free
Description
Free the write buffers, tty queue and tty memory itself.
Locking: none. Must be called after tty is definitely unused
tty_free_file() #
void free file->private_data
Parameters
struct file *file: to free private_data of
Description
This shall be used only for fail path handling when tty_add_file was not called yet.
get_tty_driver() #
struct tty_driver * find device of a tty
Parameters
dev_t device: device identifierint *index: returns the index of the tty
Description
This routine returns a tty driver structure, given a device number and also passes back the index number.
Locking: caller must hold tty_mutex
tty_release_redirect() #
struct file * Release a redirect on a pty if present
Parameters
struct tty_struct *tty: tty device
Description
This is available to the pty code so if the master closes, if the slave is a redirect it can release the redirect.
__tty_hangup() #
void actual handler for hangup events
Parameters
struct tty_struct *tty: tty deviceint exit_session: if non-zero, signal all foreground group processes
Description
This can be called by a "kworker" kernel thread. That is process synchronous but doesn't hold any locks, so we need to make sure we have the appropriate locks for what we're doing.
The hangup event clears any pending redirections onto the hung up device. It ensures future writes will error and it does the needed line discipline hangup and signal delivery. The tty object itself remains intact.
- Locking:
-
BTM
-
redirect lock for undoing redirection
-
file list lock for manipulating list of ttys
-
tty_ldiscs_lock from called functions
-
termios_rwsem resetting termios data
-
tasklist_lock to walk task list for hangup event
- ->siglock to protect ->signal/->sighand
-
-
tty_vhangup_self() #
void process vhangup for own ctty
Parameters
void: no arguments
Description
Perform a vhangup on the current controlling tty
tty_vhangup_session() #
void hangup session leader exit
Parameters
struct tty_struct *tty: tty to hangup
Description
The session leader is exiting and hanging up its controlling terminal.
Every process in the foreground process group is signalled SIGHUP.
We do this synchronously so that when the syscall returns the process is complete. That guarantee is necessary for security reasons.
tty_read() #
ssize_t read method for tty device files
Parameters
struct kiocb *iocb: kernel I/O control blockstruct iov_iter *to: destination for the data read
Description
Perform the read system call function on this terminal device. Checks for hung up devices before calling the line discipline method.
- Locking: Locks the line discipline internally while needed. Multiple read calls may be outstanding in parallel.
tty_write_message() #
void write a message to a certain tty, not just the console.
Parameters
struct tty_struct *tty: the destination tty_structchar *msg: the message to write
Description
This is used for messages that need to be redirected to a specific tty. We don't put it into the syslog queue right now maybe in the future if really needed.
We must still hold the BTM and test the CLOSING flag for the moment.
This function is DEPRECATED, do not use in new code.
tty_write() #
ssize_t write method for tty device file
Parameters
struct kiocb *iocb: kernel I/O control blockstruct iov_iter *from: iov_iter with data to write
Description
Write data to a tty device via the line discipline.
- Locking: Locks the line discipline as required Writes to the tty driver are serialized by the atomic_write_lock and are then processed in chunks to the device. The line discipline write method will not be invoked in parallel for each device.
tty_send_xchar() #
int send priority character
Parameters
struct tty_struct *tty: the tty to send tou8 ch: xchar to send
Description
Send a high priority character to the tty even if stopped.
Locking: none for xchar method, write ordering for write method.
pty_line_name() #
void generate name for a pty
Parameters
struct tty_driver *driver: the tty driver in useint index: the minor numberchar *p: output buffer of at least 6 bytes
Description
Generate a name from a driver reference and write it to the output buffer p.
Locking: None
tty_line_name() #
ssize_t generate name for a tty
Parameters
struct tty_driver *driver: the tty driver in useint index: the minor numberchar *p: output buffer of at least 7 bytes
Description
Generate a name from a driver reference and write it to the output buffer p.
Locking: None
tty_driver_lookup_tty() #
struct tty_struct * find an existing tty, if any
Parameters
struct tty_driver *driver: the driver for the ttystruct file *file: file objectint idx: the minor number
Return
the tty, if found. If not found, return NULL or ERR_PTR() if the
driver lookup() method returns an error.
Description
Locking: tty_mutex must be held. If the tty is found, bump the tty kref.
tty_driver_install_tty() #
int install a tty entry in the driver
Parameters
struct tty_driver *driver: the driver for the ttystruct tty_struct *tty: the tty
Description
Install a tty object into the driver tables. The tty->index field will be set by the time this is called. This method is responsible for ensuring any need additional structures are allocated and configured.
Locking: tty_mutex for now
tty_driver_remove_tty() #
void remove a tty from the driver tables
Parameters
struct tty_driver *driver: the driver for the ttystruct tty_struct *tty: tty to remove
Description
Remove a tty object from the driver tables. The tty->index field will be set by the time this is called.
Locking: tty_mutex for now
tty_reopen() #
int fast re-open of an open tty
Parameters
struct tty_struct *tty: the tty to open
Description
Re-opens on master ptys are not allowed and return -EIO.
Locking: Caller must hold tty_lock
Return
0 on success, -errno on error.
tty_init_dev() #
struct tty_struct * initialise a tty device
Parameters
struct tty_driver *driver: tty driver we are opening a device onint idx: device index
Description
Prepare a tty device. This may not be a "new" clean device but could also be an active device. The pty drivers require special handling because of this.
- Locking: The function is called under the tty_mutex, which protects us from the tty struct or driver itself going away.
On exit the tty device has the line discipline attached and a reference count of 1. If a pair was created for pty/tty use and the other was a pty master then it too has a reference count of 1.
WSH 06/09/97: Rewritten to remove races and properly clean up after a failed open. The new code protects the open with a mutex, so it's really quite straightforward. The mutex locking can probably be relaxed for the (most common) case of reopening a tty.
Return
new tty structure
tty_flush_works() #
void flush all works of a tty/pty pair
Parameters
struct tty_struct *tty: tty device to flush works for (or either end of a pty pair)
Description
Sync flush all works belonging to tty (and the 'other' tty).
release_one_tty() #
void release tty structure memory
Parameters
struct work_struct *work: work of tty we are obliterating
Description
Releases memory associated with a tty structure, and clears out the driver table slots. This function is called when a device is no longer in use. It also gets called when setup of a device fails.
- Locking: takes the file list lock internally when working on the list of ttys that the driver keeps.
This method gets called from a work queue so that the driver private cleanup ops can sleep (needed for USB at least)
release_tty() #
void release tty structure memory
Parameters
struct tty_struct *tty: tty device releaseint idx: index of the tty device release
Description
Release both tty and a possible linked partner (think pty pair), and decrement the refcount of the backing module.
- Locking: tty_mutex takes the file list lock internally when working on the list of ttys that the driver keeps.
tty_release_checks() #
int check a tty before real release
Parameters
struct tty_struct *tty: tty to checkint idx: index of the tty
Description
Performs some paranoid checking before true release of the tty. This is a
no-op unless TTY_PARANOIA_CHECK is defined.
tty_release() #
int vfs callback for close
Parameters
struct inode *inode: inode of ttystruct file *filp: file pointer for handle to tty
Description
Called the last time each file handle is closed that references this tty. There may however be several such references.
- Locking:
Takes BKL. See
tty_release_dev().
Even releasing the tty structures is a tricky business. We have to be very careful that the structures are all released at the same time, as interrupts might otherwise get the wrong pointers.
WSH 09/09/97: rewritten to avoid some nasty race conditions that could lead to double frees or releasing memory still in use.
tty_open_current_tty() #
struct tty_struct * get locked tty of current task
Parameters
dev_t device: device numberstruct file *filp: file pointer to tty
Return
locked tty of the current task iff device is /dev/tty
Description
Performs a re-open of the current task's controlling tty.
We cannot return driver and index like for the other nodes because devpts will not work then. It expects inodes to be from devpts FS.
tty_lookup_driver() #
struct tty_driver * lookup a tty driver for a given device file
Parameters
dev_t device: device numberstruct file *filp: file pointer to ttyint *index: index for the device in the return driver
Description
If returned value is not erroneous, the caller is responsible to decrement
the refcount by tty_driver_kref_put().
Locking: tty_mutex protects get_tty_driver()
Return
driver for this inode (with increased refcount)
tty_open_by_driver() #
struct tty_struct * open a tty device
Parameters
dev_t device: dev_t of device to openstruct file *filp: file pointer to tty
Description
Performs the driver lookup, checks for a reopen, or otherwise performs the first-time tty initialization.
- Claims the global tty_mutex to serialize:
- concurrent first-time tty initialization
- concurrent tty driver removal w/ lookup
- concurrent tty removal from driver table
Return
the locked initialized or re-opened tty_struct
tty_open() #
int open a tty device
Parameters
struct inode *inode: inode of device filestruct file *filp: file pointer to tty
Description
tty_open() and tty_release() keep up the tty count that contains the number
of opens done on a tty. We cannot use the inode-count, as different inodes
might point to the same tty.
Open-counting is needed for pty masters, as well as for keeping track of serial lines: DTR is dropped when the last close happens. (This is not done solely through tty->count, now. - Ted 1/27/92)
The termios state of a pty is reset on the first open so that settings don't persist across reuse.
- Locking:
tty_mutexprotects tty,tty_lookup_driver()andtty_init_dev().- tty->count should protect the rest.
- ->siglock protects ->signal/->sighand
Note
the tty_unlock/lock cases without a ref are only safe due to tty_mutex
tty_poll() #
__poll_t check tty status
Parameters
struct file *filp: file being polledpoll_table *wait: poll wait structures to update
Description
Call the line discipline polling method to obtain the poll status of the device.
Locking: locks called line discipline but ldisc poll method may be re-entered freely by other callers.
tiocsti() #
int fake input character
Parameters
struct tty_struct *tty: tty to fake input intou8 __user *p: pointer to character
Description
Fake input to a tty device. Does the necessary locking and input management.
FIXME: does not honour flow control ??
- Locking:
- Called functions take tty_ldiscs_lock
- current->signal->tty check is safe without locks
tiocgwinsz() #
int implement window query ioctl
Parameters
struct tty_struct *tty: ttystruct winsize __user *arg: user buffer for result
Description
Copies the kernel idea of the window size into the user buffer.
Locking: tty->winsize_mutex is taken to ensure the winsize data is consistent.
tiocswinsz() #
int implement window size set ioctl
Parameters
struct tty_struct *tty: tty side of ttystruct winsize __user *arg: user buffer for result
Description
Copies the user idea of the window size to the kernel. Traditionally this is just advisory information but for the Linux console it actually has driver level meaning and triggers a VC resize.
- Locking: Driver dependent. The default do_resize method takes the tty termios mutex and ctrl.lock. The console takes its own lock then calls into the default method.
tioccons() #
int allow admin to move logical console
Parameters
struct file *file: the file to become console
Description
Allow the administrator to move the redirected console device.
Locking: uses redirect_lock to guard the redirect information
tiocsetd() #
int set line discipline
Parameters
struct tty_struct *tty: tty deviceint __user *p: pointer to user data
Description
Set the line discipline according to user request.
Locking: see tty_set_ldisc(), this function is just a helper
tiocgetd() #
int get line discipline
Parameters
struct tty_struct *tty: tty deviceint __user *p: pointer to user data
Description
Retrieves the line discipline id directly from the ldisc.
Locking: waits for ldisc reference (in case the line discipline is changing or the tty is being hungup)
send_break() #
int performed time break
Parameters
struct tty_struct *tty: device to break onunsigned int duration: timeout in mS
Description
Perform a timed break on hardware that lacks its own driver level timed break functionality.
- Locking: tty->atomic_write_lock serializes
tty_tiocmget() #
int get modem status
Parameters
struct tty_struct *tty: tty deviceint __user *p: pointer to result
Description
Obtain the modem status bits from the tty driver if the feature is
supported. Return -ENOTTY if it is not available.
Locking: none (up to the driver)
tty_tiocmset() #
int set modem status
Parameters
struct tty_struct *tty: tty deviceunsigned int cmd: command - clear bits, set bits or set allunsigned __user *p: pointer to desired bits
Description
Set the modem status bits from the tty driver if the feature
is supported. Return -ENOTTY if it is not available.
Locking: none (up to the driver)
alloc_tty_struct() #
struct tty_struct * allocate a new tty
Parameters
struct tty_driver *driver: driver which will handle the returned ttyint idx: minor of the tty
Description
This subroutine allocates and initializes a tty structure.
Locking: none - tty in question is not exposed at this point
TTY IOCTL Helpers
Peios Kernel / Hardware and drivers / Driver development / TTY
tty_chars_in_buffer() #
unsigned int characters pending
Parameters
struct tty_struct *tty: terminal
Return
the number of bytes of data in the device private output queue. If no private method is supplied there is assumed to be no queue on the device.
tty_write_room() #
unsigned int write queue space
Parameters
struct tty_struct *tty: terminal
Return
the number of bytes that can be queued to this device at the present time. The result should be treated as a guarantee and the driver cannot offer a value it later shrinks by more than the number of bytes written. If no method is provided, 2K is always returned and data may be lost as there will be no flow control.
tty_driver_flush_buffer() #
void discard internal buffer
Parameters
struct tty_struct *tty: terminal
Description
Discard the internal output buffer for this device. If no method is provided, then either the buffer cannot be hardware flushed or there is no buffer driver side.
tty_unthrottle() #
void flow control
Parameters
struct tty_struct *tty: terminal
Description
Indicate that a tty may continue transmitting data down the stack. Takes
the tty_struct->termios_rwsem to protect against parallel
throttle/unthrottle and also to ensure the driver can consistently reference
its own termios data at this point when implementing software flow control.
Drivers should however remember that the stack can issue a throttle, then change flow control method, then unthrottle.
tty_throttle_safe() #
bool flow control
Parameters
struct tty_struct *tty: terminal
Description
Indicate that a tty should stop transmitting data down the stack.
tty_throttle_safe() will only attempt throttle if tty->flow_change is
TTY_THROTTLE_SAFE. Prevents an accidental throttle due to race conditions
when throttling is conditional on factors evaluated prior to throttling.
Return
true if tty is throttled (or was already throttled)
tty_unthrottle_safe() #
bool flow control
Parameters
struct tty_struct *tty: terminal
Description
Similar to tty_unthrottle() but will only attempt unthrottle if
tty->flow_change is TTY_UNTHROTTLE_SAFE. Prevents an accidental unthrottle
due to race conditions when unthrottling is conditional on factors evaluated
prior to unthrottling.
Return
true if tty is unthrottled (or was already unthrottled)
tty_wait_until_sent() #
void wait for I/O to finish
Parameters
struct tty_struct *tty: tty we are waiting forlong timeout: how long we will wait
Description
Wait for characters pending in a tty driver to hit the wire, or for a timeout to occur (eg due to flow control).
Locking: none
tty_termios_copy_hw() #
void copy hardware settings
Parameters
struct ktermios *new: new termiosconst struct ktermios *old: old termios
Description
Propagate the hardware specific terminal setting bits from the old termios structure to the new one. This is used in cases where the hardware does not support reconfiguration or as a helper in some cases where only minimal reconfiguration is supported.
tty_termios_hw_change() #
bool check for setting change
Parameters
const struct ktermios *a: termiosconst struct ktermios *b: termios to compare
Description
Check if any of the bits that affect a dumb device have changed between the two termios structures, or a speed change is needed.
Return
true if change is needed
tty_get_char_size() #
unsigned char get size of a character
Parameters
unsigned int cflag: termios cflag value
Return
size (in bits) of a character depending on cflag's CSIZE setting
tty_get_frame_size() #
unsigned char get size of a frame
Parameters
unsigned int cflag: termios cflag value
Description
Get the size (in bits) of a frame depending on cflag's CSIZE, CSTOPB, and
PARENB setting. The result is a sum of character size, start and stop bits
-- one bit each -- second stop bit (if set), and parity bit (if set).
Return
size (in bits) of a frame depending on cflag's setting.
tty_set_termios() #
int update termios values
Parameters
struct tty_struct *tty: tty to updatestruct ktermios *new_termios: desired new value
Description
Perform updates to the termios values set on this tty. A master pty's termios should never be set.
Locking: tty_struct->termios_rwsem
set_termios() #
int set termios values for a tty
Parameters
struct tty_struct *tty: terminal devicevoid __user *arg: user dataint opt: option information
Description
Helper function to prepare termios data and run necessary other functions
before using tty_set_termios() to do the actual changes.
Locking: called functions take tty_struct->ldisc_sem and
tty_struct->termios_rwsem locks
Return
0 on success, an error otherwise
set_sgttyb() #
int set legacy terminal values
Parameters
struct tty_struct *tty: tty structurestruct sgttyb __user *sgttyb: pointer to old style terminal structure
Description
Updates a terminal from the legacy BSD style terminal information structure.
Locking: tty_struct->termios_rwsem
Return
0 on success, an error otherwise
tty_change_softcar() #
int carrier change ioctl helper
Parameters
struct tty_struct *tty: tty to updatebool enable: enable/disableCLOCAL
Description
Perform a change to the CLOCAL state and call into the driver layer to make
it visible.
Locking: tty_struct->termios_rwsem.
Return
0 on success, an error otherwise
tty_mode_ioctl() #
int mode related ioctls
Parameters
struct tty_struct *tty: tty for the ioctlunsigned int cmd: commandunsigned long arg: ioctl argument
Description
Perform non-line discipline specific mode control ioctls. This is designed to be called by line disciplines to ensure they provide consistent mode setting.
tty_get_baud_rate() #
speed_t get tty bit rates
Parameters
const struct tty_struct *tty: tty to query
Return
the baud rate as an integer for this terminal
Description
Locking: The termios lock must be held by the caller.
TTY Line Discipline
Peios Kernel / Hardware and drivers / Driver development / TTY
TTY line discipline process all incoming and outgoing character from/to a tty device. The default line discipline is N_TTY. It is also a fallback if establishing any other discipline for a tty fails. If even N_TTY fails, N_NULL takes over. That never fails, but also does not process any characters -- it throws them away.
Registration #
Line disciplines are registered with tty_register_ldisc() passing the ldisc structure. At the point of registration the discipline must be ready to use and it is possible it will get used before the call returns success. If the call returns an error then it won’t get called. Do not reuse ldisc numbers as they are part of the userspace ABI and writing over an existing ldisc will cause demons to eat your computer. You must not re-register over the top of the line discipline even with the same data or your computer again will be eaten by demons. In order to remove a line discipline call tty_unregister_ldisc().
Heed this warning: the reference count field of the registered copies of the tty_ldisc structure in the ldisc table counts the number of lines using this discipline. The reference count of the tty_ldisc structure within a tty counts the number of active users of the ldisc at this instant. In effect it counts the number of threads of execution within an ldisc method (plus those about to enter and exit although this detail matters not).
tty_register_ldisc() #
int install a line discipline
Parameters
struct tty_ldisc_ops *new_ldisc: pointer to the ldisc object
Description
Installs a new line discipline into the kernel. The discipline is set up as unreferenced and then made available to the kernel from this point onwards.
Locking: takes tty_ldiscs_lock to guard against ldisc races
tty_unregister_ldisc() #
void unload a line discipline
Parameters
struct tty_ldisc_ops *ldisc: ldisc number
Description
Remove a line discipline from the kernel providing it is not currently in use.
Locking: takes tty_ldiscs_lock to guard against ldisc races
Other Functions #
tty_ldisc_flush() #
void flush line discipline queue
Parameters
struct tty_struct *tty: tty to flush ldisc for
Description
Flush the line discipline queue (if any) and the tty flip buffers for this tty.
tty_set_ldisc() #
int set line discipline
Parameters
struct tty_struct *tty: the terminal to setint disc: the line discipline number
Description
Set the discipline of a tty line. Must be called from a process context. The ldisc change logic has to protect itself against any overlapping ldisc change (including on the other end of pty pairs), the close of one side of a tty/pty pair, and eventually hangup.
Line Discipline Operations Reference #
struct tty_ldisc_ops #
ldisc operations
Definition
;
Members
name: name of this ldisc rendered in /proc/tty/ldiscsnum:N_*number (N_TTY,N_HDLC, ...) reserved to this ldiscopen: [TTY]int ()(struct tty_struct *tty)close: [TTY]void ()(struct tty_struct *tty)flush_buffer: [TTY]void ()(struct tty_struct *tty)read: [TTY]ssize_t ()(struct tty_struct *tty, struct file *file, u8 *buf, size_t nr)write: [TTY]ssize_t ()(struct tty_struct *tty, struct file *file, const u8 *buf, size_t nr)ioctl: [TTY]int ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)compat_ioctl: [TTY]int ()(struct tty_struct *tty, unsigned int cmd, unsigned long arg)set_termios: [TTY]void ()(struct tty_struct *tty, const struct ktermios *old)poll: [TTY]int ()(struct tty_struct *tty, struct file *file, struct poll_table_struct *wait)hangup: [TTY]void ()(struct tty_struct *tty)receive_buf: [DRV]void ()(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count)write_wakeup: [DRV]void ()(struct tty_struct *tty)dcd_change: [DRV]void ()(struct tty_struct *tty, bool active)receive_buf2: [DRV]ssize_t ()(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count)lookahead_buf: [DRV]void ()(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count)owner: module containting this ldisc (for reference counting)
Description
This function is called when the line discipline is associated with the tty. No other call into the line discipline for this tty will occur until it completes successfully. It should initialize any state needed by the ldisc, and set tty->receive_room to the maximum amount of data the line discipline is willing to accept from the driver with a single call to receive_buf(). Returning an error will prevent the ldisc from being attached.
Optional. Can sleep.
This function is called when the line discipline is being shutdown, either because the tty is being closed or because the tty is being changed to use a new line discipline. At the point of execution no further users will enter the ldisc code for this tty.
Optional. Can sleep.
This function instructs the line discipline to clear its buffers of any input characters it may have queued to be delivered to the user mode process. It may be called at any point between open and close.
Optional.
This function is called when the user requests to read from the tty.
The line discipline will return whatever characters it has buffered up
for the user. If this function is not defined, the user will receive
an EIO error. Multiple read calls may occur in parallel and the ldisc
must deal with serialization issues.
Optional: EIO unless provided. Can sleep.
This function is called when the user requests to write to the tty.
The line discipline will deliver the characters to the low-level tty
device for transmission, optionally performing some processing on the
characters first. If this function is not defined, the user will
receive an EIO error.
Optional: EIO unless provided. Can sleep.
This function is called when the user requests an ioctl which is not handled by the tty layer or the low-level tty driver. It is intended for ioctls which affect line discpline operation. Note that the search order for ioctls is (1) tty layer, (2) tty low-level driver, (3) line discpline. So a low-level driver can "grab" an ioctl request before the line discpline has a chance to see it.
Optional.
Process ioctl calls from 32-bit process on 64-bit system.
Note that only ioctls that are neither "pointer to compatible
structure" nor tty-generic. Something private that takes an integer or
a pointer to wordsize-sensitive structure belongs here, but most of
ldiscs will happily leave it NULL.
Optional.
This function notifies the line discpline that a change has been made to the termios structure.
Optional.
This function is called when a user attempts to select/poll on a tty device. It is solely the responsibility of the line discipline to handle poll requests.
Optional.
Called on a hangup. Tells the discipline that it should cease I/O to the tty driver. The driver should seek to perform this action quickly but should wait until any pending driver I/O is completed. No further calls into the ldisc code will occur.
Optional. Can sleep.
This function is called by the low-level tty driver to send characters
received by the hardware to the line discpline for processing. cp is
a pointer to the buffer of input character received by the device. fp
is a pointer to an array of flag bytes which indicate whether a
character was received with a parity error, etc. fp may be NULL to
indicate all data received is TTY_NORMAL.
Optional.
This function is called by the low-level tty driver to signal that line discpline should try to send more characters to the low-level driver for transmission. If the line discpline does not have any more data to send, it can just return. If the line discipline does have some data to send, please arise a tasklet or workqueue to do the real data transfer. Do not send data in this hook, it may lead to a deadlock.
Optional.
Tells the discipline that the DCD pin has changed its status. Used
exclusively by the N_PPS (Pulse-Per-Second) line discipline.
Optional.
This function is called by the low-level tty driver to send characters
received by the hardware to the line discpline for processing. cp is a
pointer to the buffer of input character received by the device. fp
is a pointer to an array of flag bytes which indicate whether a
character was received with a parity error, etc. fp may be NULL to
indicate all data received is TTY_NORMAL. If assigned, prefer this
function for automatic flow control.
Optional.
This function is called by the low-level tty driver for characters
not eaten by ->receive_buf() or ->receive_buf2(). It is useful for
processing high-priority characters such as software flow-control
characters that could otherwise get stuck into the intermediate
buffer until tty has room to receive them. Ldisc must be able to
handle later a ->receive_buf() or ->receive_buf2() call for the
same characters (e.g. by skipping the actions for high-priority
characters already handled by ->lookahead_buf()).
Optional.
This structure defines the interface between the tty line discipline
implementation and the tty routines. The above routines can be defined.
Unless noted otherwise, they are optional, and can be filled in with a NULL
pointer.
Hooks marked [TTY] are invoked from the TTY core, the [DRV] ones from the tty_driver side.
Driver Access #
Line discipline methods can call the methods of the underlying hardware driver. These are documented as a part of struct tty_operations.
TTY Flags #
Line discipline methods have access to tty_struct.flags field. See TTY Struct.
Locking #
Callers to the line discipline functions from the tty layer are required to take line discipline locks. The same is true of calls from the driver side but not yet enforced.
tty_ldisc_ref_wait() #
struct tty_ldisc * wait for the tty ldisc
Parameters
struct tty_struct *tty: tty device
Description
Dereference the line discipline for the terminal and take a reference to it. If the line discipline is in flux then wait patiently until it changes.
Note 1: Must not be called from an IRQ/timer context. The caller must also be careful not to hold other locks that will deadlock against a discipline change, such as an existing ldisc reference (which we check for).
Note 2: a file_operations routine (read/poll/write) should use this function to wait for any ldisc lifetime events to finish.
Return
NULL if the tty has been hungup and not re-opened with a new file
descriptor, otherwise valid ldisc reference
tty_ldisc_ref() #
struct tty_ldisc * get the tty ldisc
Parameters
struct tty_struct *tty: tty device
Description
Dereference the line discipline for the terminal and take a reference to it.
If the line discipline is in flux then return NULL. Can be called from IRQ
and timer functions.
tty_ldisc_deref() #
void free a tty ldisc reference
Parameters
struct tty_ldisc *ld: reference to free up
Description
Undoes the effect of tty_ldisc_ref() or tty_ldisc_ref_wait(). May be called
in IRQ context.
While these functions are slightly slower than the old code they should have minimal impact as most receive logic uses the flip buffers and they only need to take a reference when they push bits up through the driver.
A caution: The tty_ldisc_ops.open(), tty_ldisc_ops.close() and tty_driver.set_ldisc() functions are called with the ldisc unavailable. Thus tty_ldisc_ref() will fail in this situation if used within these functions. Ldisc and driver code calling its own functions must be careful in this case.
Internal Functions #
tty_ldisc_get() #
struct tty_ldisc * take a reference to an ldisc
Parameters
struct tty_struct *tty: tty deviceint disc: ldisc number
Description
Takes a reference to a line discipline. Deals with refcounts and module locking counts. If the discipline is not available, its module loaded, if possible.
Locking: takes tty_ldiscs_lock to guard against ldisc races
Return
- -
EINVALif the discipline index is not [N_TTY..NR_LDISCS] or if the discipline is not registered - -
EAGAINifrequest_module()failed to load or register the discipline - -
ENOMEMif allocation failure - Otherwise, returns a pointer to the discipline and bumps the ref count
tty_ldisc_put() #
void release the ldisc
Parameters
struct tty_ldisc *ld: lisdsc to release
Description
Complement of tty_ldisc_get().
tty_set_termios_ldisc() #
void set ldisc field
Parameters
struct tty_struct *tty: tty structureint disc: line discipline number
Description
This is probably overkill for real world processors but they are not on hot paths so a little discipline won't do any harm.
The line discipline-related tty_struct fields are reset to prevent the ldisc driver from re-using stale information for the new ldisc instance.
Locking: takes termios_rwsem
tty_ldisc_open() #
int open a line discipline
Parameters
struct tty_struct *tty: tty we are opening the ldisc onstruct tty_ldisc *ld: discipline to open
Description
A helper opening method. Also a convenient debugging and check point.
Locking: always called with BTM already held.
tty_ldisc_close() #
void close a line discipline
Parameters
struct tty_struct *tty: tty we are opening the ldisc onstruct tty_ldisc *ld: discipline to close
Description
A helper close method. Also a convenient debugging and check point.
tty_ldisc_failto() #
int helper for ldisc failback
Parameters
struct tty_struct *tty: tty to open the ldisc onint ld: ldisc we are trying to fail back to
Description
Helper to try and recover a tty when switching back to the old ldisc fails and we need something attached.
tty_ldisc_restore() #
void helper for tty ldisc change
Parameters
struct tty_struct *tty: tty to recoverstruct tty_ldisc *old: previous ldisc
Description
Restore the previous line discipline or N_TTY when a line discipline change
fails due to an open error
tty_ldisc_kill() #
void teardown ldisc
Parameters
struct tty_struct *tty: tty being released
Description
Perform final close of the ldisc and reset tty->ldisc
tty_reset_termios() #
void reset terminal state
Parameters
struct tty_struct *tty: tty to reset
Description
Restore a terminal to the driver default state.
tty_ldisc_reinit() #
int reinitialise the tty ldisc
Parameters
struct tty_struct *tty: tty to reinitint disc: line discipline to reinitialize
Description
Completely reinitialize the line discipline state, by closing the current
instance, if there is one, and opening a new instance. If an error occurs
opening the new non-N_TTY instance, the instance is dropped and tty->ldisc
reset to NULL. The caller can then retry with N_TTY instead.
Return
0 if successful, otherwise error code < 0
tty_ldisc_hangup() #
void hangup ldisc reset
Parameters
struct tty_struct *tty: tty being hung upbool reinit: whether to re-initialise the tty
Description
Some tty devices reset their termios when they receive a hangup event. In
that situation we must also switch back to N_TTY properly before we reset
the termios data.
Locking: We can take the ldisc mutex as the rest of the code is careful to allow for this.
In the pty pair case this occurs in the close() path of the tty itself so we
must be careful about locking rules.
tty_ldisc_setup() #
int open line discipline
Parameters
struct tty_struct *tty: tty being shut downstruct tty_struct *o_tty: pair tty for pty/tty pairs
Description
Called during the initial open of a tty/pty pair in order to set up the line disciplines and bind them to the tty. This has no locking issues as the device isn't yet active.
tty_ldisc_release() #
void release line discipline
Parameters
struct tty_struct *tty: tty being shut down (or one end of pty pair)
Description
Called during the final close of a tty or a pty pair in order to shut down
the line discpline layer. On exit, each tty's ldisc is NULL.
tty_ldisc_init() #
int ldisc setup for new tty
Parameters
struct tty_struct *tty: tty being allocated
Description
Set up the line discipline objects for a newly allocated tty. Note that the tty structure is not completely set up when this call is made.
tty_ldisc_deinit() #
void ldisc cleanup for new tty
Parameters
struct tty_struct *tty: tty that was allocated recently
Description
The tty structure must not be completely set up (tty_ldisc_setup()) when
this call is made.
TTY Port
Peios Kernel / Hardware and drivers / Driver development / TTY
The TTY drivers are advised to use struct tty_port helpers as much as possible. If the drivers implement tty_port.ops.activate() and tty_port.ops.shutdown(), they can use tty_port_open(), tty_port_close(), and tty_port_hangup() in respective tty_struct.ops hooks.
The reference and details are contained in the TTY Port Reference and TTY Port Operations Reference sections at the bottom.
TTY Port Functions #
Init & Destroy #
tty_port_init() #
void initialize tty_port
Parameters
struct tty_port *port: tty_port to initialize
Description
Initializes the state of struct tty_port. When a port was initialized using
this function, one has to destroy the port by tty_port_destroy(). Either
indirectly by using tty_port refcounting (tty_port_put()) or directly if
refcounting is not used.
tty_port_destroy() #
void destroy inited port
Parameters
struct tty_port *port: tty port to be destroyed
Description
When a port was initialized using tty_port_init(), one has to destroy the
port by this function. Either indirectly by using tty_port refcounting
(tty_port_put()) or directly if refcounting is not used.
tty_port_put() #
void drop a reference to tty_port
Parameters
struct tty_port *port: port to drop a reference of (can be NULL)
Description
The final put will destroy and free up the port using
port->ops->destruct() hook, or using kfree() if not provided.
Open/Close/Hangup Helpers #
tty_port_shutdown() #
void internal helper to shutdown the device
Parameters
struct tty_port *port: tty port to be shut downstruct tty_struct *tty: the associated tty
Description
It is used by tty_port_hangup() and tty_port_close(). Its task is to
shutdown the device if it was initialized (note consoles remain
functioning). It lowers DTR/RTS (if tty has HUPCL set) and invokes
port->ops->shutdown().
tty_port_hangup() #
void hangup helper
Parameters
struct tty_port *port: tty port
Description
Perform port level tty hangup flag and count changes. Drop the tty reference.
Caller holds tty lock.
tty_port_block_til_ready() #
int Waiting logic for tty open
Parameters
struct tty_port *port: the tty port being openedstruct tty_struct *tty: the tty device being boundstruct file *filp: the file pointer of the opener orNULL
Description
Implement the core POSIX/SuS tty behaviour when opening a tty device. Handles:
- hangup (both before and during)
- non blocking open
- rts/dtr/dcd
- signals
- port flags and counts
The passed port must implement the port->ops->carrier_raised method if it can do carrier detect and the port->ops->dtr_rts method if it supports software management of these lines. Note that the dtr/rts raise is done each iteration as a hangup may have previously dropped them while we wait.
Caller holds tty lock.
Note
May drop and reacquire tty lock when blocking, so tty and port may have changed state (eg., may have been hung up).
tty_port_close_start() #
int helper for tty->ops->close, part 1/2
Parameters
struct tty_port *port: tty_port of the devicestruct tty_struct *tty: tty being closedstruct file *filp: passed file pointer
Description
Decrements and checks open count. Flushes the port if this is the last
close. That means, dropping the data from the outpu buffer on the device and
waiting for sending logic to finish. The rest of close handling is performed
in tty_port_close_end().
Locking: Caller holds tty lock.
Return
1 if this is the last close, otherwise 0
tty_port_close_end() #
void helper for tty->ops->close, part 2/2
Parameters
struct tty_port *port: tty_port of the devicestruct tty_struct *tty: tty being closed
Description
This is a continuation of the first part: tty_port_close_start(). This
should be called after turning off the device. It flushes the data from the
line discipline and delays the close by port->close_delay.
Locking: Caller holds tty lock.
tty_port_close() #
void generic tty->ops->close handler
Parameters
struct tty_port *port: tty_port of the devicestruct tty_struct *tty: tty being closedstruct file *filp: passed file pointer
Description
It is a generic helper to be used in driver's tty->ops->close. It wraps a
sequence of tty_port_close_start(), tty_port_shutdown(), and
tty_port_close_end(). The latter two are called only if this is the last
close. See the respective functions for the details.
Locking: Caller holds tty lock
tty_port_install() #
int generic tty->ops->install handler
Parameters
struct tty_port *port: tty_port of the devicestruct tty_driver *driver: tty_driver for this devicestruct tty_struct *tty: tty to be installed
Description
It is the same as tty_standard_install() except the provided port is linked
to a concrete tty specified by tty. Use this or tty_port_register_device()
(or both). Call tty_port_link_device() as a last resort.
tty_port_open() #
int generic tty->ops->open handler
Parameters
struct tty_port *port: tty_port of the devicestruct tty_struct *tty: tty to be openedstruct file *filp: passed file pointer
Description
It is a generic helper to be used in driver's tty->ops->open. It activates
the devices using port->ops->activate if not active already. And waits for
the device to be ready using tty_port_block_til_ready() (e.g. raises
DTR/CTS and waits for carrier).
Note that port->ops->shutdown is not called when port->ops->activate returns an error (on the contrary, tty->ops->close is).
Locking: Caller holds tty lock.
Note
may drop and reacquire tty lock (in tty_port_block_til_ready()) so
tty and port may have changed state (eg., may be hung up now).
TTY Refcounting #
tty_port_tty_get() #
struct tty_struct * get a tty reference
Parameters
struct tty_port *port: tty port
Description
Return a refcount protected tty instance or NULL if the port is not
associated with a tty (eg due to close or hangup).
tty_port_tty_set() #
void set the tty of a port
Parameters
struct tty_port *port: tty portstruct tty_struct *tty: the tty
Description
Associate the port and tty pair. Manages any internal refcounts. Pass NULL
to deassociate a port.
TTY Helpers #
tty_port_tty_hangup() #
void helper to hang up a tty asynchronously
Parameters
struct tty_port *port: tty portbool check_clocal: hang only ttys withCLOCALunset?
tty_port_tty_vhangup() #
void helper to hang up a tty synchronously
Parameters
struct tty_port *port: tty port
tty_port_tty_wakeup() #
void helper to wake up a tty
Parameters
struct tty_port *port: tty port
Modem Signals #
tty_port_carrier_raised() #
bool carrier raised check
Parameters
struct tty_port *port: tty port
Description
Wrapper for the carrier detect logic. For the moment this is used to hide some internal details. This will eventually become entirely internal to the tty port.
tty_port_raise_dtr_rts() #
void Raise DTR/RTS
Parameters
struct tty_port *port: tty port
Description
Wrapper for the DTR/RTS raise logic. For the moment this is used to hide some internal details. This will eventually become entirely internal to the tty port.
tty_port_lower_dtr_rts() #
void Lower DTR/RTS
Parameters
struct tty_port *port: tty port
Description
Wrapper for the DTR/RTS raise logic. For the moment this is used to hide some internal details. This will eventually become entirely internal to the tty port.
TTY Port Reference #
struct tty_port #
- port level information
Definition
;
Members
-
buf: buffer for this port, locked internally -
tty: back pointer tostruct tty_struct, valid only if the tty is open. Usetty_port_tty_get()to obtain it (andtty_kref_put()to release). -
itty: internal back pointer tostruct tty_struct. Avoid this. It should be eliminated in the long term. -
ops: tty port operations (like activate, shutdown), seestruct tty_port_operations -
client_ops: tty port client operations (like receive_buf, write_wakeup). By default, tty_port_default_client_ops is used. -
lock: lock protecting tty -
blocked_open: # of procs waiting for open intty_port_block_til_ready() -
count: usage count -
open_wait: open waiters queue (waiting e.g. for a carrier) -
delta_msr_wait: modem status change queue (waiting for MSR changes) -
flags: user TTY flags (ASYNC_) -
iflags: internal flags (TTY_PORT_) -
console: when set, the port is a console -
mutex: locking, for open, shutdown and other port operations -
buf_mutex:xmit_buf alloc lock
-
xmit_buf: optional xmit buffer used by some drivers -
xmit_fifo: optional xmit buffer used by some drivers -
close_delay: delay in jiffies to wait when closing the port -
closing_wait: delay in jiffies for output to be sent before closing -
drain_delay: set to zero if no pure time based drain is needed else set to size of fifo -
kref: references counter. Reaching zero calls ops->destruct() if non-NULLor frees the port otherwise. -
client_data: pointer to private data, for client_ops
Description
Each device keeps its own port level information. struct tty_port was
introduced as a common structure for such information. As every TTY device
shall have a backing tty_port structure, every driver can use these members.
The tty port has a different lifetime to the tty so must be kept apart. In addition be careful as tty -> port mappings are valid for the life of the tty object but in many cases port -> tty mappings are valid only until a hangup so don't use the wrong path.
Tty port shall be initialized by tty_port_init() and shut down either by
tty_port_destroy() (refcounting not used), or tty_port_put() (refcounting).
There is a lot of helpers around struct tty_port too. To name the most
significant ones: tty_port_open(), tty_port_close() (or
tty_port_close_start() and tty_port_close_end() separately if need be), and
tty_port_hangup(). These call ops->activate() and ops->shutdown() as
needed.
TTY Port Operations Reference #
struct tty_port_operations #
- operations on tty_port
Definition
;
Members
carrier_raised: return true if the carrier is raised on portdtr_rts: raise the DTR line if active is true, otherwise lower DTRshutdown: called when the last close completes or a hangup finishes IFF the port was initialized. Do not use to free resources. Turn off the device only. Called under the port mutex to serialize against activate and shutdown.activate: called under the port mutex fromtty_port_open(), serialized using the port mutex. Supposed to turn on the device.destruct: called on the final put of a port. Free resources, possibly incl. the port itself.
Description
FIXME: long term getting the tty argument out of this would be good for consoles.
TTY Struct
Peios Kernel / Hardware and drivers / Driver development / TTY
struct tty_struct is allocated by the TTY layer upon the first open of the TTY device and released after the last close. The TTY layer passes this structure to most of struct tty_operation's hooks. Members of tty_struct are documented in TTY Struct Reference at the bottom.
Initialization #
tty_init_termios() #
void helper for termios setup
Parameters
struct tty_struct *tty: the tty to set up
Description
Initialise the termios structure for this tty. This runs under the
tty_mutex currently so we can be relaxed about ordering.
Name #
tty_name() #
const char * return tty naming
Parameters
const struct tty_struct *tty: tty structure
Description
Convert a tty structure into a name. The name reflects the kernel naming policy and if udev is in use may not reflect user space
Locking: none
Reference counting #
tty_kref_get() #
struct tty_struct * get a tty reference
Parameters
struct tty_struct *tty: tty device
Return
a new reference to a tty object
Description
Locking: The caller must hold sufficient locks/counts to ensure that their existing reference cannot go away.
tty_kref_put() #
void release a tty kref
Parameters
struct tty_struct *tty: tty device
Description
Release a reference to the tty device and if need be let the kref layer destruct the object for us.
Install #
tty_standard_install() #
int usual tty->ops->install
Parameters
struct tty_driver *driver: the driver for the ttystruct tty_struct *tty: the tty
Description
If the driver overrides tty->ops->install, it still can call this function to perform the standard install operations.
Read & Write #
tty_put_char() #
int write one character to a tty
Parameters
struct tty_struct *tty: ttyu8 ch: character to write
Description
Write one byte to the tty using the provided tty->ops->put_char() method if present.
Note
the specific put_char operation in the driver layer may go away soon. Don't call it directly, use this method
Return
the number of characters successfully output.
Start & Stop #
stop_tty() #
void propagate flow control
Parameters
struct tty_struct *tty: tty to stop
Description
Perform flow control to the driver. May be called on an already stopped
device and will not re-call the tty_driver->stop() method.
This functionality is used by both the line disciplines for halting incoming
flow and by the driver. It may therefore be called from any context, may be
under the tty atomic_write_lock but not always.
- Locking: flow.lock
start_tty() #
void propagate flow control
Parameters
struct tty_struct *tty: tty to start
Description
Start a tty that has been stopped if at all possible. If tty was previously
stopped and is now being started, the tty_driver->start() method is invoked
and the line discipline woken.
- Locking: flow.lock
Wakeup #
tty_wakeup() #
void request more data
Parameters
struct tty_struct *tty: terminal
Description
Internal and external helper for wakeups of tty. This function informs the line discipline if present that the driver is ready to receive more output data.
Hangup #
tty_hangup() #
void trigger a hangup event
Parameters
struct tty_struct *tty: tty to hangup
Description
A carrier loss (virtual or otherwise) has occurred on tty. Schedule a hangup sequence to run after this event.
tty_vhangup() #
void process vhangup
Parameters
struct tty_struct *tty: tty to hangup
Description
The user has asked via system call for the terminal to be hung up. We do this synchronously so that when the syscall returns the process is complete. That guarantee is necessary for security reasons.
tty_hung_up_p() #
int was tty hung up
Parameters
struct file *filp: file pointer of tty
Return
true if the tty has been subject to a vhangup or a carrier loss
Misc #
tty_do_resize() #
int resize event
Parameters
struct tty_struct *tty: tty being resizedstruct winsize *ws: new dimensions
Description
Update the termios variables and send the necessary signals to peform a terminal resize correctly.
TTY Struct Flags #
enum tty_struct_flags #
TTY Struct Flags
Constants
TTY_THROTTLED: Driver input is throttled. The ldisc should calltty_driver.unthrottle()in order to resume reception when it is ready to process more data (at threshold min).TTY_IO_ERROR: If set, causes all subsequent userspace read/write calls on the tty to fail, returning -EIO. (May be no ldisc too.)TTY_OTHER_CLOSED: Device is a pty and the other side has closed.TTY_EXCLUSIVE: Exclusive open mode (a single opener).TTY_DO_WRITE_WAKEUP: If set, causes the driver to call thetty_ldisc_ops.write_wakeup()method in order to resume transmission when it can accept more data to transmit.TTY_LDISC_OPEN: Indicates that a line discipline is open. For debugging purposes only.TTY_PTY_LOCK: A flag private to pty code to implementTIOCSPTLCK/TIOCGPTLCKlogic.TTY_NO_WRITE_SPLIT: Prevent driver from splitting up writes into smaller chunks (preserve write boundaries to driver).TTY_HUPPED: The TTY was hung up. This is set posttty_driver.hangup().TTY_HUPPING: The TTY is in the process of hanging up to abort potential readers.TTY_LDISC_CHANGING: Line discipline for this TTY is being changed. I/O should not block when this is set. Usetty_io_nonblock()to check.TTY_LDISC_HALTED: Line discipline for this TTY was stopped. No work should be queued to this ldisc.
Description
These bits are used in the tty_struct.flags field.
So that interrupts won't be able to mess up the queues,
copy_to_cooked must be atomic with respect to itself, as must
tty->write. Thus, you must use the inline functions set_bit() and
clear_bit() to make things atomic.
TTY Struct Reference #
struct tty_struct #
state associated with a tty while open
Definition
;
Members
kref: reference counting bytty_kref_get()andtty_kref_put(), reaching zero frees the structureindex: index of this tty (e.g. to construct name like tty12)dev: class device orNULL(e.g. ptys, serdev)driver:struct tty_driveroperating this ttyport: persistent storage for this device (i.e.struct tty_port)ops:struct tty_operationsof driver for this tty (open, close, etc.)ldisc: the current line discipline for this tty (n_tty by default)ldisc_sem: protects line discipline changes (ldisc) -- lock tty not ptyatomic_write_lock: protects against concurrent writers, i.e. locks write_cnt, write_buf and similarlegacy_mutex: leftover from history (BKL -> BTM -> legacy_mutex), protecting several operations on this ttythrottle_mutex: protects against concurrenttty_throttle_safe()andtty_unthrottle_safe()(but nottty_unthrottle())termios_rwsem: protects termios and termios_lockedwinsize_mutex: protects winsizetermios: termios for the current tty, copied from/to driver.termiostermios_locked: locked termios (byTIOCGLCKTRMIOSandTIOCSLCKTRMIOSioctls)name: name of the tty constructed bytty_line_name()(e.g. ttyS3)flags: bitwise OR ofTTY_THROTTLED,TTY_IO_ERROR, ...count: count of open processes, reaching zero cancels all the work for this tty and drops a kref too (but does not free this tty)receive_room: bytes permitted to feed to ldisc without any being lostwinsize: size of the terminal "window" (cf. winsize_mutex)flow: flow settings grouped togetherflow.lock: lock for flow membersflow.stopped: tty stopped/started bystop_tty()/start_tty()flow.tco_stopped: tty stopped/started byTCOOFF/TCOONioctls (it has precedence over flow.stopped)ctrl: control settings grouped togetherctrl.pgrp: process group of this tty (setpgrp(2))ctrl.session: session of this tty (setsid(2)). Writes are protected by both ctrl.lock and legacy_mutex, readers must use at least one of them.ctrl.lock: lock for ctrl membersctrl.pktstatus: packet mode status (bitwise OR ofTIOCPKT_constants)ctrl.packet: packet mode enabledhw_stopped: not controlled by the tty layer, under driver's control for CTS handlingclosing: when set during close, n_tty processes only START & STOP charsflow_change: controls behavior of throttling, seetty_throttle_safe()andtty_unthrottle_safe()link: link to another pty (master -> slave and vice versa)fasync: state forO_ASYNC(forSIGIO); managed byfasync_helper()write_wait: concurrent writers are waiting in this queue until they are allowed to writeread_wait: readers wait for data in this queuehangup_work: normally a work to perform a hangup (do_tty_hangup()); while freeing the tty, (re)used torelease_one_tty()disc_data: pointer to ldisc's private data (e.g. tostruct n_tty_data)driver_data: pointer to driver's private data (e.g.struct uart_state)files_lock: protects tty_files listwrite_cnt: count of bytes written intty_write()to write_bufwrite_buf: temporary buffer used duringtty_write()to copy user data totty_files: list of (re)openers of this tty (i.e. linkedstruct tty_file_private)SAK_work: if the tty has a pending do_SAK, it is queued here
Description
All of the state associated with a tty while the tty is open. Persistent
storage for tty devices is referenced here as port and is documented in
struct tty_port.