linux/drivers/tty/vt/vt.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *  Copyright (C) 1991, 1992  Linus Torvalds
   4 */
   5
   6/*
   7 * Hopefully this will be a rather complete VT102 implementation.
   8 *
   9 * Beeping thanks to John T Kohl.
  10 *
  11 * Virtual Consoles, Screen Blanking, Screen Dumping, Color, Graphics
  12 *   Chars, and VT100 enhancements by Peter MacDonald.
  13 *
  14 * Copy and paste function by Andrew Haylett,
  15 *   some enhancements by Alessandro Rubini.
  16 *
  17 * Code to check for different video-cards mostly by Galen Hunt,
  18 * <g-hunt@ee.utah.edu>
  19 *
  20 * Rudimentary ISO 10646/Unicode/UTF-8 character set support by
  21 * Markus Kuhn, <mskuhn@immd4.informatik.uni-erlangen.de>.
  22 *
  23 * Dynamic allocation of consoles, aeb@cwi.nl, May 1994
  24 * Resizing of consoles, aeb, 940926
  25 *
  26 * Code for xterm like mouse click reporting by Peter Orbaek 20-Jul-94
  27 * <poe@daimi.aau.dk>
  28 *
  29 * User-defined bell sound, new setterm control sequences and printk
  30 * redirection by Martin Mares <mj@k332.feld.cvut.cz> 19-Nov-95
  31 *
  32 * APM screenblank bug fixed Takashi Manabe <manabe@roy.dsl.tutics.tut.jp>
  33 *
  34 * Merge with the abstract console driver by Geert Uytterhoeven
  35 * <geert@linux-m68k.org>, Jan 1997.
  36 *
  37 *   Original m68k console driver modifications by
  38 *
  39 *     - Arno Griffioen <arno@usn.nl>
  40 *     - David Carter <carter@cs.bris.ac.uk>
  41 * 
  42 *   The abstract console driver provides a generic interface for a text
  43 *   console. It supports VGA text mode, frame buffer based graphical consoles
  44 *   and special graphics processors that are only accessible through some
  45 *   registers (e.g. a TMS340x0 GSP).
  46 *
  47 *   The interface to the hardware is specified using a special structure
  48 *   (struct consw) which contains function pointers to console operations
  49 *   (see <linux/console.h> for more information).
  50 *
  51 * Support for changeable cursor shape
  52 * by Pavel Machek <pavel@atrey.karlin.mff.cuni.cz>, August 1997
  53 *
  54 * Ported to i386 and con_scrolldelta fixed
  55 * by Emmanuel Marty <core@ggi-project.org>, April 1998
  56 *
  57 * Resurrected character buffers in videoram plus lots of other trickery
  58 * by Martin Mares <mj@atrey.karlin.mff.cuni.cz>, July 1998
  59 *
  60 * Removed old-style timers, introduced console_timer, made timer
  61 * deletion SMP-safe.  17Jun00, Andrew Morton
  62 *
  63 * Removed console_lock, enabled interrupts across all console operations
  64 * 13 March 2001, Andrew Morton
  65 *
  66 * Fixed UTF-8 mode so alternate charset modes always work according
  67 * to control sequences interpreted in do_con_trol function
  68 * preserving backward VT100 semigraphics compatibility,
  69 * malformed UTF sequences represented as sequences of replacement glyphs,
  70 * original codes or '?' as a last resort if replacement glyph is undefined
  71 * by Adam Tla/lka <atlka@pg.gda.pl>, Aug 2006
  72 */
  73
  74#include <linux/module.h>
  75#include <linux/types.h>
  76#include <linux/sched/signal.h>
  77#include <linux/tty.h>
  78#include <linux/tty_flip.h>
  79#include <linux/kernel.h>
  80#include <linux/string.h>
  81#include <linux/errno.h>
  82#include <linux/kd.h>
  83#include <linux/slab.h>
  84#include <linux/major.h>
  85#include <linux/mm.h>
  86#include <linux/console.h>
  87#include <linux/init.h>
  88#include <linux/mutex.h>
  89#include <linux/vt_kern.h>
  90#include <linux/selection.h>
  91#include <linux/tiocl.h>
  92#include <linux/kbd_kern.h>
  93#include <linux/consolemap.h>
  94#include <linux/timer.h>
  95#include <linux/interrupt.h>
  96#include <linux/workqueue.h>
  97#include <linux/pm.h>
  98#include <linux/font.h>
  99#include <linux/bitops.h>
 100#include <linux/notifier.h>
 101#include <linux/device.h>
 102#include <linux/io.h>
 103#include <linux/uaccess.h>
 104#include <linux/kdb.h>
 105#include <linux/ctype.h>
 106#include <linux/bsearch.h>
 107
 108#define MAX_NR_CON_DRIVER 16
 109
 110#define CON_DRIVER_FLAG_MODULE 1
 111#define CON_DRIVER_FLAG_INIT   2
 112#define CON_DRIVER_FLAG_ATTR   4
 113#define CON_DRIVER_FLAG_ZOMBIE 8
 114
 115struct con_driver {
 116        const struct consw *con;
 117        const char *desc;
 118        struct device *dev;
 119        int node;
 120        int first;
 121        int last;
 122        int flag;
 123};
 124
 125static struct con_driver registered_con_driver[MAX_NR_CON_DRIVER];
 126const struct consw *conswitchp;
 127
 128/* A bitmap for codes <32. A bit of 1 indicates that the code
 129 * corresponding to that bit number invokes some special action
 130 * (such as cursor movement) and should not be displayed as a
 131 * glyph unless the disp_ctrl mode is explicitly enabled.
 132 */
 133#define CTRL_ACTION 0x0d00ff81
 134#define CTRL_ALWAYS 0x0800f501  /* Cannot be overridden by disp_ctrl */
 135
 136/*
 137 * Here is the default bell parameters: 750HZ, 1/8th of a second
 138 */
 139#define DEFAULT_BELL_PITCH      750
 140#define DEFAULT_BELL_DURATION   (HZ/8)
 141#define DEFAULT_CURSOR_BLINK_MS 200
 142
 143struct vc vc_cons [MAX_NR_CONSOLES];
 144
 145#ifndef VT_SINGLE_DRIVER
 146static const struct consw *con_driver_map[MAX_NR_CONSOLES];
 147#endif
 148
 149static int con_open(struct tty_struct *, struct file *);
 150static void vc_init(struct vc_data *vc, unsigned int rows,
 151                    unsigned int cols, int do_clear);
 152static void gotoxy(struct vc_data *vc, int new_x, int new_y);
 153static void save_cur(struct vc_data *vc);
 154static void reset_terminal(struct vc_data *vc, int do_clear);
 155static void con_flush_chars(struct tty_struct *tty);
 156static int set_vesa_blanking(char __user *p);
 157static void set_cursor(struct vc_data *vc);
 158static void hide_cursor(struct vc_data *vc);
 159static void console_callback(struct work_struct *ignored);
 160static void con_driver_unregister_callback(struct work_struct *ignored);
 161static void blank_screen_t(struct timer_list *unused);
 162static void set_palette(struct vc_data *vc);
 163
 164#define vt_get_kmsg_redirect() vt_kmsg_redirect(-1)
 165
 166static int printable;           /* Is console ready for printing? */
 167int default_utf8 = true;
 168module_param(default_utf8, int, S_IRUGO | S_IWUSR);
 169int global_cursor_default = -1;
 170module_param(global_cursor_default, int, S_IRUGO | S_IWUSR);
 171
 172static int cur_default = CUR_DEFAULT;
 173module_param(cur_default, int, S_IRUGO | S_IWUSR);
 174
 175/*
 176 * ignore_poke: don't unblank the screen when things are typed.  This is
 177 * mainly for the privacy of braille terminal users.
 178 */
 179static int ignore_poke;
 180
 181int do_poke_blanked_console;
 182int console_blanked;
 183
 184static int vesa_blank_mode; /* 0:none 1:suspendV 2:suspendH 3:powerdown */
 185static int vesa_off_interval;
 186static int blankinterval;
 187core_param(consoleblank, blankinterval, int, 0444);
 188
 189static DECLARE_WORK(console_work, console_callback);
 190static DECLARE_WORK(con_driver_unregister_work, con_driver_unregister_callback);
 191
 192/*
 193 * fg_console is the current virtual console,
 194 * last_console is the last used one,
 195 * want_console is the console we want to switch to,
 196 * saved_* variants are for save/restore around kernel debugger enter/leave
 197 */
 198int fg_console;
 199int last_console;
 200int want_console = -1;
 201static int saved_fg_console;
 202static int saved_last_console;
 203static int saved_want_console;
 204static int saved_vc_mode;
 205static int saved_console_blanked;
 206
 207/*
 208 * For each existing display, we have a pointer to console currently visible
 209 * on that display, allowing consoles other than fg_console to be refreshed
 210 * appropriately. Unless the low-level driver supplies its own display_fg
 211 * variable, we use this one for the "master display".
 212 */
 213static struct vc_data *master_display_fg;
 214
 215/*
 216 * Unfortunately, we need to delay tty echo when we're currently writing to the
 217 * console since the code is (and always was) not re-entrant, so we schedule
 218 * all flip requests to process context with schedule-task() and run it from
 219 * console_callback().
 220 */
 221
 222/*
 223 * For the same reason, we defer scrollback to the console callback.
 224 */
 225static int scrollback_delta;
 226
 227/*
 228 * Hook so that the power management routines can (un)blank
 229 * the console on our behalf.
 230 */
 231int (*console_blank_hook)(int);
 232
 233static DEFINE_TIMER(console_timer, blank_screen_t);
 234static int blank_state;
 235static int blank_timer_expired;
 236enum {
 237        blank_off = 0,
 238        blank_normal_wait,
 239        blank_vesa_wait,
 240};
 241
 242/*
 243 * /sys/class/tty/tty0/
 244 *
 245 * the attribute 'active' contains the name of the current vc
 246 * console and it supports poll() to detect vc switches
 247 */
 248static struct device *tty0dev;
 249
 250/*
 251 * Notifier list for console events.
 252 */
 253static ATOMIC_NOTIFIER_HEAD(vt_notifier_list);
 254
 255int register_vt_notifier(struct notifier_block *nb)
 256{
 257        return atomic_notifier_chain_register(&vt_notifier_list, nb);
 258}
 259EXPORT_SYMBOL_GPL(register_vt_notifier);
 260
 261int unregister_vt_notifier(struct notifier_block *nb)
 262{
 263        return atomic_notifier_chain_unregister(&vt_notifier_list, nb);
 264}
 265EXPORT_SYMBOL_GPL(unregister_vt_notifier);
 266
 267static void notify_write(struct vc_data *vc, unsigned int unicode)
 268{
 269        struct vt_notifier_param param = { .vc = vc, .c = unicode };
 270        atomic_notifier_call_chain(&vt_notifier_list, VT_WRITE, &param);
 271}
 272
 273static void notify_update(struct vc_data *vc)
 274{
 275        struct vt_notifier_param param = { .vc = vc };
 276        atomic_notifier_call_chain(&vt_notifier_list, VT_UPDATE, &param);
 277}
 278/*
 279 *      Low-Level Functions
 280 */
 281
 282static inline bool con_is_fg(const struct vc_data *vc)
 283{
 284        return vc->vc_num == fg_console;
 285}
 286
 287static inline bool con_should_update(const struct vc_data *vc)
 288{
 289        return con_is_visible(vc) && !console_blanked;
 290}
 291
 292static inline unsigned short *screenpos(struct vc_data *vc, int offset, int viewed)
 293{
 294        unsigned short *p;
 295        
 296        if (!viewed)
 297                p = (unsigned short *)(vc->vc_origin + offset);
 298        else if (!vc->vc_sw->con_screen_pos)
 299                p = (unsigned short *)(vc->vc_visible_origin + offset);
 300        else
 301                p = vc->vc_sw->con_screen_pos(vc, offset);
 302        return p;
 303}
 304
 305/* Called  from the keyboard irq path.. */
 306static inline void scrolldelta(int lines)
 307{
 308        /* FIXME */
 309        /* scrolldelta needs some kind of consistency lock, but the BKL was
 310           and still is not protecting versus the scheduled back end */
 311        scrollback_delta += lines;
 312        schedule_console_callback();
 313}
 314
 315void schedule_console_callback(void)
 316{
 317        schedule_work(&console_work);
 318}
 319
 320/*
 321 * Code to manage unicode-based screen buffers
 322 */
 323
 324#ifdef NO_VC_UNI_SCREEN
 325/* this disables and optimizes related code away at compile time */
 326#define get_vc_uniscr(vc) NULL
 327#else
 328#define get_vc_uniscr(vc) vc->vc_uni_screen
 329#endif
 330
 331typedef uint32_t char32_t;
 332
 333/*
 334 * Our screen buffer is preceded by an array of line pointers so that
 335 * scrolling only implies some pointer shuffling.
 336 */
 337struct uni_screen {
 338        char32_t *lines[0];
 339};
 340
 341static struct uni_screen *vc_uniscr_alloc(unsigned int cols, unsigned int rows)
 342{
 343        struct uni_screen *uniscr;
 344        void *p;
 345        unsigned int memsize, i;
 346
 347        /* allocate everything in one go */
 348        memsize = cols * rows * sizeof(char32_t);
 349        memsize += rows * sizeof(char32_t *);
 350        p = kmalloc(memsize, GFP_KERNEL);
 351        if (!p)
 352                return NULL;
 353
 354        /* initial line pointers */
 355        uniscr = p;
 356        p = uniscr->lines + rows;
 357        for (i = 0; i < rows; i++) {
 358                uniscr->lines[i] = p;
 359                p += cols * sizeof(char32_t);
 360        }
 361        return uniscr;
 362}
 363
 364static void vc_uniscr_set(struct vc_data *vc, struct uni_screen *new_uniscr)
 365{
 366        kfree(vc->vc_uni_screen);
 367        vc->vc_uni_screen = new_uniscr;
 368}
 369
 370static void vc_uniscr_putc(struct vc_data *vc, char32_t uc)
 371{
 372        struct uni_screen *uniscr = get_vc_uniscr(vc);
 373
 374        if (uniscr)
 375                uniscr->lines[vc->vc_y][vc->vc_x] = uc;
 376}
 377
 378static void vc_uniscr_insert(struct vc_data *vc, unsigned int nr)
 379{
 380        struct uni_screen *uniscr = get_vc_uniscr(vc);
 381
 382        if (uniscr) {
 383                char32_t *ln = uniscr->lines[vc->vc_y];
 384                unsigned int x = vc->vc_x, cols = vc->vc_cols;
 385
 386                memmove(&ln[x + nr], &ln[x], (cols - x - nr) * sizeof(*ln));
 387                memset32(&ln[x], ' ', nr);
 388        }
 389}
 390
 391static void vc_uniscr_delete(struct vc_data *vc, unsigned int nr)
 392{
 393        struct uni_screen *uniscr = get_vc_uniscr(vc);
 394
 395        if (uniscr) {
 396                char32_t *ln = uniscr->lines[vc->vc_y];
 397                unsigned int x = vc->vc_x, cols = vc->vc_cols;
 398
 399                memcpy(&ln[x], &ln[x + nr], (cols - x - nr) * sizeof(*ln));
 400                memset32(&ln[cols - nr], ' ', nr);
 401        }
 402}
 403
 404static void vc_uniscr_clear_line(struct vc_data *vc, unsigned int x,
 405                                 unsigned int nr)
 406{
 407        struct uni_screen *uniscr = get_vc_uniscr(vc);
 408
 409        if (uniscr) {
 410                char32_t *ln = uniscr->lines[vc->vc_y];
 411
 412                memset32(&ln[x], ' ', nr);
 413        }
 414}
 415
 416static void vc_uniscr_clear_lines(struct vc_data *vc, unsigned int y,
 417                                  unsigned int nr)
 418{
 419        struct uni_screen *uniscr = get_vc_uniscr(vc);
 420
 421        if (uniscr) {
 422                unsigned int cols = vc->vc_cols;
 423
 424                while (nr--)
 425                        memset32(uniscr->lines[y++], ' ', cols);
 426        }
 427}
 428
 429static void vc_uniscr_scroll(struct vc_data *vc, unsigned int t, unsigned int b,
 430                             enum con_scroll dir, unsigned int nr)
 431{
 432        struct uni_screen *uniscr = get_vc_uniscr(vc);
 433
 434        if (uniscr) {
 435                unsigned int s, d, rescue, clear;
 436                char32_t *save[nr];
 437
 438                s = clear = t;
 439                d = t + nr;
 440                rescue = b - nr;
 441                if (dir == SM_UP) {
 442                        swap(s, d);
 443                        swap(clear, rescue);
 444                }
 445                memcpy(save, uniscr->lines + rescue, nr * sizeof(*save));
 446                memmove(uniscr->lines + d, uniscr->lines + s,
 447                        (b - t - nr) * sizeof(*uniscr->lines));
 448                memcpy(uniscr->lines + clear, save, nr * sizeof(*save));
 449                vc_uniscr_clear_lines(vc, clear, nr);
 450        }
 451}
 452
 453static void vc_uniscr_copy_area(struct uni_screen *dst,
 454                                unsigned int dst_cols,
 455                                unsigned int dst_rows,
 456                                struct uni_screen *src,
 457                                unsigned int src_cols,
 458                                unsigned int src_top_row,
 459                                unsigned int src_bot_row)
 460{
 461        unsigned int dst_row = 0;
 462
 463        if (!dst)
 464                return;
 465
 466        while (src_top_row < src_bot_row) {
 467                char32_t *src_line = src->lines[src_top_row];
 468                char32_t *dst_line = dst->lines[dst_row];
 469
 470                memcpy(dst_line, src_line, src_cols * sizeof(char32_t));
 471                if (dst_cols - src_cols)
 472                        memset32(dst_line + src_cols, ' ', dst_cols - src_cols);
 473                src_top_row++;
 474                dst_row++;
 475        }
 476        while (dst_row < dst_rows) {
 477                char32_t *dst_line = dst->lines[dst_row];
 478
 479                memset32(dst_line, ' ', dst_cols);
 480                dst_row++;
 481        }
 482}
 483
 484
 485static void con_scroll(struct vc_data *vc, unsigned int t, unsigned int b,
 486                enum con_scroll dir, unsigned int nr)
 487{
 488        u16 *clear, *d, *s;
 489
 490        if (t + nr >= b)
 491                nr = b - t - 1;
 492        if (b > vc->vc_rows || t >= b || nr < 1)
 493                return;
 494        vc_uniscr_scroll(vc, t, b, dir, nr);
 495        if (con_is_visible(vc) && vc->vc_sw->con_scroll(vc, t, b, dir, nr))
 496                return;
 497
 498        s = clear = (u16 *)(vc->vc_origin + vc->vc_size_row * t);
 499        d = (u16 *)(vc->vc_origin + vc->vc_size_row * (t + nr));
 500
 501        if (dir == SM_UP) {
 502                clear = s + (b - t - nr) * vc->vc_cols;
 503                swap(s, d);
 504        }
 505        scr_memmovew(d, s, (b - t - nr) * vc->vc_size_row);
 506        scr_memsetw(clear, vc->vc_video_erase_char, vc->vc_size_row * nr);
 507}
 508
 509static void do_update_region(struct vc_data *vc, unsigned long start, int count)
 510{
 511        unsigned int xx, yy, offset;
 512        u16 *p;
 513
 514        p = (u16 *) start;
 515        if (!vc->vc_sw->con_getxy) {
 516                offset = (start - vc->vc_origin) / 2;
 517                xx = offset % vc->vc_cols;
 518                yy = offset / vc->vc_cols;
 519        } else {
 520                int nxx, nyy;
 521                start = vc->vc_sw->con_getxy(vc, start, &nxx, &nyy);
 522                xx = nxx; yy = nyy;
 523        }
 524        for(;;) {
 525                u16 attrib = scr_readw(p) & 0xff00;
 526                int startx = xx;
 527                u16 *q = p;
 528                while (xx < vc->vc_cols && count) {
 529                        if (attrib != (scr_readw(p) & 0xff00)) {
 530                                if (p > q)
 531                                        vc->vc_sw->con_putcs(vc, q, p-q, yy, startx);
 532                                startx = xx;
 533                                q = p;
 534                                attrib = scr_readw(p) & 0xff00;
 535                        }
 536                        p++;
 537                        xx++;
 538                        count--;
 539                }
 540                if (p > q)
 541                        vc->vc_sw->con_putcs(vc, q, p-q, yy, startx);
 542                if (!count)
 543                        break;
 544                xx = 0;
 545                yy++;
 546                if (vc->vc_sw->con_getxy) {
 547                        p = (u16 *)start;
 548                        start = vc->vc_sw->con_getxy(vc, start, NULL, NULL);
 549                }
 550        }
 551}
 552
 553void update_region(struct vc_data *vc, unsigned long start, int count)
 554{
 555        WARN_CONSOLE_UNLOCKED();
 556
 557        if (con_should_update(vc)) {
 558                hide_cursor(vc);
 559                do_update_region(vc, start, count);
 560                set_cursor(vc);
 561        }
 562}
 563
 564/* Structure of attributes is hardware-dependent */
 565
 566static u8 build_attr(struct vc_data *vc, u8 _color, u8 _intensity, u8 _blink,
 567    u8 _underline, u8 _reverse, u8 _italic)
 568{
 569        if (vc->vc_sw->con_build_attr)
 570                return vc->vc_sw->con_build_attr(vc, _color, _intensity,
 571                       _blink, _underline, _reverse, _italic);
 572
 573/*
 574 * ++roman: I completely changed the attribute format for monochrome
 575 * mode (!can_do_color). The formerly used MDA (monochrome display
 576 * adapter) format didn't allow the combination of certain effects.
 577 * Now the attribute is just a bit vector:
 578 *  Bit 0..1: intensity (0..2)
 579 *  Bit 2   : underline
 580 *  Bit 3   : reverse
 581 *  Bit 7   : blink
 582 */
 583        {
 584        u8 a = _color;
 585        if (!vc->vc_can_do_color)
 586                return _intensity |
 587                       (_italic ? 2 : 0) |
 588                       (_underline ? 4 : 0) |
 589                       (_reverse ? 8 : 0) |
 590                       (_blink ? 0x80 : 0);
 591        if (_italic)
 592                a = (a & 0xF0) | vc->vc_itcolor;
 593        else if (_underline)
 594                a = (a & 0xf0) | vc->vc_ulcolor;
 595        else if (_intensity == 0)
 596                a = (a & 0xf0) | vc->vc_halfcolor;
 597        if (_reverse)
 598                a = ((a) & 0x88) | ((((a) >> 4) | ((a) << 4)) & 0x77);
 599        if (_blink)
 600                a ^= 0x80;
 601        if (_intensity == 2)
 602                a ^= 0x08;
 603        if (vc->vc_hi_font_mask == 0x100)
 604                a <<= 1;
 605        return a;
 606        }
 607}
 608
 609static void update_attr(struct vc_data *vc)
 610{
 611        vc->vc_attr = build_attr(vc, vc->vc_color, vc->vc_intensity,
 612                      vc->vc_blink, vc->vc_underline,
 613                      vc->vc_reverse ^ vc->vc_decscnm, vc->vc_italic);
 614        vc->vc_video_erase_char = (build_attr(vc, vc->vc_color, 1, vc->vc_blink, 0, vc->vc_decscnm, 0) << 8) | ' ';
 615}
 616
 617/* Note: inverting the screen twice should revert to the original state */
 618void invert_screen(struct vc_data *vc, int offset, int count, int viewed)
 619{
 620        unsigned short *p;
 621
 622        WARN_CONSOLE_UNLOCKED();
 623
 624        count /= 2;
 625        p = screenpos(vc, offset, viewed);
 626        if (vc->vc_sw->con_invert_region) {
 627                vc->vc_sw->con_invert_region(vc, p, count);
 628        } else {
 629                u16 *q = p;
 630                int cnt = count;
 631                u16 a;
 632
 633                if (!vc->vc_can_do_color) {
 634                        while (cnt--) {
 635                            a = scr_readw(q);
 636                            a ^= 0x0800;
 637                            scr_writew(a, q);
 638                            q++;
 639                        }
 640                } else if (vc->vc_hi_font_mask == 0x100) {
 641                        while (cnt--) {
 642                                a = scr_readw(q);
 643                                a = ((a) & 0x11ff) | (((a) & 0xe000) >> 4) | (((a) & 0x0e00) << 4);
 644                                scr_writew(a, q);
 645                                q++;
 646                        }
 647                } else {
 648                        while (cnt--) {
 649                                a = scr_readw(q);
 650                                a = ((a) & 0x88ff) | (((a) & 0x7000) >> 4) | (((a) & 0x0700) << 4);
 651                                scr_writew(a, q);
 652                                q++;
 653                        }
 654                }
 655        }
 656
 657        if (con_should_update(vc))
 658                do_update_region(vc, (unsigned long) p, count);
 659        notify_update(vc);
 660}
 661
 662/* used by selection: complement pointer position */
 663void complement_pos(struct vc_data *vc, int offset)
 664{
 665        static int old_offset = -1;
 666        static unsigned short old;
 667        static unsigned short oldx, oldy;
 668
 669        WARN_CONSOLE_UNLOCKED();
 670
 671        if (old_offset != -1 && old_offset >= 0 &&
 672            old_offset < vc->vc_screenbuf_size) {
 673                scr_writew(old, screenpos(vc, old_offset, 1));
 674                if (con_should_update(vc))
 675                        vc->vc_sw->con_putc(vc, old, oldy, oldx);
 676                notify_update(vc);
 677        }
 678
 679        old_offset = offset;
 680
 681        if (offset != -1 && offset >= 0 &&
 682            offset < vc->vc_screenbuf_size) {
 683                unsigned short new;
 684                unsigned short *p;
 685                p = screenpos(vc, offset, 1);
 686                old = scr_readw(p);
 687                new = old ^ vc->vc_complement_mask;
 688                scr_writew(new, p);
 689                if (con_should_update(vc)) {
 690                        oldx = (offset >> 1) % vc->vc_cols;
 691                        oldy = (offset >> 1) / vc->vc_cols;
 692                        vc->vc_sw->con_putc(vc, new, oldy, oldx);
 693                }
 694                notify_update(vc);
 695        }
 696}
 697
 698static void insert_char(struct vc_data *vc, unsigned int nr)
 699{
 700        unsigned short *p = (unsigned short *) vc->vc_pos;
 701
 702        vc_uniscr_insert(vc, nr);
 703        scr_memmovew(p + nr, p, (vc->vc_cols - vc->vc_x - nr) * 2);
 704        scr_memsetw(p, vc->vc_video_erase_char, nr * 2);
 705        vc->vc_need_wrap = 0;
 706        if (con_should_update(vc))
 707                do_update_region(vc, (unsigned long) p,
 708                        vc->vc_cols - vc->vc_x);
 709}
 710
 711static void delete_char(struct vc_data *vc, unsigned int nr)
 712{
 713        unsigned short *p = (unsigned short *) vc->vc_pos;
 714
 715        vc_uniscr_delete(vc, nr);
 716        scr_memcpyw(p, p + nr, (vc->vc_cols - vc->vc_x - nr) * 2);
 717        scr_memsetw(p + vc->vc_cols - vc->vc_x - nr, vc->vc_video_erase_char,
 718                        nr * 2);
 719        vc->vc_need_wrap = 0;
 720        if (con_should_update(vc))
 721                do_update_region(vc, (unsigned long) p,
 722                        vc->vc_cols - vc->vc_x);
 723}
 724
 725static int softcursor_original = -1;
 726
 727static void add_softcursor(struct vc_data *vc)
 728{
 729        int i = scr_readw((u16 *) vc->vc_pos);
 730        u32 type = vc->vc_cursor_type;
 731
 732        if (! (type & 0x10)) return;
 733        if (softcursor_original != -1) return;
 734        softcursor_original = i;
 735        i |= ((type >> 8) & 0xff00 );
 736        i ^= ((type) & 0xff00 );
 737        if ((type & 0x20) && ((softcursor_original & 0x7000) == (i & 0x7000))) i ^= 0x7000;
 738        if ((type & 0x40) && ((i & 0x700) == ((i & 0x7000) >> 4))) i ^= 0x0700;
 739        scr_writew(i, (u16 *) vc->vc_pos);
 740        if (con_should_update(vc))
 741                vc->vc_sw->con_putc(vc, i, vc->vc_y, vc->vc_x);
 742}
 743
 744static void hide_softcursor(struct vc_data *vc)
 745{
 746        if (softcursor_original != -1) {
 747                scr_writew(softcursor_original, (u16 *)vc->vc_pos);
 748                if (con_should_update(vc))
 749                        vc->vc_sw->con_putc(vc, softcursor_original,
 750                                        vc->vc_y, vc->vc_x);
 751                softcursor_original = -1;
 752        }
 753}
 754
 755static void hide_cursor(struct vc_data *vc)
 756{
 757        if (vc_is_sel(vc))
 758                clear_selection();
 759
 760        vc->vc_sw->con_cursor(vc, CM_ERASE);
 761        hide_softcursor(vc);
 762}
 763
 764static void set_cursor(struct vc_data *vc)
 765{
 766        if (!con_is_fg(vc) || console_blanked || vc->vc_mode == KD_GRAPHICS)
 767                return;
 768        if (vc->vc_deccm) {
 769                if (vc_is_sel(vc))
 770                        clear_selection();
 771                add_softcursor(vc);
 772                if ((vc->vc_cursor_type & 0x0f) != 1)
 773                        vc->vc_sw->con_cursor(vc, CM_DRAW);
 774        } else
 775                hide_cursor(vc);
 776}
 777
 778static void set_origin(struct vc_data *vc)
 779{
 780        WARN_CONSOLE_UNLOCKED();
 781
 782        if (!con_is_visible(vc) ||
 783            !vc->vc_sw->con_set_origin ||
 784            !vc->vc_sw->con_set_origin(vc))
 785                vc->vc_origin = (unsigned long)vc->vc_screenbuf;
 786        vc->vc_visible_origin = vc->vc_origin;
 787        vc->vc_scr_end = vc->vc_origin + vc->vc_screenbuf_size;
 788        vc->vc_pos = vc->vc_origin + vc->vc_size_row * vc->vc_y + 2 * vc->vc_x;
 789}
 790
 791static void save_screen(struct vc_data *vc)
 792{
 793        WARN_CONSOLE_UNLOCKED();
 794
 795        if (vc->vc_sw->con_save_screen)
 796                vc->vc_sw->con_save_screen(vc);
 797}
 798
 799static void flush_scrollback(struct vc_data *vc)
 800{
 801        WARN_CONSOLE_UNLOCKED();
 802
 803        if (vc->vc_sw->con_flush_scrollback)
 804                vc->vc_sw->con_flush_scrollback(vc);
 805}
 806
 807/*
 808 *      Redrawing of screen
 809 */
 810
 811void clear_buffer_attributes(struct vc_data *vc)
 812{
 813        unsigned short *p = (unsigned short *)vc->vc_origin;
 814        int count = vc->vc_screenbuf_size / 2;
 815        int mask = vc->vc_hi_font_mask | 0xff;
 816
 817        for (; count > 0; count--, p++) {
 818                scr_writew((scr_readw(p)&mask) | (vc->vc_video_erase_char & ~mask), p);
 819        }
 820}
 821
 822void redraw_screen(struct vc_data *vc, int is_switch)
 823{
 824        int redraw = 0;
 825
 826        WARN_CONSOLE_UNLOCKED();
 827
 828        if (!vc) {
 829                /* strange ... */
 830                /* printk("redraw_screen: tty %d not allocated ??\n", new_console+1); */
 831                return;
 832        }
 833
 834        if (is_switch) {
 835                struct vc_data *old_vc = vc_cons[fg_console].d;
 836                if (old_vc == vc)
 837                        return;
 838                if (!con_is_visible(vc))
 839                        redraw = 1;
 840                *vc->vc_display_fg = vc;
 841                fg_console = vc->vc_num;
 842                hide_cursor(old_vc);
 843                if (!con_is_visible(old_vc)) {
 844                        save_screen(old_vc);
 845                        set_origin(old_vc);
 846                }
 847                if (tty0dev)
 848                        sysfs_notify(&tty0dev->kobj, NULL, "active");
 849        } else {
 850                hide_cursor(vc);
 851                redraw = 1;
 852        }
 853
 854        if (redraw) {
 855                int update;
 856                int old_was_color = vc->vc_can_do_color;
 857
 858                set_origin(vc);
 859                update = vc->vc_sw->con_switch(vc);
 860                set_palette(vc);
 861                /*
 862                 * If console changed from mono<->color, the best we can do
 863                 * is to clear the buffer attributes. As it currently stands,
 864                 * rebuilding new attributes from the old buffer is not doable
 865                 * without overly complex code.
 866                 */
 867                if (old_was_color != vc->vc_can_do_color) {
 868                        update_attr(vc);
 869                        clear_buffer_attributes(vc);
 870                }
 871
 872                if (update && vc->vc_mode != KD_GRAPHICS)
 873                        do_update_region(vc, vc->vc_origin, vc->vc_screenbuf_size / 2);
 874        }
 875        set_cursor(vc);
 876        if (is_switch) {
 877                set_leds();
 878                compute_shiftstate();
 879                notify_update(vc);
 880        }
 881}
 882
 883/*
 884 *      Allocation, freeing and resizing of VTs.
 885 */
 886
 887int vc_cons_allocated(unsigned int i)
 888{
 889        return (i < MAX_NR_CONSOLES && vc_cons[i].d);
 890}
 891
 892static void visual_init(struct vc_data *vc, int num, int init)
 893{
 894        /* ++Geert: vc->vc_sw->con_init determines console size */
 895        if (vc->vc_sw)
 896                module_put(vc->vc_sw->owner);
 897        vc->vc_sw = conswitchp;
 898#ifndef VT_SINGLE_DRIVER
 899        if (con_driver_map[num])
 900                vc->vc_sw = con_driver_map[num];
 901#endif
 902        __module_get(vc->vc_sw->owner);
 903        vc->vc_num = num;
 904        vc->vc_display_fg = &master_display_fg;
 905        if (vc->vc_uni_pagedir_loc)
 906                con_free_unimap(vc);
 907        vc->vc_uni_pagedir_loc = &vc->vc_uni_pagedir;
 908        vc->vc_uni_pagedir = NULL;
 909        vc->vc_hi_font_mask = 0;
 910        vc->vc_complement_mask = 0;
 911        vc->vc_can_do_color = 0;
 912        vc->vc_cur_blink_ms = DEFAULT_CURSOR_BLINK_MS;
 913        vc->vc_sw->con_init(vc, init);
 914        if (!vc->vc_complement_mask)
 915                vc->vc_complement_mask = vc->vc_can_do_color ? 0x7700 : 0x0800;
 916        vc->vc_s_complement_mask = vc->vc_complement_mask;
 917        vc->vc_size_row = vc->vc_cols << 1;
 918        vc->vc_screenbuf_size = vc->vc_rows * vc->vc_size_row;
 919}
 920
 921
 922static void visual_deinit(struct vc_data *vc)
 923{
 924        vc->vc_sw->con_deinit(vc);
 925        module_put(vc->vc_sw->owner);
 926}
 927
 928static void vc_port_destruct(struct tty_port *port)
 929{
 930        struct vc_data *vc = container_of(port, struct vc_data, port);
 931
 932        kfree(vc);
 933}
 934
 935static const struct tty_port_operations vc_port_ops = {
 936        .destruct = vc_port_destruct,
 937};
 938
 939int vc_allocate(unsigned int currcons)  /* return 0 on success */
 940{
 941        struct vt_notifier_param param;
 942        struct vc_data *vc;
 943
 944        WARN_CONSOLE_UNLOCKED();
 945
 946        if (currcons >= MAX_NR_CONSOLES)
 947                return -ENXIO;
 948
 949        if (vc_cons[currcons].d)
 950                return 0;
 951
 952        /* due to the granularity of kmalloc, we waste some memory here */
 953        /* the alloc is done in two steps, to optimize the common situation
 954           of a 25x80 console (structsize=216, screenbuf_size=4000) */
 955        /* although the numbers above are not valid since long ago, the
 956           point is still up-to-date and the comment still has its value
 957           even if only as a historical artifact.  --mj, July 1998 */
 958        param.vc = vc = kzalloc(sizeof(struct vc_data), GFP_KERNEL);
 959        if (!vc)
 960                return -ENOMEM;
 961
 962        vc_cons[currcons].d = vc;
 963        tty_port_init(&vc->port);
 964        vc->port.ops = &vc_port_ops;
 965        INIT_WORK(&vc_cons[currcons].SAK_work, vc_SAK);
 966
 967        visual_init(vc, currcons, 1);
 968
 969        if (!*vc->vc_uni_pagedir_loc)
 970                con_set_default_unimap(vc);
 971
 972        vc->vc_screenbuf = kzalloc(vc->vc_screenbuf_size, GFP_KERNEL);
 973        if (!vc->vc_screenbuf)
 974                goto err_free;
 975
 976        /* If no drivers have overridden us and the user didn't pass a
 977           boot option, default to displaying the cursor */
 978        if (global_cursor_default == -1)
 979                global_cursor_default = 1;
 980
 981        vc_init(vc, vc->vc_rows, vc->vc_cols, 1);
 982        vcs_make_sysfs(currcons);
 983        atomic_notifier_call_chain(&vt_notifier_list, VT_ALLOCATE, &param);
 984
 985        return 0;
 986err_free:
 987        visual_deinit(vc);
 988        kfree(vc);
 989        vc_cons[currcons].d = NULL;
 990        return -ENOMEM;
 991}
 992
 993static inline int resize_screen(struct vc_data *vc, int width, int height,
 994                                int user)
 995{
 996        /* Resizes the resolution of the display adapater */
 997        int err = 0;
 998
 999        if (vc->vc_sw->con_resize)
1000                err = vc->vc_sw->con_resize(vc, width, height, user);
1001
1002        return err;
1003}
1004
1005/*
1006 * Change # of rows and columns (0 means unchanged/the size of fg_console)
1007 * [this is to be used together with some user program
1008 * like resize that changes the hardware videomode]
1009 */
1010#define VC_RESIZE_MAXCOL (32767)
1011#define VC_RESIZE_MAXROW (32767)
1012
1013/**
1014 *      vc_do_resize    -       resizing method for the tty
1015 *      @tty: tty being resized
1016 *      @real_tty: real tty (different to tty if a pty/tty pair)
1017 *      @vc: virtual console private data
1018 *      @cols: columns
1019 *      @lines: lines
1020 *
1021 *      Resize a virtual console, clipping according to the actual constraints.
1022 *      If the caller passes a tty structure then update the termios winsize
1023 *      information and perform any necessary signal handling.
1024 *
1025 *      Caller must hold the console semaphore. Takes the termios rwsem and
1026 *      ctrl_lock of the tty IFF a tty is passed.
1027 */
1028
1029static int vc_do_resize(struct tty_struct *tty, struct vc_data *vc,
1030                                unsigned int cols, unsigned int lines)
1031{
1032        unsigned long old_origin, new_origin, new_scr_end, rlth, rrem, err = 0;
1033        unsigned long end;
1034        unsigned int old_rows, old_row_size, first_copied_row;
1035        unsigned int new_cols, new_rows, new_row_size, new_screen_size;
1036        unsigned int user;
1037        unsigned short *newscreen;
1038        struct uni_screen *new_uniscr = NULL;
1039
1040        WARN_CONSOLE_UNLOCKED();
1041
1042        if (!vc)
1043                return -ENXIO;
1044
1045        user = vc->vc_resize_user;
1046        vc->vc_resize_user = 0;
1047
1048        if (cols > VC_RESIZE_MAXCOL || lines > VC_RESIZE_MAXROW)
1049                return -EINVAL;
1050
1051        new_cols = (cols ? cols : vc->vc_cols);
1052        new_rows = (lines ? lines : vc->vc_rows);
1053        new_row_size = new_cols << 1;
1054        new_screen_size = new_row_size * new_rows;
1055
1056        if (new_cols == vc->vc_cols && new_rows == vc->vc_rows)
1057                return 0;
1058
1059        if (new_screen_size > (4 << 20))
1060                return -EINVAL;
1061        newscreen = kzalloc(new_screen_size, GFP_USER);
1062        if (!newscreen)
1063                return -ENOMEM;
1064
1065        if (get_vc_uniscr(vc)) {
1066                new_uniscr = vc_uniscr_alloc(new_cols, new_rows);
1067                if (!new_uniscr) {
1068                        kfree(newscreen);
1069                        return -ENOMEM;
1070                }
1071        }
1072
1073        if (vc_is_sel(vc))
1074                clear_selection();
1075
1076        old_rows = vc->vc_rows;
1077        old_row_size = vc->vc_size_row;
1078
1079        err = resize_screen(vc, new_cols, new_rows, user);
1080        if (err) {
1081                kfree(newscreen);
1082                kfree(new_uniscr);
1083                return err;
1084        }
1085
1086        vc->vc_rows = new_rows;
1087        vc->vc_cols = new_cols;
1088        vc->vc_size_row = new_row_size;
1089        vc->vc_screenbuf_size = new_screen_size;
1090
1091        rlth = min(old_row_size, new_row_size);
1092        rrem = new_row_size - rlth;
1093        old_origin = vc->vc_origin;
1094        new_origin = (long) newscreen;
1095        new_scr_end = new_origin + new_screen_size;
1096
1097        if (vc->vc_y > new_rows) {
1098                if (old_rows - vc->vc_y < new_rows) {
1099                        /*
1100                         * Cursor near the bottom, copy contents from the
1101                         * bottom of buffer
1102                         */
1103                        first_copied_row = (old_rows - new_rows);
1104                } else {
1105                        /*
1106                         * Cursor is in no man's land, copy 1/2 screenful
1107                         * from the top and bottom of cursor position
1108                         */
1109                        first_copied_row = (vc->vc_y - new_rows/2);
1110                }
1111                old_origin += first_copied_row * old_row_size;
1112        } else
1113                first_copied_row = 0;
1114        end = old_origin + old_row_size * min(old_rows, new_rows);
1115
1116        vc_uniscr_copy_area(new_uniscr, new_cols, new_rows,
1117                            get_vc_uniscr(vc), rlth/2, first_copied_row,
1118                            min(old_rows, new_rows));
1119        vc_uniscr_set(vc, new_uniscr);
1120
1121        update_attr(vc);
1122
1123        while (old_origin < end) {
1124                scr_memcpyw((unsigned short *) new_origin,
1125                            (unsigned short *) old_origin, rlth);
1126                if (rrem)
1127                        scr_memsetw((void *)(new_origin + rlth),
1128                                    vc->vc_video_erase_char, rrem);
1129                old_origin += old_row_size;
1130                new_origin += new_row_size;
1131        }
1132        if (new_scr_end > new_origin)
1133                scr_memsetw((void *)new_origin, vc->vc_video_erase_char,
1134                            new_scr_end - new_origin);
1135        kfree(vc->vc_screenbuf);
1136        vc->vc_screenbuf = newscreen;
1137        vc->vc_screenbuf_size = new_screen_size;
1138        set_origin(vc);
1139
1140        /* do part of a reset_terminal() */
1141        vc->vc_top = 0;
1142        vc->vc_bottom = vc->vc_rows;
1143        gotoxy(vc, vc->vc_x, vc->vc_y);
1144        save_cur(vc);
1145
1146        if (tty) {
1147                /* Rewrite the requested winsize data with the actual
1148                   resulting sizes */
1149                struct winsize ws;
1150                memset(&ws, 0, sizeof(ws));
1151                ws.ws_row = vc->vc_rows;
1152                ws.ws_col = vc->vc_cols;
1153                ws.ws_ypixel = vc->vc_scan_lines;
1154                tty_do_resize(tty, &ws);
1155        }
1156
1157        if (con_is_visible(vc))
1158                update_screen(vc);
1159        vt_event_post(VT_EVENT_RESIZE, vc->vc_num, vc->vc_num);
1160        return err;
1161}
1162
1163/**
1164 *      vc_resize               -       resize a VT
1165 *      @vc: virtual console
1166 *      @cols: columns
1167 *      @rows: rows
1168 *
1169 *      Resize a virtual console as seen from the console end of things. We
1170 *      use the common vc_do_resize methods to update the structures. The
1171 *      caller must hold the console sem to protect console internals and
1172 *      vc->port.tty
1173 */
1174
1175int vc_resize(struct vc_data *vc, unsigned int cols, unsigned int rows)
1176{
1177        return vc_do_resize(vc->port.tty, vc, cols, rows);
1178}
1179
1180/**
1181 *      vt_resize               -       resize a VT
1182 *      @tty: tty to resize
1183 *      @ws: winsize attributes
1184 *
1185 *      Resize a virtual terminal. This is called by the tty layer as we
1186 *      register our own handler for resizing. The mutual helper does all
1187 *      the actual work.
1188 *
1189 *      Takes the console sem and the called methods then take the tty
1190 *      termios_rwsem and the tty ctrl_lock in that order.
1191 */
1192static int vt_resize(struct tty_struct *tty, struct winsize *ws)
1193{
1194        struct vc_data *vc = tty->driver_data;
1195        int ret;
1196
1197        console_lock();
1198        ret = vc_do_resize(tty, vc, ws->ws_col, ws->ws_row);
1199        console_unlock();
1200        return ret;
1201}
1202
1203struct vc_data *vc_deallocate(unsigned int currcons)
1204{
1205        struct vc_data *vc = NULL;
1206
1207        WARN_CONSOLE_UNLOCKED();
1208
1209        if (vc_cons_allocated(currcons)) {
1210                struct vt_notifier_param param;
1211
1212                param.vc = vc = vc_cons[currcons].d;
1213                atomic_notifier_call_chain(&vt_notifier_list, VT_DEALLOCATE, &param);
1214                vcs_remove_sysfs(currcons);
1215                visual_deinit(vc);
1216                put_pid(vc->vt_pid);
1217                vc_uniscr_set(vc, NULL);
1218                kfree(vc->vc_screenbuf);
1219                vc_cons[currcons].d = NULL;
1220        }
1221        return vc;
1222}
1223
1224/*
1225 *      VT102 emulator
1226 */
1227
1228#define set_kbd(vc, x)  vt_set_kbd_mode_bit((vc)->vc_num, (x))
1229#define clr_kbd(vc, x)  vt_clr_kbd_mode_bit((vc)->vc_num, (x))
1230#define is_kbd(vc, x)   vt_get_kbd_mode_bit((vc)->vc_num, (x))
1231
1232#define decarm          VC_REPEAT
1233#define decckm          VC_CKMODE
1234#define kbdapplic       VC_APPLIC
1235#define lnm             VC_CRLF
1236
1237/*
1238 * this is what the terminal answers to a ESC-Z or csi0c query.
1239 */
1240#define VT100ID "\033[?1;2c"
1241#define VT102ID "\033[?6c"
1242
1243const unsigned char color_table[] = { 0, 4, 2, 6, 1, 5, 3, 7,
1244                                       8,12,10,14, 9,13,11,15 };
1245
1246/* the default colour table, for VGA+ colour systems */
1247unsigned char default_red[] = {
1248        0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa,
1249        0x55, 0xff, 0x55, 0xff, 0x55, 0xff, 0x55, 0xff
1250};
1251module_param_array(default_red, byte, NULL, S_IRUGO | S_IWUSR);
1252
1253unsigned char default_grn[] = {
1254        0x00, 0x00, 0xaa, 0x55, 0x00, 0x00, 0xaa, 0xaa,
1255        0x55, 0x55, 0xff, 0xff, 0x55, 0x55, 0xff, 0xff
1256};
1257module_param_array(default_grn, byte, NULL, S_IRUGO | S_IWUSR);
1258
1259unsigned char default_blu[] = {
1260        0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa,
1261        0x55, 0x55, 0x55, 0x55, 0xff, 0xff, 0xff, 0xff
1262};
1263module_param_array(default_blu, byte, NULL, S_IRUGO | S_IWUSR);
1264
1265/*
1266 * gotoxy() must verify all boundaries, because the arguments
1267 * might also be negative. If the given position is out of
1268 * bounds, the cursor is placed at the nearest margin.
1269 */
1270static void gotoxy(struct vc_data *vc, int new_x, int new_y)
1271{
1272        int min_y, max_y;
1273
1274        if (new_x < 0)
1275                vc->vc_x = 0;
1276        else {
1277                if (new_x >= vc->vc_cols)
1278                        vc->vc_x = vc->vc_cols - 1;
1279                else
1280                        vc->vc_x = new_x;
1281        }
1282
1283        if (vc->vc_decom) {
1284                min_y = vc->vc_top;
1285                max_y = vc->vc_bottom;
1286        } else {
1287                min_y = 0;
1288                max_y = vc->vc_rows;
1289        }
1290        if (new_y < min_y)
1291                vc->vc_y = min_y;
1292        else if (new_y >= max_y)
1293                vc->vc_y = max_y - 1;
1294        else
1295                vc->vc_y = new_y;
1296        vc->vc_pos = vc->vc_origin + vc->vc_y * vc->vc_size_row + (vc->vc_x<<1);
1297        vc->vc_need_wrap = 0;
1298}
1299
1300/* for absolute user moves, when decom is set */
1301static void gotoxay(struct vc_data *vc, int new_x, int new_y)
1302{
1303        gotoxy(vc, new_x, vc->vc_decom ? (vc->vc_top + new_y) : new_y);
1304}
1305
1306void scrollback(struct vc_data *vc)
1307{
1308        scrolldelta(-(vc->vc_rows / 2));
1309}
1310
1311void scrollfront(struct vc_data *vc, int lines)
1312{
1313        if (!lines)
1314                lines = vc->vc_rows / 2;
1315        scrolldelta(lines);
1316}
1317
1318static void lf(struct vc_data *vc)
1319{
1320        /* don't scroll if above bottom of scrolling region, or
1321         * if below scrolling region
1322         */
1323        if (vc->vc_y + 1 == vc->vc_bottom)
1324                con_scroll(vc, vc->vc_top, vc->vc_bottom, SM_UP, 1);
1325        else if (vc->vc_y < vc->vc_rows - 1) {
1326                vc->vc_y++;
1327                vc->vc_pos += vc->vc_size_row;
1328        }
1329        vc->vc_need_wrap = 0;
1330        notify_write(vc, '\n');
1331}
1332
1333static void ri(struct vc_data *vc)
1334{
1335        /* don't scroll if below top of scrolling region, or
1336         * if above scrolling region
1337         */
1338        if (vc->vc_y == vc->vc_top)
1339                con_scroll(vc, vc->vc_top, vc->vc_bottom, SM_DOWN, 1);
1340        else if (vc->vc_y > 0) {
1341                vc->vc_y--;
1342                vc->vc_pos -= vc->vc_size_row;
1343        }
1344        vc->vc_need_wrap = 0;
1345}
1346
1347static inline void cr(struct vc_data *vc)
1348{
1349        vc->vc_pos -= vc->vc_x << 1;
1350        vc->vc_need_wrap = vc->vc_x = 0;
1351        notify_write(vc, '\r');
1352}
1353
1354static inline void bs(struct vc_data *vc)
1355{
1356        if (vc->vc_x) {
1357                vc->vc_pos -= 2;
1358                vc->vc_x--;
1359                vc->vc_need_wrap = 0;
1360                notify_write(vc, '\b');
1361        }
1362}
1363
1364static inline void del(struct vc_data *vc)
1365{
1366        /* ignored */
1367}
1368
1369static void csi_J(struct vc_data *vc, int vpar)
1370{
1371        unsigned int count;
1372        unsigned short * start;
1373
1374        switch (vpar) {
1375                case 0: /* erase from cursor to end of display */
1376                        vc_uniscr_clear_line(vc, vc->vc_x,
1377                                             vc->vc_cols - vc->vc_x);
1378                        vc_uniscr_clear_lines(vc, vc->vc_y + 1,
1379                                              vc->vc_rows - vc->vc_y - 1);
1380                        count = (vc->vc_scr_end - vc->vc_pos) >> 1;
1381                        start = (unsigned short *)vc->vc_pos;
1382                        break;
1383                case 1: /* erase from start to cursor */
1384                        vc_uniscr_clear_line(vc, 0, vc->vc_x + 1);
1385                        vc_uniscr_clear_lines(vc, 0, vc->vc_y);
1386                        count = ((vc->vc_pos - vc->vc_origin) >> 1) + 1;
1387                        start = (unsigned short *)vc->vc_origin;
1388                        break;
1389                case 2: /* erase whole display */
1390                case 3: /* (and scrollback buffer later) */
1391                        vc_uniscr_clear_lines(vc, 0, vc->vc_rows);
1392                        count = vc->vc_cols * vc->vc_rows;
1393                        start = (unsigned short *)vc->vc_origin;
1394                        break;
1395                default:
1396                        return;
1397        }
1398        scr_memsetw(start, vc->vc_video_erase_char, 2 * count);
1399        if (vpar == 3) {
1400                set_origin(vc);
1401                flush_scrollback(vc);
1402                if (con_is_visible(vc))
1403                        update_screen(vc);
1404        } else if (con_should_update(vc))
1405                do_update_region(vc, (unsigned long) start, count);
1406        vc->vc_need_wrap = 0;
1407}
1408
1409static void csi_K(struct vc_data *vc, int vpar)
1410{
1411        unsigned int count;
1412        unsigned short *start = (unsigned short *)vc->vc_pos;
1413        int offset;
1414
1415        switch (vpar) {
1416                case 0: /* erase from cursor to end of line */
1417                        offset = 0;
1418                        count = vc->vc_cols - vc->vc_x;
1419                        break;
1420                case 1: /* erase from start of line to cursor */
1421                        offset = -vc->vc_x;
1422                        count = vc->vc_x + 1;
1423                        break;
1424                case 2: /* erase whole line */
1425                        offset = -vc->vc_x;
1426                        count = vc->vc_cols;
1427                        break;
1428                default:
1429                        return;
1430        }
1431        vc_uniscr_clear_line(vc, vc->vc_x + offset, count);
1432        scr_memsetw(start + offset, vc->vc_video_erase_char, 2 * count);
1433        vc->vc_need_wrap = 0;
1434        if (con_should_update(vc))
1435                do_update_region(vc, (unsigned long)(start + offset), count);
1436}
1437
1438static void csi_X(struct vc_data *vc, int vpar) /* erase the following vpar positions */
1439{                                         /* not vt100? */
1440        int count;
1441
1442        if (!vpar)
1443                vpar++;
1444        count = (vpar > vc->vc_cols - vc->vc_x) ? (vc->vc_cols - vc->vc_x) : vpar;
1445
1446        vc_uniscr_clear_line(vc, vc->vc_x, count);
1447        scr_memsetw((unsigned short *)vc->vc_pos, vc->vc_video_erase_char, 2 * count);
1448        if (con_should_update(vc))
1449                vc->vc_sw->con_clear(vc, vc->vc_y, vc->vc_x, 1, count);
1450        vc->vc_need_wrap = 0;
1451}
1452
1453static void default_attr(struct vc_data *vc)
1454{
1455        vc->vc_intensity = 1;
1456        vc->vc_italic = 0;
1457        vc->vc_underline = 0;
1458        vc->vc_reverse = 0;
1459        vc->vc_blink = 0;
1460        vc->vc_color = vc->vc_def_color;
1461}
1462
1463struct rgb { u8 r; u8 g; u8 b; };
1464
1465static void rgb_from_256(int i, struct rgb *c)
1466{
1467        if (i < 8) {            /* Standard colours. */
1468                c->r = i&1 ? 0xaa : 0x00;
1469                c->g = i&2 ? 0xaa : 0x00;
1470                c->b = i&4 ? 0xaa : 0x00;
1471        } else if (i < 16) {
1472                c->r = i&1 ? 0xff : 0x55;
1473                c->g = i&2 ? 0xff : 0x55;
1474                c->b = i&4 ? 0xff : 0x55;
1475        } else if (i < 232) {   /* 6x6x6 colour cube. */
1476                c->r = (i - 16) / 36 * 85 / 2;
1477                c->g = (i - 16) / 6 % 6 * 85 / 2;
1478                c->b = (i - 16) % 6 * 85 / 2;
1479        } else                  /* Grayscale ramp. */
1480                c->r = c->g = c->b = i * 10 - 2312;
1481}
1482
1483static void rgb_foreground(struct vc_data *vc, const struct rgb *c)
1484{
1485        u8 hue = 0, max = max3(c->r, c->g, c->b);
1486
1487        if (c->r > max / 2)
1488                hue |= 4;
1489        if (c->g > max / 2)
1490                hue |= 2;
1491        if (c->b > max / 2)
1492                hue |= 1;
1493
1494        if (hue == 7 && max <= 0x55) {
1495                hue = 0;
1496                vc->vc_intensity = 2;
1497        } else if (max > 0xaa)
1498                vc->vc_intensity = 2;
1499        else
1500                vc->vc_intensity = 1;
1501
1502        vc->vc_color = (vc->vc_color & 0xf0) | hue;
1503}
1504
1505static void rgb_background(struct vc_data *vc, const struct rgb *c)
1506{
1507        /* For backgrounds, err on the dark side. */
1508        vc->vc_color = (vc->vc_color & 0x0f)
1509                | (c->r&0x80) >> 1 | (c->g&0x80) >> 2 | (c->b&0x80) >> 3;
1510}
1511
1512/*
1513 * ITU T.416 Higher colour modes. They break the usual properties of SGR codes
1514 * and thus need to be detected and ignored by hand. Strictly speaking, that
1515 * standard also wants : rather than ; as separators, contrary to ECMA-48, but
1516 * no one produces such codes and almost no one accepts them.
1517 *
1518 * Subcommands 3 (CMY) and 4 (CMYK) are so insane there's no point in
1519 * supporting them.
1520 */
1521static int vc_t416_color(struct vc_data *vc, int i,
1522                void(*set_color)(struct vc_data *vc, const struct rgb *c))
1523{
1524        struct rgb c;
1525
1526        i++;
1527        if (i > vc->vc_npar)
1528                return i;
1529
1530        if (vc->vc_par[i] == 5 && i + 1 <= vc->vc_npar) {
1531                /* 256 colours */
1532                i++;
1533                rgb_from_256(vc->vc_par[i], &c);
1534        } else if (vc->vc_par[i] == 2 && i + 3 <= vc->vc_npar) {
1535                /* 24 bit */
1536                c.r = vc->vc_par[i + 1];
1537                c.g = vc->vc_par[i + 2];
1538                c.b = vc->vc_par[i + 3];
1539                i += 3;
1540        } else
1541                return i;
1542
1543        set_color(vc, &c);
1544
1545        return i;
1546}
1547
1548/* console_lock is held */
1549static void csi_m(struct vc_data *vc)
1550{
1551        int i;
1552
1553        for (i = 0; i <= vc->vc_npar; i++)
1554                switch (vc->vc_par[i]) {
1555                case 0: /* all attributes off */
1556                        default_attr(vc);
1557                        break;
1558                case 1:
1559                        vc->vc_intensity = 2;
1560                        break;
1561                case 2:
1562                        vc->vc_intensity = 0;
1563                        break;
1564                case 3:
1565                        vc->vc_italic = 1;
1566                        break;
1567                case 21:
1568                        /*
1569                         * No console drivers support double underline, so
1570                         * convert it to a single underline.
1571                         */
1572                case 4:
1573                        vc->vc_underline = 1;
1574                        break;
1575                case 5:
1576                        vc->vc_blink = 1;
1577                        break;
1578                case 7:
1579                        vc->vc_reverse = 1;
1580                        break;
1581                case 10: /* ANSI X3.64-1979 (SCO-ish?)
1582                          * Select primary font, don't display control chars if
1583                          * defined, don't set bit 8 on output.
1584                          */
1585                        vc->vc_translate = set_translate(vc->vc_charset == 0
1586                                        ? vc->vc_G0_charset
1587                                        : vc->vc_G1_charset, vc);
1588                        vc->vc_disp_ctrl = 0;
1589                        vc->vc_toggle_meta = 0;
1590                        break;
1591                case 11: /* ANSI X3.64-1979 (SCO-ish?)
1592                          * Select first alternate font, lets chars < 32 be
1593                          * displayed as ROM chars.
1594                          */
1595                        vc->vc_translate = set_translate(IBMPC_MAP, vc);
1596                        vc->vc_disp_ctrl = 1;
1597                        vc->vc_toggle_meta = 0;
1598                        break;
1599                case 12: /* ANSI X3.64-1979 (SCO-ish?)
1600                          * Select second alternate font, toggle high bit
1601                          * before displaying as ROM char.
1602                          */
1603                        vc->vc_translate = set_translate(IBMPC_MAP, vc);
1604                        vc->vc_disp_ctrl = 1;
1605                        vc->vc_toggle_meta = 1;
1606                        break;
1607                case 22:
1608                        vc->vc_intensity = 1;
1609                        break;
1610                case 23:
1611                        vc->vc_italic = 0;
1612                        break;
1613                case 24:
1614                        vc->vc_underline = 0;
1615                        break;
1616                case 25:
1617                        vc->vc_blink = 0;
1618                        break;
1619                case 27:
1620                        vc->vc_reverse = 0;
1621                        break;
1622                case 38:
1623                        i = vc_t416_color(vc, i, rgb_foreground);
1624                        break;
1625                case 48:
1626                        i = vc_t416_color(vc, i, rgb_background);
1627                        break;
1628                case 39:
1629                        vc->vc_color = (vc->vc_def_color & 0x0f) |
1630                                (vc->vc_color & 0xf0);
1631                        break;
1632                case 49:
1633                        vc->vc_color = (vc->vc_def_color & 0xf0) |
1634                                (vc->vc_color & 0x0f);
1635                        break;
1636                default:
1637                        if (vc->vc_par[i] >= 90 && vc->vc_par[i] <= 107) {
1638                                if (vc->vc_par[i] < 100)
1639                                        vc->vc_intensity = 2;
1640                                vc->vc_par[i] -= 60;
1641                        }
1642                        if (vc->vc_par[i] >= 30 && vc->vc_par[i] <= 37)
1643                                vc->vc_color = color_table[vc->vc_par[i] - 30]
1644                                        | (vc->vc_color & 0xf0);
1645                        else if (vc->vc_par[i] >= 40 && vc->vc_par[i] <= 47)
1646                                vc->vc_color = (color_table[vc->vc_par[i] - 40] << 4)
1647                                        | (vc->vc_color & 0x0f);
1648                        break;
1649                }
1650        update_attr(vc);
1651}
1652
1653static void respond_string(const char *p, struct tty_port *port)
1654{
1655        while (*p) {
1656                tty_insert_flip_char(port, *p, 0);
1657                p++;
1658        }
1659        tty_schedule_flip(port);
1660}
1661
1662static void cursor_report(struct vc_data *vc, struct tty_struct *tty)
1663{
1664        char buf[40];
1665
1666        sprintf(buf, "\033[%d;%dR", vc->vc_y + (vc->vc_decom ? vc->vc_top + 1 : 1), vc->vc_x + 1);
1667        respond_string(buf, tty->port);
1668}
1669
1670static inline void status_report(struct tty_struct *tty)
1671{
1672        respond_string("\033[0n", tty->port);   /* Terminal ok */
1673}
1674
1675static inline void respond_ID(struct tty_struct *tty)
1676{
1677        respond_string(VT102ID, tty->port);
1678}
1679
1680void mouse_report(struct tty_struct *tty, int butt, int mrx, int mry)
1681{
1682        char buf[8];
1683
1684        sprintf(buf, "\033[M%c%c%c", (char)(' ' + butt), (char)('!' + mrx),
1685                (char)('!' + mry));
1686        respond_string(buf, tty->port);
1687}
1688
1689/* invoked via ioctl(TIOCLINUX) and through set_selection_user */
1690int mouse_reporting(void)
1691{
1692        return vc_cons[fg_console].d->vc_report_mouse;
1693}
1694
1695/* console_lock is held */
1696static void set_mode(struct vc_data *vc, int on_off)
1697{
1698        int i;
1699
1700        for (i = 0; i <= vc->vc_npar; i++)
1701                if (vc->vc_ques) {
1702                        switch(vc->vc_par[i]) { /* DEC private modes set/reset */
1703                        case 1:                 /* Cursor keys send ^[Ox/^[[x */
1704                                if (on_off)
1705                                        set_kbd(vc, decckm);
1706                                else
1707                                        clr_kbd(vc, decckm);
1708                                break;
1709                        case 3: /* 80/132 mode switch unimplemented */
1710#if 0
1711                                vc_resize(deccolm ? 132 : 80, vc->vc_rows);
1712                                /* this alone does not suffice; some user mode
1713                                   utility has to change the hardware regs */
1714#endif
1715                                break;
1716                        case 5:                 /* Inverted screen on/off */
1717                                if (vc->vc_decscnm != on_off) {
1718                                        vc->vc_decscnm = on_off;
1719                                        invert_screen(vc, 0, vc->vc_screenbuf_size, 0);
1720                                        update_attr(vc);
1721                                }
1722                                break;
1723                        case 6:                 /* Origin relative/absolute */
1724                                vc->vc_decom = on_off;
1725                                gotoxay(vc, 0, 0);
1726                                break;
1727                        case 7:                 /* Autowrap on/off */
1728                                vc->vc_decawm = on_off;
1729                                break;
1730                        case 8:                 /* Autorepeat on/off */
1731                                if (on_off)
1732                                        set_kbd(vc, decarm);
1733                                else
1734                                        clr_kbd(vc, decarm);
1735                                break;
1736                        case 9:
1737                                vc->vc_report_mouse = on_off ? 1 : 0;
1738                                break;
1739                        case 25:                /* Cursor on/off */
1740                                vc->vc_deccm = on_off;
1741                                break;
1742                        case 1000:
1743                                vc->vc_report_mouse = on_off ? 2 : 0;
1744                                break;
1745                        }
1746                } else {
1747                        switch(vc->vc_par[i]) { /* ANSI modes set/reset */
1748                        case 3:                 /* Monitor (display ctrls) */
1749                                vc->vc_disp_ctrl = on_off;
1750                                break;
1751                        case 4:                 /* Insert Mode on/off */
1752                                vc->vc_decim = on_off;
1753                                break;
1754                        case 20:                /* Lf, Enter == CrLf/Lf */
1755                                if (on_off)
1756                                        set_kbd(vc, lnm);
1757                                else
1758                                        clr_kbd(vc, lnm);
1759                                break;
1760                        }
1761                }
1762}
1763
1764/* console_lock is held */
1765static void setterm_command(struct vc_data *vc)
1766{
1767        switch(vc->vc_par[0]) {
1768                case 1: /* set color for underline mode */
1769                        if (vc->vc_can_do_color &&
1770                                        vc->vc_par[1] < 16) {
1771                                vc->vc_ulcolor = color_table[vc->vc_par[1]];
1772                                if (vc->vc_underline)
1773                                        update_attr(vc);
1774                        }
1775                        break;
1776                case 2: /* set color for half intensity mode */
1777                        if (vc->vc_can_do_color &&
1778                                        vc->vc_par[1] < 16) {
1779                                vc->vc_halfcolor = color_table[vc->vc_par[1]];
1780                                if (vc->vc_intensity == 0)
1781                                        update_attr(vc);
1782                        }
1783                        break;
1784                case 8: /* store colors as defaults */
1785                        vc->vc_def_color = vc->vc_attr;
1786                        if (vc->vc_hi_font_mask == 0x100)
1787                                vc->vc_def_color >>= 1;
1788                        default_attr(vc);
1789                        update_attr(vc);
1790                        break;
1791                case 9: /* set blanking interval */
1792                        blankinterval = ((vc->vc_par[1] < 60) ? vc->vc_par[1] : 60) * 60;
1793                        poke_blanked_console();
1794                        break;
1795                case 10: /* set bell frequency in Hz */
1796                        if (vc->vc_npar >= 1)
1797                                vc->vc_bell_pitch = vc->vc_par[1];
1798                        else
1799                                vc->vc_bell_pitch = DEFAULT_BELL_PITCH;
1800                        break;
1801                case 11: /* set bell duration in msec */
1802                        if (vc->vc_npar >= 1)
1803                                vc->vc_bell_duration = (vc->vc_par[1] < 2000) ?
1804                                        msecs_to_jiffies(vc->vc_par[1]) : 0;
1805                        else
1806                                vc->vc_bell_duration = DEFAULT_BELL_DURATION;
1807                        break;
1808                case 12: /* bring specified console to the front */
1809                        if (vc->vc_par[1] >= 1 && vc_cons_allocated(vc->vc_par[1] - 1))
1810                                set_console(vc->vc_par[1] - 1);
1811                        break;
1812                case 13: /* unblank the screen */
1813                        poke_blanked_console();
1814                        break;
1815                case 14: /* set vesa powerdown interval */
1816                        vesa_off_interval = ((vc->vc_par[1] < 60) ? vc->vc_par[1] : 60) * 60 * HZ;
1817                        break;
1818                case 15: /* activate the previous console */
1819                        set_console(last_console);
1820                        break;
1821                case 16: /* set cursor blink duration in msec */
1822                        if (vc->vc_npar >= 1 && vc->vc_par[1] >= 50 &&
1823                                        vc->vc_par[1] <= USHRT_MAX)
1824                                vc->vc_cur_blink_ms = vc->vc_par[1];
1825                        else
1826                                vc->vc_cur_blink_ms = DEFAULT_CURSOR_BLINK_MS;
1827                        break;
1828        }
1829}
1830
1831/* console_lock is held */
1832static void csi_at(struct vc_data *vc, unsigned int nr)
1833{
1834        if (nr > vc->vc_cols - vc->vc_x)
1835                nr = vc->vc_cols - vc->vc_x;
1836        else if (!nr)
1837                nr = 1;
1838        insert_char(vc, nr);
1839}
1840
1841/* console_lock is held */
1842static void csi_L(struct vc_data *vc, unsigned int nr)
1843{
1844        if (nr > vc->vc_rows - vc->vc_y)
1845                nr = vc->vc_rows - vc->vc_y;
1846        else if (!nr)
1847                nr = 1;
1848        con_scroll(vc, vc->vc_y, vc->vc_bottom, SM_DOWN, nr);
1849        vc->vc_need_wrap = 0;
1850}
1851
1852/* console_lock is held */
1853static void csi_P(struct vc_data *vc, unsigned int nr)
1854{
1855        if (nr > vc->vc_cols - vc->vc_x)
1856                nr = vc->vc_cols - vc->vc_x;
1857        else if (!nr)
1858                nr = 1;
1859        delete_char(vc, nr);
1860}
1861
1862/* console_lock is held */
1863static void csi_M(struct vc_data *vc, unsigned int nr)
1864{
1865        if (nr > vc->vc_rows - vc->vc_y)
1866                nr = vc->vc_rows - vc->vc_y;
1867        else if (!nr)
1868                nr=1;
1869        con_scroll(vc, vc->vc_y, vc->vc_bottom, SM_UP, nr);
1870        vc->vc_need_wrap = 0;
1871}
1872
1873/* console_lock is held (except via vc_init->reset_terminal */
1874static void save_cur(struct vc_data *vc)
1875{
1876        vc->vc_saved_x          = vc->vc_x;
1877        vc->vc_saved_y          = vc->vc_y;
1878        vc->vc_s_intensity      = vc->vc_intensity;
1879        vc->vc_s_italic         = vc->vc_italic;
1880        vc->vc_s_underline      = vc->vc_underline;
1881        vc->vc_s_blink          = vc->vc_blink;
1882        vc->vc_s_reverse        = vc->vc_reverse;
1883        vc->vc_s_charset        = vc->vc_charset;
1884        vc->vc_s_color          = vc->vc_color;
1885        vc->vc_saved_G0         = vc->vc_G0_charset;
1886        vc->vc_saved_G1         = vc->vc_G1_charset;
1887}
1888
1889/* console_lock is held */
1890static void restore_cur(struct vc_data *vc)
1891{
1892        gotoxy(vc, vc->vc_saved_x, vc->vc_saved_y);
1893        vc->vc_intensity        = vc->vc_s_intensity;
1894        vc->vc_italic           = vc->vc_s_italic;
1895        vc->vc_underline        = vc->vc_s_underline;
1896        vc->vc_blink            = vc->vc_s_blink;
1897        vc->vc_reverse          = vc->vc_s_reverse;
1898        vc->vc_charset          = vc->vc_s_charset;
1899        vc->vc_color            = vc->vc_s_color;
1900        vc->vc_G0_charset       = vc->vc_saved_G0;
1901        vc->vc_G1_charset       = vc->vc_saved_G1;
1902        vc->vc_translate        = set_translate(vc->vc_charset ? vc->vc_G1_charset : vc->vc_G0_charset, vc);
1903        update_attr(vc);
1904        vc->vc_need_wrap = 0;
1905}
1906
1907enum { ESnormal, ESesc, ESsquare, ESgetpars, ESfunckey,
1908        EShash, ESsetG0, ESsetG1, ESpercent, ESignore, ESnonstd,
1909        ESpalette, ESosc };
1910
1911/* console_lock is held (except via vc_init()) */
1912static void reset_terminal(struct vc_data *vc, int do_clear)
1913{
1914        vc->vc_top              = 0;
1915        vc->vc_bottom           = vc->vc_rows;
1916        vc->vc_state            = ESnormal;
1917        vc->vc_ques             = 0;
1918        vc->vc_translate        = set_translate(LAT1_MAP, vc);
1919        vc->vc_G0_charset       = LAT1_MAP;
1920        vc->vc_G1_charset       = GRAF_MAP;
1921        vc->vc_charset          = 0;
1922        vc->vc_need_wrap        = 0;
1923        vc->vc_report_mouse     = 0;
1924        vc->vc_utf              = default_utf8;
1925        vc->vc_utf_count        = 0;
1926
1927        vc->vc_disp_ctrl        = 0;
1928        vc->vc_toggle_meta      = 0;
1929
1930        vc->vc_decscnm          = 0;
1931        vc->vc_decom            = 0;
1932        vc->vc_decawm           = 1;
1933        vc->vc_deccm            = global_cursor_default;
1934        vc->vc_decim            = 0;
1935
1936        vt_reset_keyboard(vc->vc_num);
1937
1938        vc->vc_cursor_type = cur_default;
1939        vc->vc_complement_mask = vc->vc_s_complement_mask;
1940
1941        default_attr(vc);
1942        update_attr(vc);
1943
1944        vc->vc_tab_stop[0]      =
1945        vc->vc_tab_stop[1]      =
1946        vc->vc_tab_stop[2]      =
1947        vc->vc_tab_stop[3]      =
1948        vc->vc_tab_stop[4]      =
1949        vc->vc_tab_stop[5]      =
1950        vc->vc_tab_stop[6]      =
1951        vc->vc_tab_stop[7]      = 0x01010101;
1952
1953        vc->vc_bell_pitch = DEFAULT_BELL_PITCH;
1954        vc->vc_bell_duration = DEFAULT_BELL_DURATION;
1955        vc->vc_cur_blink_ms = DEFAULT_CURSOR_BLINK_MS;
1956
1957        gotoxy(vc, 0, 0);
1958        save_cur(vc);
1959        if (do_clear)
1960            csi_J(vc, 2);
1961}
1962
1963/* console_lock is held */
1964static void do_con_trol(struct tty_struct *tty, struct vc_data *vc, int c)
1965{
1966        /*
1967         *  Control characters can be used in the _middle_
1968         *  of an escape sequence.
1969         */
1970        if (vc->vc_state == ESosc && c>=8 && c<=13) /* ... except for OSC */
1971                return;
1972        switch (c) {
1973        case 0:
1974                return;
1975        case 7:
1976                if (vc->vc_state == ESosc)
1977                        vc->vc_state = ESnormal;
1978                else if (vc->vc_bell_duration)
1979                        kd_mksound(vc->vc_bell_pitch, vc->vc_bell_duration);
1980                return;
1981        case 8:
1982                bs(vc);
1983                return;
1984        case 9:
1985                vc->vc_pos -= (vc->vc_x << 1);
1986                while (vc->vc_x < vc->vc_cols - 1) {
1987                        vc->vc_x++;
1988                        if (vc->vc_tab_stop[7 & (vc->vc_x >> 5)] & (1 << (vc->vc_x & 31)))
1989                                break;
1990                }
1991                vc->vc_pos += (vc->vc_x << 1);
1992                notify_write(vc, '\t');
1993                return;
1994        case 10: case 11: case 12:
1995                lf(vc);
1996                if (!is_kbd(vc, lnm))
1997                        return;
1998        case 13:
1999                cr(vc);
2000                return;
2001        case 14:
2002                vc->vc_charset = 1;
2003                vc->vc_translate = set_translate(vc->vc_G1_charset, vc);
2004                vc->vc_disp_ctrl = 1;
2005                return;
2006        case 15:
2007                vc->vc_charset = 0;
2008                vc->vc_translate = set_translate(vc->vc_G0_charset, vc);
2009                vc->vc_disp_ctrl = 0;
2010                return;
2011        case 24: case 26:
2012                vc->vc_state = ESnormal;
2013                return;
2014        case 27:
2015                vc->vc_state = ESesc;
2016                return;
2017        case 127:
2018                del(vc);
2019                return;
2020        case 128+27:
2021                vc->vc_state = ESsquare;
2022                return;
2023        }
2024        switch(vc->vc_state) {
2025        case ESesc:
2026                vc->vc_state = ESnormal;
2027                switch (c) {
2028                case '[':
2029                        vc->vc_state = ESsquare;
2030                        return;
2031                case ']':
2032                        vc->vc_state = ESnonstd;
2033                        return;
2034                case '%':
2035                        vc->vc_state = ESpercent;
2036                        return;
2037                case 'E':
2038                        cr(vc);
2039                        lf(vc);
2040                        return;
2041                case 'M':
2042                        ri(vc);
2043                        return;
2044                case 'D':
2045                        lf(vc);
2046                        return;
2047                case 'H':
2048                        vc->vc_tab_stop[7 & (vc->vc_x >> 5)] |= (1 << (vc->vc_x & 31));
2049                        return;
2050                case 'Z':
2051                        respond_ID(tty);
2052                        return;
2053                case '7':
2054                        save_cur(vc);
2055                        return;
2056                case '8':
2057                        restore_cur(vc);
2058                        return;
2059                case '(':
2060                        vc->vc_state = ESsetG0;
2061                        return;
2062                case ')':
2063                        vc->vc_state = ESsetG1;
2064                        return;
2065                case '#':
2066                        vc->vc_state = EShash;
2067                        return;
2068                case 'c':
2069                        reset_terminal(vc, 1);
2070                        return;
2071                case '>':  /* Numeric keypad */
2072                        clr_kbd(vc, kbdapplic);
2073                        return;
2074                case '=':  /* Appl. keypad */
2075                        set_kbd(vc, kbdapplic);
2076                        return;
2077                }
2078                return;
2079        case ESnonstd:
2080                if (c=='P') {   /* palette escape sequence */
2081                        for (vc->vc_npar = 0; vc->vc_npar < NPAR; vc->vc_npar++)
2082                                vc->vc_par[vc->vc_npar] = 0;
2083                        vc->vc_npar = 0;
2084                        vc->vc_state = ESpalette;
2085                        return;
2086                } else if (c=='R') {   /* reset palette */
2087                        reset_palette(vc);
2088                        vc->vc_state = ESnormal;
2089                } else if (c>='0' && c<='9')
2090                        vc->vc_state = ESosc;
2091                else
2092                        vc->vc_state = ESnormal;
2093                return;
2094        case ESpalette:
2095                if (isxdigit(c)) {
2096                        vc->vc_par[vc->vc_npar++] = hex_to_bin(c);
2097                        if (vc->vc_npar == 7) {
2098                                int i = vc->vc_par[0] * 3, j = 1;
2099                                vc->vc_palette[i] = 16 * vc->vc_par[j++];
2100                                vc->vc_palette[i++] += vc->vc_par[j++];
2101                                vc->vc_palette[i] = 16 * vc->vc_par[j++];
2102                                vc->vc_palette[i++] += vc->vc_par[j++];
2103                                vc->vc_palette[i] = 16 * vc->vc_par[j++];
2104                                vc->vc_palette[i] += vc->vc_par[j];
2105                                set_palette(vc);
2106                                vc->vc_state = ESnormal;
2107                        }
2108                } else
2109                        vc->vc_state = ESnormal;
2110                return;
2111        case ESsquare:
2112                for (vc->vc_npar = 0; vc->vc_npar < NPAR; vc->vc_npar++)
2113                        vc->vc_par[vc->vc_npar] = 0;
2114                vc->vc_npar = 0;
2115                vc->vc_state = ESgetpars;
2116                if (c == '[') { /* Function key */
2117                        vc->vc_state=ESfunckey;
2118                        return;
2119                }
2120                vc->vc_ques = (c == '?');
2121                if (vc->vc_ques)
2122                        return;
2123        case ESgetpars:
2124                if (c == ';' && vc->vc_npar < NPAR - 1) {
2125                        vc->vc_npar++;
2126                        return;
2127                } else if (c>='0' && c<='9') {
2128                        vc->vc_par[vc->vc_npar] *= 10;
2129                        vc->vc_par[vc->vc_npar] += c - '0';
2130                        return;
2131                }
2132                vc->vc_state = ESnormal;
2133                switch(c) {
2134                case 'h':
2135                        set_mode(vc, 1);
2136                        return;
2137                case 'l':
2138                        set_mode(vc, 0);
2139                        return;
2140                case 'c':
2141                        if (vc->vc_ques) {
2142                                if (vc->vc_par[0])
2143                                        vc->vc_cursor_type = vc->vc_par[0] | (vc->vc_par[1] << 8) | (vc->vc_par[2] << 16);
2144                                else
2145                                        vc->vc_cursor_type = cur_default;
2146                                return;
2147                        }
2148                        break;
2149                case 'm':
2150                        if (vc->vc_ques) {
2151                                clear_selection();
2152                                if (vc->vc_par[0])
2153                                        vc->vc_complement_mask = vc->vc_par[0] << 8 | vc->vc_par[1];
2154                                else
2155                                        vc->vc_complement_mask = vc->vc_s_complement_mask;
2156                                return;
2157                        }
2158                        break;
2159                case 'n':
2160                        if (!vc->vc_ques) {
2161                                if (vc->vc_par[0] == 5)
2162                                        status_report(tty);
2163                                else if (vc->vc_par[0] == 6)
2164                                        cursor_report(vc, tty);
2165                        }
2166                        return;
2167                }
2168                if (vc->vc_ques) {
2169                        vc->vc_ques = 0;
2170                        return;
2171                }
2172                switch(c) {
2173                case 'G': case '`':
2174                        if (vc->vc_par[0])
2175                                vc->vc_par[0]--;
2176                        gotoxy(vc, vc->vc_par[0], vc->vc_y);
2177                        return;
2178                case 'A':
2179                        if (!vc->vc_par[0])
2180                                vc->vc_par[0]++;
2181                        gotoxy(vc, vc->vc_x, vc->vc_y - vc->vc_par[0]);
2182                        return;
2183                case 'B': case 'e':
2184                        if (!vc->vc_par[0])
2185                                vc->vc_par[0]++;
2186                        gotoxy(vc, vc->vc_x, vc->vc_y + vc->vc_par[0]);
2187                        return;
2188                case 'C': case 'a':
2189                        if (!vc->vc_par[0])
2190                                vc->vc_par[0]++;
2191                        gotoxy(vc, vc->vc_x + vc->vc_par[0], vc->vc_y);
2192                        return;
2193                case 'D':
2194                        if (!vc->vc_par[0])
2195                                vc->vc_par[0]++;
2196                        gotoxy(vc, vc->vc_x - vc->vc_par[0], vc->vc_y);
2197                        return;
2198                case 'E':
2199                        if (!vc->vc_par[0])
2200                                vc->vc_par[0]++;
2201                        gotoxy(vc, 0, vc->vc_y + vc->vc_par[0]);
2202                        return;
2203                case 'F':
2204                        if (!vc->vc_par[0])
2205                                vc->vc_par[0]++;
2206                        gotoxy(vc, 0, vc->vc_y - vc->vc_par[0]);
2207                        return;
2208                case 'd':
2209                        if (vc->vc_par[0])
2210                                vc->vc_par[0]--;
2211                        gotoxay(vc, vc->vc_x ,vc->vc_par[0]);
2212                        return;
2213                case 'H': case 'f':
2214                        if (vc->vc_par[0])
2215                                vc->vc_par[0]--;
2216                        if (vc->vc_par[1])
2217                                vc->vc_par[1]--;
2218                        gotoxay(vc, vc->vc_par[1], vc->vc_par[0]);
2219                        return;
2220                case 'J':
2221                        csi_J(vc, vc->vc_par[0]);
2222                        return;
2223                case 'K':
2224                        csi_K(vc, vc->vc_par[0]);
2225                        return;
2226                case 'L':
2227                        csi_L(vc, vc->vc_par[0]);
2228                        return;
2229                case 'M':
2230                        csi_M(vc, vc->vc_par[0]);
2231                        return;
2232                case 'P':
2233                        csi_P(vc, vc->vc_par[0]);
2234                        return;
2235                case 'c':
2236                        if (!vc->vc_par[0])
2237                                respond_ID(tty);
2238                        return;
2239                case 'g':
2240                        if (!vc->vc_par[0])
2241                                vc->vc_tab_stop[7 & (vc->vc_x >> 5)] &= ~(1 << (vc->vc_x & 31));
2242                        else if (vc->vc_par[0] == 3) {
2243                                vc->vc_tab_stop[0] =
2244                                        vc->vc_tab_stop[1] =
2245                                        vc->vc_tab_stop[2] =
2246                                        vc->vc_tab_stop[3] =
2247                                        vc->vc_tab_stop[4] =
2248                                        vc->vc_tab_stop[5] =
2249                                        vc->vc_tab_stop[6] =
2250                                        vc->vc_tab_stop[7] = 0;
2251                        }
2252                        return;
2253                case 'm':
2254                        csi_m(vc);
2255                        return;
2256                case 'q': /* DECLL - but only 3 leds */
2257                        /* map 0,1,2,3 to 0,1,2,4 */
2258                        if (vc->vc_par[0] < 4)
2259                                vt_set_led_state(vc->vc_num,
2260                                            (vc->vc_par[0] < 3) ? vc->vc_par[0] : 4);
2261                        return;
2262                case 'r':
2263                        if (!vc->vc_par[0])
2264                                vc->vc_par[0]++;
2265                        if (!vc->vc_par[1])
2266                                vc->vc_par[1] = vc->vc_rows;
2267                        /* Minimum allowed region is 2 lines */
2268                        if (vc->vc_par[0] < vc->vc_par[1] &&
2269                            vc->vc_par[1] <= vc->vc_rows) {
2270                                vc->vc_top = vc->vc_par[0] - 1;
2271                                vc->vc_bottom = vc->vc_par[1];
2272                                gotoxay(vc, 0, 0);
2273                        }
2274                        return;
2275                case 's':
2276                        save_cur(vc);
2277                        return;
2278                case 'u':
2279                        restore_cur(vc);
2280                        return;
2281                case 'X':
2282                        csi_X(vc, vc->vc_par[0]);
2283                        return;
2284                case '@':
2285                        csi_at(vc, vc->vc_par[0]);
2286                        return;
2287                case ']': /* setterm functions */
2288                        setterm_command(vc);
2289                        return;
2290                }
2291                return;
2292        case ESpercent:
2293                vc->vc_state = ESnormal;
2294                switch (c) {
2295                case '@':  /* defined in ISO 2022 */
2296                        vc->vc_utf = 0;
2297                        return;
2298                case 'G':  /* prelim official escape code */
2299                case '8':  /* retained for compatibility */
2300                        vc->vc_utf = 1;
2301                        return;
2302                }
2303                return;
2304        case ESfunckey:
2305                vc->vc_state = ESnormal;
2306                return;
2307        case EShash:
2308                vc->vc_state = ESnormal;
2309                if (c == '8') {
2310                        /* DEC screen alignment test. kludge :-) */
2311                        vc->vc_video_erase_char =
2312                                (vc->vc_video_erase_char & 0xff00) | 'E';
2313                        csi_J(vc, 2);
2314                        vc->vc_video_erase_char =
2315                                (vc->vc_video_erase_char & 0xff00) | ' ';
2316                        do_update_region(vc, vc->vc_origin, vc->vc_screenbuf_size / 2);
2317                }
2318                return;
2319        case ESsetG0:
2320                if (c == '0')
2321                        vc->vc_G0_charset = GRAF_MAP;
2322                else if (c == 'B')
2323                        vc->vc_G0_charset = LAT1_MAP;
2324                else if (c == 'U')
2325                        vc->vc_G0_charset = IBMPC_MAP;
2326                else if (c == 'K')
2327                        vc->vc_G0_charset = USER_MAP;
2328                if (vc->vc_charset == 0)
2329                        vc->vc_translate = set_translate(vc->vc_G0_charset, vc);
2330                vc->vc_state = ESnormal;
2331                return;
2332        case ESsetG1:
2333                if (c == '0')
2334                        vc->vc_G1_charset = GRAF_MAP;
2335                else if (c == 'B')
2336                        vc->vc_G1_charset = LAT1_MAP;
2337                else if (c == 'U')
2338                        vc->vc_G1_charset = IBMPC_MAP;
2339                else if (c == 'K')
2340                        vc->vc_G1_charset = USER_MAP;
2341                if (vc->vc_charset == 1)
2342                        vc->vc_translate = set_translate(vc->vc_G1_charset, vc);
2343                vc->vc_state = ESnormal;
2344                return;
2345        case ESosc:
2346                return;
2347        default:
2348                vc->vc_state = ESnormal;
2349        }
2350}
2351
2352/* is_double_width() is based on the wcwidth() implementation by
2353 * Markus Kuhn -- 2007-05-26 (Unicode 5.0)
2354 * Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
2355 */
2356struct interval {
2357        uint32_t first;
2358        uint32_t last;
2359};
2360
2361static int ucs_cmp(const void *key, const void *elt)
2362{
2363        uint32_t ucs = *(uint32_t *)key;
2364        struct interval e = *(struct interval *) elt;
2365
2366        if (ucs > e.last)
2367                return 1;
2368        else if (ucs < e.first)
2369                return -1;
2370        return 0;
2371}
2372
2373static int is_double_width(uint32_t ucs)
2374{
2375        static const struct interval double_width[] = {
2376                { 0x1100, 0x115F }, { 0x2329, 0x232A }, { 0x2E80, 0x303E },
2377                { 0x3040, 0xA4CF }, { 0xAC00, 0xD7A3 }, { 0xF900, 0xFAFF },
2378                { 0xFE10, 0xFE19 }, { 0xFE30, 0xFE6F }, { 0xFF00, 0xFF60 },
2379                { 0xFFE0, 0xFFE6 }, { 0x20000, 0x2FFFD }, { 0x30000, 0x3FFFD }
2380        };
2381        if (ucs < double_width[0].first ||
2382            ucs > double_width[ARRAY_SIZE(double_width) - 1].last)
2383                return 0;
2384
2385        return bsearch(&ucs, double_width, ARRAY_SIZE(double_width),
2386                        sizeof(struct interval), ucs_cmp) != NULL;
2387}
2388
2389static void con_flush(struct vc_data *vc, unsigned long draw_from,
2390                unsigned long draw_to, int *draw_x)
2391{
2392        if (*draw_x < 0)
2393                return;
2394
2395        vc->vc_sw->con_putcs(vc, (u16 *)draw_from,
2396                        (u16 *)draw_to - (u16 *)draw_from, vc->vc_y, *draw_x);
2397        *draw_x = -1;
2398}
2399
2400/* acquires console_lock */
2401static int do_con_write(struct tty_struct *tty, const unsigned char *buf, int count)
2402{
2403        int c, next_c, tc, ok, n = 0, draw_x = -1;
2404        unsigned int currcons;
2405        unsigned long draw_from = 0, draw_to = 0;
2406        struct vc_data *vc;
2407        unsigned char vc_attr;
2408        struct vt_notifier_param param;
2409        uint8_t rescan;
2410        uint8_t inverse;
2411        uint8_t width;
2412        u16 himask, charmask;
2413
2414        if (in_interrupt())
2415                return count;
2416
2417        might_sleep();
2418
2419        console_lock();
2420        vc = tty->driver_data;
2421        if (vc == NULL) {
2422                pr_err("vt: argh, driver_data is NULL !\n");
2423                console_unlock();
2424                return 0;
2425        }
2426
2427        currcons = vc->vc_num;
2428        if (!vc_cons_allocated(currcons)) {
2429                /* could this happen? */
2430                pr_warn_once("con_write: tty %d not allocated\n", currcons+1);
2431                console_unlock();
2432                return 0;
2433        }
2434
2435        himask = vc->vc_hi_font_mask;
2436        charmask = himask ? 0x1ff : 0xff;
2437
2438        /* undraw cursor first */
2439        if (con_is_fg(vc))
2440                hide_cursor(vc);
2441
2442        param.vc = vc;
2443
2444        while (!tty->stopped && count) {
2445                int orig = *buf;
2446                c = orig;
2447                buf++;
2448                n++;
2449                count--;
2450                rescan = 0;
2451                inverse = 0;
2452                width = 1;
2453
2454                /* Do no translation at all in control states */
2455                if (vc->vc_state != ESnormal) {
2456                        tc = c;
2457                } else if (vc->vc_utf && !vc->vc_disp_ctrl) {
2458                    /* Combine UTF-8 into Unicode in vc_utf_char.
2459                     * vc_utf_count is the number of continuation bytes still
2460                     * expected to arrive.
2461                     * vc_npar is the number of continuation bytes arrived so
2462                     * far
2463                     */
2464rescan_last_byte:
2465                    if ((c & 0xc0) == 0x80) {
2466                        /* Continuation byte received */
2467                        static const uint32_t utf8_length_changes[] = { 0x0000007f, 0x000007ff, 0x0000ffff, 0x001fffff, 0x03ffffff, 0x7fffffff };
2468                        if (vc->vc_utf_count) {
2469                            vc->vc_utf_char = (vc->vc_utf_char << 6) | (c & 0x3f);
2470                            vc->vc_npar++;
2471                            if (--vc->vc_utf_count) {
2472                                /* Still need some bytes */
2473                                continue;
2474                            }
2475                            /* Got a whole character */
2476                            c = vc->vc_utf_char;
2477                            /* Reject overlong sequences */
2478                            if (c <= utf8_length_changes[vc->vc_npar - 1] ||
2479                                        c > utf8_length_changes[vc->vc_npar])
2480                                c = 0xfffd;
2481                        } else {
2482                            /* Unexpected continuation byte */
2483                            vc->vc_utf_count = 0;
2484                            c = 0xfffd;
2485                        }
2486                    } else {
2487                        /* Single ASCII byte or first byte of a sequence received */
2488                        if (vc->vc_utf_count) {
2489                            /* Continuation byte expected */
2490                            rescan = 1;
2491                            vc->vc_utf_count = 0;
2492                            c = 0xfffd;
2493                        } else if (c > 0x7f) {
2494                            /* First byte of a multibyte sequence received */
2495                            vc->vc_npar = 0;
2496                            if ((c & 0xe0) == 0xc0) {
2497                                vc->vc_utf_count = 1;
2498                                vc->vc_utf_char = (c & 0x1f);
2499                            } else if ((c & 0xf0) == 0xe0) {
2500                                vc->vc_utf_count = 2;
2501                                vc->vc_utf_char = (c & 0x0f);
2502                            } else if ((c & 0xf8) == 0xf0) {
2503                                vc->vc_utf_count = 3;
2504                                vc->vc_utf_char = (c & 0x07);
2505                            } else if ((c & 0xfc) == 0xf8) {
2506                                vc->vc_utf_count = 4;
2507                                vc->vc_utf_char = (c & 0x03);
2508                            } else if ((c & 0xfe) == 0xfc) {
2509                                vc->vc_utf_count = 5;
2510                                vc->vc_utf_char = (c & 0x01);
2511                            } else {
2512                                /* 254 and 255 are invalid */
2513                                c = 0xfffd;
2514                            }
2515                            if (vc->vc_utf_count) {
2516                                /* Still need some bytes */
2517                                continue;
2518                            }
2519                        }
2520                        /* Nothing to do if an ASCII byte was received */
2521                    }
2522                    /* End of UTF-8 decoding. */
2523                    /* c is the received character, or U+FFFD for invalid sequences. */
2524                    /* Replace invalid Unicode code points with U+FFFD too */
2525                    if ((c >= 0xd800 && c <= 0xdfff) || c == 0xfffe || c == 0xffff)
2526                        c = 0xfffd;
2527                    tc = c;
2528                } else {        /* no utf or alternate charset mode */
2529                    tc = vc_translate(vc, c);
2530                }
2531
2532                param.c = tc;
2533                if (atomic_notifier_call_chain(&vt_notifier_list, VT_PREWRITE,
2534                                        &param) == NOTIFY_STOP)
2535                        continue;
2536
2537                /* If the original code was a control character we
2538                 * only allow a glyph to be displayed if the code is
2539                 * not normally used (such as for cursor movement) or
2540                 * if the disp_ctrl mode has been explicitly enabled.
2541                 * Certain characters (as given by the CTRL_ALWAYS
2542                 * bitmap) are always displayed as control characters,
2543                 * as the console would be pretty useless without
2544                 * them; to display an arbitrary font position use the
2545                 * direct-to-font zone in UTF-8 mode.
2546                 */
2547                ok = tc && (c >= 32 ||
2548                            !(vc->vc_disp_ctrl ? (CTRL_ALWAYS >> c) & 1 :
2549                                  vc->vc_utf || ((CTRL_ACTION >> c) & 1)))
2550                        && (c != 127 || vc->vc_disp_ctrl)
2551                        && (c != 128+27);
2552
2553                if (vc->vc_state == ESnormal && ok) {
2554                        if (vc->vc_utf && !vc->vc_disp_ctrl) {
2555                                if (is_double_width(c))
2556                                        width = 2;
2557                        }
2558                        /* Now try to find out how to display it */
2559                        tc = conv_uni_to_pc(vc, tc);
2560                        if (tc & ~charmask) {
2561                                if (tc == -1 || tc == -2) {
2562                                    continue; /* nothing to display */
2563                                }
2564                                /* Glyph not found */
2565                                if ((!(vc->vc_utf && !vc->vc_disp_ctrl) || c < 128) && !(c & ~charmask)) {
2566                                    /* In legacy mode use the glyph we get by a 1:1 mapping.
2567                                       This would make absolutely no sense with Unicode in mind,
2568                                       but do this for ASCII characters since a font may lack
2569                                       Unicode mapping info and we don't want to end up with
2570                                       having question marks only. */
2571                                    tc = c;
2572                                } else {
2573                                    /* Display U+FFFD. If it's not found, display an inverse question mark. */
2574                                    tc = conv_uni_to_pc(vc, 0xfffd);
2575                                    if (tc < 0) {
2576                                        inverse = 1;
2577                                        tc = conv_uni_to_pc(vc, '?');
2578                                        if (tc < 0) tc = '?';
2579                                    }
2580                                }
2581                        }
2582
2583                        if (!inverse) {
2584                                vc_attr = vc->vc_attr;
2585                        } else {
2586                                /* invert vc_attr */
2587                                if (!vc->vc_can_do_color) {
2588                                        vc_attr = (vc->vc_attr) ^ 0x08;
2589                                } else if (vc->vc_hi_font_mask == 0x100) {
2590                                        vc_attr = ((vc->vc_attr) & 0x11) | (((vc->vc_attr) & 0xe0) >> 4) | (((vc->vc_attr) & 0x0e) << 4);
2591                                } else {
2592                                        vc_attr = ((vc->vc_attr) & 0x88) | (((vc->vc_attr) & 0x70) >> 4) | (((vc->vc_attr) & 0x07) << 4);
2593                                }
2594                                con_flush(vc, draw_from, draw_to, &draw_x);
2595                        }
2596
2597                        next_c = c;
2598                        while (1) {
2599                                if (vc->vc_need_wrap || vc->vc_decim)
2600                                        con_flush(vc, draw_from, draw_to,
2601                                                        &draw_x);
2602                                if (vc->vc_need_wrap) {
2603                                        cr(vc);
2604                                        lf(vc);
2605                                }
2606                                if (vc->vc_decim)
2607                                        insert_char(vc, 1);
2608                                vc_uniscr_putc(vc, next_c);
2609                                scr_writew(himask ?
2610                                             ((vc_attr << 8) & ~himask) + ((tc & 0x100) ? himask : 0) + (tc & 0xff) :
2611                                             (vc_attr << 8) + tc,
2612                                           (u16 *) vc->vc_pos);
2613                                if (con_should_update(vc) && draw_x < 0) {
2614                                        draw_x = vc->vc_x;
2615                                        draw_from = vc->vc_pos;
2616                                }
2617                                if (vc->vc_x == vc->vc_cols - 1) {
2618                                        vc->vc_need_wrap = vc->vc_decawm;
2619                                        draw_to = vc->vc_pos + 2;
2620                                } else {
2621                                        vc->vc_x++;
2622                                        draw_to = (vc->vc_pos += 2);
2623                                }
2624
2625                                if (!--width) break;
2626
2627                                tc = conv_uni_to_pc(vc, ' '); /* A space is printed in the second column */
2628                                if (tc < 0) tc = ' ';
2629                                next_c = ' ';
2630                        }
2631                        notify_write(vc, c);
2632
2633                        if (inverse)
2634                                con_flush(vc, draw_from, draw_to, &draw_x);
2635
2636                        if (rescan) {
2637                                rescan = 0;
2638                                inverse = 0;
2639                                width = 1;
2640                                c = orig;
2641                                goto rescan_last_byte;
2642                        }
2643                        continue;
2644                }
2645                con_flush(vc, draw_from, draw_to, &draw_x);
2646                do_con_trol(tty, vc, orig);
2647        }
2648        con_flush(vc, draw_from, draw_to, &draw_x);
2649        console_conditional_schedule();
2650        console_unlock();
2651        notify_update(vc);
2652        return n;
2653}
2654
2655/*
2656 * This is the console switching callback.
2657 *
2658 * Doing console switching in a process context allows
2659 * us to do the switches asynchronously (needed when we want
2660 * to switch due to a keyboard interrupt).  Synchronization
2661 * with other console code and prevention of re-entrancy is
2662 * ensured with console_lock.
2663 */
2664static void console_callback(struct work_struct *ignored)
2665{
2666        console_lock();
2667
2668        if (want_console >= 0) {
2669                if (want_console != fg_console &&
2670                    vc_cons_allocated(want_console)) {
2671                        hide_cursor(vc_cons[fg_console].d);
2672                        change_console(vc_cons[want_console].d);
2673                        /* we only changed when the console had already
2674                           been allocated - a new console is not created
2675                           in an interrupt routine */
2676                }
2677                want_console = -1;
2678        }
2679        if (do_poke_blanked_console) { /* do not unblank for a LED change */
2680                do_poke_blanked_console = 0;
2681                poke_blanked_console();
2682        }
2683        if (scrollback_delta) {
2684                struct vc_data *vc = vc_cons[fg_console].d;
2685                clear_selection();
2686                if (vc->vc_mode == KD_TEXT && vc->vc_sw->con_scrolldelta)
2687                        vc->vc_sw->con_scrolldelta(vc, scrollback_delta);
2688                scrollback_delta = 0;
2689        }
2690        if (blank_timer_expired) {
2691                do_blank_screen(0);
2692                blank_timer_expired = 0;
2693        }
2694        notify_update(vc_cons[fg_console].d);
2695
2696        console_unlock();
2697}
2698
2699int set_console(int nr)
2700{
2701        struct vc_data *vc = vc_cons[fg_console].d;
2702
2703        if (!vc_cons_allocated(nr) || vt_dont_switch ||
2704                (vc->vt_mode.mode == VT_AUTO && vc->vc_mode == KD_GRAPHICS)) {
2705
2706                /*
2707                 * Console switch will fail in console_callback() or
2708                 * change_console() so there is no point scheduling
2709                 * the callback
2710                 *
2711                 * Existing set_console() users don't check the return
2712                 * value so this shouldn't break anything
2713                 */
2714                return -EINVAL;
2715        }
2716
2717        want_console = nr;
2718        schedule_console_callback();
2719
2720        return 0;
2721}
2722
2723struct tty_driver *console_driver;
2724
2725#ifdef CONFIG_VT_CONSOLE
2726
2727/**
2728 * vt_kmsg_redirect() - Sets/gets the kernel message console
2729 * @new:        The new virtual terminal number or -1 if the console should stay
2730 *              unchanged
2731 *
2732 * By default, the kernel messages are always printed on the current virtual
2733 * console. However, the user may modify that default with the
2734 * TIOCL_SETKMSGREDIRECT ioctl call.
2735 *
2736 * This function sets the kernel message console to be @new. It returns the old
2737 * virtual console number. The virtual terminal number 0 (both as parameter and
2738 * return value) means no redirection (i.e. always printed on the currently
2739 * active console).
2740 *
2741 * The parameter -1 means that only the current console is returned, but the
2742 * value is not modified. You may use the macro vt_get_kmsg_redirect() in that
2743 * case to make the code more understandable.
2744 *
2745 * When the kernel is compiled without CONFIG_VT_CONSOLE, this function ignores
2746 * the parameter and always returns 0.
2747 */
2748int vt_kmsg_redirect(int new)
2749{
2750        static int kmsg_con;
2751
2752        if (new != -1)
2753                return xchg(&kmsg_con, new);
2754        else
2755                return kmsg_con;
2756}
2757
2758/*
2759 *      Console on virtual terminal
2760 *
2761 * The console must be locked when we get here.
2762 */
2763
2764static void vt_console_print(struct console *co, const char *b, unsigned count)
2765{
2766        struct vc_data *vc = vc_cons[fg_console].d;
2767        unsigned char c;
2768        static DEFINE_SPINLOCK(printing_lock);
2769        const ushort *start;
2770        ushort cnt = 0;
2771        ushort myx;
2772        int kmsg_console;
2773
2774        /* console busy or not yet initialized */
2775        if (!printable)
2776                return;
2777        if (!spin_trylock(&printing_lock))
2778                return;
2779
2780        kmsg_console = vt_get_kmsg_redirect();
2781        if (kmsg_console && vc_cons_allocated(kmsg_console - 1))
2782                vc = vc_cons[kmsg_console - 1].d;
2783
2784        /* read `x' only after setting currcons properly (otherwise
2785           the `x' macro will read the x of the foreground console). */
2786        myx = vc->vc_x;
2787
2788        if (!vc_cons_allocated(fg_console)) {
2789                /* impossible */
2790                /* printk("vt_console_print: tty %d not allocated ??\n", currcons+1); */
2791                goto quit;
2792        }
2793
2794        if (vc->vc_mode != KD_TEXT)
2795                goto quit;
2796
2797        /* undraw cursor first */
2798        if (con_is_fg(vc))
2799                hide_cursor(vc);
2800
2801        start = (ushort *)vc->vc_pos;
2802
2803        /* Contrived structure to try to emulate original need_wrap behaviour
2804         * Problems caused when we have need_wrap set on '\n' character */
2805        while (count--) {
2806                c = *b++;
2807                if (c == 10 || c == 13 || c == 8 || vc->vc_need_wrap) {
2808                        if (cnt > 0) {
2809                                if (con_is_visible(vc))
2810                                        vc->vc_sw->con_putcs(vc, start, cnt, vc->vc_y, vc->vc_x);
2811                                vc->vc_x += cnt;
2812                                if (vc->vc_need_wrap)
2813                                        vc->vc_x--;
2814                                cnt = 0;
2815                        }
2816                        if (c == 8) {           /* backspace */
2817                                bs(vc);
2818                                start = (ushort *)vc->vc_pos;
2819                                myx = vc->vc_x;
2820                                continue;
2821                        }
2822                        if (c != 13)
2823                                lf(vc);
2824                        cr(vc);
2825                        start = (ushort *)vc->vc_pos;
2826                        myx = vc->vc_x;
2827                        if (c == 10 || c == 13)
2828                                continue;
2829                }
2830                scr_writew((vc->vc_attr << 8) + c, (unsigned short *)vc->vc_pos);
2831                notify_write(vc, c);
2832                cnt++;
2833                if (myx == vc->vc_cols - 1) {
2834                        vc->vc_need_wrap = 1;
2835                        continue;
2836                }
2837                vc->vc_pos += 2;
2838                myx++;
2839        }
2840        if (cnt > 0) {
2841                if (con_is_visible(vc))
2842                        vc->vc_sw->con_putcs(vc, start, cnt, vc->vc_y, vc->vc_x);
2843                vc->vc_x += cnt;
2844                if (vc->vc_x == vc->vc_cols) {
2845                        vc->vc_x--;
2846                        vc->vc_need_wrap = 1;
2847                }
2848        }
2849        set_cursor(vc);
2850        notify_update(vc);
2851
2852quit:
2853        spin_unlock(&printing_lock);
2854}
2855
2856static struct tty_driver *vt_console_device(struct console *c, int *index)
2857{
2858        *index = c->index ? c->index-1 : fg_console;
2859        return console_driver;
2860}
2861
2862static struct console vt_console_driver = {
2863        .name           = "tty",
2864        .write          = vt_console_print,
2865        .device         = vt_console_device,
2866        .unblank        = unblank_screen,
2867        .flags          = CON_PRINTBUFFER,
2868        .index          = -1,
2869};
2870#endif
2871
2872/*
2873 *      Handling of Linux-specific VC ioctls
2874 */
2875
2876/*
2877 * Generally a bit racy with respect to console_lock();.
2878 *
2879 * There are some functions which don't need it.
2880 *
2881 * There are some functions which can sleep for arbitrary periods
2882 * (paste_selection) but we don't need the lock there anyway.
2883 *
2884 * set_selection_user has locking, and definitely needs it
2885 */
2886
2887int tioclinux(struct tty_struct *tty, unsigned long arg)
2888{
2889        char type, data;
2890        char __user *p = (char __user *)arg;
2891        int lines;
2892        int ret;
2893
2894        if (current->signal->tty != tty && !capable(CAP_SYS_ADMIN))
2895                return -EPERM;
2896        if (get_user(type, p))
2897                return -EFAULT;
2898        ret = 0;
2899
2900        switch (type)
2901        {
2902                case TIOCL_SETSEL:
2903                        ret = set_selection_user((struct tiocl_selection
2904                                                 __user *)(p+1), tty);
2905                        break;
2906                case TIOCL_PASTESEL:
2907                        ret = paste_selection(tty);
2908                        break;
2909                case TIOCL_UNBLANKSCREEN:
2910                        console_lock();
2911                        unblank_screen();
2912                        console_unlock();
2913                        break;
2914                case TIOCL_SELLOADLUT:
2915                        console_lock();
2916                        ret = sel_loadlut(p);
2917                        console_unlock();
2918                        break;
2919                case TIOCL_GETSHIFTSTATE:
2920
2921        /*
2922         * Make it possible to react to Shift+Mousebutton.
2923         * Note that 'shift_state' is an undocumented
2924         * kernel-internal variable; programs not closely
2925         * related to the kernel should not use this.
2926         */
2927                        data = vt_get_shift_state();
2928                        ret = put_user(data, p);
2929                        break;
2930                case TIOCL_GETMOUSEREPORTING:
2931                        console_lock(); /* May be overkill */
2932                        data = mouse_reporting();
2933                        console_unlock();
2934                        ret = put_user(data, p);
2935                        break;
2936                case TIOCL_SETVESABLANK:
2937                        console_lock();
2938                        ret = set_vesa_blanking(p);
2939                        console_unlock();
2940                        break;
2941                case TIOCL_GETKMSGREDIRECT:
2942                        data = vt_get_kmsg_redirect();
2943                        ret = put_user(data, p);
2944                        break;
2945                case TIOCL_SETKMSGREDIRECT:
2946                        if (!capable(CAP_SYS_ADMIN)) {
2947                                ret = -EPERM;
2948                        } else {
2949                                if (get_user(data, p+1))
2950                                        ret = -EFAULT;
2951                                else
2952                                        vt_kmsg_redirect(data);
2953                        }
2954                        break;
2955                case TIOCL_GETFGCONSOLE:
2956                        /* No locking needed as this is a transiently
2957                           correct return anyway if the caller hasn't
2958                           disabled switching */
2959                        ret = fg_console;
2960                        break;
2961                case TIOCL_SCROLLCONSOLE:
2962                        if (get_user(lines, (s32 __user *)(p+4))) {
2963                                ret = -EFAULT;
2964                        } else {
2965                                /* Need the console lock here. Note that lots
2966                                   of other calls need fixing before the lock
2967                                   is actually useful ! */
2968                                console_lock();
2969                                scrollfront(vc_cons[fg_console].d, lines);
2970                                console_unlock();
2971                                ret = 0;
2972                        }
2973                        break;
2974                case TIOCL_BLANKSCREEN: /* until explicitly unblanked, not only poked */
2975                        console_lock();
2976                        ignore_poke = 1;
2977                        do_blank_screen(0);
2978                        console_unlock();
2979                        break;
2980                case TIOCL_BLANKEDSCREEN:
2981                        ret = console_blanked;
2982                        break;
2983                default:
2984                        ret = -EINVAL;
2985                        break;
2986        }
2987        return ret;
2988}
2989
2990/*
2991 * /dev/ttyN handling
2992 */
2993
2994static int con_write(struct tty_struct *tty, const unsigned char *buf, int count)
2995{
2996        int     retval;
2997
2998        retval = do_con_write(tty, buf, count);
2999        con_flush_chars(tty);
3000
3001        return retval;
3002}
3003
3004static int con_put_char(struct tty_struct *tty, unsigned char ch)
3005{
3006        if (in_interrupt())
3007                return 0;       /* n_r3964 calls put_char() from interrupt context */
3008        return do_con_write(tty, &ch, 1);
3009}
3010
3011static int con_write_room(struct tty_struct *tty)
3012{
3013        if (tty->stopped)
3014                return 0;
3015        return 32768;           /* No limit, really; we're not buffering */
3016}
3017
3018static int con_chars_in_buffer(struct tty_struct *tty)
3019{
3020        return 0;               /* we're not buffering */
3021}
3022
3023/*
3024 * con_throttle and con_unthrottle are only used for
3025 * paste_selection(), which has to stuff in a large number of
3026 * characters...
3027 */
3028static void con_throttle(struct tty_struct *tty)
3029{
3030}
3031
3032static void con_unthrottle(struct tty_struct *tty)
3033{
3034        struct vc_data *vc = tty->driver_data;
3035
3036        wake_up_interruptible(&vc->paste_wait);
3037}
3038
3039/*
3040 * Turn the Scroll-Lock LED on when the tty is stopped
3041 */
3042static void con_stop(struct tty_struct *tty)
3043{
3044        int console_num;
3045        if (!tty)
3046                return;
3047        console_num = tty->index;
3048        if (!vc_cons_allocated(console_num))
3049                return;
3050        vt_kbd_con_stop(console_num);
3051}
3052
3053/*
3054 * Turn the Scroll-Lock LED off when the console is started
3055 */
3056static void con_start(struct tty_struct *tty)
3057{
3058        int console_num;
3059        if (!tty)
3060                return;
3061        console_num = tty->index;
3062        if (!vc_cons_allocated(console_num))
3063                return;
3064        vt_kbd_con_start(console_num);
3065}
3066
3067static void con_flush_chars(struct tty_struct *tty)
3068{
3069        struct vc_data *vc;
3070
3071        if (in_interrupt())     /* from flush_to_ldisc */
3072                return;
3073
3074        /* if we race with con_close(), vt may be null */
3075        console_lock();
3076        vc = tty->driver_data;
3077        if (vc)
3078                set_cursor(vc);
3079        console_unlock();
3080}
3081
3082/*
3083 * Allocate the console screen memory.
3084 */
3085static int con_install(struct tty_driver *driver, struct tty_struct *tty)
3086{
3087        unsigned int currcons = tty->index;
3088        struct vc_data *vc;
3089        int ret;
3090
3091        console_lock();
3092        ret = vc_allocate(currcons);
3093        if (ret)
3094                goto unlock;
3095
3096        vc = vc_cons[currcons].d;
3097
3098        /* Still being freed */
3099        if (vc->port.tty) {
3100                ret = -ERESTARTSYS;
3101                goto unlock;
3102        }
3103
3104        ret = tty_port_install(&vc->port, driver, tty);
3105        if (ret)
3106                goto unlock;
3107
3108        tty->driver_data = vc;
3109        vc->port.tty = tty;
3110        tty_port_get(&vc->port);
3111
3112        if (!tty->winsize.ws_row && !tty->winsize.ws_col) {
3113                tty->winsize.ws_row = vc_cons[currcons].d->vc_rows;
3114                tty->winsize.ws_col = vc_cons[currcons].d->vc_cols;
3115        }
3116        if (vc->vc_utf)
3117                tty->termios.c_iflag |= IUTF8;
3118        else
3119                tty->termios.c_iflag &= ~IUTF8;
3120unlock:
3121        console_unlock();
3122        return ret;
3123}
3124
3125static int con_open(struct tty_struct *tty, struct file *filp)
3126{
3127        /* everything done in install */
3128        return 0;
3129}
3130
3131
3132static void con_close(struct tty_struct *tty, struct file *filp)
3133{
3134        /* Nothing to do - we defer to shutdown */
3135}
3136
3137static void con_shutdown(struct tty_struct *tty)
3138{
3139        struct vc_data *vc = tty->driver_data;
3140        BUG_ON(vc == NULL);
3141        console_lock();
3142        vc->port.tty = NULL;
3143        console_unlock();
3144}
3145
3146static void con_cleanup(struct tty_struct *tty)
3147{
3148        struct vc_data *vc = tty->driver_data;
3149
3150        tty_port_put(&vc->port);
3151}
3152
3153static int default_color           = 7; /* white */
3154static int default_italic_color    = 2; // green (ASCII)
3155static int default_underline_color = 3; // cyan (ASCII)
3156module_param_named(color, default_color, int, S_IRUGO | S_IWUSR);
3157module_param_named(italic, default_italic_color, int, S_IRUGO | S_IWUSR);
3158module_param_named(underline, default_underline_color, int, S_IRUGO | S_IWUSR);
3159
3160static void vc_init(struct vc_data *vc, unsigned int rows,
3161                    unsigned int cols, int do_clear)
3162{
3163        int j, k ;
3164
3165        vc->vc_cols = cols;
3166        vc->vc_rows = rows;
3167        vc->vc_size_row = cols << 1;
3168        vc->vc_screenbuf_size = vc->vc_rows * vc->vc_size_row;
3169
3170        set_origin(vc);
3171        vc->vc_pos = vc->vc_origin;
3172        reset_vc(vc);
3173        for (j=k=0; j<16; j++) {
3174                vc->vc_palette[k++] = default_red[j] ;
3175                vc->vc_palette[k++] = default_grn[j] ;
3176                vc->vc_palette[k++] = default_blu[j] ;
3177        }
3178        vc->vc_def_color       = default_color;
3179        vc->vc_ulcolor         = default_underline_color;
3180        vc->vc_itcolor         = default_italic_color;
3181        vc->vc_halfcolor       = 0x08;   /* grey */
3182        init_waitqueue_head(&vc->paste_wait);
3183        reset_terminal(vc, do_clear);
3184}
3185
3186/*
3187 * This routine initializes console interrupts, and does nothing
3188 * else. If you want the screen to clear, call tty_write with
3189 * the appropriate escape-sequence.
3190 */
3191
3192static int __init con_init(void)
3193{
3194        const char *display_desc = NULL;
3195        struct vc_data *vc;
3196        unsigned int currcons = 0, i;
3197
3198        console_lock();
3199
3200        if (conswitchp)
3201                display_desc = conswitchp->con_startup();
3202        if (!display_desc) {
3203                fg_console = 0;
3204                console_unlock();
3205                return 0;
3206        }
3207
3208        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3209                struct con_driver *con_driver = &registered_con_driver[i];
3210
3211                if (con_driver->con == NULL) {
3212                        con_driver->con = conswitchp;
3213                        con_driver->desc = display_desc;
3214                        con_driver->flag = CON_DRIVER_FLAG_INIT;
3215                        con_driver->first = 0;
3216                        con_driver->last = MAX_NR_CONSOLES - 1;
3217                        break;
3218                }
3219        }
3220
3221        for (i = 0; i < MAX_NR_CONSOLES; i++)
3222                con_driver_map[i] = conswitchp;
3223
3224        if (blankinterval) {
3225                blank_state = blank_normal_wait;
3226                mod_timer(&console_timer, jiffies + (blankinterval * HZ));
3227        }
3228
3229        for (currcons = 0; currcons < MIN_NR_CONSOLES; currcons++) {
3230                vc_cons[currcons].d = vc = kzalloc(sizeof(struct vc_data), GFP_NOWAIT);
3231                INIT_WORK(&vc_cons[currcons].SAK_work, vc_SAK);
3232                tty_port_init(&vc->port);
3233                visual_init(vc, currcons, 1);
3234                vc->vc_screenbuf = kzalloc(vc->vc_screenbuf_size, GFP_NOWAIT);
3235                vc_init(vc, vc->vc_rows, vc->vc_cols,
3236                        currcons || !vc->vc_sw->con_save_screen);
3237        }
3238        currcons = fg_console = 0;
3239        master_display_fg = vc = vc_cons[currcons].d;
3240        set_origin(vc);
3241        save_screen(vc);
3242        gotoxy(vc, vc->vc_x, vc->vc_y);
3243        csi_J(vc, 0);
3244        update_screen(vc);
3245        pr_info("Console: %s %s %dx%d\n",
3246                vc->vc_can_do_color ? "colour" : "mono",
3247                display_desc, vc->vc_cols, vc->vc_rows);
3248        printable = 1;
3249
3250        console_unlock();
3251
3252#ifdef CONFIG_VT_CONSOLE
3253        register_console(&vt_console_driver);
3254#endif
3255        return 0;
3256}
3257console_initcall(con_init);
3258
3259static const struct tty_operations con_ops = {
3260        .install = con_install,
3261        .open = con_open,
3262        .close = con_close,
3263        .write = con_write,
3264        .write_room = con_write_room,
3265        .put_char = con_put_char,
3266        .flush_chars = con_flush_chars,
3267        .chars_in_buffer = con_chars_in_buffer,
3268        .ioctl = vt_ioctl,
3269#ifdef CONFIG_COMPAT
3270        .compat_ioctl = vt_compat_ioctl,
3271#endif
3272        .stop = con_stop,
3273        .start = con_start,
3274        .throttle = con_throttle,
3275        .unthrottle = con_unthrottle,
3276        .resize = vt_resize,
3277        .shutdown = con_shutdown,
3278        .cleanup = con_cleanup,
3279};
3280
3281static struct cdev vc0_cdev;
3282
3283static ssize_t show_tty_active(struct device *dev,
3284                                struct device_attribute *attr, char *buf)
3285{
3286        return sprintf(buf, "tty%d\n", fg_console + 1);
3287}
3288static DEVICE_ATTR(active, S_IRUGO, show_tty_active, NULL);
3289
3290static struct attribute *vt_dev_attrs[] = {
3291        &dev_attr_active.attr,
3292        NULL
3293};
3294
3295ATTRIBUTE_GROUPS(vt_dev);
3296
3297int __init vty_init(const struct file_operations *console_fops)
3298{
3299        cdev_init(&vc0_cdev, console_fops);
3300        if (cdev_add(&vc0_cdev, MKDEV(TTY_MAJOR, 0), 1) ||
3301            register_chrdev_region(MKDEV(TTY_MAJOR, 0), 1, "/dev/vc/0") < 0)
3302                panic("Couldn't register /dev/tty0 driver\n");
3303        tty0dev = device_create_with_groups(tty_class, NULL,
3304                                            MKDEV(TTY_MAJOR, 0), NULL,
3305                                            vt_dev_groups, "tty0");
3306        if (IS_ERR(tty0dev))
3307                tty0dev = NULL;
3308
3309        vcs_init();
3310
3311        console_driver = alloc_tty_driver(MAX_NR_CONSOLES);
3312        if (!console_driver)
3313                panic("Couldn't allocate console driver\n");
3314
3315        console_driver->name = "tty";
3316        console_driver->name_base = 1;
3317        console_driver->major = TTY_MAJOR;
3318        console_driver->minor_start = 1;
3319        console_driver->type = TTY_DRIVER_TYPE_CONSOLE;
3320        console_driver->init_termios = tty_std_termios;
3321        if (default_utf8)
3322                console_driver->init_termios.c_iflag |= IUTF8;
3323        console_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_RESET_TERMIOS;
3324        tty_set_operations(console_driver, &con_ops);
3325        if (tty_register_driver(console_driver))
3326                panic("Couldn't register console driver\n");
3327        kbd_init();
3328        console_map_init();
3329#ifdef CONFIG_MDA_CONSOLE
3330        mda_console_init();
3331#endif
3332        return 0;
3333}
3334
3335#ifndef VT_SINGLE_DRIVER
3336
3337static struct class *vtconsole_class;
3338
3339static int do_bind_con_driver(const struct consw *csw, int first, int last,
3340                           int deflt)
3341{
3342        struct module *owner = csw->owner;
3343        const char *desc = NULL;
3344        struct con_driver *con_driver;
3345        int i, j = -1, k = -1, retval = -ENODEV;
3346
3347        if (!try_module_get(owner))
3348                return -ENODEV;
3349
3350        WARN_CONSOLE_UNLOCKED();
3351
3352        /* check if driver is registered */
3353        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3354                con_driver = &registered_con_driver[i];
3355
3356                if (con_driver->con == csw) {
3357                        desc = con_driver->desc;
3358                        retval = 0;
3359                        break;
3360                }
3361        }
3362
3363        if (retval)
3364                goto err;
3365
3366        if (!(con_driver->flag & CON_DRIVER_FLAG_INIT)) {
3367                csw->con_startup();
3368                con_driver->flag |= CON_DRIVER_FLAG_INIT;
3369        }
3370
3371        if (deflt) {
3372                if (conswitchp)
3373                        module_put(conswitchp->owner);
3374
3375                __module_get(owner);
3376                conswitchp = csw;
3377        }
3378
3379        first = max(first, con_driver->first);
3380        last = min(last, con_driver->last);
3381
3382        for (i = first; i <= last; i++) {
3383                int old_was_color;
3384                struct vc_data *vc = vc_cons[i].d;
3385
3386                if (con_driver_map[i])
3387                        module_put(con_driver_map[i]->owner);
3388                __module_get(owner);
3389                con_driver_map[i] = csw;
3390
3391                if (!vc || !vc->vc_sw)
3392                        continue;
3393
3394                j = i;
3395
3396                if (con_is_visible(vc)) {
3397                        k = i;
3398                        save_screen(vc);
3399                }
3400
3401                old_was_color = vc->vc_can_do_color;
3402                vc->vc_sw->con_deinit(vc);
3403                vc->vc_origin = (unsigned long)vc->vc_screenbuf;
3404                visual_init(vc, i, 0);
3405                set_origin(vc);
3406                update_attr(vc);
3407
3408                /* If the console changed between mono <-> color, then
3409                 * the attributes in the screenbuf will be wrong.  The
3410                 * following resets all attributes to something sane.
3411                 */
3412                if (old_was_color != vc->vc_can_do_color)
3413                        clear_buffer_attributes(vc);
3414        }
3415
3416        pr_info("Console: switching ");
3417        if (!deflt)
3418                pr_cont("consoles %d-%d ", first + 1, last + 1);
3419        if (j >= 0) {
3420                struct vc_data *vc = vc_cons[j].d;
3421
3422                pr_cont("to %s %s %dx%d\n",
3423                        vc->vc_can_do_color ? "colour" : "mono",
3424                        desc, vc->vc_cols, vc->vc_rows);
3425
3426                if (k >= 0) {
3427                        vc = vc_cons[k].d;
3428                        update_screen(vc);
3429                }
3430        } else {
3431                pr_cont("to %s\n", desc);
3432        }
3433
3434        retval = 0;
3435err:
3436        module_put(owner);
3437        return retval;
3438};
3439
3440
3441#ifdef CONFIG_VT_HW_CONSOLE_BINDING
3442/* unlocked version of unbind_con_driver() */
3443int do_unbind_con_driver(const struct consw *csw, int first, int last, int deflt)
3444{
3445        struct module *owner = csw->owner;
3446        const struct consw *defcsw = NULL;
3447        struct con_driver *con_driver = NULL, *con_back = NULL;
3448        int i, retval = -ENODEV;
3449
3450        if (!try_module_get(owner))
3451                return -ENODEV;
3452
3453        WARN_CONSOLE_UNLOCKED();
3454
3455        /* check if driver is registered and if it is unbindable */
3456        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3457                con_driver = &registered_con_driver[i];
3458
3459                if (con_driver->con == csw &&
3460                    con_driver->flag & CON_DRIVER_FLAG_MODULE) {
3461                        retval = 0;
3462                        break;
3463                }
3464        }
3465
3466        if (retval)
3467                goto err;
3468
3469        retval = -ENODEV;
3470
3471        /* check if backup driver exists */
3472        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3473                con_back = &registered_con_driver[i];
3474
3475                if (con_back->con && con_back->con != csw) {
3476                        defcsw = con_back->con;
3477                        retval = 0;
3478                        break;
3479                }
3480        }
3481
3482        if (retval)
3483                goto err;
3484
3485        if (!con_is_bound(csw))
3486                goto err;
3487
3488        first = max(first, con_driver->first);
3489        last = min(last, con_driver->last);
3490
3491        for (i = first; i <= last; i++) {
3492                if (con_driver_map[i] == csw) {
3493                        module_put(csw->owner);
3494                        con_driver_map[i] = NULL;
3495                }
3496        }
3497
3498        if (!con_is_bound(defcsw)) {
3499                const struct consw *defconsw = conswitchp;
3500
3501                defcsw->con_startup();
3502                con_back->flag |= CON_DRIVER_FLAG_INIT;
3503                /*
3504                 * vgacon may change the default driver to point
3505                 * to dummycon, we restore it here...
3506                 */
3507                conswitchp = defconsw;
3508        }
3509
3510        if (!con_is_bound(csw))
3511                con_driver->flag &= ~CON_DRIVER_FLAG_INIT;
3512
3513        /* ignore return value, binding should not fail */
3514        do_bind_con_driver(defcsw, first, last, deflt);
3515err:
3516        module_put(owner);
3517        return retval;
3518
3519}
3520EXPORT_SYMBOL_GPL(do_unbind_con_driver);
3521
3522static int vt_bind(struct con_driver *con)
3523{
3524        const struct consw *defcsw = NULL, *csw = NULL;
3525        int i, more = 1, first = -1, last = -1, deflt = 0;
3526
3527        if (!con->con || !(con->flag & CON_DRIVER_FLAG_MODULE))
3528                goto err;
3529
3530        csw = con->con;
3531
3532        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3533                struct con_driver *con = &registered_con_driver[i];
3534
3535                if (con->con && !(con->flag & CON_DRIVER_FLAG_MODULE)) {
3536                        defcsw = con->con;
3537                        break;
3538                }
3539        }
3540
3541        if (!defcsw)
3542                goto err;
3543
3544        while (more) {
3545                more = 0;
3546
3547                for (i = con->first; i <= con->last; i++) {
3548                        if (con_driver_map[i] == defcsw) {
3549                                if (first == -1)
3550                                        first = i;
3551                                last = i;
3552                                more = 1;
3553                        } else if (first != -1)
3554                                break;
3555                }
3556
3557                if (first == 0 && last == MAX_NR_CONSOLES -1)
3558                        deflt = 1;
3559
3560                if (first != -1)
3561                        do_bind_con_driver(csw, first, last, deflt);
3562
3563                first = -1;
3564                last = -1;
3565                deflt = 0;
3566        }
3567
3568err:
3569        return 0;
3570}
3571
3572static int vt_unbind(struct con_driver *con)
3573{
3574        const struct consw *csw = NULL;
3575        int i, more = 1, first = -1, last = -1, deflt = 0;
3576        int ret;
3577
3578        if (!con->con || !(con->flag & CON_DRIVER_FLAG_MODULE))
3579                goto err;
3580
3581        csw = con->con;
3582
3583        while (more) {
3584                more = 0;
3585
3586                for (i = con->first; i <= con->last; i++) {
3587                        if (con_driver_map[i] == csw) {
3588                                if (first == -1)
3589                                        first = i;
3590                                last = i;
3591                                more = 1;
3592                        } else if (first != -1)
3593                                break;
3594                }
3595
3596                if (first == 0 && last == MAX_NR_CONSOLES -1)
3597                        deflt = 1;
3598
3599                if (first != -1) {
3600                        ret = do_unbind_con_driver(csw, first, last, deflt);
3601                        if (ret != 0)
3602                                return ret;
3603                }
3604
3605                first = -1;
3606                last = -1;
3607                deflt = 0;
3608        }
3609
3610err:
3611        return 0;
3612}
3613#else
3614static inline int vt_bind(struct con_driver *con)
3615{
3616        return 0;
3617}
3618static inline int vt_unbind(struct con_driver *con)
3619{
3620        return 0;
3621}
3622#endif /* CONFIG_VT_HW_CONSOLE_BINDING */
3623
3624static ssize_t store_bind(struct device *dev, struct device_attribute *attr,
3625                          const char *buf, size_t count)
3626{
3627        struct con_driver *con = dev_get_drvdata(dev);
3628        int bind = simple_strtoul(buf, NULL, 0);
3629
3630        console_lock();
3631
3632        if (bind)
3633                vt_bind(con);
3634        else
3635                vt_unbind(con);
3636
3637        console_unlock();
3638
3639        return count;
3640}
3641
3642static ssize_t show_bind(struct device *dev, struct device_attribute *attr,
3643                         char *buf)
3644{
3645        struct con_driver *con = dev_get_drvdata(dev);
3646        int bind = con_is_bound(con->con);
3647
3648        return snprintf(buf, PAGE_SIZE, "%i\n", bind);
3649}
3650
3651static ssize_t show_name(struct device *dev, struct device_attribute *attr,
3652                         char *buf)
3653{
3654        struct con_driver *con = dev_get_drvdata(dev);
3655
3656        return snprintf(buf, PAGE_SIZE, "%s %s\n",
3657                        (con->flag & CON_DRIVER_FLAG_MODULE) ? "(M)" : "(S)",
3658                         con->desc);
3659
3660}
3661
3662static DEVICE_ATTR(bind, S_IRUGO|S_IWUSR, show_bind, store_bind);
3663static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
3664
3665static struct attribute *con_dev_attrs[] = {
3666        &dev_attr_bind.attr,
3667        &dev_attr_name.attr,
3668        NULL
3669};
3670
3671ATTRIBUTE_GROUPS(con_dev);
3672
3673static int vtconsole_init_device(struct con_driver *con)
3674{
3675        con->flag |= CON_DRIVER_FLAG_ATTR;
3676        return 0;
3677}
3678
3679static void vtconsole_deinit_device(struct con_driver *con)
3680{
3681        con->flag &= ~CON_DRIVER_FLAG_ATTR;
3682}
3683
3684/**
3685 * con_is_bound - checks if driver is bound to the console
3686 * @csw: console driver
3687 *
3688 * RETURNS: zero if unbound, nonzero if bound
3689 *
3690 * Drivers can call this and if zero, they should release
3691 * all resources allocated on con_startup()
3692 */
3693int con_is_bound(const struct consw *csw)
3694{
3695        int i, bound = 0;
3696
3697        for (i = 0; i < MAX_NR_CONSOLES; i++) {
3698                if (con_driver_map[i] == csw) {
3699                        bound = 1;
3700                        break;
3701                }
3702        }
3703
3704        return bound;
3705}
3706EXPORT_SYMBOL(con_is_bound);
3707
3708/**
3709 * con_debug_enter - prepare the console for the kernel debugger
3710 * @sw: console driver
3711 *
3712 * Called when the console is taken over by the kernel debugger, this
3713 * function needs to save the current console state, then put the console
3714 * into a state suitable for the kernel debugger.
3715 *
3716 * RETURNS:
3717 * Zero on success, nonzero if a failure occurred when trying to prepare
3718 * the console for the debugger.
3719 */
3720int con_debug_enter(struct vc_data *vc)
3721{
3722        int ret = 0;
3723
3724        saved_fg_console = fg_console;
3725        saved_last_console = last_console;
3726        saved_want_console = want_console;
3727        saved_vc_mode = vc->vc_mode;
3728        saved_console_blanked = console_blanked;
3729        vc->vc_mode = KD_TEXT;
3730        console_blanked = 0;
3731        if (vc->vc_sw->con_debug_enter)
3732                ret = vc->vc_sw->con_debug_enter(vc);
3733#ifdef CONFIG_KGDB_KDB
3734        /* Set the initial LINES variable if it is not already set */
3735        if (vc->vc_rows < 999) {
3736                int linecount;
3737                char lns[4];
3738                const char *setargs[3] = {
3739                        "set",
3740                        "LINES",
3741                        lns,
3742                };
3743                if (kdbgetintenv(setargs[0], &linecount)) {
3744                        snprintf(lns, 4, "%i", vc->vc_rows);
3745                        kdb_set(2, setargs);
3746                }
3747        }
3748        if (vc->vc_cols < 999) {
3749                int colcount;
3750                char cols[4];
3751                const char *setargs[3] = {
3752                        "set",
3753                        "COLUMNS",
3754                        cols,
3755                };
3756                if (kdbgetintenv(setargs[0], &colcount)) {
3757                        snprintf(cols, 4, "%i", vc->vc_cols);
3758                        kdb_set(2, setargs);
3759                }
3760        }
3761#endif /* CONFIG_KGDB_KDB */
3762        return ret;
3763}
3764EXPORT_SYMBOL_GPL(con_debug_enter);
3765
3766/**
3767 * con_debug_leave - restore console state
3768 * @sw: console driver
3769 *
3770 * Restore the console state to what it was before the kernel debugger
3771 * was invoked.
3772 *
3773 * RETURNS:
3774 * Zero on success, nonzero if a failure occurred when trying to restore
3775 * the console.
3776 */
3777int con_debug_leave(void)
3778{
3779        struct vc_data *vc;
3780        int ret = 0;
3781
3782        fg_console = saved_fg_console;
3783        last_console = saved_last_console;
3784        want_console = saved_want_console;
3785        console_blanked = saved_console_blanked;
3786        vc_cons[fg_console].d->vc_mode = saved_vc_mode;
3787
3788        vc = vc_cons[fg_console].d;
3789        if (vc->vc_sw->con_debug_leave)
3790                ret = vc->vc_sw->con_debug_leave(vc);
3791        return ret;
3792}
3793EXPORT_SYMBOL_GPL(con_debug_leave);
3794
3795static int do_register_con_driver(const struct consw *csw, int first, int last)
3796{
3797        struct module *owner = csw->owner;
3798        struct con_driver *con_driver;
3799        const char *desc;
3800        int i, retval;
3801
3802        WARN_CONSOLE_UNLOCKED();
3803
3804        if (!try_module_get(owner))
3805                return -ENODEV;
3806
3807        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3808                con_driver = &registered_con_driver[i];
3809
3810                /* already registered */
3811                if (con_driver->con == csw) {
3812                        retval = -EBUSY;
3813                        goto err;
3814                }
3815        }
3816
3817        desc = csw->con_startup();
3818        if (!desc) {
3819                retval = -ENODEV;
3820                goto err;
3821        }
3822
3823        retval = -EINVAL;
3824
3825        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3826                con_driver = &registered_con_driver[i];
3827
3828                if (con_driver->con == NULL &&
3829                    !(con_driver->flag & CON_DRIVER_FLAG_ZOMBIE)) {
3830                        con_driver->con = csw;
3831                        con_driver->desc = desc;
3832                        con_driver->node = i;
3833                        con_driver->flag = CON_DRIVER_FLAG_MODULE |
3834                                           CON_DRIVER_FLAG_INIT;
3835                        con_driver->first = first;
3836                        con_driver->last = last;
3837                        retval = 0;
3838                        break;
3839                }
3840        }
3841
3842        if (retval)
3843                goto err;
3844
3845        con_driver->dev =
3846                device_create_with_groups(vtconsole_class, NULL,
3847                                          MKDEV(0, con_driver->node),
3848                                          con_driver, con_dev_groups,
3849                                          "vtcon%i", con_driver->node);
3850        if (IS_ERR(con_driver->dev)) {
3851                pr_warn("Unable to create device for %s; errno = %ld\n",
3852                        con_driver->desc, PTR_ERR(con_driver->dev));
3853                con_driver->dev = NULL;
3854        } else {
3855                vtconsole_init_device(con_driver);
3856        }
3857
3858err:
3859        module_put(owner);
3860        return retval;
3861}
3862
3863
3864/**
3865 * do_unregister_con_driver - unregister console driver from console layer
3866 * @csw: console driver
3867 *
3868 * DESCRIPTION: All drivers that registers to the console layer must
3869 * call this function upon exit, or if the console driver is in a state
3870 * where it won't be able to handle console services, such as the
3871 * framebuffer console without loaded framebuffer drivers.
3872 *
3873 * The driver must unbind first prior to unregistration.
3874 */
3875int do_unregister_con_driver(const struct consw *csw)
3876{
3877        int i;
3878
3879        /* cannot unregister a bound driver */
3880        if (con_is_bound(csw))
3881                return -EBUSY;
3882
3883        if (csw == conswitchp)
3884                return -EINVAL;
3885
3886        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3887                struct con_driver *con_driver = &registered_con_driver[i];
3888
3889                if (con_driver->con == csw) {
3890                        /*
3891                         * Defer the removal of the sysfs entries since that
3892                         * will acquire the kernfs s_active lock and we can't
3893                         * acquire this lock while holding the console lock:
3894                         * the unbind sysfs entry imposes already the opposite
3895                         * order. Reset con already here to prevent any later
3896                         * lookup to succeed and mark this slot as zombie, so
3897                         * it won't get reused until we complete the removal
3898                         * in the deferred work.
3899                         */
3900                        con_driver->con = NULL;
3901                        con_driver->flag = CON_DRIVER_FLAG_ZOMBIE;
3902                        schedule_work(&con_driver_unregister_work);
3903
3904                        return 0;
3905                }
3906        }
3907
3908        return -ENODEV;
3909}
3910EXPORT_SYMBOL_GPL(do_unregister_con_driver);
3911
3912static void con_driver_unregister_callback(struct work_struct *ignored)
3913{
3914        int i;
3915
3916        console_lock();
3917
3918        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3919                struct con_driver *con_driver = &registered_con_driver[i];
3920
3921                if (!(con_driver->flag & CON_DRIVER_FLAG_ZOMBIE))
3922                        continue;
3923
3924                console_unlock();
3925
3926                vtconsole_deinit_device(con_driver);
3927                device_destroy(vtconsole_class, MKDEV(0, con_driver->node));
3928
3929                console_lock();
3930
3931                if (WARN_ON_ONCE(con_driver->con))
3932                        con_driver->con = NULL;
3933                con_driver->desc = NULL;
3934                con_driver->dev = NULL;
3935                con_driver->node = 0;
3936                WARN_ON_ONCE(con_driver->flag != CON_DRIVER_FLAG_ZOMBIE);
3937                con_driver->flag = 0;
3938                con_driver->first = 0;
3939                con_driver->last = 0;
3940        }
3941
3942        console_unlock();
3943}
3944
3945/*
3946 *      If we support more console drivers, this function is used
3947 *      when a driver wants to take over some existing consoles
3948 *      and become default driver for newly opened ones.
3949 *
3950 *      do_take_over_console is basically a register followed by unbind
3951 */
3952int do_take_over_console(const struct consw *csw, int first, int last, int deflt)
3953{
3954        int err;
3955
3956        err = do_register_con_driver(csw, first, last);
3957        /*
3958         * If we get an busy error we still want to bind the console driver
3959         * and return success, as we may have unbound the console driver
3960         * but not unregistered it.
3961         */
3962        if (err == -EBUSY)
3963                err = 0;
3964        if (!err)
3965                do_bind_con_driver(csw, first, last, deflt);
3966
3967        return err;
3968}
3969EXPORT_SYMBOL_GPL(do_take_over_console);
3970
3971
3972/*
3973 * give_up_console is a wrapper to unregister_con_driver. It will only
3974 * work if driver is fully unbound.
3975 */
3976void give_up_console(const struct consw *csw)
3977{
3978        console_lock();
3979        do_unregister_con_driver(csw);
3980        console_unlock();
3981}
3982
3983static int __init vtconsole_class_init(void)
3984{
3985        int i;
3986
3987        vtconsole_class = class_create(THIS_MODULE, "vtconsole");
3988        if (IS_ERR(vtconsole_class)) {
3989                pr_warn("Unable to create vt console class; errno = %ld\n",
3990                        PTR_ERR(vtconsole_class));
3991                vtconsole_class = NULL;
3992        }
3993
3994        /* Add system drivers to sysfs */
3995        for (i = 0; i < MAX_NR_CON_DRIVER; i++) {
3996                struct con_driver *con = &registered_con_driver[i];
3997
3998                if (con->con && !con->dev) {
3999                        con->dev =
4000                                device_create_with_groups(vtconsole_class, NULL,
4001                                                          MKDEV(0, con->node),
4002                                                          con, con_dev_groups,
4003                                                          "vtcon%i", con->node);
4004
4005                        if (IS_ERR(con->dev)) {
4006                                pr_warn("Unable to create device for %s; errno = %ld\n",
4007                                        con->desc, PTR_ERR(con->dev));
4008                                con->dev = NULL;
4009                        } else {
4010                                vtconsole_init_device(con);
4011                        }
4012                }
4013        }
4014
4015        return 0;
4016}
4017postcore_initcall(vtconsole_class_init);
4018
4019#endif
4020
4021/*
4022 *      Screen blanking
4023 */
4024
4025static int set_vesa_blanking(char __user *p)
4026{
4027        unsigned int mode;
4028
4029        if (get_user(mode, p + 1))
4030                return -EFAULT;
4031
4032        vesa_blank_mode = (mode < 4) ? mode : 0;
4033        return 0;
4034}
4035
4036void do_blank_screen(int entering_gfx)
4037{
4038        struct vc_data *vc = vc_cons[fg_console].d;
4039        int i;
4040
4041        WARN_CONSOLE_UNLOCKED();
4042
4043        if (console_blanked) {
4044                if (blank_state == blank_vesa_wait) {
4045                        blank_state = blank_off;
4046                        vc->vc_sw->con_blank(vc, vesa_blank_mode + 1, 0);
4047                }
4048                return;
4049        }
4050
4051        /* entering graphics mode? */
4052        if (entering_gfx) {
4053                hide_cursor(vc);
4054                save_screen(vc);
4055                vc->vc_sw->con_blank(vc, -1, 1);
4056                console_blanked = fg_console + 1;
4057                blank_state = blank_off;
4058                set_origin(vc);
4059                return;
4060        }
4061
4062        if (blank_state != blank_normal_wait)
4063                return;
4064        blank_state = blank_off;
4065
4066        /* don't blank graphics */
4067        if (vc->vc_mode != KD_TEXT) {
4068                console_blanked = fg_console + 1;
4069                return;
4070        }
4071
4072        hide_cursor(vc);
4073        del_timer_sync(&console_timer);
4074        blank_timer_expired = 0;
4075
4076        save_screen(vc);
4077        /* In case we need to reset origin, blanking hook returns 1 */
4078        i = vc->vc_sw->con_blank(vc, vesa_off_interval ? 1 : (vesa_blank_mode + 1), 0);
4079        console_blanked = fg_console + 1;
4080        if (i)
4081                set_origin(vc);
4082
4083        if (console_blank_hook && console_blank_hook(1))
4084                return;
4085
4086        if (vesa_off_interval && vesa_blank_mode) {
4087                blank_state = blank_vesa_wait;
4088                mod_timer(&console_timer, jiffies + vesa_off_interval);
4089        }
4090        vt_event_post(VT_EVENT_BLANK, vc->vc_num, vc->vc_num);
4091}
4092EXPORT_SYMBOL(do_blank_screen);
4093
4094/*
4095 * Called by timer as well as from vt_console_driver
4096 */
4097void do_unblank_screen(int leaving_gfx)
4098{
4099        struct vc_data *vc;
4100
4101        /* This should now always be called from a "sane" (read: can schedule)
4102         * context for the sake of the low level drivers, except in the special
4103         * case of oops_in_progress
4104         */
4105        if (!oops_in_progress)
4106                might_sleep();
4107
4108        WARN_CONSOLE_UNLOCKED();
4109
4110        ignore_poke = 0;
4111        if (!console_blanked)
4112                return;
4113        if (!vc_cons_allocated(fg_console)) {
4114                /* impossible */
4115                pr_warn("unblank_screen: tty %d not allocated ??\n",
4116                        fg_console + 1);
4117                return;
4118        }
4119        vc = vc_cons[fg_console].d;
4120        if (vc->vc_mode != KD_TEXT)
4121                return; /* but leave console_blanked != 0 */
4122
4123        if (blankinterval) {
4124                mod_timer(&console_timer, jiffies + (blankinterval * HZ));
4125                blank_state = blank_normal_wait;
4126        }
4127
4128        console_blanked = 0;
4129        if (vc->vc_sw->con_blank(vc, 0, leaving_gfx))
4130                /* Low-level driver cannot restore -> do it ourselves */
4131                update_screen(vc);
4132        if (console_blank_hook)
4133                console_blank_hook(0);
4134        set_palette(vc);
4135        set_cursor(vc);
4136        vt_event_post(VT_EVENT_UNBLANK, vc->vc_num, vc->vc_num);
4137}
4138EXPORT_SYMBOL(do_unblank_screen);
4139
4140/*
4141 * This is called by the outside world to cause a forced unblank, mostly for
4142 * oopses. Currently, I just call do_unblank_screen(0), but we could eventually
4143 * call it with 1 as an argument and so force a mode restore... that may kill
4144 * X or at least garbage the screen but would also make the Oops visible...
4145 */
4146void unblank_screen(void)
4147{
4148        do_unblank_screen(0);
4149}
4150
4151/*
4152 * We defer the timer blanking to work queue so it can take the console mutex
4153 * (console operations can still happen at irq time, but only from printk which
4154 * has the console mutex. Not perfect yet, but better than no locking
4155 */
4156static void blank_screen_t(struct timer_list *unused)
4157{
4158        blank_timer_expired = 1;
4159        schedule_work(&console_work);
4160}
4161
4162void poke_blanked_console(void)
4163{
4164        WARN_CONSOLE_UNLOCKED();
4165
4166        /* Add this so we quickly catch whoever might call us in a non
4167         * safe context. Nowadays, unblank_screen() isn't to be called in
4168         * atomic contexts and is allowed to schedule (with the special case
4169         * of oops_in_progress, but that isn't of any concern for this
4170         * function. --BenH.
4171         */
4172        might_sleep();
4173
4174        /* This isn't perfectly race free, but a race here would be mostly harmless,
4175         * at worse, we'll do a spurrious blank and it's unlikely
4176         */
4177        del_timer(&console_timer);
4178        blank_timer_expired = 0;
4179
4180        if (ignore_poke || !vc_cons[fg_console].d || vc_cons[fg_console].d->vc_mode == KD_GRAPHICS)
4181                return;
4182        if (console_blanked)
4183                unblank_screen();
4184        else if (blankinterval) {
4185                mod_timer(&console_timer, jiffies + (blankinterval * HZ));
4186                blank_state = blank_normal_wait;
4187        }
4188}
4189
4190/*
4191 *      Palettes
4192 */
4193
4194static void set_palette(struct vc_data *vc)
4195{
4196        WARN_CONSOLE_UNLOCKED();
4197
4198        if (vc->vc_mode != KD_GRAPHICS && vc->vc_sw->con_set_palette)
4199                vc->vc_sw->con_set_palette(vc, color_table);
4200}
4201
4202/*
4203 * Load palette into the DAC registers. arg points to a colour
4204 * map, 3 bytes per colour, 16 colours, range from 0 to 255.
4205 */
4206
4207int con_set_cmap(unsigned char __user *arg)
4208{
4209        int i, j, k;
4210        unsigned char colormap[3*16];
4211
4212        if (copy_from_user(colormap, arg, sizeof(colormap)))
4213                return -EFAULT;
4214
4215        console_lock();
4216        for (i = k = 0; i < 16; i++) {
4217                default_red[i] = colormap[k++];
4218                default_grn[i] = colormap[k++];
4219                default_blu[i] = colormap[k++];
4220        }
4221        for (i = 0; i < MAX_NR_CONSOLES; i++) {
4222                if (!vc_cons_allocated(i))
4223                        continue;
4224                for (j = k = 0; j < 16; j++) {
4225                        vc_cons[i].d->vc_palette[k++] = default_red[j];
4226                        vc_cons[i].d->vc_palette[k++] = default_grn[j];
4227                        vc_cons[i].d->vc_palette[k++] = default_blu[j];
4228                }
4229                set_palette(vc_cons[i].d);
4230        }
4231        console_unlock();
4232
4233        return 0;
4234}
4235
4236int con_get_cmap(unsigned char __user *arg)
4237{
4238        int i, k;
4239        unsigned char colormap[3*16];
4240
4241        console_lock();
4242        for (i = k = 0; i < 16; i++) {
4243                colormap[k++] = default_red[i];
4244                colormap[k++] = default_grn[i];
4245                colormap[k++] = default_blu[i];
4246        }
4247        console_unlock();
4248
4249        if (copy_to_user(arg, colormap, sizeof(colormap)))
4250                return -EFAULT;
4251
4252        return 0;
4253}
4254
4255void reset_palette(struct vc_data *vc)
4256{
4257        int j, k;
4258        for (j=k=0; j<16; j++) {
4259                vc->vc_palette[k++] = default_red[j];
4260                vc->vc_palette[k++] = default_grn[j];
4261                vc->vc_palette[k++] = default_blu[j];
4262        }
4263        set_palette(vc);
4264}
4265
4266/*
4267 *  Font switching
4268 *
4269 *  Currently we only support fonts up to 32 pixels wide, at a maximum height
4270 *  of 32 pixels. Userspace fontdata is stored with 32 bytes (shorts/ints, 
4271 *  depending on width) reserved for each character which is kinda wasty, but 
4272 *  this is done in order to maintain compatibility with the EGA/VGA fonts. It 
4273 *  is up to the actual low-level console-driver convert data into its favorite
4274 *  format (maybe we should add a `fontoffset' field to the `display'
4275 *  structure so we won't have to convert the fontdata all the time.
4276 *  /Jes
4277 */
4278
4279#define max_font_size 65536
4280
4281static int con_font_get(struct vc_data *vc, struct console_font_op *op)
4282{
4283        struct console_font font;
4284        int rc = -EINVAL;
4285        int c;
4286
4287        if (op->data) {
4288                font.data = kmalloc(max_font_size, GFP_KERNEL);
4289                if (!font.data)
4290                        return -ENOMEM;
4291        } else
4292                font.data = NULL;
4293
4294        console_lock();
4295        if (vc->vc_mode != KD_TEXT)
4296                rc = -EINVAL;
4297        else if (vc->vc_sw->con_font_get)
4298                rc = vc->vc_sw->con_font_get(vc, &font);
4299        else
4300                rc = -ENOSYS;
4301        console_unlock();
4302
4303        if (rc)
4304                goto out;
4305
4306        c = (font.width+7)/8 * 32 * font.charcount;
4307
4308        if (op->data && font.charcount > op->charcount)
4309                rc = -ENOSPC;
4310        if (!(op->flags & KD_FONT_FLAG_OLD)) {
4311                if (font.width > op->width || font.height > op->height) 
4312                        rc = -ENOSPC;
4313        } else {
4314                if (font.width != 8)
4315                        rc = -EIO;
4316                else if ((op->height && font.height > op->height) ||
4317                         font.height > 32)
4318                        rc = -ENOSPC;
4319        }
4320        if (rc)
4321                goto out;
4322
4323        op->height = font.height;
4324        op->width = font.width;
4325        op->charcount = font.charcount;
4326
4327        if (op->data && copy_to_user(op->data, font.data, c))
4328                rc = -EFAULT;
4329
4330out:
4331        kfree(font.data);
4332        return rc;
4333}
4334
4335static int con_font_set(struct vc_data *vc, struct console_font_op *op)
4336{
4337        struct console_font font;
4338        int rc = -EINVAL;
4339        int size;
4340
4341        if (vc->vc_mode != KD_TEXT)
4342                return -EINVAL;
4343        if (!op->data)
4344                return -EINVAL;
4345        if (op->charcount > 512)
4346                return -EINVAL;
4347        if (op->width <= 0 || op->width > 32 || op->height > 32)
4348                return -EINVAL;
4349        size = (op->width+7)/8 * 32 * op->charcount;
4350        if (size > max_font_size)
4351                return -ENOSPC;
4352
4353        font.data = memdup_user(op->data, size);
4354        if (IS_ERR(font.data))
4355                return PTR_ERR(font.data);
4356
4357        if (!op->height) {              /* Need to guess font height [compat] */
4358                int h, i;
4359                u8 *charmap = font.data;
4360
4361                /*
4362                 * If from KDFONTOP ioctl, don't allow things which can be done
4363                 * in userland,so that we can get rid of this soon
4364                 */
4365                if (!(op->flags & KD_FONT_FLAG_OLD)) {
4366                        kfree(font.data);
4367                        return -EINVAL;
4368                }
4369
4370                for (h = 32; h > 0; h--)
4371                        for (i = 0; i < op->charcount; i++)
4372                                if (charmap[32*i+h-1])
4373                                        goto nonzero;
4374
4375                kfree(font.data);
4376                return -EINVAL;
4377
4378        nonzero:
4379                op->height = h;
4380        }
4381
4382        font.charcount = op->charcount;
4383        font.width = op->width;
4384        font.height = op->height;
4385
4386        console_lock();
4387        if (vc->vc_mode != KD_TEXT)
4388                rc = -EINVAL;
4389        else if (vc->vc_sw->con_font_set)
4390                rc = vc->vc_sw->con_font_set(vc, &font, op->flags);
4391        else
4392                rc = -ENOSYS;
4393        console_unlock();
4394        kfree(font.data);
4395        return rc;
4396}
4397
4398static int con_font_default(struct vc_data *vc, struct console_font_op *op)
4399{
4400        struct console_font font = {.width = op->width, .height = op->height};
4401        char name[MAX_FONT_NAME];
4402        char *s = name;
4403        int rc;
4404
4405
4406        if (!op->data)
4407                s = NULL;
4408        else if (strncpy_from_user(name, op->data, MAX_FONT_NAME - 1) < 0)
4409                return -EFAULT;
4410        else
4411                name[MAX_FONT_NAME - 1] = 0;
4412
4413        console_lock();
4414        if (vc->vc_mode != KD_TEXT) {
4415                console_unlock();
4416                return -EINVAL;
4417        }
4418        if (vc->vc_sw->con_font_default)
4419                rc = vc->vc_sw->con_font_default(vc, &font, s);
4420        else
4421                rc = -ENOSYS;
4422        console_unlock();
4423        if (!rc) {
4424                op->width = font.width;
4425                op->height = font.height;
4426        }
4427        return rc;
4428}
4429
4430int con_font_op(struct vc_data *vc, struct console_font_op *op)
4431{
4432        switch (op->op) {
4433        case KD_FONT_OP_SET:
4434                return con_font_set(vc, op);
4435        case KD_FONT_OP_GET:
4436                return con_font_get(vc, op);
4437        case KD_FONT_OP_SET_DEFAULT:
4438                return con_font_default(vc, op);
4439        case KD_FONT_OP_COPY:
4440                /* was buggy and never really used */
4441                return -EINVAL;
4442        }
4443        return -ENOSYS;
4444}
4445
4446/*
4447 *      Interface exported to selection and vcs.
4448 */
4449
4450/* used by selection */
4451u16 screen_glyph(struct vc_data *vc, int offset)
4452{
4453        u16 w = scr_readw(screenpos(vc, offset, 1));
4454        u16 c = w & 0xff;
4455
4456        if (w & vc->vc_hi_font_mask)
4457                c |= 0x100;
4458        return c;
4459}
4460EXPORT_SYMBOL_GPL(screen_glyph);
4461
4462u32 screen_glyph_unicode(struct vc_data *vc, int n)
4463{
4464        struct uni_screen *uniscr = get_vc_uniscr(vc);
4465
4466        if (uniscr)
4467                return uniscr->lines[n / vc->vc_cols][n % vc->vc_cols];
4468        return inverse_translate(vc, screen_glyph(vc, n * 2), 1);
4469}
4470EXPORT_SYMBOL_GPL(screen_glyph_unicode);
4471
4472/* used by vcs - note the word offset */
4473unsigned short *screen_pos(struct vc_data *vc, int w_offset, int viewed)
4474{
4475        return screenpos(vc, 2 * w_offset, viewed);
4476}
4477EXPORT_SYMBOL_GPL(screen_pos);
4478
4479void getconsxy(struct vc_data *vc, unsigned char *p)
4480{
4481        p[0] = vc->vc_x;
4482        p[1] = vc->vc_y;
4483}
4484
4485void putconsxy(struct vc_data *vc, unsigned char *p)
4486{
4487        hide_cursor(vc);
4488        gotoxy(vc, p[0], p[1]);
4489        set_cursor(vc);
4490}
4491
4492u16 vcs_scr_readw(struct vc_data *vc, const u16 *org)
4493{
4494        if ((unsigned long)org == vc->vc_pos && softcursor_original != -1)
4495                return softcursor_original;
4496        return scr_readw(org);
4497}
4498
4499void vcs_scr_writew(struct vc_data *vc, u16 val, u16 *org)
4500{
4501        scr_writew(val, org);
4502        if ((unsigned long)org == vc->vc_pos) {
4503                softcursor_original = -1;
4504                add_softcursor(vc);
4505        }
4506}
4507
4508void vcs_scr_updated(struct vc_data *vc)
4509{
4510        notify_update(vc);
4511}
4512
4513void vc_scrolldelta_helper(struct vc_data *c, int lines,
4514                unsigned int rolled_over, void *base, unsigned int size)
4515{
4516        unsigned long ubase = (unsigned long)base;
4517        ptrdiff_t scr_end = (void *)c->vc_scr_end - base;
4518        ptrdiff_t vorigin = (void *)c->vc_visible_origin - base;
4519        ptrdiff_t origin = (void *)c->vc_origin - base;
4520        int margin = c->vc_size_row * 4;
4521        int from, wrap, from_off, avail;
4522
4523        /* Turn scrollback off */
4524        if (!lines) {
4525                c->vc_visible_origin = c->vc_origin;
4526                return;
4527        }
4528
4529        /* Do we have already enough to allow jumping from 0 to the end? */
4530        if (rolled_over > scr_end + margin) {
4531                from = scr_end;
4532                wrap = rolled_over + c->vc_size_row;
4533        } else {
4534                from = 0;
4535                wrap = size;
4536        }
4537
4538        from_off = (vorigin - from + wrap) % wrap + lines * c->vc_size_row;
4539        avail = (origin - from + wrap) % wrap;
4540
4541        /* Only a little piece would be left? Show all incl. the piece! */
4542        if (avail < 2 * margin)
4543                margin = 0;
4544        if (from_off < margin)
4545                from_off = 0;
4546        if (from_off > avail - margin)
4547                from_off = avail;
4548
4549        c->vc_visible_origin = ubase + (from + from_off) % wrap;
4550}
4551EXPORT_SYMBOL_GPL(vc_scrolldelta_helper);
4552
4553/*
4554 *      Visible symbols for modules
4555 */
4556
4557EXPORT_SYMBOL(color_table);
4558EXPORT_SYMBOL(default_red);
4559EXPORT_SYMBOL(default_grn);
4560EXPORT_SYMBOL(default_blu);
4561EXPORT_SYMBOL(update_region);
4562EXPORT_SYMBOL(redraw_screen);
4563EXPORT_SYMBOL(vc_resize);
4564EXPORT_SYMBOL(fg_console);
4565EXPORT_SYMBOL(console_blank_hook);
4566EXPORT_SYMBOL(console_blanked);
4567EXPORT_SYMBOL(vc_cons);
4568EXPORT_SYMBOL(global_cursor_default);
4569#ifndef VT_SINGLE_DRIVER
4570EXPORT_SYMBOL(give_up_console);
4571#endif
4572