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