bd1975895bef096e76d922ae53fb48ccd3deb034
[platform/kernel/u-boot.git] / cmd / eficonfig.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  Menu-driven UEFI Variable maintenance
4  *
5  *  Copyright (c) 2022 Masahisa Kojima, Linaro Limited
6  */
7
8 #include <ansi.h>
9 #include <common.h>
10 #include <charset.h>
11 #include <efi_loader.h>
12 #include <efi_load_initrd.h>
13 #include <efi_config.h>
14 #include <efi_variable.h>
15 #include <log.h>
16 #include <malloc.h>
17 #include <menu.h>
18 #include <sort.h>
19 #include <watchdog.h>
20 #include <asm/unaligned.h>
21 #include <linux/delay.h>
22
23 static struct efi_simple_text_input_protocol *cin;
24
25 #define EFICONFIG_DESCRIPTION_MAX 32
26 #define EFICONFIG_OPTIONAL_DATA_MAX 64
27
28 /**
29  * struct eficonfig_filepath_info - structure to be used to store file path
30  *
31  * @name:       file or directory name
32  * @list:       list structure
33  */
34 struct eficonfig_filepath_info {
35         char *name;
36         struct list_head list;
37 };
38
39 /**
40  * struct eficonfig_boot_option - structure to be used for updating UEFI boot option
41  *
42  * @file_info:          user selected file info
43  * @initrd_info:        user selected initrd file info
44  * @boot_index:         index of the boot option
45  * @description:        pointer to the description string
46  * @optional_data:      pointer to the optional_data
47  * @edit_completed:     flag indicates edit complete
48  */
49 struct eficonfig_boot_option {
50         struct eficonfig_select_file_info file_info;
51         struct eficonfig_select_file_info initrd_info;
52         unsigned int boot_index;
53         u16 *description;
54         u16 *optional_data;
55         bool edit_completed;
56 };
57
58 /**
59  * struct eficonfig_volume_entry_data - structure to be used to store volume info
60  *
61  * @file_info:  pointer to file info structure
62  * @v:          pointer to the protocol interface
63  * @dp:         pointer to the device path
64  */
65 struct eficonfig_volume_entry_data {
66         struct eficonfig_select_file_info *file_info;
67         struct efi_simple_file_system_protocol *v;
68         struct efi_device_path *dp;
69 };
70
71 /**
72  * struct eficonfig_file_entry_data - structure to be used to store file info
73  *
74  * @file_info:          pointer to file info structure
75  * @is_directory:       flag to identify the directory or file
76  * @file_name:          name of directory or file
77  */
78 struct eficonfig_file_entry_data {
79         struct eficonfig_select_file_info *file_info;
80         bool is_directory;
81         char *file_name;
82 };
83
84 /**
85  * struct eficonfig_boot_selection_data - structure to be used to select the boot option entry
86  *
87  * @boot_index: index of the boot option
88  * @selected:           pointer to store the selected index in the BootOrder variable
89  */
90 struct eficonfig_boot_selection_data {
91         u16 boot_index;
92         int *selected;
93 };
94
95 /**
96  * eficonfig_print_msg() - print message
97  *
98  * display the message to the user, user proceeds the screen
99  * with any key press.
100  *
101  * @items:              pointer to the structure of each menu entry
102  * @count:              the number of menu entry
103  * @menu_header:        pointer to the menu header string
104  * Return:      status code
105  */
106 void eficonfig_print_msg(char *msg)
107 {
108         /* Flush input */
109         while (tstc())
110                 getchar();
111
112         printf(ANSI_CURSOR_HIDE
113                ANSI_CLEAR_CONSOLE
114                ANSI_CURSOR_POSITION
115                "%s\n\n  Press any key to continue", 3, 4, msg);
116
117         getchar();
118 }
119
120 /**
121  * eficonfig_print_entry() - print each menu entry
122  *
123  * @data:       pointer to the data associated with each menu entry
124  */
125 static void eficonfig_print_entry(void *data)
126 {
127         struct eficonfig_entry *entry = data;
128         int reverse = (entry->efi_menu->active == entry->num);
129
130         /* TODO: support scroll or page for many entries */
131
132         /*
133          * Move cursor to line where the entry will be drawn (entry->num)
134          * First 3 lines(menu header) + 1 empty line
135          */
136         printf(ANSI_CURSOR_POSITION, entry->num + 4, 7);
137
138         if (reverse)
139                 puts(ANSI_COLOR_REVERSE);
140
141         printf("%s", entry->title);
142
143         if (reverse)
144                 puts(ANSI_COLOR_RESET);
145 }
146
147 /**
148  * eficonfig_display_statusline() - print status line
149  *
150  * @m:  pointer to the menu structure
151  */
152 static void eficonfig_display_statusline(struct menu *m)
153 {
154         struct eficonfig_entry *entry;
155
156         if (menu_default_choice(m, (void *)&entry) < 0)
157                 return;
158
159         printf(ANSI_CURSOR_POSITION
160               "\n%s\n"
161                ANSI_CURSOR_POSITION ANSI_CLEAR_LINE ANSI_CURSOR_POSITION
162                "  Press UP/DOWN to move, ENTER to select, ESC/CTRL+C to quit"
163                ANSI_CLEAR_LINE_TO_END ANSI_CURSOR_POSITION ANSI_CLEAR_LINE,
164                1, 1, entry->efi_menu->menu_header, entry->efi_menu->count + 5, 1,
165                entry->efi_menu->count + 6, 1, entry->efi_menu->count + 7, 1);
166 }
167
168 /**
169  * eficonfig_choice_entry() - user key input handler
170  *
171  * @data:       pointer to the efimenu structure
172  * Return:      key string to identify the selected entry
173  */
174 static char *eficonfig_choice_entry(void *data)
175 {
176         int esc = 0;
177         struct list_head *pos, *n;
178         struct eficonfig_entry *entry;
179         enum bootmenu_key key = KEY_NONE;
180         struct efimenu *efi_menu = data;
181
182         while (1) {
183                 bootmenu_loop((struct bootmenu_data *)efi_menu, &key, &esc);
184
185                 switch (key) {
186                 case KEY_UP:
187                         if (efi_menu->active > 0)
188                                 --efi_menu->active;
189                         /* no menu key selected, regenerate menu */
190                         return NULL;
191                 case KEY_DOWN:
192                         if (efi_menu->active < efi_menu->count - 1)
193                                 ++efi_menu->active;
194                         /* no menu key selected, regenerate menu */
195                         return NULL;
196                 case KEY_SELECT:
197                         list_for_each_safe(pos, n, &efi_menu->list) {
198                                 entry = list_entry(pos, struct eficonfig_entry, list);
199                                 if (entry->num == efi_menu->active)
200                                         return entry->key;
201                         }
202                         break;
203                 case KEY_QUIT:
204                         /* Quit by choosing the last entry */
205                         entry = list_last_entry(&efi_menu->list, struct eficonfig_entry, list);
206                         return entry->key;
207                 default:
208                         /* Pressed key is not valid, no need to regenerate the menu */
209                         break;
210                 }
211         }
212 }
213
214 /**
215  * eficonfig_destroy() - destroy efimenu
216  *
217  * @efi_menu:   pointer to the efimenu structure
218  */
219 void eficonfig_destroy(struct efimenu *efi_menu)
220 {
221         struct list_head *pos, *n;
222         struct eficonfig_entry *entry;
223
224         if (!efi_menu)
225                 return;
226
227         list_for_each_safe(pos, n, &efi_menu->list) {
228                 entry = list_entry(pos, struct eficonfig_entry, list);
229                 free(entry->title);
230                 list_del(&entry->list);
231                 free(entry);
232         }
233         free(efi_menu->menu_header);
234         free(efi_menu);
235 }
236
237 /**
238  * eficonfig_process_quit() - callback function for "Quit" entry
239  *
240  * @data:       pointer to the data
241  * Return:      status code
242  */
243 efi_status_t eficonfig_process_quit(void *data)
244 {
245         return EFI_ABORTED;
246 }
247
248 /**
249  * append_entry() - append menu item
250  *
251  * @efi_menu:   pointer to the efimenu structure
252  * @title:      pointer to the entry title
253  * @func:       callback of each entry
254  * @data:       pointer to the data to be passed to each entry callback
255  * Return:      status code
256  */
257 static efi_status_t append_entry(struct efimenu *efi_menu,
258                                  char *title, eficonfig_entry_func func, void *data)
259 {
260         struct eficonfig_entry *entry;
261
262         if (efi_menu->count >= EFICONFIG_ENTRY_NUM_MAX)
263                 return EFI_OUT_OF_RESOURCES;
264
265         entry = calloc(1, sizeof(struct eficonfig_entry));
266         if (!entry)
267                 return EFI_OUT_OF_RESOURCES;
268
269         entry->title = title;
270         sprintf(entry->key, "%d", efi_menu->count);
271         entry->efi_menu = efi_menu;
272         entry->func = func;
273         entry->data = data;
274         entry->num = efi_menu->count++;
275         list_add_tail(&entry->list, &efi_menu->list);
276
277         return EFI_SUCCESS;
278 }
279
280 /**
281  * append_quit_entry() - append quit entry
282  *
283  * @efi_menu:   pointer to the efimenu structure
284  * Return:      status code
285  */
286 static efi_status_t append_quit_entry(struct efimenu *efi_menu)
287 {
288         char *title;
289         efi_status_t ret;
290
291         title = strdup("Quit");
292         if (!title)
293                 return EFI_OUT_OF_RESOURCES;
294
295         ret = append_entry(efi_menu, title, eficonfig_process_quit, NULL);
296         if (ret != EFI_SUCCESS)
297                 free(title);
298
299         return ret;
300 }
301
302 /**
303  * eficonfig_create_fixed_menu() - create fixed entry menu structure
304  *
305  * @items:      pointer to the menu entry item
306  * @count:      the number of menu entry
307  * Return:      pointer to the efimenu structure
308  */
309 void *eficonfig_create_fixed_menu(const struct eficonfig_item *items, int count)
310 {
311         u32 i;
312         char *title;
313         efi_status_t ret;
314         struct efimenu *efi_menu;
315         const struct eficonfig_item *iter = items;
316
317         efi_menu = calloc(1, sizeof(struct efimenu));
318         if (!efi_menu)
319                 return NULL;
320
321         INIT_LIST_HEAD(&efi_menu->list);
322         for (i = 0; i < count; i++, iter++) {
323                 title = strdup(iter->title);
324                 if (!title)
325                         goto out;
326
327                 ret = append_entry(efi_menu, title, iter->func, iter->data);
328                 if (ret != EFI_SUCCESS) {
329                         free(title);
330                         goto out;
331                 }
332         }
333
334         return efi_menu;
335 out:
336         eficonfig_destroy(efi_menu);
337
338         return NULL;
339 }
340
341 /**
342  * eficonfig_process_common() - main handler for UEFI menu
343  *
344  * Construct the structures required to show the menu, then handle
345  * the user input interacting with u-boot menu functions.
346  *
347  * @efi_menu:           pointer to the efimenu structure
348  * @menu_header:        pointer to the menu header string
349  * Return:              status code
350  */
351 efi_status_t eficonfig_process_common(struct efimenu *efi_menu, char *menu_header)
352 {
353         struct menu *menu;
354         void *choice = NULL;
355         struct list_head *pos, *n;
356         struct eficonfig_entry *entry;
357         efi_status_t ret = EFI_SUCCESS;
358
359         if (efi_menu->count > EFICONFIG_ENTRY_NUM_MAX)
360                 return EFI_OUT_OF_RESOURCES;
361
362         efi_menu->delay = -1;
363         efi_menu->active = 0;
364
365         if (menu_header) {
366                 efi_menu->menu_header = strdup(menu_header);
367                 if (!efi_menu->menu_header)
368                         return EFI_OUT_OF_RESOURCES;
369         }
370
371         menu = menu_create(NULL, 0, 1, eficonfig_display_statusline,
372                            eficonfig_print_entry, eficonfig_choice_entry,
373                            efi_menu);
374         if (!menu)
375                 return EFI_INVALID_PARAMETER;
376
377         list_for_each_safe(pos, n, &efi_menu->list) {
378                 entry = list_entry(pos, struct eficonfig_entry, list);
379                 if (!menu_item_add(menu, entry->key, entry)) {
380                         ret = EFI_INVALID_PARAMETER;
381                         goto out;
382                 }
383         }
384
385         entry = list_first_entry_or_null(&efi_menu->list, struct eficonfig_entry, list);
386         if (entry)
387                 menu_default_set(menu, entry->key);
388
389         printf(ANSI_CURSOR_HIDE
390                ANSI_CLEAR_CONSOLE
391                ANSI_CURSOR_POSITION, 1, 1);
392
393         if (menu_get_choice(menu, &choice)) {
394                 entry = choice;
395                 if (entry->func)
396                         ret = entry->func(entry->data);
397         }
398 out:
399         menu_destroy(menu);
400
401         printf(ANSI_CLEAR_CONSOLE
402                ANSI_CURSOR_POSITION
403                ANSI_CURSOR_SHOW, 1, 1);
404
405         return ret;
406 }
407
408 /**
409  * eficonfig_volume_selected() - handler of volume selection
410  *
411  * @data:       pointer to the data of selected entry
412  * Return:      status code
413  */
414 static efi_status_t eficonfig_volume_selected(void *data)
415 {
416         struct eficonfig_volume_entry_data *info = data;
417
418         if (info) {
419                 info->file_info->current_volume = info->v;
420                 info->file_info->dp_volume = info->dp;
421         }
422
423         return EFI_SUCCESS;
424 }
425
426 /**
427  * create_selected_device_path() - create device path
428  *
429  * @file_info:  pointer to the selected file information
430  * Return:
431  * device path or NULL. Caller must free the returned value
432  */
433 static
434 struct efi_device_path *create_selected_device_path(struct eficonfig_select_file_info *file_info)
435 {
436         char *p;
437         void *buf;
438         efi_uintn_t fp_size;
439         struct efi_device_path *dp;
440         struct efi_device_path_file_path *fp;
441
442         fp_size = sizeof(struct efi_device_path) +
443                   ((u16_strlen(file_info->current_path) + 1) * sizeof(u16));
444         buf = calloc(1, fp_size + sizeof(END));
445         if (!buf)
446                 return NULL;
447
448         fp = buf;
449         fp->dp.type = DEVICE_PATH_TYPE_MEDIA_DEVICE,
450         fp->dp.sub_type = DEVICE_PATH_SUB_TYPE_FILE_PATH,
451         fp->dp.length = (u16)fp_size;
452         u16_strcpy(fp->str, file_info->current_path);
453
454         p = buf;
455         p += fp_size;
456         *((struct efi_device_path *)p) = END;
457
458         dp = efi_dp_append(file_info->dp_volume, (struct efi_device_path *)buf);
459         free(buf);
460
461         return dp;
462 }
463
464 /**
465  * eficonfig_file_selected() - handler of file selection
466  *
467  * @data:       pointer to the data of selected entry
468  * Return:      status code
469  */
470 static efi_status_t eficonfig_file_selected(void *data)
471 {
472         u16 *tmp;
473         struct eficonfig_file_entry_data *info = data;
474
475         if (!info)
476                 return EFI_INVALID_PARAMETER;
477
478         if (!strcmp(info->file_name, "..")) {
479                 struct eficonfig_filepath_info *iter;
480                 struct list_head *pos, *n;
481                 int is_last;
482                 char *filepath;
483                 tmp = info->file_info->current_path;
484
485                 memset(info->file_info->current_path, 0, EFICONFIG_FILE_PATH_BUF_SIZE);
486                 filepath = calloc(1, EFICONFIG_FILE_PATH_MAX);
487                 if (!filepath)
488                         return EFI_OUT_OF_RESOURCES;
489
490                 list_for_each_safe(pos, n, &info->file_info->filepath_list) {
491                         iter = list_entry(pos, struct eficonfig_filepath_info, list);
492
493                         is_last = list_is_last(&iter->list, &info->file_info->filepath_list);
494                         if (is_last) {
495                                 list_del(&iter->list);
496                                 free(iter->name);
497                                 free(iter);
498                                 break;
499                         }
500                         strlcat(filepath, iter->name, EFICONFIG_FILE_PATH_MAX);
501                 }
502                 utf8_utf16_strcpy(&tmp, filepath);
503         } else {
504                 size_t new_len;
505                 struct eficonfig_filepath_info *filepath_info;
506
507                 new_len = u16_strlen(info->file_info->current_path) +
508                                      strlen(info->file_name);
509                 if (new_len >= EFICONFIG_FILE_PATH_MAX) {
510                         eficonfig_print_msg("File path is too long!");
511                         return EFI_INVALID_PARAMETER;
512                 }
513                 tmp = &info->file_info->current_path[u16_strlen(info->file_info->current_path)];
514                 utf8_utf16_strcpy(&tmp, info->file_name);
515
516                 filepath_info = calloc(1, sizeof(struct eficonfig_filepath_info));
517                 if (!filepath_info)
518                         return EFI_OUT_OF_RESOURCES;
519
520                 filepath_info->name = strdup(info->file_name);
521                 if (!filepath_info->name) {
522                         free(filepath_info);
523                         return EFI_OUT_OF_RESOURCES;
524                 }
525                 list_add_tail(&filepath_info->list, &info->file_info->filepath_list);
526
527                 if (!info->is_directory)
528                         info->file_info->file_selected = true;
529         }
530
531         return EFI_SUCCESS;
532 }
533
534 /**
535  * eficonfig_select_volume() - construct the volume selection menu
536  *
537  * @file_info:  pointer to the file selection structure
538  * Return:      status code
539  */
540 static efi_status_t eficonfig_select_volume(struct eficonfig_select_file_info *file_info)
541 {
542         u32 i;
543         efi_status_t ret;
544         efi_uintn_t count;
545         struct efimenu *efi_menu;
546         struct list_head *pos, *n;
547         struct efi_handler *handler;
548         struct eficonfig_entry *entry;
549         struct efi_device_path *device_path;
550         efi_handle_t *volume_handles = NULL;
551         struct efi_simple_file_system_protocol *v;
552
553         ret = efi_locate_handle_buffer_int(BY_PROTOCOL, &efi_simple_file_system_protocol_guid,
554                                            NULL, &count, (efi_handle_t **)&volume_handles);
555         if (ret != EFI_SUCCESS) {
556                 eficonfig_print_msg("No block device found!");
557                 return ret;
558         }
559
560         efi_menu = calloc(1, sizeof(struct efimenu));
561         if (!efi_menu)
562                 return EFI_OUT_OF_RESOURCES;
563
564         INIT_LIST_HEAD(&efi_menu->list);
565         for (i = 0; i < count; i++) {
566                 char *devname;
567                 struct efi_block_io *block_io;
568                 struct eficonfig_volume_entry_data *info;
569
570                 if (efi_menu->count >= EFICONFIG_ENTRY_NUM_MAX - 1)
571                         break;
572
573                 ret = efi_search_protocol(volume_handles[i],
574                                           &efi_simple_file_system_protocol_guid, &handler);
575                 if (ret != EFI_SUCCESS)
576                         continue;
577                 ret = efi_protocol_open(handler, (void **)&v, efi_root, NULL,
578                                         EFI_OPEN_PROTOCOL_GET_PROTOCOL);
579                 if (ret != EFI_SUCCESS)
580                         continue;
581
582                 ret = efi_search_protocol(volume_handles[i], &efi_guid_device_path, &handler);
583                 if (ret != EFI_SUCCESS)
584                         continue;
585                 ret = efi_protocol_open(handler, (void **)&device_path,
586                                         efi_root, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
587                 if (ret != EFI_SUCCESS)
588                         continue;
589
590                 ret = efi_search_protocol(volume_handles[i], &efi_block_io_guid, &handler);
591                 if (ret != EFI_SUCCESS)
592                         continue;
593                 ret = efi_protocol_open(handler, (void **)&block_io,
594                                         efi_root, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
595                 if (ret != EFI_SUCCESS)
596                         continue;
597
598                 info = calloc(1, sizeof(struct eficonfig_volume_entry_data));
599                 if (!info) {
600                         ret = EFI_OUT_OF_RESOURCES;
601                         goto out;
602                 }
603
604                 devname = calloc(1, BOOTMENU_DEVICE_NAME_MAX);
605                 if (!devname) {
606                         free(info);
607                         ret = EFI_OUT_OF_RESOURCES;
608                         goto out;
609                 }
610                 ret = efi_disk_get_device_name(volume_handles[i], devname,
611                                                BOOTMENU_DEVICE_NAME_MAX);
612                 if (ret != EFI_SUCCESS) {
613                         free(info);
614                         goto out;
615                 }
616
617                 info->v = v;
618                 info->dp = device_path;
619                 info->file_info = file_info;
620                 ret = append_entry(efi_menu, devname, eficonfig_volume_selected, info);
621                 if (ret != EFI_SUCCESS) {
622                         free(info);
623                         goto out;
624                 }
625         }
626
627         ret = append_quit_entry(efi_menu);
628         if (ret != EFI_SUCCESS)
629                 goto out;
630
631         ret = eficonfig_process_common(efi_menu, "  ** Select Volume **");
632 out:
633         efi_free_pool(volume_handles);
634         list_for_each_safe(pos, n, &efi_menu->list) {
635                 entry = list_entry(pos, struct eficonfig_entry, list);
636                 free(entry->data);
637         }
638         eficonfig_destroy(efi_menu);
639
640         return ret;
641 }
642
643 /**
644  * sort_file() - sort the file name in ascii order
645  *
646  * @data1:      pointer to the file entry data
647  * @data2:      pointer to the file entry data
648  * Return:      -1 if the data1 file name is less than data2 file name,
649  *              0 if both file name match,
650  *              1 if the data1 file name is greater thant data2 file name.
651  */
652 static int sort_file(const void *arg1, const void *arg2)
653 {
654         const struct eficonfig_file_entry_data *data1, *data2;
655
656         data1 = *((const struct eficonfig_file_entry_data **)arg1);
657         data2 = *((const struct eficonfig_file_entry_data **)arg2);
658
659         return strcasecmp(data1->file_name, data2->file_name);
660 }
661
662 /**
663  * eficonfig_create_file_entry() - construct the file menu entry
664  *
665  * @efi_menu:   pointer to the efimenu structure
666  * @count:      number of the directory and file
667  * @tmp_infos:  pointer to the entry data array
668  * @f:          pointer to the file handle
669  * @buf:        pointer to the buffer to store the directory information
670  * @file_info:  pointer to the file selection structure
671  * Return:      status code
672  */
673 static efi_status_t
674 eficonfig_create_file_entry(struct efimenu *efi_menu, u32 count,
675                             struct eficonfig_file_entry_data **tmp_infos,
676                             struct efi_file_handle *f, struct efi_file_info *buf,
677                             struct eficonfig_select_file_info *file_info)
678 {
679         char *name, *p;
680         efi_uintn_t len;
681         efi_status_t ret;
682         u32 i, entry_num = 0;
683         struct eficonfig_file_entry_data *info;
684
685         efi_file_setpos_int(f, 0);
686         /* Read directory and construct menu structure */
687         for (i = 0; i < count; i++) {
688                 if (entry_num >= EFICONFIG_ENTRY_NUM_MAX - 1)
689                         break;
690
691                 len = sizeof(struct efi_file_info) + EFICONFIG_FILE_PATH_BUF_SIZE;
692                 ret = efi_file_read_int(f, &len, buf);
693                 if (ret != EFI_SUCCESS || len == 0)
694                         break;
695
696                 info = calloc(1, sizeof(struct eficonfig_file_entry_data));
697                 if (!info) {
698                         ret = EFI_OUT_OF_RESOURCES;
699                         goto out;
700                 }
701
702                 /* append '\\' at the end of directory name */
703                 name = calloc(1, utf16_utf8_strlen(buf->file_name) + 2);
704                 if (!name) {
705                         ret = EFI_OUT_OF_RESOURCES;
706                         free(info);
707                         goto out;
708                 }
709                 p = name;
710                 utf16_utf8_strcpy(&p, buf->file_name);
711                 if (buf->attribute & EFI_FILE_DIRECTORY) {
712                         /* filter out u'.' */
713                         if (!u16_strcmp(buf->file_name, u".")) {
714                                 free(info);
715                                 free(name);
716                                 continue;
717                         }
718                         name[u16_strlen(buf->file_name)] = '\\';
719                         info->is_directory = true;
720                 }
721
722                 info->file_name = name;
723                 info->file_info = file_info;
724                 tmp_infos[entry_num++] = info;
725         }
726
727         qsort(tmp_infos, entry_num, sizeof(*tmp_infos),
728               (int (*)(const void *, const void *))sort_file);
729
730         for (i = 0; i < entry_num; i++) {
731                 ret = append_entry(efi_menu, tmp_infos[i]->file_name,
732                                    eficonfig_file_selected, tmp_infos[i]);
733                 if (ret != EFI_SUCCESS)
734                         goto out;
735         }
736
737 out:
738         return ret;
739 }
740
741 /**
742  * eficonfig_select_file() - construct the file selection menu
743  *
744  * @file_info:  pointer to the file selection structure
745  * @root:       pointer to the file handle
746  * Return:      status code
747  */
748 static efi_status_t eficonfig_select_file(struct eficonfig_select_file_info *file_info,
749                                           struct efi_file_handle *root)
750 {
751         u32 count = 0, i;
752         efi_uintn_t len;
753         efi_status_t ret;
754         struct efimenu *efi_menu;
755         struct efi_file_handle *f;
756         struct efi_file_info *buf;
757         struct eficonfig_file_entry_data **tmp_infos;
758
759         buf = calloc(1, sizeof(struct efi_file_info) + EFICONFIG_FILE_PATH_BUF_SIZE);
760         if (!buf)
761                 return EFI_OUT_OF_RESOURCES;
762
763         while (!file_info->file_selected) {
764                 efi_menu = calloc(1, sizeof(struct efimenu));
765                 if (!efi_menu) {
766                         ret = EFI_OUT_OF_RESOURCES;
767                         goto out;
768                 }
769                 INIT_LIST_HEAD(&efi_menu->list);
770
771                 ret = efi_file_open_int(root, &f, file_info->current_path, EFI_FILE_MODE_READ, 0);
772                 if (ret != EFI_SUCCESS) {
773                         eficonfig_print_msg("Reading volume failed!");
774                         free(efi_menu);
775                         ret = EFI_ABORTED;
776                         goto out;
777                 }
778
779                 /* Count the number of directory entries */
780                 for (;;) {
781                         len = sizeof(struct efi_file_info) + EFICONFIG_FILE_PATH_BUF_SIZE;
782                         ret = efi_file_read_int(f, &len, buf);
783                         if (ret != EFI_SUCCESS || len == 0)
784                                 break;
785
786                         count++;
787                 }
788
789                 /* allocate array to sort the entry */
790                 tmp_infos = calloc(count, sizeof(*tmp_infos));
791                 if (!tmp_infos) {
792                         ret = EFI_OUT_OF_RESOURCES;
793                         goto err;
794                 }
795
796                 ret = eficonfig_create_file_entry(efi_menu, count, tmp_infos,
797                                                   f, buf, file_info);
798                 if (ret != EFI_SUCCESS)
799                         goto err;
800
801                 ret = append_quit_entry(efi_menu);
802                 if (ret != EFI_SUCCESS)
803                         goto err;
804
805                 ret = eficonfig_process_common(efi_menu, "  ** Select File **");
806 err:
807                 efi_file_close_int(f);
808                 eficonfig_destroy(efi_menu);
809
810                 if (tmp_infos) {
811                         for (i = 0; i < count; i++)
812                                 free(tmp_infos[i]);
813                 }
814
815                 free(tmp_infos);
816
817                 if (ret != EFI_SUCCESS)
818                         break;
819         }
820
821 out:
822         free(buf);
823
824         return ret;
825 }
826
827 /**
828  * handle_user_input() - handle user input
829  *
830  * @buf:        pointer to the buffer
831  * @buf_size:   size of the buffer
832  * @cursor_col: cursor column for user input
833  * @msg:        pointer to the string to display
834  * Return:      status code
835  */
836 static efi_status_t handle_user_input(u16 *buf, int buf_size,
837                                       int cursor_col, char *msg)
838 {
839         u16 *tmp;
840         efi_status_t ret;
841
842         printf(ANSI_CLEAR_CONSOLE
843                ANSI_CURSOR_POSITION
844                "%s"
845                ANSI_CURSOR_POSITION
846                "  Press ENTER to complete, ESC/CTRL+C to quit",
847                0, 1, msg, 8, 1);
848
849         /* tmp is used to accept user cancel */
850         tmp = calloc(1, buf_size * sizeof(u16));
851         if (!tmp)
852                 return EFI_OUT_OF_RESOURCES;
853
854         ret = efi_console_get_u16_string(cin, tmp, buf_size, NULL, 4, cursor_col);
855         if (ret == EFI_SUCCESS)
856                 u16_strcpy(buf, tmp);
857
858         free(tmp);
859
860         /* to stay the parent menu */
861         ret = (ret == EFI_ABORTED) ? EFI_NOT_READY : ret;
862
863         return ret;
864 }
865
866 /**
867  * eficonfig_boot_add_enter_description() - handle user input for description
868  *
869  * @data:       pointer to the internal boot option structure
870  * Return:      status code
871  */
872 static efi_status_t eficonfig_boot_add_enter_description(void *data)
873 {
874         struct eficonfig_boot_option *bo = data;
875
876         return handle_user_input(bo->description, EFICONFIG_DESCRIPTION_MAX, 22,
877                                  "\n  ** Edit Description **\n"
878                                  "\n"
879                                  "  enter description: ");
880 }
881
882 /**
883  * eficonfig_boot_add_optional_data() - handle user input for optional data
884  *
885  * @data:       pointer to the internal boot option structure
886  * Return:      status code
887  */
888 static efi_status_t eficonfig_boot_add_optional_data(void *data)
889 {
890         struct eficonfig_boot_option *bo = data;
891
892         return handle_user_input(bo->optional_data, EFICONFIG_OPTIONAL_DATA_MAX, 24,
893                                  "\n  ** Edit Optional Data **\n"
894                                  "\n"
895                                  "  enter optional data:");
896 }
897
898 /**
899  * eficonfig_boot_edit_save() - handler to save the boot option
900  *
901  * @data:       pointer to the internal boot option structure
902  * Return:      status code
903  */
904 static efi_status_t eficonfig_boot_edit_save(void *data)
905 {
906         struct eficonfig_boot_option *bo = data;
907
908         if (u16_strlen(bo->description) == 0) {
909                 eficonfig_print_msg("Boot Description is empty!");
910                 bo->edit_completed = false;
911                 return EFI_NOT_READY;
912         }
913         if (u16_strlen(bo->file_info.current_path) == 0) {
914                 eficonfig_print_msg("File is not selected!");
915                 bo->edit_completed = false;
916                 return EFI_NOT_READY;
917         }
918
919         bo->edit_completed = true;
920
921         return EFI_SUCCESS;
922 }
923
924 /**
925  * eficonfig_process_select_file() - callback function for "Select File" entry
926  *
927  * @data:       pointer to the data
928  * Return:      status code
929  */
930 efi_status_t eficonfig_process_select_file(void *data)
931 {
932         return EFI_SUCCESS;
933 }
934
935 /**
936  * eficonfig_process_clear_file_selection() - callback function for "Clear" entry
937  *
938  * @data:       pointer to the data
939  * Return:      status code
940  */
941 efi_status_t eficonfig_process_clear_file_selection(void *data)
942 {
943         struct eficonfig_select_file_info *file_info = data;
944
945         /* clear the existing file information */
946         file_info->current_volume = NULL;
947         file_info->current_path[0] = u'\0';
948         file_info->dp_volume = NULL;
949
950         return EFI_ABORTED;
951 }
952
953 static struct eficonfig_item select_file_menu_items[] = {
954         {"Select File", eficonfig_process_select_file},
955         {"Clear", eficonfig_process_clear_file_selection},
956         {"Quit", eficonfig_process_quit},
957 };
958
959
960 /**
961  * eficonfig_display_select_file_option() - display select file option
962  *
963  * @file_info:  pointer to the file information structure
964  * Return:      status code
965  */
966 efi_status_t eficonfig_display_select_file_option(struct eficonfig_select_file_info *file_info)
967 {
968         efi_status_t ret;
969         struct efimenu *efi_menu;
970
971         select_file_menu_items[1].data = file_info;
972         efi_menu = eficonfig_create_fixed_menu(select_file_menu_items,
973                                                ARRAY_SIZE(select_file_menu_items));
974         if (!efi_menu)
975                 return EFI_OUT_OF_RESOURCES;
976
977         ret = eficonfig_process_common(efi_menu, "  ** Update File **");
978         if (ret != EFI_SUCCESS) /* User selects "Clear" or "Quit" */
979                 ret = EFI_NOT_READY;
980
981         eficonfig_destroy(efi_menu);
982
983         return ret;
984 }
985
986 /**
987  * eficonfig_select_file_handler() - handle user file selection
988  *
989  * @data:       pointer to the data
990  * Return:      status code
991  */
992 efi_status_t eficonfig_select_file_handler(void *data)
993 {
994         size_t len;
995         efi_status_t ret;
996         struct list_head *pos, *n;
997         struct efi_file_handle *root;
998         struct eficonfig_filepath_info *item;
999         struct eficonfig_select_file_info *tmp = NULL;
1000         struct eficonfig_select_file_info *file_info = data;
1001
1002         ret = eficonfig_display_select_file_option(file_info);
1003         if (ret != EFI_SUCCESS)
1004                 return ret;
1005
1006         tmp = calloc(1, sizeof(struct eficonfig_select_file_info));
1007         if (!tmp)
1008                 return EFI_OUT_OF_RESOURCES;
1009
1010         tmp->current_path = calloc(1, EFICONFIG_FILE_PATH_BUF_SIZE);
1011         if (!tmp->current_path) {
1012                 free(tmp);
1013                 return EFI_OUT_OF_RESOURCES;
1014         }
1015         INIT_LIST_HEAD(&tmp->filepath_list);
1016
1017         while (!tmp->file_selected) {
1018                 tmp->current_volume = NULL;
1019                 memset(tmp->current_path, 0, EFICONFIG_FILE_PATH_BUF_SIZE);
1020
1021                 ret = eficonfig_select_volume(tmp);
1022                 if (ret != EFI_SUCCESS)
1023                         goto out;
1024
1025                 if (!tmp->current_volume)
1026                         return EFI_INVALID_PARAMETER;
1027
1028                 ret = efi_open_volume_int(tmp->current_volume, &root);
1029                 if (ret != EFI_SUCCESS)
1030                         goto out;
1031
1032                 ret = eficonfig_select_file(tmp, root);
1033                 if (ret == EFI_ABORTED)
1034                         continue;
1035                 if (ret != EFI_SUCCESS)
1036                         goto out;
1037         }
1038
1039 out:
1040         if (ret == EFI_SUCCESS) {
1041                 len = u16_strlen(tmp->current_path);
1042                 len = (len >= EFICONFIG_FILE_PATH_MAX) ? (EFICONFIG_FILE_PATH_MAX - 1) : len;
1043                 memcpy(file_info->current_path, tmp->current_path, len * sizeof(u16));
1044                 file_info->current_path[len] = u'\0';
1045                 file_info->current_volume = tmp->current_volume;
1046                 file_info->dp_volume = tmp->dp_volume;
1047         }
1048
1049         list_for_each_safe(pos, n, &tmp->filepath_list) {
1050                 item = list_entry(pos, struct eficonfig_filepath_info, list);
1051                 list_del(&item->list);
1052                 free(item->name);
1053                 free(item);
1054         }
1055         free(tmp->current_path);
1056         free(tmp);
1057
1058         /* to stay the parent menu */
1059         ret = (ret == EFI_ABORTED) ? EFI_NOT_READY : ret;
1060
1061         return ret;
1062 }
1063
1064 /**
1065  * eficonfig_get_unused_bootoption() - get unused "Boot####" index
1066  *
1067  * @buf:        pointer to the buffer to store boot option variable name
1068  * @buf_size:   buffer size
1069  * @index:      pointer to store the index in the BootOrder variable
1070  * Return:      status code
1071  */
1072 efi_status_t eficonfig_get_unused_bootoption(u16 *buf, efi_uintn_t buf_size,
1073                                              unsigned int *index)
1074 {
1075         u32 i;
1076         efi_status_t ret;
1077         efi_uintn_t size;
1078
1079         if (buf_size < u16_strsize(u"Boot####"))
1080                 return EFI_BUFFER_TOO_SMALL;
1081
1082         for (i = 0; i <= 0xFFFF; i++) {
1083                 size = 0;
1084                 efi_create_indexed_name(buf, buf_size, "Boot", i);
1085                 ret = efi_get_variable_int(buf, &efi_global_variable_guid,
1086                                            NULL, &size, NULL, NULL);
1087                 if (ret == EFI_BUFFER_TOO_SMALL)
1088                         continue;
1089                 else
1090                         break;
1091         }
1092
1093         if (i > 0xFFFF)
1094                 return EFI_OUT_OF_RESOURCES;
1095
1096         *index = i;
1097
1098         return EFI_SUCCESS;
1099 }
1100
1101 /**
1102  * eficonfig_set_boot_option() - set boot option
1103  *
1104  * @varname:            pointer to variable name
1105  * @dp:                 pointer to device path
1106  * @label:              pointer to label string
1107  * @optional_data:      pointer to optional data
1108  * Return:              status code
1109  */
1110 static efi_status_t eficonfig_set_boot_option(u16 *varname, struct efi_device_path *dp,
1111                                               efi_uintn_t dp_size, u16 *label, char *optional_data)
1112 {
1113         void *p = NULL;
1114         efi_status_t ret;
1115         efi_uintn_t size;
1116         struct efi_load_option lo;
1117
1118         lo.file_path = dp;
1119         lo.file_path_length = dp_size;
1120         lo.attributes = LOAD_OPTION_ACTIVE;
1121         lo.optional_data = optional_data;
1122         lo.label = label;
1123
1124         size = efi_serialize_load_option(&lo, (u8 **)&p);
1125         if (!size)
1126                 return EFI_INVALID_PARAMETER;
1127
1128         ret = efi_set_variable_int(varname, &efi_global_variable_guid,
1129                                    EFI_VARIABLE_NON_VOLATILE |
1130                                    EFI_VARIABLE_BOOTSERVICE_ACCESS |
1131                                    EFI_VARIABLE_RUNTIME_ACCESS,
1132                                    size, p, false);
1133         free(p);
1134
1135         return ret;
1136 }
1137
1138 /**
1139  * eficonfig_append_bootorder() - append new boot option in BootOrder variable
1140  *
1141  * @index:      "Boot####" index to append to BootOrder variable
1142  * Return:      status code
1143  */
1144 efi_status_t eficonfig_append_bootorder(u16 index)
1145 {
1146         u16 *bootorder;
1147         efi_status_t ret;
1148         u16 *new_bootorder = NULL;
1149         efi_uintn_t last, size, new_size;
1150
1151         /* append new boot option */
1152         bootorder = efi_get_var(u"BootOrder", &efi_global_variable_guid, &size);
1153         last = size / sizeof(u16);
1154         new_size = size + sizeof(u16);
1155         new_bootorder = calloc(1, new_size);
1156         if (!new_bootorder) {
1157                 ret = EFI_OUT_OF_RESOURCES;
1158                 goto out;
1159         }
1160         memcpy(new_bootorder, bootorder, size);
1161         new_bootorder[last] = index;
1162
1163         ret = efi_set_variable_int(u"BootOrder", &efi_global_variable_guid,
1164                                    EFI_VARIABLE_NON_VOLATILE |
1165                                    EFI_VARIABLE_BOOTSERVICE_ACCESS |
1166                                    EFI_VARIABLE_RUNTIME_ACCESS,
1167                                    new_size, new_bootorder, false);
1168         if (ret != EFI_SUCCESS)
1169                 goto out;
1170
1171 out:
1172         free(bootorder);
1173         free(new_bootorder);
1174
1175         return ret;
1176 }
1177
1178 /**
1179  * create_boot_option_entry() - create boot option entry
1180  *
1181  * @efi_menu:   pointer to the efimenu structure
1182  * @title:      pointer to the entry title
1183  * @val:        pointer to boot option label
1184  * @func:       callback of each entry
1185  * @data:       pointer to the data to be passed to each entry callback
1186  * Return:      status code
1187  */
1188 static efi_status_t create_boot_option_entry(struct efimenu *efi_menu, char *title, u16 *val,
1189                                              eficonfig_entry_func func, void *data)
1190 {
1191         u32 len;
1192         char *p, *buf;
1193
1194         len = strlen(title) + 1;
1195         if (val)
1196                 len += utf16_utf8_strlen(val);
1197         buf = calloc(1, len);
1198         if (!buf)
1199                 return EFI_OUT_OF_RESOURCES;
1200
1201         strcpy(buf, title);
1202         if (val) {
1203                 p = buf + strlen(title);
1204                 utf16_utf8_strcpy(&p, val);
1205         }
1206
1207         return append_entry(efi_menu, buf, func, data);
1208 }
1209
1210 /**
1211  * prepare_file_selection_entry() - prepare file selection entry
1212  *
1213  * @efi_menu:   pointer to the efimenu structure
1214  * @title:      pointer to the title string
1215  * @file_info:  pointer to the file info
1216  * Return:      status code
1217  */
1218 static efi_status_t prepare_file_selection_entry(struct efimenu *efi_menu, char *title,
1219                                                  struct eficonfig_select_file_info *file_info)
1220 {
1221         u32 len;
1222         efi_status_t ret;
1223         u16 *file_name = NULL, *p;
1224         efi_handle_t handle;
1225         char *devname;
1226
1227         devname = calloc(1, EFICONFIG_VOLUME_PATH_MAX + 1);
1228         if (!devname)
1229                 return EFI_OUT_OF_RESOURCES;
1230
1231         /* get the device name only when the user already selected the file path */
1232         handle = efi_dp_find_obj(file_info->dp_volume, NULL, NULL);
1233         if (handle) {
1234                 ret = efi_disk_get_device_name(handle, devname, EFICONFIG_VOLUME_PATH_MAX);
1235                 if (ret != EFI_SUCCESS)
1236                         goto out;
1237         }
1238
1239         /*
1240          * If the preconfigured volume does not exist in the system, display the text
1241          * converted volume device path instead of U-Boot friendly name(e.g. "usb 0:1").
1242          */
1243         if (!handle && file_info->dp_volume) {
1244                 u16 *dp_str;
1245                 char *q = devname;
1246
1247                 dp_str = efi_dp_str(file_info->dp_volume);
1248                 if (dp_str)
1249                         utf16_utf8_strncpy(&q, dp_str, EFICONFIG_VOLUME_PATH_MAX);
1250
1251                 efi_free_pool(dp_str);
1252         }
1253
1254         /* append u'/' to devname, it is just for display purpose. */
1255         if (file_info->current_path[0] != u'\0' && file_info->current_path[0] != u'/')
1256                 strlcat(devname, "/", EFICONFIG_VOLUME_PATH_MAX + 1);
1257
1258         len = strlen(devname);
1259         len += utf16_utf8_strlen(file_info->current_path) + 1;
1260         file_name = calloc(1, len * sizeof(u16));
1261         if (!file_name) {
1262                 ret = EFI_OUT_OF_RESOURCES;
1263                 goto out;
1264         }
1265
1266         p = file_name;
1267         utf8_utf16_strcpy(&p, devname);
1268         u16_strlcat(file_name, file_info->current_path, len);
1269         ret = create_boot_option_entry(efi_menu, title, file_name,
1270                                        eficonfig_select_file_handler, file_info);
1271 out:
1272         free(devname);
1273         free(file_name);
1274
1275         return ret;
1276 }
1277
1278 /**
1279  * eficonfig_show_boot_option() - prepare menu entry for editing boot option
1280  *
1281  * Construct the structures to create edit boot option menu
1282  *
1283  * @bo:         pointer to the boot option
1284  * @header_str: pointer to the header string
1285  * Return:      status code
1286  */
1287 static efi_status_t eficonfig_show_boot_option(struct eficonfig_boot_option *bo,
1288                                                char *header_str)
1289 {
1290         efi_status_t ret;
1291         struct efimenu *efi_menu;
1292
1293         efi_menu = calloc(1, sizeof(struct efimenu));
1294         if (!efi_menu)
1295                 return EFI_OUT_OF_RESOURCES;
1296
1297         INIT_LIST_HEAD(&efi_menu->list);
1298
1299         ret = create_boot_option_entry(efi_menu, "Description: ", bo->description,
1300                                        eficonfig_boot_add_enter_description, bo);
1301         if (ret != EFI_SUCCESS)
1302                 goto out;
1303
1304         ret = prepare_file_selection_entry(efi_menu, "File: ", &bo->file_info);
1305         if (ret != EFI_SUCCESS)
1306                 goto out;
1307
1308         ret = prepare_file_selection_entry(efi_menu, "Initrd File: ", &bo->initrd_info);
1309         if (ret != EFI_SUCCESS)
1310                 goto out;
1311
1312         ret = create_boot_option_entry(efi_menu, "Optional Data: ", bo->optional_data,
1313                                        eficonfig_boot_add_optional_data, bo);
1314         if (ret != EFI_SUCCESS)
1315                 goto out;
1316
1317         ret = create_boot_option_entry(efi_menu, "Save", NULL,
1318                                        eficonfig_boot_edit_save, bo);
1319         if (ret != EFI_SUCCESS)
1320                 goto out;
1321
1322         ret = create_boot_option_entry(efi_menu, "Quit", NULL,
1323                                        eficonfig_process_quit, NULL);
1324         if (ret != EFI_SUCCESS)
1325                 goto out;
1326
1327         ret = eficonfig_process_common(efi_menu, header_str);
1328 out:
1329         eficonfig_destroy(efi_menu);
1330
1331         return ret;
1332 }
1333
1334 /**
1335  * fill_file_info() - fill the file info from efi_device_path structure
1336  *
1337  * @dp:         pointer to the device path
1338  * @file_info:  pointer to the file info structure
1339  * @device_dp:  pointer to the volume device path
1340  */
1341 static void fill_file_info(struct efi_device_path *dp,
1342                            struct eficonfig_select_file_info *file_info,
1343                            struct efi_device_path *device_dp)
1344 {
1345         u16 *file_str, *p;
1346         struct efi_device_path *file_dp = NULL;
1347
1348         efi_dp_split_file_path(dp, &device_dp, &file_dp);
1349         file_info->dp_volume = device_dp;
1350
1351         if (file_dp) {
1352                 file_str = efi_dp_str(file_dp);
1353                 /*
1354                  * efi_convert_device_path_to_text() automatically adds u'/' at the
1355                  * beginning of file name, remove u'/' before copying to current_path
1356                  */
1357                 p = file_str;
1358                 if (p[0] == u'/')
1359                         p++;
1360
1361                 u16_strcpy(file_info->current_path, p);
1362                 efi_free_pool(file_dp);
1363                 efi_free_pool(file_str);
1364         }
1365 }
1366
1367 /**
1368  * eficonfig_edit_boot_option() - prepare boot option structure for editing
1369  *
1370  * Construct the boot option structure and copy the existing value
1371  *
1372  * @varname:            pointer to the UEFI variable name
1373  * @bo:                 pointer to the boot option
1374  * @load_option:        pointer to the load option
1375  * @load_option_size:   size of the load option
1376  * @header_str:         pointer to the header string
1377  * Return       :       status code
1378  */
1379 static efi_status_t eficonfig_edit_boot_option(u16 *varname, struct eficonfig_boot_option *bo,
1380                                                void *load_option, efi_uintn_t load_option_size,
1381                                                char *header_str)
1382 {
1383         size_t len;
1384         efi_status_t ret;
1385         char *tmp = NULL, *p;
1386         struct efi_load_option lo = {0};
1387         efi_uintn_t final_dp_size;
1388         struct efi_device_path *dp = NULL;
1389         efi_uintn_t size = load_option_size;
1390         struct efi_device_path *final_dp = NULL;
1391         struct efi_device_path *device_dp = NULL;
1392         struct efi_device_path *initrd_dp = NULL;
1393         struct efi_device_path *initrd_device_dp = NULL;
1394
1395         const struct efi_initrd_dp id_dp = {
1396                 .vendor = {
1397                         {
1398                         DEVICE_PATH_TYPE_MEDIA_DEVICE,
1399                         DEVICE_PATH_SUB_TYPE_VENDOR_PATH,
1400                         sizeof(id_dp.vendor),
1401                         },
1402                         EFI_INITRD_MEDIA_GUID,
1403                 },
1404                 .end = {
1405                         DEVICE_PATH_TYPE_END,
1406                         DEVICE_PATH_SUB_TYPE_END,
1407                         sizeof(id_dp.end),
1408                 }
1409         };
1410
1411         bo->file_info.current_path = calloc(1, EFICONFIG_FILE_PATH_BUF_SIZE);
1412         if (!bo->file_info.current_path) {
1413                 ret =  EFI_OUT_OF_RESOURCES;
1414                 goto out;
1415         }
1416
1417         bo->initrd_info.current_path = calloc(1, EFICONFIG_FILE_PATH_BUF_SIZE);
1418         if (!bo->file_info.current_path) {
1419                 ret =  EFI_OUT_OF_RESOURCES;
1420                 goto out;
1421         }
1422
1423         bo->description = calloc(1, EFICONFIG_DESCRIPTION_MAX * sizeof(u16));
1424         if (!bo->description) {
1425                 ret =  EFI_OUT_OF_RESOURCES;
1426                 goto out;
1427         }
1428
1429         bo->optional_data = calloc(1, EFICONFIG_OPTIONAL_DATA_MAX * sizeof(u16));
1430         if (!bo->optional_data) {
1431                 ret =  EFI_OUT_OF_RESOURCES;
1432                 goto out;
1433         }
1434
1435         /* copy the preset value */
1436         if (load_option) {
1437                 ret = efi_deserialize_load_option(&lo, load_option, &size);
1438                 if (ret != EFI_SUCCESS)
1439                         goto out;
1440
1441                 if (!lo.label) {
1442                         ret = EFI_INVALID_PARAMETER;
1443                         goto out;
1444                 }
1445                 /* truncate the long label string */
1446                 if (u16_strlen(lo.label) >= EFICONFIG_DESCRIPTION_MAX)
1447                         lo.label[EFICONFIG_DESCRIPTION_MAX - 1] = u'\0';
1448
1449                 u16_strcpy(bo->description, lo.label);
1450
1451                 /* EFI image file path is a first instance */
1452                 if (lo.file_path)
1453                         fill_file_info(lo.file_path, &bo->file_info, device_dp);
1454
1455                 /* Initrd file path(optional) is placed at second instance. */
1456                 initrd_dp = efi_dp_from_lo(&lo, &efi_lf2_initrd_guid);
1457                 if (initrd_dp) {
1458                         fill_file_info(initrd_dp, &bo->initrd_info, initrd_device_dp);
1459                         efi_free_pool(initrd_dp);
1460                 }
1461
1462                 if (size > 0)
1463                         memcpy(bo->optional_data, lo.optional_data, size);
1464         }
1465
1466         while (1) {
1467                 ret = eficonfig_show_boot_option(bo, header_str);
1468                 if (ret == EFI_SUCCESS && bo->edit_completed)
1469                         break;
1470                 if (ret == EFI_NOT_READY)
1471                         continue;
1472                 if (ret != EFI_SUCCESS)
1473                         goto out;
1474         }
1475
1476         if (bo->initrd_info.dp_volume) {
1477                 dp = create_selected_device_path(&bo->initrd_info);
1478                 if (!dp) {
1479                         ret = EFI_OUT_OF_RESOURCES;
1480                         goto out;
1481                 }
1482                 initrd_dp = efi_dp_append((const struct efi_device_path *)&id_dp, dp);
1483                 efi_free_pool(dp);
1484         }
1485
1486         dp = create_selected_device_path(&bo->file_info);
1487         if (!dp) {
1488                 ret = EFI_OUT_OF_RESOURCES;
1489                 goto out;
1490         }
1491         final_dp_size = efi_dp_size(dp) + sizeof(END);
1492         if (initrd_dp) {
1493                 final_dp = efi_dp_concat(dp, initrd_dp);
1494                 final_dp_size += efi_dp_size(initrd_dp) + sizeof(END);
1495         } else {
1496                 final_dp = efi_dp_dup(dp);
1497         }
1498         efi_free_pool(dp);
1499
1500         if (!final_dp)
1501                 goto out;
1502
1503         if (utf16_utf8_strlen(bo->optional_data)) {
1504                 len = utf16_utf8_strlen(bo->optional_data) + 1;
1505                 tmp = calloc(1, len);
1506                 if (!tmp)
1507                         goto out;
1508                 p = tmp;
1509                 utf16_utf8_strncpy(&p, bo->optional_data, u16_strlen(bo->optional_data));
1510         }
1511
1512         ret = eficonfig_set_boot_option(varname, final_dp, final_dp_size, bo->description, tmp);
1513         if (ret != EFI_SUCCESS)
1514                 goto out;
1515 out:
1516         free(tmp);
1517         free(bo->optional_data);
1518         free(bo->description);
1519         free(bo->file_info.current_path);
1520         free(bo->initrd_info.current_path);
1521         efi_free_pool(device_dp);
1522         efi_free_pool(initrd_device_dp);
1523         efi_free_pool(initrd_dp);
1524         efi_free_pool(final_dp);
1525
1526         return ret;
1527 }
1528
1529 /**
1530  * eficonfig_process_add_boot_option() - handler to add boot option
1531  *
1532  * @data:       pointer to the data for each entry
1533  * Return:      status code
1534  */
1535 static efi_status_t eficonfig_process_add_boot_option(void *data)
1536 {
1537         u16 varname[9];
1538         efi_status_t ret;
1539         struct eficonfig_boot_option *bo = NULL;
1540
1541         bo = calloc(1, sizeof(struct eficonfig_boot_option));
1542         if (!bo)
1543                 return EFI_OUT_OF_RESOURCES;
1544
1545         ret = eficonfig_get_unused_bootoption(varname, sizeof(varname), &bo->boot_index);
1546         if (ret != EFI_SUCCESS)
1547                 return ret;
1548
1549         ret = eficonfig_edit_boot_option(varname, bo, NULL, 0,  "  ** Add Boot Option ** ");
1550         if (ret != EFI_SUCCESS)
1551                 goto out;
1552
1553         ret = eficonfig_append_bootorder((u16)bo->boot_index);
1554         if (ret != EFI_SUCCESS)
1555                 goto out;
1556
1557 out:
1558         free(bo);
1559
1560         /* to stay the parent menu */
1561         ret = (ret == EFI_ABORTED) ? EFI_SUCCESS : ret;
1562
1563         return ret;
1564 }
1565
1566 /**
1567  * eficonfig_process_boot_selected() - handler to select boot option entry
1568  *
1569  * @data:       pointer to the data for each entry
1570  * Return:      status code
1571  */
1572 static efi_status_t eficonfig_process_boot_selected(void *data)
1573 {
1574         struct eficonfig_boot_selection_data *info = data;
1575
1576         if (info)
1577                 *info->selected = info->boot_index;
1578
1579         return EFI_SUCCESS;
1580 }
1581
1582 /**
1583  * search_bootorder() - search the boot option index in BootOrder
1584  *
1585  * @bootorder:  pointer to the BootOrder variable
1586  * @num:        number of BootOrder entry
1587  * @target:     target boot option index to search
1588  * @index:      pointer to store the index of BootOrder variable
1589  * Return:      true if exists, false otherwise
1590  */
1591 static bool search_bootorder(u16 *bootorder, efi_uintn_t num, u32 target, u32 *index)
1592 {
1593         u32 i;
1594
1595         for (i = 0; i < num; i++) {
1596                 if (target == bootorder[i]) {
1597                         if (index)
1598                                 *index = i;
1599
1600                         return true;
1601                 }
1602         }
1603
1604         return false;
1605 }
1606
1607 /**
1608  * eficonfig_add_boot_selection_entry() - add boot option menu entry
1609  *
1610  * @efi_menu:   pointer to store the efimenu structure
1611  * @boot_index: boot option index to be added
1612  * @selected:   pointer to store the selected boot option index
1613  * Return:      status code
1614  */
1615 static efi_status_t eficonfig_add_boot_selection_entry(struct efimenu *efi_menu,
1616                                                        unsigned int boot_index,
1617                                                        unsigned int *selected)
1618 {
1619         char *buf, *p;
1620         efi_status_t ret;
1621         efi_uintn_t size;
1622         void *load_option;
1623         struct efi_load_option lo;
1624         u16 varname[] = u"Boot####";
1625         struct eficonfig_boot_selection_data *info;
1626
1627         efi_create_indexed_name(varname, sizeof(varname), "Boot", boot_index);
1628         load_option = efi_get_var(varname, &efi_global_variable_guid, &size);
1629         if (!load_option)
1630                 return EFI_SUCCESS;
1631
1632         ret = efi_deserialize_load_option(&lo, load_option, &size);
1633         if (ret != EFI_SUCCESS) {
1634                 log_warning("Invalid load option for %ls\n", varname);
1635                 free(load_option);
1636                 return ret;
1637         }
1638
1639         if (size >= sizeof(efi_guid_t) &&
1640             !guidcmp(lo.optional_data, &efi_guid_bootmenu_auto_generated)) {
1641                 /*
1642                  * auto generated entry has GUID in optional_data,
1643                  * skip auto generated entry because it will be generated
1644                  * again even if it is edited or deleted.
1645                  */
1646                 free(load_option);
1647                 return EFI_SUCCESS;
1648         }
1649
1650         info = calloc(1, sizeof(struct eficonfig_boot_selection_data));
1651         if (!info) {
1652                 free(load_option);
1653                 return EFI_OUT_OF_RESOURCES;
1654         }
1655
1656         buf = calloc(1, utf16_utf8_strlen(lo.label) + 1);
1657         if (!buf) {
1658                 free(load_option);
1659                 free(info);
1660                 return EFI_OUT_OF_RESOURCES;
1661         }
1662         p = buf;
1663         utf16_utf8_strcpy(&p, lo.label);
1664         info->boot_index = boot_index;
1665         info->selected = selected;
1666         ret = append_entry(efi_menu, buf, eficonfig_process_boot_selected, info);
1667         if (ret != EFI_SUCCESS) {
1668                 free(load_option);
1669                 free(info);
1670                 return ret;
1671         }
1672         free(load_option);
1673
1674         return EFI_SUCCESS;
1675 }
1676
1677 /**
1678  * eficonfig_show_boot_selection() - construct boot option menu entry
1679  *
1680  * @selected:   pointer to store the selected boot option index
1681  * Return:      status code
1682  */
1683 static efi_status_t eficonfig_show_boot_selection(unsigned int *selected)
1684 {
1685         u32 i;
1686         u16 *bootorder;
1687         efi_status_t ret;
1688         efi_uintn_t num, size;
1689         struct efimenu *efi_menu;
1690         struct list_head *pos, *n;
1691         struct eficonfig_entry *entry;
1692
1693         efi_menu = calloc(1, sizeof(struct efimenu));
1694         if (!efi_menu)
1695                 return EFI_OUT_OF_RESOURCES;
1696
1697         bootorder = efi_get_var(u"BootOrder", &efi_global_variable_guid, &size);
1698
1699         INIT_LIST_HEAD(&efi_menu->list);
1700         num = size / sizeof(u16);
1701         /* list the load option in the order of BootOrder variable */
1702         for (i = 0; i < num; i++) {
1703                 ret = eficonfig_add_boot_selection_entry(efi_menu, bootorder[i], selected);
1704                 if (ret != EFI_SUCCESS)
1705                         goto out;
1706
1707                 if (efi_menu->count >= EFICONFIG_ENTRY_NUM_MAX - 1)
1708                         break;
1709         }
1710
1711         /* list the remaining load option not included in the BootOrder */
1712         for (i = 0; i <= 0xFFFF; i++) {
1713                 /* If the index is included in the BootOrder, skip it */
1714                 if (search_bootorder(bootorder, num, i, NULL))
1715                         continue;
1716
1717                 ret = eficonfig_add_boot_selection_entry(efi_menu, i, selected);
1718                 if (ret != EFI_SUCCESS)
1719                         goto out;
1720
1721                 if (efi_menu->count >= EFICONFIG_ENTRY_NUM_MAX - 1)
1722                         break;
1723         }
1724
1725         ret = append_quit_entry(efi_menu);
1726         if (ret != EFI_SUCCESS)
1727                 goto out;
1728
1729         ret = eficonfig_process_common(efi_menu, "  ** Select Boot Option **");
1730 out:
1731         list_for_each_safe(pos, n, &efi_menu->list) {
1732                 entry = list_entry(pos, struct eficonfig_entry, list);
1733                 free(entry->data);
1734         }
1735         eficonfig_destroy(efi_menu);
1736
1737         return ret;
1738 }
1739
1740 /**
1741  * eficonfig_process_edit_boot_option() - handler to edit boot option
1742  *
1743  * @data:       pointer to the data for each entry
1744  * Return:      status code
1745  */
1746 static efi_status_t eficonfig_process_edit_boot_option(void *data)
1747 {
1748         efi_status_t ret;
1749         efi_uintn_t size;
1750         struct eficonfig_boot_option *bo = NULL;
1751
1752         while (1) {
1753                 unsigned int selected;
1754                 void *load_option;
1755                 u16 varname[] = u"Boot####";
1756
1757                 ret = eficonfig_show_boot_selection(&selected);
1758                 if (ret != EFI_SUCCESS)
1759                         break;
1760
1761                 bo = calloc(1, sizeof(struct eficonfig_boot_option));
1762                 if (!bo) {
1763                         ret = EFI_OUT_OF_RESOURCES;
1764                         goto out;
1765                 }
1766
1767                 bo->boot_index = selected;
1768                 efi_create_indexed_name(varname, sizeof(varname), "Boot", selected);
1769                 load_option = efi_get_var(varname, &efi_global_variable_guid, &size);
1770                 if (!load_option) {
1771                         free(bo);
1772                         ret = EFI_NOT_FOUND;
1773                         goto out;
1774                 }
1775
1776                 ret = eficonfig_edit_boot_option(varname, bo, load_option, size,
1777                                                  "  ** Edit Boot Option ** ");
1778
1779                 free(load_option);
1780                 free(bo);
1781                 if (ret != EFI_SUCCESS && ret != EFI_ABORTED)
1782                         break;
1783         }
1784 out:
1785         /* to stay the parent menu */
1786         ret = (ret == EFI_ABORTED) ? EFI_NOT_READY : ret;
1787
1788         return ret;
1789 }
1790
1791 /**
1792  * eficonfig_init() - do required initialization for eficonfig command
1793  *
1794  * Return:      status code
1795  */
1796 static efi_status_t eficonfig_init(void)
1797 {
1798         efi_status_t ret = EFI_SUCCESS;
1799         static bool init;
1800         struct efi_handler *handler;
1801
1802         if (!init) {
1803                 ret = efi_search_protocol(efi_root, &efi_guid_text_input_protocol, &handler);
1804                 if (ret != EFI_SUCCESS)
1805                         return ret;
1806
1807                 ret = efi_protocol_open(handler, (void **)&cin, efi_root, NULL,
1808                                         EFI_OPEN_PROTOCOL_GET_PROTOCOL);
1809                 if (ret != EFI_SUCCESS)
1810                         return ret;
1811         }
1812
1813         init = true;
1814
1815         return ret;
1816 }
1817
1818 static const struct eficonfig_item maintenance_menu_items[] = {
1819         {"Add Boot Option", eficonfig_process_add_boot_option},
1820         {"Edit Boot Option", eficonfig_process_edit_boot_option},
1821         {"Quit", eficonfig_process_quit},
1822 };
1823
1824 /**
1825  * do_eficonfig() - execute `eficonfig` command
1826  *
1827  * @cmdtp:      table entry describing command
1828  * @flag:       bitmap indicating how the command was invoked
1829  * @argc:       number of arguments
1830  * @argv:       command line arguments
1831  * Return:      status code
1832  */
1833 static int do_eficonfig(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
1834 {
1835         efi_status_t ret;
1836         struct efimenu *efi_menu;
1837
1838         if (argc > 1)
1839                 return CMD_RET_USAGE;
1840
1841         ret = efi_init_obj_list();
1842         if (ret != EFI_SUCCESS) {
1843                 log_err("Error: Cannot initialize UEFI sub-system, r = %lu\n",
1844                         ret & ~EFI_ERROR_MASK);
1845
1846                 return CMD_RET_FAILURE;
1847         }
1848
1849         ret = eficonfig_init();
1850         if (ret != EFI_SUCCESS)
1851                 return CMD_RET_FAILURE;
1852
1853         while (1) {
1854                 efi_menu = eficonfig_create_fixed_menu(maintenance_menu_items,
1855                                                        ARRAY_SIZE(maintenance_menu_items));
1856                 if (!efi_menu)
1857                         return CMD_RET_FAILURE;
1858
1859                 ret = eficonfig_process_common(efi_menu, "  ** UEFI Maintenance Menu **");
1860                 eficonfig_destroy(efi_menu);
1861
1862                 if (ret == EFI_ABORTED)
1863                         break;
1864         }
1865
1866         return CMD_RET_SUCCESS;
1867 }
1868
1869 U_BOOT_CMD(
1870         eficonfig, 1, 0, do_eficonfig,
1871         "provide menu-driven UEFI variable maintenance interface",
1872         ""
1873 );