# TTY

---

# 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).

<a id="rst-tty"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Teletypewriter (TTY) layer takes care of all those serial devices. Including the virtual ones like pseudoterminal (PTY).

<a id="rst-tty-structures"></a>

## 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](</kernel/hardware/driver-api/tty/tty-ldisc.md>) (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](</kernel/hardware/driver-api/tty/tty-driver.md>)
- [TTY Port](</kernel/hardware/driver-api/tty/tty-port.md>)
- [TTY Struct](</kernel/hardware/driver-api/tty/tty-struct.md>)
- [TTY Line Discipline](</kernel/hardware/driver-api/tty/tty-ldisc.md>)
- [TTY Buffer](</kernel/hardware/driver-api/tty/tty-buffer.md>)
- [TTY IOCTL Helpers](</kernel/hardware/driver-api/tty/tty-ioctl.md>)
- [TTY Internals](</kernel/hardware/driver-api/tty/tty-internals.md>)
- [Console](</kernel/hardware/driver-api/tty/console.md>)

<a id="rst-writing-tty-driver"></a>

## Writing TTY Driver

Before one starts writing a TTY driver, they must consider [Serial](</kernel/hardware/driver-api/serial/driver.md>) and [USB Serial](</kernel/hardware/usb/usb-serial.md>) 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:

1. Allocate and register a TTY driver (module init)

2. Create and register TTY devices as they are probed (probe function)

3. Handle TTY operations and events like interrupts (TTY core invokes the former, the device the latter)

4. Remove devices as they are going away (remove function)

5. 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](</kernel/hardware/driver-api/tty/tty-driver.md>). For the other two (devices handling), look into [TTY Port](</kernel/hardware/driver-api/tty/tty-port.md>).

<a id="rst-other-documentation"></a>

## Other Documentation

Miscellaneous documentation can be further found in these documents:

- [MOXA Smartio/Industio Family Device Driver Installation Guide](</kernel/hardware/driver-api/tty/moxa-smartio.md>)
- [GSM 0710 tty multiplexor HOWTO](</kernel/hardware/driver-api/tty/n-gsm.md>)
- [N_TTY](</kernel/hardware/driver-api/tty/n-tty.md>)

---

# Console

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> Struct Console

<a id="rst-console"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-struct-console"></a>

## Struct Console


#### <a id="c-enum-cons_flags"></a>`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 via `syslog()` 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`: The `write_atomic()` callback is not safe and is
  therefore only used by `nbcon_atomic_flush_unsafe()`.

#### <a id="c-struct-console"></a>`struct console`

The console descriptor structure

**Definition**

```c
struct console {
    char name[16];
    void (*write)(struct console *co, const char *s, unsigned int count);
    int (*read)(struct console *co, char *s, unsigned int count);
    struct tty_driver       *(*device)(struct console *co, int *index);
    void (*unblank)(void);
    int (*setup)(struct console *co, char *options);
    int (*exit)(struct console *co);
    int (*match)(struct console *co, char *name, int idx, char *options);
    short flags;
    short index;
    int cflag;
    uint ispeed;
    uint ospeed;
    u64 seq;
    unsigned long           dropped;
    void *data;
    struct hlist_node       node;
    void (*write_atomic)(struct console *con, struct nbcon_write_context *wctxt);
    void (*write_thread)(struct console *con, struct nbcon_write_context *wctxt);
    void (*device_lock)(struct console *con, unsigned long *flags);
    void (*device_unlock)(struct console *con, unsigned long flags);
    atomic_t nbcon_state;
    atomic_long_t nbcon_seq;
    struct nbcon_context  nbcon_device_ctxt;
    atomic_long_t nbcon_prev_seq;
    struct printk_buffers   *pbufs;
    struct task_struct      *kthread;
    struct rcuwait          rcuwait;
    struct irq_work         irq_work;
};
```

**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()` and `nbcon_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 with

    the preemption enabled, see `nbcon_owner_matches()`. But it
    can be safe when always called in the preemptive context
    under the `device_lock()`.

  - \[**\] The `device_lock()` makes sure that `nbcon_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()`](/kernel/internals/core-api/printk-basics.md#c-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


<a id="rst-internals"></a>

### Internals


#### <a id="c-struct-nbcon_state"></a>`struct nbcon_state`

console state for nbcon consoles

**Definition**

```c
struct nbcon_state {
    union {
        unsigned int    atom;
        struct {
            unsigned int prio               :  2;
            unsigned int req_prio           :  2;
            unsigned int unsafe             :  1;
            unsigned int unsafe_takeover    :  1;
            unsigned int cpu                : 24;
        };
    };
};
```

**Members**

- `{unnamed_union}`: anonymous
- `atom`: Compound of the state fields for atomic operations
- `{unnamed_struct}`: anonymous
- `prio`: The priority of the current owner
- `req_prio`: The priority of a handover request
- `unsafe`: Console is busy in a non takeover region
- `unsafe_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.

#### <a id="c-enum-nbcon_prio"></a>`enum nbcon_prio`

console owner priority for nbcon consoles

**Constants**

- `NBCON_PRIO_NONE`: Unused
- `NBCON_PRIO_NORMAL`: Normal (non-emergency) usage
- `NBCON_PRIO_EMERGENCY`: Emergency output (WARN/OOPS...)
- `NBCON_PRIO_PANIC`: Panic output
- `NBCON_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).

#### <a id="c-struct-nbcon_context"></a>`struct nbcon_context`

Context for console acquire/release

**Definition**

```c
struct nbcon_context {
    struct console          *console;
    unsigned int            spinwait_max_us;
    enum nbcon_prio         prio;
    unsigned int            allow_unsafe_takeover   : 1;
    unsigned int            backlog                 : 1;
    struct printk_buffers   *pbufs;
    u64 seq;
};
```

**Members**

