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