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