linux/drivers/tty/tty_io.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *  Copyright (C) 1991, 1992  Linus Torvalds
   4 */
   5
   6/*
   7 * 'tty_io.c' gives an orthogonal feeling to tty's, be they consoles
   8 * or rs-channels. It also implements echoing, cooked mode etc.
   9 *
  10 * Kill-line thanks to John T Kohl, who also corrected VMIN = VTIME = 0.
  11 *
  12 * Modified by Theodore Ts'o, 9/14/92, to dynamically allocate the
  13 * tty_struct and tty_queue structures.  Previously there was an array
  14 * of 256 tty_struct's which was statically allocated, and the
  15 * tty_queue structures were allocated at boot time.  Both are now
  16 * dynamically allocated only when the tty is open.
  17 *
  18 * Also restructured routines so that there is more of a separation
  19 * between the high-level tty routines (tty_io.c and tty_ioctl.c) and
  20 * the low-level tty routines (serial.c, pty.c, console.c).  This
  21 * makes for cleaner and more compact code.  -TYT, 9/17/92
  22 *
  23 * Modified by Fred N. van Kempen, 01/29/93, to add line disciplines
  24 * which can be dynamically activated and de-activated by the line
  25 * discipline handling modules (like SLIP).
  26 *
  27 * NOTE: pay no attention to the line discipline code (yet); its
  28 * interface is still subject to change in this version...
  29 * -- TYT, 1/31/92
  30 *
  31 * Added functionality to the OPOST tty handling.  No delays, but all
  32 * other bits should be there.
  33 *      -- Nick Holloway <alfie@dcs.warwick.ac.uk>, 27th May 1993.
  34 *
  35 * Rewrote canonical mode and added more termios flags.
  36 *      -- julian@uhunix.uhcc.hawaii.edu (J. Cowley), 13Jan94
  37 *
  38 * Reorganized FASYNC support so mouse code can share it.
  39 *      -- ctm@ardi.com, 9Sep95
  40 *
  41 * New TIOCLINUX variants added.
  42 *      -- mj@k332.feld.cvut.cz, 19-Nov-95
  43 *
  44 * Restrict vt switching via ioctl()
  45 *      -- grif@cs.ucr.edu, 5-Dec-95
  46 *
  47 * Move console and virtual terminal code to more appropriate files,
  48 * implement CONFIG_VT and generalize console device interface.
  49 *      -- Marko Kohtala <Marko.Kohtala@hut.fi>, March 97
  50 *
  51 * Rewrote tty_init_dev and tty_release_dev to eliminate races.
  52 *      -- Bill Hawes <whawes@star.net>, June 97
  53 *
  54 * Added devfs support.
  55 *      -- C. Scott Ananian <cananian@alumni.princeton.edu>, 13-Jan-1998
  56 *
  57 * Added support for a Unix98-style ptmx device.
  58 *      -- C. Scott Ananian <cananian@alumni.princeton.edu>, 14-Jan-1998
  59 *
  60 * Reduced memory usage for older ARM systems
  61 *      -- Russell King <rmk@arm.linux.org.uk>
  62 *
  63 * Move do_SAK() into process context.  Less stack use in devfs functions.
  64 * alloc_tty_struct() always uses kmalloc()
  65 *                       -- Andrew Morton <andrewm@uow.edu.eu> 17Mar01
  66 */
  67
  68#include <linux/types.h>
  69#include <linux/major.h>
  70#include <linux/errno.h>
  71#include <linux/signal.h>
  72#include <linux/fcntl.h>
  73#include <linux/sched/signal.h>
  74#include <linux/sched/task.h>
  75#include <linux/interrupt.h>
  76#include <linux/tty.h>
  77#include <linux/tty_driver.h>
  78#include <linux/tty_flip.h>
  79#include <linux/devpts_fs.h>
  80#include <linux/file.h>
  81#include <linux/fdtable.h>
  82#include <linux/console.h>
  83#include <linux/timer.h>
  84#include <linux/ctype.h>
  85#include <linux/kd.h>
  86#include <linux/mm.h>
  87#include <linux/string.h>
  88#include <linux/slab.h>
  89#include <linux/poll.h>
  90#include <linux/proc_fs.h>
  91#include <linux/init.h>
  92#include <linux/module.h>
  93#include <linux/device.h>
  94#include <linux/wait.h>
  95#include <linux/bitops.h>
  96#include <linux/delay.h>
  97#include <linux/seq_file.h>
  98#include <linux/serial.h>
  99#include <linux/ratelimit.h>
 100
 101#include <linux/uaccess.h>
 102
 103#include <linux/kbd_kern.h>
 104#include <linux/vt_kern.h>
 105#include <linux/selection.h>
 106
 107#include <linux/kmod.h>
 108#include <linux/nsproxy.h>
 109
 110#undef TTY_DEBUG_HANGUP
 111#ifdef TTY_DEBUG_HANGUP
 112# define tty_debug_hangup(tty, f, args...)      tty_debug(tty, f, ##args)
 113#else
 114# define tty_debug_hangup(tty, f, args...)      do { } while (0)
 115#endif
 116
 117#define TTY_PARANOIA_CHECK 1
 118#define CHECK_TTY_COUNT 1
 119
 120struct ktermios tty_std_termios = {     /* for the benefit of tty drivers  */
 121        .c_iflag = ICRNL | IXON,
 122        .c_oflag = OPOST | ONLCR,
 123        .c_cflag = B38400 | CS8 | CREAD | HUPCL,
 124        .c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |
 125                   ECHOCTL | ECHOKE | IEXTEN,
 126        .c_cc = INIT_C_CC,
 127        .c_ispeed = 38400,
 128        .c_ospeed = 38400,
 129        /* .c_line = N_TTY, */
 130};
 131
 132EXPORT_SYMBOL(tty_std_termios);
 133
 134/* This list gets poked at by procfs and various bits of boot up code. This
 135   could do with some rationalisation such as pulling the tty proc function
 136   into this file */
 137
 138LIST_HEAD(tty_drivers);                 /* linked list of tty drivers */
 139
 140/* Mutex to protect creating and releasing a tty */
 141DEFINE_MUTEX(tty_mutex);
 142
 143static ssize_t tty_read(struct file *, char __user *, size_t, loff_t *);
 144static ssize_t tty_write(struct file *, const char __user *, size_t, loff_t *);
 145ssize_t redirected_tty_write(struct file *, const char __user *,
 146                                                        size_t, loff_t *);
 147static __poll_t tty_poll(struct file *, poll_table *);
 148static int tty_open(struct inode *, struct file *);
 149long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
 150#ifdef CONFIG_COMPAT
 151static long tty_compat_ioctl(struct file *file, unsigned int cmd,
 152                                unsigned long arg);
 153#else
 154#define tty_compat_ioctl NULL
 155#endif
 156static int __tty_fasync(int fd, struct file *filp, int on);
 157static int tty_fasync(int fd, struct file *filp, int on);
 158static void release_tty(struct tty_struct *tty, int idx);
 159
 160/**
 161 *      free_tty_struct         -       free a disused tty
 162 *      @tty: tty struct to free
 163 *
 164 *      Free the write buffers, tty queue and tty memory itself.
 165 *
 166 *      Locking: none. Must be called after tty is definitely unused
 167 */
 168
 169static void free_tty_struct(struct tty_struct *tty)
 170{
 171        tty_ldisc_deinit(tty);
 172        put_device(tty->dev);
 173        kfree(tty->write_buf);
 174        tty->magic = 0xDEADDEAD;
 175        kfree(tty);
 176}
 177
 178static inline struct tty_struct *file_tty(struct file *file)
 179{
 180        return ((struct tty_file_private *)file->private_data)->tty;
 181}
 182
 183int tty_alloc_file(struct file *file)
 184{
 185        struct tty_file_private *priv;
 186
 187        priv = kmalloc(sizeof(*priv), GFP_KERNEL);
 188        if (!priv)
 189                return -ENOMEM;
 190
 191        file->private_data = priv;
 192
 193        return 0;
 194}
 195
 196/* Associate a new file with the tty structure */
 197void tty_add_file(struct tty_struct *tty, struct file *file)
 198{
 199        struct tty_file_private *priv = file->private_data;
 200
 201        priv->tty = tty;
 202        priv->file = file;
 203
 204        spin_lock(&tty->files_lock);
 205        list_add(&priv->list, &tty->tty_files);
 206        spin_unlock(&tty->files_lock);
 207}
 208
 209/**
 210 * tty_free_file - free file->private_data
 211 *
 212 * This shall be used only for fail path handling when tty_add_file was not
 213 * called yet.
 214 */
 215void tty_free_file(struct file *file)
 216{
 217        struct tty_file_private *priv = file->private_data;
 218
 219        file->private_data = NULL;
 220        kfree(priv);
 221}
 222
 223/* Delete file from its tty */
 224static void tty_del_file(struct file *file)
 225{
 226        struct tty_file_private *priv = file->private_data;
 227        struct tty_struct *tty = priv->tty;
 228
 229        spin_lock(&tty->files_lock);
 230        list_del(&priv->list);
 231        spin_unlock(&tty->files_lock);
 232        tty_free_file(file);
 233}
 234
 235/**
 236 *      tty_name        -       return tty naming
 237 *      @tty: tty structure
 238 *
 239 *      Convert a tty structure into a name. The name reflects the kernel
 240 *      naming policy and if udev is in use may not reflect user space
 241 *
 242 *      Locking: none
 243 */
 244
 245const char *tty_name(const struct tty_struct *tty)
 246{
 247        if (!tty) /* Hmm.  NULL pointer.  That's fun. */
 248                return "NULL tty";
 249        return tty->name;
 250}
 251
 252EXPORT_SYMBOL(tty_name);
 253
 254const char *tty_driver_name(const struct tty_struct *tty)
 255{
 256        if (!tty || !tty->driver)
 257                return "";
 258        return tty->driver->name;
 259}
 260
 261static int tty_paranoia_check(struct tty_struct *tty, struct inode *inode,
 262                              const char *routine)
 263{
 264#ifdef TTY_PARANOIA_CHECK
 265        if (!tty) {
 266                pr_warn("(%d:%d): %s: NULL tty\n",
 267                        imajor(inode), iminor(inode), routine);
 268                return 1;
 269        }
 270        if (tty->magic != TTY_MAGIC) {
 271                pr_warn("(%d:%d): %s: bad magic number\n",
 272                        imajor(inode), iminor(inode), routine);
 273                return 1;
 274        }
 275#endif
 276        return 0;
 277}
 278
 279/* Caller must hold tty_lock */
 280static int check_tty_count(struct tty_struct *tty, const char *routine)
 281{
 282#ifdef CHECK_TTY_COUNT
 283        struct list_head *p;
 284        int count = 0, kopen_count = 0;
 285
 286        spin_lock(&tty->files_lock);
 287        list_for_each(p, &tty->tty_files) {
 288                count++;
 289        }
 290        spin_unlock(&tty->files_lock);
 291        if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
 292            tty->driver->subtype == PTY_TYPE_SLAVE &&
 293            tty->link && tty->link->count)
 294                count++;
 295        if (tty_port_kopened(tty->port))
 296                kopen_count++;
 297        if (tty->count != (count + kopen_count)) {
 298                tty_warn(tty, "%s: tty->count(%d) != (#fd's(%d) + #kopen's(%d))\n",
 299                         routine, tty->count, count, kopen_count);
 300                return (count + kopen_count);
 301        }
 302#endif
 303        return 0;
 304}
 305
 306/**
 307 *      get_tty_driver          -       find device of a tty
 308 *      @dev_t: device identifier
 309 *      @index: returns the index of the tty
 310 *
 311 *      This routine returns a tty driver structure, given a device number
 312 *      and also passes back the index number.
 313 *
 314 *      Locking: caller must hold tty_mutex
 315 */
 316
 317static struct tty_driver *get_tty_driver(dev_t device, int *index)
 318{
 319        struct tty_driver *p;
 320
 321        list_for_each_entry(p, &tty_drivers, tty_drivers) {
 322                dev_t base = MKDEV(p->major, p->minor_start);
 323                if (device < base || device >= base + p->num)
 324                        continue;
 325                *index = device - base;
 326                return tty_driver_kref_get(p);
 327        }
 328        return NULL;
 329}
 330
 331/**
 332 *      tty_dev_name_to_number  -       return dev_t for device name
 333 *      @name: user space name of device under /dev
 334 *      @number: pointer to dev_t that this function will populate
 335 *
 336 *      This function converts device names like ttyS0 or ttyUSB1 into dev_t
 337 *      like (4, 64) or (188, 1). If no corresponding driver is registered then
 338 *      the function returns -ENODEV.
 339 *
 340 *      Locking: this acquires tty_mutex to protect the tty_drivers list from
 341 *              being modified while we are traversing it, and makes sure to
 342 *              release it before exiting.
 343 */
 344int tty_dev_name_to_number(const char *name, dev_t *number)
 345{
 346        struct tty_driver *p;
 347        int ret;
 348        int index, prefix_length = 0;
 349        const char *str;
 350
 351        for (str = name; *str && !isdigit(*str); str++)
 352                ;
 353
 354        if (!*str)
 355                return -EINVAL;
 356
 357        ret = kstrtoint(str, 10, &index);
 358        if (ret)
 359                return ret;
 360
 361        prefix_length = str - name;
 362        mutex_lock(&tty_mutex);
 363
 364        list_for_each_entry(p, &tty_drivers, tty_drivers)
 365                if (prefix_length == strlen(p->name) && strncmp(name,
 366                                        p->name, prefix_length) == 0) {
 367                        if (index < p->num) {
 368                                *number = MKDEV(p->major, p->minor_start + index);
 369                                goto out;
 370                        }
 371                }
 372
 373        /* if here then driver wasn't found */
 374        ret = -ENODEV;
 375out:
 376        mutex_unlock(&tty_mutex);
 377        return ret;
 378}
 379EXPORT_SYMBOL_GPL(tty_dev_name_to_number);
 380
 381#ifdef CONFIG_CONSOLE_POLL
 382
 383/**
 384 *      tty_find_polling_driver -       find device of a polled tty
 385 *      @name: name string to match
 386 *      @line: pointer to resulting tty line nr
 387 *
 388 *      This routine returns a tty driver structure, given a name
 389 *      and the condition that the tty driver is capable of polled
 390 *      operation.
 391 */
 392struct tty_driver *tty_find_polling_driver(char *name, int *line)
 393{
 394        struct tty_driver *p, *res = NULL;
 395        int tty_line = 0;
 396        int len;
 397        char *str, *stp;
 398
 399        for (str = name; *str; str++)
 400                if ((*str >= '0' && *str <= '9') || *str == ',')
 401                        break;
 402        if (!*str)
 403                return NULL;
 404
 405        len = str - name;
 406        tty_line = simple_strtoul(str, &str, 10);
 407
 408        mutex_lock(&tty_mutex);
 409        /* Search through the tty devices to look for a match */
 410        list_for_each_entry(p, &tty_drivers, tty_drivers) {
 411                if (strncmp(name, p->name, len) != 0)
 412                        continue;
 413                stp = str;
 414                if (*stp == ',')
 415                        stp++;
 416                if (*stp == '\0')
 417                        stp = NULL;
 418
 419                if (tty_line >= 0 && tty_line < p->num && p->ops &&
 420                    p->ops->poll_init && !p->ops->poll_init(p, tty_line, stp)) {
 421                        res = tty_driver_kref_get(p);
 422                        *line = tty_line;
 423                        break;
 424                }
 425        }
 426        mutex_unlock(&tty_mutex);
 427
 428        return res;
 429}
 430EXPORT_SYMBOL_GPL(tty_find_polling_driver);
 431#endif
 432
 433static ssize_t hung_up_tty_read(struct file *file, char __user *buf,
 434                                size_t count, loff_t *ppos)
 435{
 436        return 0;
 437}
 438
 439static ssize_t hung_up_tty_write(struct file *file, const char __user *buf,
 440                                 size_t count, loff_t *ppos)
 441{
 442        return -EIO;
 443}
 444
 445/* No kernel lock held - none needed ;) */
 446static __poll_t hung_up_tty_poll(struct file *filp, poll_table *wait)
 447{
 448        return EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDNORM | EPOLLWRNORM;
 449}
 450
 451static long hung_up_tty_ioctl(struct file *file, unsigned int cmd,
 452                unsigned long arg)
 453{
 454        return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
 455}
 456
 457static long hung_up_tty_compat_ioctl(struct file *file,
 458                                     unsigned int cmd, unsigned long arg)
 459{
 460        return cmd == TIOCSPGRP ? -ENOTTY : -EIO;
 461}
 462
 463static int hung_up_tty_fasync(int fd, struct file *file, int on)
 464{
 465        return -ENOTTY;
 466}
 467
 468static void tty_show_fdinfo(struct seq_file *m, struct file *file)
 469{
 470        struct tty_struct *tty = file_tty(file);
 471
 472        if (tty && tty->ops && tty->ops->show_fdinfo)
 473                tty->ops->show_fdinfo(tty, m);
 474}
 475
 476static const struct file_operations tty_fops = {
 477        .llseek         = no_llseek,
 478        .read           = tty_read,
 479        .write          = tty_write,
 480        .poll           = tty_poll,
 481        .unlocked_ioctl = tty_ioctl,
 482        .compat_ioctl   = tty_compat_ioctl,
 483        .open           = tty_open,
 484        .release        = tty_release,
 485        .fasync         = tty_fasync,
 486        .show_fdinfo    = tty_show_fdinfo,
 487};
 488
 489static const struct file_operations console_fops = {
 490        .llseek         = no_llseek,
 491        .read           = tty_read,
 492        .write          = redirected_tty_write,
 493        .poll           = tty_poll,
 494        .unlocked_ioctl = tty_ioctl,
 495        .compat_ioctl   = tty_compat_ioctl,
 496        .open           = tty_open,
 497        .release        = tty_release,
 498        .fasync         = tty_fasync,
 499};
 500
 501static const struct file_operations hung_up_tty_fops = {
 502        .llseek         = no_llseek,
 503        .read           = hung_up_tty_read,
 504        .write          = hung_up_tty_write,
 505        .poll           = hung_up_tty_poll,
 506        .unlocked_ioctl = hung_up_tty_ioctl,
 507        .compat_ioctl   = hung_up_tty_compat_ioctl,
 508        .release        = tty_release,
 509        .fasync         = hung_up_tty_fasync,
 510};
 511
 512static DEFINE_SPINLOCK(redirect_lock);
 513static struct file *redirect;
 514
 515/**
 516 *      tty_wakeup      -       request more data
 517 *      @tty: terminal
 518 *
 519 *      Internal and external helper for wakeups of tty. This function
 520 *      informs the line discipline if present that the driver is ready
 521 *      to receive more output data.
 522 */
 523
 524void tty_wakeup(struct tty_struct *tty)
 525{
 526        struct tty_ldisc *ld;
 527
 528        if (test_bit(TTY_DO_WRITE_WAKEUP, &tty->flags)) {
 529                ld = tty_ldisc_ref(tty);
 530                if (ld) {
 531                        if (ld->ops->write_wakeup)
 532                                ld->ops->write_wakeup(tty);
 533                        tty_ldisc_deref(ld);
 534                }
 535        }
 536        wake_up_interruptible_poll(&tty->write_wait, EPOLLOUT);
 537}
 538
 539EXPORT_SYMBOL_GPL(tty_wakeup);
 540
 541/**
 542 *      __tty_hangup            -       actual handler for hangup events
 543 *      @work: tty device
 544 *
 545 *      This can be called by a "kworker" kernel thread.  That is process
 546 *      synchronous but doesn't hold any locks, so we need to make sure we
 547 *      have the appropriate locks for what we're doing.
 548 *
 549 *      The hangup event clears any pending redirections onto the hung up
 550 *      device. It ensures future writes will error and it does the needed
 551 *      line discipline hangup and signal delivery. The tty object itself
 552 *      remains intact.
 553 *
 554 *      Locking:
 555 *              BTM
 556 *                redirect lock for undoing redirection
 557 *                file list lock for manipulating list of ttys
 558 *                tty_ldiscs_lock from called functions
 559 *                termios_rwsem resetting termios data
 560 *                tasklist_lock to walk task list for hangup event
 561 *                  ->siglock to protect ->signal/->sighand
 562 */
 563static void __tty_hangup(struct tty_struct *tty, int exit_session)
 564{
 565        struct file *cons_filp = NULL;
 566        struct file *filp, *f = NULL;
 567        struct tty_file_private *priv;
 568        int    closecount = 0, n;
 569        int refs;
 570
 571        if (!tty)
 572                return;
 573
 574
 575        spin_lock(&redirect_lock);
 576        if (redirect && file_tty(redirect) == tty) {
 577                f = redirect;
 578                redirect = NULL;
 579        }
 580        spin_unlock(&redirect_lock);
 581
 582        tty_lock(tty);
 583
 584        if (test_bit(TTY_HUPPED, &tty->flags)) {
 585                tty_unlock(tty);
 586                return;
 587        }
 588
 589        /*
 590         * Some console devices aren't actually hung up for technical and
 591         * historical reasons, which can lead to indefinite interruptible
 592         * sleep in n_tty_read().  The following explicitly tells
 593         * n_tty_read() to abort readers.
 594         */
 595        set_bit(TTY_HUPPING, &tty->flags);
 596
 597        /* inuse_filps is protected by the single tty lock,
 598           this really needs to change if we want to flush the
 599           workqueue with the lock held */
 600        check_tty_count(tty, "tty_hangup");
 601
 602        spin_lock(&tty->files_lock);
 603        /* This breaks for file handles being sent over AF_UNIX sockets ? */
 604        list_for_each_entry(priv, &tty->tty_files, list) {
 605                filp = priv->file;
 606                if (filp->f_op->write == redirected_tty_write)
 607                        cons_filp = filp;
 608                if (filp->f_op->write != tty_write)
 609                        continue;
 610                closecount++;
 611                __tty_fasync(-1, filp, 0);      /* can't block */
 612                filp->f_op = &hung_up_tty_fops;
 613        }
 614        spin_unlock(&tty->files_lock);
 615
 616        refs = tty_signal_session_leader(tty, exit_session);
 617        /* Account for the p->signal references we killed */
 618        while (refs--)
 619                tty_kref_put(tty);
 620
 621        tty_ldisc_hangup(tty, cons_filp != NULL);
 622
 623        spin_lock_irq(&tty->ctrl_lock);
 624        clear_bit(TTY_THROTTLED, &tty->flags);
 625        clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
 626        put_pid(tty->session);
 627        put_pid(tty->pgrp);
 628        tty->session = NULL;
 629        tty->pgrp = NULL;
 630        tty->ctrl_status = 0;
 631        spin_unlock_irq(&tty->ctrl_lock);
 632
 633        /*
 634         * If one of the devices matches a console pointer, we
 635         * cannot just call hangup() because that will cause
 636         * tty->count and state->count to go out of sync.
 637         * So we just call close() the right number of times.
 638         */
 639        if (cons_filp) {
 640                if (tty->ops->close)
 641                        for (n = 0; n < closecount; n++)
 642                                tty->ops->close(tty, cons_filp);
 643        } else if (tty->ops->hangup)
 644                tty->ops->hangup(tty);
 645        /*
 646         * We don't want to have driver/ldisc interactions beyond the ones
 647         * we did here. The driver layer expects no calls after ->hangup()
 648         * from the ldisc side, which is now guaranteed.
 649         */
 650        set_bit(TTY_HUPPED, &tty->flags);
 651        clear_bit(TTY_HUPPING, &tty->flags);
 652        tty_unlock(tty);
 653
 654        if (f)
 655                fput(f);
 656}
 657
 658static void do_tty_hangup(struct work_struct *work)
 659{
 660        struct tty_struct *tty =
 661                container_of(work, struct tty_struct, hangup_work);
 662
 663        __tty_hangup(tty, 0);
 664}
 665
 666/**
 667 *      tty_hangup              -       trigger a hangup event
 668 *      @tty: tty to hangup
 669 *
 670 *      A carrier loss (virtual or otherwise) has occurred on this like
 671 *      schedule a hangup sequence to run after this event.
 672 */
 673
 674void tty_hangup(struct tty_struct *tty)
 675{
 676        tty_debug_hangup(tty, "hangup\n");
 677        schedule_work(&tty->hangup_work);
 678}
 679
 680EXPORT_SYMBOL(tty_hangup);
 681
 682/**
 683 *      tty_vhangup             -       process vhangup
 684 *      @tty: tty to hangup
 685 *
 686 *      The user has asked via system call for the terminal to be hung up.
 687 *      We do this synchronously so that when the syscall returns the process
 688 *      is complete. That guarantee is necessary for security reasons.
 689 */
 690
 691void tty_vhangup(struct tty_struct *tty)
 692{
 693        tty_debug_hangup(tty, "vhangup\n");
 694        __tty_hangup(tty, 0);
 695}
 696
 697EXPORT_SYMBOL(tty_vhangup);
 698
 699
 700/**
 701 *      tty_vhangup_self        -       process vhangup for own ctty
 702 *
 703 *      Perform a vhangup on the current controlling tty
 704 */
 705
 706void tty_vhangup_self(void)
 707{
 708        struct tty_struct *tty;
 709
 710        tty = get_current_tty();
 711        if (tty) {
 712                tty_vhangup(tty);
 713                tty_kref_put(tty);
 714        }
 715}
 716
 717/**
 718 *      tty_vhangup_session             -       hangup session leader exit
 719 *      @tty: tty to hangup
 720 *
 721 *      The session leader is exiting and hanging up its controlling terminal.
 722 *      Every process in the foreground process group is signalled SIGHUP.
 723 *
 724 *      We do this synchronously so that when the syscall returns the process
 725 *      is complete. That guarantee is necessary for security reasons.
 726 */
 727
 728void tty_vhangup_session(struct tty_struct *tty)
 729{
 730        tty_debug_hangup(tty, "session hangup\n");
 731        __tty_hangup(tty, 1);
 732}
 733
 734/**
 735 *      tty_hung_up_p           -       was tty hung up
 736 *      @filp: file pointer of tty
 737 *
 738 *      Return true if the tty has been subject to a vhangup or a carrier
 739 *      loss
 740 */
 741
 742int tty_hung_up_p(struct file *filp)
 743{
 744        return (filp && filp->f_op == &hung_up_tty_fops);
 745}
 746
 747EXPORT_SYMBOL(tty_hung_up_p);
 748
 749/**
 750 *      stop_tty        -       propagate flow control
 751 *      @tty: tty to stop
 752 *
 753 *      Perform flow control to the driver. May be called
 754 *      on an already stopped device and will not re-call the driver
 755 *      method.
 756 *
 757 *      This functionality is used by both the line disciplines for
 758 *      halting incoming flow and by the driver. It may therefore be
 759 *      called from any context, may be under the tty atomic_write_lock
 760 *      but not always.
 761 *
 762 *      Locking:
 763 *              flow_lock
 764 */
 765
 766void __stop_tty(struct tty_struct *tty)
 767{
 768        if (tty->stopped)
 769                return;
 770        tty->stopped = 1;
 771        if (tty->ops->stop)
 772                tty->ops->stop(tty);
 773}
 774
 775void stop_tty(struct tty_struct *tty)
 776{
 777        unsigned long flags;
 778
 779        spin_lock_irqsave(&tty->flow_lock, flags);
 780        __stop_tty(tty);
 781        spin_unlock_irqrestore(&tty->flow_lock, flags);
 782}
 783EXPORT_SYMBOL(stop_tty);
 784
 785/**
 786 *      start_tty       -       propagate flow control
 787 *      @tty: tty to start
 788 *
 789 *      Start a tty that has been stopped if at all possible. If this
 790 *      tty was previous stopped and is now being started, the driver
 791 *      start method is invoked and the line discipline woken.
 792 *
 793 *      Locking:
 794 *              flow_lock
 795 */
 796
 797void __start_tty(struct tty_struct *tty)
 798{
 799        if (!tty->stopped || tty->flow_stopped)
 800                return;
 801        tty->stopped = 0;
 802        if (tty->ops->start)
 803                tty->ops->start(tty);
 804        tty_wakeup(tty);
 805}
 806
 807void start_tty(struct tty_struct *tty)
 808{
 809        unsigned long flags;
 810
 811        spin_lock_irqsave(&tty->flow_lock, flags);
 812        __start_tty(tty);
 813        spin_unlock_irqrestore(&tty->flow_lock, flags);
 814}
 815EXPORT_SYMBOL(start_tty);
 816
 817static void tty_update_time(struct timespec *time)
 818{
 819        unsigned long sec = get_seconds();
 820
 821        /*
 822         * We only care if the two values differ in anything other than the
 823         * lower three bits (i.e every 8 seconds).  If so, then we can update
 824         * the time of the tty device, otherwise it could be construded as a
 825         * security leak to let userspace know the exact timing of the tty.
 826         */
 827        if ((sec ^ time->tv_sec) & ~7)
 828                time->tv_sec = sec;
 829}
 830
 831/**
 832 *      tty_read        -       read method for tty device files
 833 *      @file: pointer to tty file
 834 *      @buf: user buffer
 835 *      @count: size of user buffer
 836 *      @ppos: unused
 837 *
 838 *      Perform the read system call function on this terminal device. Checks
 839 *      for hung up devices before calling the line discipline method.
 840 *
 841 *      Locking:
 842 *              Locks the line discipline internally while needed. Multiple
 843 *      read calls may be outstanding in parallel.
 844 */
 845
 846static ssize_t tty_read(struct file *file, char __user *buf, size_t count,
 847                        loff_t *ppos)
 848{
 849        int i;
 850        struct inode *inode = file_inode(file);
 851        struct tty_struct *tty = file_tty(file);
 852        struct tty_ldisc *ld;
 853
 854        if (tty_paranoia_check(tty, inode, "tty_read"))
 855                return -EIO;
 856        if (!tty || tty_io_error(tty))
 857                return -EIO;
 858
 859        /* We want to wait for the line discipline to sort out in this
 860           situation */
 861        ld = tty_ldisc_ref_wait(tty);
 862        if (!ld)
 863                return hung_up_tty_read(file, buf, count, ppos);
 864        if (ld->ops->read)
 865                i = ld->ops->read(tty, file, buf, count);
 866        else
 867                i = -EIO;
 868        tty_ldisc_deref(ld);
 869
 870        if (i > 0) {
 871                struct timespec ts;
 872
 873                ts = timespec64_to_timespec(inode->i_atime);
 874                tty_update_time(&ts);
 875                inode->i_atime = timespec_to_timespec64(ts);
 876        }
 877
 878        return i;
 879}
 880
 881static void tty_write_unlock(struct tty_struct *tty)
 882{
 883        mutex_unlock(&tty->atomic_write_lock);
 884        wake_up_interruptible_poll(&tty->write_wait, EPOLLOUT);
 885}
 886
 887static int tty_write_lock(struct tty_struct *tty, int ndelay)
 888{
 889        if (!mutex_trylock(&tty->atomic_write_lock)) {
 890                if (ndelay)
 891                        return -EAGAIN;
 892                if (mutex_lock_interruptible(&tty->atomic_write_lock))
 893                        return -ERESTARTSYS;
 894        }
 895        return 0;
 896}
 897
 898/*
 899 * Split writes up in sane blocksizes to avoid
 900 * denial-of-service type attacks
 901 */
 902static inline ssize_t do_tty_write(
 903        ssize_t (*write)(struct tty_struct *, struct file *, const unsigned char *, size_t),
 904        struct tty_struct *tty,
 905        struct file *file,
 906        const char __user *buf,
 907        size_t count)
 908{
 909        ssize_t ret, written = 0;
 910        unsigned int chunk;
 911
 912        ret = tty_write_lock(tty, file->f_flags & O_NDELAY);
 913        if (ret < 0)
 914                return ret;
 915
 916        /*
 917         * We chunk up writes into a temporary buffer. This
 918         * simplifies low-level drivers immensely, since they
 919         * don't have locking issues and user mode accesses.
 920         *
 921         * But if TTY_NO_WRITE_SPLIT is set, we should use a
 922         * big chunk-size..
 923         *
 924         * The default chunk-size is 2kB, because the NTTY
 925         * layer has problems with bigger chunks. It will
 926         * claim to be able to handle more characters than
 927         * it actually does.
 928         *
 929         * FIXME: This can probably go away now except that 64K chunks
 930         * are too likely to fail unless switched to vmalloc...
 931         */
 932        chunk = 2048;
 933        if (test_bit(TTY_NO_WRITE_SPLIT, &tty->flags))
 934                chunk = 65536;
 935        if (count < chunk)
 936                chunk = count;
 937
 938        /* write_buf/write_cnt is protected by the atomic_write_lock mutex */
 939        if (tty->write_cnt < chunk) {
 940                unsigned char *buf_chunk;
 941
 942                if (chunk < 1024)
 943                        chunk = 1024;
 944
 945                buf_chunk = kmalloc(chunk, GFP_KERNEL);
 946                if (!buf_chunk) {
 947                        ret = -ENOMEM;
 948                        goto out;
 949                }
 950                kfree(tty->write_buf);
 951                tty->write_cnt = chunk;
 952                tty->write_buf = buf_chunk;
 953        }
 954
 955        /* Do the write .. */
 956        for (;;) {
 957                size_t size = count;
 958                if (size > chunk)
 959                        size = chunk;
 960                ret = -EFAULT;
 961                if (copy_from_user(tty->write_buf, buf, size))
 962                        break;
 963                ret = write(tty, file, tty->write_buf, size);
 964                if (ret <= 0)
 965                        break;
 966                written += ret;
 967                buf += ret;
 968                count -= ret;
 969                if (!count)
 970                        break;
 971                ret = -ERESTARTSYS;
 972                if (signal_pending(current))
 973                        break;
 974                cond_resched();
 975        }
 976        if (written) {
 977                struct timespec ts;
 978
 979                ts = timespec64_to_timespec(file_inode(file)->i_mtime);
 980                tty_update_time(&ts);
 981                file_inode(file)->i_mtime = timespec_to_timespec64(ts);
 982                ret = written;
 983        }
 984out:
 985        tty_write_unlock(tty);
 986        return ret;
 987}
 988
 989/**
 990 * tty_write_message - write a message to a certain tty, not just the console.
 991 * @tty: the destination tty_struct
 992 * @msg: the message to write
 993 *
 994 * This is used for messages that need to be redirected to a specific tty.
 995 * We don't put it into the syslog queue right now maybe in the future if
 996 * really needed.
 997 *
 998 * We must still hold the BTM and test the CLOSING flag for the moment.
 999 */
