File Index
Files and directories
Sign in
FILE

vt.c

File preview with syntax highlighting.

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