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