1000
1001void tty_write_message(struct tty_struct *tty, char *msg)
1002{
1003        if (tty) {
1004                mutex_lock(&tty->atomic_write_lock);
1005                tty_lock(tty);
1006                if (tty->ops->write && tty->count > 0)
1007                        tty->ops->write(tty, msg, strlen(msg));
1008                tty_unlock(tty);
1009                tty_write_unlock(tty);
1010        }
1011        return;
1012}
1013
1014
1015/**
1016 *      tty_write               -       write method for tty device file
1017 *      @file: tty file pointer
1018 *      @buf: user data to write
1019 *      @count: bytes to write
1020 *      @ppos: unused
1021 *
1022 *      Write data to a tty device via the line discipline.
1023 *
1024 *      Locking:
1025 *              Locks the line discipline as required
1026 *              Writes to the tty driver are serialized by the atomic_write_lock
1027 *      and are then processed in chunks to the device. The line discipline
1028 *      write method will not be invoked in parallel for each device.
1029 */
1030
1031static ssize_t tty_write(struct file *file, const char __user *buf,
1032                                                size_t count, loff_t *ppos)
1033{
1034        struct tty_struct *tty = file_tty(file);
1035        struct tty_ldisc *ld;
1036        ssize_t ret;
1037
1038        if (tty_paranoia_check(tty, file_inode(file), "tty_write"))
1039                return -EIO;
1040        if (!tty || !tty->ops->write || tty_io_error(tty))
1041                        return -EIO;
1042        /* Short term debug to catch buggy drivers */
1043        if (tty->ops->write_room == NULL)
1044                tty_err(tty, "missing write_room method\n");
1045        ld = tty_ldisc_ref_wait(tty);
1046        if (!ld)
1047                return hung_up_tty_write(file, buf, count, ppos);
1048        if (!ld->ops->write)
1049                ret = -EIO;
1050        else
1051                ret = do_tty_write(ld->ops->write, tty, file, buf, count);
1052        tty_ldisc_deref(ld);
1053        return ret;
1054}
1055
1056ssize_t redirected_tty_write(struct file *file, const char __user *buf,
1057                                                size_t count, loff_t *ppos)
1058{
1059        struct file *p = NULL;
1060
1061        spin_lock(&redirect_lock);
1062        if (redirect)
1063                p = get_file(redirect);
1064        spin_unlock(&redirect_lock);
1065
1066        if (p) {
1067                ssize_t res;
1068                res = vfs_write(p, buf, count, &p->f_pos);
1069                fput(p);
1070                return res;
1071        }
1072        return tty_write(file, buf, count, ppos);
1073}
1074
1075/**
1076 *      tty_send_xchar  -       send priority character
1077 *
1078 *      Send a high priority character to the tty even if stopped
1079 *
1080 *      Locking: none for xchar method, write ordering for write method.
1081 */
1082
1083int tty_send_xchar(struct tty_struct *tty, char ch)
1084{
1085        int     was_stopped = tty->stopped;
1086
1087        if (tty->ops->send_xchar) {
1088                down_read(&tty->termios_rwsem);
1089                tty->ops->send_xchar(tty, ch);
1090                up_read(&tty->termios_rwsem);
1091                return 0;
1092        }
1093
1094        if (tty_write_lock(tty, 0) < 0)
1095                return -ERESTARTSYS;
1096
1097        down_read(&tty->termios_rwsem);
1098        if (was_stopped)
1099                start_tty(tty);
1100        tty->ops->write(tty, &ch, 1);
1101        if (was_stopped)
1102                stop_tty(tty);
1103        up_read(&tty->termios_rwsem);
1104        tty_write_unlock(tty);
1105        return 0;
1106}
1107
1108static char ptychar[] = "pqrstuvwxyzabcde";
1109
1110/**
1111 *      pty_line_name   -       generate name for a pty
1112 *      @driver: the tty driver in use
1113 *      @index: the minor number
1114 *      @p: output buffer of at least 6 bytes
1115 *
1116 *      Generate a name from a driver reference and write it to the output
1117 *      buffer.
1118 *
1119 *      Locking: None
1120 */
1121static void pty_line_name(struct tty_driver *driver, int index, char *p)
1122{
1123        int i = index + driver->name_base;
1124        /* ->name is initialized to "ttyp", but "tty" is expected */
1125        sprintf(p, "%s%c%x",
1126                driver->subtype == PTY_TYPE_SLAVE ? "tty" : driver->name,
1127                ptychar[i >> 4 & 0xf], i & 0xf);
1128}
1129
1130/**
1131 *      tty_line_name   -       generate name for a tty
1132 *      @driver: the tty driver in use
1133 *      @index: the minor number
1134 *      @p: output buffer of at least 7 bytes
1135 *
1136 *      Generate a name from a driver reference and write it to the output
1137 *      buffer.
1138 *
1139 *      Locking: None
1140 */
1141static ssize_t tty_line_name(struct tty_driver *driver, int index, char *p)
1142{
1143        if (driver->flags & TTY_DRIVER_UNNUMBERED_NODE)
1144                return sprintf(p, "%s", driver->name);
1145        else
1146                return sprintf(p, "%s%d", driver->name,
1147                               index + driver->name_base);
1148}
1149
1150/**
1151 *      tty_driver_lookup_tty() - find an existing tty, if any
1152 *      @driver: the driver for the tty
1153 *      @idx:    the minor number
1154 *
1155 *      Return the tty, if found. If not found, return NULL or ERR_PTR() if the
1156 *      driver lookup() method returns an error.
1157 *
1158 *      Locking: tty_mutex must be held. If the tty is found, bump the tty kref.
1159 */
1160static struct tty_struct *tty_driver_lookup_tty(struct tty_driver *driver,
1161                struct file *file, int idx)
1162{
1163        struct tty_struct *tty;
1164
1165        if (driver->ops->lookup)
1166                if (!file)
1167                        tty = ERR_PTR(-EIO);
1168                else
1169                        tty = driver->ops->lookup(driver, file, idx);
1170        else
1171                tty = driver->ttys[idx];
1172
1173        if (!IS_ERR(tty))
1174                tty_kref_get(tty);
1175        return tty;
1176}
1177
1178/**
1179 *      tty_init_termios        -  helper for termios setup
1180 *      @tty: the tty to set up
1181 *
1182 *      Initialise the termios structures for this tty. Thus runs under
1183 *      the tty_mutex currently so we can be relaxed about ordering.
1184 */
1185
1186void tty_init_termios(struct tty_struct *tty)
1187{
1188        struct ktermios *tp;
1189        int idx = tty->index;
1190
1191        if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
1192                tty->termios = tty->driver->init_termios;
1193        else {
1194                /* Check for lazy saved data */
1195                tp = tty->driver->termios[idx];
1196                if (tp != NULL) {
1197                        tty->termios = *tp;
1198                        tty->termios.c_line  = tty->driver->init_termios.c_line;
1199                } else
1200                        tty->termios = tty->driver->init_termios;
1201        }
1202        /* Compatibility until drivers always set this */
1203        tty->termios.c_ispeed = tty_termios_input_baud_rate(&tty->termios);
1204        tty->termios.c_ospeed = tty_termios_baud_rate(&tty->termios);
1205}
1206EXPORT_SYMBOL_GPL(tty_init_termios);
1207
1208int tty_standard_install(struct tty_driver *driver, struct tty_struct *tty)
1209{
1210        tty_init_termios(tty);
1211        tty_driver_kref_get(driver);
1212        tty->count++;
1213        driver->ttys[tty->index] = tty;
1214        return 0;
1215}
1216EXPORT_SYMBOL_GPL(tty_standard_install);
1217
1218/**
1219 *      tty_driver_install_tty() - install a tty entry in the driver
1220 *      @driver: the driver for the tty
1221 *      @tty: the tty
1222 *
1223 *      Install a tty object into the driver tables. The tty->index field
1224 *      will be set by the time this is called. This method is responsible
1225 *      for ensuring any need additional structures are allocated and
1226 *      configured.
1227 *
1228 *      Locking: tty_mutex for now
1229 */
1230static int tty_driver_install_tty(struct tty_driver *driver,
1231                                                struct tty_struct *tty)
1232{
1233        return driver->ops->install ? driver->ops->install(driver, tty) :
1234                tty_standard_install(driver, tty);
1235}
1236
1237/**
1238 *      tty_driver_remove_tty() - remove a tty from the driver tables
1239 *      @driver: the driver for the tty
1240 *      @idx:    the minor number
1241 *
1242 *      Remvoe a tty object from the driver tables. The tty->index field
1243 *      will be set by the time this is called.
1244 *
1245 *      Locking: tty_mutex for now
1246 */
1247static void tty_driver_remove_tty(struct tty_driver *driver, struct tty_struct *tty)
1248{
1249        if (driver->ops->remove)
1250                driver->ops->remove(driver, tty);
1251        else
1252                driver->ttys[tty->index] = NULL;
1253}
1254
1255/*
1256 *      tty_reopen()    - fast re-open of an open tty
1257 *      @tty    - the tty to open
1258 *
1259 *      Return 0 on success, -errno on error.
1260 *      Re-opens on master ptys are not allowed and return -EIO.
1261 *
1262 *      Locking: Caller must hold tty_lock
1263 */
1264static int tty_reopen(struct tty_struct *tty)
1265{
1266        struct tty_driver *driver = tty->driver;
1267        struct tty_ldisc *ld;
1268        int retval = 0;
1269
1270        if (driver->type == TTY_DRIVER_TYPE_PTY &&
1271            driver->subtype == PTY_TYPE_MASTER)
1272                return -EIO;
1273
1274        if (!tty->count)
1275                return -EAGAIN;
1276
1277        if (test_bit(TTY_EXCLUSIVE, &tty->flags) && !capable(CAP_SYS_ADMIN))
1278                return -EBUSY;
1279
1280        ld = tty_ldisc_ref_wait(tty);
1281        if (ld) {
1282                tty_ldisc_deref(ld);
1283        } else {
1284                retval = tty_ldisc_lock(tty, 5 * HZ);
1285                if (retval)
1286                        return retval;
1287
1288                if (!tty->ldisc)
1289                        retval = tty_ldisc_reinit(tty, tty->termios.c_line);
1290                tty_ldisc_unlock(tty);
1291        }
1292
1293        if (retval == 0)
1294                tty->count++;
1295
1296        return retval;
1297}
1298
1299/**
1300 *      tty_init_dev            -       initialise a tty device
1301 *      @driver: tty driver we are opening a device on
1302 *      @idx: device index
1303 *      @ret_tty: returned tty structure
1304 *
1305 *      Prepare a tty device. This may not be a "new" clean device but
1306 *      could also be an active device. The pty drivers require special
1307 *      handling because of this.
1308 *
1309 *      Locking:
1310 *              The function is called under the tty_mutex, which
1311 *      protects us from the tty struct or driver itself going away.
1312 *
1313 *      On exit the tty device has the line discipline attached and
1314 *      a reference count of 1. If a pair was created for pty/tty use
1315 *      and the other was a pty master then it too has a reference count of 1.
1316 *
1317 * WSH 06/09/97: Rewritten to remove races and properly clean up after a
1318 * failed open.  The new code protects the open with a mutex, so it's
1319 * really quite straightforward.  The mutex locking can probably be
1320 * relaxed for the (most common) case of reopening a tty.
1321 */
1322
1323struct tty_struct *tty_init_dev(struct tty_driver *driver, int idx)
1324{
1325        struct tty_struct *tty;
1326        int retval;
1327
1328        /*
1329         * First time open is complex, especially for PTY devices.
1330         * This code guarantees that either everything succeeds and the
1331         * TTY is ready for operation, or else the table slots are vacated
1332         * and the allocated memory released.  (Except that the termios
1333         * may be retained.)
1334         */
1335
1336        if (!try_module_get(driver->owner))
1337                return ERR_PTR(-ENODEV);
1338
1339        tty = alloc_tty_struct(driver, idx);
1340        if (!tty) {
1341                retval = -ENOMEM;
1342                goto err_module_put;
1343        }
1344
1345        tty_lock(tty);
1346        retval = tty_driver_install_tty(driver, tty);
1347        if (retval < 0)
1348                goto err_free_tty;
1349
1350        if (!tty->port)
1351                tty->port = driver->ports[idx];
1352
1353        WARN_RATELIMIT(!tty->port,
1354                        "%s: %s driver does not set tty->port. This will crash the kernel later. Fix the driver!\n",
1355                        __func__, tty->driver->name);
1356
1357        retval = tty_ldisc_lock(tty, 5 * HZ);
1358        if (retval)
1359                goto err_release_lock;
1360        tty->port->itty = tty;
1361
1362        /*
1363         * Structures all installed ... call the ldisc open routines.
1364         * If we fail here just call release_tty to clean up.  No need
1365         * to decrement the use counts, as release_tty doesn't care.
1366         */
1367        retval = tty_ldisc_setup(tty, tty->link);
1368        if (retval)
1369                goto err_release_tty;
1370        tty_ldisc_unlock(tty);
1371        /* Return the tty locked so that it cannot vanish under the caller */
1372        return tty;
1373
1374err_free_tty:
1375        tty_unlock(tty);
1376        free_tty_struct(tty);
1377err_module_put:
1378        module_put(driver->owner);
1379        return ERR_PTR(retval);
1380
1381        /* call the tty release_tty routine to clean out this slot */
1382err_release_tty:
1383        tty_ldisc_unlock(tty);
1384        tty_info_ratelimited(tty, "ldisc open failed (%d), clearing slot %d\n",
1385                             retval, idx);
1386err_release_lock:
1387        tty_unlock(tty);
1388        release_tty(tty, idx);
1389        return ERR_PTR(retval);
1390}
1391
1392/**
1393 * tty_save_termios() - save tty termios data in driver table
1394 * @tty: tty whose termios data to save
1395 *
1396 * Locking: Caller guarantees serialisation with tty_init_termios().
1397 */
1398void tty_save_termios(struct tty_struct *tty)
1399{
1400        struct ktermios *tp;
1401        int idx = tty->index;
1402
1403        /* If the port is going to reset then it has no termios to save */
1404        if (tty->driver->flags & TTY_DRIVER_RESET_TERMIOS)
1405                return;
1406
1407        /* Stash the termios data */
1408        tp = tty->driver->termios[idx];
1409        if (tp == NULL) {
1410                tp = kmalloc(sizeof(struct ktermios), GFP_KERNEL);
1411                if (tp == NULL)
1412                        return;
1413                tty->driver->termios[idx] = tp;
1414        }
1415        *tp = tty->termios;
1416}
1417EXPORT_SYMBOL_GPL(tty_save_termios);
1418
1419/**
1420 *      tty_flush_works         -       flush all works of a tty/pty pair
1421 *      @tty: tty device to flush works for (or either end of a pty pair)
1422 *
1423 *      Sync flush all works belonging to @tty (and the 'other' tty).
1424 */
1425static void tty_flush_works(struct tty_struct *tty)
1426{
1427        flush_work(&tty->SAK_work);
1428        flush_work(&tty->hangup_work);
1429        if (tty->link) {
1430                flush_work(&tty->link->SAK_work);
1431                flush_work(&tty->link->hangup_work);
1432        }
1433}
1434
1435/**
1436 *      release_one_tty         -       release tty structure memory
1437 *      @kref: kref of tty we are obliterating
1438 *
1439 *      Releases memory associated with a tty structure, and clears out the
1440 *      driver table slots. This function is called when a device is no longer
1441 *      in use. It also gets called when setup of a device fails.
1442 *
1443 *      Locking:
1444 *              takes the file list lock internally when working on the list
1445 *      of ttys that the driver keeps.
1446 *
1447 *      This method gets called from a work queue so that the driver private
1448 *      cleanup ops can sleep (needed for USB at least)
1449 */
1450static void release_one_tty(struct work_struct *work)
1451{
1452        struct tty_struct *tty =
1453                container_of(work, struct tty_struct, hangup_work);
1454        struct tty_driver *driver = tty->driver;
1455        struct module *owner = driver->owner;
1456
1457        if (tty->ops->cleanup)
1458                tty->ops->cleanup(tty);
1459
1460        tty->magic = 0;
1461        tty_driver_kref_put(driver);
1462        module_put(owner);
1463
1464        spin_lock(&tty->files_lock);
1465        list_del_init(&tty->tty_files);
1466        spin_unlock(&tty->files_lock);
1467
1468        put_pid(tty->pgrp);
1469        put_pid(tty->session);
1470        free_tty_struct(tty);
1471}
1472
1473static void queue_release_one_tty(struct kref *kref)
1474{
1475        struct tty_struct *tty = container_of(kref, struct tty_struct, kref);
1476
1477        /* The hangup queue is now free so we can reuse it rather than
1478           waste a chunk of memory for each port */
1479        INIT_WORK(&tty->hangup_work, release_one_tty);
1480        schedule_work(&tty->hangup_work);
1481}
1482
1483/**
1484 *      tty_kref_put            -       release a tty kref
1485 *      @tty: tty device
1486 *
1487 *      Release a reference to a tty device and if need be let the kref
1488 *      layer destruct the object for us
1489 */
1490
1491void tty_kref_put(struct tty_struct *tty)
1492{
1493        if (tty)
1494                kref_put(&tty->kref, queue_release_one_tty);
1495}
1496EXPORT_SYMBOL(tty_kref_put);
1497
1498/**
1499 *      release_tty             -       release tty structure memory
1500 *
1501 *      Release both @tty and a possible linked partner (think pty pair),
1502 *      and decrement the refcount of the backing module.
1503 *
1504 *      Locking:
1505 *              tty_mutex
1506 *              takes the file list lock internally when working on the list
1507 *      of ttys that the driver keeps.
1508 *
1509 */
1510static void release_tty(struct tty_struct *tty, int idx)
1511{
1512        /* This should always be true but check for the moment */
1513        WARN_ON(tty->index != idx);
1514        WARN_ON(!mutex_is_locked(&tty_mutex));
1515        if (tty->ops->shutdown)
1516                tty->ops->shutdown(tty);
1517        tty_save_termios(tty);
1518        tty_driver_remove_tty(tty->driver, tty);
1519        tty->port->itty = NULL;
1520        if (tty->link)
1521                tty->link->port->itty = NULL;
1522        tty_buffer_cancel_work(tty->port);
1523        if (tty->link)
1524                tty_buffer_cancel_work(tty->link->port);
1525
1526        tty_kref_put(tty->link);
1527        tty_kref_put(tty);
1528}
1529
1530/**
1531 *      tty_release_checks - check a tty before real release
1532 *      @tty: tty to check
1533 *      @o_tty: link of @tty (if any)
1534 *      @idx: index of the tty
1535 *
1536 *      Performs some paranoid checking before true release of the @tty.
1537 *      This is a no-op unless TTY_PARANOIA_CHECK is defined.
1538 */
1539static int tty_release_checks(struct tty_struct *tty, int idx)
1540{
1541#ifdef TTY_PARANOIA_CHECK
1542        if (idx < 0 || idx >= tty->driver->num) {
1543                tty_debug(tty, "bad idx %d\n", idx);
1544                return -1;
1545        }
1546
1547        /* not much to check for devpts */
1548        if (tty->driver->flags & TTY_DRIVER_DEVPTS_MEM)
1549                return 0;
1550
1551        if (tty != tty->driver->ttys[idx]) {
1552                tty_debug(tty, "bad driver table[%d] = %p\n",
1553                          idx, tty->driver->ttys[idx]);
1554                return -1;
1555        }
1556        if (tty->driver->other) {
1557                struct tty_struct *o_tty = tty->link;
1558
1559                if (o_tty != tty->driver->other->ttys[idx]) {
1560                        tty_debug(tty, "bad other table[%d] = %p\n",
1561                                  idx, tty->driver->other->ttys[idx]);
1562                        return -1;
1563                }
1564                if (o_tty->link != tty) {
1565                        tty_debug(tty, "bad link = %p\n", o_tty->link);
1566                        return -1;
1567                }
1568        }
1569#endif
1570        return 0;
1571}
1572
1573/**
1574 *      tty_kclose      -       closes tty opened by tty_kopen
1575 *      @tty: tty device
1576 *
1577 *      Performs the final steps to release and free a tty device. It is the
1578 *      same as tty_release_struct except that it also resets TTY_PORT_KOPENED
1579 *      flag on tty->port.
1580 */
1581void tty_kclose(struct tty_struct *tty)
1582{
1583        /*
1584         * Ask the line discipline code to release its structures
1585         */
1586        tty_ldisc_release(tty);
1587
1588        /* Wait for pending work before tty destruction commmences */
1589        tty_flush_works(tty);
1590
1591        tty_debug_hangup(tty, "freeing structure\n");
1592        /*
1593         * The release_tty function takes care of the details of clearing
1594         * the slots and preserving the termios structure. The tty_unlock_pair
1595         * should be safe as we keep a kref while the tty is locked (so the
1596         * unlock never unlocks a freed tty).
1597         */
1598        mutex_lock(&tty_mutex);
1599        tty_port_set_kopened(tty->port, 0);
1600        release_tty(tty, tty->index);
1601        mutex_unlock(&tty_mutex);
1602}
1603EXPORT_SYMBOL_GPL(tty_kclose);
1604
1605/**
1606 *      tty_release_struct      -       release a tty struct
1607 *      @tty: tty device
1608 *      @idx: index of the tty
1609 *
1610 *      Performs the final steps to release and free a tty device. It is
1611 *      roughly the reverse of tty_init_dev.
1612 */
1613void tty_release_struct(struct tty_struct *tty, int idx)
1614{
1615        /*
1616         * Ask the line discipline code to release its structures
1617         */
1618        tty_ldisc_release(tty);
1619
1620        /* Wait for pending work before tty destruction commmences */
1621        tty_flush_works(tty);
1622
1623        tty_debug_hangup(tty, "freeing structure\n");
1624        /*
1625         * The release_tty function takes care of the details of clearing
1626         * the slots and preserving the termios structure. The tty_unlock_pair
1627         * should be safe as we keep a kref while the tty is locked (so the
1628         * unlock never unlocks a freed tty).
1629         */
1630        mutex_lock(&tty_mutex);
1631        release_tty(tty, idx);
1632        mutex_unlock(&tty_mutex);
1633}
1634EXPORT_SYMBOL_GPL(tty_release_struct);
1635
1636/**
1637 *      tty_release             -       vfs callback for close
1638 *      @inode: inode of tty
1639 *      @filp: file pointer for handle to tty
1640 *
1641 *      Called the last time each file handle is closed that references
1642 *      this tty. There may however be several such references.
1643 *
1644 *      Locking:
1645 *              Takes bkl. See tty_release_dev
1646 *
1647 * Even releasing the tty structures is a tricky business.. We have
1648 * to be very careful that the structures are all released at the
1649 * same time, as interrupts might otherwise get the wrong pointers.
1650 *
1651 * WSH 09/09/97: rewritten to avoid some nasty race conditions that could
1652 * lead to double frees or releasing memory still in use.
1653 */
1654
1655int tty_release(struct inode *inode, struct file *filp)
1656{
1657        struct tty_struct *tty = file_tty(filp);
1658        struct tty_struct *o_tty = NULL;
1659        int     do_sleep, final;
1660        int     idx;
1661        long    timeout = 0;
1662        int     once = 1;
1663
1664        if (tty_paranoia_check(tty, inode, __func__))
1665                return 0;
1666
1667        tty_lock(tty);
1668        check_tty_count(tty, __func__);
1669
1670        __tty_fasync(-1, filp, 0);
1671
1672        idx = tty->index;
1673        if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
1674            tty->driver->subtype == PTY_TYPE_MASTER)
1675                o_tty = tty->link;
1676
1677        if (tty_release_checks(tty, idx)) {
1678                tty_unlock(tty);
1679                return 0;
1680        }
1681
1682        tty_debug_hangup(tty, "releasing (count=%d)\n", tty->count);
1683
1684        if (tty->ops->close)
1685                tty->ops->close(tty, filp);
1686
1687        /* If tty is pty master, lock the slave pty (stable lock order) */
1688        tty_lock_slave(o_tty);
1689
1690        /*
1691         * Sanity check: if tty->count is going to zero, there shouldn't be
1692         * any waiters on tty->read_wait or tty->write_wait.  We test the
1693         * wait queues and kick everyone out _before_ actually starting to
1694         * close.  This ensures that we won't block while releasing the tty
1695         * structure.
1696         *
1697         * The test for the o_tty closing is necessary, since the master and
1698         * slave sides may close in any order.  If the slave side closes out
1699         * first, its count will be one, since the master side holds an open.
1700         * Thus this test wouldn't be triggered at the time the slave closed,
1701         * so we do it now.
1702         */
1703        while (1) {
1704                do_sleep = 0;
1705
1706                if (tty->count <= 1) {
1707                        if (waitqueue_active(&tty->read_wait)) {
1708                                wake_up_poll(&tty->read_wait, EPOLLIN);
1709                                do_sleep++;
1710                        }
1711                        if (waitqueue_active(&tty->write_wait)) {
1712                                wake_up_poll(&tty->write_wait, EPOLLOUT);
1713                                do_sleep++;
1714                        }
1715                }
1716                if (o_tty && o_tty->count <= 1) {
1717                        if (waitqueue_active(&o_tty->read_wait)) {
1718                                wake_up_poll(&o_tty->read_wait, EPOLLIN);
1719                                do_sleep++;
1720                        }
1721                        if (waitqueue_active(&o_tty->write_wait)) {
1722                                wake_up_poll(&o_tty->write_wait, EPOLLOUT);
1723                                do_sleep++;
1724                        }
1725                }
1726                if (!do_sleep)
1727                        break;
1728
1729                if (once) {
1730                        once = 0;
1731                        tty_warn(tty, "read/write wait queue active!\n");
1732                }
1733                schedule_timeout_killable(timeout);
1734                if (timeout < 120 * HZ)
1735                        timeout = 2 * timeout + 1;
1736                else
1737                        timeout = MAX_SCHEDULE_TIMEOUT;
1738        }
1739
1740        if (o_tty) {
1741                if (--o_tty->count < 0) {
1742                        tty_warn(tty, "bad slave count (%d)\n", o_tty->count);
1743                        o_tty->count = 0;
1744                }
1745        }
1746        if (--tty->count < 0) {
1747                tty_warn(tty, "bad tty->count (%d)\n", tty->count);
1748                tty->count = 0;
1749        }
1750
1751        /*
1752         * We've decremented tty->count, so we need to remove this file
1753         * descriptor off the tty->tty_files list; this serves two
1754         * purposes:
1755         *  - check_tty_count sees the correct number of file descriptors
1756         *    associated with this tty.
1757         *  - do_tty_hangup no longer sees this file descriptor as
1758         *    something that needs to be handled for hangups.
1759         */
1760        tty_del_file(filp);
1761
1762        /*
1763         * Perform some housekeeping before deciding whether to return.
1764         *
1765         * If _either_ side is closing, make sure there aren't any
1766         * processes that still think tty or o_tty is their controlling
1767         * tty.
1768         */
1769        if (!tty->count) {
1770                read_lock(&tasklist_lock);
1771                session_clear_tty(tty->session);
1772                if (o_tty)
1773                        session_clear_tty(o_tty->session);
1774                read_unlock(&tasklist_lock);
1775        }
1776
1777        /* check whether both sides are closing ... */
1778        final = !tty->count && !(o_tty && o_tty->count);
1779
1780        tty_unlock_slave(o_tty);
1781        tty_unlock(tty);
1782
1783        /* At this point, the tty->count == 0 should ensure a dead tty
1784           cannot be re-opened by a racing opener */
1785
1786        if (!final)
1787                return 0;
1788
1789        tty_debug_hangup(tty, "final close\n");
1790
1791        tty_release_struct(tty, idx);
1792        return 0;
1793}
1794
1795/**
1796 *      tty_open_current_tty - get locked tty of current task
1797 *      @device: device number
1798 *      @filp: file pointer to tty
1799 *      @return: locked tty of the current task iff @device is /dev/tty
1800 *
1801 *      Performs a re-open of the current task's controlling tty.
1802 *
1803 *      We cannot return driver and index like for the other nodes because
1804 *      devpts will not work then. It expects inodes to be from devpts FS.
1805 */
1806static struct tty_struct *tty_open_current_tty(dev_t device, struct file *filp)
1807{
1808        struct tty_struct *tty;
1809        int retval;
1810
1811        if (device != MKDEV(TTYAUX_MAJOR, 0))
1812                return NULL;
1813
1814        tty = get_current_tty();
1815        if (!tty)
1816                return ERR_PTR(-ENXIO);
1817
1818        filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
1819        /* noctty = 1; */
1820        tty_lock(tty);
1821        tty_kref_put(tty);      /* safe to drop the kref now */
1822
1823        retval = tty_reopen(tty);
1824        if (retval < 0) {
1825                tty_unlock(tty);
1826                tty = ERR_PTR(retval);
1827        }
1828        return tty;
1829}
1830
1831/**
1832 *      tty_lookup_driver - lookup a tty driver for a given device file
1833 *      @device: device number
1834 *      @filp: file pointer to tty
1835 *      @index: index for the device in the @return driver
1836 *      @return: driver for this inode (with increased refcount)
1837 *
1838 *      If @return is not erroneous, the caller is responsible to decrement the
1839 *      refcount by tty_driver_kref_put.
1840 *
1841 *      Locking: tty_mutex protects get_tty_driver
1842 */
1843static struct tty_driver *tty_lookup_driver(dev_t device, struct file *filp,
1844                int *index)
1845{
1846        struct tty_driver *driver;
1847
1848        switch (device) {
1849#ifdef CONFIG_VT
1850        case MKDEV(TTY_MAJOR, 0): {
1851                extern struct tty_driver *console_driver;
1852                driver = tty_driver_kref_get(console_driver);
1853                *index = fg_console;
1854                break;
1855        }
1856#endif
1857        case MKDEV(TTYAUX_MAJOR, 1): {
1858                struct tty_driver *console_driver = console_device(index);
1859                if (console_driver) {
1860                        driver = tty_driver_kref_get(console_driver);
1861                        if (driver && filp) {
1862                                /* Don't let /dev/console block */
1863                                filp->f_flags |= O_NONBLOCK;
1864                                break;
1865                        }
1866                }
1867                return ERR_PTR(-ENODEV);
1868        }
1869        default:
1870                driver = get_tty_driver(device, index);
1871                if (!driver)
1872                        return ERR_PTR(-ENODEV);
1873                break;
1874        }
1875        return driver;
1876}
1877
1878/**
1879 *      tty_kopen       -       open a tty device for kernel
1880 *      @device: dev_t of device to open
1881 *
1882 *      Opens tty exclusively for kernel. Performs the driver lookup,
1883 *      makes sure it's not already opened and performs the first-time
1884 *      tty initialization.
1885 *
1886 *      Returns the locked initialized &tty_struct
1887 *
1888 *      Claims the global tty_mutex to serialize:
1889 *        - concurrent first-time tty initialization
1890 *        - concurrent tty driver removal w/ lookup
1891 *        - concurrent tty removal from driver table
1892 */
1893struct tty_struct *tty_kopen(dev_t device)
1894{
1895        struct tty_struct *tty;
1896        struct tty_driver *driver = NULL;
1897        int index = -1;
1898
1899        mutex_lock(&tty_mutex);
1900        driver = tty_lookup_driver(device, NULL, &index);
1901        if (IS_ERR(driver)) {
1902                mutex_unlock(&tty_mutex);
1903                return ERR_CAST(driver);
1904        }
1905
1906        /* check whether we're reopening an existing tty */
1907        tty = tty_driver_lookup_tty(driver, NULL, index);
1908        if (IS_ERR(tty))
1909                goto out;
1910
1911        if (tty) {
1912                /* drop kref from tty_driver_lookup_tty() */
1913                tty_kref_put(tty);
1914                tty = ERR_PTR(-EBUSY);
1915        } else { /* tty_init_dev returns tty with the tty_lock held */
1916                tty = tty_init_dev(driver, index);
1917                if (IS_ERR(tty))
1918                        goto out;
1919                tty_port_set_kopened(tty->port, 1);
1920        }
1921out:
1922        mutex_unlock(&tty_mutex);
1923        tty_driver_kref_put(driver);
1924        return tty;
1925}
1926EXPORT_SYMBOL_GPL(tty_kopen);
1927
1928/**
1929 *      tty_open_by_driver      -       open a tty device
1930 *      @device: dev_t of device to open
1931 *      @inode: inode of device file
1932 *      @filp: file pointer to tty
1933 *
1934 *      Performs the driver lookup, checks for a reopen, or otherwise
1935 *      performs the first-time tty initialization.
1936 *
1937 *      Returns the locked initialized or re-opened &tty_struct
1938 *
1939 *      Claims the global tty_mutex to serialize:
1940 *        - concurrent first-time tty initialization
1941 *        - concurrent tty driver removal w/ lookup
1942 *        - concurrent tty removal from driver table
1943 */
1944static struct tty_struct *tty_open_by_driver(dev_t device, struct inode *inode,
1945                                             struct file *filp)
1946{
1947        struct tty_struct *tty;
1948        struct tty_driver *driver = NULL;
1949        int index = -1;
1950        int retval;
1951
1952        mutex_lock(&tty_mutex);
1953        driver = tty_lookup_driver(device, filp, &index);
1954        if (IS_ERR(driver)) {
1955                mutex_unlock(&tty_mutex);
1956                return ERR_CAST(driver);
1957        }
1958
1959        /* check whether we're reopening an existing tty */
1960        tty = tty_driver_lookup_tty(driver, filp, index);
1961        if (IS_ERR(tty)) {
1962                mutex_unlock(&tty_mutex);
1963                goto out;
1964        }
1965
1966        if (tty) {
1967                if (tty_port_kopened(tty->port)) {
1968                        tty_kref_put(tty);
1969                        mutex_unlock(&tty_mutex);
1970                        tty = ERR_PTR(-EBUSY);
1971                        goto out;
1972                }
1973                mutex_unlock(&tty_mutex);
1974                retval = tty_lock_interruptible(tty);
1975                tty_kref_put(tty);  /* drop kref from tty_driver_lookup_tty() */
1976                if (retval) {
1977                        if (retval == -EINTR)
1978                                retval = -ERESTARTSYS;
1979                        tty = ERR_PTR(retval);
1980                        goto out;
1981                }
1982                retval = tty_reopen(tty);
1983                if (retval < 0) {
1984                        tty_unlock(tty);
1985                        tty = ERR_PTR(retval);
1986                }
1987        } else { /* Returns with the tty_lock held for now */
1988                tty = tty_init_dev(driver, index);
1989                mutex_unlock(&tty_mutex);
1990        }
1991out:
1992        tty_driver_kref_put(driver);
1993        return tty;
1994}
1995
1996/**
1997 *      tty_open                -       open a tty device
1998 *      @inode: inode of device file
1999 *      @filp: file pointer to tty
2000 *
2001 *      tty_open and tty_release keep up the tty count that contains the
2002 *      number of opens done on a tty. We cannot use the inode-count, as
2003 *      different inodes might point to the same tty.
2004 *
2005 *      Open-counting is needed for pty masters, as well as for keeping
2006 *      track of serial lines: DTR is dropped when the last close happens.
2007 *      (This is not done solely through tty->count, now.  - Ted 1/27/92)
2008 *
2009 *      The termios state of a pty is reset on first open so that
2010 *      settings don't persist across reuse.
2011 *
2012 *      Locking: tty_mutex protects tty, tty_lookup_driver and tty_init_dev.
2013 *               tty->count should protect the rest.
2014 *               ->siglock protects ->signal/->sighand
2015 *
2016 *      Note: the tty_unlock/lock cases without a ref are only safe due to
2017 *      tty_mutex
2018 */
2019
2020static int tty_open(struct inode *inode, struct file *filp)
2021{
2022        struct tty_struct *tty;
2023        int noctty, retval;
2024        dev_t device = inode->i_rdev;
2025        unsigned saved_flags = filp->f_flags;
2026
2027        nonseekable_open(inode, filp);
2028
2029retry_open:
2030        retval = tty_alloc_file(filp);
2031        if (retval)
2032                return -ENOMEM;
2033
2034        tty = tty_open_current_tty(device, filp);
2035        if (!tty)
2036                tty = tty_open_by_driver(device, inode, filp);
2037
2038        if (IS_ERR(tty)) {
2039                tty_free_file(filp);
2040                retval = PTR_ERR(tty);
2041                if (retval != -EAGAIN || signal_pending(current))
2042                        return retval;
2043                schedule();
2044                goto retry_open;
2045        }
2046
2047        tty_add_file(tty, filp);
2048
2049        check_tty_count(tty, __func__);
2050        tty_debug_hangup(tty, "opening (count=%d)\n", tty->count);
2051
2052        if (tty->ops->open)
2053                retval = tty->ops->open(tty, filp);
2054        else
2055                retval = -ENODEV;
2056        filp->f_flags = saved_flags;
2057
2058        if (retval) {
2059                tty_debug_hangup(tty, "open error %d, releasing\n", retval);
2060
2061                tty_unlock(tty); /* need to call tty_release without BTM */
2062                tty_release(inode, filp);
2063                if (retval != -ERESTARTSYS)
2064                        return retval;
2065
2066                if (signal_pending(current))
2067                        return retval;
2068
2069                schedule();
2070                /*
2071                 * Need to reset f_op in case a hangup happened.
2072                 */
2073                if (tty_hung_up_p(filp))
2074                        filp->f_op = &tty_fops;
2075                goto retry_open;
2076        }
2077        clear_bit(TTY_HUPPED, &tty->flags);
2078
2079        noctty = (filp->f_flags & O_NOCTTY) ||
2080                 (IS_ENABLED(CONFIG_VT) && device == MKDEV(TTY_MAJOR, 0)) ||
2081                 device == MKDEV(TTYAUX_MAJOR, 1) ||
2082                 (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
2083                  tty->driver->subtype == PTY_TYPE_MASTER);
2084        if (!noctty)
2085                tty_open_proc_set_tty(filp, tty);
2086        tty_unlock(tty);
2087        return 0;
2088}
2089
2090
2091
2092/**
2093 *      tty_poll        -       check tty status
2094 *      @filp: file being polled
2095 *      @wait: poll wait structures to update
2096 *
2097 *      Call the line discipline polling method to obtain the poll
2098 *      status of the device.
2099 *
2100 *      Locking: locks called line discipline but ldisc poll method
2101 *      may be re-entered freely by other callers.
2102 */
2103
2104static __poll_t tty_poll(struct file *filp, poll_table *wait)
2105{
2106        struct tty_struct *tty = file_tty(filp);
2107        struct tty_ldisc *ld;
2108        __poll_t ret = 0;
2109
2110        if (tty_paranoia_check(tty, file_inode(filp), "tty_poll"))
2111                return 0;
2112
2113        ld = tty_ldisc_ref_wait(tty);
2114        if (!ld)
2115                return hung_up_tty_poll(filp, wait);
2116        if (ld->ops->poll)
2117                ret = ld->ops->poll(tty, filp, wait);
2118        tty_ldisc_deref(ld);
2119        return ret;
2120}
2121
2122static int __tty_fasync(int fd, struct file *filp, int on)
2123{
2124        struct tty_struct *tty = file_tty(filp);
2125        unsigned long flags;
2126        int retval = 0;
2127
2128        if (tty_paranoia_check(tty, file_inode(filp), "tty_fasync"))
2129                goto out;
2130
2131        retval = fasync_helper(fd, filp, on, &tty->fasync);
2132        if (retval <= 0)
2133                goto out;
2134
2135        if (on) {
2136                enum pid_type type;
2137                struct pid *pid;
2138
2139                spin_lock_irqsave(&tty->ctrl_lock, flags);
2140                if (tty->pgrp) {
2141                        pid = tty->pgrp;
2142                        type = PIDTYPE_PGID;
2143                } else {
2144                        pid = task_pid(current);
2145                        type = PIDTYPE_TGID;
2146                }
2147                get_pid(pid);
2148                spin_unlock_irqrestore(&tty->ctrl_lock, flags);
2149                __f_setown(filp, pid, type, 0);
2150                put_pid(pid);
2151                retval = 0;
2152        }
2153out:
2154        return retval;
2155}
2156
2157static int tty_fasync(int fd, struct file *filp, int on)
2158{
2159        struct tty_struct *tty = file_tty(filp);
2160        int retval = -ENOTTY;
2161
2162        tty_lock(tty);
2163        if (!tty_hung_up_p(filp))
2164                retval = __tty_fasync(fd, filp, on);
2165        tty_unlock(tty);
2166
2167        return retval;
2168}
2169
2170/**
2171 *      tiocsti                 -       fake input character
2172 *      @tty: tty to fake input into
2173 *      @p: pointer to character
2174 *
2175 *      Fake input to a tty device. Does the necessary locking and
2176 *      input management.
2177 *
2178 *      FIXME: does not honour flow control ??
2179 *
2180 *      Locking:
2181 *              Called functions take tty_ldiscs_lock
2182 *              current->signal->tty check is safe without locks
2183 *
2184 *      FIXME: may race normal receive processing
2185 */
2186
2187static int tiocsti(struct tty_struct *tty, char __user *p)
2188{
2189        char ch, mbz = 0;
2190        struct tty_ldisc *ld;
2191
2192        if ((current->signal->tty != tty) && !capable(CAP_SYS_ADMIN))
2193                return -EPERM;
2194        if (get_user(ch, p))
2195                return -EFAULT;
2196        tty_audit_tiocsti(tty, ch);
2197        ld = tty_ldisc_ref_wait(tty);
2198        if (!ld)
2199                return -EIO;
2200        ld->ops->receive_buf(tty, &ch, &mbz, 1);
2201        tty_ldisc_deref(ld);
2202        return 0;
2203}
2204
2205/**
2206 *      tiocgwinsz              -       implement window query ioctl
2207 *      @tty; tty
2208 *      @arg: user buffer for result
2209 *
2210 *      Copies the kernel idea of the window size into the user buffer.
2211 *
2212 *      Locking: tty->winsize_mutex is taken to ensure the winsize data
2213 *              is consistent.
2214 */
2215
2216static int tiocgwinsz(struct tty_struct *tty, struct winsize __user *arg)
2217{
2218        int err;
2219
2220        mutex_lock(&tty->winsize_mutex);
2221        err = copy_to_user(arg, &tty->winsize, sizeof(*arg));
2222        mutex_unlock(&tty->winsize_mutex);
2223
2224        return err ? -EFAULT: 0;
2225}
2226
2227/**
2228 *      tty_do_resize           -       resize event
2229 *      @tty: tty being resized
2230 *      @rows: rows (character)
2231 *      @cols: cols (character)
2232 *
2233 *      Update the termios variables and send the necessary signals to
2234 *      peform a terminal resize correctly
2235 */
2236
2237int tty_do_resize(struct tty_struct *tty, struct winsize *ws)
2238{
2239        struct pid *pgrp;
2240
2241        /* Lock the tty */
2242        mutex_lock(&tty->winsize_mutex);
2243        if (!memcmp(ws, &tty->winsize, sizeof(*ws)))
2244                goto done;
2245
2246        /* Signal the foreground process group */
2247        pgrp = tty_get_pgrp(tty);
2248        if (pgrp)
2249                kill_pgrp(pgrp, SIGWINCH, 1);
2250        put_pid(pgrp);
2251
2252        tty->winsize = *ws;
2253done:
2254        mutex_unlock(&tty->winsize_mutex);
2255        return 0;
2256}
2257EXPORT_SYMBOL(tty_do_resize);
2258
2259/**
2260 *      tiocswinsz              -       implement window size set ioctl
2261 *      @tty; tty side of tty
2262 *      @arg: user buffer for result
2263 *
2264 *      Copies the user idea of the window size to the kernel. Traditionally
2265 *      this is just advisory information but for the Linux console it
2266 *      actually has driver level meaning and triggers a VC resize.
2267 *
2268 *      Locking:
2269 *              Driver dependent. The default do_resize method takes the
2270 *      tty termios mutex and ctrl_lock. The console takes its own lock
2271 *      then calls into the default method.
2272 */
2273
2274static int tiocswinsz(struct tty_struct *tty, struct winsize __user *arg)
2275{
2276        struct winsize tmp_ws;
2277        if (copy_from_user(&tmp_ws, arg, sizeof(*arg)))
2278                return -EFAULT;
2279
2280        if (tty->ops->resize)
2281                return tty->ops->resize(tty, &tmp_ws);
2282        else
2283                return tty_do_resize(tty, &tmp_ws);
2284}
2285
2286/**
2287 *      tioccons        -       allow admin to move logical console
2288 *      @file: the file to become console
2289 *
2290 *      Allow the administrator to move the redirected console device
2291 *
2292 *      Locking: uses redirect_lock to guard the redirect information
2293 */
2294
2295static int tioccons(struct file *file)
2296{
2297        if (!capable(CAP_SYS_ADMIN))
2298                return -EPERM;
2299        if (file->f_op->write == redirected_tty_write) {
2300                struct file *f;
2301                spin_lock(&redirect_lock);
2302                f = redirect;
2303                redirect = NULL;
2304                spin_unlock(&redirect_lock);
2305                if (f)
2306                        fput(f);
2307                return 0;
2308        }
2309        spin_lock(&redirect_lock);
2310        if (redirect) {
2311                spin_unlock(&redirect_lock);
2312                return -EBUSY;
2313        }
2314        redirect = get_file(file);
2315        spin_unlock(&redirect_lock);
2316        return 0;
2317}
2318
2319/**
2320 *      fionbio         -       non blocking ioctl
2321 *      @file: file to set blocking value
2322 *      @p: user parameter
2323 *
2324 *      Historical tty interfaces had a blocking control ioctl before
2325 *      the generic functionality existed. This piece of history is preserved
2326 *      in the expected tty API of posix OS's.
2327 *
2328 *      Locking: none, the open file handle ensures it won't go away.
2329 */
2330
2331static int fionbio(struct file *file, int __user *p)
2332{
2333        int nonblock;
2334
2335        if (get_user(nonblock, p))
2336                return -EFAULT;
2337
2338        spin_lock(&file->f_lock);
2339        if (nonblock)
2340                file->f_flags |= O_NONBLOCK;
2341        else
2342                file->f_flags &= ~O_NONBLOCK;
2343        spin_unlock(&file->f_lock);
2344        return 0;
2345}
2346
2347/**
2348 *      tiocsetd        -       set line discipline
2349 *      @tty: tty device
2350 *      @p: pointer to user data
2351 *
2352 *      Set the line discipline according to user request.
2353 *
2354 *      Locking: see tty_set_ldisc, this function is just a helper
2355 */
2356
2357static int tiocsetd(struct tty_struct *tty, int __user *p)
2358{
2359        int disc;
2360        int ret;
2361
2362        if (get_user(disc, p))
2363                return -EFAULT;
2364
2365        ret = tty_set_ldisc(tty, disc);
2366
2367        return ret;
2368}
2369
2370/**
2371 *      tiocgetd        -       get line discipline
2372 *      @tty: tty device
2373 *      @p: pointer to user data
2374 *
2375 *      Retrieves the line discipline id directly from the ldisc.
2376 *
2377 *      Locking: waits for ldisc reference (in case the line discipline
2378 *              is changing or the tty is being hungup)
2379 */
2380
2381static int tiocgetd(struct tty_struct *tty, int __user *p)
2382{
2383        struct tty_ldisc *ld;
2384        int ret;
2385
2386        ld = tty_ldisc_ref_wait(tty);
2387        if (!ld)
2388                return -EIO;
2389        ret = put_user(ld->ops->num, p);
2390        tty_ldisc_deref(ld);
2391        return ret;
2392}
2393
2394/**
2395 *      send_break      -       performed time break
2396 *      @tty: device to break on
2397 *      @duration: timeout in mS
2398 *
2399 *      Perform a timed break on hardware that lacks its own driver level
2400 *      timed break functionality.
2401 *
2402 *      Locking:
2403 *              atomic_write_lock serializes
2404 *
2405 */
2406
2407static int send_break(struct tty_struct *tty, unsigned int duration)
2408{
2409        int retval;
2410
2411        if (tty->ops->break_ctl == NULL)
2412                return 0;
2413
2414        if (tty->driver->flags & TTY_DRIVER_HARDWARE_BREAK)
2415                retval = tty->ops->break_ctl(tty, duration);
2416        else {
2417                /* Do the work ourselves */
2418                if (tty_write_lock(tty, 0) < 0)
2419                        return -EINTR;
2420                retval = tty->ops->break_ctl(tty, -1);
2421                if (retval)
2422                        goto out;
2423                if (!signal_pending(current))
2424                        msleep_interruptible(duration);
2425                retval = tty->ops->break_ctl(tty, 0);
2426out:
2427                tty_write_unlock(tty);
2428                if (signal_pending(current))
2429                        retval = -EINTR;
2430        }
2431        return retval;
2432}
2433
2434/**
2435 *      tty_tiocmget            -       get modem status
2436 *      @tty: tty device
2437 *      @file: user file pointer
2438 *      @p: pointer to result
2439 *
2440 *      Obtain the modem status bits from the tty driver if the feature
2441 *      is supported. Return -EINVAL if it is not available.
2442 *
2443 *      Locking: none (up to the driver)
2444 */
2445
2446static int tty_tiocmget(struct tty_struct *tty, int __user *p)
2447{
2448        int retval = -EINVAL;
2449
2450        if (tty->ops->tiocmget) {
2451                retval = tty->ops->tiocmget(tty);
2452
2453                if (retval >= 0)
2454                        retval = put_user(retval, p);
2455        }
2456        return retval;
2457}
2458
2459/**
2460 *      tty_tiocmset            -       set modem status
2461 *      @tty: tty device
2462 *      @cmd: command - clear bits, set bits or set all
2463 *      @p: pointer to desired bits
2464 *
2465 *      Set the modem status bits from the tty driver if the feature
2466 *      is supported. Return -EINVAL if it is not available.
2467 *
2468 *      Locking: none (up to the driver)
2469 */
2470
2471static int tty_tiocmset(struct tty_struct *tty, unsigned int cmd,
2472             unsigned __user *p)
2473{
2474        int retval;
2475        unsigned int set, clear, val;
2476
2477        if (tty->ops->tiocmset == NULL)
2478                return -EINVAL;
2479
2480        retval = get_user(val, p);
2481        if (retval)
2482                return retval;
2483        set = clear = 0;
2484        switch (cmd) {
2485        case TIOCMBIS:
2486                set = val;
2487                break;
2488        case TIOCMBIC:
2489                clear = val;
2490                break;
2491        case TIOCMSET:
2492                set = val;
2493                clear = ~val;
2494                break;
2495        }
2496        set &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
2497        clear &= TIOCM_DTR|TIOCM_RTS|TIOCM_OUT1|TIOCM_OUT2|TIOCM_LOOP;
2498        return tty->ops->tiocmset(tty, set, clear);
2499}
2500
2501static int tty_tiocgicount(struct tty_struct *tty, void __user *arg)
2502{
2503        int retval = -EINVAL;
2504        struct serial_icounter_struct icount;
2505        memset(&icount, 0, sizeof(icount));
2506        if (tty->ops->get_icount)
2507                retval = tty->ops->get_icount(tty, &icount);
2508        if (retval != 0)
2509                return retval;
2510        if (copy_to_user(arg, &icount, sizeof(icount)))
2511                return -EFAULT;
2512        return 0;
2513}
2514
2515static int tty_tiocsserial(struct tty_struct *tty, struct serial_struct __user *ss)
2516{
2517        static DEFINE_RATELIMIT_STATE(depr_flags,
2518                        DEFAULT_RATELIMIT_INTERVAL,
2519                        DEFAULT_RATELIMIT_BURST);
2520        char comm[TASK_COMM_LEN];
2521        struct serial_struct v;
2522        int flags;
2523
2524        if (copy_from_user(&v, ss, sizeof(struct serial_struct)))
2525                return -EFAULT;
2526
2527        flags = v.flags & ASYNC_DEPRECATED;
2528
2529        if (flags && __ratelimit(&depr_flags))
2530                pr_warn("%s: '%s' is using deprecated serial flags (with no effect): %.8x\n",
2531                        __func__, get_task_comm(comm, current), flags);
2532        if (!tty->ops->set_serial)
2533                return -ENOTTY;
2534        return tty->ops->set_serial(tty, &v);
2535}
2536
2537static int tty_tiocgserial(struct tty_struct *tty, struct serial_struct __user *ss)
2538{
2539        struct serial_struct v;
2540        int err;
2541
2542        memset(&v, 0, sizeof(struct serial_struct));
2543        if (!tty->ops->get_serial)
2544                return -ENOTTY;
2545        err = tty->ops->get_serial(tty, &v);
2546        if (!err && copy_to_user(ss, &v, sizeof(struct serial_struct)))
2547                err = -EFAULT;
2548        return err;
2549}
2550
2551/*
2552 * if pty, return the slave side (real_tty)
2553 * otherwise, return self
2554 */
2555static struct tty_struct *tty_pair_get_tty(struct tty_struct *tty)
2556{
2557        if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
2558            tty->driver->subtype == PTY_TYPE_MASTER)
2559                tty = tty->link;
2560        return tty;
2561}
2562
2563/*
2564 * Split this up, as gcc can choke on it otherwise..
2565 */
2566long tty_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2567{
2568        struct tty_struct *tty = file_tty(file);
2569        struct tty_struct *real_tty;
2570        void __user *p = (void __user *)arg;
2571        int retval;
2572        struct tty_ldisc *ld;
2573
2574        if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
2575                return -EINVAL;
2576
2577        real_tty = tty_pair_get_tty(tty);
2578
2579        /*
2580         * Factor out some common prep work
2581         */
2582        switch (cmd) {
2583        case TIOCSETD:
2584        case TIOCSBRK:
2585        case TIOCCBRK:
2586        case TCSBRK:
2587        case TCSBRKP:
2588                retval = tty_check_change(tty);
2589                if (retval)
2590                        return retval;
2591                if (cmd != TIOCCBRK) {
2592                        tty_wait_until_sent(tty, 0);
2593                        if (signal_pending(current))
2594                                return -EINTR;
2595                }
2596                break;
2597        }
2598
2599        /*
2600         *      Now do the stuff.
2601         */
2602        switch (cmd) {
2603        case TIOCSTI:
2604                return tiocsti(tty, p);
2605        case TIOCGWINSZ:
2606                return tiocgwinsz(real_tty, p);
2607        case TIOCSWINSZ:
2608                return tiocswinsz(real_tty, p);
2609        case TIOCCONS:
2610                return real_tty != tty ? -EINVAL : tioccons(file);
2611        case FIONBIO:
2612                return fionbio(file, p);
2613        case TIOCEXCL:
2614                set_bit(TTY_EXCLUSIVE, &tty->flags);
2615                return 0;
2616        case TIOCNXCL:
2617                clear_bit(TTY_EXCLUSIVE, &tty->flags);
2618                return 0;
2619        case TIOCGEXCL:
2620        {
2621                int excl = test_bit(TTY_EXCLUSIVE, &tty->flags);
2622                return put_user(excl, (int __user *)p);
2623        }
2624        case TIOCGETD:
2625                return tiocgetd(tty, p);
2626        case TIOCSETD:
2627                return tiocsetd(tty, p);
2628        case TIOCVHANGUP:
2629                if (!capable(CAP_SYS_ADMIN))
2630                        return -EPERM;
2631                tty_vhangup(tty);
2632                return 0;
2633        case TIOCGDEV:
2634        {
2635                unsigned int ret = new_encode_dev(tty_devnum(real_tty));
2636                return put_user(ret, (unsigned int __user *)p);
2637        }
2638        /*
2639         * Break handling
2640         */
2641        case TIOCSBRK:  /* Turn break on, unconditionally */
2642                if (tty->ops->break_ctl)
2643                        return tty->ops->break_ctl(tty, -1);
2644                return 0;
2645        case TIOCCBRK:  /* Turn break off, unconditionally */
2646                if (tty->ops->break_ctl)
2647                        return tty->ops->break_ctl(tty, 0);
2648                return 0;
2649        case TCSBRK:   /* SVID version: non-zero arg --> no break */
2650                /* non-zero arg means wait for all output data
2651                 * to be sent (performed above) but don't send break.
2652                 * This is used by the tcdrain() termios function.
2653                 */
2654                if (!arg)
2655                        return send_break(tty, 250);
2656                return 0;
2657        case TCSBRKP:   /* support for POSIX tcsendbreak() */
2658                return send_break(tty, arg ? arg*100 : 250);
2659
2660        case TIOCMGET:
2661                return tty_tiocmget(tty, p);
2662        case TIOCMSET:
2663        case TIOCMBIC:
2664        case TIOCMBIS:
2665                return tty_tiocmset(tty, cmd, p);
2666        case TIOCGICOUNT:
2667                retval = tty_tiocgicount(tty, p);
2668                /* For the moment allow fall through to the old method */
2669                if (retval != -EINVAL)
2670                        return retval;
2671                break;
2672        case TCFLSH:
2673                switch (arg) {
2674                case TCIFLUSH:
2675                case TCIOFLUSH:
2676                /* flush tty buffer and allow ldisc to process ioctl */
2677                        tty_buffer_flush(tty, NULL);
2678                        break;
2679                }
2680                break;
2681        case TIOCSSERIAL:
2682                return tty_tiocsserial(tty, p);
2683        case TIOCGSERIAL:
2684                return tty_tiocgserial(tty, p);
2685        case TIOCGPTPEER:
2686                /* Special because the struct file is needed */
2687                return ptm_open_peer(file, tty, (int)arg);
2688        default:
2689                retval = tty_jobctrl_ioctl(tty, real_tty, file, cmd, arg);
2690                if (retval != -ENOIOCTLCMD)
2691                        return retval;
2692        }
2693        if (tty->ops->ioctl) {
2694                retval = tty->ops->ioctl(tty, cmd, arg);
2695                if (retval != -ENOIOCTLCMD)
2696                        return retval;
2697        }
2698        ld = tty_ldisc_ref_wait(tty);
2699        if (!ld)
2700                return hung_up_tty_ioctl(file, cmd, arg);
2701        retval = -EINVAL;
2702        if (ld->ops->ioctl) {
2703                retval = ld->ops->ioctl(tty, file, cmd, arg);
2704                if (retval == -ENOIOCTLCMD)
2705                        retval = -ENOTTY;
2706        }
2707        tty_ldisc_deref(ld);
2708        return retval;
2709}
2710
2711#ifdef CONFIG_COMPAT
2712static long tty_compat_ioctl(struct file *file, unsigned int cmd,
2713                                unsigned long arg)
2714{
2715        struct tty_struct *tty = file_tty(file);
2716        struct tty_ldisc *ld;
2717        int retval = -ENOIOCTLCMD;
2718
2719        if (tty_paranoia_check(tty, file_inode(file), "tty_ioctl"))
2720                return -EINVAL;
2721
2722        if (tty->ops->compat_ioctl) {
2723                retval = tty->ops->compat_ioctl(tty, cmd, arg);
2724                if (retval != -ENOIOCTLCMD)
2725                        return retval;
2726        }
2727
2728        ld = tty_ldisc_ref_wait(tty);
2729        if (!ld)
2730                return hung_up_tty_compat_ioctl(file, cmd, arg);
2731        if (ld->ops->compat_ioctl)
2732                retval = ld->ops->compat_ioctl(tty, file, cmd, arg);
2733        else
2734                retval = n_tty_compat_ioctl_helper(tty, file, cmd, arg);
2735        tty_ldisc_deref(ld);
2736
2737        return retval;
2738}
2739#endif
2740
2741static int this_tty(const void *t, struct file *file, unsigned fd)
2742{
2743        if (likely(file->f_op->read != tty_read))
2744                return 0;
2745        return file_tty(file) != t ? 0 : fd + 1;
2746}
2747        
2748/*
2749 * This implements the "Secure Attention Key" ---  the idea is to
2750 * prevent trojan horses by killing all processes associated with this
2751 * tty when the user hits the "Secure Attention Key".  Required for
2752 * super-paranoid applications --- see the Orange Book for more details.
2753 *
2754 * This code could be nicer; ideally it should send a HUP, wait a few
2755 * seconds, then send a INT, and then a KILL signal.  But you then
2756 * have to coordinate with the init process, since all processes associated
2757 * with the current tty must be dead before the new getty is allowed
2758 * to spawn.
2759 *
2760 * Now, if it would be correct ;-/ The current code has a nasty hole -
2761 * it doesn't catch files in flight. We may send the descriptor to ourselves
2762 * via AF_UNIX socket, close it and later fetch from socket. FIXME.
2763 *
2764 * Nasty bug: do_SAK is being called in interrupt context.  This can
2765 * deadlock.  We punt it up to process context.  AKPM - 16Mar2001
2766 */
2767void __do_SAK(struct tty_struct *tty)
2768{
2769#ifdef TTY_SOFT_SAK
2770        tty_hangup(tty);
2771#else
2772        struct task_struct *g, *p;
2773        struct pid *session;
2774        int             i;
2775        unsigned long flags;
2776
2777        if (!tty)
2778                return;
2779
2780        spin_lock_irqsave(&tty->ctrl_lock, flags);
2781        session = get_pid(tty->session);
2782        spin_unlock_irqrestore(&tty->ctrl_lock, flags);
2783
2784        tty_ldisc_flush(tty);
2785
2786        tty_driver_flush_buffer(tty);
2787
2788        read_lock(&tasklist_lock);
2789        /* Kill the entire session */
2790        do_each_pid_task(session, PIDTYPE_SID, p) {
2791                tty_notice(tty, "SAK: killed process %d (%s): by session\n",
2792                           task_pid_nr(p), p->comm);
2793                group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);
2794        } while_each_pid_task(session, PIDTYPE_SID, p);
2795
2796        /* Now kill any processes that happen to have the tty open */
2797        do_each_thread(g, p) {
2798                if (p->signal->tty == tty) {
2799                        tty_notice(tty, "SAK: killed process %d (%s): by controlling tty\n",
2800                                   task_pid_nr(p), p->comm);
2801                        group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);
2802                        continue;
2803                }
2804                task_lock(p);
2805                i = iterate_fd(p->files, 0, this_tty, tty);
2806                if (i != 0) {
2807                        tty_notice(tty, "SAK: killed process %d (%s): by fd#%d\n",
2808                                   task_pid_nr(p), p->comm, i - 1);
2809                        group_send_sig_info(SIGKILL, SEND_SIG_PRIV, p, PIDTYPE_SID);
2810                }
2811                task_unlock(p);
2812        } while_each_thread(g, p);
2813        read_unlock(&tasklist_lock);
2814        put_pid(session);
2815#endif
2816}
2817
2818static void do_SAK_work(struct work_struct *work)
2819{
2820        struct tty_struct *tty =
2821                container_of(work, struct tty_struct, SAK_work);
2822        __do_SAK(tty);
2823}
2824
2825/*
2826 * The tq handling here is a little racy - tty->SAK_work may already be queued.
2827 * Fortunately we don't need to worry, because if ->SAK_work is already queued,
2828 * the values which we write to it will be identical to the values which it
2829 * already has. --akpm
2830 */
2831void do_SAK(struct tty_struct *tty)
2832{
2833        if (!tty)
2834                return;
2835        schedule_work(&tty->SAK_work);
2836}
2837
2838EXPORT_SYMBOL(do_SAK);
2839
2840/* Must put_device() after it's unused! */
2841static struct device *tty_get_device(struct tty_struct *tty)
2842{
2843        dev_t devt = tty_devnum(tty);
2844        return class_find_device_by_devt(tty_class, devt);
2845}
2846
2847
2848/**
2849 *      alloc_tty_struct
2850 *
2851 *      This subroutine allocates and initializes a tty structure.
2852 *
2853 *      Locking: none - tty in question is not exposed at this point
2854 */
2855
2856struct tty_struct *alloc_tty_struct(struct tty_driver *driver, int idx)
2857{
2858        struct tty_struct *tty;
2859
2860        tty = kzalloc(sizeof(*tty), GFP_KERNEL);
2861        if (!tty)
2862                return NULL;
2863
2864        kref_init(&tty->kref);
2865        tty->magic = TTY_MAGIC;
2866        if (tty_ldisc_init(tty)) {
2867                kfree(tty);
2868                return NULL;
2869        }
2870        tty->session = NULL;
2871        tty->pgrp = NULL;
2872        mutex_init(&tty->legacy_mutex);
2873        mutex_init(&tty->throttle_mutex);
2874        init_rwsem(&tty->termios_rwsem);
2875        mutex_init(&tty->winsize_mutex);
2876        init_ldsem(&tty->ldisc_sem);
2877        init_waitqueue_head(&tty->write_wait);
2878        init_waitqueue_head(&tty->read_wait);
2879        INIT_WORK(&tty->hangup_work, do_tty_hangup);
2880        mutex_init(&tty->atomic_write_lock);
2881        spin_lock_init(&tty->ctrl_lock);
2882        spin_lock_init(&tty->flow_lock);
2883        spin_lock_init(&tty->files_lock);
2884        INIT_LIST_HEAD(&tty->tty_files);
2885        INIT_WORK(&tty->SAK_work, do_SAK_work);
2886
2887        tty->driver = driver;
2888        tty->ops = driver->ops;
2889        tty->index = idx;
2890        tty_line_name(driver, idx, tty->name);
2891        tty->dev = tty_get_device(tty);
2892
2893        return tty;
2894}
2895
2896/**
2897 *      tty_put_char    -       write one character to a tty
2898 *      @tty: tty
2899 *      @ch: character
2900 *
2901 *      Write one byte to the tty using the provided put_char method
2902 *      if present. Returns the number of characters successfully output.
2903 *
2904 *      Note: the specific put_char operation in the driver layer may go
2905 *      away soon. Don't call it directly, use this method
2906 */
2907
2908int tty_put_char(struct tty_struct *tty, unsigned char ch)
2909{
2910        if (tty->ops->put_char)
2911                return tty->ops->put_char(tty, ch);
2912        return tty->ops->write(tty, &ch, 1);
2913}
2914EXPORT_SYMBOL_GPL(tty_put_char);
2915
2916struct class *tty_class;
2917
2918static int tty_cdev_add(struct tty_driver *driver, dev_t dev,
2919                unsigned int index, unsigned int count)
2920{
2921        int err;
2922
2923        /* init here, since reused cdevs cause crashes */
2924        driver->cdevs[index] = cdev_alloc();
2925        if (!driver->cdevs[index])
2926                return -ENOMEM;
2927        driver->cdevs[index]->ops = &tty_fops;
2928        driver->cdevs[index]->owner = driver->owner;
2929        err = cdev_add(driver->cdevs[index], dev, count);
2930        if (err)
2931                kobject_put(&driver->cdevs[index]->kobj);
2932        return err;
2933}
2934
2935/**
2936 *      tty_register_device - register a tty device
2937 *      @driver: the tty driver that describes the tty device
2938 *      @index: the index in the tty driver for this tty device
2939 *      @device: a struct device that is associated with this tty device.
2940 *              This field is optional, if there is no known struct device
2941 *              for this tty device it can be set to NULL safely.
2942 *
2943 *      Returns a pointer to the struct device for this tty device
2944 *      (or ERR_PTR(-EFOO) on error).
2945 *
2946 *      This call is required to be made to register an individual tty device
2947 *      if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set.  If
2948 *      that bit is not set, this function should not be called by a tty
2949 *      driver.
2950 *
2951 *      Locking: ??
2952 */
2953
2954struct device *tty_register_device(struct tty_driver *driver, unsigned index,
2955                                   struct device *device)
2956{
2957        return tty_register_device_attr(driver, index, device, NULL, NULL);
2958}
2959EXPORT_SYMBOL(tty_register_device);
2960
2961static void tty_device_create_release(struct device *dev)
2962{
2963        dev_dbg(dev, "releasing...\n");
2964        kfree(dev);
2965}
2966
2967/**
2968 *      tty_register_device_attr - register a tty device
2969 *      @driver: the tty driver that describes the tty device
2970 *      @index: the index in the tty driver for this tty device
2971 *      @device: a struct device that is associated with this tty device.
2972 *              This field is optional, if there is no known struct device
2973 *              for this tty device it can be set to NULL safely.
2974 *      @drvdata: Driver data to be set to device.
2975 *      @attr_grp: Attribute group to be set on device.
2976 *
2977 *      Returns a pointer to the struct device for this tty device
2978 *      (or ERR_PTR(-EFOO) on error).
2979 *
2980 *      This call is required to be made to register an individual tty device
2981 *      if the tty driver's flags have the TTY_DRIVER_DYNAMIC_DEV bit set.  If
2982 *      that bit is not set, this function should not be called by a tty
2983 *      driver.
2984 *
2985 *      Locking: ??
2986 */
2987struct device *tty_register_device_attr(struct tty_driver *driver,
2988                                   unsigned index, struct device *device,
2989                                   void *drvdata,
2990                                   const struct attribute_group **attr_grp)
2991{
2992        char name[64];
2993        dev_t devt = MKDEV(driver->major, driver->minor_start) + index;
2994        struct ktermios *tp;
2995        struct device *dev;
2996        int retval;
2997
2998        if (index >= driver->num) {
2999                pr_err("%s: Attempt to register invalid tty line number (%d)\n",
3000                       driver->name, index);
3001                return ERR_PTR(-EINVAL);
3002        }
3003
3004        if (driver->type == TTY_DRIVER_TYPE_PTY)
3005                pty_line_name(driver, index, name);
3006        else
3007                tty_line_name(driver, index, name);
3008
3009        dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3010        if (!dev)
3011                return ERR_PTR(-ENOMEM);
3012
3013        dev->devt = devt;
3014        dev->class = tty_class;
3015        dev->parent = device;
3016        dev->release = tty_device_create_release;
3017        dev_set_name(dev, "%s", name);
3018        dev->groups = attr_grp;
3019        dev_set_drvdata(dev, drvdata);
3020
3021        dev_set_uevent_suppress(dev, 1);
3022
3023        retval = device_register(dev);
3024        if (retval)
3025                goto err_put;
3026
3027        if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
3028                /*
3029                 * Free any saved termios data so that the termios state is
3030                 * reset when reusing a minor number.
3031                 */
3032                tp = driver->termios[index];
3033                if (tp) {
3034                        driver->termios[index] = NULL;
3035                        kfree(tp);
3036                }
3037
3038                retval = tty_cdev_add(driver, devt, index, 1);
3039                if (retval)
3040                        goto err_del;
3041        }
3042
3043        dev_set_uevent_suppress(dev, 0);
3044        kobject_uevent(&dev->kobj, KOBJ_ADD);
3045
3046        return dev;
3047
3048err_del:
3049        device_del(dev);
3050err_put:
3051        put_device(dev);
3052
3053        return ERR_PTR(retval);
3054}
3055EXPORT_SYMBOL_GPL(tty_register_device_attr);
3056
3057/**
3058 *      tty_unregister_device - unregister a tty device
3059 *      @driver: the tty driver that describes the tty device
3060 *      @index: the index in the tty driver for this tty device
3061 *
3062 *      If a tty device is registered with a call to tty_register_device() then
3063 *      this function must be called when the tty device is gone.
3064 *
3065 *      Locking: ??
3066 */
3067
3068void tty_unregister_device(struct tty_driver *driver, unsigned index)
3069{
3070        device_destroy(tty_class,
3071                MKDEV(driver->major, driver->minor_start) + index);
3072        if (!(driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
3073                cdev_del(driver->cdevs[index]);
3074                driver->cdevs[index] = NULL;
3075        }
3076}
3077EXPORT_SYMBOL(tty_unregister_device);
3078
3079/**
3080 * __tty_alloc_driver -- allocate tty driver
3081 * @lines: count of lines this driver can handle at most
3082 * @owner: module which is responsible for this driver
3083 * @flags: some of TTY_DRIVER_* flags, will be set in driver->flags
3084 *
3085 * This should not be called directly, some of the provided macros should be
3086 * used instead. Use IS_ERR and friends on @retval.
3087 */
3088struct tty_driver *__tty_alloc_driver(unsigned int lines, struct module *owner,
3089                unsigned long flags)
3090{
3091        struct tty_driver *driver;
3092        unsigned int cdevs = 1;
3093        int err;
3094
3095        if (!lines || (flags & TTY_DRIVER_UNNUMBERED_NODE && lines > 1))
3096                return ERR_PTR(-EINVAL);
3097
3098        driver = kzalloc(sizeof(struct tty_driver), GFP_KERNEL);
3099        if (!driver)
3100                return ERR_PTR(-ENOMEM);
3101
3102        kref_init(&driver->kref);
3103        driver->magic = TTY_DRIVER_MAGIC;
3104        driver->num = lines;
3105        driver->owner = owner;
3106        driver->flags = flags;
3107
3108        if (!(flags & TTY_DRIVER_DEVPTS_MEM)) {
3109                driver->ttys = kcalloc(lines, sizeof(*driver->ttys),
3110                                GFP_KERNEL);
3111                driver->termios = kcalloc(lines, sizeof(*driver->termios),
3112                                GFP_KERNEL);
3113                if (!driver->ttys || !driver->termios) {
3114                        err = -ENOMEM;
3115                        goto err_free_all;
3116                }
3117        }
3118
3119        if (!(flags & TTY_DRIVER_DYNAMIC_ALLOC)) {
3120                driver->ports = kcalloc(lines, sizeof(*driver->ports),
3121                                GFP_KERNEL);
3122                if (!driver->ports) {
3123                        err = -ENOMEM;
3124                        goto err_free_all;
3125                }
3126                cdevs = lines;
3127        }
3128
3129        driver->cdevs = kcalloc(cdevs, sizeof(*driver->cdevs), GFP_KERNEL);
3130        if (!driver->cdevs) {
3131                err = -ENOMEM;
3132                goto err_free_all;
3133        }
3134
3135        return driver;
3136err_free_all:
3137        kfree(driver->ports);
3138        kfree(driver->ttys);
3139        kfree(driver->termios);
3140        kfree(driver->cdevs);
3141        kfree(driver);
3142        return ERR_PTR(err);
3143}
3144EXPORT_SYMBOL(__tty_alloc_driver);
3145
3146static void destruct_tty_driver(struct kref *kref)
3147{
3148        struct tty_driver *driver = container_of(kref, struct tty_driver, kref);
3149        int i;
3150        struct ktermios *tp;
3151
3152        if (driver->flags & TTY_DRIVER_INSTALLED) {
3153                for (i = 0; i < driver->num; i++) {
3154                        tp = driver->termios[i];
3155                        if (tp) {
3156                                driver->termios[i] = NULL;
3157                                kfree(tp);
3158                        }
3159                        if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV))
3160                                tty_unregister_device(driver, i);
3161                }
3162                proc_tty_unregister_driver(driver);
3163                if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC)
3164                        cdev_del(driver->cdevs[0]);
3165        }
3166        kfree(driver->cdevs);
3167        kfree(driver->ports);
3168        kfree(driver->termios);
3169        kfree(driver->ttys);
3170        kfree(driver);
3171}
3172
3173void tty_driver_kref_put(struct tty_driver *driver)
3174{
3175        kref_put(&driver->kref, destruct_tty_driver);
3176}
3177EXPORT_SYMBOL(tty_driver_kref_put);
3178
3179void tty_set_operations(struct tty_driver *driver,
3180                        const struct tty_operations *op)
3181{
3182        driver->ops = op;
3183};
3184EXPORT_SYMBOL(tty_set_operations);
3185
3186void put_tty_driver(struct tty_driver *d)
3187{
3188        tty_driver_kref_put(d);
3189}
3190EXPORT_SYMBOL(put_tty_driver);
3191
3192/*
3193 * Called by a tty driver to register itself.
3194 */
3195int tty_register_driver(struct tty_driver *driver)
3196{
3197        int error;
3198        int i;
3199        dev_t dev;
3200        struct device *d;
3201
3202        if (!driver->major) {
3203                error = alloc_chrdev_region(&dev, driver->minor_start,
3204                                                driver->num, driver->name);
3205                if (!error) {
3206                        driver->major = MAJOR(dev);
3207                        driver->minor_start = MINOR(dev);
3208                }
3209        } else {
3210                dev = MKDEV(driver->major, driver->minor_start);
3211                error = register_chrdev_region(dev, driver->num, driver->name);
3212        }
3213        if (error < 0)
3214                goto err;
3215
3216        if (driver->flags & TTY_DRIVER_DYNAMIC_ALLOC) {
3217                error = tty_cdev_add(driver, dev, 0, driver->num);
3218                if (error)
3219                        goto err_unreg_char;
3220        }
3221
3222        mutex_lock(&tty_mutex);
3223        list_add(&driver->tty_drivers, &tty_drivers);
3224        mutex_unlock(&tty_mutex);
3225
3226        if (!(driver->flags & TTY_DRIVER_DYNAMIC_DEV)) {
3227                for (i = 0; i < driver->num; i++) {
3228                        d = tty_register_device(driver, i, NULL);
3229                        if (IS_ERR(d)) {
3230                                error = PTR_ERR(d);
3231                                goto err_unreg_devs;
3232                        }
3233                }
3234        }
3235        proc_tty_register_driver(driver);
3236        driver->flags |= TTY_DRIVER_INSTALLED;
3237        return 0;
3238
3239err_unreg_devs:
3240        for (i--; i >= 0; i--)
3241                tty_unregister_device(driver, i);
3242
3243        mutex_lock(&tty_mutex);
3244        list_del(&driver->tty_drivers);
3245        mutex_unlock(&tty_mutex);
3246
3247err_unreg_char:
3248        unregister_chrdev_region(dev, driver->num);
3249err:
3250        return error;
3251}
3252EXPORT_SYMBOL(tty_register_driver);
3253
3254/*
3255 * Called by a tty driver to unregister itself.
3256 */
3257int tty_unregister_driver(struct tty_driver *driver)
3258{
3259#if 0
3260        /* FIXME */
3261        if (driver->refcount)
3262                return -EBUSY;
3263#endif
3264        unregister_chrdev_region(MKDEV(driver->major, driver->minor_start),
3265                                driver->num);
3266        mutex_lock(&tty_mutex);
3267        list_del(&driver->tty_drivers);
3268        mutex_unlock(&tty_mutex);
3269        return 0;
3270}
3271
3272EXPORT_SYMBOL(tty_unregister_driver);
3273
3274dev_t tty_devnum(struct tty_struct *tty)
3275{
3276        return MKDEV(tty->driver->major, tty->driver->minor_start) + tty->index;
3277}
3278EXPORT_SYMBOL(tty_devnum);
3279
3280void tty_default_fops(struct file_operations *fops)
3281{
3282        *fops = tty_fops;
3283}
3284
3285static char *tty_devnode(struct device *dev, umode_t *mode)
3286{
3287        if (!mode)
3288                return NULL;
3289        if (dev->devt == MKDEV(TTYAUX_MAJOR, 0) ||
3290            dev->devt == MKDEV(TTYAUX_MAJOR, 2))
3291                *mode = 0666;
3292        return NULL;
3293}
3294
3295static int __init tty_class_init(void)
3296{
3297        tty_class = class_create(THIS_MODULE, "tty");
3298        if (IS_ERR(tty_class))
3299                return PTR_ERR(tty_class);
3300        tty_class->devnode = tty_devnode;
3301        return 0;
3302}
3303
3304postcore_initcall(tty_class_init);
3305
3306/* 3/2004 jmc: why do these devices exist? */
3307static struct cdev tty_cdev, console_cdev;
3308
3309static ssize_t show_cons_active(struct device *dev,
3310                                struct device_attribute *attr, char *buf)
3311{
3312        struct console *cs[16];
3313        int i = 0;
3314        struct console *c;
3315        ssize_t count = 0;
3316
3317        console_lock();
3318        for_each_console(c) {
3319                if (!c->device)
3320                        continue;
3321                if (!c->write)
3322                        continue;
3323                if ((c->flags & CON_ENABLED) == 0)
3324                        continue;
3325                cs[i++] = c;
3326                if (i >= ARRAY_SIZE(cs))
3327                        break;
3328        }
3329        while (i--) {
3330                int index = cs[i]->index;
3331                struct tty_driver *drv = cs[i]->device(cs[i], &index);
3332
3333                /* don't resolve tty0 as some programs depend on it */
3334                if (drv && (cs[i]->index > 0 || drv->major != TTY_MAJOR))
3335                        count += tty_line_name(drv, index, buf + count);
3336                else
3337                        count += sprintf(buf + count, "%s%d",
3338                                         cs[i]->name, cs[i]->index);
3339
3340                count += sprintf(buf + count, "%c", i ? ' ':'\n');
3341        }
3342        console_unlock();
3343
3344        return count;
3345}
3346static DEVICE_ATTR(active, S_IRUGO, show_cons_active, NULL);
3347
3348static struct attribute *cons_dev_attrs[] = {
3349        &dev_attr_active.attr,
3350        NULL
3351};
3352
3353ATTRIBUTE_GROUPS(cons_dev);
3354
3355static struct device *consdev;
3356
3357void console_sysfs_notify(void)
3358{
3359        if (consdev)
3360                sysfs_notify(&consdev->kobj, NULL, "active");
3361}
3362
3363/*
3364 * Ok, now we can initialize the rest of the tty devices and can count
3365 * on memory allocations, interrupts etc..
3366 */
3367int __init tty_init(void)
3368{
3369        cdev_init(&tty_cdev, &tty_fops);
3370        if (cdev_add(&tty_cdev, MKDEV(TTYAUX_MAJOR, 0), 1) ||
3371            register_chrdev_region(MKDEV(TTYAUX_MAJOR, 0), 1, "/dev/tty") < 0)
3372                panic("Couldn't register /dev/tty driver\n");
3373        device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 0), NULL, "tty");
3374
3375        cdev_init(&console_cdev, &console_fops);
3376        if (cdev_add(&console_cdev, MKDEV(TTYAUX_MAJOR, 1), 1) ||
3377            register_chrdev_region(MKDEV(TTYAUX_MAJOR, 1), 1, "/dev/console") < 0)
3378                panic("Couldn't register /dev/console driver\n");
3379        consdev = device_create_with_groups(tty_class, NULL,
3380                                            MKDEV(TTYAUX_MAJOR, 1), NULL,
3381                                            cons_dev_groups, "console");
3382        if (IS_ERR(consdev))
3383                consdev = NULL;
3384
3385#ifdef CONFIG_VT
3386        vty_init(&console_fops);
3387#endif
3388        return 0;
3389}
3390
3391