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