- `console`: The associated console
- `spinwait_max_us`: Limit for spin-wait acquire
- `prio`: Priority of the context
- `allow_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 records
- `pbufs`: Pointer to the text buffer for this context
- `seq`: The sequence number to print for this context

#### <a id="c-struct-nbcon_write_context"></a>`struct nbcon_write_context`

Context handed to the nbcon write callbacks

**Definition**

```c
struct nbcon_write_context {
        struct nbcon_context  ctxt;
        char *outbuf;
        unsigned int            len;
        bool unsafe_takeover;
    #ifdef CONFIG_PRINTK_EXECUTION_CTX;
        int cpu;
        pid_t pid;
        char comm[TASK_COMM_LEN];
    #endif;
};
```

**Members**

- `ctxt`: The core console context
- `outbuf`: Pointer to the text buffer for output
- `len`: Length to write
- `unsafe_takeover`: If a hostile takeover in an unsafe state has occurred
- `cpu`: CPU on which the message was generated
- `pid`: PID of the task that generated the message
- `comm`: Name of the task that generated the message


<a id="rst-struct-consw"></a>

## Struct Consw


#### <a id="c-struct-consw"></a>`struct consw`

callbacks for consoles

**Definition**

```c
struct consw {
    struct module *owner;
    const char *(*con_startup)(void);
    void (*con_init)(struct vc_data *vc, bool init);
    void (*con_deinit)(struct vc_data *vc);
    void (*con_clear)(struct vc_data *vc, unsigned int y, unsigned int x, unsigned int count);
    void (*con_putc)(struct vc_data *vc, u16 ca, unsigned int y, unsigned int x);
    void (*con_putcs)(struct vc_data *vc, const u16 *s, unsigned int count, unsigned int ypos, unsigned int xpos);
    void (*con_cursor)(struct vc_data *vc, bool enable);
    bool (*con_scroll)(struct vc_data *vc, unsigned int top, unsigned int bottom, enum con_scroll dir, unsigned int lines);
    bool (*con_switch)(struct vc_data *vc);
    bool (*con_blank)(struct vc_data *vc, enum vesa_blank_mode blank, bool mode_switch);
    int (*con_font_set)(struct vc_data *vc, const struct console_font *font, unsigned int vpitch, unsigned int flags);
    int (*con_font_get)(struct vc_data *vc, struct console_font *font, unsigned int vpitch);
    int (*con_font_default)(struct vc_data *vc, struct console_font *font, const char *name);
    int (*con_resize)(struct vc_data *vc, unsigned int width, unsigned int height, bool from_user);
    void (*con_set_palette)(struct vc_data *vc, const unsigned char *table);
    void (*con_scrolldelta)(struct vc_data *vc, int lines);
    bool (*con_set_origin)(struct vc_data *vc);
    void (*con_save_screen)(struct vc_data *vc);
    u8 (*con_build_attr)(struct vc_data *vc, u8 color, enum vc_intensity intensity, bool blink, bool underline, bool reverse, bool italic);
    void (*con_invert_region)(struct vc_data *vc, u16 *p, int count);
};
```

**Members**

- `owner`: the module to get references of when this console is used
- `con_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 **enable**
- `con_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
  be `KD_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 be `NULL` or 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 (see `vc_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)


<a id="rst-console-functions"></a>

## Console functions


#### <a id="c-console_srcu_read_flags"></a>`console_srcu_read_flags()`

```c
short console_srcu_read_flags(const struct console *con)
```

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.

#### <a id="c-console_srcu_write_flags"></a>`console_srcu_write_flags()`

```c
void console_srcu_write_flags(struct console *con, short flags)
```

Write flags for a registered console

**Parameters**

- `struct console *con`: struct console pointer of console to write flags to
- `short 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.

#### <a id="c-for_each_console_srcu"></a>`for_each_console_srcu()`

```c
for_each_console_srcu(con)
```

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.

#### <a id="c-for_each_console"></a>`for_each_console()`

```c
for_each_console(con)
```

Iterator over registered consoles

**Parameters**

- `con`: struct console pointer used as loop cursor

**Description**

The console list and the [`console.flags`](#c-struct-console) are immutable while iterating.

Requires console_list_lock to be held.



#### <a id="c-clear_selection"></a>`clear_selection()`

```c
void 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.



#### <a id="c-__vc_resize"></a>`__vc_resize()`

```c
int __vc_resize(struct vc_data *vc, unsigned int cols, unsigned int rows, bool from_user)
```

resize a VT

**Parameters**

- `struct vc_data *vc`: virtual console
- `unsigned int cols`: columns
- `unsigned int rows`: rows
- `bool 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()`](#c-vc_do_resize) method to update the structures.

Locking: The caller must hold the console sem to protect console internals
and **vc->port.tty**.

#### <a id="c-con_is_bound"></a>`con_is_bound()`

```c
int con_is_bound(const struct consw *csw)
```

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()`](#c-struct-consw)

#### <a id="c-con_is_visible"></a>`con_is_visible()`

```c
bool con_is_visible(const struct vc_data *vc)
```

checks whether the current console is visible

**Parameters**

- `const struct vc_data *vc`: virtual console

**Return**

zero if not visible, nonzero if visible

#### <a id="c-con_debug_enter"></a>`con_debug_enter()`

```c
void con_debug_enter(struct vc_data *vc)
```

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.

#### <a id="c-con_debug_leave"></a>`con_debug_leave()`

```c
void 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.

#### <a id="c-do_unregister_con_driver"></a>`do_unregister_con_driver()`

```c
int do_unregister_con_driver(const struct consw *csw)
```

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.


<a id="rst-internals-1"></a>

### Internals


#### <a id="c-sel_loadlut"></a>`sel_loadlut()`

```c
int sel_loadlut(u32 __user *lut)
```

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.

#### <a id="c-set_selection_user"></a>`set_selection_user()`

```c
int set_selection_user(const struct tiocl_selection __user *sel, struct tty_struct *tty)
```

set the current selection.

**Parameters**

- `const struct tiocl_selection __user *sel`: user selection info
- `struct 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.



#### <a id="c-vc_do_resize"></a>`vc_do_resize()`

```c
int vc_do_resize(struct tty_struct *tty, struct vc_data *vc, unsigned int cols, unsigned int lines, bool from_user)
```

resizing method for the tty

**Parameters**

- `struct tty_struct *tty`: tty being resized
- `struct vc_data *vc`: virtual console private data
- `unsigned int cols`: columns
- `unsigned int lines`: lines
- `bool 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.

#### <a id="c-vt_resize"></a>`vt_resize()`

```c
int vt_resize(struct tty_struct *tty, struct winsize *ws)
```

resize a VT

**Parameters**

- `struct tty_struct *tty`: tty to resize
- `struct 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.

#### <a id="c-enum-vc_ctl_state"></a>`enum vc_ctl_state`

control characters state of a vt

**Constants**

- `ESnormal`: initial state, no control characters parsed
- `ESesc`: ESC parsed
- `ESsquare`: CSI parsed -- modifiers/parameters/ctrl chars expected
- `ESgetpars`: CSI parsed -- parameters/ctrl chars expected
- `ESfunckey`: CSI \[ parsed
- `EShash`: ESC # parsed
- `ESsetG0`: ESC ( parsed
- `ESsetG1`: ESC ) parsed
- `ESpercent`: ESC % parsed
- `EScsiignore`: CSI \[0x20-0x3f\] parsed
- `ESnonstd`: OSC parsed
- `ESpalette`: OSC P parsed
- `ESosc`: OSC \[0-9\] parsed
- `ESANSI_first`: first state for ignoring ansi control sequences
- `ESapc`: ESC _ parsed
- `ESpm`: ESC ^ parsed
- `ESdcs`: ESC P parsed
- `ESANSI_last`: last state for ignoring ansi control sequences

#### <a id="c-vc_sanitize_unicode"></a>`vc_sanitize_unicode()`

```c
int vc_sanitize_unicode(const int c)
```

Replace invalid Unicode code points with `U+FFFD`

**Parameters**

- `const int c`: the received code point

#### <a id="c-vc_translate_unicode"></a>`vc_translate_unicode()`

```c
int vc_translate_unicode(struct vc_data *vc, int c, bool *rescan)
```

Combine UTF-8 into Unicode in `vc_data.vc_utf_char`

**Parameters**

- `struct vc_data *vc`: virtual console
- `int c`: UTF-8 byte to translate
- `bool *rescan`: set to true iff **c** wasn't consumed here and needs to be re-processed

**Description**

* `vc_data.vc_utf_char` is the being-constructed Unicode code point.
* `vc_data.vc_utf_count` is the number of continuation bytes still expected to
  arrive.
* `vc_data.vc_npar` is 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+FFFD` is the resulting code point. `U+FFFD` is valid,
  `REPLACEMENT CHARACTER`.
* otherwise - Input OK, **c** consumed, resulting code point returned.

#### <a id="c-vt_kmsg_redirect"></a>`vt_kmsg_redirect()`

```c
int vt_kmsg_redirect(int new)
```

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

<a id="rst-moxa-smartio-industio-family-device-driver-installation-guide"></a>

Copyright (C) 2008, Moxa Inc. Copyright (C) 2021, Jiri Slaby

<!-- Content

1. Introduction
2. System Requirement
3. Installation
   3.1 Hardware installation
   3.2 Device naming convention
4. Utilities
5. Setserial
6. Troubleshooting -->

<a id="rst-introduction"></a>

## 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](<mailto: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/](<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

<a id="rst-system-requirement"></a>

## 2. System Requirement

> - Maximum 4 boards can be installed in combination

<a id="rst-installation"></a>

## 3. Installation

<a id="rst-hardware-installation"></a>

### 3.1 Hardware installation

<a id="rst-pci-upci-board"></a>

#### 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.

<a id="rst-pci-irq-sharing"></a>

#### 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.

<a id="rst-device-naming-convention"></a>

### 3.2 Device naming convention

> The device node is named "ttyMxx".

<a id="rst-device-naming-when-more-than-2-boards-installed"></a>

#### Device naming when more than 2 boards installed

> Naming convention for each Smartio/Industio multiport board is pre-defined as below.
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> Board Num.
>
> </td>
> <td>
>
>
> Device node
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1st board
>
> </td>
> <td>
>
>
> ttyM0  - ttyM7
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2nd board
>
> </td>
> <td>
>
>
> ttyM8  - ttyM15
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3rd board
>
> </td>
> <td>
>
>
> ttyM16 - ttyM23
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4th board
>
> </td>
> <td>
>
>
> ttyM24 - ttyM31
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-utilities"></a>

## 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.

<a id="rst-msdiag-diagnostic"></a>

### msdiag - Diagnostic

> This utility provides the function to display what Moxa Smartio/Industio board was found by the driver in the system.

<a id="rst-msmon-port-monitoring"></a>

### 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 &lt;HOME&gt; key. &lt;+&gt; &lt;-&gt; (plus/minus) keys to change the displaying time interval. Press &lt;ENTER&gt; on the port, that cursor stay, to view the port's communication parameters, signal status, and input/output queue.

<a id="rst-msterm-terminal-emulation"></a>

### 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.

<a id="rst-setserial"></a>

## 5. Setserial

> Supported Setserial parameters are listed as below.
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> uart
>
> </td>
> <td>
>
>
> set UART type(16450 --&gt; disable FIFO, 16550A --&gt; enable FIFO)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> close_delay
>
> </td>
> <td>
>
>
> set the amount of time (in 1/100 of a second) that DTR should be kept low while being closed.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> closing_wait
>
> </td>
> <td>
>
>
> 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.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_hi
>
> </td>
> <td>
>
>
> Use 57.6kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_vhi
>
> </td>
> <td>
>
>
> Use 115.2kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_shi
>
> </td>
> <td>
>
>
> Use 230.4kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_warp
>
> </td>
> <td>
>
>
> Use 460.8kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_normal
>
> </td>
> <td>
>
>
> Use 38.4kb when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> spd_cust
>
> </td>
> <td>
>
>
> Use the custom divisor to set the speed when the application requests 38.4kb.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> divisor
>
> </td>
> <td>
>
>
> This option sets the custom division.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> baud_base
>
> </td>
> <td>
>
>
> This option sets the base baud rate.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-troubleshooting"></a>

## 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_

> How to use it

<a id="rst-gsm-0710-tty-multiplexor-howto"></a>

<a id="rst-contents"></a>



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](<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.

<a id="rst-how-to-use-it"></a>

## How to use it

<a id="rst-config-initiator"></a>

### Config Initiator

1. 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.

2. Switch the serial line to using the n_gsm line discipline by using `TIOCSETD` ioctl.

3. Configure the mux using `GSMIOC_GETCONF_EXT`/`GSMIOC_SETCONF_EXT` ioctl if needed.

4. Configure the mux using `GSMIOC_GETCONF`/`GSMIOC_SETCONF` ioctl.

5. Configure DLCs using `GSMIOC_GETCONF_DLCI`/`GSMIOC_SETCONF_DLCI` ioctl for non-defaults.

6. 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):



   ```text
   #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();
   ```

7. 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`

8. 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:



   ```text
   0xf9, 0x03, 0xef, 0x03, 0xc3, 0x16, 0xf9
   ```

<a id="rst-config-requester"></a>

### Config Requester

1. Receive `AT+CMUX=` command through its serial port, initialize mux mode config.

2. Switch the serial line to using the *n_gsm* line discipline by using `TIOCSETD` ioctl.

3. Configure the mux using `GSMIOC_GETCONF_EXT`/`GSMIOC_SETCONF_EXT` ioctl if needed.

4. Configure the mux using `GSMIOC_GETCONF`/`GSMIOC_SETCONF` ioctl.

5. Configure DLCs using `GSMIOC_GETCONF_DLCI`/`GSMIOC_SETCONF_DLCI` ioctl for non-defaults.

6. Obtain base gsmtty number for the used serial port:



   ```text
   #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 - &lt;[eric@eukrea.com](<mailto:eric@eukrea.com>)&gt;

---

# N_TTY

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> External Functions

<a id="rst-n-tty"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



The default (and fallback) [TTY line discipline](</kernel/hardware/driver-api/tty/tty-ldisc.md>). It tries to handle characters as per POSIX.

<a id="rst-external-functions"></a>

## External Functions


#### <a id="c-n_tty_inherit_ops"></a>`n_tty_inherit_ops()`

```c
void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
```

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.


<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-n_tty_kick_worker"></a>`n_tty_kick_worker()`

```c
void n_tty_kick_worker(const struct tty_struct *tty)
```

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()`](#c-n_tty_read)/consumer path:
    holds non-exclusive `termios_rwsem`

#### <a id="c-n_tty_write_wakeup"></a>`n_tty_write_wakeup()`

```c
void n_tty_write_wakeup(struct tty_struct *tty)
```

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.

#### <a id="c-put_tty_queue"></a>`put_tty_queue()`

```c
void put_tty_queue(u8 c, struct n_tty_data *ldata)
```

add character to tty

**Parameters**

- `u8 c`: character
- `struct 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-exclusive `termios_rwsem`

#### <a id="c-reset_buffer_flags"></a>`reset_buffer_flags()`

```c
void reset_buffer_flags(struct n_tty_data *ldata)
```

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()`](#c-n_tty_open) and [`n_tty_flush_buffer()`](#c-n_tty_flush_buffer).

- Locking:
  * caller holds exclusive `termios_rwsem`, or
  * (locking is not required)

#### <a id="c-n_tty_flush_buffer"></a>`n_tty_flush_buffer()`

```c
void n_tty_flush_buffer(struct tty_struct *tty)
```

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`

#### <a id="c-is_utf8_continuation"></a>`is_utf8_continuation()`

```c
int is_utf8_continuation(u8 c)
```

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.

#### <a id="c-is_continuation"></a>`is_continuation()`

```c
int is_continuation(u8 c, const struct tty_struct *tty)
```

multibyte check

**Parameters**

- `u8 c`: byte to check
- `const 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.

#### <a id="c-do_output_char"></a>`do_output_char()`

```c
int do_output_char(u8 c, struct tty_struct *tty, int space)
```

output one character

**Parameters**

- `u8 c`: character (or partial unicode symbol)
- `struct tty_struct *tty`: terminal device
- `int 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.

#### <a id="c-process_output"></a>`process_output()`

```c
int process_output(u8 c, struct tty_struct *tty)
```

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()`](#c-n_tty_write) under the tty layer write lock).

**Return**

-1 when the output device is full and the character must be
retried.

#### <a id="c-process_output_block"></a>`process_output_block()`

```c
ssize_t process_output_block(struct tty_struct *tty, const u8 *buf, unsigned int nr)
```

block post processor

**Parameters**

- `struct tty_struct *tty`: terminal device
- `const u8 *buf`: character buffer
- `unsigned 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()`](#c-n_tty_write) under the tty layer write lock).

**Return**

the number of characters output.

#### <a id="c-__process_echoes"></a>`__process_echoes()`

```c
size_t __process_echoes(struct tty_struct *tty)
```

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`.

#### <a id="c-add_echo_byte"></a>`add_echo_byte()`

```c
void add_echo_byte(u8 c, struct n_tty_data *ldata)
```

add a byte to the echo buffer

**Parameters**

- `u8 c`: unicode byte to echo
- `struct n_tty_data *ldata`: n_tty data

**Description**

Add a character or operation byte to the echo buffer.

#### <a id="c-echo_move_back_col"></a>`echo_move_back_col()`

```c
void echo_move_back_col(struct n_tty_data *ldata)
```

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.

#### <a id="c-echo_set_canon_col"></a>`echo_set_canon_col()`

```c
void echo_set_canon_col(struct n_tty_data *ldata)
```

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.

#### <a id="c-echo_erase_tab"></a>`echo_erase_tab()`

```c
void echo_erase_tab(unsigned int num_chars, int after_tab, struct n_tty_data *ldata)
```

add operation to erase a tab

**Parameters**

- `unsigned int num_chars`: number of character columns already used
- `int after_tab`: true if num_chars starts after a previous tab
- `struct 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.

#### <a id="c-echo_char_raw"></a>`echo_char_raw()`

```c
void echo_char_raw(u8 c, struct n_tty_data *ldata)
```

echo a character raw

**Parameters**

- `u8 c`: unicode byte to echo
- `struct 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()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) path.

This variant does not treat control characters specially.

#### <a id="c-echo_char"></a>`echo_char()`

```c
void echo_char(u8 c, const struct tty_struct *tty)
```

echo a character

**Parameters**

- `u8 c`: unicode byte to echo
- `const 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()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) path.

This variant tags control characters to be echoed as "^X" (where X is the
letter representing the control char).

#### <a id="c-finish_erasing"></a>`finish_erasing()`

```c
void finish_erasing(struct n_tty_data *ldata)
```

complete erase

**Parameters**

- `struct n_tty_data *ldata`: n_tty data

#### <a id="c-eraser"></a>`eraser()`

```c
void eraser(u8 c, const struct tty_struct *tty)
```

handle erase function

**Parameters**

- `u8 c`: character input
- `const 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-exclusive `termios_rwsem`

#### <a id="c-isig"></a>`isig()`

```c
void isig(int sig, struct tty_struct *tty)
```

handle the ISIG optio

**Parameters**

- `int sig`: signal
- `struct tty_struct *tty`: terminal

**Description**

Called when a signal is being sent due to terminal input. Called from the
[`tty_driver.receive_buf()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) 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

#### <a id="c-n_tty_receive_break"></a>`n_tty_receive_break()`

```c
void n_tty_receive_break(struct tty_struct *tty)
```

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

#### <a id="c-n_tty_receive_overrun"></a>`n_tty_receive_overrun()`

```c
void n_tty_receive_overrun(const struct tty_struct *tty)
```

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.

#### <a id="c-n_tty_receive_parity_error"></a>`n_tty_receive_parity_error()`

```c
void n_tty_receive_parity_error(const struct tty_struct *tty, u8 c)
```

error notifier

**Parameters**

- `const struct tty_struct *tty`: terminal device
- `u8 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-exclusive `termios_rwsem`

#### <a id="c-n_tty_receive_char_flow_ctrl"></a>`n_tty_receive_char_flow_ctrl()`

```c
bool n_tty_receive_char_flow_ctrl(struct tty_struct *tty, u8 c, bool lookahead_done)
```

receive flow control chars

**Parameters**

- `struct tty_struct *tty`: terminal device
- `u8 c`: character
- `bool 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.

#### <a id="c-n_tty_receive_char"></a>`n_tty_receive_char()`

```c
void n_tty_receive_char(struct tty_struct *tty, u8 c)
```

perform processing

**Parameters**

- `struct tty_struct *tty`: terminal device
- `u8 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-exclusive `termios_rwsem`
  publishes canon_head if canonical mode is active

#### <a id="c-n_tty_receive_buf_common"></a>`n_tty_receive_buf_common()`

```c
size_t n_tty_receive_buf_common(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count, bool flow)
```

process input

**Parameters**

- `struct tty_struct *tty`: device to receive input
- `const u8 *cp`: input chars
- `const u8 *fp`: flags for each char (if `NULL`, all chars are `TTY_NORMAL`)
- `size_t count`: number of input chars in **cp**
- `bool 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()`](/kernel/hardware/driver-api/tty/tty-buffer.md#c-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-exclusive `termios_rwsem`
  publishes commit_head or canon_head

**Return**

the # of input chars from **cp** which were processed.

#### <a id="c-n_tty_set_termios"></a>`n_tty_set_termios()`

```c
void n_tty_set_termios(struct tty_struct *tty, const struct ktermios *old)
```

termios data changed

**Parameters**

- `struct tty_struct *tty`: terminal
- `const 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**

#### <a id="c-n_tty_close"></a>`n_tty_close()`

```c
void n_tty_close(struct tty_struct *tty)
```

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.

#### <a id="c-n_tty_open"></a>`n_tty_open()`

```c
int n_tty_open(struct tty_struct *tty)
```

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.

#### <a id="c-copy_from_read_buf"></a>`copy_from_read_buf()`

```c
bool copy_from_read_buf(const struct tty_struct *tty, u8 **kbp, size_t *nr)
```

copy read data directly

**Parameters**

- `const struct tty_struct *tty`: terminal device
- `u8 **kbp`: data
- `size_t *nr`: size of data

**Description**

Helper function to speed up [`n_tty_read()`](#c-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()`](#c-n_tty_read)/consumer path:
    caller holds non-exclusive `termios_rwsem`;
    read_tail published

**Return**

true if it successfully copied data, but there is still more data
to be had.

#### <a id="c-canon_copy_from_read_buf"></a>`canon_copy_from_read_buf()`

```c
bool canon_copy_from_read_buf(const struct tty_struct *tty, u8 **kbp, size_t *nr)
```

copy read data in canonical mode

**Parameters**

- `const struct tty_struct *tty`: terminal device
- `u8 **kbp`: data
- `size_t *nr`: size of data

**Description**

Helper function for [`n_tty_read()`](#c-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()`](#c-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_lock` mutex
  * [`n_tty_read()`](#c-n_tty_read)/consumer path:
    caller holds non-exclusive `termios_rwsem`;
    read_tail published

#### <a id="c-job_control"></a>`job_control()`

```c
int job_control(struct tty_struct *tty, struct file *file)
```

check job control

**Parameters**

- `struct tty_struct *tty`: tty
- `struct 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**

#### <a id="c-n_tty_read"></a>`n_tty_read()`

```c
ssize_t n_tty_read(struct tty_struct *tty, struct file *file, u8 *kbuf, size_t nr, void **cookie, unsigned long offset)
```

read function for tty

**Parameters**

- `struct tty_struct *tty`: tty device
- `struct file *file`: file object
- `u8 *kbuf`: kernelspace buffer pointer
- `size_t nr`: size of I/O
- `void **cookie`: if non-`NULL`, this is a continuation read
- `unsigned 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()`](#c-n_tty_read)/consumer path:
  claims non-exclusive termios_rwsem;
  publishes read_tail

#### <a id="c-n_tty_write"></a>`n_tty_write()`

```c
ssize_t n_tty_write(struct tty_struct *tty, struct file *file, const u8 *buf, size_t nr)
```

write function for tty

**Parameters**

- `struct tty_struct *tty`: tty device
- `struct file *file`: file object
- `const u8 *buf`: userspace buffer pointer
- `size_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)

#### <a id="c-n_tty_poll"></a>`n_tty_poll()`

```c
__poll_t n_tty_poll(struct tty_struct *tty, struct file *file, poll_table *wait)
```

poll method for N_TTY

**Parameters**

- `struct tty_struct *tty`: terminal device
- `struct file *file`: file accessing it
- `poll_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_

> Flip Buffer Management

<a id="rst-tty-buffer"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



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](</kernel/hardware/driver-api/tty/tty-ldisc.md>) for further processing.

<a id="rst-flip-buffer-management"></a>

## Flip Buffer Management


#### <a id="c-tty_prepare_flip_string"></a>`tty_prepare_flip_string()`

```c
size_t tty_prepare_flip_string(struct tty_port *port, u8 **chars, size_t size)
```

make room for characters

**Parameters**

- `struct tty_port *port`: tty port
- `u8 **chars`: return pointer for character write area
- `size_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.

#### <a id="c-tty_ldisc_receive_buf"></a>`tty_ldisc_receive_buf()`

```c
size_t tty_ldisc_receive_buf(struct tty_ldisc *ld, const u8 *p, const u8 *f, size_t count)
```

forward data to line discipline

**Parameters**

- `struct tty_ldisc *ld`: line discipline to process input
- `const u8 *p`: char buffer
- `const u8 *f`: `TTY_NORMAL`, `TTY_BREAK`, etc. flags buffer
- `size_t count`: number of bytes to process

**Description**

Callers other than [`flush_to_ldisc()`](#c-flush_to_ldisc) need to exclude the kworker from
concurrent use of the line discipline, see `paste_selection()`.

**Return**

the number of bytes processed.

#### <a id="c-tty_flip_buffer_push"></a>`tty_flip_buffer_push()`

```c
void tty_flip_buffer_push(struct tty_port *port)
```

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.



#### <a id="c-tty_insert_flip_string_fixed_flag"></a>`tty_insert_flip_string_fixed_flag()`

```c
size_t tty_insert_flip_string_fixed_flag(struct tty_port *port, const u8 *chars, u8 flag, size_t size)
```

add characters to the tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `const u8 *chars`: characters
- `u8 flag`: flag value for each character
- `size_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.

#### <a id="c-tty_insert_flip_string_flags"></a>`tty_insert_flip_string_flags()`

```c
size_t tty_insert_flip_string_flags(struct tty_port *port, const u8 *chars, const u8 *flags, size_t size)
```

add characters to the tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `const u8 *chars`: characters
- `const u8 *flags`: flag bytes
- `size_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.

#### <a id="c-tty_insert_flip_char"></a>`tty_insert_flip_char()`

```c
size_t tty_insert_flip_char(struct tty_port *port, u8 ch, u8 flag)
```

add one character to the tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `u8 ch`: character
- `u8 flag`: flag byte

**Description**

Queue a single byte **ch** to the tty buffering, with an optional flag.


---

<a id="rst-other-functions"></a>

## Other Functions


#### <a id="c-tty_buffer_space_avail"></a>`tty_buffer_space_avail()`

```c
unsigned int tty_buffer_space_avail(struct tty_port *port)
```

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()`](#c-tty_prepare_flip_string) to pre-allocate if memory
guarantee is required).

#### <a id="c-tty_buffer_set_limit"></a>`tty_buffer_set_limit()`

```c
int tty_buffer_set_limit(struct tty_port *port, int limit)
```

change the tty buffer memory limit

**Parameters**

- `struct tty_port *port`: tty port to change
- `int limit`: memory limit to set

**Description**

Change the tty buffer memory limit.

Must be called before the other tty buffer functions are used.


---

<a id="rst-buffer-locking"></a>

## Buffer Locking

These are used only in special circumstances. Avoid them.


#### <a id="c-tty_buffer_lock_exclusive"></a>`tty_buffer_lock_exclusive()`

```c
void tty_buffer_lock_exclusive(struct tty_port *port)
```

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()`](/kernel/hardware/driver-api/tty/tty-ldisc.md#c-struct-tty_ldisc_ops) 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()`](#c-tty_buffer_unlock_exclusive).

#### <a id="c-tty_buffer_unlock_exclusive"></a>`tty_buffer_unlock_exclusive()`

```c
void tty_buffer_unlock_exclusive(struct tty_port *port)
```

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()`](#c-tty_buffer_lock_exclusive).


---

<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-tty_buffer_free_all"></a>`tty_buffer_free_all()`

```c
void tty_buffer_free_all(struct tty_port *port)
```

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.

#### <a id="c-tty_buffer_alloc"></a>`tty_buffer_alloc()`

```c
struct tty_buffer * tty_buffer_alloc(struct tty_port *port, size_t size)
```

allocate a tty buffer

**Parameters**

- `struct tty_port *port`: tty port
- `size_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.

#### <a id="c-tty_buffer_free"></a>`tty_buffer_free()`

```c
void tty_buffer_free(struct tty_port *port, struct tty_buffer *b)
```

free a tty buffer

**Parameters**

- `struct tty_port *port`: tty port owning the buffer
- `struct tty_buffer *b`: the buffer to free

**Description**

Free a tty buffer, or add it to the free list according to our internal
strategy.

#### <a id="c-tty_buffer_flush"></a>`tty_buffer_flush()`

```c
void tty_buffer_flush(struct tty_struct *tty, struct tty_ldisc *ld)
```

flush full tty buffers

**Parameters**

- `struct tty_struct *tty`: tty to flush
- `struct 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'.

#### <a id="c-__tty_buffer_request_room"></a>`__tty_buffer_request_room()`

```c
int __tty_buffer_request_room(struct tty_port *port, size_t size, bool flags)
```

grow tty buffer if needed

**Parameters**

- `struct tty_port *port`: tty port
- `size_t size`: size desired
- `bool 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.

#### <a id="c-flush_to_ldisc"></a>`flush_to_ldisc()`

```c
void flush_to_ldisc(struct work_struct *work)
```

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'.

#### <a id="c-tty_insert_flip_string_and_push_buffer"></a>`tty_insert_flip_string_and_push_buffer()`

```c
int tty_insert_flip_string_and_push_buffer(struct tty_port *port, const u8 *chars, size_t size)
```

add characters to the tty buffer and push

**Parameters**

- `struct tty_port *port`: tty port
- `const u8 *chars`: characters
- `size_t size`: size

**Description**

The function combines `tty_insert_flip_string()` and [`tty_flip_buffer_push()`](#c-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.

#### <a id="c-tty_buffer_init"></a>`tty_buffer_init()`

```c
void tty_buffer_init(struct tty_port *port)
```

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

<a id="rst-tty-driver-and-tty-operations"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-allocation"></a>

## 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](<#rst-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](<#rst-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:


#### <a id="c-tty_alloc_driver"></a>`tty_alloc_driver()`

```c
tty_alloc_driver(lines, flags)
```

allocate tty driver

**Parameters**

- `lines`: count of lines this driver can handle at most
- `flags`: some of enum tty_driver_flag, will be set in driver->flags

**Return**

struct tty_driver or a PTR-encoded error (use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) and friends).



#### <a id="c-__tty_alloc_driver"></a>`__tty_alloc_driver()`

```c
struct tty_driver * __tty_alloc_driver(unsigned int lines, struct module *owner, unsigned long flags)
```

allocate tty driver

**Parameters**

- `unsigned int lines`: count of lines this driver can handle at most
- `struct module *owner`: module which is responsible for this driver
- `unsigned long flags`: some of enum tty_driver_flag, will be set in driver->flags

**Description**

This should not be called directly, [`tty_alloc_driver()`](#c-tty_alloc_driver) should be used
instead.

**Return**

struct tty_driver or a PTR-encoded error (use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) and friends).

#### <a id="c-tty_driver_kref_put"></a>`tty_driver_kref_put()`

```c
void tty_driver_kref_put(struct tty_driver *driver)
```

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.


<a id="rst-tty-driver-flags"></a>

### TTY Driver Flags

Here comes the documentation of flags accepted by tty_alloc_driver() (or \__tty_alloc_driver()):


#### <a id="c-enum-tty_driver_flag"></a>`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 to
  [`tty_register_device()`](#c-tty_register_device) when the device is found in the system and
  unregistered with a call to [`tty_unregister_device()`](#c-tty_unregister_device) so the devices will
  be show up properly in sysfs.  If not set, all [`tty_driver.num`](#c-struct-tty_driver) entries
  will be created by the tty core in sysfs when [`tty_register_driver()`](#c-tty_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.ttys`](#c-struct-tty_driver) and
  [`tty_driver.termios`](#c-struct-tty_driver)), 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 the
  [`tty_operations.break_ctl`](#c-struct-tty_operations) instead 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`](#c-struct-tty_driver)) 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 `/dev` nodes. For example, create
  `/dev/ttyprintk` and 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()`](#c-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.)


---

<a id="rst-registration"></a>

## 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](<#rst-registering-devices>) is still relevant there.


#### <a id="c-tty_register_driver"></a>`tty_register_driver()`

```c
int tty_register_driver(struct tty_driver *driver)
```

register a tty driver

**Parameters**

- `struct tty_driver *driver`: driver to register

**Description**

Called by a tty driver to register itself.

#### <a id="c-tty_unregister_driver"></a>`tty_unregister_driver()`

```c
void tty_unregister_driver(struct tty_driver *driver)
```

unregister a tty driver

**Parameters**

- `struct tty_driver *driver`: driver to unregister

**Description**

Called by a tty driver to unregister itself.


<a id="rst-registering-devices"></a>

### 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](</kernel/hardware/driver-api/tty/tty-port.md>). 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](<#rst-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](<#rst-tty-operations-reference>).

The registration routines are documented as follows:


#### <a id="c-tty_register_device"></a>`tty_register_device()`

```c
struct device * tty_register_device(struct tty_driver *driver, unsigned index, struct device *device)
```

register a tty device

**Parameters**

- `struct tty_driver *driver`: the tty driver that describes the tty device
- `unsigned index`: the index in the tty driver for this tty device
- `struct 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).

#### <a id="c-tty_register_device_attr"></a>`tty_register_device_attr()`

```c
struct device * tty_register_device_attr(struct tty_driver *driver, unsigned index, struct device *device, void *drvdata, const struct attribute_group **attr_grp)
```

register a tty device

**Parameters**

- `struct tty_driver *driver`: the tty driver that describes the tty device
- `unsigned index`: the index in the tty driver for this tty device
- `struct 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.
- `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).

#### <a id="c-tty_unregister_device"></a>`tty_unregister_device()`

```c
void tty_unregister_device(struct tty_driver *driver, unsigned index)
```

unregister a tty device

**Parameters**

- `struct tty_driver *driver`: the tty driver that describes the tty device
- `unsigned 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()`](#c-tty_register_device) then
this function must be called when the tty device is gone.

Locking: ??


---

<a id="rst-linking-devices-to-ports"></a>

### 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:


#### <a id="c-tty_port_link_device"></a>`tty_port_link_device()`

```c
void tty_port_link_device(struct tty_port *port, struct tty_driver *driver, unsigned index)
```

link tty and tty_port

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `unsigned 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()`](#c-tty_port_register_device) nor
[`tty_port_install()`](/kernel/hardware/driver-api/tty/tty-port.md#c-tty_port_install) is used in the driver. If used, this has to be called
before [`tty_register_driver()`](#c-tty_register_driver).

#### <a id="c-tty_port_register_device"></a>`tty_port_register_device()`

```c
struct device * tty_port_register_device(struct tty_port *port, struct tty_driver *driver, unsigned index, struct device *device)
```

register tty device

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `unsigned index`: index of the tty
- `struct device *device`: parent if exists, otherwise NULL

**Description**

It is the same as [`tty_register_device()`](#c-tty_register_device) except the provided **port** is linked
to a concrete tty specified by **index**. Use this or [`tty_port_install()`](/kernel/hardware/driver-api/tty/tty-port.md#c-tty_port_install) (or
both). Call [`tty_port_link_device()`](#c-tty_port_link_device) as a last resort.

#### <a id="c-tty_port_register_device_attr"></a>`tty_port_register_device_attr()`

```c
struct device * tty_port_register_device_attr(struct tty_port *port, struct tty_driver *driver, unsigned index, struct device *device, void *drvdata, const struct attribute_group **attr_grp)
```

register tty device

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `unsigned index`: index of the tty
- `struct device *device`: parent if exists, otherwise NULL
- `void *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()`](#c-tty_register_device_attr) except the provided **port** is
linked to a concrete tty specified by **index**. Use this or [`tty_port_install()`](/kernel/hardware/driver-api/tty/tty-port.md#c-tty_port_install)
(or both). Call [`tty_port_link_device()`](#c-tty_port_link_device) as a last resort.


---

<a id="rst-tty-driver-reference"></a>

## 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.


#### <a id="c-struct-tty_driver"></a>`struct tty_driver`

- driver for TTY devices

**Definition**

```c
struct tty_driver {
    struct kref kref;
    struct cdev **cdevs;
    struct module   *owner;
    const char      *driver_name;
    const char      *name;
    int name_base;
    int major;
    int minor_start;
    unsigned int    num;
    enum tty_driver_type type;
    enum tty_driver_subtype subtype;
    struct ktermios init_termios;
    unsigned long   flags;
    struct proc_dir_entry *proc_entry;
    struct tty_driver *other;
    struct tty_struct **ttys;
    struct tty_port **ports;
    struct ktermios **termios;
    void *driver_state;
    const struct tty_operations *ops;
    struct list_head tty_drivers;
};
```

**Members**

- `kref`: reference counting. Reaching zero frees all the internals and the
  driver.
- `cdevs`: allocated/registered character /dev devices
- `owner`: modules owning this driver. Used drivers cannot be rmmod'ed.
  Automatically set by [`tty_alloc_driver()`](#c-tty_alloc_driver).
- `driver_name`: name of the driver used in /proc/tty
- `name`: used for constructing /dev node name
- `name_base`: used as a number base for constructing /dev node name
- `major`: major /dev device number (zero for autoassignment)
- `minor_start`: the first minor /dev device number
- `num`: number of devices allocated
- `type`: 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 internally
- `other`: driver of the linked tty; only used for the PTY driver
- `ttys`: array of active [`struct tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct), set by [`tty_standard_install()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_standard_install)
- `ports`: array of [`struct tty_port`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port); can be set during initialization by
  [`tty_port_link_device()`](#c-tty_port_link_device) and similar
- `termios`: storage for termios at each TTY close for the next open
- `driver_state`: pointer to driver's arbitrary data
- `ops`: driver hooks for TTYs. Set them using `tty_set_operations()`. Use [`struct tty_port`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port) helpers in them as much as possible.
- `tty_drivers`: used internally to link tty_drivers together

**Description**

The usual handling of [`struct tty_driver`](#c-struct-tty_driver) is to allocate it by
[`tty_alloc_driver()`](#c-tty_alloc_driver), set up all the necessary members, and register it by
[`tty_register_driver()`](#c-tty_register_driver). At last, the driver is torn down by calling
[`tty_unregister_driver()`](#c-tty_unregister_driver) followed by [`tty_driver_kref_put()`](#c-tty_driver_kref_put).

The fields required to be set before calling [`tty_register_driver()`](#c-tty_register_driver) include
**driver_name**, **name**, **type**, **subtype**, **init_termios**, and **ops**.


---

<a id="rst-tty-operations-reference"></a>

## TTY Operations Reference

When a TTY is registered, these driver hooks can be invoked by the TTY layer:


#### <a id="c-struct-tty_operations"></a>`struct tty_operations`

- interface between driver and tty

**Definition**

```c
struct tty_operations {
        struct tty_struct * (*lookup)(struct tty_driver *driver, struct file *filp, int idx);
        int (*install)(struct tty_driver *driver, struct tty_struct *tty);
        void (*remove)(struct tty_driver *driver, struct tty_struct *tty);
        int (*open)(struct tty_struct * tty, struct file * filp);
        void (*close)(struct tty_struct * tty, struct file * filp);
        void (*shutdown)(struct tty_struct *tty);
        void (*cleanup)(struct tty_struct *tty);
        ssize_t (*write)(struct tty_struct *tty, const u8 *buf, size_t count);
        int (*put_char)(struct tty_struct *tty, u8 ch);
        void (*flush_chars)(struct tty_struct *tty);
        unsigned int (*write_room)(struct tty_struct *tty);
        unsigned int (*chars_in_buffer)(struct tty_struct *tty);
        int (*ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
        long (*compat_ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
        void (*set_termios)(struct tty_struct *tty, const struct ktermios *old);
        void (*throttle)(struct tty_struct * tty);
        void (*unthrottle)(struct tty_struct * tty);
        void (*stop)(struct tty_struct *tty);
        void (*start)(struct tty_struct *tty);
        void (*hangup)(struct tty_struct *tty);
        int (*break_ctl)(struct tty_struct *tty, int state);
        void (*flush_buffer)(struct tty_struct *tty);
        int (*ldisc_ok)(struct tty_struct *tty, int ldisc);
        void (*set_ldisc)(struct tty_struct *tty);
        void (*wait_until_sent)(struct tty_struct *tty, int timeout);
        void (*send_xchar)(struct tty_struct *tty, u8 ch);
        int (*tiocmget)(struct tty_struct *tty);
        int (*tiocmset)(struct tty_struct *tty, unsigned int set, unsigned int clear);
        int (*resize)(struct tty_struct *tty, struct winsize *ws);
        int (*get_icount)(struct tty_struct *tty, struct serial_icounter_struct *icount);
        int (*get_serial)(struct tty_struct *tty, struct serial_struct *p);
        int (*set_serial)(struct tty_struct *tty, struct serial_struct *p);
        void (*show_fdinfo)(struct tty_struct *tty, struct seq_file *m);
    #ifdef CONFIG_CONSOLE_POLL;
        int (*poll_init)(struct tty_driver *driver, int line, char *options);
        int (*poll_get_char)(struct tty_driver *driver, int line);
        void (*poll_put_char)(struct tty_driver *driver, int line, char ch);
    #endif;
        int (*proc_show)(struct seq_file *m, void *driver);
};
```

**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()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-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()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_write_room)

This routine returns the number of characters in the device private
output queue. Used in [`tty_wait_until_sent()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-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()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-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()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-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()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-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()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-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()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-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()`](#c-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()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-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()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-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()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-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()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-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()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-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`](#c-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

<a id="rst-tty-internals"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-kopen"></a>

## Kopen

These functions serve for opening a TTY from the kernelspace:


#### <a id="c-tty_kclose"></a>`tty_kclose()`

```c
void tty_kclose(struct tty_struct *tty)
```

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()`](#c-tty_release_struct) except that it also resets `TTY_PORT_KOPENED` flag on
**tty->port**.

#### <a id="c-tty_kopen_exclusive"></a>`tty_kopen_exclusive()`

```c
struct tty_struct * tty_kopen_exclusive(dev_t device)
```

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_mutex` to serialize:
  * concurrent first-time tty initialization
  * concurrent tty driver removal w/ lookup
  * concurrent tty removal from driver table

**Return**

the locked initialized [`tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

#### <a id="c-tty_kopen_shared"></a>`tty_kopen_shared()`

```c
struct tty_struct * tty_kopen_shared(dev_t device)
```

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()`](#c-tty_kopen_exclusive) above it doesn't ensure to be the only user.

Locking: identical to `tty_kopen()` above.


---

<a id="rst-exported-internal-functions"></a>

## Exported Internal Functions


#### <a id="c-tty_dev_name_to_number"></a>`tty_dev_name_to_number()`

```c
int tty_dev_name_to_number(const char *name, dev_t *number)
```

return dev_t for device name

**Parameters**

- `const char *name`: user space name of device under /dev
- `dev_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.

#### <a id="c-tty_release_struct"></a>`tty_release_struct()`

```c
void tty_release_struct(struct tty_struct *tty, int idx)
```

release a tty struct

**Parameters**

- `struct tty_struct *tty`: tty device
- `int 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()`](#c-tty_init_dev).

#### <a id="c-tty_get_icount"></a>`tty_get_icount()`

```c
int tty_get_icount(struct tty_struct *tty, struct serial_icounter_struct *icount)
```

get tty statistics

**Parameters**

- `struct tty_struct *tty`: tty device
- `struct serial_icounter_struct *icount`: output parameter

**Description**

Gets a copy of the **tty**'s icount statistics.

Locking: none (up to the driver)


---

<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-free_tty_struct"></a>`free_tty_struct()`

```c
void free_tty_struct(struct tty_struct *tty)
```

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

#### <a id="c-tty_free_file"></a>`tty_free_file()`

```c
void tty_free_file(struct file *file)
```

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.

#### <a id="c-get_tty_driver"></a>`get_tty_driver()`

```c
struct tty_driver * get_tty_driver(dev_t device, int *index)
```

find device of a tty

**Parameters**

- `dev_t device`: device identifier
- `int *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

#### <a id="c-tty_release_redirect"></a>`tty_release_redirect()`

```c
struct file * tty_release_redirect(struct tty_struct *tty)
```

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.

#### <a id="c-__tty_hangup"></a>`__tty_hangup()`

```c
void __tty_hangup(struct tty_struct *tty, int exit_session)
```

actual handler for hangup events

**Parameters**

- `struct tty_struct *tty`: tty device
- `int 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

#### <a id="c-tty_vhangup_self"></a>`tty_vhangup_self()`

```c
void tty_vhangup_self(void)
```

process vhangup for own ctty

**Parameters**

- `void`: no arguments

**Description**

Perform a vhangup on the current controlling tty

#### <a id="c-tty_vhangup_session"></a>`tty_vhangup_session()`

```c
void tty_vhangup_session(struct tty_struct *tty)
```

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.

#### <a id="c-tty_read"></a>`tty_read()`

```c
ssize_t tty_read(struct kiocb *iocb, struct iov_iter *to)
```

read method for tty device files

**Parameters**

- `struct kiocb *iocb`: kernel I/O control block
- `struct 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.

#### <a id="c-tty_write_message"></a>`tty_write_message()`

```c
void tty_write_message(struct tty_struct *tty, char *msg)
```

write a message to a certain tty, not just the console.

**Parameters**

- `struct tty_struct *tty`: the destination tty_struct
- `char *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.

#### <a id="c-tty_write"></a>`tty_write()`

```c
ssize_t tty_write(struct kiocb *iocb, struct iov_iter *from)
```

write method for tty device file

**Parameters**

- `struct kiocb *iocb`: kernel I/O control block
- `struct 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.

#### <a id="c-tty_send_xchar"></a>`tty_send_xchar()`

```c
int tty_send_xchar(struct tty_struct *tty, u8 ch)
```

send priority character

**Parameters**

- `struct tty_struct *tty`: the tty to send to
- `u8 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.

#### <a id="c-pty_line_name"></a>`pty_line_name()`

```c
void pty_line_name(struct tty_driver *driver, int index, char *p)
```

generate name for a pty

**Parameters**

- `struct tty_driver *driver`: the tty driver in use
- `int index`: the minor number
- `char *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

#### <a id="c-tty_line_name"></a>`tty_line_name()`

```c
ssize_t tty_line_name(struct tty_driver *driver, int index, char *p)
```

generate name for a tty

**Parameters**

- `struct tty_driver *driver`: the tty driver in use
- `int index`: the minor number
- `char *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

#### <a id="c-tty_driver_lookup_tty"></a>`tty_driver_lookup_tty()`

```c
struct tty_struct * tty_driver_lookup_tty(struct tty_driver *driver, struct file *file, int idx)
```

find an existing tty, if any

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct file *file`: file object
- `int idx`: the minor number

**Return**

the tty, if found. If not found, return `NULL` or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-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.

#### <a id="c-tty_driver_install_tty"></a>`tty_driver_install_tty()`

```c
int tty_driver_install_tty(struct tty_driver *driver, struct tty_struct *tty)
```

install a tty entry in the driver

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct 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

#### <a id="c-tty_driver_remove_tty"></a>`tty_driver_remove_tty()`

```c
void tty_driver_remove_tty(struct tty_driver *driver, struct tty_struct *tty)
```

remove a tty from the driver tables

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct 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

#### <a id="c-tty_reopen"></a>`tty_reopen()`

```c
int tty_reopen(struct tty_struct *tty)
```

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.

#### <a id="c-tty_init_dev"></a>`tty_init_dev()`

```c
struct tty_struct * tty_init_dev(struct tty_driver *driver, int idx)
```

initialise a tty device

**Parameters**

- `struct tty_driver *driver`: tty driver we are opening a device on
- `int 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

#### <a id="c-tty_flush_works"></a>`tty_flush_works()`

```c
void tty_flush_works(struct tty_struct *tty)
```

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).

#### <a id="c-release_one_tty"></a>`release_one_tty()`

```c
void release_one_tty(struct work_struct *work)
```

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)

#### <a id="c-release_tty"></a>`release_tty()`

```c
void release_tty(struct tty_struct *tty, int idx)
```

release tty structure memory

**Parameters**

- `struct tty_struct *tty`: tty device release
- `int 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.

#### <a id="c-tty_release_checks"></a>`tty_release_checks()`

```c
int tty_release_checks(struct tty_struct *tty, int idx)
```

check a tty before real release

**Parameters**

- `struct tty_struct *tty`: tty to check
- `int 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.

#### <a id="c-tty_release"></a>`tty_release()`

```c
int tty_release(struct inode *inode, struct file *filp)
```

vfs callback for close

**Parameters**

- `struct inode *inode`: inode of tty
- `struct 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.

#### <a id="c-tty_open_current_tty"></a>`tty_open_current_tty()`

```c
struct tty_struct * tty_open_current_tty(dev_t device, struct file *filp)
```

get locked tty of current task

**Parameters**

- `dev_t device`: device number
- `struct 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.

#### <a id="c-tty_lookup_driver"></a>`tty_lookup_driver()`

```c
struct tty_driver * tty_lookup_driver(dev_t device, struct file *filp, int *index)
```

lookup a tty driver for a given device file

**Parameters**

- `dev_t device`: device number
- `struct file *filp`: file pointer to tty
- `int *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()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-tty_driver_kref_put).

Locking: `tty_mutex` protects [`get_tty_driver()`](#c-get_tty_driver)

**Return**

driver for this inode (with increased refcount)

#### <a id="c-tty_open_by_driver"></a>`tty_open_by_driver()`

```c
struct tty_struct * tty_open_by_driver(dev_t device, struct file *filp)
```

open a tty device

**Parameters**

- `dev_t device`: dev_t of device to open
- `struct 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`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

#### <a id="c-tty_open"></a>`tty_open()`

```c
int tty_open(struct inode *inode, struct file *filp)
```

open a tty device

**Parameters**

- `struct inode *inode`: inode of device file
- `struct file *filp`: file pointer to tty

**Description**

[`tty_open()`](#c-tty_open) and [`tty_release()`](#c-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_mutex` protects tty, [`tty_lookup_driver()`](#c-tty_lookup_driver) and [`tty_init_dev()`](#c-tty_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`

#### <a id="c-tty_poll"></a>`tty_poll()`

```c
__poll_t tty_poll(struct file *filp, poll_table *wait)
```

check tty status

**Parameters**

- `struct file *filp`: file being polled
- `poll_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.

#### <a id="c-tiocsti"></a>`tiocsti()`

```c
int tiocsti(struct tty_struct *tty, u8 __user *p)
```

fake input character

**Parameters**

- `struct tty_struct *tty`: tty to fake input into
- `u8 __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

#### <a id="c-tiocgwinsz"></a>`tiocgwinsz()`

```c
int tiocgwinsz(struct tty_struct *tty, struct winsize __user *arg)
```

implement window query ioctl

**Parameters**

- `struct tty_struct *tty`: tty
- `struct 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.

#### <a id="c-tiocswinsz"></a>`tiocswinsz()`

```c
int tiocswinsz(struct tty_struct *tty, struct winsize __user *arg)
```

implement window size set ioctl

**Parameters**

- `struct tty_struct *tty`: tty side of tty
- `struct 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.

#### <a id="c-tioccons"></a>`tioccons()`

```c
int tioccons(struct file *file)
```

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

#### <a id="c-tiocsetd"></a>`tiocsetd()`

```c
int tiocsetd(struct tty_struct *tty, int __user *p)
```

set line discipline

**Parameters**

- `struct tty_struct *tty`: tty device
- `int __user *p`: pointer to user data

**Description**

Set the line discipline according to user request.

Locking: see [`tty_set_ldisc()`](/kernel/hardware/driver-api/tty/tty-ldisc.md#c-tty_set_ldisc), this function is just a helper

#### <a id="c-tiocgetd"></a>`tiocgetd()`

```c
int tiocgetd(struct tty_struct *tty, int __user *p)
```

get line discipline

**Parameters**

- `struct tty_struct *tty`: tty device
- `int __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)

#### <a id="c-send_break"></a>`send_break()`

```c
int send_break(struct tty_struct *tty, unsigned int duration)
```

performed time break

**Parameters**

- `struct tty_struct *tty`: device to break on
- `unsigned 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

#### <a id="c-tty_tiocmget"></a>`tty_tiocmget()`

```c
int tty_tiocmget(struct tty_struct *tty, int __user *p)
```

get modem status

**Parameters**

- `struct tty_struct *tty`: tty device
- `int __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)

#### <a id="c-tty_tiocmset"></a>`tty_tiocmset()`

```c
int tty_tiocmset(struct tty_struct *tty, unsigned int cmd, unsigned __user *p)
```

set modem status

**Parameters**

- `struct tty_struct *tty`: tty device
- `unsigned int cmd`: command - clear bits, set bits or set all
- `unsigned __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)

#### <a id="c-alloc_tty_struct"></a>`alloc_tty_struct()`

```c
struct tty_struct * alloc_tty_struct(struct tty_driver *driver, int idx)
```

allocate a new tty

**Parameters**

- `struct tty_driver *driver`: driver which will handle the returned tty
- `int 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_

> Reference for TTY IOCTL Helpers.

<a id="rst-tty-ioctl-helpers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-tty_chars_in_buffer"></a>`tty_chars_in_buffer()`

```c
unsigned int tty_chars_in_buffer(struct tty_struct *tty)
```

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.

#### <a id="c-tty_write_room"></a>`tty_write_room()`

```c
unsigned int tty_write_room(struct tty_struct *tty)
```

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.

#### <a id="c-tty_driver_flush_buffer"></a>`tty_driver_flush_buffer()`

```c
void tty_driver_flush_buffer(struct tty_struct *tty)
```

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.

#### <a id="c-tty_unthrottle"></a>`tty_unthrottle()`

```c
void tty_unthrottle(struct tty_struct *tty)
```

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`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct) 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.

#### <a id="c-tty_throttle_safe"></a>`tty_throttle_safe()`

```c
bool tty_throttle_safe(struct tty_struct *tty)
```

flow control

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

Indicate that a **tty** should stop transmitting data down the stack.
[`tty_throttle_safe()`](#c-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)

#### <a id="c-tty_unthrottle_safe"></a>`tty_unthrottle_safe()`

```c
bool tty_unthrottle_safe(struct tty_struct *tty)
```

flow control

**Parameters**

- `struct tty_struct *tty`: terminal

**Description**

Similar to [`tty_unthrottle()`](#c-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)

#### <a id="c-tty_wait_until_sent"></a>`tty_wait_until_sent()`

```c
void tty_wait_until_sent(struct tty_struct *tty, long timeout)
```

wait for I/O to finish

**Parameters**

- `struct tty_struct *tty`: tty we are waiting for
- `long 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

#### <a id="c-tty_termios_copy_hw"></a>`tty_termios_copy_hw()`

```c
void tty_termios_copy_hw(struct ktermios *new, const struct ktermios *old)
```

copy hardware settings

**Parameters**

- `struct ktermios *new`: new termios
- `const 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.

#### <a id="c-tty_termios_hw_change"></a>`tty_termios_hw_change()`

```c
bool tty_termios_hw_change(const struct ktermios *a, const struct ktermios *b)
```

check for setting change

**Parameters**

- `const struct ktermios *a`: termios
- `const 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

#### <a id="c-tty_get_char_size"></a>`tty_get_char_size()`

```c
unsigned char tty_get_char_size(unsigned int cflag)
```

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

#### <a id="c-tty_get_frame_size"></a>`tty_get_frame_size()`

```c
unsigned char tty_get_frame_size(unsigned int cflag)
```

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.

#### <a id="c-tty_set_termios"></a>`tty_set_termios()`

```c
int tty_set_termios(struct tty_struct *tty, struct ktermios *new_termios)
```

update termios values

**Parameters**

- `struct tty_struct *tty`: tty to update
- `struct 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`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

#### <a id="c-set_termios"></a>`set_termios()`

```c
int set_termios(struct tty_struct *tty, void __user *arg, int opt)
```

set termios values for a tty

**Parameters**

- `struct tty_struct *tty`: terminal device
- `void __user *arg`: user data
- `int opt`: option information

**Description**

Helper function to prepare termios data and run necessary other functions
before using [`tty_set_termios()`](#c-tty_set_termios) to do the actual changes.

Locking: called functions take [`tty_struct->ldisc_sem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct) and
[`tty_struct->termios_rwsem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct) locks

**Return**

0 on success, an error otherwise

#### <a id="c-set_sgttyb"></a>`set_sgttyb()`

```c
int set_sgttyb(struct tty_struct *tty, struct sgttyb __user *sgttyb)
```

set legacy terminal values

**Parameters**

- `struct tty_struct *tty`: tty structure
- `struct 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`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct)

**Return**

0 on success, an error otherwise

#### <a id="c-tty_change_softcar"></a>`tty_change_softcar()`

```c
int tty_change_softcar(struct tty_struct *tty, bool enable)
```

carrier change ioctl helper

**Parameters**

- `struct tty_struct *tty`: tty to update
- `bool enable`: enable/disable `CLOCAL`

**Description**

Perform a change to the `CLOCAL` state and call into the driver layer to make
it visible.

Locking: [`tty_struct->termios_rwsem`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct).

**Return**

0 on success, an error otherwise

#### <a id="c-tty_mode_ioctl"></a>`tty_mode_ioctl()`

```c
int tty_mode_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg)
```

mode related ioctls

**Parameters**

- `struct tty_struct *tty`: tty for the ioctl
- `unsigned int cmd`: command
- `unsigned 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.



#### <a id="c-tty_get_baud_rate"></a>`tty_get_baud_rate()`

```c
speed_t tty_get_baud_rate(const struct tty_struct *tty)
```

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_

> Registration

<a id="rst-tty-line-discipline"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



TTY line discipline process all incoming and outgoing character from/to a tty device. The default line discipline is [N_TTY](</kernel/hardware/driver-api/tty/n-tty.md>). 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.

<a id="rst-registration"></a>

## 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).


#### <a id="c-tty_register_ldisc"></a>`tty_register_ldisc()`

```c
int tty_register_ldisc(struct tty_ldisc_ops *new_ldisc)
```

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

#### <a id="c-tty_unregister_ldisc"></a>`tty_unregister_ldisc()`

```c
void tty_unregister_ldisc(struct tty_ldisc_ops *ldisc)
```

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


<a id="rst-other-functions"></a>

## Other Functions


#### <a id="c-tty_ldisc_flush"></a>`tty_ldisc_flush()`

```c
void tty_ldisc_flush(struct tty_struct *tty)
```

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**.

#### <a id="c-tty_set_ldisc"></a>`tty_set_ldisc()`

```c
int tty_set_ldisc(struct tty_struct *tty, int disc)
```

set line discipline

**Parameters**

- `struct tty_struct *tty`: the terminal to set
- `int 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.


<a id="rst-line-discipline-operations-reference"></a>

## Line Discipline Operations Reference


#### <a id="c-struct-tty_ldisc_ops"></a>`struct tty_ldisc_ops`

ldisc operations

**Definition**

```c
struct tty_ldisc_ops {
    char *name;
    int num;
    int (*open)(struct tty_struct *tty);
    void (*close)(struct tty_struct *tty);
    void (*flush_buffer)(struct tty_struct *tty);
    ssize_t (*read)(struct tty_struct *tty, struct file *file, u8 *buf, size_t nr, void **cookie, unsigned long offset);
    ssize_t (*write)(struct tty_struct *tty, struct file *file, const u8 *buf, size_t nr);
    int (*ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
    int (*compat_ioctl)(struct tty_struct *tty, unsigned int cmd, unsigned long arg);
    void (*set_termios)(struct tty_struct *tty, const struct ktermios *old);
    __poll_t (*poll)(struct tty_struct *tty, struct file *file, struct poll_table_struct *wait);
    void (*hangup)(struct tty_struct *tty);
    void (*receive_buf)(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count);
    void (*write_wakeup)(struct tty_struct *tty);
    void (*dcd_change)(struct tty_struct *tty, bool active);
    size_t (*receive_buf2)(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count);
    void (*lookahead_buf)(struct tty_struct *tty, const u8 *cp, const u8 *fp, size_t count);
    struct module *owner;
};
```

**Members**

- `name`: name of this ldisc rendered in /proc/tty/ldiscs
- `num`: `N_*` number (`N_TTY`, `N_HDLC`, ...) reserved to this ldisc
- `open`: \[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.


<a id="rst-driver-access"></a>

## Driver Access

Line discipline methods can call the methods of the underlying hardware driver. These are documented as a part of struct tty_operations.

<a id="rst-tty-flags"></a>

## TTY Flags

Line discipline methods have access to `tty_struct.flags` field. See [TTY Struct](</kernel/hardware/driver-api/tty/tty-struct.md>).

<a id="rst-locking"></a>

## 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.


#### <a id="c-tty_ldisc_ref_wait"></a>`tty_ldisc_ref_wait()`

```c
struct tty_ldisc * tty_ldisc_ref_wait(struct tty_struct *tty)
```

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

#### <a id="c-tty_ldisc_ref"></a>`tty_ldisc_ref()`

```c
struct tty_ldisc * tty_ldisc_ref(struct tty_struct *tty)
```

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.

#### <a id="c-tty_ldisc_deref"></a>`tty_ldisc_deref()`

```c
void tty_ldisc_deref(struct tty_ldisc *ld)
```

free a tty ldisc reference

**Parameters**

- `struct tty_ldisc *ld`: reference to free up

**Description**

Undoes the effect of [`tty_ldisc_ref()`](#c-tty_ldisc_ref) or [`tty_ldisc_ref_wait()`](#c-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.

<a id="rst-internal-functions"></a>

## Internal Functions


#### <a id="c-tty_ldisc_get"></a>`tty_ldisc_get()`

```c
struct tty_ldisc * tty_ldisc_get(struct tty_struct *tty, int disc)
```

take a reference to an ldisc

**Parameters**

- `struct tty_struct *tty`: tty device
- `int 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**

* -`EINVAL` if the discipline index is not \[`N_TTY` .. `NR_LDISCS`\] or if the
  discipline is not registered
* -`EAGAIN` if `request_module()` failed to load or register the discipline
* -`ENOMEM` if allocation failure
* Otherwise, returns a pointer to the discipline and bumps the ref count

#### <a id="c-tty_ldisc_put"></a>`tty_ldisc_put()`

```c
void tty_ldisc_put(struct tty_ldisc *ld)
```

release the ldisc

**Parameters**

- `struct tty_ldisc *ld`: lisdsc to release

**Description**

Complement of [`tty_ldisc_get()`](#c-tty_ldisc_get).

#### <a id="c-tty_set_termios_ldisc"></a>`tty_set_termios_ldisc()`

```c
void tty_set_termios_ldisc(struct tty_struct *tty, int disc)
```

set ldisc field

**Parameters**

- `struct tty_struct *tty`: tty structure
- `int 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

#### <a id="c-tty_ldisc_open"></a>`tty_ldisc_open()`

```c
int tty_ldisc_open(struct tty_struct *tty, struct tty_ldisc *ld)
```

open a line discipline

**Parameters**

- `struct tty_struct *tty`: tty we are opening the ldisc on
- `struct 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.

#### <a id="c-tty_ldisc_close"></a>`tty_ldisc_close()`

```c
void tty_ldisc_close(struct tty_struct *tty, struct tty_ldisc *ld)
```

close a line discipline

**Parameters**

- `struct tty_struct *tty`: tty we are opening the ldisc on
- `struct tty_ldisc *ld`: discipline to close

**Description**

A helper close method. Also a convenient debugging and check point.

#### <a id="c-tty_ldisc_failto"></a>`tty_ldisc_failto()`

```c
int tty_ldisc_failto(struct tty_struct *tty, int ld)
```

helper for ldisc failback

**Parameters**

- `struct tty_struct *tty`: tty to open the ldisc on
- `int 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.

#### <a id="c-tty_ldisc_restore"></a>`tty_ldisc_restore()`

```c
void tty_ldisc_restore(struct tty_struct *tty, struct tty_ldisc *old)
```

helper for tty ldisc change

**Parameters**

- `struct tty_struct *tty`: tty to recover
- `struct 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

#### <a id="c-tty_ldisc_kill"></a>`tty_ldisc_kill()`

```c
void tty_ldisc_kill(struct tty_struct *tty)
```

teardown ldisc

**Parameters**

- `struct tty_struct *tty`: tty being released

**Description**

Perform final close of the ldisc and reset **tty->ldisc**

#### <a id="c-tty_reset_termios"></a>`tty_reset_termios()`

```c
void tty_reset_termios(struct tty_struct *tty)
```

reset terminal state

**Parameters**

- `struct tty_struct *tty`: tty to reset

**Description**

Restore a terminal to the driver default state.

#### <a id="c-tty_ldisc_reinit"></a>`tty_ldisc_reinit()`

```c
int tty_ldisc_reinit(struct tty_struct *tty, int disc)
```

reinitialise the tty ldisc

**Parameters**

- `struct tty_struct *tty`: tty to reinit
- `int 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

#### <a id="c-tty_ldisc_hangup"></a>`tty_ldisc_hangup()`

```c
void tty_ldisc_hangup(struct tty_struct *tty, bool reinit)
```

hangup ldisc reset

**Parameters**

- `struct tty_struct *tty`: tty being hung up
- `bool 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.

#### <a id="c-tty_ldisc_setup"></a>`tty_ldisc_setup()`

```c
int tty_ldisc_setup(struct tty_struct *tty, struct tty_struct *o_tty)
```

open line discipline

**Parameters**

- `struct tty_struct *tty`: tty being shut down
- `struct 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.

#### <a id="c-tty_ldisc_release"></a>`tty_ldisc_release()`

```c
void tty_ldisc_release(struct tty_struct *tty)
```

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`.

#### <a id="c-tty_ldisc_init"></a>`tty_ldisc_init()`

```c
int tty_ldisc_init(struct tty_struct *tty)
```

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.

#### <a id="c-tty_ldisc_deinit"></a>`tty_ldisc_deinit()`

```c
void tty_ldisc_deinit(struct tty_struct *tty)
```

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()`](#c-tty_ldisc_setup)) when
this call is made.

---

# TTY Port

_Peios Kernel / Hardware and drivers / Driver development / TTY_

> TTY Port Functions

<a id="rst-tty-port"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



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](<#rst-tty-port-reference>) and [TTY Port Operations Reference](<#rst-tty-port-operations-reference>) sections at the bottom.

<a id="rst-tty-port-functions"></a>

## TTY Port Functions

<a id="rst-init-destroy"></a>

### Init &amp; Destroy


#### <a id="c-tty_port_init"></a>`tty_port_init()`

```c
void tty_port_init(struct tty_port *port)
```

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()`](#c-tty_port_destroy). Either
indirectly by using [`tty_port`](#c-struct-tty_port) refcounting ([`tty_port_put()`](#c-tty_port_put)) or directly if
refcounting is not used.

#### <a id="c-tty_port_destroy"></a>`tty_port_destroy()`

```c
void tty_port_destroy(struct tty_port *port)
```

destroy inited port

**Parameters**

- `struct tty_port *port`: tty port to be destroyed

**Description**

When a port was initialized using [`tty_port_init()`](#c-tty_port_init), one has to destroy the
port by this function. Either indirectly by using [`tty_port`](#c-struct-tty_port) refcounting
([`tty_port_put()`](#c-tty_port_put)) or directly if refcounting is not used.

#### <a id="c-tty_port_put"></a>`tty_port_put()`

```c
void tty_port_put(struct tty_port *port)
```

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()`](/kernel/internals/core-api/mm-api.md#c-kfree) if not provided.


<a id="rst-open-close-hangup-helpers"></a>

### Open/Close/Hangup Helpers


#### <a id="c-tty_port_shutdown"></a>`tty_port_shutdown()`

```c
void tty_port_shutdown(struct tty_port *port, struct tty_struct *tty)
```

internal helper to shutdown the device

**Parameters**

- `struct tty_port *port`: tty port to be shut down
- `struct tty_struct *tty`: the associated tty

**Description**

It is used by [`tty_port_hangup()`](#c-tty_port_hangup) and [`tty_port_close()`](#c-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()**.

#### <a id="c-tty_port_hangup"></a>`tty_port_hangup()`

```c
void tty_port_hangup(struct tty_port *port)
```

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.

#### <a id="c-tty_port_block_til_ready"></a>`tty_port_block_til_ready()`

```c
int tty_port_block_til_ready(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

Waiting logic for tty open

**Parameters**

- `struct tty_port *port`: the tty port being opened
- `struct tty_struct *tty`: the tty device being bound
- `struct file *filp`: the file pointer of the opener or `NULL`

**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).

#### <a id="c-tty_port_close_start"></a>`tty_port_close_start()`

```c
int tty_port_close_start(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

helper for tty->ops->close, part 1/2

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty being closed
- `struct 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()`](#c-tty_port_close_end).

Locking: Caller holds tty lock.

**Return**

1 if this is the last close, otherwise 0

#### <a id="c-tty_port_close_end"></a>`tty_port_close_end()`

```c
void tty_port_close_end(struct tty_port *port, struct tty_struct *tty)
```

helper for tty->ops->close, part 2/2

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty being closed

**Description**

This is a continuation of the first part: [`tty_port_close_start()`](#c-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.

#### <a id="c-tty_port_close"></a>`tty_port_close()`

```c
void tty_port_close(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

generic tty->ops->close handler

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty being closed
- `struct 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()`](#c-tty_port_close_start), [`tty_port_shutdown()`](#c-tty_port_shutdown), and
[`tty_port_close_end()`](#c-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

#### <a id="c-tty_port_install"></a>`tty_port_install()`

```c
int tty_port_install(struct tty_port *port, struct tty_driver *driver, struct tty_struct *tty)
```

generic tty->ops->install handler

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_driver *driver`: tty_driver for this device
- `struct tty_struct *tty`: tty to be installed

**Description**

It is the same as [`tty_standard_install()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_standard_install) except the provided **port** is linked
to a concrete tty specified by **tty**. Use this or [`tty_port_register_device()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-tty_port_register_device)
(or both). Call [`tty_port_link_device()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-tty_port_link_device) as a last resort.

#### <a id="c-tty_port_open"></a>`tty_port_open()`

```c
int tty_port_open(struct tty_port *port, struct tty_struct *tty, struct file *filp)
```

generic tty->ops->open handler

**Parameters**

- `struct tty_port *port`: tty_port of the device
- `struct tty_struct *tty`: tty to be opened
- `struct 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()`](#c-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()`](#c-tty_port_block_til_ready)) so
**tty** and **port** may have changed state (eg., may be hung up now).


<a id="rst-tty-refcounting"></a>

### TTY Refcounting


#### <a id="c-tty_port_tty_get"></a>`tty_port_tty_get()`

```c
struct tty_struct * tty_port_tty_get(struct tty_port *port)
```

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).

#### <a id="c-tty_port_tty_set"></a>`tty_port_tty_set()`

```c
void tty_port_tty_set(struct tty_port *port, struct tty_struct *tty)
```

set the tty of a port

**Parameters**

- `struct tty_port *port`: tty port
- `struct tty_struct *tty`: the tty

**Description**

Associate the port and tty pair. Manages any internal refcounts. Pass `NULL`
to deassociate a port.


<a id="rst-tty-helpers"></a>

### TTY Helpers


#### <a id="c-tty_port_tty_hangup"></a>`tty_port_tty_hangup()`

```c
void tty_port_tty_hangup(struct tty_port *port, bool check_clocal)
```

helper to hang up a tty asynchronously

**Parameters**

- `struct tty_port *port`: tty port
- `bool check_clocal`: hang only ttys with `CLOCAL` unset?

#### <a id="c-tty_port_tty_vhangup"></a>`tty_port_tty_vhangup()`

```c
void tty_port_tty_vhangup(struct tty_port *port)
```

helper to hang up a tty synchronously

**Parameters**

- `struct tty_port *port`: tty port



#### <a id="c-tty_port_tty_wakeup"></a>`tty_port_tty_wakeup()`

```c
void tty_port_tty_wakeup(struct tty_port *port)
```

helper to wake up a tty

**Parameters**

- `struct tty_port *port`: tty port


<a id="rst-modem-signals"></a>

### Modem Signals


#### <a id="c-tty_port_carrier_raised"></a>`tty_port_carrier_raised()`

```c
bool tty_port_carrier_raised(struct tty_port *port)
```

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.

#### <a id="c-tty_port_raise_dtr_rts"></a>`tty_port_raise_dtr_rts()`

```c
void tty_port_raise_dtr_rts(struct tty_port *port)
```

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.

#### <a id="c-tty_port_lower_dtr_rts"></a>`tty_port_lower_dtr_rts()`

```c
void tty_port_lower_dtr_rts(struct tty_port *port)
```

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.


---

<a id="rst-tty-port-reference"></a>

## TTY Port Reference


#### <a id="c-struct-tty_port"></a>`struct tty_port`

- port level information

**Definition**

```c
struct tty_port {
    struct tty_bufhead      buf;
    struct tty_struct       *tty;
    struct tty_struct       *itty;
    const struct tty_port_operations *ops;
    const struct tty_port_client_operations *client_ops;
    spinlock_t lock;
    int blocked_open;
    int count;
    wait_queue_head_t open_wait;
    wait_queue_head_t delta_msr_wait;
    unsigned long           flags;
    unsigned long           iflags;
    unsigned char           console:1;
    struct mutex            mutex;
    struct mutex            buf_mutex;
    u8 *xmit_buf;
    u8 *xmit_fifo;
    unsigned int            close_delay;
    unsigned int            closing_wait;
    int drain_delay;
    struct kref             kref;
    void *client_data;
};
```

**Members**

- `buf`: buffer for this port, locked internally
- `tty`: back pointer to [`struct tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct), valid only if the tty is open. Use
  [`tty_port_tty_get()`](#c-tty_port_tty_get) to obtain it (and [`tty_kref_put()`](/kernel/hardware/driver-api/tty/tty-struct.md#c-tty_kref_put) to release).
- `itty`: internal back pointer to [`struct tty_struct`](/kernel/hardware/driver-api/tty/tty-struct.md#c-struct-tty_struct). Avoid this. It should be
  eliminated in the long term.
- `ops`: tty port operations (like activate, shutdown), see [`struct tty_port_operations`](#c-struct-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 in [`tty_port_block_til_ready()`](#c-tty_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-`NULL`
  or 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`](#c-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()`](#c-tty_port_init) and shut down either by
[`tty_port_destroy()`](#c-tty_port_destroy) (refcounting not used), or [`tty_port_put()`](#c-tty_port_put) (refcounting).

There is a lot of helpers around [`struct tty_port`](#c-struct-tty_port) too. To name the most
significant ones: [`tty_port_open()`](#c-tty_port_open), [`tty_port_close()`](#c-tty_port_close) (or
[`tty_port_close_start()`](#c-tty_port_close_start) and [`tty_port_close_end()`](#c-tty_port_close_end) separately if need be), and
[`tty_port_hangup()`](#c-tty_port_hangup). These call **ops->activate()** and **ops->shutdown()** as
needed.


---

<a id="rst-tty-port-operations-reference"></a>

## TTY Port Operations Reference


#### <a id="c-struct-tty_port_operations"></a>`struct tty_port_operations`

- operations on tty_port

**Definition**

```c
struct tty_port_operations {
    bool (*carrier_raised)(struct tty_port *port);
    void (*dtr_rts)(struct tty_port *port, bool active);
    void (*shutdown)(struct tty_port *port);
    int (*activate)(struct tty_port *port, struct tty_struct *tty);
    void (*destruct)(struct tty_port *port);
};
```

**Members**

- `carrier_raised`: return true if the carrier is raised on **port**
- `dtr_rts`: raise the DTR line if **active** is true, otherwise lower DTR
- `shutdown`: 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 from [`tty_port_open()`](#c-tty_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_

> Initialization

<a id="rst-tty-struct"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



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](<#rst-tty-struct-reference>) at the bottom.

<a id="rst-initialization"></a>

## Initialization


#### <a id="c-tty_init_termios"></a>`tty_init_termios()`

```c
void tty_init_termios(struct tty_struct *tty)
```

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.


<a id="rst-name"></a>

## Name


#### <a id="c-tty_name"></a>`tty_name()`

```c
const char * tty_name(const struct tty_struct *tty)
```

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


<a id="rst-reference-counting"></a>

## Reference counting


#### <a id="c-tty_kref_get"></a>`tty_kref_get()`

```c
struct tty_struct * tty_kref_get(struct tty_struct *tty)
```

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.



#### <a id="c-tty_kref_put"></a>`tty_kref_put()`

```c
void tty_kref_put(struct tty_struct *tty)
```

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.


<a id="rst-install"></a>

## Install


#### <a id="c-tty_standard_install"></a>`tty_standard_install()`

```c
int tty_standard_install(struct tty_driver *driver, struct tty_struct *tty)
```

usual tty->ops->install

**Parameters**

- `struct tty_driver *driver`: the driver for the tty
- `struct 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.


<a id="rst-read-write"></a>

## Read &amp; Write


#### <a id="c-tty_put_char"></a>`tty_put_char()`

```c
int tty_put_char(struct tty_struct *tty, u8 ch)
```

write one character to a tty

**Parameters**

- `struct tty_struct *tty`: tty
- `u8 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.


<a id="rst-start-stop"></a>

## Start &amp; Stop


#### <a id="c-stop_tty"></a>`stop_tty()`

```c
void stop_tty(struct tty_struct *tty)
```

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()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) 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

#### <a id="c-start_tty"></a>`start_tty()`

```c
void start_tty(struct tty_struct *tty)
```

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()`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) method is invoked
and the line discipline woken.

- Locking:
  flow.lock


<a id="rst-wakeup"></a>

## Wakeup


#### <a id="c-tty_wakeup"></a>`tty_wakeup()`

```c
void tty_wakeup(struct tty_struct *tty)
```

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.


<a id="rst-hangup"></a>

## Hangup


#### <a id="c-tty_hangup"></a>`tty_hangup()`

```c
void tty_hangup(struct tty_struct *tty)
```

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.

#### <a id="c-tty_vhangup"></a>`tty_vhangup()`

```c
void tty_vhangup(struct tty_struct *tty)
```

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.

#### <a id="c-tty_hung_up_p"></a>`tty_hung_up_p()`

```c
int tty_hung_up_p(struct file *filp)
```

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


<a id="rst-misc"></a>

## Misc


#### <a id="c-tty_do_resize"></a>`tty_do_resize()`

```c
int tty_do_resize(struct tty_struct *tty, struct winsize *ws)
```

resize event

**Parameters**

- `struct tty_struct *tty`: tty being resized
- `struct winsize *ws`: new dimensions

**Description**

Update the termios variables and send the necessary signals to peform a
terminal resize correctly.


<a id="rst-tty-struct-flags"></a>

## TTY Struct Flags


#### <a id="c-enum-tty_struct_flags"></a>`enum tty_struct_flags`

TTY Struct Flags

**Constants**

- `TTY_THROTTLED`: Driver input is throttled. The ldisc should call
  `tty_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 the
  `tty_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 implement `TIOCSPTLCK`/`TIOCGPTLCK` logic.
- `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 post `tty_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. Use `tty_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()`](/kernel/internals/core-api/kernel-api.md#c-set_bit) and
[`clear_bit()`](/kernel/internals/core-api/kernel-api.md#c-clear_bit) to make things atomic.


<a id="rst-tty-struct-reference"></a>

## TTY Struct Reference


#### <a id="c-struct-tty_struct"></a>`struct tty_struct`

state associated with a tty while open

**Definition**

```c
struct tty_struct {
    struct kref kref;
    int index;
    struct device *dev;
    struct tty_driver *driver;
    struct tty_port *port;
    const struct tty_operations *ops;
    struct tty_ldisc *ldisc;
    struct ld_semaphore ldisc_sem;
    struct mutex atomic_write_lock;
    struct mutex legacy_mutex;
    struct mutex throttle_mutex;
    struct rw_semaphore termios_rwsem;
    struct mutex winsize_mutex;
    struct ktermios termios, termios_locked;
    char name[64];
    unsigned long flags;
    int count;
    unsigned int receive_room;
    struct winsize winsize;
    struct {
        spinlock_t lock;
        bool stopped;
        bool tco_stopped;
    } flow;
    struct {
        struct pid *pgrp;
        struct pid *session;
        spinlock_t lock;
        unsigned char pktstatus;
        bool packet;
    } ctrl;
    bool hw_stopped;
    bool closing;
    int flow_change;
    struct tty_struct *link;
    struct fasync_struct *fasync;
    wait_queue_head_t write_wait;
    wait_queue_head_t read_wait;
    struct work_struct hangup_work;
    void *disc_data;
    void *driver_data;
    spinlock_t files_lock;
    int write_cnt;
    u8 *write_buf;
    struct list_head tty_files;
    struct work_struct SAK_work;
};
```

**Members**

- `kref`: reference counting by [`tty_kref_get()`](#c-tty_kref_get) and [`tty_kref_put()`](#c-tty_kref_put), reaching zero
  frees the structure
- `index`: index of this tty (e.g. to construct **name** like tty12)
- `dev`: class device or `NULL` (e.g. ptys, serdev)
- `driver`: [`struct tty_driver`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_driver) operating this tty
- `port`: persistent storage for this device (i.e. [`struct tty_port`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port))
- `ops`: [`struct tty_operations`](/kernel/hardware/driver-api/tty/tty-driver.md#c-struct-tty_operations) of **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 pty
- `atomic_write_lock`: protects against concurrent writers, i.e. locks
  **write_cnt**, **write_buf** and similar
- `legacy_mutex`: leftover from history (BKL -> BTM -> **legacy_mutex**),
  protecting several operations on this tty
- `throttle_mutex`: protects against concurrent [`tty_throttle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_throttle_safe) and
  [`tty_unthrottle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_unthrottle_safe) (but not [`tty_unthrottle()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_unthrottle))
- `termios_rwsem`: protects **termios** and **termios_locked**
- `winsize_mutex`: protects **winsize**
- `termios`: termios for the current tty, copied from/to **driver.termios**
- `termios_locked`: locked termios (by `TIOCGLCKTRMIOS` and `TIOCSLCKTRMIOS`
  ioctls)
- `name`: name of the tty constructed by [`tty_line_name()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_line_name) (e.g. ttyS3)
- `flags`: bitwise OR of `TTY_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 lost
- `winsize`: size of the terminal "window" (cf. **winsize_mutex**)
- `flow`: flow settings grouped together
- `flow.lock`: lock for **flow** members
- `flow.stopped`: tty stopped/started by [`stop_tty()`](#c-stop_tty)/[`start_tty()`](#c-start_tty)
- `flow.tco_stopped`: tty stopped/started by `TCOOFF`/`TCOON` ioctls (it has
  precedence over **flow.stopped**)
- `ctrl`: control settings grouped together
- `ctrl.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** members
- `ctrl.pktstatus`: packet mode status (bitwise OR of `TIOCPKT_` constants)
- `ctrl.packet`: packet mode enabled
- `hw_stopped`: not controlled by the tty layer, under **driver**'s control for CTS
  handling
- `closing`: when set during close, n_tty processes only START & STOP chars
- `flow_change`: controls behavior of throttling, see [`tty_throttle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_throttle_safe) and
  [`tty_unthrottle_safe()`](/kernel/hardware/driver-api/tty/tty-ioctl.md#c-tty_unthrottle_safe)
- `link`: link to another pty (master -> slave and vice versa)
- `fasync`: state for `O_ASYNC` (for `SIGIO`); managed by `fasync_helper()`
- `write_wait`: concurrent writers are waiting in this queue until they are
  allowed to write
- `read_wait`: readers wait for data in this queue
- `hangup_work`: normally a work to perform a hangup (`do_tty_hangup()`); while
  freeing the tty, (re)used to [`release_one_tty()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-release_one_tty)
- `disc_data`: pointer to **ldisc**'s private data (e.g. to `struct n_tty_data`)
- `driver_data`: pointer to **driver**'s private data (e.g. `struct uart_state`)
- `files_lock`: protects **tty_files** list
- `write_cnt`: count of bytes written in [`tty_write()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_write) to **write_buf**
- `write_buf`: temporary buffer used during [`tty_write()`](/kernel/hardware/driver-api/tty/tty-internals.md#c-tty_write) to copy user data to
- `tty_files`: list of (re)openers of this tty (i.e. linked `struct 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`](/kernel/hardware/driver-api/tty/tty-port.md#c-struct-tty_port).
