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