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