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