GNU Linux-libre 4.19.314-gnu1
[releases.git] / drivers / firmware / efi / vars.c
1 /*
2  * Originally from efivars.c
3  *
4  * Copyright (C) 2001,2003,2004 Dell <Matt_Domsch@dell.com>
5  * Copyright (C) 2004 Intel Corporation <matthew.e.tolentino@intel.com>
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include <linux/capability.h>
23 #include <linux/types.h>
24 #include <linux/errno.h>
25 #include <linux/init.h>
26 #include <linux/mm.h>
27 #include <linux/module.h>
28 #include <linux/string.h>
29 #include <linux/smp.h>
30 #include <linux/efi.h>
31 #include <linux/sysfs.h>
32 #include <linux/device.h>
33 #include <linux/slab.h>
34 #include <linux/ctype.h>
35 #include <linux/ucs2_string.h>
36
37 /* Private pointer to registered efivars */
38 static struct efivars *__efivars;
39
40 /*
41  * efivars_lock protects three things:
42  * 1) efivarfs_list and efivars_sysfs_list
43  * 2) ->ops calls
44  * 3) (un)registration of __efivars
45  */
46 static DEFINE_SEMAPHORE(efivars_lock);
47
48 static bool efivar_wq_enabled = true;
49 DECLARE_WORK(efivar_work, NULL);
50 EXPORT_SYMBOL_GPL(efivar_work);
51
52 static bool
53 validate_device_path(efi_char16_t *var_name, int match, u8 *buffer,
54                      unsigned long len)
55 {
56         struct efi_generic_dev_path *node;
57         int offset = 0;
58
59         node = (struct efi_generic_dev_path *)buffer;
60
61         if (len < sizeof(*node))
62                 return false;
63
64         while (offset <= len - sizeof(*node) &&
65                node->length >= sizeof(*node) &&
66                 node->length <= len - offset) {
67                 offset += node->length;
68
69                 if ((node->type == EFI_DEV_END_PATH ||
70                      node->type == EFI_DEV_END_PATH2) &&
71                     node->sub_type == EFI_DEV_END_ENTIRE)
72                         return true;
73
74                 node = (struct efi_generic_dev_path *)(buffer + offset);
75         }
76
77         /*
78          * If we're here then either node->length pointed past the end
79          * of the buffer or we reached the end of the buffer without
80          * finding a device path end node.
81          */
82         return false;
83 }
84
85 static bool
86 validate_boot_order(efi_char16_t *var_name, int match, u8 *buffer,
87                     unsigned long len)
88 {
89         /* An array of 16-bit integers */
90         if ((len % 2) != 0)
91                 return false;
92
93         return true;
94 }
95
96 static bool
97 validate_load_option(efi_char16_t *var_name, int match, u8 *buffer,
98                      unsigned long len)
99 {
100         u16 filepathlength;
101         int i, desclength = 0, namelen;
102
103         namelen = ucs2_strnlen(var_name, EFI_VAR_NAME_LEN);
104
105         /* Either "Boot" or "Driver" followed by four digits of hex */
106         for (i = match; i < match+4; i++) {
107                 if (var_name[i] > 127 ||
108                     hex_to_bin(var_name[i] & 0xff) < 0)
109                         return true;
110         }
111
112         /* Reject it if there's 4 digits of hex and then further content */
113         if (namelen > match + 4)
114                 return false;
115
116         /* A valid entry must be at least 8 bytes */
117         if (len < 8)
118                 return false;
119
120         filepathlength = buffer[4] | buffer[5] << 8;
121
122         /*
123          * There's no stored length for the description, so it has to be
124          * found by hand
125          */
126         desclength = ucs2_strsize((efi_char16_t *)(buffer + 6), len - 6) + 2;
127
128         /* Each boot entry must have a descriptor */
129         if (!desclength)
130                 return false;
131
132         /*
133          * If the sum of the length of the description, the claimed filepath
134          * length and the original header are greater than the length of the
135          * variable, it's malformed
136          */
137         if ((desclength + filepathlength + 6) > len)
138                 return false;
139
140         /*
141          * And, finally, check the filepath
142          */
143         return validate_device_path(var_name, match, buffer + desclength + 6,
144                                     filepathlength);
145 }
146
147 static bool
148 validate_uint16(efi_char16_t *var_name, int match, u8 *buffer,
149                 unsigned long len)
150 {
151         /* A single 16-bit integer */
152         if (len != 2)
153                 return false;
154
155         return true;
156 }
157
158 static bool
159 validate_ascii_string(efi_char16_t *var_name, int match, u8 *buffer,
160                       unsigned long len)
161 {
162         int i;
163
164         for (i = 0; i < len; i++) {
165                 if (buffer[i] > 127)
166                         return false;
167
168                 if (buffer[i] == 0)
169                         return true;
170         }
171
172         return false;
173 }
174
175 struct variable_validate {
176         efi_guid_t vendor;
177         char *name;
178         bool (*validate)(efi_char16_t *var_name, int match, u8 *data,
179                          unsigned long len);
180 };
181
182 /*
183  * This is the list of variables we need to validate, as well as the
184  * whitelist for what we think is safe not to default to immutable.
185  *
186  * If it has a validate() method that's not NULL, it'll go into the
187  * validation routine.  If not, it is assumed valid, but still used for
188  * whitelisting.
189  *
190  * Note that it's sorted by {vendor,name}, but globbed names must come after
191  * any other name with the same prefix.
192  */
193 static const struct variable_validate variable_validate[] = {
194         { EFI_GLOBAL_VARIABLE_GUID, "BootNext", validate_uint16 },
195         { EFI_GLOBAL_VARIABLE_GUID, "BootOrder", validate_boot_order },
196         { EFI_GLOBAL_VARIABLE_GUID, "Boot*", validate_load_option },
197         { EFI_GLOBAL_VARIABLE_GUID, "DriverOrder", validate_boot_order },
198         { EFI_GLOBAL_VARIABLE_GUID, "Driver*", validate_load_option },
199         { EFI_GLOBAL_VARIABLE_GUID, "ConIn", validate_device_path },
200         { EFI_GLOBAL_VARIABLE_GUID, "ConInDev", validate_device_path },
201         { EFI_GLOBAL_VARIABLE_GUID, "ConOut", validate_device_path },
202         { EFI_GLOBAL_VARIABLE_GUID, "ConOutDev", validate_device_path },
203         { EFI_GLOBAL_VARIABLE_GUID, "ErrOut", validate_device_path },
204         { EFI_GLOBAL_VARIABLE_GUID, "ErrOutDev", validate_device_path },
205         { EFI_GLOBAL_VARIABLE_GUID, "Lang", validate_ascii_string },
206         { EFI_GLOBAL_VARIABLE_GUID, "OsIndications", NULL },
207         { EFI_GLOBAL_VARIABLE_GUID, "PlatformLang", validate_ascii_string },
208         { EFI_GLOBAL_VARIABLE_GUID, "Timeout", validate_uint16 },
209         { LINUX_EFI_CRASH_GUID, "*", NULL },
210         { NULL_GUID, "", NULL },
211 };
212
213 /*
214  * Check if @var_name matches the pattern given in @match_name.
215  *
216  * @var_name: an array of @len non-NUL characters.
217  * @match_name: a NUL-terminated pattern string, optionally ending in "*". A
218  *              final "*" character matches any trailing characters @var_name,
219  *              including the case when there are none left in @var_name.
220  * @match: on output, the number of non-wildcard characters in @match_name
221  *         that @var_name matches, regardless of the return value.
222  * @return: whether @var_name fully matches @match_name.
223  */
224 static bool
225 variable_matches(const char *var_name, size_t len, const char *match_name,
226                  int *match)
227 {
228         for (*match = 0; ; (*match)++) {
229                 char c = match_name[*match];
230
231                 switch (c) {
232                 case '*':
233                         /* Wildcard in @match_name means we've matched. */
234                         return true;
235
236                 case '\0':
237                         /* @match_name has ended. Has @var_name too? */
238                         return (*match == len);
239
240                 default:
241                         /*
242                          * We've reached a non-wildcard char in @match_name.
243                          * Continue only if there's an identical character in
244                          * @var_name.
245                          */
246                         if (*match < len && c == var_name[*match])
247                                 continue;
248                         return false;
249                 }
250         }
251 }
252
253 bool
254 efivar_validate(efi_guid_t vendor, efi_char16_t *var_name, u8 *data,
255                 unsigned long data_size)
256 {
257         int i;
258         unsigned long utf8_size;
259         u8 *utf8_name;
260
261         utf8_size = ucs2_utf8size(var_name);
262         utf8_name = kmalloc(utf8_size + 1, GFP_KERNEL);
263         if (!utf8_name)
264                 return false;
265
266         ucs2_as_utf8(utf8_name, var_name, utf8_size);
267         utf8_name[utf8_size] = '\0';
268
269         for (i = 0; variable_validate[i].name[0] != '\0'; i++) {
270                 const char *name = variable_validate[i].name;
271                 int match = 0;
272
273                 if (efi_guidcmp(vendor, variable_validate[i].vendor))
274                         continue;
275
276                 if (variable_matches(utf8_name, utf8_size+1, name, &match)) {
277                         if (variable_validate[i].validate == NULL)
278                                 break;
279                         kfree(utf8_name);
280                         return variable_validate[i].validate(var_name, match,
281                                                              data, data_size);
282                 }
283         }
284         kfree(utf8_name);
285         return true;
286 }
287 EXPORT_SYMBOL_GPL(efivar_validate);
288
289 bool
290 efivar_variable_is_removable(efi_guid_t vendor, const char *var_name,
291                              size_t len)
292 {
293         int i;
294         bool found = false;
295         int match = 0;
296
297         /*
298          * Check if our variable is in the validated variables list
299          */
300         for (i = 0; variable_validate[i].name[0] != '\0'; i++) {
301                 if (efi_guidcmp(variable_validate[i].vendor, vendor))
302                         continue;
303
304                 if (variable_matches(var_name, len,
305                                      variable_validate[i].name, &match)) {
306                         found = true;
307                         break;
308                 }
309         }
310
311         /*
312          * If it's in our list, it is removable.
313          */
314         return found;
315 }
316 EXPORT_SYMBOL_GPL(efivar_variable_is_removable);
317
318 static efi_status_t
319 check_var_size(u32 attributes, unsigned long size)
320 {
321         const struct efivar_operations *fops;
322
323         if (!__efivars)
324                 return EFI_UNSUPPORTED;
325
326         fops = __efivars->ops;
327
328         if (!fops->query_variable_store)
329                 return EFI_UNSUPPORTED;
330
331         return fops->query_variable_store(attributes, size, false);
332 }
333
334 static efi_status_t
335 check_var_size_nonblocking(u32 attributes, unsigned long size)
336 {
337         const struct efivar_operations *fops;
338
339         if (!__efivars)
340                 return EFI_UNSUPPORTED;
341
342         fops = __efivars->ops;
343
344         if (!fops->query_variable_store)
345                 return EFI_UNSUPPORTED;
346
347         return fops->query_variable_store(attributes, size, true);
348 }
349
350 static bool variable_is_present(efi_char16_t *variable_name, efi_guid_t *vendor,
351                                 struct list_head *head)
352 {
353         struct efivar_entry *entry, *n;
354         unsigned long strsize1, strsize2;
355         bool found = false;
356
357         strsize1 = ucs2_strsize(variable_name, 1024);
358         list_for_each_entry_safe(entry, n, head, list) {
359                 strsize2 = ucs2_strsize(entry->var.VariableName, 1024);
360                 if (strsize1 == strsize2 &&
361                         !memcmp(variable_name, &(entry->var.VariableName),
362                                 strsize2) &&
363                         !efi_guidcmp(entry->var.VendorGuid,
364                                 *vendor)) {
365                         found = true;
366                         break;
367                 }
368         }
369         return found;
370 }
371
372 /*
373  * Returns the size of variable_name, in bytes, including the
374  * terminating NULL character, or variable_name_size if no NULL
375  * character is found among the first variable_name_size bytes.
376  */
377 static unsigned long var_name_strnsize(efi_char16_t *variable_name,
378                                        unsigned long variable_name_size)
379 {
380         unsigned long len;
381         efi_char16_t c;
382
383         /*
384          * The variable name is, by definition, a NULL-terminated
385          * string, so make absolutely sure that variable_name_size is
386          * the value we expect it to be. If not, return the real size.
387          */
388         for (len = 2; len <= variable_name_size; len += sizeof(c)) {
389                 c = variable_name[(len / sizeof(c)) - 1];
390                 if (!c)
391                         break;
392         }
393
394         return min(len, variable_name_size);
395 }
396
397 /*
398  * Print a warning when duplicate EFI variables are encountered and
399  * disable the sysfs workqueue since the firmware is buggy.
400  */
401 static void dup_variable_bug(efi_char16_t *str16, efi_guid_t *vendor_guid,
402                              unsigned long len16)
403 {
404         size_t i, len8 = len16 / sizeof(efi_char16_t);
405         char *str8;
406
407         /*
408          * Disable the workqueue since the algorithm it uses for
409          * detecting new variables won't work with this buggy
410          * implementation of GetNextVariableName().
411          */
412         efivar_wq_enabled = false;
413
414         str8 = kzalloc(len8, GFP_KERNEL);
415         if (!str8)
416                 return;
417
418         for (i = 0; i < len8; i++)
419                 str8[i] = str16[i];
420
421         printk(KERN_WARNING "efivars: duplicate variable: %s-%pUl\n",
422                str8, vendor_guid);
423         kfree(str8);
424 }
425
426 /**
427  * efivar_init - build the initial list of EFI variables
428  * @func: callback function to invoke for every variable
429  * @data: function-specific data to pass to @func
430  * @atomic: do we need to execute the @func-loop atomically?
431  * @duplicates: error if we encounter duplicates on @head?
432  * @head: initialised head of variable list
433  *
434  * Get every EFI variable from the firmware and invoke @func. @func
435  * should call efivar_entry_add() to build the list of variables.
436  *
437  * Returns 0 on success, or a kernel error code on failure.
438  */
439 int efivar_init(int (*func)(efi_char16_t *, efi_guid_t, unsigned long, void *),
440                 void *data, bool duplicates, struct list_head *head)
441 {
442         const struct efivar_operations *ops;
443         unsigned long variable_name_size = 512;
444         efi_char16_t *variable_name;
445         efi_status_t status;
446         efi_guid_t vendor_guid;
447         int err = 0;
448
449         if (!__efivars)
450                 return -EFAULT;
451
452         ops = __efivars->ops;
453
454         variable_name = kzalloc(variable_name_size, GFP_KERNEL);
455         if (!variable_name) {
456                 printk(KERN_ERR "efivars: Memory allocation failed.\n");
457                 return -ENOMEM;
458         }
459
460         if (down_interruptible(&efivars_lock)) {
461                 err = -EINTR;
462                 goto free;
463         }
464
465         /*
466          * A small set of old UEFI implementations reject sizes
467          * above a certain threshold, the lowest seen in the wild
468          * is 512.
469          */
470
471         do {
472                 variable_name_size = 512;
473
474                 status = ops->get_next_variable(&variable_name_size,
475                                                 variable_name,
476                                                 &vendor_guid);
477                 switch (status) {
478                 case EFI_SUCCESS:
479                         if (duplicates)
480                                 up(&efivars_lock);
481
482                         variable_name_size = var_name_strnsize(variable_name,
483                                                                variable_name_size);
484
485                         /*
486                          * Some firmware implementations return the
487                          * same variable name on multiple calls to
488                          * get_next_variable(). Terminate the loop
489                          * immediately as there is no guarantee that
490                          * we'll ever see a different variable name,
491                          * and may end up looping here forever.
492                          */
493                         if (duplicates &&
494                             variable_is_present(variable_name, &vendor_guid,
495                                                 head)) {
496                                 dup_variable_bug(variable_name, &vendor_guid,
497                                                  variable_name_size);
498                                 status = EFI_NOT_FOUND;
499                         } else {
500                                 err = func(variable_name, vendor_guid,
501                                            variable_name_size, data);
502                                 if (err)
503                                         status = EFI_NOT_FOUND;
504                         }
505
506                         if (duplicates) {
507                                 if (down_interruptible(&efivars_lock)) {
508                                         err = -EINTR;
509                                         goto free;
510                                 }
511                         }
512
513                         break;
514                 case EFI_NOT_FOUND:
515                         break;
516                 case EFI_BUFFER_TOO_SMALL:
517                         pr_warn("efivars: Variable name size exceeds maximum (%lu > 512)\n",
518                                 variable_name_size);
519                         status = EFI_NOT_FOUND;
520                         break;
521                 default:
522                         pr_warn("efivars: get_next_variable: status=%lx\n", status);
523                         status = EFI_NOT_FOUND;
524                         break;
525                 }
526
527         } while (status != EFI_NOT_FOUND);
528
529         up(&efivars_lock);
530 free:
531         kfree(variable_name);
532
533         return err;
534 }
535 EXPORT_SYMBOL_GPL(efivar_init);
536
537 /**
538  * efivar_entry_add - add entry to variable list
539  * @entry: entry to add to list
540  * @head: list head
541  *
542  * Returns 0 on success, or a kernel error code on failure.
543  */
544 int efivar_entry_add(struct efivar_entry *entry, struct list_head *head)
545 {
546         if (down_interruptible(&efivars_lock))
547                 return -EINTR;
548         list_add(&entry->list, head);
549         up(&efivars_lock);
550
551         return 0;
552 }
553 EXPORT_SYMBOL_GPL(efivar_entry_add);
554
555 /**
556  * efivar_entry_remove - remove entry from variable list
557  * @entry: entry to remove from list
558  *
559  * Returns 0 on success, or a kernel error code on failure.
560  */
561 int efivar_entry_remove(struct efivar_entry *entry)
562 {
563         if (down_interruptible(&efivars_lock))
564                 return -EINTR;
565         list_del(&entry->list);
566         up(&efivars_lock);
567
568         return 0;
569 }
570 EXPORT_SYMBOL_GPL(efivar_entry_remove);
571
572 /*
573  * efivar_entry_list_del_unlock - remove entry from variable list
574  * @entry: entry to remove
575  *
576  * Remove @entry from the variable list and release the list lock.
577  *
578  * NOTE: slightly weird locking semantics here - we expect to be
579  * called with the efivars lock already held, and we release it before
580  * returning. This is because this function is usually called after
581  * set_variable() while the lock is still held.
582  */
583 static void efivar_entry_list_del_unlock(struct efivar_entry *entry)
584 {
585         list_del(&entry->list);
586         up(&efivars_lock);
587 }
588
589 /**
590  * __efivar_entry_delete - delete an EFI variable
591  * @entry: entry containing EFI variable to delete
592  *
593  * Delete the variable from the firmware but leave @entry on the
594  * variable list.
595  *
596  * This function differs from efivar_entry_delete() because it does
597  * not remove @entry from the variable list. Also, it is safe to be
598  * called from within a efivar_entry_iter_begin() and
599  * efivar_entry_iter_end() region, unlike efivar_entry_delete().
600  *
601  * Returns 0 on success, or a converted EFI status code if
602  * set_variable() fails.
603  */
604 int __efivar_entry_delete(struct efivar_entry *entry)
605 {
606         efi_status_t status;
607
608         if (!__efivars)
609                 return -EINVAL;
610
611         status = __efivars->ops->set_variable(entry->var.VariableName,
612                                               &entry->var.VendorGuid,
613                                               0, 0, NULL);
614
615         return efi_status_to_err(status);
616 }
617 EXPORT_SYMBOL_GPL(__efivar_entry_delete);
618
619 /**
620  * efivar_entry_delete - delete variable and remove entry from list
621  * @entry: entry containing variable to delete
622  *
623  * Delete the variable from the firmware and remove @entry from the
624  * variable list. It is the caller's responsibility to free @entry
625  * once we return.
626  *
627  * Returns 0 on success, -EINTR if we can't grab the semaphore,
628  * converted EFI status code if set_variable() fails.
629  */
630 int efivar_entry_delete(struct efivar_entry *entry)
631 {
632         const struct efivar_operations *ops;
633         efi_status_t status;
634
635         if (down_interruptible(&efivars_lock))
636                 return -EINTR;
637
638         if (!__efivars) {
639                 up(&efivars_lock);
640                 return -EINVAL;
641         }
642         ops = __efivars->ops;
643         status = ops->set_variable(entry->var.VariableName,
644                                    &entry->var.VendorGuid,
645                                    0, 0, NULL);
646         if (!(status == EFI_SUCCESS || status == EFI_NOT_FOUND)) {
647                 up(&efivars_lock);
648                 return efi_status_to_err(status);
649         }
650
651         efivar_entry_list_del_unlock(entry);
652         return 0;
653 }
654 EXPORT_SYMBOL_GPL(efivar_entry_delete);
655
656 /**
657  * efivar_entry_set - call set_variable()
658  * @entry: entry containing the EFI variable to write
659  * @attributes: variable attributes
660  * @size: size of @data buffer
661  * @data: buffer containing variable data
662  * @head: head of variable list
663  *
664  * Calls set_variable() for an EFI variable. If creating a new EFI
665  * variable, this function is usually followed by efivar_entry_add().
666  *
667  * Before writing the variable, the remaining EFI variable storage
668  * space is checked to ensure there is enough room available.
669  *
670  * If @head is not NULL a lookup is performed to determine whether
671  * the entry is already on the list.
672  *
673  * Returns 0 on success, -EINTR if we can't grab the semaphore,
674  * -EEXIST if a lookup is performed and the entry already exists on
675  * the list, or a converted EFI status code if set_variable() fails.
676  */
677 int efivar_entry_set(struct efivar_entry *entry, u32 attributes,
678                      unsigned long size, void *data, struct list_head *head)
679 {
680         const struct efivar_operations *ops;
681         efi_status_t status;
682         efi_char16_t *name = entry->var.VariableName;
683         efi_guid_t vendor = entry->var.VendorGuid;
684
685         if (down_interruptible(&efivars_lock))
686                 return -EINTR;
687
688         if (!__efivars) {
689                 up(&efivars_lock);
690                 return -EINVAL;
691         }
692         ops = __efivars->ops;
693         if (head && efivar_entry_find(name, vendor, head, false)) {
694                 up(&efivars_lock);
695                 return -EEXIST;
696         }
697
698         status = check_var_size(attributes, size + ucs2_strsize(name, 1024));
699         if (status == EFI_SUCCESS || status == EFI_UNSUPPORTED)
700                 status = ops->set_variable(name, &vendor,
701                                            attributes, size, data);
702
703         up(&efivars_lock);
704
705         return efi_status_to_err(status);
706
707 }
708 EXPORT_SYMBOL_GPL(efivar_entry_set);
709
710 /*
711  * efivar_entry_set_nonblocking - call set_variable_nonblocking()
712  *
713  * This function is guaranteed to not block and is suitable for calling
714  * from crash/panic handlers.
715  *
716  * Crucially, this function will not block if it cannot acquire
717  * efivars_lock. Instead, it returns -EBUSY.
718  */
719 static int
720 efivar_entry_set_nonblocking(efi_char16_t *name, efi_guid_t vendor,
721                              u32 attributes, unsigned long size, void *data)
722 {
723         const struct efivar_operations *ops;
724         efi_status_t status;
725
726         if (down_trylock(&efivars_lock))
727                 return -EBUSY;
728
729         if (!__efivars) {
730                 up(&efivars_lock);
731                 return -EINVAL;
732         }
733
734         status = check_var_size_nonblocking(attributes,
735                                             size + ucs2_strsize(name, 1024));
736         if (status != EFI_SUCCESS) {
737                 up(&efivars_lock);
738                 return -ENOSPC;
739         }
740
741         ops = __efivars->ops;
742         status = ops->set_variable_nonblocking(name, &vendor, attributes,
743                                                size, data);
744
745         up(&efivars_lock);
746         return efi_status_to_err(status);
747 }
748
749 /**
750  * efivar_entry_set_safe - call set_variable() if enough space in firmware
751  * @name: buffer containing the variable name
752  * @vendor: variable vendor guid
753  * @attributes: variable attributes
754  * @block: can we block in this context?
755  * @size: size of @data buffer
756  * @data: buffer containing variable data
757  *
758  * Ensures there is enough free storage in the firmware for this variable, and
759  * if so, calls set_variable(). If creating a new EFI variable, this function
760  * is usually followed by efivar_entry_add().
761  *
762  * Returns 0 on success, -ENOSPC if the firmware does not have enough
763  * space for set_variable() to succeed, or a converted EFI status code
764  * if set_variable() fails.
765  */
766 int efivar_entry_set_safe(efi_char16_t *name, efi_guid_t vendor, u32 attributes,
767                           bool block, unsigned long size, void *data)
768 {
769         const struct efivar_operations *ops;
770         efi_status_t status;
771         unsigned long varsize;
772
773         if (!__efivars)
774                 return -EINVAL;
775
776         ops = __efivars->ops;
777         if (!ops->query_variable_store)
778                 return -ENOSYS;
779
780         /*
781          * If the EFI variable backend provides a non-blocking
782          * ->set_variable() operation and we're in a context where we
783          * cannot block, then we need to use it to avoid live-locks,
784          * since the implication is that the regular ->set_variable()
785          * will block.
786          *
787          * If no ->set_variable_nonblocking() is provided then
788          * ->set_variable() is assumed to be non-blocking.
789          */
790         if (!block && ops->set_variable_nonblocking)
791                 return efivar_entry_set_nonblocking(name, vendor, attributes,
792                                                     size, data);
793
794         varsize = size + ucs2_strsize(name, 1024);
795         if (!block) {
796                 if (down_trylock(&efivars_lock))
797                         return -EBUSY;
798                 status = check_var_size_nonblocking(attributes, varsize);
799         } else {
800                 if (down_interruptible(&efivars_lock))
801                         return -EINTR;
802                 status = check_var_size(attributes, varsize);
803         }
804
805         if (status != EFI_SUCCESS) {
806                 up(&efivars_lock);
807                 return -ENOSPC;
808         }
809
810         status = ops->set_variable(name, &vendor, attributes, size, data);
811
812         up(&efivars_lock);
813
814         return efi_status_to_err(status);
815 }
816 EXPORT_SYMBOL_GPL(efivar_entry_set_safe);
817
818 /**
819  * efivar_entry_find - search for an entry
820  * @name: the EFI variable name
821  * @guid: the EFI variable vendor's guid
822  * @head: head of the variable list
823  * @remove: should we remove the entry from the list?
824  *
825  * Search for an entry on the variable list that has the EFI variable
826  * name @name and vendor guid @guid. If an entry is found on the list
827  * and @remove is true, the entry is removed from the list.
828  *
829  * The caller MUST call efivar_entry_iter_begin() and
830  * efivar_entry_iter_end() before and after the invocation of this
831  * function, respectively.
832  *
833  * Returns the entry if found on the list, %NULL otherwise.
834  */
835 struct efivar_entry *efivar_entry_find(efi_char16_t *name, efi_guid_t guid,
836                                        struct list_head *head, bool remove)
837 {
838         struct efivar_entry *entry, *n;
839         int strsize1, strsize2;
840         bool found = false;
841
842         list_for_each_entry_safe(entry, n, head, list) {
843                 strsize1 = ucs2_strsize(name, 1024);
844                 strsize2 = ucs2_strsize(entry->var.VariableName, 1024);
845                 if (strsize1 == strsize2 &&
846                     !memcmp(name, &(entry->var.VariableName), strsize1) &&
847                     !efi_guidcmp(guid, entry->var.VendorGuid)) {
848                         found = true;
849                         break;
850                 }
851         }
852
853         if (!found)
854                 return NULL;
855
856         if (remove) {
857                 if (entry->scanning) {
858                         /*
859                          * The entry will be deleted
860                          * after scanning is completed.
861                          */
862                         entry->deleting = true;
863                 } else
864                         list_del(&entry->list);
865         }
866
867         return entry;
868 }
869 EXPORT_SYMBOL_GPL(efivar_entry_find);
870
871 /**
872  * efivar_entry_size - obtain the size of a variable
873  * @entry: entry for this variable
874  * @size: location to store the variable's size
875  */
876 int efivar_entry_size(struct efivar_entry *entry, unsigned long *size)
877 {
878         const struct efivar_operations *ops;
879         efi_status_t status;
880
881         *size = 0;
882
883         if (down_interruptible(&efivars_lock))
884                 return -EINTR;
885         if (!__efivars) {
886                 up(&efivars_lock);
887                 return -EINVAL;
888         }
889         ops = __efivars->ops;
890         status = ops->get_variable(entry->var.VariableName,
891                                    &entry->var.VendorGuid, NULL, size, NULL);
892         up(&efivars_lock);
893
894         if (status != EFI_BUFFER_TOO_SMALL)
895                 return efi_status_to_err(status);
896
897         return 0;
898 }
899 EXPORT_SYMBOL_GPL(efivar_entry_size);
900
901 /**
902  * __efivar_entry_get - call get_variable()
903  * @entry: read data for this variable
904  * @attributes: variable attributes
905  * @size: size of @data buffer
906  * @data: buffer to store variable data
907  *
908  * The caller MUST call efivar_entry_iter_begin() and
909  * efivar_entry_iter_end() before and after the invocation of this
910  * function, respectively.
911  */
912 int __efivar_entry_get(struct efivar_entry *entry, u32 *attributes,
913                        unsigned long *size, void *data)
914 {
915         efi_status_t status;
916
917         if (!__efivars)
918                 return -EINVAL;
919
920         status = __efivars->ops->get_variable(entry->var.VariableName,
921                                               &entry->var.VendorGuid,
922                                               attributes, size, data);
923
924         return efi_status_to_err(status);
925 }
926 EXPORT_SYMBOL_GPL(__efivar_entry_get);
927
928 /**
929  * efivar_entry_get - call get_variable()
930  * @entry: read data for this variable
931  * @attributes: variable attributes
932  * @size: size of @data buffer
933  * @data: buffer to store variable data
934  */
935 int efivar_entry_get(struct efivar_entry *entry, u32 *attributes,
936                      unsigned long *size, void *data)
937 {
938         efi_status_t status;
939
940         if (down_interruptible(&efivars_lock))
941                 return -EINTR;
942
943         if (!__efivars) {
944                 up(&efivars_lock);
945                 return -EINVAL;
946         }
947
948         status = __efivars->ops->get_variable(entry->var.VariableName,
949                                               &entry->var.VendorGuid,
950                                               attributes, size, data);
951         up(&efivars_lock);
952
953         return efi_status_to_err(status);
954 }
955 EXPORT_SYMBOL_GPL(efivar_entry_get);
956
957 /**
958  * efivar_entry_set_get_size - call set_variable() and get new size (atomic)
959  * @entry: entry containing variable to set and get
960  * @attributes: attributes of variable to be written
961  * @size: size of data buffer
962  * @data: buffer containing data to write
963  * @set: did the set_variable() call succeed?
964  *
965  * This is a pretty special (complex) function. See efivarfs_file_write().
966  *
967  * Atomically call set_variable() for @entry and if the call is
968  * successful, return the new size of the variable from get_variable()
969  * in @size. The success of set_variable() is indicated by @set.
970  *
971  * Returns 0 on success, -EINVAL if the variable data is invalid,
972  * -ENOSPC if the firmware does not have enough available space, or a
973  * converted EFI status code if either of set_variable() or
974  * get_variable() fail.
975  *
976  * If the EFI variable does not exist when calling set_variable()
977  * (EFI_NOT_FOUND), @entry is removed from the variable list.
978  */
979 int efivar_entry_set_get_size(struct efivar_entry *entry, u32 attributes,
980                               unsigned long *size, void *data, bool *set)
981 {
982         const struct efivar_operations *ops;
983         efi_char16_t *name = entry->var.VariableName;
984         efi_guid_t *vendor = &entry->var.VendorGuid;
985         efi_status_t status;
986         int err;
987
988         *set = false;
989
990         if (efivar_validate(*vendor, name, data, *size) == false)
991                 return -EINVAL;
992
993         /*
994          * The lock here protects the get_variable call, the conditional
995          * set_variable call, and removal of the variable from the efivars
996          * list (in the case of an authenticated delete).
997          */
998         if (down_interruptible(&efivars_lock))
999                 return -EINTR;
1000
1001         if (!__efivars) {
1002                 err = -EINVAL;
1003                 goto out;
1004         }
1005
1006         /*
1007          * Ensure that the available space hasn't shrunk below the safe level
1008          */
1009         status = check_var_size(attributes, *size + ucs2_strsize(name, 1024));
1010         if (status != EFI_SUCCESS) {
1011                 if (status != EFI_UNSUPPORTED) {
1012                         err = efi_status_to_err(status);
1013                         goto out;
1014                 }
1015
1016                 if (*size > 65536) {
1017                         err = -ENOSPC;
1018                         goto out;
1019                 }
1020         }
1021
1022         ops = __efivars->ops;
1023
1024         status = ops->set_variable(name, vendor, attributes, *size, data);
1025         if (status != EFI_SUCCESS) {
1026                 err = efi_status_to_err(status);
1027                 goto out;
1028         }
1029
1030         *set = true;
1031
1032         /*
1033          * Writing to the variable may have caused a change in size (which
1034          * could either be an append or an overwrite), or the variable to be
1035          * deleted. Perform a GetVariable() so we can tell what actually
1036          * happened.
1037          */
1038         *size = 0;
1039         status = ops->get_variable(entry->var.VariableName,
1040                                    &entry->var.VendorGuid,
1041                                    NULL, size, NULL);
1042
1043         if (status == EFI_NOT_FOUND)
1044                 efivar_entry_list_del_unlock(entry);
1045         else
1046                 up(&efivars_lock);
1047
1048         if (status && status != EFI_BUFFER_TOO_SMALL)
1049                 return efi_status_to_err(status);
1050
1051         return 0;
1052
1053 out:
1054         up(&efivars_lock);
1055         return err;
1056
1057 }
1058 EXPORT_SYMBOL_GPL(efivar_entry_set_get_size);
1059
1060 /**
1061  * efivar_entry_iter_begin - begin iterating the variable list
1062  *
1063  * Lock the variable list to prevent entry insertion and removal until
1064  * efivar_entry_iter_end() is called. This function is usually used in
1065  * conjunction with __efivar_entry_iter() or efivar_entry_iter().
1066  */
1067 int efivar_entry_iter_begin(void)
1068 {
1069         return down_interruptible(&efivars_lock);
1070 }
1071 EXPORT_SYMBOL_GPL(efivar_entry_iter_begin);
1072
1073 /**
1074  * efivar_entry_iter_end - finish iterating the variable list
1075  *
1076  * Unlock the variable list and allow modifications to the list again.
1077  */
1078 void efivar_entry_iter_end(void)
1079 {
1080         up(&efivars_lock);
1081 }
1082 EXPORT_SYMBOL_GPL(efivar_entry_iter_end);
1083
1084 /**
1085  * __efivar_entry_iter - iterate over variable list
1086  * @func: callback function
1087  * @head: head of the variable list
1088  * @data: function-specific data to pass to callback
1089  * @prev: entry to begin iterating from
1090  *
1091  * Iterate over the list of EFI variables and call @func with every
1092  * entry on the list. It is safe for @func to remove entries in the
1093  * list via efivar_entry_delete().
1094  *
1095  * You MUST call efivar_enter_iter_begin() before this function, and
1096  * efivar_entry_iter_end() afterwards.
1097  *
1098  * It is possible to begin iteration from an arbitrary entry within
1099  * the list by passing @prev. @prev is updated on return to point to
1100  * the last entry passed to @func. To begin iterating from the
1101  * beginning of the list @prev must be %NULL.
1102  *
1103  * The restrictions for @func are the same as documented for
1104  * efivar_entry_iter().
1105  */
1106 int __efivar_entry_iter(int (*func)(struct efivar_entry *, void *),
1107                         struct list_head *head, void *data,
1108                         struct efivar_entry **prev)
1109 {
1110         struct efivar_entry *entry, *n;
1111         int err = 0;
1112
1113         if (!prev || !*prev) {
1114                 list_for_each_entry_safe(entry, n, head, list) {
1115                         err = func(entry, data);
1116                         if (err)
1117                                 break;
1118                 }
1119
1120                 if (prev)
1121                         *prev = entry;
1122
1123                 return err;
1124         }
1125
1126
1127         list_for_each_entry_safe_continue((*prev), n, head, list) {
1128                 err = func(*prev, data);
1129                 if (err)
1130                         break;
1131         }
1132
1133         return err;
1134 }
1135 EXPORT_SYMBOL_GPL(__efivar_entry_iter);
1136
1137 /**
1138  * efivar_entry_iter - iterate over variable list
1139  * @func: callback function
1140  * @head: head of variable list
1141  * @data: function-specific data to pass to callback
1142  *
1143  * Iterate over the list of EFI variables and call @func with every
1144  * entry on the list. It is safe for @func to remove entries in the
1145  * list via efivar_entry_delete() while iterating.
1146  *
1147  * Some notes for the callback function:
1148  *  - a non-zero return value indicates an error and terminates the loop
1149  *  - @func is called from atomic context
1150  */
1151 int efivar_entry_iter(int (*func)(struct efivar_entry *, void *),
1152                       struct list_head *head, void *data)
1153 {
1154         int err = 0;
1155
1156         err = efivar_entry_iter_begin();
1157         if (err)
1158                 return err;
1159         err = __efivar_entry_iter(func, head, data, NULL);
1160         efivar_entry_iter_end();
1161
1162         return err;
1163 }
1164 EXPORT_SYMBOL_GPL(efivar_entry_iter);
1165
1166 /**
1167  * efivars_kobject - get the kobject for the registered efivars
1168  *
1169  * If efivars_register() has not been called we return NULL,
1170  * otherwise return the kobject used at registration time.
1171  */
1172 struct kobject *efivars_kobject(void)
1173 {
1174         if (!__efivars)
1175                 return NULL;
1176
1177         return __efivars->kobject;
1178 }
1179 EXPORT_SYMBOL_GPL(efivars_kobject);
1180
1181 /**
1182  * efivar_run_worker - schedule the efivar worker thread
1183  */
1184 void efivar_run_worker(void)
1185 {
1186         if (efivar_wq_enabled)
1187                 schedule_work(&efivar_work);
1188 }
1189 EXPORT_SYMBOL_GPL(efivar_run_worker);
1190
1191 /**
1192  * efivars_register - register an efivars
1193  * @efivars: efivars to register
1194  * @ops: efivars operations
1195  * @kobject: @efivars-specific kobject
1196  *
1197  * Only a single efivars can be registered at any time.
1198  */
1199 int efivars_register(struct efivars *efivars,
1200                      const struct efivar_operations *ops,
1201                      struct kobject *kobject)
1202 {
1203         if (down_interruptible(&efivars_lock))
1204                 return -EINTR;
1205
1206         efivars->ops = ops;
1207         efivars->kobject = kobject;
1208
1209         __efivars = efivars;
1210
1211         pr_info("Registered efivars operations\n");
1212
1213         up(&efivars_lock);
1214
1215         return 0;
1216 }
1217 EXPORT_SYMBOL_GPL(efivars_register);
1218
1219 /**
1220  * efivars_unregister - unregister an efivars
1221  * @efivars: efivars to unregister
1222  *
1223  * The caller must have already removed every entry from the list,
1224  * failure to do so is an error.
1225  */
1226 int efivars_unregister(struct efivars *efivars)
1227 {
1228         int rv;
1229
1230         if (down_interruptible(&efivars_lock))
1231                 return -EINTR;
1232
1233         if (!__efivars) {
1234                 printk(KERN_ERR "efivars not registered\n");
1235                 rv = -EINVAL;
1236                 goto out;
1237         }
1238
1239         if (__efivars != efivars) {
1240                 rv = -EINVAL;
1241                 goto out;
1242         }
1243
1244         pr_info("Unregistered efivars operations\n");
1245         __efivars = NULL;
1246
1247         rv = 0;
1248 out:
1249         up(&efivars_lock);
1250         return rv;
1251 }
1252 EXPORT_SYMBOL_GPL(efivars_unregister);