Merge tag 'efi-2020-07-rc6' of https://gitlab.denx.de/u-boot/custodians/u-boot-efi
[oweals/u-boot.git] / lib / efi_loader / efi_console.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  EFI application console interface
4  *
5  *  Copyright (c) 2016 Alexander Graf
6  */
7
8 #include <common.h>
9 #include <charset.h>
10 #include <malloc.h>
11 #include <time.h>
12 #include <dm/device.h>
13 #include <efi_loader.h>
14 #include <env.h>
15 #include <stdio_dev.h>
16 #include <video_console.h>
17
18 #define EFI_COUT_MODE_2 2
19 #define EFI_MAX_COUT_MODE 3
20
21 struct cout_mode {
22         unsigned long columns;
23         unsigned long rows;
24         int present;
25 };
26
27 static struct cout_mode efi_cout_modes[] = {
28         /* EFI Mode 0 is 80x25 and always present */
29         {
30                 .columns = 80,
31                 .rows = 25,
32                 .present = 1,
33         },
34         /* EFI Mode 1 is always 80x50 */
35         {
36                 .columns = 80,
37                 .rows = 50,
38                 .present = 0,
39         },
40         /* Value are unknown until we query the console */
41         {
42                 .columns = 0,
43                 .rows = 0,
44                 .present = 0,
45         },
46 };
47
48 const efi_guid_t efi_guid_text_input_ex_protocol =
49                         EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID;
50 const efi_guid_t efi_guid_text_input_protocol =
51                         EFI_SIMPLE_TEXT_INPUT_PROTOCOL_GUID;
52 const efi_guid_t efi_guid_text_output_protocol =
53                         EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL_GUID;
54
55 #define cESC '\x1b'
56 #define ESC "\x1b"
57
58 /* Default to mode 0 */
59 static struct simple_text_output_mode efi_con_mode = {
60         .max_mode = 1,
61         .mode = 0,
62         .attribute = 0,
63         .cursor_column = 0,
64         .cursor_row = 0,
65         .cursor_visible = 1,
66 };
67
68 static int term_get_char(s32 *c)
69 {
70         u64 timeout;
71
72         /* Wait up to 100 ms for a character */
73         timeout = timer_get_us() + 100000;
74
75         while (!tstc())
76                 if (timer_get_us() > timeout)
77                         return 1;
78
79         *c = getc();
80         return 0;
81 }
82
83 /**
84  * Receive and parse a reply from the terminal.
85  *
86  * @n:          array of return values
87  * @num:        number of return values expected
88  * @end_char:   character indicating end of terminal message
89  * Return:      non-zero indicates error
90  */
91 static int term_read_reply(int *n, int num, char end_char)
92 {
93         s32 c;
94         int i = 0;
95
96         if (term_get_char(&c) || c != cESC)
97                 return -1;
98
99         if (term_get_char(&c) || c != '[')
100                 return -1;
101
102         n[0] = 0;
103         while (1) {
104                 if (!term_get_char(&c)) {
105                         if (c == ';') {
106                                 i++;
107                                 if (i >= num)
108                                         return -1;
109                                 n[i] = 0;
110                                 continue;
111                         } else if (c == end_char) {
112                                 break;
113                         } else if (c > '9' || c < '0') {
114                                 return -1;
115                         }
116
117                         /* Read one more decimal position */
118                         n[i] *= 10;
119                         n[i] += c - '0';
120                 } else {
121                         return -1;
122                 }
123         }
124         if (i != num - 1)
125                 return -1;
126
127         return 0;
128 }
129
130 /**
131  * efi_cout_output_string() - write Unicode string to console
132  *
133  * This function implements the OutputString service of the simple text output
134  * protocol. See the Unified Extensible Firmware Interface (UEFI) specification
135  * for details.
136  *
137  * @this:       simple text output protocol
138  * @string:     u16 string
139  * Return:      status code
140  */
141 static efi_status_t EFIAPI efi_cout_output_string(
142                         struct efi_simple_text_output_protocol *this,
143                         const efi_string_t string)
144 {
145         struct simple_text_output_mode *con = &efi_con_mode;
146         struct cout_mode *mode = &efi_cout_modes[con->mode];
147         char *buf, *pos;
148         u16 *p;
149         efi_status_t ret = EFI_SUCCESS;
150
151         EFI_ENTRY("%p, %p", this, string);
152
153         if (!this || !string) {
154                 ret = EFI_INVALID_PARAMETER;
155                 goto out;
156         }
157
158         buf = malloc(utf16_utf8_strlen(string) + 1);
159         if (!buf) {
160                 ret = EFI_OUT_OF_RESOURCES;
161                 goto out;
162         }
163         pos = buf;
164         utf16_utf8_strcpy(&pos, string);
165         fputs(stdout, buf);
166         free(buf);
167
168         /*
169          * Update the cursor position.
170          *
171          * The UEFI spec provides advance rules for U+0000, U+0008, U+000A,
172          * and U000D. All other control characters are ignored. Any non-control
173          * character increase the column by one.
174          */
175         for (p = string; *p; ++p) {
176                 switch (*p) {
177                 case '\b':      /* U+0008, backspace */
178                         if (con->cursor_column)
179                                 con->cursor_column--;
180                         break;
181                 case '\n':      /* U+000A, newline */
182                         con->cursor_column = 0;
183                         con->cursor_row++;
184                         break;
185                 case '\r':      /* U+000D, carriage-return */
186                         con->cursor_column = 0;
187                         break;
188                 case 0xd800 ... 0xdbff:
189                         /*
190                          * Ignore high surrogates, we do not want to count a
191                          * Unicode character twice.
192                          */
193                         break;
194                 default:
195                         /* Exclude control codes */
196                         if (*p > 0x1f)
197                                 con->cursor_column++;
198                         break;
199                 }
200                 if (con->cursor_column >= mode->columns) {
201                         con->cursor_column = 0;
202                         con->cursor_row++;
203                 }
204                 /*
205                  * When we exceed the row count the terminal will scroll up one
206                  * line. We have to adjust the cursor position.
207                  */
208                 if (con->cursor_row >= mode->rows && con->cursor_row)
209                         con->cursor_row--;
210         }
211
212 out:
213         return EFI_EXIT(ret);
214 }
215
216 /**
217  * efi_cout_test_string() - test writing Unicode string to console
218  *
219  * This function implements the TestString service of the simple text output
220  * protocol. See the Unified Extensible Firmware Interface (UEFI) specification
221  * for details.
222  *
223  * As in OutputString we simply convert UTF-16 to UTF-8 there are no unsupported
224  * code points and we can always return EFI_SUCCESS.
225  *
226  * @this:       simple text output protocol
227  * @string:     u16 string
228  * Return:      status code
229  */
230 static efi_status_t EFIAPI efi_cout_test_string(
231                         struct efi_simple_text_output_protocol *this,
232                         const efi_string_t string)
233 {
234         EFI_ENTRY("%p, %p", this, string);
235         return EFI_EXIT(EFI_SUCCESS);
236 }
237
238 /**
239  * cout_mode_matches() - check if mode has given terminal size
240  *
241  * @mode:       text mode
242  * @rows:       number of rows
243  * @cols:       number of columns
244  * Return:      true if number of rows and columns matches the mode and
245  *              the mode is present
246  */
247 static bool cout_mode_matches(struct cout_mode *mode, int rows, int cols)
248 {
249         if (!mode->present)
250                 return false;
251
252         return (mode->rows == rows) && (mode->columns == cols);
253 }
254
255 /**
256  * query_console_serial() - query console size
257  *
258  * When using a serial console or the net console we can only devise the
259  * terminal size by querying the terminal using ECMA-48 control sequences.
260  *
261  * @rows:       pointer to return number of rows
262  * @cols:       pointer to return number of columns
263  * Returns:     0 on success
264  */
265 static int query_console_serial(int *rows, int *cols)
266 {
267         int ret = 0;
268         int n[2];
269
270         /* Empty input buffer */
271         while (tstc())
272                 getc();
273
274         /*
275          * Not all terminals understand CSI [18t for querying the console size.
276          * We should adhere to escape sequences documented in the console_codes
277          * man page and the ECMA-48 standard.
278          *
279          * So here we follow a different approach. We position the cursor to the
280          * bottom right and query its position. Before leaving the function we
281          * restore the original cursor position.
282          */
283         printf(ESC "7"          /* Save cursor position */
284                ESC "[r"         /* Set scrolling region to full window */
285                ESC "[999;999H"  /* Move to bottom right corner */
286                ESC "[6n");      /* Query cursor position */
287
288         /* Read {rows,cols} */
289         if (term_read_reply(n, 2, 'R')) {
290                 ret = 1;
291                 goto out;
292         }
293
294         *cols = n[1];
295         *rows = n[0];
296 out:
297         printf(ESC "8");        /* Restore cursor position */
298         return ret;
299 }
300
301 /**
302  * query_console_size() - update the mode table.
303  *
304  * By default the only mode available is 80x25. If the console has at least 50
305  * lines, enable mode 80x50. If we can query the console size and it is neither
306  * 80x25 nor 80x50, set it as an additional mode.
307  */
308 static void query_console_size(void)
309 {
310         const char *stdout_name = env_get("stdout");
311         int rows = 25, cols = 80;
312
313         if (stdout_name && !strcmp(stdout_name, "vidconsole") &&
314             IS_ENABLED(CONFIG_DM_VIDEO)) {
315                 struct stdio_dev *stdout_dev =
316                         stdio_get_by_name("vidconsole");
317                 struct udevice *dev = stdout_dev->priv;
318                 struct vidconsole_priv *priv =
319                         dev_get_uclass_priv(dev);
320                 rows = priv->rows;
321                 cols = priv->cols;
322         } else if (query_console_serial(&rows, &cols)) {
323                 return;
324         }
325
326         /* Test if we can have Mode 1 */
327         if (cols >= 80 && rows >= 50) {
328                 efi_cout_modes[1].present = 1;
329                 efi_con_mode.max_mode = 2;
330         }
331
332         /*
333          * Install our mode as mode 2 if it is different
334          * than mode 0 or 1 and set it as the currently selected mode
335          */
336         if (!cout_mode_matches(&efi_cout_modes[0], rows, cols) &&
337             !cout_mode_matches(&efi_cout_modes[1], rows, cols)) {
338                 efi_cout_modes[EFI_COUT_MODE_2].columns = cols;
339                 efi_cout_modes[EFI_COUT_MODE_2].rows = rows;
340                 efi_cout_modes[EFI_COUT_MODE_2].present = 1;
341                 efi_con_mode.max_mode = EFI_MAX_COUT_MODE;
342                 efi_con_mode.mode = EFI_COUT_MODE_2;
343         }
344 }
345
346
347 /**
348  * efi_cout_query_mode() - get terminal size for a text mode
349  *
350  * This function implements the QueryMode service of the simple text output
351  * protocol. See the Unified Extensible Firmware Interface (UEFI) specification
352  * for details.
353  *
354  * @this:               simple text output protocol
355  * @mode_number:        mode number to retrieve information on
356  * @columns:            number of columns
357  * @rows:               number of rows
358  * Return:              status code
359  */
360 static efi_status_t EFIAPI efi_cout_query_mode(
361                         struct efi_simple_text_output_protocol *this,
362                         unsigned long mode_number, unsigned long *columns,
363                         unsigned long *rows)
364 {
365         EFI_ENTRY("%p, %ld, %p, %p", this, mode_number, columns, rows);
366
367         if (mode_number >= efi_con_mode.max_mode)
368                 return EFI_EXIT(EFI_UNSUPPORTED);
369
370         if (efi_cout_modes[mode_number].present != 1)
371                 return EFI_EXIT(EFI_UNSUPPORTED);
372
373         if (columns)
374                 *columns = efi_cout_modes[mode_number].columns;
375         if (rows)
376                 *rows = efi_cout_modes[mode_number].rows;
377
378         return EFI_EXIT(EFI_SUCCESS);
379 }
380
381 static const struct {
382         unsigned int fg;
383         unsigned int bg;
384 } color[] = {
385         { 30, 40 },     /* 0: black */
386         { 34, 44 },     /* 1: blue */
387         { 32, 42 },     /* 2: green */
388         { 36, 46 },     /* 3: cyan */
389         { 31, 41 },     /* 4: red */
390         { 35, 45 },     /* 5: magenta */
391         { 33, 43 },     /* 6: brown, map to yellow as EDK2 does*/
392         { 37, 47 },     /* 7: light gray, map to white */
393 };
394
395 /**
396  * efi_cout_set_attribute() - set fore- and background color
397  *
398  * This function implements the SetAttribute service of the simple text output
399  * protocol. See the Unified Extensible Firmware Interface (UEFI) specification
400  * for details.
401  *
402  * @this:       simple text output protocol
403  * @attribute:  foreground color - bits 0-3, background color - bits 4-6
404  * Return:      status code
405  */
406 static efi_status_t EFIAPI efi_cout_set_attribute(
407                         struct efi_simple_text_output_protocol *this,
408                         unsigned long attribute)
409 {
410         unsigned int bold = EFI_ATTR_BOLD(attribute);
411         unsigned int fg = EFI_ATTR_FG(attribute);
412         unsigned int bg = EFI_ATTR_BG(attribute);
413
414         EFI_ENTRY("%p, %lx", this, attribute);
415
416         efi_con_mode.attribute = attribute;
417         if (attribute)
418                 printf(ESC"[%u;%u;%um", bold, color[fg].fg, color[bg].bg);
419         else
420                 printf(ESC"[0;37;40m");
421
422         return EFI_EXIT(EFI_SUCCESS);
423 }
424
425 /**
426  * efi_cout_clear_screen() - clear screen
427  *
428  * This function implements the ClearScreen service of the simple text output
429  * protocol. See the Unified Extensible Firmware Interface (UEFI) specification
430  * for details.
431  *
432  * @this:       pointer to the protocol instance
433  * Return:      status code
434  */
435 static efi_status_t EFIAPI efi_cout_clear_screen(
436                         struct efi_simple_text_output_protocol *this)
437 {
438         EFI_ENTRY("%p", this);
439
440         /*
441          * The Linux console wants both a clear and a home command. The video
442          * uclass does not support <ESC>[H without coordinates, yet.
443          */
444         printf(ESC "[2J" ESC "[1;1H");
445         efi_con_mode.cursor_column = 0;
446         efi_con_mode.cursor_row = 0;
447
448         return EFI_EXIT(EFI_SUCCESS);
449 }
450
451 /**
452  * efi_cout_clear_set_mode() - set text model
453  *
454  * This function implements the SetMode service of the simple text output
455  * protocol. See the Unified Extensible Firmware  Interface (UEFI) specification
456  * for details.
457  *
458  * @this:               pointer to the protocol instance
459  * @mode_number:        number of the text mode to set
460  * Return:              status code
461  */
462 static efi_status_t EFIAPI efi_cout_set_mode(
463                         struct efi_simple_text_output_protocol *this,
464                         unsigned long mode_number)
465 {
466         EFI_ENTRY("%p, %ld", this, mode_number);
467
468         if (mode_number >= efi_con_mode.max_mode)
469                 return EFI_EXIT(EFI_UNSUPPORTED);
470
471         if (!efi_cout_modes[mode_number].present)
472                 return EFI_EXIT(EFI_UNSUPPORTED);
473
474         efi_con_mode.mode = mode_number;
475         EFI_CALL(efi_cout_clear_screen(this));
476
477         return EFI_EXIT(EFI_SUCCESS);
478 }
479
480 /**
481  * efi_cout_reset() - reset the terminal
482  *
483  * This function implements the Reset service of the simple text output
484  * protocol. See the Unified Extensible Firmware  Interface (UEFI) specification
485  * for details.
486  *
487  * @this:                       pointer to the protocol instance
488  * @extended_verification:      if set an extended verification may be executed
489  * Return:                      status code
490  */
491 static efi_status_t EFIAPI efi_cout_reset(
492                         struct efi_simple_text_output_protocol *this,
493                         char extended_verification)
494 {
495         EFI_ENTRY("%p, %d", this, extended_verification);
496
497         /* Clear screen */
498         EFI_CALL(efi_cout_clear_screen(this));
499         /* Set default colors */
500         efi_con_mode.attribute = 0x07;
501         printf(ESC "[0;37;40m");
502
503         return EFI_EXIT(EFI_SUCCESS);
504 }
505
506 /**
507  * efi_cout_set_cursor_position() - reset the terminal
508  *
509  * This function implements the SetCursorPosition service of the simple text
510  * output protocol. See the Unified Extensible Firmware  Interface (UEFI)
511  * specification for details.
512  *
513  * @this:       pointer to the protocol instance
514  * @column:     column to move to
515  * @row:        row to move to
516  * Return:      status code
517  */
518 static efi_status_t EFIAPI efi_cout_set_cursor_position(
519                         struct efi_simple_text_output_protocol *this,
520                         unsigned long column, unsigned long row)
521 {
522         efi_status_t ret = EFI_SUCCESS;
523         struct simple_text_output_mode *con = &efi_con_mode;
524         struct cout_mode *mode = &efi_cout_modes[con->mode];
525
526         EFI_ENTRY("%p, %ld, %ld", this, column, row);
527
528         /* Check parameters */
529         if (!this) {
530                 ret = EFI_INVALID_PARAMETER;
531                 goto out;
532         }
533         if (row >= mode->rows || column >= mode->columns) {
534                 ret = EFI_UNSUPPORTED;
535                 goto out;
536         }
537
538         /*
539          * Set cursor position by sending CSI H.
540          * EFI origin is [0, 0], terminal origin is [1, 1].
541          */
542         printf(ESC "[%d;%dH", (int)row + 1, (int)column + 1);
543         efi_con_mode.cursor_column = column;
544         efi_con_mode.cursor_row = row;
545 out:
546         return EFI_EXIT(ret);
547 }
548
549 /**
550  * efi_cout_enable_cursor() - enable the cursor
551  *
552  * This function implements the EnableCursor service of the simple text  output
553  * protocol. See the Unified Extensible Firmware  Interface (UEFI) specification
554  * for details.
555  *
556  * @this:       pointer to the protocol instance
557  * @enable:     if true enable, if false disable the cursor
558  * Return:      status code
559  */
560 static efi_status_t EFIAPI efi_cout_enable_cursor(
561                         struct efi_simple_text_output_protocol *this,
562                         bool enable)
563 {
564         EFI_ENTRY("%p, %d", this, enable);
565
566         printf(ESC"[?25%c", enable ? 'h' : 'l');
567         efi_con_mode.cursor_visible = !!enable;
568
569         return EFI_EXIT(EFI_SUCCESS);
570 }
571
572 struct efi_simple_text_output_protocol efi_con_out = {
573         .reset = efi_cout_reset,
574         .output_string = efi_cout_output_string,
575         .test_string = efi_cout_test_string,
576         .query_mode = efi_cout_query_mode,
577         .set_mode = efi_cout_set_mode,
578         .set_attribute = efi_cout_set_attribute,
579         .clear_screen = efi_cout_clear_screen,
580         .set_cursor_position = efi_cout_set_cursor_position,
581         .enable_cursor = efi_cout_enable_cursor,
582         .mode = (void*)&efi_con_mode,
583 };
584
585 /**
586  * struct efi_cin_notify_function - registered console input notify function
587  *
588  * @link:       link to list
589  * @key:        key to notify
590  * @function:   function to call
591  */
592 struct efi_cin_notify_function {
593         struct list_head link;
594         struct efi_key_data key;
595         efi_status_t (EFIAPI *function)
596                 (struct efi_key_data *key_data);
597 };
598
599 static bool key_available;
600 static struct efi_key_data next_key;
601 static LIST_HEAD(cin_notify_functions);
602
603 /**
604  * set_shift_mask() - set shift mask
605  *
606  * @mod:        Xterm shift mask
607  * @key_state:  receives the state of the shift, alt, control, and logo keys
608  */
609 void set_shift_mask(int mod, struct efi_key_state *key_state)
610 {
611         key_state->key_shift_state = EFI_SHIFT_STATE_VALID;
612         if (mod) {
613                 --mod;
614                 if (mod & 1)
615                         key_state->key_shift_state |= EFI_LEFT_SHIFT_PRESSED;
616                 if (mod & 2)
617                         key_state->key_shift_state |= EFI_LEFT_ALT_PRESSED;
618                 if (mod & 4)
619                         key_state->key_shift_state |= EFI_LEFT_CONTROL_PRESSED;
620                 if (!mod || (mod & 8))
621                         key_state->key_shift_state |= EFI_LEFT_LOGO_PRESSED;
622         }
623 }
624
625 /**
626  * analyze_modifiers() - analyze modifiers (shift, alt, ctrl) for function keys
627  *
628  * This gets called when we have already parsed CSI.
629  *
630  * @key_state:  receives the state of the shift, alt, control, and logo keys
631  * Return:      the unmodified code
632  */
633 static int analyze_modifiers(struct efi_key_state *key_state)
634 {
635         int c, mod = 0, ret = 0;
636
637         c = getc();
638
639         if (c != ';') {
640                 ret = c;
641                 if (c == '~')
642                         goto out;
643                 c = getc();
644         }
645         for (;;) {
646                 switch (c) {
647                 case '0'...'9':
648                         mod *= 10;
649                         mod += c - '0';
650                 /* fall through */
651                 case ';':
652                         c = getc();
653                         break;
654                 default:
655                         goto out;
656                 }
657         }
658 out:
659         set_shift_mask(mod, key_state);
660         if (!ret)
661                 ret = c;
662         return ret;
663 }
664
665 /**
666  * efi_cin_read_key() - read a key from the console input
667  *
668  * @key:        - key received
669  * Return:      - status code
670  */
671 static efi_status_t efi_cin_read_key(struct efi_key_data *key)
672 {
673         struct efi_input_key pressed_key = {
674                 .scan_code = 0,
675                 .unicode_char = 0,
676         };
677         s32 ch;
678
679         if (console_read_unicode(&ch))
680                 return EFI_NOT_READY;
681
682         key->key_state.key_shift_state = EFI_SHIFT_STATE_INVALID;
683         key->key_state.key_toggle_state = EFI_TOGGLE_STATE_INVALID;
684
685         /* We do not support multi-word codes */
686         if (ch >= 0x10000)
687                 ch = '?';
688
689         switch (ch) {
690         case 0x1b:
691                 /*
692                  * Xterm Control Sequences
693                  * https://www.xfree86.org/4.8.0/ctlseqs.html
694                  */
695                 ch = getc();
696                 switch (ch) {
697                 case cESC: /* ESC */
698                         pressed_key.scan_code = 23;
699                         break;
700                 case 'O': /* F1 - F4, End */
701                         ch = getc();
702                         /* consider modifiers */
703                         if (ch == 'F') { /* End */
704                                 pressed_key.scan_code = 6;
705                                 break;
706                         } else if (ch < 'P') {
707                                 set_shift_mask(ch - '0', &key->key_state);
708                                 ch = getc();
709                         }
710                         pressed_key.scan_code = ch - 'P' + 11;
711                         break;
712                 case '[':
713                         ch = getc();
714                         switch (ch) {
715                         case 'A'...'D': /* up, down right, left */
716                                 pressed_key.scan_code = ch - 'A' + 1;
717                                 break;
718                         case 'F': /* End */
719                                 pressed_key.scan_code = 6;
720                                 break;
721                         case 'H': /* Home */
722                                 pressed_key.scan_code = 5;
723                                 break;
724                         case '1':
725                                 ch = analyze_modifiers(&key->key_state);
726                                 switch (ch) {
727                                 case '1'...'5': /* F1 - F5 */
728                                         pressed_key.scan_code = ch - '1' + 11;
729                                         break;
730                                 case '6'...'9': /* F5 - F8 */
731                                         pressed_key.scan_code = ch - '6' + 15;
732                                         break;
733                                 case 'A'...'D': /* up, down right, left */
734                                         pressed_key.scan_code = ch - 'A' + 1;
735                                         break;
736                                 case 'F': /* End */
737                                         pressed_key.scan_code = 6;
738                                         break;
739                                 case 'H': /* Home */
740                                         pressed_key.scan_code = 5;
741                                         break;
742                                 case '~': /* Home */
743                                         pressed_key.scan_code = 5;
744                                         break;
745                                 }
746                                 break;
747                         case '2':
748                                 ch = analyze_modifiers(&key->key_state);
749                                 switch (ch) {
750                                 case '0'...'1': /* F9 - F10 */
751                                         pressed_key.scan_code = ch - '0' + 19;
752                                         break;
753                                 case '3'...'4': /* F11 - F12 */
754                                         pressed_key.scan_code = ch - '3' + 21;
755                                         break;
756                                 case '~': /* INS */
757                                         pressed_key.scan_code = 7;
758                                         break;
759                                 }
760                                 break;
761                         case '3': /* DEL */
762                                 pressed_key.scan_code = 8;
763                                 analyze_modifiers(&key->key_state);
764                                 break;
765                         case '5': /* PG UP */
766                                 pressed_key.scan_code = 9;
767                                 analyze_modifiers(&key->key_state);
768                                 break;
769                         case '6': /* PG DOWN */
770                                 pressed_key.scan_code = 10;
771                                 analyze_modifiers(&key->key_state);
772                                 break;
773                         } /* [ */
774                         break;
775                 default:
776                         /* ALT key */
777                         set_shift_mask(3, &key->key_state);
778                 }
779                 break;
780         case 0x7f:
781                 /* Backspace */
782                 ch = 0x08;
783         }
784         if (pressed_key.scan_code) {
785                 key->key_state.key_shift_state |= EFI_SHIFT_STATE_VALID;
786         } else {
787                 pressed_key.unicode_char = ch;
788
789                 /*
790                  * Assume left control key for control characters typically
791                  * entered using the control key.
792                  */
793                 if (ch >= 0x01 && ch <= 0x1f) {
794                         key->key_state.key_shift_state |=
795                                         EFI_SHIFT_STATE_VALID;
796                         switch (ch) {
797                         case 0x01 ... 0x07:
798                         case 0x0b ... 0x0c:
799                         case 0x0e ... 0x1f:
800                                 key->key_state.key_shift_state |=
801                                                 EFI_LEFT_CONTROL_PRESSED;
802                         }
803                 }
804         }
805         key->key = pressed_key;
806
807         return EFI_SUCCESS;
808 }
809
810 /**
811  * efi_cin_notify() - notify registered functions
812  */
813 static void efi_cin_notify(void)
814 {
815         struct efi_cin_notify_function *item;
816
817         list_for_each_entry(item, &cin_notify_functions, link) {
818                 bool match = true;
819
820                 /* We do not support toggle states */
821                 if (item->key.key.unicode_char || item->key.key.scan_code) {
822                         if (item->key.key.unicode_char !=
823                             next_key.key.unicode_char ||
824                             item->key.key.scan_code != next_key.key.scan_code)
825                                 match = false;
826                 }
827                 if (item->key.key_state.key_shift_state &&
828                     item->key.key_state.key_shift_state !=
829                     next_key.key_state.key_shift_state)
830                         match = false;
831
832                 if (match)
833                         /* We don't bother about the return code */
834                         EFI_CALL(item->function(&next_key));
835         }
836 }
837
838 /**
839  * efi_cin_check() - check if keyboard input is available
840  */
841 static void efi_cin_check(void)
842 {
843         efi_status_t ret;
844
845         if (key_available) {
846                 efi_signal_event(efi_con_in.wait_for_key);
847                 return;
848         }
849
850         if (tstc()) {
851                 ret = efi_cin_read_key(&next_key);
852                 if (ret == EFI_SUCCESS) {
853                         key_available = true;
854
855                         /* Notify registered functions */
856                         efi_cin_notify();
857
858                         /* Queue the wait for key event */
859                         if (key_available)
860                                 efi_signal_event(efi_con_in.wait_for_key);
861                 }
862         }
863 }
864
865 /**
866  * efi_cin_empty_buffer() - empty input buffer
867  */
868 static void efi_cin_empty_buffer(void)
869 {
870         while (tstc())
871                 getc();
872         key_available = false;
873 }
874
875 /**
876  * efi_cin_reset_ex() - reset console input
877  *
878  * @this:                       - the extended simple text input protocol
879  * @extended_verification:      - extended verification
880  *
881  * This function implements the reset service of the
882  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
883  *
884  * See the Unified Extensible Firmware Interface (UEFI) specification for
885  * details.
886  *
887  * Return: old value of the task priority level
888  */
889 static efi_status_t EFIAPI efi_cin_reset_ex(
890                 struct efi_simple_text_input_ex_protocol *this,
891                 bool extended_verification)
892 {
893         efi_status_t ret = EFI_SUCCESS;
894
895         EFI_ENTRY("%p, %d", this, extended_verification);
896
897         /* Check parameters */
898         if (!this) {
899                 ret = EFI_INVALID_PARAMETER;
900                 goto out;
901         }
902
903         efi_cin_empty_buffer();
904 out:
905         return EFI_EXIT(ret);
906 }
907
908 /**
909  * efi_cin_read_key_stroke_ex() - read key stroke
910  *
911  * @this:       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
912  * @key_data:   key read from console
913  * Return:      status code
914  *
915  * This function implements the ReadKeyStrokeEx service of the
916  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
917  *
918  * See the Unified Extensible Firmware Interface (UEFI) specification for
919  * details.
920  */
921 static efi_status_t EFIAPI efi_cin_read_key_stroke_ex(
922                 struct efi_simple_text_input_ex_protocol *this,
923                 struct efi_key_data *key_data)
924 {
925         efi_status_t ret = EFI_SUCCESS;
926
927         EFI_ENTRY("%p, %p", this, key_data);
928
929         /* Check parameters */
930         if (!this || !key_data) {
931                 ret = EFI_INVALID_PARAMETER;
932                 goto out;
933         }
934
935         /* We don't do interrupts, so check for timers cooperatively */
936         efi_timer_check();
937
938         /* Enable console input after ExitBootServices */
939         efi_cin_check();
940
941         if (!key_available) {
942                 ret = EFI_NOT_READY;
943                 goto out;
944         }
945         /*
946          * CTRL+A - CTRL+Z have to be signaled as a - z.
947          * SHIFT+CTRL+A - SHIFT+CTRL+Z have to be signaled as A - Z.
948          */
949         switch (next_key.key.unicode_char) {
950         case 0x01 ... 0x07:
951         case 0x0b ... 0x0c:
952         case 0x0e ... 0x1a:
953                 if (!(next_key.key_state.key_toggle_state &
954                       EFI_CAPS_LOCK_ACTIVE) ^
955                     !(next_key.key_state.key_shift_state &
956                       (EFI_LEFT_SHIFT_PRESSED | EFI_RIGHT_SHIFT_PRESSED)))
957                         next_key.key.unicode_char += 0x40;
958                 else
959                         next_key.key.unicode_char += 0x60;
960         }
961         *key_data = next_key;
962         key_available = false;
963         efi_con_in.wait_for_key->is_signaled = false;
964
965 out:
966         return EFI_EXIT(ret);
967 }
968
969 /**
970  * efi_cin_set_state() - set toggle key state
971  *
972  * @this:               instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
973  * @key_toggle_state:   pointer to key toggle state
974  * Return:              status code
975  *
976  * This function implements the SetState service of the
977  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
978  *
979  * See the Unified Extensible Firmware Interface (UEFI) specification for
980  * details.
981  */
982 static efi_status_t EFIAPI efi_cin_set_state(
983                 struct efi_simple_text_input_ex_protocol *this,
984                 u8 *key_toggle_state)
985 {
986         EFI_ENTRY("%p, %p", this, key_toggle_state);
987         /*
988          * U-Boot supports multiple console input sources like serial and
989          * net console for which a key toggle state cannot be set at all.
990          *
991          * According to the UEFI specification it is allowable to not implement
992          * this service.
993          */
994         return EFI_EXIT(EFI_UNSUPPORTED);
995 }
996
997 /**
998  * efi_cin_register_key_notify() - register key notification function
999  *
1000  * @this:                       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
1001  * @key_data:                   key to be notified
1002  * @key_notify_function:        function to be called if the key is pressed
1003  * @notify_handle:              handle for unregistering the notification
1004  * Return:                      status code
1005  *
1006  * This function implements the SetState service of the
1007  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
1008  *
1009  * See the Unified Extensible Firmware Interface (UEFI) specification for
1010  * details.
1011  */
1012 static efi_status_t EFIAPI efi_cin_register_key_notify(
1013                 struct efi_simple_text_input_ex_protocol *this,
1014                 struct efi_key_data *key_data,
1015                 efi_status_t (EFIAPI *key_notify_function)(
1016                         struct efi_key_data *key_data),
1017                 void **notify_handle)
1018 {
1019         efi_status_t ret = EFI_SUCCESS;
1020         struct efi_cin_notify_function *notify_function;
1021
1022         EFI_ENTRY("%p, %p, %p, %p",
1023                   this, key_data, key_notify_function, notify_handle);
1024
1025         /* Check parameters */
1026         if (!this || !key_data || !key_notify_function || !notify_handle) {
1027                 ret = EFI_INVALID_PARAMETER;
1028                 goto out;
1029         }
1030
1031         EFI_PRINT("u+%04x, sc %04x, sh %08x, tg %02x\n",
1032                   key_data->key.unicode_char,
1033                key_data->key.scan_code,
1034                key_data->key_state.key_shift_state,
1035                key_data->key_state.key_toggle_state);
1036
1037         notify_function = calloc(1, sizeof(struct efi_cin_notify_function));
1038         if (!notify_function) {
1039                 ret = EFI_OUT_OF_RESOURCES;
1040                 goto out;
1041         }
1042         notify_function->key = *key_data;
1043         notify_function->function = key_notify_function;
1044         list_add_tail(&notify_function->link, &cin_notify_functions);
1045         *notify_handle = notify_function;
1046 out:
1047         return EFI_EXIT(ret);
1048 }
1049
1050 /**
1051  * efi_cin_unregister_key_notify() - unregister key notification function
1052  *
1053  * @this:                       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
1054  * @notification_handle:        handle received when registering
1055  * Return:                      status code
1056  *
1057  * This function implements the SetState service of the
1058  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
1059  *
1060  * See the Unified Extensible Firmware Interface (UEFI) specification for
1061  * details.
1062  */
1063 static efi_status_t EFIAPI efi_cin_unregister_key_notify(
1064                 struct efi_simple_text_input_ex_protocol *this,
1065                 void *notification_handle)
1066 {
1067         efi_status_t ret = EFI_INVALID_PARAMETER;
1068         struct efi_cin_notify_function *item, *notify_function =
1069                         notification_handle;
1070
1071         EFI_ENTRY("%p, %p", this, notification_handle);
1072
1073         /* Check parameters */
1074         if (!this || !notification_handle)
1075                 goto out;
1076
1077         list_for_each_entry(item, &cin_notify_functions, link) {
1078                 if (item == notify_function) {
1079                         ret = EFI_SUCCESS;
1080                         break;
1081                 }
1082         }
1083         if (ret != EFI_SUCCESS)
1084                 goto out;
1085
1086         /* Remove the notify function */
1087         list_del(&notify_function->link);
1088         free(notify_function);
1089 out:
1090         return EFI_EXIT(ret);
1091 }
1092
1093
1094 /**
1095  * efi_cin_reset() - drain the input buffer
1096  *
1097  * @this:                       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
1098  * @extended_verification:      allow for exhaustive verification
1099  * Return:                      status code
1100  *
1101  * This function implements the Reset service of the
1102  * EFI_SIMPLE_TEXT_INPUT_PROTOCOL.
1103  *
1104  * See the Unified Extensible Firmware Interface (UEFI) specification for
1105  * details.
1106  */
1107 static efi_status_t EFIAPI efi_cin_reset
1108                         (struct efi_simple_text_input_protocol *this,
1109                          bool extended_verification)
1110 {
1111         efi_status_t ret = EFI_SUCCESS;
1112
1113         EFI_ENTRY("%p, %d", this, extended_verification);
1114
1115         /* Check parameters */
1116         if (!this) {
1117                 ret = EFI_INVALID_PARAMETER;
1118                 goto out;
1119         }
1120
1121         efi_cin_empty_buffer();
1122 out:
1123         return EFI_EXIT(ret);
1124 }
1125
1126 /**
1127  * efi_cin_read_key_stroke() - read key stroke
1128  *
1129  * @this:       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
1130  * @key:        key read from console
1131  * Return:      status code
1132  *
1133  * This function implements the ReadKeyStroke service of the
1134  * EFI_SIMPLE_TEXT_INPUT_PROTOCOL.
1135  *
1136  * See the Unified Extensible Firmware Interface (UEFI) specification for
1137  * details.
1138  */
1139 static efi_status_t EFIAPI efi_cin_read_key_stroke
1140                         (struct efi_simple_text_input_protocol *this,
1141                          struct efi_input_key *key)
1142 {
1143         efi_status_t ret = EFI_SUCCESS;
1144
1145         EFI_ENTRY("%p, %p", this, key);
1146
1147         /* Check parameters */
1148         if (!this || !key) {
1149                 ret = EFI_INVALID_PARAMETER;
1150                 goto out;
1151         }
1152
1153         /* We don't do interrupts, so check for timers cooperatively */
1154         efi_timer_check();
1155
1156         /* Enable console input after ExitBootServices */
1157         efi_cin_check();
1158
1159         if (!key_available) {
1160                 ret = EFI_NOT_READY;
1161                 goto out;
1162         }
1163         *key = next_key.key;
1164         key_available = false;
1165         efi_con_in.wait_for_key->is_signaled = false;
1166 out:
1167         return EFI_EXIT(ret);
1168 }
1169
1170 static struct efi_simple_text_input_ex_protocol efi_con_in_ex = {
1171         .reset = efi_cin_reset_ex,
1172         .read_key_stroke_ex = efi_cin_read_key_stroke_ex,
1173         .wait_for_key_ex = NULL,
1174         .set_state = efi_cin_set_state,
1175         .register_key_notify = efi_cin_register_key_notify,
1176         .unregister_key_notify = efi_cin_unregister_key_notify,
1177 };
1178
1179 struct efi_simple_text_input_protocol efi_con_in = {
1180         .reset = efi_cin_reset,
1181         .read_key_stroke = efi_cin_read_key_stroke,
1182         .wait_for_key = NULL,
1183 };
1184
1185 static struct efi_event *console_timer_event;
1186
1187 /*
1188  * efi_console_timer_notify() - notify the console timer event
1189  *
1190  * @event:      console timer event
1191  * @context:    not used
1192  */
1193 static void EFIAPI efi_console_timer_notify(struct efi_event *event,
1194                                             void *context)
1195 {
1196         EFI_ENTRY("%p, %p", event, context);
1197         efi_cin_check();
1198         EFI_EXIT(EFI_SUCCESS);
1199 }
1200
1201 /**
1202  * efi_key_notify() - notify the wait for key event
1203  *
1204  * @event:      wait for key event
1205  * @context:    not used
1206  */
1207 static void EFIAPI efi_key_notify(struct efi_event *event, void *context)
1208 {
1209         EFI_ENTRY("%p, %p", event, context);
1210         efi_cin_check();
1211         EFI_EXIT(EFI_SUCCESS);
1212 }
1213
1214 /**
1215  * efi_console_register() - install the console protocols
1216  *
1217  * This function is called from do_bootefi_exec().
1218  *
1219  * Return:      status code
1220  */
1221 efi_status_t efi_console_register(void)
1222 {
1223         efi_status_t r;
1224         efi_handle_t console_output_handle;
1225         efi_handle_t console_input_handle;
1226
1227         /* Set up mode information */
1228         query_console_size();
1229
1230         /* Create handles */
1231         r = efi_create_handle(&console_output_handle);
1232         if (r != EFI_SUCCESS)
1233                 goto out_of_memory;
1234
1235         r = efi_add_protocol(console_output_handle,
1236                              &efi_guid_text_output_protocol, &efi_con_out);
1237         if (r != EFI_SUCCESS)
1238                 goto out_of_memory;
1239         systab.con_out_handle = console_output_handle;
1240         systab.stderr_handle = console_output_handle;
1241
1242         r = efi_create_handle(&console_input_handle);
1243         if (r != EFI_SUCCESS)
1244                 goto out_of_memory;
1245
1246         r = efi_add_protocol(console_input_handle,
1247                              &efi_guid_text_input_protocol, &efi_con_in);
1248         if (r != EFI_SUCCESS)
1249                 goto out_of_memory;
1250         systab.con_in_handle = console_input_handle;
1251         r = efi_add_protocol(console_input_handle,
1252                              &efi_guid_text_input_ex_protocol, &efi_con_in_ex);
1253         if (r != EFI_SUCCESS)
1254                 goto out_of_memory;
1255
1256         /* Create console events */
1257         r = efi_create_event(EVT_NOTIFY_WAIT, TPL_CALLBACK, efi_key_notify,
1258                              NULL, NULL, &efi_con_in.wait_for_key);
1259         if (r != EFI_SUCCESS) {
1260                 printf("ERROR: Failed to register WaitForKey event\n");
1261                 return r;
1262         }
1263         efi_con_in_ex.wait_for_key_ex = efi_con_in.wait_for_key;
1264         r = efi_create_event(EVT_TIMER | EVT_NOTIFY_SIGNAL, TPL_CALLBACK,
1265                              efi_console_timer_notify, NULL, NULL,
1266                              &console_timer_event);
1267         if (r != EFI_SUCCESS) {
1268                 printf("ERROR: Failed to register console event\n");
1269                 return r;
1270         }
1271         /* 5000 ns cycle is sufficient for 2 MBaud */
1272         r = efi_set_timer(console_timer_event, EFI_TIMER_PERIODIC, 50);
1273         if (r != EFI_SUCCESS)
1274                 printf("ERROR: Failed to set console timer\n");
1275         return r;
1276 out_of_memory:
1277         printf("ERROR: Out of memory\n");
1278         return r;
1279 }