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