GNU Linux-libre 4.19.304-gnu1
[releases.git] / drivers / firmware / qemu_fw_cfg.c
1 /*
2  * drivers/firmware/qemu_fw_cfg.c
3  *
4  * Copyright 2015 Carnegie Mellon University
5  *
6  * Expose entries from QEMU's firmware configuration (fw_cfg) device in
7  * sysfs (read-only, under "/sys/firmware/qemu_fw_cfg/...").
8  *
9  * The fw_cfg device may be instantiated via either an ACPI node (on x86
10  * and select subsets of aarch64), a Device Tree node (on arm), or using
11  * a kernel module (or command line) parameter with the following syntax:
12  *
13  *      [qemu_fw_cfg.]ioport=<size>@<base>[:<ctrl_off>:<data_off>[:<dma_off>]]
14  * or
15  *      [qemu_fw_cfg.]mmio=<size>@<base>[:<ctrl_off>:<data_off>[:<dma_off>]]
16  *
17  * where:
18  *      <size>     := size of ioport or mmio range
19  *      <base>     := physical base address of ioport or mmio range
20  *      <ctrl_off> := (optional) offset of control register
21  *      <data_off> := (optional) offset of data register
22  *      <dma_off> := (optional) offset of dma register
23  *
24  * e.g.:
25  *      qemu_fw_cfg.ioport=12@0x510:0:1:4       (the default on x86)
26  * or
27  *      qemu_fw_cfg.mmio=16@0x9020000:8:0:16    (the default on arm)
28  */
29
30 #include <linux/module.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/platform_device.h>
33 #include <linux/acpi.h>
34 #include <linux/slab.h>
35 #include <linux/io.h>
36 #include <linux/ioport.h>
37 #include <uapi/linux/qemu_fw_cfg.h>
38 #include <linux/delay.h>
39 #include <linux/crash_dump.h>
40 #include <linux/crash_core.h>
41
42 MODULE_AUTHOR("Gabriel L. Somlo <somlo@cmu.edu>");
43 MODULE_DESCRIPTION("QEMU fw_cfg sysfs support");
44 MODULE_LICENSE("GPL");
45
46 /* fw_cfg revision attribute, in /sys/firmware/qemu_fw_cfg top-level dir. */
47 static u32 fw_cfg_rev;
48
49 /* fw_cfg device i/o register addresses */
50 static bool fw_cfg_is_mmio;
51 static phys_addr_t fw_cfg_p_base;
52 static resource_size_t fw_cfg_p_size;
53 static void __iomem *fw_cfg_dev_base;
54 static void __iomem *fw_cfg_reg_ctrl;
55 static void __iomem *fw_cfg_reg_data;
56 static void __iomem *fw_cfg_reg_dma;
57
58 /* atomic access to fw_cfg device (potentially slow i/o, so using mutex) */
59 static DEFINE_MUTEX(fw_cfg_dev_lock);
60
61 /* pick appropriate endianness for selector key */
62 static void fw_cfg_sel_endianness(u16 key)
63 {
64         if (fw_cfg_is_mmio)
65                 iowrite16be(key, fw_cfg_reg_ctrl);
66         else
67                 iowrite16(key, fw_cfg_reg_ctrl);
68 }
69
70 #ifdef CONFIG_CRASH_CORE
71 static inline bool fw_cfg_dma_enabled(void)
72 {
73         return (fw_cfg_rev & FW_CFG_VERSION_DMA) && fw_cfg_reg_dma;
74 }
75
76 /* qemu fw_cfg device is sync today, but spec says it may become async */
77 static void fw_cfg_wait_for_control(struct fw_cfg_dma_access *d)
78 {
79         for (;;) {
80                 u32 ctrl = be32_to_cpu(READ_ONCE(d->control));
81
82                 /* do not reorder the read to d->control */
83                 rmb();
84                 if ((ctrl & ~FW_CFG_DMA_CTL_ERROR) == 0)
85                         return;
86
87                 cpu_relax();
88         }
89 }
90
91 static ssize_t fw_cfg_dma_transfer(void *address, u32 length, u32 control)
92 {
93         phys_addr_t dma;
94         struct fw_cfg_dma_access *d = NULL;
95         ssize_t ret = length;
96
97         d = kmalloc(sizeof(*d), GFP_KERNEL);
98         if (!d) {
99                 ret = -ENOMEM;
100                 goto end;
101         }
102
103         /* fw_cfg device does not need IOMMU protection, so use physical addresses */
104         *d = (struct fw_cfg_dma_access) {
105                 .address = cpu_to_be64(address ? virt_to_phys(address) : 0),
106                 .length = cpu_to_be32(length),
107                 .control = cpu_to_be32(control)
108         };
109
110         dma = virt_to_phys(d);
111
112         iowrite32be((u64)dma >> 32, fw_cfg_reg_dma);
113         /* force memory to sync before notifying device via MMIO */
114         wmb();
115         iowrite32be(dma, fw_cfg_reg_dma + 4);
116
117         fw_cfg_wait_for_control(d);
118
119         if (be32_to_cpu(READ_ONCE(d->control)) & FW_CFG_DMA_CTL_ERROR) {
120                 ret = -EIO;
121         }
122
123 end:
124         kfree(d);
125
126         return ret;
127 }
128 #endif
129
130 /* read chunk of given fw_cfg blob (caller responsible for sanity-check) */
131 static ssize_t fw_cfg_read_blob(u16 key,
132                                 void *buf, loff_t pos, size_t count)
133 {
134         u32 glk = -1U;
135         acpi_status status;
136
137         /* If we have ACPI, ensure mutual exclusion against any potential
138          * device access by the firmware, e.g. via AML methods:
139          */
140         status = acpi_acquire_global_lock(ACPI_WAIT_FOREVER, &glk);
141         if (ACPI_FAILURE(status) && status != AE_NOT_CONFIGURED) {
142                 /* Should never get here */
143                 WARN(1, "fw_cfg_read_blob: Failed to lock ACPI!\n");
144                 memset(buf, 0, count);
145                 return -EINVAL;
146         }
147
148         mutex_lock(&fw_cfg_dev_lock);
149         fw_cfg_sel_endianness(key);
150         while (pos-- > 0)
151                 ioread8(fw_cfg_reg_data);
152         ioread8_rep(fw_cfg_reg_data, buf, count);
153         mutex_unlock(&fw_cfg_dev_lock);
154
155         acpi_release_global_lock(glk);
156         return count;
157 }
158
159 #ifdef CONFIG_CRASH_CORE
160 /* write chunk of given fw_cfg blob (caller responsible for sanity-check) */
161 static ssize_t fw_cfg_write_blob(u16 key,
162                                  void *buf, loff_t pos, size_t count)
163 {
164         u32 glk = -1U;
165         acpi_status status;
166         ssize_t ret = count;
167
168         /* If we have ACPI, ensure mutual exclusion against any potential
169          * device access by the firmware, e.g. via AML methods:
170          */
171         status = acpi_acquire_global_lock(ACPI_WAIT_FOREVER, &glk);
172         if (ACPI_FAILURE(status) && status != AE_NOT_CONFIGURED) {
173                 /* Should never get here */
174                 WARN(1, "%s: Failed to lock ACPI!\n", __func__);
175                 return -EINVAL;
176         }
177
178         mutex_lock(&fw_cfg_dev_lock);
179         if (pos == 0) {
180                 ret = fw_cfg_dma_transfer(buf, count, key << 16
181                                           | FW_CFG_DMA_CTL_SELECT
182                                           | FW_CFG_DMA_CTL_WRITE);
183         } else {
184                 fw_cfg_sel_endianness(key);
185                 ret = fw_cfg_dma_transfer(NULL, pos, FW_CFG_DMA_CTL_SKIP);
186                 if (ret < 0)
187                         goto end;
188                 ret = fw_cfg_dma_transfer(buf, count, FW_CFG_DMA_CTL_WRITE);
189         }
190
191 end:
192         mutex_unlock(&fw_cfg_dev_lock);
193
194         acpi_release_global_lock(glk);
195
196         return ret;
197 }
198 #endif /* CONFIG_CRASH_CORE */
199
200 /* clean up fw_cfg device i/o */
201 static void fw_cfg_io_cleanup(void)
202 {
203         if (fw_cfg_is_mmio) {
204                 iounmap(fw_cfg_dev_base);
205                 release_mem_region(fw_cfg_p_base, fw_cfg_p_size);
206         } else {
207                 ioport_unmap(fw_cfg_dev_base);
208                 release_region(fw_cfg_p_base, fw_cfg_p_size);
209         }
210 }
211
212 /* arch-specific ctrl & data register offsets are not available in ACPI, DT */
213 #if !(defined(FW_CFG_CTRL_OFF) && defined(FW_CFG_DATA_OFF))
214 # if (defined(CONFIG_ARM) || defined(CONFIG_ARM64))
215 #  define FW_CFG_CTRL_OFF 0x08
216 #  define FW_CFG_DATA_OFF 0x00
217 #  define FW_CFG_DMA_OFF 0x10
218 # elif (defined(CONFIG_PPC_PMAC) || defined(CONFIG_SPARC32)) /* ppc/mac,sun4m */
219 #  define FW_CFG_CTRL_OFF 0x00
220 #  define FW_CFG_DATA_OFF 0x02
221 # elif (defined(CONFIG_X86) || defined(CONFIG_SPARC64)) /* x86, sun4u */
222 #  define FW_CFG_CTRL_OFF 0x00
223 #  define FW_CFG_DATA_OFF 0x01
224 #  define FW_CFG_DMA_OFF 0x04
225 # else
226 #  error "QEMU FW_CFG not available on this architecture!"
227 # endif
228 #endif
229
230 /* initialize fw_cfg device i/o from platform data */
231 static int fw_cfg_do_platform_probe(struct platform_device *pdev)
232 {
233         char sig[FW_CFG_SIG_SIZE];
234         struct resource *range, *ctrl, *data, *dma;
235
236         /* acquire i/o range details */
237         fw_cfg_is_mmio = false;
238         range = platform_get_resource(pdev, IORESOURCE_IO, 0);
239         if (!range) {
240                 fw_cfg_is_mmio = true;
241                 range = platform_get_resource(pdev, IORESOURCE_MEM, 0);
242                 if (!range)
243                         return -EINVAL;
244         }
245         fw_cfg_p_base = range->start;
246         fw_cfg_p_size = resource_size(range);
247
248         if (fw_cfg_is_mmio) {
249                 if (!request_mem_region(fw_cfg_p_base,
250                                         fw_cfg_p_size, "fw_cfg_mem"))
251                         return -EBUSY;
252                 fw_cfg_dev_base = ioremap(fw_cfg_p_base, fw_cfg_p_size);
253                 if (!fw_cfg_dev_base) {
254                         release_mem_region(fw_cfg_p_base, fw_cfg_p_size);
255                         return -EFAULT;
256                 }
257         } else {
258                 if (!request_region(fw_cfg_p_base,
259                                     fw_cfg_p_size, "fw_cfg_io"))
260                         return -EBUSY;
261                 fw_cfg_dev_base = ioport_map(fw_cfg_p_base, fw_cfg_p_size);
262                 if (!fw_cfg_dev_base) {
263                         release_region(fw_cfg_p_base, fw_cfg_p_size);
264                         return -EFAULT;
265                 }
266         }
267
268         /* were custom register offsets provided (e.g. on the command line)? */
269         ctrl = platform_get_resource_byname(pdev, IORESOURCE_REG, "ctrl");
270         data = platform_get_resource_byname(pdev, IORESOURCE_REG, "data");
271         dma = platform_get_resource_byname(pdev, IORESOURCE_REG, "dma");
272         if (ctrl && data) {
273                 fw_cfg_reg_ctrl = fw_cfg_dev_base + ctrl->start;
274                 fw_cfg_reg_data = fw_cfg_dev_base + data->start;
275         } else {
276                 /* use architecture-specific offsets */
277                 fw_cfg_reg_ctrl = fw_cfg_dev_base + FW_CFG_CTRL_OFF;
278                 fw_cfg_reg_data = fw_cfg_dev_base + FW_CFG_DATA_OFF;
279         }
280
281         if (dma)
282                 fw_cfg_reg_dma = fw_cfg_dev_base + dma->start;
283 #ifdef FW_CFG_DMA_OFF
284         else
285                 fw_cfg_reg_dma = fw_cfg_dev_base + FW_CFG_DMA_OFF;
286 #endif
287
288         /* verify fw_cfg device signature */
289         if (fw_cfg_read_blob(FW_CFG_SIGNATURE, sig,
290                                 0, FW_CFG_SIG_SIZE) < 0 ||
291                 memcmp(sig, "QEMU", FW_CFG_SIG_SIZE) != 0) {
292                 fw_cfg_io_cleanup();
293                 return -ENODEV;
294         }
295
296         return 0;
297 }
298
299 static ssize_t fw_cfg_showrev(struct kobject *k, struct kobj_attribute *a,
300                               char *buf)
301 {
302         return sprintf(buf, "%u\n", fw_cfg_rev);
303 }
304
305 static const struct kobj_attribute fw_cfg_rev_attr = {
306         .attr = { .name = "rev", .mode = S_IRUSR },
307         .show = fw_cfg_showrev,
308 };
309
310 /* fw_cfg_sysfs_entry type */
311 struct fw_cfg_sysfs_entry {
312         struct kobject kobj;
313         u32 size;
314         u16 select;
315         char name[FW_CFG_MAX_FILE_PATH];
316         struct list_head list;
317 };
318
319 #ifdef CONFIG_CRASH_CORE
320 static ssize_t fw_cfg_write_vmcoreinfo(const struct fw_cfg_file *f)
321 {
322         static struct fw_cfg_vmcoreinfo *data;
323         ssize_t ret;
324
325         data = kmalloc(sizeof(struct fw_cfg_vmcoreinfo), GFP_KERNEL);
326         if (!data)
327                 return -ENOMEM;
328
329         *data = (struct fw_cfg_vmcoreinfo) {
330                 .guest_format = cpu_to_le16(FW_CFG_VMCOREINFO_FORMAT_ELF),
331                 .size = cpu_to_le32(VMCOREINFO_NOTE_SIZE),
332                 .paddr = cpu_to_le64(paddr_vmcoreinfo_note())
333         };
334         /* spare ourself reading host format support for now since we
335          * don't know what else to format - host may ignore ours
336          */
337         ret = fw_cfg_write_blob(be16_to_cpu(f->select), data,
338                                 0, sizeof(struct fw_cfg_vmcoreinfo));
339
340         kfree(data);
341         return ret;
342 }
343 #endif /* CONFIG_CRASH_CORE */
344
345 /* get fw_cfg_sysfs_entry from kobject member */
346 static inline struct fw_cfg_sysfs_entry *to_entry(struct kobject *kobj)
347 {
348         return container_of(kobj, struct fw_cfg_sysfs_entry, kobj);
349 }
350
351 /* fw_cfg_sysfs_attribute type */
352 struct fw_cfg_sysfs_attribute {
353         struct attribute attr;
354         ssize_t (*show)(struct fw_cfg_sysfs_entry *entry, char *buf);
355 };
356
357 /* get fw_cfg_sysfs_attribute from attribute member */
358 static inline struct fw_cfg_sysfs_attribute *to_attr(struct attribute *attr)
359 {
360         return container_of(attr, struct fw_cfg_sysfs_attribute, attr);
361 }
362
363 /* global cache of fw_cfg_sysfs_entry objects */
364 static LIST_HEAD(fw_cfg_entry_cache);
365
366 /* kobjects removed lazily by kernel, mutual exclusion needed */
367 static DEFINE_SPINLOCK(fw_cfg_cache_lock);
368
369 static inline void fw_cfg_sysfs_cache_enlist(struct fw_cfg_sysfs_entry *entry)
370 {
371         spin_lock(&fw_cfg_cache_lock);
372         list_add_tail(&entry->list, &fw_cfg_entry_cache);
373         spin_unlock(&fw_cfg_cache_lock);
374 }
375
376 static inline void fw_cfg_sysfs_cache_delist(struct fw_cfg_sysfs_entry *entry)
377 {
378         spin_lock(&fw_cfg_cache_lock);
379         list_del(&entry->list);
380         spin_unlock(&fw_cfg_cache_lock);
381 }
382
383 static void fw_cfg_sysfs_cache_cleanup(void)
384 {
385         struct fw_cfg_sysfs_entry *entry, *next;
386
387         list_for_each_entry_safe(entry, next, &fw_cfg_entry_cache, list) {
388                 fw_cfg_sysfs_cache_delist(entry);
389                 kobject_put(&entry->kobj);
390         }
391 }
392
393 /* default_attrs: per-entry attributes and show methods */
394
395 #define FW_CFG_SYSFS_ATTR(_attr) \
396 struct fw_cfg_sysfs_attribute fw_cfg_sysfs_attr_##_attr = { \
397         .attr = { .name = __stringify(_attr), .mode = S_IRUSR }, \
398         .show = fw_cfg_sysfs_show_##_attr, \
399 }
400
401 static ssize_t fw_cfg_sysfs_show_size(struct fw_cfg_sysfs_entry *e, char *buf)
402 {
403         return sprintf(buf, "%u\n", e->size);
404 }
405
406 static ssize_t fw_cfg_sysfs_show_key(struct fw_cfg_sysfs_entry *e, char *buf)
407 {
408         return sprintf(buf, "%u\n", e->select);
409 }
410
411 static ssize_t fw_cfg_sysfs_show_name(struct fw_cfg_sysfs_entry *e, char *buf)
412 {
413         return sprintf(buf, "%s\n", e->name);
414 }
415
416 static FW_CFG_SYSFS_ATTR(size);
417 static FW_CFG_SYSFS_ATTR(key);
418 static FW_CFG_SYSFS_ATTR(name);
419
420 static struct attribute *fw_cfg_sysfs_entry_attrs[] = {
421         &fw_cfg_sysfs_attr_size.attr,
422         &fw_cfg_sysfs_attr_key.attr,
423         &fw_cfg_sysfs_attr_name.attr,
424         NULL,
425 };
426
427 /* sysfs_ops: find fw_cfg_[entry, attribute] and call appropriate show method */
428 static ssize_t fw_cfg_sysfs_attr_show(struct kobject *kobj, struct attribute *a,
429                                       char *buf)
430 {
431         struct fw_cfg_sysfs_entry *entry = to_entry(kobj);
432         struct fw_cfg_sysfs_attribute *attr = to_attr(a);
433
434         return attr->show(entry, buf);
435 }
436
437 static const struct sysfs_ops fw_cfg_sysfs_attr_ops = {
438         .show = fw_cfg_sysfs_attr_show,
439 };
440
441 /* release: destructor, to be called via kobject_put() */
442 static void fw_cfg_sysfs_release_entry(struct kobject *kobj)
443 {
444         struct fw_cfg_sysfs_entry *entry = to_entry(kobj);
445
446         kfree(entry);
447 }
448
449 /* kobj_type: ties together all properties required to register an entry */
450 static struct kobj_type fw_cfg_sysfs_entry_ktype = {
451         .default_attrs = fw_cfg_sysfs_entry_attrs,
452         .sysfs_ops = &fw_cfg_sysfs_attr_ops,
453         .release = fw_cfg_sysfs_release_entry,
454 };
455
456 /* raw-read method and attribute */
457 static ssize_t fw_cfg_sysfs_read_raw(struct file *filp, struct kobject *kobj,
458                                      struct bin_attribute *bin_attr,
459                                      char *buf, loff_t pos, size_t count)
460 {
461         struct fw_cfg_sysfs_entry *entry = to_entry(kobj);
462
463         if (pos > entry->size)
464                 return -EINVAL;
465
466         if (count > entry->size - pos)
467                 count = entry->size - pos;
468
469         return fw_cfg_read_blob(entry->select, buf, pos, count);
470 }
471
472 static struct bin_attribute fw_cfg_sysfs_attr_raw = {
473         .attr = { .name = "raw", .mode = S_IRUSR },
474         .read = fw_cfg_sysfs_read_raw,
475 };
476
477 /*
478  * Create a kset subdirectory matching each '/' delimited dirname token
479  * in 'name', starting with sysfs kset/folder 'dir'; At the end, create
480  * a symlink directed at the given 'target'.
481  * NOTE: We do this on a best-effort basis, since 'name' is not guaranteed
482  * to be a well-behaved path name. Whenever a symlink vs. kset directory
483  * name collision occurs, the kernel will issue big scary warnings while
484  * refusing to add the offending link or directory. We follow up with our
485  * own, slightly less scary error messages explaining the situation :)
486  */
487 static int fw_cfg_build_symlink(struct kset *dir,
488                                 struct kobject *target, const char *name)
489 {
490         int ret;
491         struct kset *subdir;
492         struct kobject *ko;
493         char *name_copy, *p, *tok;
494
495         if (!dir || !target || !name || !*name)
496                 return -EINVAL;
497
498         /* clone a copy of name for parsing */
499         name_copy = p = kstrdup(name, GFP_KERNEL);
500         if (!name_copy)
501                 return -ENOMEM;
502
503         /* create folders for each dirname token, then symlink for basename */
504         while ((tok = strsep(&p, "/")) && *tok) {
505
506                 /* last (basename) token? If so, add symlink here */
507                 if (!p || !*p) {
508                         ret = sysfs_create_link(&dir->kobj, target, tok);
509                         break;
510                 }
511
512                 /* does the current dir contain an item named after tok ? */
513                 ko = kset_find_obj(dir, tok);
514                 if (ko) {
515                         /* drop reference added by kset_find_obj */
516                         kobject_put(ko);
517
518                         /* ko MUST be a kset - we're about to use it as one ! */
519                         if (ko->ktype != dir->kobj.ktype) {
520                                 ret = -EINVAL;
521                                 break;
522                         }
523
524                         /* descend into already existing subdirectory */
525                         dir = to_kset(ko);
526                 } else {
527                         /* create new subdirectory kset */
528                         subdir = kzalloc(sizeof(struct kset), GFP_KERNEL);
529                         if (!subdir) {
530                                 ret = -ENOMEM;
531                                 break;
532                         }
533                         subdir->kobj.kset = dir;
534                         subdir->kobj.ktype = dir->kobj.ktype;
535                         ret = kobject_set_name(&subdir->kobj, "%s", tok);
536                         if (ret) {
537                                 kfree(subdir);
538                                 break;
539                         }
540                         ret = kset_register(subdir);
541                         if (ret) {
542                                 kfree(subdir);
543                                 break;
544                         }
545
546                         /* descend into newly created subdirectory */
547                         dir = subdir;
548                 }
549         }
550
551         /* we're done with cloned copy of name */
552         kfree(name_copy);
553         return ret;
554 }
555
556 /* recursively unregister fw_cfg/by_name/ kset directory tree */
557 static void fw_cfg_kset_unregister_recursive(struct kset *kset)
558 {
559         struct kobject *k, *next;
560
561         list_for_each_entry_safe(k, next, &kset->list, entry)
562                 /* all set members are ksets too, but check just in case... */
563                 if (k->ktype == kset->kobj.ktype)
564                         fw_cfg_kset_unregister_recursive(to_kset(k));
565
566         /* symlinks are cleanly and automatically removed with the directory */
567         kset_unregister(kset);
568 }
569
570 /* kobjects & kset representing top-level, by_key, and by_name folders */
571 static struct kobject *fw_cfg_top_ko;
572 static struct kobject *fw_cfg_sel_ko;
573 static struct kset *fw_cfg_fname_kset;
574
575 /* register an individual fw_cfg file */
576 static int fw_cfg_register_file(const struct fw_cfg_file *f)
577 {
578         int err;
579         struct fw_cfg_sysfs_entry *entry;
580
581 #ifdef CONFIG_CRASH_CORE
582         if (fw_cfg_dma_enabled() &&
583                 strcmp(f->name, FW_CFG_VMCOREINFO_FILENAME) == 0 &&
584                 !is_kdump_kernel()) {
585                 if (fw_cfg_write_vmcoreinfo(f) < 0)
586                         pr_warn("fw_cfg: failed to write vmcoreinfo");
587         }
588 #endif
589
590         /* allocate new entry */
591         entry = kzalloc(sizeof(*entry), GFP_KERNEL);
592         if (!entry)
593                 return -ENOMEM;
594
595         /* set file entry information */
596         entry->size = be32_to_cpu(f->size);
597         entry->select = be16_to_cpu(f->select);
598         strscpy(entry->name, f->name, FW_CFG_MAX_FILE_PATH);
599
600         /* register entry under "/sys/firmware/qemu_fw_cfg/by_key/" */
601         err = kobject_init_and_add(&entry->kobj, &fw_cfg_sysfs_entry_ktype,
602                                    fw_cfg_sel_ko, "%d", entry->select);
603         if (err)
604                 goto err_put_entry;
605
606         /* add raw binary content access */
607         err = sysfs_create_bin_file(&entry->kobj, &fw_cfg_sysfs_attr_raw);
608         if (err)
609                 goto err_del_entry;
610
611         /* try adding "/sys/firmware/qemu_fw_cfg/by_name/" symlink */
612         fw_cfg_build_symlink(fw_cfg_fname_kset, &entry->kobj, entry->name);
613
614         /* success, add entry to global cache */
615         fw_cfg_sysfs_cache_enlist(entry);
616         return 0;
617
618 err_del_entry:
619         kobject_del(&entry->kobj);
620 err_put_entry:
621         kobject_put(&entry->kobj);
622         return err;
623 }
624
625 /* iterate over all fw_cfg directory entries, registering each one */
626 static int fw_cfg_register_dir_entries(void)
627 {
628         int ret = 0;
629         __be32 files_count;
630         u32 count, i;
631         struct fw_cfg_file *dir;
632         size_t dir_size;
633
634         ret = fw_cfg_read_blob(FW_CFG_FILE_DIR, &files_count,
635                         0, sizeof(files_count));
636         if (ret < 0)
637                 return ret;
638
639         count = be32_to_cpu(files_count);
640         dir_size = count * sizeof(struct fw_cfg_file);
641
642         dir = kmalloc(dir_size, GFP_KERNEL);
643         if (!dir)
644                 return -ENOMEM;
645
646         ret = fw_cfg_read_blob(FW_CFG_FILE_DIR, dir,
647                         sizeof(files_count), dir_size);
648         if (ret < 0)
649                 goto end;
650
651         for (i = 0; i < count; i++) {
652                 ret = fw_cfg_register_file(&dir[i]);
653                 if (ret)
654                         break;
655         }
656
657 end:
658         kfree(dir);
659         return ret;
660 }
661
662 /* unregister top-level or by_key folder */
663 static inline void fw_cfg_kobj_cleanup(struct kobject *kobj)
664 {
665         kobject_del(kobj);
666         kobject_put(kobj);
667 }
668
669 static int fw_cfg_sysfs_probe(struct platform_device *pdev)
670 {
671         int err;
672         __le32 rev;
673
674         /* NOTE: If we supported multiple fw_cfg devices, we'd first create
675          * a subdirectory named after e.g. pdev->id, then hang per-device
676          * by_key (and by_name) subdirectories underneath it. However, only
677          * one fw_cfg device exist system-wide, so if one was already found
678          * earlier, we might as well stop here.
679          */
680         if (fw_cfg_sel_ko)
681                 return -EBUSY;
682
683         /* create by_key and by_name subdirs of /sys/firmware/qemu_fw_cfg/ */
684         err = -ENOMEM;
685         fw_cfg_sel_ko = kobject_create_and_add("by_key", fw_cfg_top_ko);
686         if (!fw_cfg_sel_ko)
687                 goto err_sel;
688         fw_cfg_fname_kset = kset_create_and_add("by_name", NULL, fw_cfg_top_ko);
689         if (!fw_cfg_fname_kset)
690                 goto err_name;
691
692         /* initialize fw_cfg device i/o from platform data */
693         err = fw_cfg_do_platform_probe(pdev);
694         if (err)
695                 goto err_probe;
696
697         /* get revision number, add matching top-level attribute */
698         err = fw_cfg_read_blob(FW_CFG_ID, &rev, 0, sizeof(rev));
699         if (err < 0)
700                 goto err_probe;
701
702         fw_cfg_rev = le32_to_cpu(rev);
703         err = sysfs_create_file(fw_cfg_top_ko, &fw_cfg_rev_attr.attr);
704         if (err)
705                 goto err_rev;
706
707         /* process fw_cfg file directory entry, registering each file */
708         err = fw_cfg_register_dir_entries();
709         if (err)
710                 goto err_dir;
711
712         /* success */
713         pr_debug("fw_cfg: loaded.\n");
714         return 0;
715
716 err_dir:
717         fw_cfg_sysfs_cache_cleanup();
718         sysfs_remove_file(fw_cfg_top_ko, &fw_cfg_rev_attr.attr);
719 err_rev:
720         fw_cfg_io_cleanup();
721 err_probe:
722         fw_cfg_kset_unregister_recursive(fw_cfg_fname_kset);
723 err_name:
724         fw_cfg_kobj_cleanup(fw_cfg_sel_ko);
725 err_sel:
726         return err;
727 }
728
729 static int fw_cfg_sysfs_remove(struct platform_device *pdev)
730 {
731         pr_debug("fw_cfg: unloading.\n");
732         fw_cfg_sysfs_cache_cleanup();
733         sysfs_remove_file(fw_cfg_top_ko, &fw_cfg_rev_attr.attr);
734         fw_cfg_io_cleanup();
735         fw_cfg_kset_unregister_recursive(fw_cfg_fname_kset);
736         fw_cfg_kobj_cleanup(fw_cfg_sel_ko);
737         return 0;
738 }
739
740 static const struct of_device_id fw_cfg_sysfs_mmio_match[] = {
741         { .compatible = "qemu,fw-cfg-mmio", },
742         {},
743 };
744 MODULE_DEVICE_TABLE(of, fw_cfg_sysfs_mmio_match);
745
746 #ifdef CONFIG_ACPI
747 static const struct acpi_device_id fw_cfg_sysfs_acpi_match[] = {
748         { FW_CFG_ACPI_DEVICE_ID, },
749         {},
750 };
751 MODULE_DEVICE_TABLE(acpi, fw_cfg_sysfs_acpi_match);
752 #endif
753
754 static struct platform_driver fw_cfg_sysfs_driver = {
755         .probe = fw_cfg_sysfs_probe,
756         .remove = fw_cfg_sysfs_remove,
757         .driver = {
758                 .name = "fw_cfg",
759                 .of_match_table = fw_cfg_sysfs_mmio_match,
760                 .acpi_match_table = ACPI_PTR(fw_cfg_sysfs_acpi_match),
761         },
762 };
763
764 #ifdef CONFIG_FW_CFG_SYSFS_CMDLINE
765
766 static struct platform_device *fw_cfg_cmdline_dev;
767
768 /* this probably belongs in e.g. include/linux/types.h,
769  * but right now we are the only ones doing it...
770  */
771 #ifdef CONFIG_PHYS_ADDR_T_64BIT
772 #define __PHYS_ADDR_PREFIX "ll"
773 #else
774 #define __PHYS_ADDR_PREFIX ""
775 #endif
776
777 /* use special scanf/printf modifier for phys_addr_t, resource_size_t */
778 #define PH_ADDR_SCAN_FMT "@%" __PHYS_ADDR_PREFIX "i%n" \
779                          ":%" __PHYS_ADDR_PREFIX "i" \
780                          ":%" __PHYS_ADDR_PREFIX "i%n" \
781                          ":%" __PHYS_ADDR_PREFIX "i%n"
782
783 #define PH_ADDR_PR_1_FMT "0x%" __PHYS_ADDR_PREFIX "x@" \
784                          "0x%" __PHYS_ADDR_PREFIX "x"
785
786 #define PH_ADDR_PR_3_FMT PH_ADDR_PR_1_FMT \
787                          ":%" __PHYS_ADDR_PREFIX "u" \
788                          ":%" __PHYS_ADDR_PREFIX "u"
789
790 #define PH_ADDR_PR_4_FMT PH_ADDR_PR_3_FMT \
791                          ":%" __PHYS_ADDR_PREFIX "u"
792
793 static int fw_cfg_cmdline_set(const char *arg, const struct kernel_param *kp)
794 {
795         struct resource res[4] = {};
796         char *str;
797         phys_addr_t base;
798         resource_size_t size, ctrl_off, data_off, dma_off;
799         int processed, consumed = 0;
800
801         /* only one fw_cfg device can exist system-wide, so if one
802          * was processed on the command line already, we might as
803          * well stop here.
804          */
805         if (fw_cfg_cmdline_dev) {
806                 /* avoid leaking previously registered device */
807                 platform_device_unregister(fw_cfg_cmdline_dev);
808                 return -EINVAL;
809         }
810
811         /* consume "<size>" portion of command line argument */
812         size = memparse(arg, &str);
813
814         /* get "@<base>[:<ctrl_off>:<data_off>[:<dma_off>]]" chunks */
815         processed = sscanf(str, PH_ADDR_SCAN_FMT,
816                            &base, &consumed,
817                            &ctrl_off, &data_off, &consumed,
818                            &dma_off, &consumed);
819
820         /* sscanf() must process precisely 1, 3 or 4 chunks:
821          * <base> is mandatory, optionally followed by <ctrl_off>
822          * and <data_off>, and <dma_off>;
823          * there must be no extra characters after the last chunk,
824          * so str[consumed] must be '\0'.
825          */
826         if (str[consumed] ||
827             (processed != 1 && processed != 3 && processed != 4))
828                 return -EINVAL;
829
830         res[0].start = base;
831         res[0].end = base + size - 1;
832         res[0].flags = !strcmp(kp->name, "mmio") ? IORESOURCE_MEM :
833                                                    IORESOURCE_IO;
834
835         /* insert register offsets, if provided */
836         if (processed > 1) {
837                 res[1].name = "ctrl";
838                 res[1].start = ctrl_off;
839                 res[1].flags = IORESOURCE_REG;
840                 res[2].name = "data";
841                 res[2].start = data_off;
842                 res[2].flags = IORESOURCE_REG;
843         }
844         if (processed > 3) {
845                 res[3].name = "dma";
846                 res[3].start = dma_off;
847                 res[3].flags = IORESOURCE_REG;
848         }
849
850         /* "processed" happens to nicely match the number of resources
851          * we need to pass in to this platform device.
852          */
853         fw_cfg_cmdline_dev = platform_device_register_simple("fw_cfg",
854                                         PLATFORM_DEVID_NONE, res, processed);
855
856         return PTR_ERR_OR_ZERO(fw_cfg_cmdline_dev);
857 }
858
859 static int fw_cfg_cmdline_get(char *buf, const struct kernel_param *kp)
860 {
861         /* stay silent if device was not configured via the command
862          * line, or if the parameter name (ioport/mmio) doesn't match
863          * the device setting
864          */
865         if (!fw_cfg_cmdline_dev ||
866             (!strcmp(kp->name, "mmio") ^
867              (fw_cfg_cmdline_dev->resource[0].flags == IORESOURCE_MEM)))
868                 return 0;
869
870         switch (fw_cfg_cmdline_dev->num_resources) {
871         case 1:
872                 return snprintf(buf, PAGE_SIZE, PH_ADDR_PR_1_FMT,
873                                 resource_size(&fw_cfg_cmdline_dev->resource[0]),
874                                 fw_cfg_cmdline_dev->resource[0].start);
875         case 3:
876                 return snprintf(buf, PAGE_SIZE, PH_ADDR_PR_3_FMT,
877                                 resource_size(&fw_cfg_cmdline_dev->resource[0]),
878                                 fw_cfg_cmdline_dev->resource[0].start,
879                                 fw_cfg_cmdline_dev->resource[1].start,
880                                 fw_cfg_cmdline_dev->resource[2].start);
881         case 4:
882                 return snprintf(buf, PAGE_SIZE, PH_ADDR_PR_4_FMT,
883                                 resource_size(&fw_cfg_cmdline_dev->resource[0]),
884                                 fw_cfg_cmdline_dev->resource[0].start,
885                                 fw_cfg_cmdline_dev->resource[1].start,
886                                 fw_cfg_cmdline_dev->resource[2].start,
887                                 fw_cfg_cmdline_dev->resource[3].start);
888         }
889
890         /* Should never get here */
891         WARN(1, "Unexpected number of resources: %d\n",
892                 fw_cfg_cmdline_dev->num_resources);
893         return 0;
894 }
895
896 static const struct kernel_param_ops fw_cfg_cmdline_param_ops = {
897         .set = fw_cfg_cmdline_set,
898         .get = fw_cfg_cmdline_get,
899 };
900
901 device_param_cb(ioport, &fw_cfg_cmdline_param_ops, NULL, S_IRUSR);
902 device_param_cb(mmio, &fw_cfg_cmdline_param_ops, NULL, S_IRUSR);
903
904 #endif /* CONFIG_FW_CFG_SYSFS_CMDLINE */
905
906 static int __init fw_cfg_sysfs_init(void)
907 {
908         int ret;
909
910         /* create /sys/firmware/qemu_fw_cfg/ top level directory */
911         fw_cfg_top_ko = kobject_create_and_add("qemu_fw_cfg", firmware_kobj);
912         if (!fw_cfg_top_ko)
913                 return -ENOMEM;
914
915         ret = platform_driver_register(&fw_cfg_sysfs_driver);
916         if (ret)
917                 fw_cfg_kobj_cleanup(fw_cfg_top_ko);
918
919         return ret;
920 }
921
922 static void __exit fw_cfg_sysfs_exit(void)
923 {
924         platform_driver_unregister(&fw_cfg_sysfs_driver);
925
926 #ifdef CONFIG_FW_CFG_SYSFS_CMDLINE
927         platform_device_unregister(fw_cfg_cmdline_dev);
928 #endif
929
930         /* clean up /sys/firmware/qemu_fw_cfg/ */
931         fw_cfg_kobj_cleanup(fw_cfg_top_ko);
932 }
933
934 module_init(fw_cfg_sysfs_init);
935 module_exit(fw_cfg_sysfs_exit);