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