GNU Linux-libre 4.19.207-gnu1
[releases.git] / drivers / base / firmware_loader / fallback.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include <linux/types.h>
4 #include <linux/kconfig.h>
5 #include <linux/list.h>
6 #include <linux/slab.h>
7 #include <linux/security.h>
8 #include <linux/highmem.h>
9 #include <linux/umh.h>
10 #include <linux/sysctl.h>
11 #include <linux/vmalloc.h>
12
13 #include "fallback.h"
14 #include "firmware.h"
15
16 /*
17  * firmware fallback mechanism
18  */
19
20 extern struct firmware_fallback_config fw_fallback_config;
21
22 /* These getters are vetted to use int properly */
23 static inline int __firmware_loading_timeout(void)
24 {
25         return fw_fallback_config.loading_timeout;
26 }
27
28 /* These setters are vetted to use int properly */
29 static void __fw_fallback_set_timeout(int timeout)
30 {
31         fw_fallback_config.loading_timeout = timeout;
32 }
33
34 /*
35  * use small loading timeout for caching devices' firmware because all these
36  * firmware images have been loaded successfully at lease once, also system is
37  * ready for completing firmware loading now. The maximum size of firmware in
38  * current distributions is about 2M bytes, so 10 secs should be enough.
39  */
40 void fw_fallback_set_cache_timeout(void)
41 {
42         fw_fallback_config.old_timeout = __firmware_loading_timeout();
43         __fw_fallback_set_timeout(10);
44 }
45
46 /* Restores the timeout to the value last configured during normal operation */
47 void fw_fallback_set_default_timeout(void)
48 {
49         __fw_fallback_set_timeout(fw_fallback_config.old_timeout);
50 }
51
52 static long firmware_loading_timeout(void)
53 {
54         return __firmware_loading_timeout() > 0 ?
55                 __firmware_loading_timeout() * HZ : MAX_JIFFY_OFFSET;
56 }
57
58 static inline bool fw_sysfs_done(struct fw_priv *fw_priv)
59 {
60         return __fw_state_check(fw_priv, FW_STATUS_DONE);
61 }
62
63 static inline bool fw_sysfs_loading(struct fw_priv *fw_priv)
64 {
65         return __fw_state_check(fw_priv, FW_STATUS_LOADING);
66 }
67
68 static inline int fw_sysfs_wait_timeout(struct fw_priv *fw_priv,  long timeout)
69 {
70         return __fw_state_wait_common(fw_priv, timeout);
71 }
72
73 struct fw_sysfs {
74         bool nowait;
75         struct device dev;
76         struct fw_priv *fw_priv;
77         struct firmware *fw;
78 };
79
80 static struct fw_sysfs *to_fw_sysfs(struct device *dev)
81 {
82         return container_of(dev, struct fw_sysfs, dev);
83 }
84
85 static void __fw_load_abort(struct fw_priv *fw_priv)
86 {
87         /*
88          * There is a small window in which user can write to 'loading'
89          * between loading done/aborted and disappearance of 'loading'
90          */
91         if (fw_state_is_aborted(fw_priv) || fw_sysfs_done(fw_priv))
92                 return;
93
94         fw_state_aborted(fw_priv);
95 }
96
97 static void fw_load_abort(struct fw_sysfs *fw_sysfs)
98 {
99         struct fw_priv *fw_priv = fw_sysfs->fw_priv;
100
101         __fw_load_abort(fw_priv);
102 }
103
104 static LIST_HEAD(pending_fw_head);
105
106 void kill_pending_fw_fallback_reqs(bool only_kill_custom)
107 {
108         struct fw_priv *fw_priv;
109         struct fw_priv *next;
110
111         mutex_lock(&fw_lock);
112         list_for_each_entry_safe(fw_priv, next, &pending_fw_head,
113                                  pending_list) {
114                 if (!fw_priv->need_uevent || !only_kill_custom)
115                          __fw_load_abort(fw_priv);
116         }
117         mutex_unlock(&fw_lock);
118 }
119
120 static ssize_t timeout_show(struct class *class, struct class_attribute *attr,
121                             char *buf)
122 {
123         return sprintf(buf, "%d\n", __firmware_loading_timeout());
124 }
125
126 /**
127  * firmware_timeout_store() - set number of seconds to wait for firmware
128  * @class: device class pointer
129  * @attr: device attribute pointer
130  * @buf: buffer to scan for timeout value
131  * @count: number of bytes in @buf
132  *
133  *      Sets the number of seconds to wait for the firmware.  Once
134  *      this expires an error will be returned to the driver and no
135  *      firmware will be provided.
136  *
137  *      Note: zero means 'wait forever'.
138  **/
139 static ssize_t timeout_store(struct class *class, struct class_attribute *attr,
140                              const char *buf, size_t count)
141 {
142         int tmp_loading_timeout = simple_strtol(buf, NULL, 10);
143
144         if (tmp_loading_timeout < 0)
145                 tmp_loading_timeout = 0;
146
147         __fw_fallback_set_timeout(tmp_loading_timeout);
148
149         return count;
150 }
151 static CLASS_ATTR_RW(timeout);
152
153 static struct attribute *firmware_class_attrs[] = {
154         &class_attr_timeout.attr,
155         NULL,
156 };
157 ATTRIBUTE_GROUPS(firmware_class);
158
159 static void fw_dev_release(struct device *dev)
160 {
161         struct fw_sysfs *fw_sysfs = to_fw_sysfs(dev);
162
163         kfree(fw_sysfs);
164 }
165
166 static int do_firmware_uevent(struct fw_sysfs *fw_sysfs, struct kobj_uevent_env *env)
167 {
168         if (add_uevent_var(env, "FIRMWARE=%s", fw_sysfs->fw_priv->fw_name))
169                 return -ENOMEM;
170         if (add_uevent_var(env, "TIMEOUT=%i", __firmware_loading_timeout()))
171                 return -ENOMEM;
172         if (add_uevent_var(env, "ASYNC=%d", fw_sysfs->nowait))
173                 return -ENOMEM;
174
175         return 0;
176 }
177
178 static int firmware_uevent(struct device *dev, struct kobj_uevent_env *env)
179 {
180         struct fw_sysfs *fw_sysfs = to_fw_sysfs(dev);
181         int err = 0;
182
183         mutex_lock(&fw_lock);
184         if (fw_sysfs->fw_priv)
185                 err = do_firmware_uevent(fw_sysfs, env);
186         mutex_unlock(&fw_lock);
187         return err;
188 }
189
190 static struct class firmware_class = {
191         .name           = "firmware",
192         .class_groups   = firmware_class_groups,
193         .dev_uevent     = firmware_uevent,
194         .dev_release    = fw_dev_release,
195 };
196
197 int register_sysfs_loader(void)
198 {
199         return class_register(&firmware_class);
200 }
201
202 void unregister_sysfs_loader(void)
203 {
204         class_unregister(&firmware_class);
205 }
206
207 static ssize_t firmware_loading_show(struct device *dev,
208                                      struct device_attribute *attr, char *buf)
209 {
210         struct fw_sysfs *fw_sysfs = to_fw_sysfs(dev);
211         int loading = 0;
212
213         mutex_lock(&fw_lock);
214         if (fw_sysfs->fw_priv)
215                 loading = fw_sysfs_loading(fw_sysfs->fw_priv);
216         mutex_unlock(&fw_lock);
217
218         return sprintf(buf, "%d\n", loading);
219 }
220
221 /* one pages buffer should be mapped/unmapped only once */
222 static int map_fw_priv_pages(struct fw_priv *fw_priv)
223 {
224         if (!fw_priv->is_paged_buf)
225                 return 0;
226
227         vunmap(fw_priv->data);
228         fw_priv->data = vmap(fw_priv->pages, fw_priv->nr_pages, 0,
229                              PAGE_KERNEL_RO);
230         if (!fw_priv->data)
231                 return -ENOMEM;
232         return 0;
233 }
234
235 /**
236  * firmware_loading_store() - set value in the 'loading' control file
237  * @dev: device pointer
238  * @attr: device attribute pointer
239  * @buf: buffer to scan for loading control value
240  * @count: number of bytes in @buf
241  *
242  *      The relevant values are:
243  *
244  *       1: Start a load, discarding any previous partial load.
245  *       0: Conclude the load and hand the data to the driver code.
246  *      -1: Conclude the load with an error and discard any written data.
247  **/
248 static ssize_t firmware_loading_store(struct device *dev,
249                                       struct device_attribute *attr,
250                                       const char *buf, size_t count)
251 {
252         struct fw_sysfs *fw_sysfs = to_fw_sysfs(dev);
253         struct fw_priv *fw_priv;
254         ssize_t written = count;
255         int loading = simple_strtol(buf, NULL, 10);
256         int i;
257
258         mutex_lock(&fw_lock);
259         fw_priv = fw_sysfs->fw_priv;
260         if (fw_state_is_aborted(fw_priv))
261                 goto out;
262
263         switch (loading) {
264         case 1:
265                 /* discarding any previous partial load */
266                 if (!fw_sysfs_done(fw_priv)) {
267                         for (i = 0; i < fw_priv->nr_pages; i++)
268                                 __free_page(fw_priv->pages[i]);
269                         vfree(fw_priv->pages);
270                         fw_priv->pages = NULL;
271                         fw_priv->page_array_size = 0;
272                         fw_priv->nr_pages = 0;
273                         fw_state_start(fw_priv);
274                 }
275                 break;
276         case 0:
277                 if (fw_sysfs_loading(fw_priv)) {
278                         int rc;
279
280                         /*
281                          * Several loading requests may be pending on
282                          * one same firmware buf, so let all requests
283                          * see the mapped 'buf->data' once the loading
284                          * is completed.
285                          * */
286                         rc = map_fw_priv_pages(fw_priv);
287                         if (rc)
288                                 dev_err(dev, "%s: map pages failed\n",
289                                         __func__);
290                         else
291                                 rc = security_kernel_post_read_file(NULL,
292                                                 fw_priv->data, fw_priv->size,
293                                                 READING_FIRMWARE);
294
295                         /*
296                          * Same logic as fw_load_abort, only the DONE bit
297                          * is ignored and we set ABORT only on failure.
298                          */
299                         if (rc) {
300                                 fw_state_aborted(fw_priv);
301                                 written = rc;
302                         } else {
303                                 fw_state_done(fw_priv);
304                         }
305                         break;
306                 }
307                 /* fallthrough */
308         default:
309                 dev_err(dev, "%s: unexpected value (%d)\n", __func__, loading);
310                 /* fallthrough */
311         case -1:
312                 fw_load_abort(fw_sysfs);
313                 break;
314         }
315 out:
316         mutex_unlock(&fw_lock);
317         return written;
318 }
319
320 static DEVICE_ATTR(loading, 0644, firmware_loading_show, firmware_loading_store);
321
322 static void firmware_rw_data(struct fw_priv *fw_priv, char *buffer,
323                            loff_t offset, size_t count, bool read)
324 {
325         if (read)
326                 memcpy(buffer, fw_priv->data + offset, count);
327         else
328                 memcpy(fw_priv->data + offset, buffer, count);
329 }
330
331 static void firmware_rw(struct fw_priv *fw_priv, char *buffer,
332                         loff_t offset, size_t count, bool read)
333 {
334         while (count) {
335                 void *page_data;
336                 int page_nr = offset >> PAGE_SHIFT;
337                 int page_ofs = offset & (PAGE_SIZE-1);
338                 int page_cnt = min_t(size_t, PAGE_SIZE - page_ofs, count);
339
340                 page_data = kmap(fw_priv->pages[page_nr]);
341
342                 if (read)
343                         memcpy(buffer, page_data + page_ofs, page_cnt);
344                 else
345                         memcpy(page_data + page_ofs, buffer, page_cnt);
346
347                 kunmap(fw_priv->pages[page_nr]);
348                 buffer += page_cnt;
349                 offset += page_cnt;
350                 count -= page_cnt;
351         }
352 }
353
354 static ssize_t firmware_data_read(struct file *filp, struct kobject *kobj,
355                                   struct bin_attribute *bin_attr,
356                                   char *buffer, loff_t offset, size_t count)
357 {
358         struct device *dev = kobj_to_dev(kobj);
359         struct fw_sysfs *fw_sysfs = to_fw_sysfs(dev);
360         struct fw_priv *fw_priv;
361         ssize_t ret_count;
362
363         mutex_lock(&fw_lock);
364         fw_priv = fw_sysfs->fw_priv;
365         if (!fw_priv || fw_sysfs_done(fw_priv)) {
366                 ret_count = -ENODEV;
367                 goto out;
368         }
369         if (offset > fw_priv->size) {
370                 ret_count = 0;
371                 goto out;
372         }
373         if (count > fw_priv->size - offset)
374                 count = fw_priv->size - offset;
375
376         ret_count = count;
377
378         if (fw_priv->data)
379                 firmware_rw_data(fw_priv, buffer, offset, count, true);
380         else
381                 firmware_rw(fw_priv, buffer, offset, count, true);
382
383 out:
384         mutex_unlock(&fw_lock);
385         return ret_count;
386 }
387
388 static int fw_realloc_pages(struct fw_sysfs *fw_sysfs, int min_size)
389 {
390         struct fw_priv *fw_priv= fw_sysfs->fw_priv;
391         int pages_needed = PAGE_ALIGN(min_size) >> PAGE_SHIFT;
392
393         /* If the array of pages is too small, grow it... */
394         if (fw_priv->page_array_size < pages_needed) {
395                 int new_array_size = max(pages_needed,
396                                          fw_priv->page_array_size * 2);
397                 struct page **new_pages;
398
399                 new_pages = vmalloc(array_size(new_array_size, sizeof(void *)));
400                 if (!new_pages) {
401                         fw_load_abort(fw_sysfs);
402                         return -ENOMEM;
403                 }
404                 memcpy(new_pages, fw_priv->pages,
405                        fw_priv->page_array_size * sizeof(void *));
406                 memset(&new_pages[fw_priv->page_array_size], 0, sizeof(void *) *
407                        (new_array_size - fw_priv->page_array_size));
408                 vfree(fw_priv->pages);
409                 fw_priv->pages = new_pages;
410                 fw_priv->page_array_size = new_array_size;
411         }
412
413         while (fw_priv->nr_pages < pages_needed) {
414                 fw_priv->pages[fw_priv->nr_pages] =
415                         alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
416
417                 if (!fw_priv->pages[fw_priv->nr_pages]) {
418                         fw_load_abort(fw_sysfs);
419                         return -ENOMEM;
420                 }
421                 fw_priv->nr_pages++;
422         }
423         return 0;
424 }
425
426 /**
427  * firmware_data_write() - write method for firmware
428  * @filp: open sysfs file
429  * @kobj: kobject for the device
430  * @bin_attr: bin_attr structure
431  * @buffer: buffer being written
432  * @offset: buffer offset for write in total data store area
433  * @count: buffer size
434  *
435  *      Data written to the 'data' attribute will be later handed to
436  *      the driver as a firmware image.
437  **/
438 static ssize_t firmware_data_write(struct file *filp, struct kobject *kobj,
439                                    struct bin_attribute *bin_attr,
440                                    char *buffer, loff_t offset, size_t count)
441 {
442         struct device *dev = kobj_to_dev(kobj);
443         struct fw_sysfs *fw_sysfs = to_fw_sysfs(dev);
444         struct fw_priv *fw_priv;
445         ssize_t retval;
446
447         if (!capable(CAP_SYS_RAWIO))
448                 return -EPERM;
449
450         mutex_lock(&fw_lock);
451         fw_priv = fw_sysfs->fw_priv;
452         if (!fw_priv || fw_sysfs_done(fw_priv)) {
453                 retval = -ENODEV;
454                 goto out;
455         }
456
457         if (fw_priv->data) {
458                 if (offset + count > fw_priv->allocated_size) {
459                         retval = -ENOMEM;
460                         goto out;
461                 }
462                 firmware_rw_data(fw_priv, buffer, offset, count, false);
463                 retval = count;
464         } else {
465                 retval = fw_realloc_pages(fw_sysfs, offset + count);
466                 if (retval)
467                         goto out;
468
469                 retval = count;
470                 firmware_rw(fw_priv, buffer, offset, count, false);
471         }
472
473         fw_priv->size = max_t(size_t, offset + count, fw_priv->size);
474 out:
475         mutex_unlock(&fw_lock);
476         return retval;
477 }
478
479 static struct bin_attribute firmware_attr_data = {
480         .attr = { .name = "data", .mode = 0644 },
481         .size = 0,
482         .read = firmware_data_read,
483         .write = firmware_data_write,
484 };
485
486 static struct attribute *fw_dev_attrs[] = {
487         &dev_attr_loading.attr,
488         NULL
489 };
490
491 static struct bin_attribute *fw_dev_bin_attrs[] = {
492         &firmware_attr_data,
493         NULL
494 };
495
496 static const struct attribute_group fw_dev_attr_group = {
497         .attrs = fw_dev_attrs,
498         .bin_attrs = fw_dev_bin_attrs,
499 };
500
501 static const struct attribute_group *fw_dev_attr_groups[] = {
502         &fw_dev_attr_group,
503         NULL
504 };
505
506 static struct fw_sysfs *
507 fw_create_instance(struct firmware *firmware, const char *fw_name,
508                    struct device *device, enum fw_opt opt_flags)
509 {
510         struct fw_sysfs *fw_sysfs;
511         struct device *f_dev;
512
513         fw_sysfs = kzalloc(sizeof(*fw_sysfs), GFP_KERNEL);
514         if (!fw_sysfs) {
515                 fw_sysfs = ERR_PTR(-ENOMEM);
516                 goto exit;
517         }
518
519         fw_sysfs->nowait = !!(opt_flags & FW_OPT_NOWAIT);
520         fw_sysfs->fw = firmware;
521         f_dev = &fw_sysfs->dev;
522
523         device_initialize(f_dev);
524         dev_set_name(f_dev, "%s", fw_name);
525         f_dev->parent = device;
526         f_dev->class = &firmware_class;
527         f_dev->groups = fw_dev_attr_groups;
528 exit:
529         return fw_sysfs;
530 }
531
532 /**
533  * fw_load_sysfs_fallback() - load a firmware via the sysfs fallback mechanism
534  * @fw_sysfs: firmware sysfs information for the firmware to load
535  * @opt_flags: flags of options, FW_OPT_*
536  * @timeout: timeout to wait for the load
537  *
538  * In charge of constructing a sysfs fallback interface for firmware loading.
539  **/
540 static int fw_load_sysfs_fallback(struct fw_sysfs *fw_sysfs,
541                                   enum fw_opt opt_flags, long timeout)
542 {
543         int retval = 0;
544         struct device *f_dev = &fw_sysfs->dev;
545         struct fw_priv *fw_priv = fw_sysfs->fw_priv;
546
547         /* fall back on userspace loading */
548         if (!fw_priv->data)
549                 fw_priv->is_paged_buf = true;
550
551         dev_set_uevent_suppress(f_dev, true);
552
553         retval = device_add(f_dev);
554         if (retval) {
555                 dev_err(f_dev, "%s: device_register failed\n", __func__);
556                 goto err_put_dev;
557         }
558
559         mutex_lock(&fw_lock);
560         if (fw_state_is_aborted(fw_priv)) {
561                 mutex_unlock(&fw_lock);
562                 retval = -EINTR;
563                 goto out;
564         }
565         list_add(&fw_priv->pending_list, &pending_fw_head);
566         mutex_unlock(&fw_lock);
567
568         if (opt_flags & FW_OPT_UEVENT) {
569                 fw_priv->need_uevent = true;
570                 dev_set_uevent_suppress(f_dev, false);
571                 dev_dbg(f_dev, "firmware: requesting %s\n", fw_priv->fw_name);
572                 kobject_uevent(&fw_sysfs->dev.kobj, KOBJ_ADD);
573         } else {
574                 timeout = MAX_JIFFY_OFFSET;
575         }
576
577         retval = fw_sysfs_wait_timeout(fw_priv, timeout);
578         if (retval < 0 && retval != -ENOENT) {
579                 mutex_lock(&fw_lock);
580                 fw_load_abort(fw_sysfs);
581                 mutex_unlock(&fw_lock);
582         }
583
584         if (fw_state_is_aborted(fw_priv)) {
585                 if (retval == -ERESTARTSYS)
586                         retval = -EINTR;
587         } else if (fw_priv->is_paged_buf && !fw_priv->data)
588                 retval = -ENOMEM;
589
590 out:
591         device_del(f_dev);
592 err_put_dev:
593         put_device(f_dev);
594         return retval;
595 }
596
597 static int fw_load_from_user_helper(struct firmware *firmware,
598                                     const char *name, struct device *device,
599                                     enum fw_opt opt_flags)
600 {
601         struct fw_sysfs *fw_sysfs;
602         long timeout;
603         int ret;
604
605         timeout = is_nonfree_firmware(name) ? 1 : firmware_loading_timeout();
606         if (opt_flags & FW_OPT_NOWAIT) {
607                 timeout = usermodehelper_read_lock_wait(timeout);
608                 if (!timeout) {
609                         dev_dbg(device, "firmware: %s loading timed out\n",
610                                 name);
611                         return -EBUSY;
612                 }
613         } else {
614                 ret = usermodehelper_read_trylock();
615                 if (WARN_ON(ret)) {
616                         dev_err(device, "firmware: %s will not be loaded\n",
617                                 name);
618                         return ret;
619                 }
620         }
621
622         fw_sysfs = fw_create_instance(firmware, name, device, opt_flags);
623         if (IS_ERR(fw_sysfs)) {
624                 ret = PTR_ERR(fw_sysfs);
625                 goto out_unlock;
626         }
627
628         fw_sysfs->fw_priv = firmware->priv;
629         ret = fw_load_sysfs_fallback(fw_sysfs, opt_flags, timeout);
630
631         if (!ret)
632                 ret = assign_fw(firmware, device, opt_flags);
633
634 out_unlock:
635         usermodehelper_read_unlock();
636
637         return ret;
638 }
639
640 static bool fw_force_sysfs_fallback(enum fw_opt opt_flags)
641 {
642         if (fw_fallback_config.force_sysfs_fallback)
643                 return true;
644         if (!(opt_flags & FW_OPT_USERHELPER))
645                 return false;
646         return true;
647 }
648
649 static bool fw_run_sysfs_fallback(enum fw_opt opt_flags)
650 {
651         int ret;
652
653         if (fw_fallback_config.ignore_sysfs_fallback) {
654                 pr_info_once("Ignoring firmware sysfs fallback due to sysctl knob\n");
655                 return false;
656         }
657
658         if ((opt_flags & FW_OPT_NOFALLBACK))
659                 return false;
660
661         /* Also permit LSMs and IMA to fail firmware sysfs fallback */
662         ret = security_kernel_load_data(LOADING_FIRMWARE);
663         if (ret < 0)
664                 return false;
665
666         return fw_force_sysfs_fallback(opt_flags);
667 }
668
669 /**
670  * firmware_fallback_sysfs() - use the fallback mechanism to find firmware
671  * @fw: pointer to firmware image
672  * @name: name of firmware file to look for
673  * @device: device for which firmware is being loaded
674  * @opt_flags: options to control firmware loading behaviour
675  * @ret: return value from direct lookup which triggered the fallback mechanism
676  *
677  * This function is called if direct lookup for the firmware failed, it enables
678  * a fallback mechanism through userspace by exposing a sysfs loading
679  * interface. Userspace is in charge of loading the firmware through the syfs
680  * loading interface. This syfs fallback mechanism may be disabled completely
681  * on a system by setting the proc sysctl value ignore_sysfs_fallback to true.
682  * If this false we check if the internal API caller set the @FW_OPT_NOFALLBACK
683  * flag, if so it would also disable the fallback mechanism. A system may want
684  * to enfoce the sysfs fallback mechanism at all times, it can do this by
685  * setting ignore_sysfs_fallback to false and force_sysfs_fallback to true.
686  * Enabling force_sysfs_fallback is functionally equivalent to build a kernel
687  * with CONFIG_FW_LOADER_USER_HELPER_FALLBACK.
688  **/
689 int firmware_fallback_sysfs(struct firmware *fw, const char *name,
690                             struct device *device,
691                             enum fw_opt opt_flags,
692                             int ret)
693 {
694         if (!fw_run_sysfs_fallback(opt_flags))
695                 return ret;
696
697         if (!(opt_flags & FW_OPT_NO_WARN))
698                 dev_warn(device, "Falling back to syfs fallback for: %s\n",
699                                  name);
700         else
701                 dev_dbg(device, "Falling back to sysfs fallback for: %s\n",
702                                 name);
703         return fw_load_from_user_helper(fw, name, device, opt_flags);
704 }