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