Merge branch 'master' of git://git.denx.de/u-boot-sunxi
[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
434         return EFI_EXIT(EFI_SUCCESS);
435 }
436
437 struct efi_simple_text_output_protocol efi_con_out = {
438         .reset = efi_cout_reset,
439         .output_string = efi_cout_output_string,
440         .test_string = efi_cout_test_string,
441         .query_mode = efi_cout_query_mode,
442         .set_mode = efi_cout_set_mode,
443         .set_attribute = efi_cout_set_attribute,
444         .clear_screen = efi_cout_clear_screen,
445         .set_cursor_position = efi_cout_set_cursor_position,
446         .enable_cursor = efi_cout_enable_cursor,
447         .mode = (void*)&efi_con_mode,
448 };
449
450 /**
451  * struct efi_cin_notify_function - registered console input notify function
452  *
453  * @link:       link to list
454  * @data:       key to notify
455  * @function:   function to call
456  */
457 struct efi_cin_notify_function {
458         struct list_head link;
459         struct efi_key_data key;
460         efi_status_t (EFIAPI *function)
461                 (struct efi_key_data *key_data);
462 };
463
464 static bool key_available;
465 static struct efi_key_data next_key;
466 static LIST_HEAD(cin_notify_functions);
467
468 /**
469  * set_shift_mask() - set shift mask
470  *
471  * @mod:        Xterm shift mask
472  */
473 void set_shift_mask(int mod, struct efi_key_state *key_state)
474 {
475         key_state->key_shift_state = EFI_SHIFT_STATE_VALID;
476         if (mod) {
477                 --mod;
478                 if (mod & 1)
479                         key_state->key_shift_state |= EFI_LEFT_SHIFT_PRESSED;
480                 if (mod & 2)
481                         key_state->key_shift_state |= EFI_LEFT_ALT_PRESSED;
482                 if (mod & 4)
483                         key_state->key_shift_state |= EFI_LEFT_CONTROL_PRESSED;
484                 if (mod & 8)
485                         key_state->key_shift_state |= EFI_LEFT_LOGO_PRESSED;
486         } else {
487                 key_state->key_shift_state |= EFI_LEFT_LOGO_PRESSED;
488         }
489 }
490
491 /**
492  * analyze_modifiers() - analyze modifiers (shift, alt, ctrl) for function keys
493  *
494  * This gets called when we have already parsed CSI.
495  *
496  * @modifiers:  bit mask (shift, alt, ctrl)
497  * @return:     the unmodified code
498  */
499 static int analyze_modifiers(struct efi_key_state *key_state)
500 {
501         int c, mod = 0, ret = 0;
502
503         c = getc();
504
505         if (c != ';') {
506                 ret = c;
507                 if (c == '~')
508                         goto out;
509                 c = getc();
510         }
511         for (;;) {
512                 switch (c) {
513                 case '0'...'9':
514                         mod *= 10;
515                         mod += c - '0';
516                 /* fall through */
517                 case ';':
518                         c = getc();
519                         break;
520                 default:
521                         goto out;
522                 }
523         }
524 out:
525         set_shift_mask(mod, key_state);
526         if (!ret)
527                 ret = c;
528         return ret;
529 }
530
531 /**
532  * efi_cin_read_key() - read a key from the console input
533  *
534  * @key:        - key received
535  * Return:      - status code
536  */
537 static efi_status_t efi_cin_read_key(struct efi_key_data *key)
538 {
539         struct efi_input_key pressed_key = {
540                 .scan_code = 0,
541                 .unicode_char = 0,
542         };
543         s32 ch;
544
545         if (console_read_unicode(&ch))
546                 return EFI_NOT_READY;
547
548         key->key_state.key_shift_state = EFI_SHIFT_STATE_INVALID;
549         key->key_state.key_toggle_state = EFI_TOGGLE_STATE_INVALID;
550
551         /* We do not support multi-word codes */
552         if (ch >= 0x10000)
553                 ch = '?';
554
555         switch (ch) {
556         case 0x1b:
557                 /*
558                  * Xterm Control Sequences
559                  * https://www.xfree86.org/4.8.0/ctlseqs.html
560                  */
561                 ch = getc();
562                 switch (ch) {
563                 case cESC: /* ESC */
564                         pressed_key.scan_code = 23;
565                         break;
566                 case 'O': /* F1 - F4 */
567                         ch = getc();
568                         /* consider modifiers */
569                         if (ch < 'P') {
570                                 set_shift_mask(ch - '0', &key->key_state);
571                                 ch = getc();
572                         }
573                         pressed_key.scan_code = ch - 'P' + 11;
574                         break;
575                 case '[':
576                         ch = getc();
577                         switch (ch) {
578                         case 'A'...'D': /* up, down right, left */
579                                 pressed_key.scan_code = ch - 'A' + 1;
580                                 break;
581                         case 'F': /* End */
582                                 pressed_key.scan_code = 6;
583                                 break;
584                         case 'H': /* Home */
585                                 pressed_key.scan_code = 5;
586                                 break;
587                         case '1':
588                                 ch = analyze_modifiers(&key->key_state);
589                                 switch (ch) {
590                                 case '1'...'5': /* F1 - F5 */
591                                         pressed_key.scan_code = ch - '1' + 11;
592                                         break;
593                                 case '7'...'9': /* F6 - F8 */
594                                         pressed_key.scan_code = ch - '7' + 16;
595                                         break;
596                                 case 'A'...'D': /* up, down right, left */
597                                         pressed_key.scan_code = ch - 'A' + 1;
598                                         break;
599                                 case 'F':
600                                         pressed_key.scan_code = 6; /* End */
601                                         break;
602                                 case 'H':
603                                         pressed_key.scan_code = 5; /* Home */
604                                         break;
605                                 }
606                                 break;
607                         case '2':
608                                 ch = analyze_modifiers(&key->key_state);
609                                 switch (ch) {
610                                 case '0'...'1': /* F9 - F10 */
611                                         pressed_key.scan_code = ch - '0' + 19;
612                                         break;
613                                 case '3'...'4': /* F11 - F12 */
614                                         pressed_key.scan_code = ch - '3' + 21;
615                                         break;
616                                 case '~': /* INS */
617                                         pressed_key.scan_code = 7;
618                                         break;
619                                 }
620                                 break;
621                         case '3': /* DEL */
622                                 pressed_key.scan_code = 8;
623                                 analyze_modifiers(&key->key_state);
624                                 break;
625                         case '5': /* PG UP */
626                                 pressed_key.scan_code = 9;
627                                 analyze_modifiers(&key->key_state);
628                                 break;
629                         case '6': /* PG DOWN */
630                                 pressed_key.scan_code = 10;
631                                 analyze_modifiers(&key->key_state);
632                                 break;
633                         } /* [ */
634                         break;
635                 default:
636                         /* ALT key */
637                         set_shift_mask(3, &key->key_state);
638                 }
639                 break;
640         case 0x7f:
641                 /* Backspace */
642                 ch = 0x08;
643         }
644         if (pressed_key.scan_code) {
645                 key->key_state.key_shift_state |= EFI_SHIFT_STATE_VALID;
646         } else {
647                 pressed_key.unicode_char = ch;
648
649                 /*
650                  * Assume left control key for control characters typically
651                  * entered using the control key.
652                  */
653                 if (ch >= 0x01 && ch <= 0x1f) {
654                         key->key_state.key_shift_state |=
655                                         EFI_SHIFT_STATE_VALID;
656                         switch (ch) {
657                         case 0x01 ... 0x07:
658                         case 0x0b ... 0x0c:
659                         case 0x0e ... 0x1f:
660                                 key->key_state.key_shift_state |=
661                                                 EFI_LEFT_CONTROL_PRESSED;
662                         }
663                 }
664         }
665         key->key = pressed_key;
666
667         return EFI_SUCCESS;
668 }
669
670 /**
671  * efi_cin_notify() - notify registered functions
672  */
673 static void efi_cin_notify(void)
674 {
675         struct efi_cin_notify_function *item;
676
677         list_for_each_entry(item, &cin_notify_functions, link) {
678                 bool match = true;
679
680                 /* We do not support toggle states */
681                 if (item->key.key.unicode_char || item->key.key.scan_code) {
682                         if (item->key.key.unicode_char !=
683                             next_key.key.unicode_char ||
684                             item->key.key.scan_code != next_key.key.scan_code)
685                                 match = false;
686                 }
687                 if (item->key.key_state.key_shift_state &&
688                     item->key.key_state.key_shift_state !=
689                     next_key.key_state.key_shift_state)
690                         match = false;
691
692                 if (match)
693                         /* We don't bother about the return code */
694                         EFI_CALL(item->function(&next_key));
695         }
696 }
697
698 /**
699  * efi_cin_check() - check if keyboard input is available
700  */
701 static void efi_cin_check(void)
702 {
703         efi_status_t ret;
704
705         if (key_available) {
706                 efi_signal_event(efi_con_in.wait_for_key, true);
707                 return;
708         }
709
710         if (tstc()) {
711                 ret = efi_cin_read_key(&next_key);
712                 if (ret == EFI_SUCCESS) {
713                         key_available = true;
714
715                         /* Notify registered functions */
716                         efi_cin_notify();
717
718                         /* Queue the wait for key event */
719                         if (key_available)
720                                 efi_signal_event(efi_con_in.wait_for_key, true);
721                 }
722         }
723 }
724
725 /**
726  * efi_cin_empty_buffer() - empty input buffer
727  */
728 static void efi_cin_empty_buffer(void)
729 {
730         while (tstc())
731                 getc();
732         key_available = false;
733 }
734
735 /**
736  * efi_cin_reset_ex() - reset console input
737  *
738  * @this:                       - the extended simple text input protocol
739  * @extended_verification:      - extended verification
740  *
741  * This function implements the reset service of the
742  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
743  *
744  * See the Unified Extensible Firmware Interface (UEFI) specification for
745  * details.
746  *
747  * Return: old value of the task priority level
748  */
749 static efi_status_t EFIAPI efi_cin_reset_ex(
750                 struct efi_simple_text_input_ex_protocol *this,
751                 bool extended_verification)
752 {
753         efi_status_t ret = EFI_SUCCESS;
754
755         EFI_ENTRY("%p, %d", this, extended_verification);
756
757         /* Check parameters */
758         if (!this) {
759                 ret = EFI_INVALID_PARAMETER;
760                 goto out;
761         }
762
763         efi_cin_empty_buffer();
764 out:
765         return EFI_EXIT(ret);
766 }
767
768 /**
769  * efi_cin_read_key_stroke_ex() - read key stroke
770  *
771  * @this:       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
772  * @key_data:   key read from console
773  * Return:      status code
774  *
775  * This function implements the ReadKeyStrokeEx service of the
776  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
777  *
778  * See the Unified Extensible Firmware Interface (UEFI) specification for
779  * details.
780  */
781 static efi_status_t EFIAPI efi_cin_read_key_stroke_ex(
782                 struct efi_simple_text_input_ex_protocol *this,
783                 struct efi_key_data *key_data)
784 {
785         efi_status_t ret = EFI_SUCCESS;
786
787         EFI_ENTRY("%p, %p", this, key_data);
788
789         /* Check parameters */
790         if (!this || !key_data) {
791                 ret = EFI_INVALID_PARAMETER;
792                 goto out;
793         }
794
795         /* We don't do interrupts, so check for timers cooperatively */
796         efi_timer_check();
797
798         /* Enable console input after ExitBootServices */
799         efi_cin_check();
800
801         if (!key_available) {
802                 ret = EFI_NOT_READY;
803                 goto out;
804         }
805         /*
806          * CTRL+A - CTRL+Z have to be signaled as a - z.
807          * SHIFT+CTRL+A - SHIFT+CTRL+Z have to be signaled as A - Z.
808          */
809         switch (next_key.key.unicode_char) {
810         case 0x01 ... 0x07:
811         case 0x0b ... 0x0c:
812         case 0x0e ... 0x1a:
813                 if (!(next_key.key_state.key_toggle_state &
814                       EFI_CAPS_LOCK_ACTIVE) ^
815                     !(next_key.key_state.key_shift_state &
816                       (EFI_LEFT_SHIFT_PRESSED | EFI_RIGHT_SHIFT_PRESSED)))
817                         next_key.key.unicode_char += 0x40;
818                 else
819                         next_key.key.unicode_char += 0x60;
820         }
821         *key_data = next_key;
822         key_available = false;
823         efi_con_in.wait_for_key->is_signaled = false;
824
825 out:
826         return EFI_EXIT(ret);
827 }
828
829 /**
830  * efi_cin_set_state() - set toggle key state
831  *
832  * @this:               instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
833  * @key_toggle_state:   pointer to key toggle state
834  * Return:              status code
835  *
836  * This function implements the SetState service of the
837  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
838  *
839  * See the Unified Extensible Firmware Interface (UEFI) specification for
840  * details.
841  */
842 static efi_status_t EFIAPI efi_cin_set_state(
843                 struct efi_simple_text_input_ex_protocol *this,
844                 u8 *key_toggle_state)
845 {
846         EFI_ENTRY("%p, %p", this, key_toggle_state);
847         /*
848          * U-Boot supports multiple console input sources like serial and
849          * net console for which a key toggle state cannot be set at all.
850          *
851          * According to the UEFI specification it is allowable to not implement
852          * this service.
853          */
854         return EFI_EXIT(EFI_UNSUPPORTED);
855 }
856
857 /**
858  * efi_cin_register_key_notify() - register key notification function
859  *
860  * @this:                       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
861  * @key_data:                   key to be notified
862  * @key_notify_function:        function to be called if the key is pressed
863  * @notify_handle:              handle for unregistering the notification
864  * Return:                      status code
865  *
866  * This function implements the SetState service of the
867  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
868  *
869  * See the Unified Extensible Firmware Interface (UEFI) specification for
870  * details.
871  */
872 static efi_status_t EFIAPI efi_cin_register_key_notify(
873                 struct efi_simple_text_input_ex_protocol *this,
874                 struct efi_key_data *key_data,
875                 efi_status_t (EFIAPI *key_notify_function)(
876                         struct efi_key_data *key_data),
877                 void **notify_handle)
878 {
879         efi_status_t ret = EFI_SUCCESS;
880         struct efi_cin_notify_function *notify_function;
881
882         EFI_ENTRY("%p, %p, %p, %p",
883                   this, key_data, key_notify_function, notify_handle);
884
885         /* Check parameters */
886         if (!this || !key_data || !key_notify_function || !notify_handle) {
887                 ret = EFI_INVALID_PARAMETER;
888                 goto out;
889         }
890
891         EFI_PRINT("u+%04x, sc %04x, sh %08x, tg %02x\n",
892                   key_data->key.unicode_char,
893                key_data->key.scan_code,
894                key_data->key_state.key_shift_state,
895                key_data->key_state.key_toggle_state);
896
897         notify_function = calloc(1, sizeof(struct efi_cin_notify_function));
898         if (!notify_function) {
899                 ret = EFI_OUT_OF_RESOURCES;
900                 goto out;
901         }
902         notify_function->key = *key_data;
903         notify_function->function = key_notify_function;
904         list_add_tail(&notify_function->link, &cin_notify_functions);
905         *notify_handle = notify_function;
906 out:
907         return EFI_EXIT(ret);
908 }
909
910 /**
911  * efi_cin_unregister_key_notify() - unregister key notification function
912  *
913  * @this:                       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
914  * @notification_handle:        handle received when registering
915  * Return:                      status code
916  *
917  * This function implements the SetState service of the
918  * EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.
919  *
920  * See the Unified Extensible Firmware Interface (UEFI) specification for
921  * details.
922  */
923 static efi_status_t EFIAPI efi_cin_unregister_key_notify(
924                 struct efi_simple_text_input_ex_protocol *this,
925                 void *notification_handle)
926 {
927         efi_status_t ret = EFI_INVALID_PARAMETER;
928         struct efi_cin_notify_function *item, *notify_function =
929                         notification_handle;
930
931         EFI_ENTRY("%p, %p", this, notification_handle);
932
933         /* Check parameters */
934         if (!this || !notification_handle)
935                 goto out;
936
937         list_for_each_entry(item, &cin_notify_functions, link) {
938                 if (item == notify_function) {
939                         ret = EFI_SUCCESS;
940                         break;
941                 }
942         }
943         if (ret != EFI_SUCCESS)
944                 goto out;
945
946         /* Remove the notify function */
947         list_del(&notify_function->link);
948         free(notify_function);
949 out:
950         return EFI_EXIT(ret);
951 }
952
953
954 /**
955  * efi_cin_reset() - drain the input buffer
956  *
957  * @this:                       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
958  * @extended_verification:      allow for exhaustive verification
959  * Return:                      status code
960  *
961  * This function implements the Reset service of the
962  * EFI_SIMPLE_TEXT_INPUT_PROTOCOL.
963  *
964  * See the Unified Extensible Firmware Interface (UEFI) specification for
965  * details.
966  */
967 static efi_status_t EFIAPI efi_cin_reset
968                         (struct efi_simple_text_input_protocol *this,
969                          bool extended_verification)
970 {
971         efi_status_t ret = EFI_SUCCESS;
972
973         EFI_ENTRY("%p, %d", this, extended_verification);
974
975         /* Check parameters */
976         if (!this) {
977                 ret = EFI_INVALID_PARAMETER;
978                 goto out;
979         }
980
981         efi_cin_empty_buffer();
982 out:
983         return EFI_EXIT(ret);
984 }
985
986 /**
987  * efi_cin_read_key_stroke() - read key stroke
988  *
989  * @this:       instance of the EFI_SIMPLE_TEXT_INPUT_PROTOCOL
990  * @key:        key read from console
991  * Return:      status code
992  *
993  * This function implements the ReadKeyStroke service of the
994  * EFI_SIMPLE_TEXT_INPUT_PROTOCOL.
995  *
996  * See the Unified Extensible Firmware Interface (UEFI) specification for
997  * details.
998  */
999 static efi_status_t EFIAPI efi_cin_read_key_stroke
1000                         (struct efi_simple_text_input_protocol *this,
1001                          struct efi_input_key *key)
1002 {
1003         efi_status_t ret = EFI_SUCCESS;
1004
1005         EFI_ENTRY("%p, %p", this, key);
1006
1007         /* Check parameters */
1008         if (!this || !key) {
1009                 ret = EFI_INVALID_PARAMETER;
1010                 goto out;
1011         }
1012
1013         /* We don't do interrupts, so check for timers cooperatively */
1014         efi_timer_check();
1015
1016         /* Enable console input after ExitBootServices */
1017         efi_cin_check();
1018
1019         if (!key_available) {
1020                 ret = EFI_NOT_READY;
1021                 goto out;
1022         }
1023         *key = next_key.key;
1024         key_available = false;
1025         efi_con_in.wait_for_key->is_signaled = false;
1026 out:
1027         return EFI_EXIT(ret);
1028 }
1029
1030 static struct efi_simple_text_input_ex_protocol efi_con_in_ex = {
1031         .reset = efi_cin_reset_ex,
1032         .read_key_stroke_ex = efi_cin_read_key_stroke_ex,
1033         .wait_for_key_ex = NULL,
1034         .set_state = efi_cin_set_state,
1035         .register_key_notify = efi_cin_register_key_notify,
1036         .unregister_key_notify = efi_cin_unregister_key_notify,
1037 };
1038
1039 struct efi_simple_text_input_protocol efi_con_in = {
1040         .reset = efi_cin_reset,
1041         .read_key_stroke = efi_cin_read_key_stroke,
1042         .wait_for_key = NULL,
1043 };
1044
1045 static struct efi_event *console_timer_event;
1046
1047 /*
1048  * efi_console_timer_notify() - notify the console timer event
1049  *
1050  * @event:      console timer event
1051  * @context:    not used
1052  */
1053 static void EFIAPI efi_console_timer_notify(struct efi_event *event,
1054                                             void *context)
1055 {
1056         EFI_ENTRY("%p, %p", event, context);
1057         efi_cin_check();
1058         EFI_EXIT(EFI_SUCCESS);
1059 }
1060
1061 /**
1062  * efi_key_notify() - notify the wait for key event
1063  *
1064  * @event:      wait for key event
1065  * @context:    not used
1066  */
1067 static void EFIAPI efi_key_notify(struct efi_event *event, void *context)
1068 {
1069         EFI_ENTRY("%p, %p", event, context);
1070         efi_cin_check();
1071         EFI_EXIT(EFI_SUCCESS);
1072 }
1073
1074 /**
1075  * efi_console_register() - install the console protocols
1076  *
1077  * This function is called from do_bootefi_exec().
1078  *
1079  * Return:      status code
1080  */
1081 efi_status_t efi_console_register(void)
1082 {
1083         efi_status_t r;
1084         efi_handle_t console_output_handle;
1085         efi_handle_t console_input_handle;
1086
1087         /* Set up mode information */
1088         query_console_size();
1089
1090         /* Create handles */
1091         r = efi_create_handle(&console_output_handle);
1092         if (r != EFI_SUCCESS)
1093                 goto out_of_memory;
1094
1095         r = efi_add_protocol(console_output_handle,
1096                              &efi_guid_text_output_protocol, &efi_con_out);
1097         if (r != EFI_SUCCESS)
1098                 goto out_of_memory;
1099         systab.con_out_handle = console_output_handle;
1100         systab.stderr_handle = console_output_handle;
1101
1102         r = efi_create_handle(&console_input_handle);
1103         if (r != EFI_SUCCESS)
1104                 goto out_of_memory;
1105
1106         r = efi_add_protocol(console_input_handle,
1107                              &efi_guid_text_input_protocol, &efi_con_in);
1108         if (r != EFI_SUCCESS)
1109                 goto out_of_memory;
1110         systab.con_in_handle = console_input_handle;
1111         r = efi_add_protocol(console_input_handle,
1112                              &efi_guid_text_input_ex_protocol, &efi_con_in_ex);
1113         if (r != EFI_SUCCESS)
1114                 goto out_of_memory;
1115
1116         /* Create console events */
1117         r = efi_create_event(EVT_NOTIFY_WAIT, TPL_CALLBACK, efi_key_notify,
1118                              NULL, NULL, &efi_con_in.wait_for_key);
1119         if (r != EFI_SUCCESS) {
1120                 printf("ERROR: Failed to register WaitForKey event\n");
1121                 return r;
1122         }
1123         efi_con_in_ex.wait_for_key_ex = efi_con_in.wait_for_key;
1124         r = efi_create_event(EVT_TIMER | EVT_NOTIFY_SIGNAL, TPL_CALLBACK,
1125                              efi_console_timer_notify, NULL, NULL,
1126                              &console_timer_event);
1127         if (r != EFI_SUCCESS) {
1128                 printf("ERROR: Failed to register console event\n");
1129                 return r;
1130         }
1131         /* 5000 ns cycle is sufficient for 2 MBaud */
1132         r = efi_set_timer(console_timer_event, EFI_TIMER_PERIODIC, 50);
1133         if (r != EFI_SUCCESS)
1134                 printf("ERROR: Failed to set console timer\n");
1135         return r;
1136 out_of_memory:
1137         printf("ERROR: Out of memory\n");
1138         return r;
1139 }