efi: be more paranoid about available space when creating variables
[profile/ivi/kernel-adaptation-intel-automotive.git] / drivers / firmware / efivars.c
1 /*
2  * EFI Variables - 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 code takes all variables accessible from EFI runtime and
8  *  exports them via sysfs
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  *
24  * Changelog:
25  *
26  *  17 May 2004 - Matt Domsch <Matt_Domsch@dell.com>
27  *   remove check for efi_enabled in exit
28  *   add MODULE_VERSION
29  *
30  *  26 Apr 2004 - Matt Domsch <Matt_Domsch@dell.com>
31  *   minor bug fixes
32  *
33  *  21 Apr 2004 - Matt Tolentino <matthew.e.tolentino@intel.com)
34  *   converted driver to export variable information via sysfs
35  *   and moved to drivers/firmware directory
36  *   bumped revision number to v0.07 to reflect conversion & move
37  *
38  *  10 Dec 2002 - Matt Domsch <Matt_Domsch@dell.com>
39  *   fix locking per Peter Chubb's findings
40  *
41  *  25 Mar 2002 - Matt Domsch <Matt_Domsch@dell.com>
42  *   move uuid_unparse() to include/asm-ia64/efi.h:efi_guid_unparse()
43  *
44  *  12 Feb 2002 - Matt Domsch <Matt_Domsch@dell.com>
45  *   use list_for_each_safe when deleting vars.
46  *   remove ifdef CONFIG_SMP around include <linux/smp.h>
47  *   v0.04 release to linux-ia64@linuxia64.org
48  *
49  *  20 April 2001 - Matt Domsch <Matt_Domsch@dell.com>
50  *   Moved vars from /proc/efi to /proc/efi/vars, and made
51  *   efi.c own the /proc/efi directory.
52  *   v0.03 release to linux-ia64@linuxia64.org
53  *
54  *  26 March 2001 - Matt Domsch <Matt_Domsch@dell.com>
55  *   At the request of Stephane, moved ownership of /proc/efi
56  *   to efi.c, and now efivars lives under /proc/efi/vars.
57  *
58  *  12 March 2001 - Matt Domsch <Matt_Domsch@dell.com>
59  *   Feedback received from Stephane Eranian incorporated.
60  *   efivar_write() checks copy_from_user() return value.
61  *   efivar_read/write() returns proper errno.
62  *   v0.02 release to linux-ia64@linuxia64.org
63  *
64  *  26 February 2001 - Matt Domsch <Matt_Domsch@dell.com>
65  *   v0.01 release to linux-ia64@linuxia64.org
66  */
67
68 #include <linux/capability.h>
69 #include <linux/types.h>
70 #include <linux/errno.h>
71 #include <linux/init.h>
72 #include <linux/mm.h>
73 #include <linux/module.h>
74 #include <linux/string.h>
75 #include <linux/smp.h>
76 #include <linux/efi.h>
77 #include <linux/sysfs.h>
78 #include <linux/kobject.h>
79 #include <linux/device.h>
80 #include <linux/slab.h>
81 #include <linux/pstore.h>
82 #include <linux/ctype.h>
83
84 #include <linux/fs.h>
85 #include <linux/ramfs.h>
86 #include <linux/pagemap.h>
87
88 #include <asm/uaccess.h>
89
90 #define EFIVARS_VERSION "0.08"
91 #define EFIVARS_DATE "2004-May-17"
92
93 MODULE_AUTHOR("Matt Domsch <Matt_Domsch@Dell.com>");
94 MODULE_DESCRIPTION("sysfs interface to EFI Variables");
95 MODULE_LICENSE("GPL");
96 MODULE_VERSION(EFIVARS_VERSION);
97
98 #define DUMP_NAME_LEN 52
99
100 /*
101  * Length of a GUID string (strlen("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"))
102  * not including trailing NUL
103  */
104 #define GUID_LEN 36
105
106 /*
107  * The maximum size of VariableName + Data = 1024
108  * Therefore, it's reasonable to save that much
109  * space in each part of the structure,
110  * and we use a page for reading/writing.
111  */
112
113 struct efi_variable {
114         efi_char16_t  VariableName[1024/sizeof(efi_char16_t)];
115         efi_guid_t    VendorGuid;
116         unsigned long DataSize;
117         __u8          Data[1024];
118         efi_status_t  Status;
119         __u32         Attributes;
120 } __attribute__((packed));
121
122 struct efivar_entry {
123         struct efivars *efivars;
124         struct efi_variable var;
125         struct list_head list;
126         struct kobject kobj;
127 };
128
129 struct efivar_attribute {
130         struct attribute attr;
131         ssize_t (*show) (struct efivar_entry *entry, char *buf);
132         ssize_t (*store)(struct efivar_entry *entry, const char *buf, size_t count);
133 };
134
135 static struct efivars __efivars;
136 static struct efivar_operations ops;
137
138 #define PSTORE_EFI_ATTRIBUTES \
139         (EFI_VARIABLE_NON_VOLATILE | \
140          EFI_VARIABLE_BOOTSERVICE_ACCESS | \
141          EFI_VARIABLE_RUNTIME_ACCESS)
142
143 #define EFIVAR_ATTR(_name, _mode, _show, _store) \
144 struct efivar_attribute efivar_attr_##_name = { \
145         .attr = {.name = __stringify(_name), .mode = _mode}, \
146         .show = _show, \
147         .store = _store, \
148 };
149
150 #define to_efivar_attr(_attr) container_of(_attr, struct efivar_attribute, attr)
151 #define to_efivar_entry(obj)  container_of(obj, struct efivar_entry, kobj)
152
153 /*
154  * Prototype for sysfs creation function
155  */
156 static int
157 efivar_create_sysfs_entry(struct efivars *efivars,
158                           unsigned long variable_name_size,
159                           efi_char16_t *variable_name,
160                           efi_guid_t *vendor_guid);
161
162 /* Return the number of unicode characters in data */
163 static unsigned long
164 utf16_strnlen(efi_char16_t *s, size_t maxlength)
165 {
166         unsigned long length = 0;
167
168         while (*s++ != 0 && length < maxlength)
169                 length++;
170         return length;
171 }
172
173 static inline unsigned long
174 utf16_strlen(efi_char16_t *s)
175 {
176         return utf16_strnlen(s, ~0UL);
177 }
178
179 /*
180  * Return the number of bytes is the length of this string
181  * Note: this is NOT the same as the number of unicode characters
182  */
183 static inline unsigned long
184 utf16_strsize(efi_char16_t *data, unsigned long maxlength)
185 {
186         return utf16_strnlen(data, maxlength/sizeof(efi_char16_t)) * sizeof(efi_char16_t);
187 }
188
189 static inline int
190 utf16_strncmp(const efi_char16_t *a, const efi_char16_t *b, size_t len)
191 {
192         while (1) {
193                 if (len == 0)
194                         return 0;
195                 if (*a < *b)
196                         return -1;
197                 if (*a > *b)
198                         return 1;
199                 if (*a == 0) /* implies *b == 0 */
200                         return 0;
201                 a++;
202                 b++;
203                 len--;
204         }
205 }
206
207 static bool
208 validate_device_path(struct efi_variable *var, int match, u8 *buffer,
209                      unsigned long len)
210 {
211         struct efi_generic_dev_path *node;
212         int offset = 0;
213
214         node = (struct efi_generic_dev_path *)buffer;
215
216         if (len < sizeof(*node))
217                 return false;
218
219         while (offset <= len - sizeof(*node) &&
220                node->length >= sizeof(*node) &&
221                 node->length <= len - offset) {
222                 offset += node->length;
223
224                 if ((node->type == EFI_DEV_END_PATH ||
225                      node->type == EFI_DEV_END_PATH2) &&
226                     node->sub_type == EFI_DEV_END_ENTIRE)
227                         return true;
228
229                 node = (struct efi_generic_dev_path *)(buffer + offset);
230         }
231
232         /*
233          * If we're here then either node->length pointed past the end
234          * of the buffer or we reached the end of the buffer without
235          * finding a device path end node.
236          */
237         return false;
238 }
239
240 static bool
241 validate_boot_order(struct efi_variable *var, int match, u8 *buffer,
242                     unsigned long len)
243 {
244         /* An array of 16-bit integers */
245         if ((len % 2) != 0)
246                 return false;
247
248         return true;
249 }
250
251 static bool
252 validate_load_option(struct efi_variable *var, int match, u8 *buffer,
253                      unsigned long len)
254 {
255         u16 filepathlength;
256         int i, desclength = 0, namelen;
257
258         namelen = utf16_strnlen(var->VariableName, sizeof(var->VariableName));
259
260         /* Either "Boot" or "Driver" followed by four digits of hex */
261         for (i = match; i < match+4; i++) {
262                 if (var->VariableName[i] > 127 ||
263                     hex_to_bin(var->VariableName[i] & 0xff) < 0)
264                         return true;
265         }
266
267         /* Reject it if there's 4 digits of hex and then further content */
268         if (namelen > match + 4)
269                 return false;
270
271         /* A valid entry must be at least 8 bytes */
272         if (len < 8)
273                 return false;
274
275         filepathlength = buffer[4] | buffer[5] << 8;
276
277         /*
278          * There's no stored length for the description, so it has to be
279          * found by hand
280          */
281         desclength = utf16_strsize((efi_char16_t *)(buffer + 6), len - 6) + 2;
282
283         /* Each boot entry must have a descriptor */
284         if (!desclength)
285                 return false;
286
287         /*
288          * If the sum of the length of the description, the claimed filepath
289          * length and the original header are greater than the length of the
290          * variable, it's malformed
291          */
292         if ((desclength + filepathlength + 6) > len)
293                 return false;
294
295         /*
296          * And, finally, check the filepath
297          */
298         return validate_device_path(var, match, buffer + desclength + 6,
299                                     filepathlength);
300 }
301
302 static bool
303 validate_uint16(struct efi_variable *var, int match, u8 *buffer,
304                 unsigned long len)
305 {
306         /* A single 16-bit integer */
307         if (len != 2)
308                 return false;
309
310         return true;
311 }
312
313 static bool
314 validate_ascii_string(struct efi_variable *var, int match, u8 *buffer,
315                       unsigned long len)
316 {
317         int i;
318
319         for (i = 0; i < len; i++) {
320                 if (buffer[i] > 127)
321                         return false;
322
323                 if (buffer[i] == 0)
324                         return true;
325         }
326
327         return false;
328 }
329
330 struct variable_validate {
331         char *name;
332         bool (*validate)(struct efi_variable *var, int match, u8 *data,
333                          unsigned long len);
334 };
335
336 static const struct variable_validate variable_validate[] = {
337         { "BootNext", validate_uint16 },
338         { "BootOrder", validate_boot_order },
339         { "DriverOrder", validate_boot_order },
340         { "Boot*", validate_load_option },
341         { "Driver*", validate_load_option },
342         { "ConIn", validate_device_path },
343         { "ConInDev", validate_device_path },
344         { "ConOut", validate_device_path },
345         { "ConOutDev", validate_device_path },
346         { "ErrOut", validate_device_path },
347         { "ErrOutDev", validate_device_path },
348         { "Timeout", validate_uint16 },
349         { "Lang", validate_ascii_string },
350         { "PlatformLang", validate_ascii_string },
351         { "", NULL },
352 };
353
354 static bool
355 validate_var(struct efi_variable *var, u8 *data, unsigned long len)
356 {
357         int i;
358         u16 *unicode_name = var->VariableName;
359
360         for (i = 0; variable_validate[i].validate != NULL; i++) {
361                 const char *name = variable_validate[i].name;
362                 int match;
363
364                 for (match = 0; ; match++) {
365                         char c = name[match];
366                         u16 u = unicode_name[match];
367
368                         /* All special variables are plain ascii */
369                         if (u > 127)
370                                 return true;
371
372                         /* Wildcard in the matching name means we've matched */
373                         if (c == '*')
374                                 return variable_validate[i].validate(var,
375                                                              match, data, len);
376
377                         /* Case sensitive match */
378                         if (c != u)
379                                 break;
380
381                         /* Reached the end of the string while matching */
382                         if (!c)
383                                 return variable_validate[i].validate(var,
384                                                              match, data, len);
385                 }
386         }
387
388         return true;
389 }
390
391 static efi_status_t
392 get_var_data_locked(struct efivars *efivars, struct efi_variable *var)
393 {
394         efi_status_t status;
395
396         var->DataSize = 1024;
397         status = efivars->ops->get_variable(var->VariableName,
398                                             &var->VendorGuid,
399                                             &var->Attributes,
400                                             &var->DataSize,
401                                             var->Data);
402         return status;
403 }
404
405 static efi_status_t
406 get_var_data(struct efivars *efivars, struct efi_variable *var)
407 {
408         efi_status_t status;
409         unsigned long flags;
410
411         spin_lock_irqsave(&efivars->lock, flags);
412         status = get_var_data_locked(efivars, var);
413         spin_unlock_irqrestore(&efivars->lock, flags);
414
415         if (status != EFI_SUCCESS) {
416                 printk(KERN_WARNING "efivars: get_variable() failed 0x%lx!\n",
417                         status);
418         }
419         return status;
420 }
421
422 static efi_status_t
423 check_var_size_locked(struct efivars *efivars, u32 attributes,
424                         unsigned long size)
425 {
426         u64 storage_size, remaining_size, max_size;
427         efi_status_t status;
428         const struct efivar_operations *fops = efivars->ops;
429
430         if (!efivars->ops->query_variable_info)
431                 return EFI_UNSUPPORTED;
432
433         status = fops->query_variable_info(attributes, &storage_size,
434                                            &remaining_size, &max_size);
435
436         if (status != EFI_SUCCESS)
437                 return status;
438
439         if (!storage_size || size > remaining_size || size > max_size ||
440             (remaining_size - size) < (storage_size / 2))
441                 return EFI_OUT_OF_RESOURCES;
442
443         return status;
444 }
445
446
447 static efi_status_t
448 check_var_size(struct efivars *efivars, u32 attributes, unsigned long size)
449 {
450         efi_status_t status;
451         unsigned long flags;
452
453         spin_lock_irqsave(&efivars->lock, flags);
454         status = check_var_size_locked(efivars, attributes, size);
455         spin_unlock_irqrestore(&efivars->lock, flags);
456
457         return status;
458 }
459
460 static ssize_t
461 efivar_guid_read(struct efivar_entry *entry, char *buf)
462 {
463         struct efi_variable *var = &entry->var;
464         char *str = buf;
465
466         if (!entry || !buf)
467                 return 0;
468
469         efi_guid_unparse(&var->VendorGuid, str);
470         str += strlen(str);
471         str += sprintf(str, "\n");
472
473         return str - buf;
474 }
475
476 static ssize_t
477 efivar_attr_read(struct efivar_entry *entry, char *buf)
478 {
479         struct efi_variable *var = &entry->var;
480         char *str = buf;
481         efi_status_t status;
482
483         if (!entry || !buf)
484                 return -EINVAL;
485
486         status = get_var_data(entry->efivars, var);
487         if (status != EFI_SUCCESS)
488                 return -EIO;
489
490         if (var->Attributes & EFI_VARIABLE_NON_VOLATILE)
491                 str += sprintf(str, "EFI_VARIABLE_NON_VOLATILE\n");
492         if (var->Attributes & EFI_VARIABLE_BOOTSERVICE_ACCESS)
493                 str += sprintf(str, "EFI_VARIABLE_BOOTSERVICE_ACCESS\n");
494         if (var->Attributes & EFI_VARIABLE_RUNTIME_ACCESS)
495                 str += sprintf(str, "EFI_VARIABLE_RUNTIME_ACCESS\n");
496         if (var->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD)
497                 str += sprintf(str, "EFI_VARIABLE_HARDWARE_ERROR_RECORD\n");
498         if (var->Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
499                 str += sprintf(str,
500                         "EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS\n");
501         if (var->Attributes &
502                         EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)
503                 str += sprintf(str,
504                         "EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS\n");
505         if (var->Attributes & EFI_VARIABLE_APPEND_WRITE)
506                 str += sprintf(str, "EFI_VARIABLE_APPEND_WRITE\n");
507         return str - buf;
508 }
509
510 static ssize_t
511 efivar_size_read(struct efivar_entry *entry, char *buf)
512 {
513         struct efi_variable *var = &entry->var;
514         char *str = buf;
515         efi_status_t status;
516
517         if (!entry || !buf)
518                 return -EINVAL;
519
520         status = get_var_data(entry->efivars, var);
521         if (status != EFI_SUCCESS)
522                 return -EIO;
523
524         str += sprintf(str, "0x%lx\n", var->DataSize);
525         return str - buf;
526 }
527
528 static ssize_t
529 efivar_data_read(struct efivar_entry *entry, char *buf)
530 {
531         struct efi_variable *var = &entry->var;
532         efi_status_t status;
533
534         if (!entry || !buf)
535                 return -EINVAL;
536
537         status = get_var_data(entry->efivars, var);
538         if (status != EFI_SUCCESS)
539                 return -EIO;
540
541         memcpy(buf, var->Data, var->DataSize);
542         return var->DataSize;
543 }
544 /*
545  * We allow each variable to be edited via rewriting the
546  * entire efi variable structure.
547  */
548 static ssize_t
549 efivar_store_raw(struct efivar_entry *entry, const char *buf, size_t count)
550 {
551         struct efi_variable *new_var, *var = &entry->var;
552         struct efivars *efivars = entry->efivars;
553         efi_status_t status = EFI_NOT_FOUND;
554
555         if (count != sizeof(struct efi_variable))
556                 return -EINVAL;
557
558         new_var = (struct efi_variable *)buf;
559         /*
560          * If only updating the variable data, then the name
561          * and guid should remain the same
562          */
563         if (memcmp(new_var->VariableName, var->VariableName, sizeof(var->VariableName)) ||
564                 efi_guidcmp(new_var->VendorGuid, var->VendorGuid)) {
565                 printk(KERN_ERR "efivars: Cannot edit the wrong variable!\n");
566                 return -EINVAL;
567         }
568
569         if ((new_var->DataSize <= 0) || (new_var->Attributes == 0)){
570                 printk(KERN_ERR "efivars: DataSize & Attributes must be valid!\n");
571                 return -EINVAL;
572         }
573
574         if ((new_var->Attributes & ~EFI_VARIABLE_MASK) != 0 ||
575             validate_var(new_var, new_var->Data, new_var->DataSize) == false) {
576                 printk(KERN_ERR "efivars: Malformed variable content\n");
577                 return -EINVAL;
578         }
579
580         spin_lock_irq(&efivars->lock);
581
582         status = check_var_size_locked(efivars, new_var->Attributes,
583                new_var->DataSize + utf16_strsize(new_var->VariableName, 1024));
584
585         if (status == EFI_SUCCESS || status == EFI_UNSUPPORTED)
586                 status = efivars->ops->set_variable(new_var->VariableName,
587                                                     &new_var->VendorGuid,
588                                                     new_var->Attributes,
589                                                     new_var->DataSize,
590                                                     new_var->Data);
591
592         spin_unlock_irq(&efivars->lock);
593
594         if (status != EFI_SUCCESS) {
595                 printk(KERN_WARNING "efivars: set_variable() failed: status=%lx\n",
596                         status);
597                 return -EIO;
598         }
599
600         memcpy(&entry->var, new_var, count);
601         return count;
602 }
603
604 static ssize_t
605 efivar_show_raw(struct efivar_entry *entry, char *buf)
606 {
607         struct efi_variable *var = &entry->var;
608         efi_status_t status;
609
610         if (!entry || !buf)
611                 return 0;
612
613         status = get_var_data(entry->efivars, var);
614         if (status != EFI_SUCCESS)
615                 return -EIO;
616
617         memcpy(buf, var, sizeof(*var));
618         return sizeof(*var);
619 }
620
621 /*
622  * Generic read/write functions that call the specific functions of
623  * the attributes...
624  */
625 static ssize_t efivar_attr_show(struct kobject *kobj, struct attribute *attr,
626                                 char *buf)
627 {
628         struct efivar_entry *var = to_efivar_entry(kobj);
629         struct efivar_attribute *efivar_attr = to_efivar_attr(attr);
630         ssize_t ret = -EIO;
631
632         if (!capable(CAP_SYS_ADMIN))
633                 return -EACCES;
634
635         if (efivar_attr->show) {
636                 ret = efivar_attr->show(var, buf);
637         }
638         return ret;
639 }
640
641 static ssize_t efivar_attr_store(struct kobject *kobj, struct attribute *attr,
642                                 const char *buf, size_t count)
643 {
644         struct efivar_entry *var = to_efivar_entry(kobj);
645         struct efivar_attribute *efivar_attr = to_efivar_attr(attr);
646         ssize_t ret = -EIO;
647
648         if (!capable(CAP_SYS_ADMIN))
649                 return -EACCES;
650
651         if (efivar_attr->store)
652                 ret = efivar_attr->store(var, buf, count);
653
654         return ret;
655 }
656
657 static const struct sysfs_ops efivar_attr_ops = {
658         .show = efivar_attr_show,
659         .store = efivar_attr_store,
660 };
661
662 static void efivar_release(struct kobject *kobj)
663 {
664         struct efivar_entry *var = container_of(kobj, struct efivar_entry, kobj);
665         kfree(var);
666 }
667
668 static EFIVAR_ATTR(guid, 0400, efivar_guid_read, NULL);
669 static EFIVAR_ATTR(attributes, 0400, efivar_attr_read, NULL);
670 static EFIVAR_ATTR(size, 0400, efivar_size_read, NULL);
671 static EFIVAR_ATTR(data, 0400, efivar_data_read, NULL);
672 static EFIVAR_ATTR(raw_var, 0600, efivar_show_raw, efivar_store_raw);
673
674 static struct attribute *def_attrs[] = {
675         &efivar_attr_guid.attr,
676         &efivar_attr_size.attr,
677         &efivar_attr_attributes.attr,
678         &efivar_attr_data.attr,
679         &efivar_attr_raw_var.attr,
680         NULL,
681 };
682
683 static struct kobj_type efivar_ktype = {
684         .release = efivar_release,
685         .sysfs_ops = &efivar_attr_ops,
686         .default_attrs = def_attrs,
687 };
688
689 static inline void
690 efivar_unregister(struct efivar_entry *var)
691 {
692         kobject_put(&var->kobj);
693 }
694
695 static int efivarfs_file_open(struct inode *inode, struct file *file)
696 {
697         file->private_data = inode->i_private;
698         return 0;
699 }
700
701 static int efi_status_to_err(efi_status_t status)
702 {
703         int err;
704
705         switch (status) {
706         case EFI_INVALID_PARAMETER:
707                 err = -EINVAL;
708                 break;
709         case EFI_OUT_OF_RESOURCES:
710                 err = -ENOSPC;
711                 break;
712         case EFI_DEVICE_ERROR:
713                 err = -EIO;
714                 break;
715         case EFI_WRITE_PROTECTED:
716                 err = -EROFS;
717                 break;
718         case EFI_SECURITY_VIOLATION:
719                 err = -EACCES;
720                 break;
721         case EFI_NOT_FOUND:
722                 err = -EIO;
723                 break;
724         default:
725                 err = -EINVAL;
726         }
727
728         return err;
729 }
730
731 static ssize_t efivarfs_file_write(struct file *file,
732                 const char __user *userbuf, size_t count, loff_t *ppos)
733 {
734         struct efivar_entry *var = file->private_data;
735         struct efivars *efivars;
736         efi_status_t status;
737         void *data;
738         u32 attributes;
739         struct inode *inode = file->f_mapping->host;
740         unsigned long datasize = count - sizeof(attributes);
741         unsigned long newdatasize, varsize;
742         ssize_t bytes = 0;
743
744         if (count < sizeof(attributes))
745                 return -EINVAL;
746
747         if (copy_from_user(&attributes, userbuf, sizeof(attributes)))
748                 return -EFAULT;
749
750         if (attributes & ~(EFI_VARIABLE_MASK))
751                 return -EINVAL;
752
753         efivars = var->efivars;
754
755         /*
756          * Ensure that the user can't allocate arbitrarily large
757          * amounts of memory. Pick a default size of 64K if
758          * QueryVariableInfo() isn't supported by the firmware.
759          */
760
761         varsize = datasize + utf16_strsize(var->var.VariableName, 1024);
762         status = check_var_size(efivars, attributes, varsize);
763
764         if (status != EFI_SUCCESS) {
765                 if (status != EFI_UNSUPPORTED)
766                         return efi_status_to_err(status);
767
768                 if (datasize > 65536)
769                         return -ENOSPC;
770         }
771
772         data = kmalloc(datasize, GFP_KERNEL);
773         if (!data)
774                 return -ENOMEM;
775
776         if (copy_from_user(data, userbuf + sizeof(attributes), datasize)) {
777                 bytes = -EFAULT;
778                 goto out;
779         }
780
781         if (validate_var(&var->var, data, datasize) == false) {
782                 bytes = -EINVAL;
783                 goto out;
784         }
785
786         /*
787          * The lock here protects the get_variable call, the conditional
788          * set_variable call, and removal of the variable from the efivars
789          * list (in the case of an authenticated delete).
790          */
791         spin_lock_irq(&efivars->lock);
792
793         /*
794          * Ensure that the available space hasn't shrunk below the safe level
795          */
796
797         status = check_var_size_locked(efivars, attributes, varsize);
798
799         if (status != EFI_SUCCESS && status != EFI_UNSUPPORTED) {
800                 spin_unlock_irq(&efivars->lock);
801                 kfree(data);
802
803                 return efi_status_to_err(status);
804         }
805
806         status = efivars->ops->set_variable(var->var.VariableName,
807                                             &var->var.VendorGuid,
808                                             attributes, datasize,
809                                             data);
810
811         if (status != EFI_SUCCESS) {
812                 spin_unlock_irq(&efivars->lock);
813                 kfree(data);
814
815                 return efi_status_to_err(status);
816         }
817
818         bytes = count;
819
820         /*
821          * Writing to the variable may have caused a change in size (which
822          * could either be an append or an overwrite), or the variable to be
823          * deleted. Perform a GetVariable() so we can tell what actually
824          * happened.
825          */
826         newdatasize = 0;
827         status = efivars->ops->get_variable(var->var.VariableName,
828                                             &var->var.VendorGuid,
829                                             NULL, &newdatasize,
830                                             NULL);
831
832         if (status == EFI_BUFFER_TOO_SMALL) {
833                 spin_unlock_irq(&efivars->lock);
834                 mutex_lock(&inode->i_mutex);
835                 i_size_write(inode, newdatasize + sizeof(attributes));
836                 mutex_unlock(&inode->i_mutex);
837
838         } else if (status == EFI_NOT_FOUND) {
839                 list_del(&var->list);
840                 spin_unlock_irq(&efivars->lock);
841                 efivar_unregister(var);
842                 drop_nlink(inode);
843                 d_delete(file->f_dentry);
844                 dput(file->f_dentry);
845
846         } else {
847                 spin_unlock_irq(&efivars->lock);
848                 pr_warn("efivarfs: inconsistent EFI variable implementation? "
849                                 "status = %lx\n", status);
850         }
851
852 out:
853         kfree(data);
854
855         return bytes;
856 }
857
858 static ssize_t efivarfs_file_read(struct file *file, char __user *userbuf,
859                 size_t count, loff_t *ppos)
860 {
861         struct efivar_entry *var = file->private_data;
862         struct efivars *efivars = var->efivars;
863         efi_status_t status;
864         unsigned long datasize = 0;
865         u32 attributes;
866         void *data;
867         ssize_t size = 0;
868
869         spin_lock_irq(&efivars->lock);
870         status = efivars->ops->get_variable(var->var.VariableName,
871                                             &var->var.VendorGuid,
872                                             &attributes, &datasize, NULL);
873         spin_unlock_irq(&efivars->lock);
874
875         if (status != EFI_BUFFER_TOO_SMALL)
876                 return efi_status_to_err(status);
877
878         data = kmalloc(datasize + sizeof(attributes), GFP_KERNEL);
879
880         if (!data)
881                 return -ENOMEM;
882
883         spin_lock_irq(&efivars->lock);
884         status = efivars->ops->get_variable(var->var.VariableName,
885                                             &var->var.VendorGuid,
886                                             &attributes, &datasize,
887                                             (data + sizeof(attributes)));
888         spin_unlock_irq(&efivars->lock);
889
890         if (status != EFI_SUCCESS) {
891                 size = efi_status_to_err(status);
892                 goto out_free;
893         }
894
895         memcpy(data, &attributes, sizeof(attributes));
896         size = simple_read_from_buffer(userbuf, count, ppos,
897                                        data, datasize + sizeof(attributes));
898 out_free:
899         kfree(data);
900
901         return size;
902 }
903
904 static void efivarfs_evict_inode(struct inode *inode)
905 {
906         clear_inode(inode);
907 }
908
909 static const struct super_operations efivarfs_ops = {
910         .statfs = simple_statfs,
911         .drop_inode = generic_delete_inode,
912         .evict_inode = efivarfs_evict_inode,
913         .show_options = generic_show_options,
914 };
915
916 static struct super_block *efivarfs_sb;
917
918 static const struct inode_operations efivarfs_dir_inode_operations;
919
920 static const struct file_operations efivarfs_file_operations = {
921         .open   = efivarfs_file_open,
922         .read   = efivarfs_file_read,
923         .write  = efivarfs_file_write,
924         .llseek = no_llseek,
925 };
926
927 static struct inode *efivarfs_get_inode(struct super_block *sb,
928                                 const struct inode *dir, int mode, dev_t dev)
929 {
930         struct inode *inode = new_inode(sb);
931
932         if (inode) {
933                 inode->i_ino = get_next_ino();
934                 inode->i_mode = mode;
935                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
936                 switch (mode & S_IFMT) {
937                 case S_IFREG:
938                         inode->i_fop = &efivarfs_file_operations;
939                         break;
940                 case S_IFDIR:
941                         inode->i_op = &efivarfs_dir_inode_operations;
942                         inode->i_fop = &simple_dir_operations;
943                         inc_nlink(inode);
944                         break;
945                 }
946         }
947         return inode;
948 }
949
950 /*
951  * Return true if 'str' is a valid efivarfs filename of the form,
952  *
953  *      VariableName-12345678-1234-1234-1234-1234567891bc
954  */
955 static bool efivarfs_valid_name(const char *str, int len)
956 {
957         static const char dashes[GUID_LEN] = {
958                 [8] = 1, [13] = 1, [18] = 1, [23] = 1
959         };
960         const char *s = str + len - GUID_LEN;
961         int i;
962
963         /*
964          * We need a GUID, plus at least one letter for the variable name,
965          * plus the '-' separator
966          */
967         if (len < GUID_LEN + 2)
968                 return false;
969
970         /* GUID must be preceded by a '-' */
971         if (*(s - 1) != '-')
972                 return false;
973
974         /*
975          * Validate that 's' is of the correct format, e.g.
976          *
977          *      12345678-1234-1234-1234-123456789abc
978          */
979         for (i = 0; i < GUID_LEN; i++) {
980                 if (dashes[i]) {
981                         if (*s++ != '-')
982                                 return false;
983                 } else {
984                         if (!isxdigit(*s++))
985                                 return false;
986                 }
987         }
988
989         return true;
990 }
991
992 static void efivarfs_hex_to_guid(const char *str, efi_guid_t *guid)
993 {
994         guid->b[0] = hex_to_bin(str[6]) << 4 | hex_to_bin(str[7]);
995         guid->b[1] = hex_to_bin(str[4]) << 4 | hex_to_bin(str[5]);
996         guid->b[2] = hex_to_bin(str[2]) << 4 | hex_to_bin(str[3]);
997         guid->b[3] = hex_to_bin(str[0]) << 4 | hex_to_bin(str[1]);
998         guid->b[4] = hex_to_bin(str[11]) << 4 | hex_to_bin(str[12]);
999         guid->b[5] = hex_to_bin(str[9]) << 4 | hex_to_bin(str[10]);
1000         guid->b[6] = hex_to_bin(str[16]) << 4 | hex_to_bin(str[17]);
1001         guid->b[7] = hex_to_bin(str[14]) << 4 | hex_to_bin(str[15]);
1002         guid->b[8] = hex_to_bin(str[19]) << 4 | hex_to_bin(str[20]);
1003         guid->b[9] = hex_to_bin(str[21]) << 4 | hex_to_bin(str[22]);
1004         guid->b[10] = hex_to_bin(str[24]) << 4 | hex_to_bin(str[25]);
1005         guid->b[11] = hex_to_bin(str[26]) << 4 | hex_to_bin(str[27]);
1006         guid->b[12] = hex_to_bin(str[28]) << 4 | hex_to_bin(str[29]);
1007         guid->b[13] = hex_to_bin(str[30]) << 4 | hex_to_bin(str[31]);
1008         guid->b[14] = hex_to_bin(str[32]) << 4 | hex_to_bin(str[33]);
1009         guid->b[15] = hex_to_bin(str[34]) << 4 | hex_to_bin(str[35]);
1010 }
1011
1012 static int efivarfs_create(struct inode *dir, struct dentry *dentry,
1013                           umode_t mode, bool excl)
1014 {
1015         struct inode *inode;
1016         struct efivars *efivars = &__efivars;
1017         struct efivar_entry *var;
1018         int namelen, i = 0, err = 0;
1019
1020         if (!efivarfs_valid_name(dentry->d_name.name, dentry->d_name.len))
1021                 return -EINVAL;
1022
1023         inode = efivarfs_get_inode(dir->i_sb, dir, mode, 0);
1024         if (!inode)
1025                 return -ENOMEM;
1026
1027         var = kzalloc(sizeof(struct efivar_entry), GFP_KERNEL);
1028         if (!var) {
1029                 err = -ENOMEM;
1030                 goto out;
1031         }
1032
1033         /* length of the variable name itself: remove GUID and separator */
1034         namelen = dentry->d_name.len - GUID_LEN - 1;
1035
1036         efivarfs_hex_to_guid(dentry->d_name.name + namelen + 1,
1037                         &var->var.VendorGuid);
1038
1039         for (i = 0; i < namelen; i++)
1040                 var->var.VariableName[i] = dentry->d_name.name[i];
1041
1042         var->var.VariableName[i] = '\0';
1043
1044         inode->i_private = var;
1045         var->efivars = efivars;
1046         var->kobj.kset = efivars->kset;
1047
1048         err = kobject_init_and_add(&var->kobj, &efivar_ktype, NULL, "%s",
1049                              dentry->d_name.name);
1050         if (err)
1051                 goto out;
1052
1053         kobject_uevent(&var->kobj, KOBJ_ADD);
1054         spin_lock_irq(&efivars->lock);
1055         list_add(&var->list, &efivars->list);
1056         spin_unlock_irq(&efivars->lock);
1057         d_instantiate(dentry, inode);
1058         dget(dentry);
1059 out:
1060         if (err) {
1061                 kfree(var);
1062                 iput(inode);
1063         }
1064         return err;
1065 }
1066
1067 static int efivarfs_unlink(struct inode *dir, struct dentry *dentry)
1068 {
1069         struct efivar_entry *var = dentry->d_inode->i_private;
1070         struct efivars *efivars = var->efivars;
1071         efi_status_t status;
1072
1073         spin_lock_irq(&efivars->lock);
1074
1075         status = efivars->ops->set_variable(var->var.VariableName,
1076                                             &var->var.VendorGuid,
1077                                             0, 0, NULL);
1078
1079         if (status == EFI_SUCCESS || status == EFI_NOT_FOUND) {
1080                 list_del(&var->list);
1081                 spin_unlock_irq(&efivars->lock);
1082                 efivar_unregister(var);
1083                 drop_nlink(dentry->d_inode);
1084                 dput(dentry);
1085                 return 0;
1086         }
1087
1088         spin_unlock_irq(&efivars->lock);
1089         return -EINVAL;
1090 };
1091
1092 /*
1093  * Compare two efivarfs file names.
1094  *
1095  * An efivarfs filename is composed of two parts,
1096  *
1097  *      1. A case-sensitive variable name
1098  *      2. A case-insensitive GUID
1099  *
1100  * So we need to perform a case-sensitive match on part 1 and a
1101  * case-insensitive match on part 2.
1102  */
1103 static int efivarfs_d_compare(const struct dentry *parent, const struct inode *pinode,
1104                               const struct dentry *dentry, const struct inode *inode,
1105                               unsigned int len, const char *str,
1106                               const struct qstr *name)
1107 {
1108         int guid = len - GUID_LEN;
1109
1110         if (name->len != len)
1111                 return 1;
1112
1113         /* Case-sensitive compare for the variable name */
1114         if (memcmp(str, name->name, guid))
1115                 return 1;
1116
1117         /* Case-insensitive compare for the GUID */
1118         return strncasecmp(name->name + guid, str + guid, GUID_LEN);
1119 }
1120
1121 static int efivarfs_d_hash(const struct dentry *dentry,
1122                            const struct inode *inode, struct qstr *qstr)
1123 {
1124         unsigned long hash = init_name_hash();
1125         const unsigned char *s = qstr->name;
1126         unsigned int len = qstr->len;
1127
1128         if (!efivarfs_valid_name(s, len))
1129                 return -EINVAL;
1130
1131         while (len-- > GUID_LEN)
1132                 hash = partial_name_hash(*s++, hash);
1133
1134         /* GUID is case-insensitive. */
1135         while (len--)
1136                 hash = partial_name_hash(tolower(*s++), hash);
1137
1138         qstr->hash = end_name_hash(hash);
1139         return 0;
1140 }
1141
1142 /*
1143  * Retaining negative dentries for an in-memory filesystem just wastes
1144  * memory and lookup time: arrange for them to be deleted immediately.
1145  */
1146 static int efivarfs_delete_dentry(const struct dentry *dentry)
1147 {
1148         return 1;
1149 }
1150
1151 static struct dentry_operations efivarfs_d_ops = {
1152         .d_compare = efivarfs_d_compare,
1153         .d_hash = efivarfs_d_hash,
1154         .d_delete = efivarfs_delete_dentry,
1155 };
1156
1157 static struct dentry *efivarfs_alloc_dentry(struct dentry *parent, char *name)
1158 {
1159         struct dentry *d;
1160         struct qstr q;
1161         int err;
1162
1163         q.name = name;
1164         q.len = strlen(name);
1165
1166         err = efivarfs_d_hash(NULL, NULL, &q);
1167         if (err)
1168                 return ERR_PTR(err);
1169
1170         d = d_alloc(parent, &q);
1171         if (d)
1172                 return d;
1173
1174         return ERR_PTR(-ENOMEM);
1175 }
1176
1177 static int efivarfs_fill_super(struct super_block *sb, void *data, int silent)
1178 {
1179         struct inode *inode = NULL;
1180         struct dentry *root;
1181         struct efivar_entry *entry, *n;
1182         struct efivars *efivars = &__efivars;
1183         char *name;
1184         int err = -ENOMEM;
1185
1186         efivarfs_sb = sb;
1187
1188         sb->s_maxbytes          = MAX_LFS_FILESIZE;
1189         sb->s_blocksize         = PAGE_CACHE_SIZE;
1190         sb->s_blocksize_bits    = PAGE_CACHE_SHIFT;
1191         sb->s_magic             = EFIVARFS_MAGIC;
1192         sb->s_op                = &efivarfs_ops;
1193         sb->s_d_op              = &efivarfs_d_ops;
1194         sb->s_time_gran         = 1;
1195
1196         inode = efivarfs_get_inode(sb, NULL, S_IFDIR | 0755, 0);
1197         if (!inode)
1198                 return -ENOMEM;
1199         inode->i_op = &efivarfs_dir_inode_operations;
1200
1201         root = d_make_root(inode);
1202         sb->s_root = root;
1203         if (!root)
1204                 return -ENOMEM;
1205
1206         list_for_each_entry_safe(entry, n, &efivars->list, list) {
1207                 struct dentry *dentry, *root = efivarfs_sb->s_root;
1208                 unsigned long size = 0;
1209                 int len, i;
1210
1211                 inode = NULL;
1212
1213                 len = utf16_strlen(entry->var.VariableName);
1214
1215                 /* name, plus '-', plus GUID, plus NUL*/
1216                 name = kmalloc(len + 1 + GUID_LEN + 1, GFP_ATOMIC);
1217                 if (!name)
1218                         goto fail;
1219
1220                 for (i = 0; i < len; i++)
1221                         name[i] = entry->var.VariableName[i] & 0xFF;
1222
1223                 name[len] = '-';
1224
1225                 efi_guid_unparse(&entry->var.VendorGuid, name + len + 1);
1226
1227                 name[len+GUID_LEN+1] = '\0';
1228
1229                 inode = efivarfs_get_inode(efivarfs_sb, root->d_inode,
1230                                           S_IFREG | 0644, 0);
1231                 if (!inode)
1232                         goto fail_name;
1233
1234                 dentry = efivarfs_alloc_dentry(root, name);
1235                 if (IS_ERR(dentry)) {
1236                         err = PTR_ERR(dentry);
1237                         goto fail_inode;
1238                 }
1239
1240                 /* copied by the above to local storage in the dentry. */
1241                 kfree(name);
1242
1243                 spin_lock_irq(&efivars->lock);
1244                 efivars->ops->get_variable(entry->var.VariableName,
1245                                            &entry->var.VendorGuid,
1246                                            &entry->var.Attributes,
1247                                            &size,
1248                                            NULL);
1249                 spin_unlock_irq(&efivars->lock);
1250
1251                 mutex_lock(&inode->i_mutex);
1252                 inode->i_private = entry;
1253                 i_size_write(inode, size+4);
1254                 mutex_unlock(&inode->i_mutex);
1255                 d_add(dentry, inode);
1256         }
1257
1258         return 0;
1259
1260 fail_inode:
1261         iput(inode);
1262 fail_name:
1263         kfree(name);
1264 fail:
1265         return err;
1266 }
1267
1268 static struct dentry *efivarfs_mount(struct file_system_type *fs_type,
1269                                     int flags, const char *dev_name, void *data)
1270 {
1271         return mount_single(fs_type, flags, data, efivarfs_fill_super);
1272 }
1273
1274 static void efivarfs_kill_sb(struct super_block *sb)
1275 {
1276         kill_litter_super(sb);
1277         efivarfs_sb = NULL;
1278 }
1279
1280 static struct file_system_type efivarfs_type = {
1281         .name    = "efivarfs",
1282         .mount   = efivarfs_mount,
1283         .kill_sb = efivarfs_kill_sb,
1284 };
1285
1286 /*
1287  * Handle negative dentry.
1288  */
1289 static struct dentry *efivarfs_lookup(struct inode *dir, struct dentry *dentry,
1290                                       unsigned int flags)
1291 {
1292         if (dentry->d_name.len > NAME_MAX)
1293                 return ERR_PTR(-ENAMETOOLONG);
1294         d_add(dentry, NULL);
1295         return NULL;
1296 }
1297
1298 static const struct inode_operations efivarfs_dir_inode_operations = {
1299         .lookup = efivarfs_lookup,
1300         .unlink = efivarfs_unlink,
1301         .create = efivarfs_create,
1302 };
1303
1304 static struct pstore_info efi_pstore_info;
1305
1306 #ifdef CONFIG_PSTORE
1307
1308 static int efi_pstore_open(struct pstore_info *psi)
1309 {
1310         struct efivars *efivars = psi->data;
1311
1312         spin_lock_irq(&efivars->lock);
1313         efivars->walk_entry = list_first_entry(&efivars->list,
1314                                                struct efivar_entry, list);
1315         return 0;
1316 }
1317
1318 static int efi_pstore_close(struct pstore_info *psi)
1319 {
1320         struct efivars *efivars = psi->data;
1321
1322         spin_unlock_irq(&efivars->lock);
1323         return 0;
1324 }
1325
1326 static ssize_t efi_pstore_read(u64 *id, enum pstore_type_id *type,
1327                                int *count, struct timespec *timespec,
1328                                char **buf, struct pstore_info *psi)
1329 {
1330         efi_guid_t vendor = LINUX_EFI_CRASH_GUID;
1331         struct efivars *efivars = psi->data;
1332         char name[DUMP_NAME_LEN];
1333         int i;
1334         int cnt;
1335         unsigned int part, size;
1336         unsigned long time;
1337
1338         while (&efivars->walk_entry->list != &efivars->list) {
1339                 if (!efi_guidcmp(efivars->walk_entry->var.VendorGuid,
1340                                  vendor)) {
1341                         for (i = 0; i < DUMP_NAME_LEN; i++) {
1342                                 name[i] = efivars->walk_entry->var.VariableName[i];
1343                         }
1344                         if (sscanf(name, "dump-type%u-%u-%d-%lu",
1345                                    type, &part, &cnt, &time) == 4) {
1346                                 *id = part;
1347                                 *count = cnt;
1348                                 timespec->tv_sec = time;
1349                                 timespec->tv_nsec = 0;
1350                         } else if (sscanf(name, "dump-type%u-%u-%lu",
1351                                    type, &part, &time) == 3) {
1352                                 /*
1353                                  * Check if an old format,
1354                                  * which doesn't support holding
1355                                  * multiple logs, remains.
1356                                  */
1357                                 *id = part;
1358                                 *count = 0;
1359                                 timespec->tv_sec = time;
1360                                 timespec->tv_nsec = 0;
1361                         } else {
1362                                 efivars->walk_entry = list_entry(
1363                                                 efivars->walk_entry->list.next,
1364                                                 struct efivar_entry, list);
1365                                 continue;
1366                         }
1367
1368                         get_var_data_locked(efivars, &efivars->walk_entry->var);
1369                         size = efivars->walk_entry->var.DataSize;
1370                         *buf = kmalloc(size, GFP_KERNEL);
1371                         if (*buf == NULL)
1372                                 return -ENOMEM;
1373                         memcpy(*buf, efivars->walk_entry->var.Data,
1374                                size);
1375                         efivars->walk_entry = list_entry(
1376                                         efivars->walk_entry->list.next,
1377                                         struct efivar_entry, list);
1378                         return size;
1379                 }
1380                 efivars->walk_entry = list_entry(efivars->walk_entry->list.next,
1381                                                  struct efivar_entry, list);
1382         }
1383         return 0;
1384 }
1385
1386 static int efi_pstore_write(enum pstore_type_id type,
1387                 enum kmsg_dump_reason reason, u64 *id,
1388                 unsigned int part, int count, size_t size,
1389                 struct pstore_info *psi)
1390 {
1391         char name[DUMP_NAME_LEN];
1392         efi_char16_t efi_name[DUMP_NAME_LEN];
1393         efi_guid_t vendor = LINUX_EFI_CRASH_GUID;
1394         struct efivars *efivars = psi->data;
1395         int i, ret = 0;
1396         efi_status_t status = EFI_NOT_FOUND;
1397         unsigned long flags;
1398
1399         spin_lock_irqsave(&efivars->lock, flags);
1400
1401         /*
1402          * Check if there is a space enough to log.
1403          * size: a size of logging data
1404          * DUMP_NAME_LEN * 2: a maximum size of variable name
1405          */
1406
1407         status = check_var_size_locked(efivars, PSTORE_EFI_ATTRIBUTES,
1408                                          size + DUMP_NAME_LEN * 2);
1409
1410         if (status) {
1411                 spin_unlock_irqrestore(&efivars->lock, flags);
1412                 *id = part;
1413                 return -ENOSPC;
1414         }
1415
1416         sprintf(name, "dump-type%u-%u-%d-%lu", type, part, count,
1417                 get_seconds());
1418
1419         for (i = 0; i < DUMP_NAME_LEN; i++)
1420                 efi_name[i] = name[i];
1421
1422         efivars->ops->set_variable(efi_name, &vendor, PSTORE_EFI_ATTRIBUTES,
1423                                    size, psi->buf);
1424
1425         spin_unlock_irqrestore(&efivars->lock, flags);
1426
1427         if (size)
1428                 ret = efivar_create_sysfs_entry(efivars,
1429                                           utf16_strsize(efi_name,
1430                                                         DUMP_NAME_LEN * 2),
1431                                           efi_name, &vendor);
1432
1433         *id = part;
1434         return ret;
1435 };
1436
1437 static int efi_pstore_erase(enum pstore_type_id type, u64 id, int count,
1438                             struct timespec time, struct pstore_info *psi)
1439 {
1440         char name[DUMP_NAME_LEN];
1441         efi_char16_t efi_name[DUMP_NAME_LEN];
1442         char name_old[DUMP_NAME_LEN];
1443         efi_char16_t efi_name_old[DUMP_NAME_LEN];
1444         efi_guid_t vendor = LINUX_EFI_CRASH_GUID;
1445         struct efivars *efivars = psi->data;
1446         struct efivar_entry *entry, *found = NULL;
1447         int i;
1448
1449         sprintf(name, "dump-type%u-%u-%d-%lu", type, (unsigned int)id, count,
1450                 time.tv_sec);
1451
1452         spin_lock_irq(&efivars->lock);
1453
1454         for (i = 0; i < DUMP_NAME_LEN; i++)
1455                 efi_name[i] = name[i];
1456
1457         /*
1458          * Clean up an entry with the same name
1459          */
1460
1461         list_for_each_entry(entry, &efivars->list, list) {
1462                 get_var_data_locked(efivars, &entry->var);
1463
1464                 if (efi_guidcmp(entry->var.VendorGuid, vendor))
1465                         continue;
1466                 if (utf16_strncmp(entry->var.VariableName, efi_name,
1467                                   utf16_strlen(efi_name))) {
1468                         /*
1469                          * Check if an old format,
1470                          * which doesn't support holding
1471                          * multiple logs, remains.
1472                          */
1473                         sprintf(name_old, "dump-type%u-%u-%lu", type,
1474                                 (unsigned int)id, time.tv_sec);
1475
1476                         for (i = 0; i < DUMP_NAME_LEN; i++)
1477                                 efi_name_old[i] = name_old[i];
1478
1479                         if (utf16_strncmp(entry->var.VariableName, efi_name_old,
1480                                           utf16_strlen(efi_name_old)))
1481                                 continue;
1482                 }
1483
1484                 /* found */
1485                 found = entry;
1486                 efivars->ops->set_variable(entry->var.VariableName,
1487                                            &entry->var.VendorGuid,
1488                                            PSTORE_EFI_ATTRIBUTES,
1489                                            0, NULL);
1490                 break;
1491         }
1492
1493         if (found)
1494                 list_del(&found->list);
1495
1496         spin_unlock_irq(&efivars->lock);
1497
1498         if (found)
1499                 efivar_unregister(found);
1500
1501         return 0;
1502 }
1503 #else
1504 static int efi_pstore_open(struct pstore_info *psi)
1505 {
1506         return 0;
1507 }
1508
1509 static int efi_pstore_close(struct pstore_info *psi)
1510 {
1511         return 0;
1512 }
1513
1514 static ssize_t efi_pstore_read(u64 *id, enum pstore_type_id *type, int *count,
1515                                struct timespec *timespec,
1516                                char **buf, struct pstore_info *psi)
1517 {
1518         return -1;
1519 }
1520
1521 static int efi_pstore_write(enum pstore_type_id type,
1522                 enum kmsg_dump_reason reason, u64 *id,
1523                 unsigned int part, int count, size_t size,
1524                 struct pstore_info *psi)
1525 {
1526         return 0;
1527 }
1528
1529 static int efi_pstore_erase(enum pstore_type_id type, u64 id, int count,
1530                             struct timespec time, struct pstore_info *psi)
1531 {
1532         return 0;
1533 }
1534 #endif
1535
1536 static struct pstore_info efi_pstore_info = {
1537         .owner          = THIS_MODULE,
1538         .name           = "efi",
1539         .open           = efi_pstore_open,
1540         .close          = efi_pstore_close,
1541         .read           = efi_pstore_read,
1542         .write          = efi_pstore_write,
1543         .erase          = efi_pstore_erase,
1544 };
1545
1546 static ssize_t efivar_create(struct file *filp, struct kobject *kobj,
1547                              struct bin_attribute *bin_attr,
1548                              char *buf, loff_t pos, size_t count)
1549 {
1550         struct efi_variable *new_var = (struct efi_variable *)buf;
1551         struct efivars *efivars = bin_attr->private;
1552         struct efivar_entry *search_efivar, *n;
1553         unsigned long strsize1, strsize2;
1554         efi_status_t status = EFI_NOT_FOUND;
1555         int found = 0;
1556
1557         if (!capable(CAP_SYS_ADMIN))
1558                 return -EACCES;
1559
1560         if ((new_var->Attributes & ~EFI_VARIABLE_MASK) != 0 ||
1561             validate_var(new_var, new_var->Data, new_var->DataSize) == false) {
1562                 printk(KERN_ERR "efivars: Malformed variable content\n");
1563                 return -EINVAL;
1564         }
1565
1566         spin_lock_irq(&efivars->lock);
1567
1568         /*
1569          * Does this variable already exist?
1570          */
1571         list_for_each_entry_safe(search_efivar, n, &efivars->list, list) {
1572                 strsize1 = utf16_strsize(search_efivar->var.VariableName, 1024);
1573                 strsize2 = utf16_strsize(new_var->VariableName, 1024);
1574                 if (strsize1 == strsize2 &&
1575                         !memcmp(&(search_efivar->var.VariableName),
1576                                 new_var->VariableName, strsize1) &&
1577                         !efi_guidcmp(search_efivar->var.VendorGuid,
1578                                 new_var->VendorGuid)) {
1579                         found = 1;
1580                         break;
1581                 }
1582         }
1583         if (found) {
1584                 spin_unlock_irq(&efivars->lock);
1585                 return -EINVAL;
1586         }
1587
1588         status = check_var_size_locked(efivars, new_var->Attributes,
1589                new_var->DataSize + utf16_strsize(new_var->VariableName, 1024));
1590
1591         if (status && status != EFI_UNSUPPORTED) {
1592                 spin_unlock_irq(&efivars->lock);
1593                 return efi_status_to_err(status);
1594         }
1595
1596         /* now *really* create the variable via EFI */
1597         status = efivars->ops->set_variable(new_var->VariableName,
1598                                             &new_var->VendorGuid,
1599                                             new_var->Attributes,
1600                                             new_var->DataSize,
1601                                             new_var->Data);
1602
1603         if (status != EFI_SUCCESS) {
1604                 printk(KERN_WARNING "efivars: set_variable() failed: status=%lx\n",
1605                         status);
1606                 spin_unlock_irq(&efivars->lock);
1607                 return -EIO;
1608         }
1609         spin_unlock_irq(&efivars->lock);
1610
1611         /* Create the entry in sysfs.  Locking is not required here */
1612         status = efivar_create_sysfs_entry(efivars,
1613                                            utf16_strsize(new_var->VariableName,
1614                                                          1024),
1615                                            new_var->VariableName,
1616                                            &new_var->VendorGuid);
1617         if (status) {
1618                 printk(KERN_WARNING "efivars: variable created, but sysfs entry wasn't.\n");
1619         }
1620         return count;
1621 }
1622
1623 static ssize_t efivar_delete(struct file *filp, struct kobject *kobj,
1624                              struct bin_attribute *bin_attr,
1625                              char *buf, loff_t pos, size_t count)
1626 {
1627         struct efi_variable *del_var = (struct efi_variable *)buf;
1628         struct efivars *efivars = bin_attr->private;
1629         struct efivar_entry *search_efivar, *n;
1630         unsigned long strsize1, strsize2;
1631         efi_status_t status = EFI_NOT_FOUND;
1632         int found = 0;
1633
1634         if (!capable(CAP_SYS_ADMIN))
1635                 return -EACCES;
1636
1637         spin_lock_irq(&efivars->lock);
1638
1639         /*
1640          * Does this variable already exist?
1641          */
1642         list_for_each_entry_safe(search_efivar, n, &efivars->list, list) {
1643                 strsize1 = utf16_strsize(search_efivar->var.VariableName, 1024);
1644                 strsize2 = utf16_strsize(del_var->VariableName, 1024);
1645                 if (strsize1 == strsize2 &&
1646                         !memcmp(&(search_efivar->var.VariableName),
1647                                 del_var->VariableName, strsize1) &&
1648                         !efi_guidcmp(search_efivar->var.VendorGuid,
1649                                 del_var->VendorGuid)) {
1650                         found = 1;
1651                         break;
1652                 }
1653         }
1654         if (!found) {
1655                 spin_unlock_irq(&efivars->lock);
1656                 return -EINVAL;
1657         }
1658         /* force the Attributes/DataSize to 0 to ensure deletion */
1659         del_var->Attributes = 0;
1660         del_var->DataSize = 0;
1661
1662         status = efivars->ops->set_variable(del_var->VariableName,
1663                                             &del_var->VendorGuid,
1664                                             del_var->Attributes,
1665                                             del_var->DataSize,
1666                                             del_var->Data);
1667
1668         if (status != EFI_SUCCESS) {
1669                 printk(KERN_WARNING "efivars: set_variable() failed: status=%lx\n",
1670                         status);
1671                 spin_unlock_irq(&efivars->lock);
1672                 return -EIO;
1673         }
1674         list_del(&search_efivar->list);
1675         /* We need to release this lock before unregistering. */
1676         spin_unlock_irq(&efivars->lock);
1677         efivar_unregister(search_efivar);
1678
1679         /* It's dead Jim.... */
1680         return count;
1681 }
1682
1683 /*
1684  * Let's not leave out systab information that snuck into
1685  * the efivars driver
1686  */
1687 static ssize_t systab_show(struct kobject *kobj,
1688                            struct kobj_attribute *attr, char *buf)
1689 {
1690         char *str = buf;
1691
1692         if (!kobj || !buf)
1693                 return -EINVAL;
1694
1695         if (efi.mps != EFI_INVALID_TABLE_ADDR)
1696                 str += sprintf(str, "MPS=0x%lx\n", efi.mps);
1697         if (efi.acpi20 != EFI_INVALID_TABLE_ADDR)
1698                 str += sprintf(str, "ACPI20=0x%lx\n", efi.acpi20);
1699         if (efi.acpi != EFI_INVALID_TABLE_ADDR)
1700                 str += sprintf(str, "ACPI=0x%lx\n", efi.acpi);
1701         if (efi.smbios != EFI_INVALID_TABLE_ADDR)
1702                 str += sprintf(str, "SMBIOS=0x%lx\n", efi.smbios);
1703         if (efi.hcdp != EFI_INVALID_TABLE_ADDR)
1704                 str += sprintf(str, "HCDP=0x%lx\n", efi.hcdp);
1705         if (efi.boot_info != EFI_INVALID_TABLE_ADDR)
1706                 str += sprintf(str, "BOOTINFO=0x%lx\n", efi.boot_info);
1707         if (efi.uga != EFI_INVALID_TABLE_ADDR)
1708                 str += sprintf(str, "UGA=0x%lx\n", efi.uga);
1709
1710         return str - buf;
1711 }
1712
1713 static struct kobj_attribute efi_attr_systab =
1714                         __ATTR(systab, 0400, systab_show, NULL);
1715
1716 static struct attribute *efi_subsys_attrs[] = {
1717         &efi_attr_systab.attr,
1718         NULL,   /* maybe more in the future? */
1719 };
1720
1721 static struct attribute_group efi_subsys_attr_group = {
1722         .attrs = efi_subsys_attrs,
1723 };
1724
1725 static struct kobject *efi_kobj;
1726
1727 /*
1728  * efivar_create_sysfs_entry()
1729  * Requires:
1730  *    variable_name_size = number of bytes required to hold
1731  *                         variable_name (not counting the NULL
1732  *                         character at the end.
1733  *    efivars->lock is not held on entry or exit.
1734  * Returns 1 on failure, 0 on success
1735  */
1736 static int
1737 efivar_create_sysfs_entry(struct efivars *efivars,
1738                           unsigned long variable_name_size,
1739                           efi_char16_t *variable_name,
1740                           efi_guid_t *vendor_guid)
1741 {
1742         int i, short_name_size;
1743         char *short_name;
1744         struct efivar_entry *new_efivar;
1745
1746         /*
1747          * Length of the variable bytes in ASCII, plus the '-' separator,
1748          * plus the GUID, plus trailing NUL
1749          */
1750         short_name_size = variable_name_size / sizeof(efi_char16_t)
1751                                 + 1 + GUID_LEN + 1;
1752
1753         short_name = kzalloc(short_name_size, GFP_KERNEL);
1754         new_efivar = kzalloc(sizeof(struct efivar_entry), GFP_KERNEL);
1755
1756         if (!short_name || !new_efivar)  {
1757                 kfree(short_name);
1758                 kfree(new_efivar);
1759                 return 1;
1760         }
1761
1762         new_efivar->efivars = efivars;
1763         memcpy(new_efivar->var.VariableName, variable_name,
1764                 variable_name_size);
1765         memcpy(&(new_efivar->var.VendorGuid), vendor_guid, sizeof(efi_guid_t));
1766
1767         /* Convert Unicode to normal chars (assume top bits are 0),
1768            ala UTF-8 */
1769         for (i=0; i < (int)(variable_name_size / sizeof(efi_char16_t)); i++) {
1770                 short_name[i] = variable_name[i] & 0xFF;
1771         }
1772         /* This is ugly, but necessary to separate one vendor's
1773            private variables from another's.         */
1774
1775         *(short_name + strlen(short_name)) = '-';
1776         efi_guid_unparse(vendor_guid, short_name + strlen(short_name));
1777
1778         new_efivar->kobj.kset = efivars->kset;
1779         i = kobject_init_and_add(&new_efivar->kobj, &efivar_ktype, NULL,
1780                                  "%s", short_name);
1781         if (i) {
1782                 kfree(short_name);
1783                 kfree(new_efivar);
1784                 return 1;
1785         }
1786
1787         kobject_uevent(&new_efivar->kobj, KOBJ_ADD);
1788         kfree(short_name);
1789         short_name = NULL;
1790
1791         spin_lock_irq(&efivars->lock);
1792         list_add(&new_efivar->list, &efivars->list);
1793         spin_unlock_irq(&efivars->lock);
1794
1795         return 0;
1796 }
1797
1798 static int
1799 create_efivars_bin_attributes(struct efivars *efivars)
1800 {
1801         struct bin_attribute *attr;
1802         int error;
1803
1804         /* new_var */
1805         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
1806         if (!attr)
1807                 return -ENOMEM;
1808
1809         attr->attr.name = "new_var";
1810         attr->attr.mode = 0200;
1811         attr->write = efivar_create;
1812         attr->private = efivars;
1813         efivars->new_var = attr;
1814
1815         /* del_var */
1816         attr = kzalloc(sizeof(*attr), GFP_KERNEL);
1817         if (!attr) {
1818                 error = -ENOMEM;
1819                 goto out_free;
1820         }
1821         attr->attr.name = "del_var";
1822         attr->attr.mode = 0200;
1823         attr->write = efivar_delete;
1824         attr->private = efivars;
1825         efivars->del_var = attr;
1826
1827         sysfs_bin_attr_init(efivars->new_var);
1828         sysfs_bin_attr_init(efivars->del_var);
1829
1830         /* Register */
1831         error = sysfs_create_bin_file(&efivars->kset->kobj,
1832                                       efivars->new_var);
1833         if (error) {
1834                 printk(KERN_ERR "efivars: unable to create new_var sysfs file"
1835                         " due to error %d\n", error);
1836                 goto out_free;
1837         }
1838         error = sysfs_create_bin_file(&efivars->kset->kobj,
1839                                       efivars->del_var);
1840         if (error) {
1841                 printk(KERN_ERR "efivars: unable to create del_var sysfs file"
1842                         " due to error %d\n", error);
1843                 sysfs_remove_bin_file(&efivars->kset->kobj,
1844                                       efivars->new_var);
1845                 goto out_free;
1846         }
1847
1848         return 0;
1849 out_free:
1850         kfree(efivars->del_var);
1851         efivars->del_var = NULL;
1852         kfree(efivars->new_var);
1853         efivars->new_var = NULL;
1854         return error;
1855 }
1856
1857 void unregister_efivars(struct efivars *efivars)
1858 {
1859         struct efivar_entry *entry, *n;
1860
1861         list_for_each_entry_safe(entry, n, &efivars->list, list) {
1862                 spin_lock_irq(&efivars->lock);
1863                 list_del(&entry->list);
1864                 spin_unlock_irq(&efivars->lock);
1865                 efivar_unregister(entry);
1866         }
1867         if (efivars->new_var)
1868                 sysfs_remove_bin_file(&efivars->kset->kobj, efivars->new_var);
1869         if (efivars->del_var)
1870                 sysfs_remove_bin_file(&efivars->kset->kobj, efivars->del_var);
1871         kfree(efivars->new_var);
1872         kfree(efivars->del_var);
1873         kobject_put(efivars->kobject);
1874         kset_unregister(efivars->kset);
1875 }
1876 EXPORT_SYMBOL_GPL(unregister_efivars);
1877
1878 int register_efivars(struct efivars *efivars,
1879                      const struct efivar_operations *ops,
1880                      struct kobject *parent_kobj)
1881 {
1882         efi_status_t status = EFI_NOT_FOUND;
1883         efi_guid_t vendor_guid;
1884         efi_char16_t *variable_name;
1885         unsigned long variable_name_size = 1024;
1886         int error = 0;
1887
1888         variable_name = kzalloc(variable_name_size, GFP_KERNEL);
1889         if (!variable_name) {
1890                 printk(KERN_ERR "efivars: Memory allocation failed.\n");
1891                 return -ENOMEM;
1892         }
1893
1894         spin_lock_init(&efivars->lock);
1895         INIT_LIST_HEAD(&efivars->list);
1896         efivars->ops = ops;
1897
1898         efivars->kset = kset_create_and_add("vars", NULL, parent_kobj);
1899         if (!efivars->kset) {
1900                 printk(KERN_ERR "efivars: Subsystem registration failed.\n");
1901                 error = -ENOMEM;
1902                 goto out;
1903         }
1904
1905         efivars->kobject = kobject_create_and_add("efivars", parent_kobj);
1906         if (!efivars->kobject) {
1907                 pr_err("efivars: Subsystem registration failed.\n");
1908                 error = -ENOMEM;
1909                 kset_unregister(efivars->kset);
1910                 goto out;
1911         }
1912
1913         /*
1914          * Per EFI spec, the maximum storage allocated for both
1915          * the variable name and variable data is 1024 bytes.
1916          */
1917
1918         do {
1919                 variable_name_size = 1024;
1920
1921                 status = ops->get_next_variable(&variable_name_size,
1922                                                 variable_name,
1923                                                 &vendor_guid);
1924                 switch (status) {
1925                 case EFI_SUCCESS:
1926                         efivar_create_sysfs_entry(efivars,
1927                                                   variable_name_size,
1928                                                   variable_name,
1929                                                   &vendor_guid);
1930                         break;
1931                 case EFI_NOT_FOUND:
1932                         break;
1933                 default:
1934                         printk(KERN_WARNING "efivars: get_next_variable: status=%lx\n",
1935                                 status);
1936                         status = EFI_NOT_FOUND;
1937                         break;
1938                 }
1939         } while (status != EFI_NOT_FOUND);
1940
1941         error = create_efivars_bin_attributes(efivars);
1942         if (error)
1943                 unregister_efivars(efivars);
1944
1945         efivars->efi_pstore_info = efi_pstore_info;
1946
1947         efivars->efi_pstore_info.buf = kmalloc(4096, GFP_KERNEL);
1948         if (efivars->efi_pstore_info.buf) {
1949                 efivars->efi_pstore_info.bufsize = 1024;
1950                 efivars->efi_pstore_info.data = efivars;
1951                 spin_lock_init(&efivars->efi_pstore_info.buf_lock);
1952                 pstore_register(&efivars->efi_pstore_info);
1953         }
1954
1955         register_filesystem(&efivarfs_type);
1956
1957 out:
1958         kfree(variable_name);
1959
1960         return error;
1961 }
1962 EXPORT_SYMBOL_GPL(register_efivars);
1963
1964 /*
1965  * For now we register the efi subsystem with the firmware subsystem
1966  * and the vars subsystem with the efi subsystem.  In the future, it
1967  * might make sense to split off the efi subsystem into its own
1968  * driver, but for now only efivars will register with it, so just
1969  * include it here.
1970  */
1971
1972 static int __init
1973 efivars_init(void)
1974 {
1975         int error = 0;
1976
1977         printk(KERN_INFO "EFI Variables Facility v%s %s\n", EFIVARS_VERSION,
1978                EFIVARS_DATE);
1979
1980         if (!efi_enabled(EFI_RUNTIME_SERVICES))
1981                 return 0;
1982
1983         /* For now we'll register the efi directory at /sys/firmware/efi */
1984         efi_kobj = kobject_create_and_add("efi", firmware_kobj);
1985         if (!efi_kobj) {
1986                 printk(KERN_ERR "efivars: Firmware registration failed.\n");
1987                 return -ENOMEM;
1988         }
1989
1990         ops.get_variable = efi.get_variable;
1991         ops.set_variable = efi.set_variable;
1992         ops.get_next_variable = efi.get_next_variable;
1993         ops.query_variable_info = efi.query_variable_info;
1994
1995         error = register_efivars(&__efivars, &ops, efi_kobj);
1996         if (error)
1997                 goto err_put;
1998
1999         /* Don't forget the systab entry */
2000         error = sysfs_create_group(efi_kobj, &efi_subsys_attr_group);
2001         if (error) {
2002                 printk(KERN_ERR
2003                        "efivars: Sysfs attribute export failed with error %d.\n",
2004                        error);
2005                 goto err_unregister;
2006         }
2007
2008         return 0;
2009
2010 err_unregister:
2011         unregister_efivars(&__efivars);
2012 err_put:
2013         kobject_put(efi_kobj);
2014         return error;
2015 }
2016
2017 static void __exit
2018 efivars_exit(void)
2019 {
2020         if (efi_enabled(EFI_RUNTIME_SERVICES)) {
2021                 unregister_efivars(&__efivars);
2022                 kobject_put(efi_kobj);
2023         }
2024 }
2025
2026 module_init(efivars_init);
2027 module_exit(efivars_exit);
2028