1f0f3dbc94fdf61d4a3a364360600ebef7847eba
[debian/efibootmgr] / src / lib / efi.c
1 /*
2   efivars_proc.[ch] - Manipulates EFI variables as exported in /proc/efi/vars
3
4   Copyright (C) 2001,2003 Dell Computer Corporation <Matt_Domsch@dell.com>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #define _FILE_OFFSET_BITS 64
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <stdint.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <unistd.h>
32 #include <dirent.h>
33 #include <sys/socket.h>
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <linux/sockios.h>
37 #include <net/if.h>
38 #include <pci/pci.h>
39 #include <linux/ethtool.h>
40 #include "efi.h"
41 #include "efichar.h"
42 #include "scsi_ioctls.h"
43 #include "disk.h"
44 #include "efibootmgr.h"
45 #include "efivars_procfs.h"
46 #include "efivars_sysfs.h"
47 #include "list.h"
48
49 static struct efivar_kernel_calls *fs_kernel_calls;
50
51 EFI_DEVICE_PATH *
52 load_option_path(EFI_LOAD_OPTION *option)
53 {
54         char *p = (char *) option;
55         return (EFI_DEVICE_PATH *)
56                 (p + sizeof(uint32_t) /* Attributes */
57                  + sizeof(uint16_t)   /* FilePathListLength*/
58                  + efichar_strsize(option->description)); /* Description */
59 }
60
61 char *
62 efi_guid_unparse(efi_guid_t *guid, char *out)
63 {
64         sprintf(out, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
65                 guid->b[3], guid->b[2], guid->b[1], guid->b[0],
66                 guid->b[5], guid->b[4], guid->b[7], guid->b[6],
67                 guid->b[8], guid->b[9], guid->b[10], guid->b[11],
68                 guid->b[12], guid->b[13], guid->b[14], guid->b[15]);
69         return out;
70 }
71
72 void
73 set_fs_kernel_calls()
74 {
75         char name[PATH_MAX];
76         DIR *dir;
77         snprintf(name, PATH_MAX, "%s", SYSFS_DIR_EFI_VARS);
78         dir = opendir(name);
79         if (dir) {
80                 closedir(dir);
81                 fs_kernel_calls = &sysfs_kernel_calls;
82                 return;
83         }
84
85         snprintf(name, PATH_MAX, "%s", PROCFS_DIR_EFI_VARS);
86         dir = opendir(name);
87         if (dir) {
88                 closedir(dir);
89                 fs_kernel_calls = &procfs_kernel_calls;
90                 return;
91         }
92         fprintf(stderr, "Fatal: Couldn't open either sysfs or procfs directories for accessing EFI variables.\n");
93         fprintf(stderr, "Try 'modprobe efivars' as root.\n");
94         exit(1);
95 }
96
97
98
99 static efi_status_t
100 write_variable_to_file(efi_variable_t *var)
101 {
102         int fd, byteswritten;
103         if (!var || !opts.testfile) return EFI_INVALID_PARAMETER;
104
105         printf("Test mode: Writing to %s\n", opts.testfile);
106         fd = creat(opts.testfile, S_IRWXU);
107         if (fd == -1) {
108                 perror("Couldn't write to testfile");
109                 return EFI_INVALID_PARAMETER;
110         }
111
112         byteswritten = write(fd, var, sizeof(*var));
113         if (byteswritten == -1) {
114                 perror("Writing to testfile");
115
116         }
117         close(fd);
118         return EFI_SUCCESS;
119 }
120
121 efi_status_t
122 read_variable(const char *name, efi_variable_t *var)
123 {
124         if (!name || !var) return EFI_INVALID_PARAMETER;
125         return fs_kernel_calls->read(name, var);
126 }
127
128 efi_status_t
129 create_variable(efi_variable_t *var)
130 {
131         if (!var) return EFI_INVALID_PARAMETER;
132         if (opts.testfile) return write_variable_to_file(var);
133         return fs_kernel_calls->create(var);
134 }
135
136 efi_status_t
137 delete_variable(efi_variable_t *var)
138 {
139         if (!var) return EFI_INVALID_PARAMETER;
140         if (opts.testfile) return write_variable_to_file(var);
141         return fs_kernel_calls->delete(var);
142 }
143
144
145 efi_status_t
146 edit_variable(efi_variable_t *var)
147 {
148         char name[PATH_MAX];
149         if (!var) return EFI_INVALID_PARAMETER;
150         if (opts.testfile) return write_variable_to_file(var);
151
152         variable_to_name(var, name);
153         return fs_kernel_calls->edit(name, var);
154 }
155
156 efi_status_t
157 create_or_edit_variable(efi_variable_t *var)
158 {
159         efi_variable_t testvar;
160         char name[PATH_MAX];
161
162         memcpy(&testvar, var, sizeof(*var));
163         variable_to_name(var, name);
164
165         if (read_variable(name, &testvar) == EFI_SUCCESS)
166                 return edit_variable(var);
167         else
168                 return create_variable(var);
169 }
170
171 static int
172 select_boot_var_names(const struct dirent *d)
173 {
174         int num, rc;
175         rc = sscanf(d->d_name, "Boot0%03x-%*s", &num);
176         return rc;
177 }
178
179 int
180 read_boot_var_names(struct dirent ***namelist)
181 {
182         if (!fs_kernel_calls || !namelist) return -1;
183         return scandir(fs_kernel_calls->path,
184                        namelist, select_boot_var_names,
185                        alphasort);
186 }
187
188
189 static int
190 get_edd_version()
191 {
192         efi_status_t status;
193         efi_variable_t var;
194         efi_guid_t guid = BLKX_UNKNOWN_GUID;
195         char name[80], text_guid[40];
196         ACPI_DEVICE_PATH *path = (ACPI_DEVICE_PATH *)&(var.Data);
197         int rc = 0;
198
199         /* Allow global user option override */
200
201         switch (opts.edd_version)
202         {
203         case 0: /* No EDD information */
204                 return 0;
205                 break;
206         case 1: /* EDD 1.0 */
207                 return 1;
208                 break;
209         case 3: /* EDD 3.0 */
210                 return 3;
211                 break;
212         default:
213                 break;
214         }
215
216
217         memset(&var, 0, sizeof(efi_variable_t));
218         efi_guid_unparse(&guid, text_guid);
219         sprintf(name, "blk0-%s", text_guid);
220
221         status = read_variable(name, &var);
222         if (status != EFI_SUCCESS) {
223                 return 0;
224         }
225         if (path->type == 2 && path->subtype == 1) rc = 3;
226         else rc = 1;
227         return rc;
228 }
229
230 /*
231   EFI_DEVICE_PATH, 0x01 (Hardware), 0x04 (Vendor), length 0x0018
232   This needs to know what EFI device has the boot device.
233 */
234 static uint16_t
235 make_edd10_device_path(void *dest, uint32_t hardware_device)
236 {
237         VENDOR_DEVICE_PATH *hw;
238         char buffer[EDD10_HARDWARE_VENDOR_PATH_LENGTH];
239         efi_guid_t guid = EDD10_HARDWARE_VENDOR_PATH_GUID;
240         uint32_t *data;
241         memset(buffer, 0, sizeof(buffer));
242         hw = (VENDOR_DEVICE_PATH *)buffer;
243         data = (uint32_t *)hw->data;
244         hw->type = 0x01; /* Hardware Device Path */
245         hw->subtype = 0x04; /* Vendor */
246         hw->length = EDD10_HARDWARE_VENDOR_PATH_LENGTH;
247         memcpy(&(hw->vendor_guid), &guid, sizeof(guid));
248         *data = hardware_device;
249         memcpy(dest, buffer, hw->length);
250         return hw->length;
251 }
252
253 static uint16_t
254 make_end_device_path(void *dest)
255 {
256         END_DEVICE_PATH p;
257         memset(&p, 0, sizeof(p));
258         p.type = 0x7F; /* End of Hardware Device Path */
259         p.subtype = 0xFF; /* End Entire Device Path */
260         p.length = sizeof(p);
261         memcpy(dest, &p, p.length);
262         return p.length;
263 }
264
265 static uint16_t
266 make_acpi_device_path(void *dest, uint32_t _HID, uint32_t _UID)
267 {
268         ACPI_DEVICE_PATH p;
269         memset(&p, 0, sizeof(p));
270         p.type = 2;
271         p.subtype = 1;
272         p.length = sizeof(p);
273         p._HID = _HID;
274         p._UID = _UID;
275         memcpy(dest, &p, p.length);
276         return p.length;
277 }
278
279 static uint16_t
280 make_mac_addr_device_path(void *dest, char *mac, uint8_t iftype)
281 {
282
283         int i;
284         MAC_ADDR_DEVICE_PATH p;
285         memset(&p, 0, sizeof(p));
286         p.type = 3;
287         p.subtype = 11;
288         p.length = sizeof(p);
289         for (i=0; i < 14; i++) {
290                 p.macaddr[i] = mac[i];
291         }
292         p.iftype = iftype;
293         memcpy(dest, &p, p.length);
294         return p.length;
295 }
296
297 struct device
298 {
299         struct pci_dev *pci_dev;
300         struct list_head node;
301 };
302
303 static struct device *
304 is_parent_bridge(struct pci_dev *p, unsigned int target_bus)
305 {
306         struct device *d;
307         unsigned int primary, secondary;
308
309         if ( (pci_read_word(p, PCI_HEADER_TYPE) & 0x7f) != PCI_HEADER_TYPE_BRIDGE)
310                 return NULL;
311
312         primary=pci_read_byte(p, PCI_PRIMARY_BUS);
313         secondary=pci_read_byte(p, PCI_SECONDARY_BUS);
314
315
316         if (secondary != target_bus)
317                 return NULL;
318
319         d = malloc(sizeof(struct device));
320         if (!d)
321                 return NULL;
322         memset(d, 0, sizeof(*d));
323         INIT_LIST_HEAD(&d->node);
324
325         d->pci_dev = p;
326
327         return d;
328 }
329
330 static struct device *
331 find_parent(struct pci_access *pacc, unsigned int target_bus)
332 {
333         struct device *dev;
334         struct pci_dev *p;
335
336         for (p=pacc->devices; p; p=p->next) {
337                 dev = is_parent_bridge(p, target_bus);
338                 if (dev)
339                         return dev;
340         }
341         return NULL;
342 }
343
344 static uint16_t
345 make_one_pci_device_path(void *dest, uint8_t device, uint8_t function)
346 {
347         PCI_DEVICE_PATH p;
348         memset(&p, 0, sizeof(p));
349         p.type = 1;
350         p.subtype = 1;
351         p.length   = sizeof(p);
352         p.device   = device;
353         p.function = function;
354         memcpy(dest, &p, p.length);
355         return p.length;
356 }
357
358 static uint16_t
359 make_pci_device_path(void *dest, uint8_t bus, uint8_t device, uint8_t function)
360 {
361         struct device *dev;
362         struct pci_access *pacc;
363         struct list_head *pos, *n;
364         LIST_HEAD(pci_parent_list);
365         char *p = dest;
366
367         pacc = pci_alloc();
368         if (!pacc)
369                 return 0;
370
371         pci_init(pacc);
372         pci_scan_bus(pacc);
373
374         do {
375                 dev = find_parent(pacc, bus);
376                 if (dev) {
377                         list_add(&pci_parent_list, &dev->node);
378                         bus = dev->pci_dev->bus;
379                 }
380         } while (dev && bus);
381
382
383         list_for_each_safe(pos, n, &pci_parent_list) {
384                 dev = list_entry(pos, struct device, node);
385                 p += make_one_pci_device_path(p,
386                                               dev->pci_dev->dev,
387                                               dev->pci_dev->func);
388                 list_del(&dev->node);
389                 free(dev);
390         }
391
392         p += make_one_pci_device_path(p, device, function);
393
394         pci_cleanup(pacc);
395
396         return ((void *)p - dest);
397 }
398
399 static uint16_t
400 make_scsi_device_path(void *dest, uint16_t id, uint16_t lun)
401 {
402         SCSI_DEVICE_PATH p;
403         memset(&p, 0, sizeof(p));
404         p.type = 3;
405         p.subtype = 2;
406         p.length   = sizeof(p);
407         p.id       = id;
408         p.lun      = lun;
409         memcpy(dest, &p, p.length);
410         return p.length;
411 }
412
413 static uint16_t
414 make_harddrive_device_path(void *dest, uint32_t num, uint64_t start, uint64_t size,
415                            uint8_t *signature,
416                            uint8_t mbr_type, uint8_t signature_type)
417 {
418         HARDDRIVE_DEVICE_PATH p;
419         memset(&p, 0, sizeof(p));
420         p.type = 4;
421         p.subtype = 1;
422         p.length   = sizeof(p);
423         p.part_num = num;
424         p.start = start;
425         p.size = size;
426         if (signature) memcpy(p.signature, signature, 16);
427         p.mbr_type = mbr_type;
428         p.signature_type = signature_type;
429         memcpy(dest, &p, p.length);
430         return p.length;
431 }
432
433 static uint16_t
434 make_file_path_device_path(void *dest, efi_char16_t *name)
435 {
436         FILE_PATH_DEVICE_PATH *p;
437         char buffer[1024];
438         int namelen  = efichar_strlen(name, -1);
439         int namesize = efichar_strsize(name);
440
441         memset(buffer, 0, sizeof(buffer));
442         p = (FILE_PATH_DEVICE_PATH *)buffer;
443         p->type      = 4;
444         p->subtype   = 4;
445         p->length    = 4 + namesize;
446         efichar_strncpy(p->path_name,
447                         name, namelen);
448
449         memcpy(dest, buffer, p->length);
450         return p->length;
451
452 }
453
454
455
456 static long
457 make_edd30_device_path(int fd, void *buffer)
458 {
459         int rc=0;
460         unsigned char bus=0, device=0, function=0;
461         Scsi_Idlun idlun;
462         unsigned char host=0, channel=0, id=0, lun=0;
463         char *p = buffer;
464
465
466         rc = disk_get_pci(fd, &bus, &device, &function);
467         if (rc) return 0;
468
469         memset(&idlun, 0, sizeof(idlun));
470         rc = get_scsi_idlun(fd, &idlun);
471         if (rc) return 0;
472         idlun_to_components(&idlun, &host, &channel, &id, &lun);
473
474         p += make_acpi_device_path      (p, EISAID_PNP0A03, bus);
475         p += make_pci_device_path       (p, bus, device, function);
476         p += make_scsi_device_path      (p, id, lun);
477         return ((void *)p - buffer);
478 }
479
480 /**
481  * make_disk_load_option()
482  * @disk disk
483  *
484  * Returns 0 on error, length of load option created on success.
485  */
486 char *make_disk_load_option(char *p, char *disk)
487 {
488     int disk_fd=0;
489     char buffer[80];
490     char signature[16];
491     int rc, edd_version=0;
492     uint8_t mbr_type=0, signature_type=0;
493     uint64_t start=0, size=0;
494     efi_char16_t os_loader_path[40];
495
496     memset(signature, 0, sizeof(signature));
497
498     disk_fd = open(opts.disk, O_RDWR);
499     if (disk_fd == -1) {
500         sprintf(buffer, "Could not open disk %s", opts.disk);
501         perror(buffer);
502         return 0;
503     }
504
505     if (opts.edd_version) {
506         edd_version = get_edd_version();
507
508         if (edd_version == 3) {
509             p += make_edd30_device_path(disk_fd, p);
510         }
511         else if (edd_version == 1) {
512             p += make_edd10_device_path(p, opts.edd10_devicenum);
513         }
514     }
515
516     rc = disk_get_partition_info (disk_fd, opts.part,
517                                   &start, &size, signature,
518                                   &mbr_type, &signature_type);
519
520     close(disk_fd);
521
522     if (rc) {
523         fprintf(stderr, "Error: no partition information on disk %s.\n"
524                 "       Cowardly refusing to create a boot option.\n",
525                 opts.disk);
526         return 0;
527     }
528
529     p += make_harddrive_device_path (p, opts.part,
530                                      start, size,
531                                      signature,
532                                      mbr_type, signature_type);
533
534     efichar_from_char(os_loader_path, opts.loader, sizeof(os_loader_path));
535     p += make_file_path_device_path (p, os_loader_path);
536     p += make_end_device_path       (p);
537
538     return(p);
539 }
540
541 /**
542  * make_net_load_option()
543  * @data - load option returned
544  *
545  * Returns 0 on error, length of load option created on success.
546  */
547 char *make_net_load_option(char *p, char *iface)
548 {
549     /* copied pretty much verbatim from the ethtool source */
550     int fd = 0, err; 
551     int bus, slot, func;
552     struct ifreq ifr;
553     struct ethtool_drvinfo drvinfo;
554
555     memset(&ifr, 0, sizeof(ifr));
556     strcpy(ifr.ifr_name, iface);
557     drvinfo.cmd = ETHTOOL_GDRVINFO;
558     ifr.ifr_data = (caddr_t)&drvinfo;
559     /* Open control socket */
560     fd = socket(AF_INET, SOCK_DGRAM, 0);
561     if (fd < 0) {
562         perror("Cannot get control socket");
563     }
564     err = ioctl(fd, SIOCETHTOOL, &ifr);
565     if (err < 0) {
566         perror("Cannot get driver information");
567     }
568
569
570     err = sscanf(drvinfo.bus_info, "%2x:%2x.%x", &bus, &slot, &func);
571     if (err == 0) {
572         perror("Couldn't parse device location string.");
573     }
574
575     p += make_acpi_device_path(p, opts.acpi_hid, opts.acpi_uid);
576     p += make_pci_device_path(p, bus, (uint8_t)slot, (uint8_t)func);
577
578     err = ioctl(fd, SIOCGIFHWADDR, &ifr);
579     if (err < 0) {
580         perror("Cannot get hardware address.");
581     }
582
583     p += make_mac_addr_device_path(p, ifr.ifr_ifru.ifru_hwaddr.sa_data, 0);
584     p += make_end_device_path       (p);
585     return(p);
586 }
587
588 /**
589  * make_linux_load_option()
590  * @data - load option returned
591  *
592  * Returns 0 on error, length of load option created on success.
593  */
594 static unsigned long
595 make_linux_load_option(void *data)
596 {
597         EFI_LOAD_OPTION *load_option = data;
598         char *p = data, *q;
599         efi_char16_t description[64];
600         unsigned long datasize=0;
601
602         /* Write Attributes */
603         if (opts.active) load_option->attributes = LOAD_OPTION_ACTIVE;
604         else             load_option->attributes = 0;
605
606         p += sizeof(uint32_t);
607         /* skip writing file_path_list_length */
608         p += sizeof(uint16_t);
609         /* Write description.  This is the text that appears on the screen for the load option. */
610         memset(description, 0, sizeof(description));
611         efichar_from_char(description, opts.label, sizeof(description));
612         efichar_strncpy(load_option->description, description, sizeof(description));
613         p += efichar_strsize(load_option->description);
614
615         q = p;
616
617         if (opts.iface) {
618               p = (char *)make_net_load_option(p, opts.iface);
619         }
620
621         else {
622               p = (char *)make_disk_load_option(p, opts.iface);
623         }
624
625         load_option->file_path_list_length = p - q;
626
627         datasize = (uint8_t *)p - (uint8_t *)data;
628         return datasize;
629 }
630
631 /*
632  * append_extra_args()
633  * appends all arguments from argv[] not snarfed by getopt
634  * as one long string onto data, up to maxchars.  allow for nulls
635  */
636
637 static unsigned long
638 append_extra_args_ascii(void *data, unsigned long maxchars)
639 {
640         char *p = data;
641         int i, appended=0;
642         unsigned long usedchars=0;
643         if (!data) return 0;
644
645
646         for (i=opts.optind; i < opts.argc && usedchars < maxchars; i++) {
647                 p = strncpy(p, opts.argv[i], maxchars-usedchars-1);
648                 p += strlen(p);
649                 appended=1;
650
651                 usedchars = p - (char *)data;
652
653                 /* Put a space between args */
654                 if (i < (opts.argc-1)) {
655
656                         p = strncpy(p, " ", maxchars-usedchars-1);
657                         p += strlen(p);
658                         usedchars = p - (char *)data;
659                 }
660
661         }
662         /* Remember the NULL */
663         if (appended) return strlen(data) + 1;
664         return 0;
665 }
666
667 static unsigned long
668 append_extra_args_unicode(void *data, unsigned long maxchars)
669 {
670         char *p = data;
671         int i, appended=0;
672         unsigned long usedchars=0;
673         if (!data) return 0;
674
675
676         for (i=opts.optind; i < opts.argc && usedchars < maxchars; i++) {
677                 p += efichar_from_char((efi_char16_t *)p, opts.argv[i],
678                                        maxchars-usedchars);
679                 usedchars = efichar_strsize(data) - sizeof(efi_char16_t);
680                 appended=1;
681
682                 /* Put a space between args */
683                 if (i < (opts.argc-1)) {
684                         p += efichar_from_char((efi_char16_t *)p, " ",
685                                                maxchars-usedchars);
686                         usedchars = efichar_strsize(data) -
687                                 sizeof(efi_char16_t);
688                 }
689         }
690
691         if (appended) return efichar_strsize( (efi_char16_t *)data );
692         return 0;
693 }
694
695
696 static unsigned long
697 append_extra_args(void *data, unsigned long maxchars)
698 {
699         if (opts.unicode)
700           return append_extra_args_unicode(data, maxchars);
701         else
702           return append_extra_args_ascii(data, maxchars);
703 }
704
705
706
707 int
708 make_linux_efi_variable(efi_variable_t *var,
709                         unsigned int free_number)
710 {
711         efi_guid_t guid = EFI_GLOBAL_VARIABLE;
712         char buffer[16];
713         unsigned char *optional_data=NULL;
714         unsigned long load_option_size = 0, opt_data_size=0;
715
716         memset(buffer,    0, sizeof(buffer));
717
718         /* VariableName needs to be BootXXXX */
719         sprintf(buffer, "Boot%04x", free_number);
720
721         efichar_from_char(var->VariableName, buffer, 1024);
722
723         memcpy(&(var->VendorGuid), &guid, sizeof(guid));
724         var->Attributes =
725                 EFI_VARIABLE_NON_VOLATILE |
726                 EFI_VARIABLE_BOOTSERVICE_ACCESS |
727                 EFI_VARIABLE_RUNTIME_ACCESS;
728
729         /* Set Data[] and DataSize */
730
731         load_option_size =  make_linux_load_option(var->Data);
732
733         if (!load_option_size) return 0;
734
735         /* Set OptionalData (passed as binary to the called app) */
736         optional_data = var->Data + load_option_size;
737         opt_data_size = append_extra_args(optional_data,
738                                   sizeof(var->Data) - load_option_size);
739         var->DataSize = load_option_size + opt_data_size;
740         return var->DataSize;
741 }
742
743
744 int
745 variable_to_name(efi_variable_t *var, char *name)
746 {
747         char *p = name;
748         efichar_to_char(p, var->VariableName, PATH_MAX);
749         p += strlen(p);
750         p += sprintf(p, "-");
751         efi_guid_unparse(&var->VendorGuid, p);
752         return strlen(name);
753 }