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