GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / base / firmware_loader / main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * main.c - Multi purpose firmware loading support
4  *
5  * Copyright (c) 2003 Manuel Estrada Sainz
6  *
7  * Please see Documentation/firmware_class/ for more information.
8  *
9  */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12
13 #include <linux/capability.h>
14 #include <linux/device.h>
15 #include <linux/module.h>
16 #include <linux/init.h>
17 #include <linux/timer.h>
18 #include <linux/vmalloc.h>
19 #include <linux/interrupt.h>
20 #include <linux/bitops.h>
21 #include <linux/mutex.h>
22 #include <linux/workqueue.h>
23 #include <linux/highmem.h>
24 #include <linux/firmware.h>
25 #include <linux/slab.h>
26 #include <linux/sched.h>
27 #include <linux/file.h>
28 #include <linux/list.h>
29 #include <linux/fs.h>
30 #include <linux/async.h>
31 #include <linux/pm.h>
32 #include <linux/suspend.h>
33 #include <linux/syscore_ops.h>
34 #include <linux/reboot.h>
35 #include <linux/security.h>
36
37 #include <generated/utsrelease.h>
38
39 #include "../base.h"
40 #include "firmware.h"
41 #include "fallback.h"
42
43 MODULE_AUTHOR("Manuel Estrada Sainz");
44 MODULE_DESCRIPTION("Multi purpose firmware loading support");
45 MODULE_LICENSE("GPL");
46
47 struct firmware_cache {
48         /* firmware_buf instance will be added into the below list */
49         spinlock_t lock;
50         struct list_head head;
51         int state;
52
53 #ifdef CONFIG_PM_SLEEP
54         /*
55          * Names of firmware images which have been cached successfully
56          * will be added into the below list so that device uncache
57          * helper can trace which firmware images have been cached
58          * before.
59          */
60         spinlock_t name_lock;
61         struct list_head fw_names;
62
63         struct delayed_work work;
64
65         struct notifier_block   pm_notify;
66 #endif
67 };
68
69 struct fw_cache_entry {
70         struct list_head list;
71         const char *name;
72 };
73
74 struct fw_name_devm {
75         unsigned long magic;
76         const char *name;
77 };
78
79 static inline struct fw_priv *to_fw_priv(struct kref *ref)
80 {
81         return container_of(ref, struct fw_priv, ref);
82 }
83
84 #define FW_LOADER_NO_CACHE      0
85 #define FW_LOADER_START_CACHE   1
86
87 /* fw_lock could be moved to 'struct fw_sysfs' but since it is just
88  * guarding for corner cases a global lock should be OK */
89 DEFINE_MUTEX(fw_lock);
90
91 static struct firmware_cache fw_cache;
92
93 /* Builtin firmware support */
94
95 #ifdef CONFIG_FW_LOADER
96
97 extern struct builtin_fw __start_builtin_fw[];
98 extern struct builtin_fw __end_builtin_fw[];
99
100 static bool fw_copy_to_prealloc_buf(struct firmware *fw,
101                                     void *buf, size_t size)
102 {
103         if (!buf)
104                 return true;
105         if (size < fw->size)
106                 return false;
107         memcpy(buf, fw->data, fw->size);
108         return true;
109 }
110
111 static bool fw_get_builtin_firmware(struct firmware *fw, const char *name,
112                                     void *buf, size_t size)
113 {
114         struct builtin_fw *b_fw;
115
116         for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++) {
117                 if (strcmp(name, b_fw->name) == 0) {
118                         fw->size = b_fw->size;
119                         fw->data = b_fw->data;
120                         return fw_copy_to_prealloc_buf(fw, buf, size);
121                 }
122         }
123
124         return false;
125 }
126
127 static bool fw_is_builtin_firmware(const struct firmware *fw)
128 {
129         struct builtin_fw *b_fw;
130
131         for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++)
132                 if (fw->data == b_fw->data)
133                         return true;
134
135         return false;
136 }
137
138 #else /* Module case - no builtin firmware support */
139
140 static inline bool fw_get_builtin_firmware(struct firmware *fw,
141                                            const char *name, void *buf,
142                                            size_t size)
143 {
144         return false;
145 }
146
147 static inline bool fw_is_builtin_firmware(const struct firmware *fw)
148 {
149         return false;
150 }
151 #endif
152
153 static void fw_state_init(struct fw_priv *fw_priv)
154 {
155         struct fw_state *fw_st = &fw_priv->fw_st;
156
157         init_completion(&fw_st->completion);
158         fw_st->status = FW_STATUS_UNKNOWN;
159 }
160
161 static inline int fw_state_wait(struct fw_priv *fw_priv)
162 {
163         return __fw_state_wait_common(fw_priv, MAX_SCHEDULE_TIMEOUT);
164 }
165
166 static int fw_cache_piggyback_on_request(const char *name);
167
168 static struct fw_priv *__allocate_fw_priv(const char *fw_name,
169                                           struct firmware_cache *fwc,
170                                           void *dbuf, size_t size)
171 {
172         struct fw_priv *fw_priv;
173
174         fw_priv = kzalloc(sizeof(*fw_priv), GFP_ATOMIC);
175         if (!fw_priv)
176                 return NULL;
177
178         fw_priv->fw_name = kstrdup_const(fw_name, GFP_ATOMIC);
179         if (!fw_priv->fw_name) {
180                 kfree(fw_priv);
181                 return NULL;
182         }
183
184         kref_init(&fw_priv->ref);
185         fw_priv->fwc = fwc;
186         fw_priv->data = dbuf;
187         fw_priv->allocated_size = size;
188         fw_state_init(fw_priv);
189 #ifdef CONFIG_FW_LOADER_USER_HELPER
190         INIT_LIST_HEAD(&fw_priv->pending_list);
191 #endif
192
193         pr_debug("%s: fw-%s fw_priv=%p\n", __func__, fw_name, fw_priv);
194
195         return fw_priv;
196 }
197
198 static struct fw_priv *__lookup_fw_priv(const char *fw_name)
199 {
200         struct fw_priv *tmp;
201         struct firmware_cache *fwc = &fw_cache;
202
203         list_for_each_entry(tmp, &fwc->head, list)
204                 if (!strcmp(tmp->fw_name, fw_name))
205                         return tmp;
206         return NULL;
207 }
208
209 /* Returns 1 for batching firmware requests with the same name */
210 static int alloc_lookup_fw_priv(const char *fw_name,
211                                 struct firmware_cache *fwc,
212                                 struct fw_priv **fw_priv, void *dbuf,
213                                 size_t size, enum fw_opt opt_flags)
214 {
215         struct fw_priv *tmp;
216
217         spin_lock(&fwc->lock);
218         if (!(opt_flags & FW_OPT_NOCACHE)) {
219                 tmp = __lookup_fw_priv(fw_name);
220                 if (tmp) {
221                         kref_get(&tmp->ref);
222                         spin_unlock(&fwc->lock);
223                         *fw_priv = tmp;
224                         pr_debug("batched request - sharing the same struct fw_priv and lookup for multiple requests\n");
225                         return 1;
226                 }
227         }
228
229         tmp = __allocate_fw_priv(fw_name, fwc, dbuf, size);
230         if (tmp) {
231                 INIT_LIST_HEAD(&tmp->list);
232                 if (!(opt_flags & FW_OPT_NOCACHE))
233                         list_add(&tmp->list, &fwc->head);
234         }
235         spin_unlock(&fwc->lock);
236
237         *fw_priv = tmp;
238
239         return tmp ? 0 : -ENOMEM;
240 }
241
242 static void __free_fw_priv(struct kref *ref)
243         __releases(&fwc->lock)
244 {
245         struct fw_priv *fw_priv = to_fw_priv(ref);
246         struct firmware_cache *fwc = fw_priv->fwc;
247
248         pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
249                  __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
250                  (unsigned int)fw_priv->size);
251
252         list_del(&fw_priv->list);
253         spin_unlock(&fwc->lock);
254
255 #ifdef CONFIG_FW_LOADER_USER_HELPER
256         if (fw_priv->is_paged_buf) {
257                 int i;
258                 vunmap(fw_priv->data);
259                 for (i = 0; i < fw_priv->nr_pages; i++)
260                         __free_page(fw_priv->pages[i]);
261                 vfree(fw_priv->pages);
262         } else
263 #endif
264         if (!fw_priv->allocated_size)
265                 vfree(fw_priv->data);
266         kfree_const(fw_priv->fw_name);
267         kfree(fw_priv);
268 }
269
270 static void free_fw_priv(struct fw_priv *fw_priv)
271 {
272         struct firmware_cache *fwc = fw_priv->fwc;
273         spin_lock(&fwc->lock);
274         if (!kref_put(&fw_priv->ref, __free_fw_priv))
275                 spin_unlock(&fwc->lock);
276 }
277
278 /* direct firmware loading support */
279 static char fw_path_para[256];
280 static const char * const fw_path[] = {
281         fw_path_para,
282         "/lib/firmware/updates/" UTS_RELEASE,
283         "/lib/firmware/updates",
284         "/lib/firmware/" UTS_RELEASE,
285         "/lib/firmware"
286 };
287
288 /*
289  * Typical usage is that passing 'firmware_class.path=$CUSTOMIZED_PATH'
290  * from kernel command line because firmware_class is generally built in
291  * kernel instead of module.
292  */
293 module_param_string(path, fw_path_para, sizeof(fw_path_para), 0644);
294 MODULE_PARM_DESC(path, "customized firmware image search path with a higher priority than default path");
295
296 static int
297 fw_get_filesystem_firmware(struct device *device, struct fw_priv *fw_priv)
298 {
299         loff_t size;
300         int i, len;
301         int rc = -ENOENT;
302         char *path;
303         enum kernel_read_file_id id = READING_FIRMWARE;
304         size_t msize = INT_MAX;
305
306         /* Already populated data member means we're loading into a buffer */
307         if (fw_priv->data) {
308                 id = READING_FIRMWARE_PREALLOC_BUFFER;
309                 msize = fw_priv->allocated_size;
310         }
311
312         path = __getname();
313         if (!path)
314                 return -ENOMEM;
315
316         for (i = 0; i < ARRAY_SIZE(fw_path); i++) {
317                 /* skip the unset customized path */
318                 if (!fw_path[i][0])
319                         continue;
320
321                 len = snprintf(path, PATH_MAX, "%s/%s",
322                                fw_path[i], fw_priv->fw_name);
323                 if (len >= PATH_MAX) {
324                         rc = -ENAMETOOLONG;
325                         break;
326                 }
327
328                 fw_priv->size = 0;
329                 rc = kernel_read_file_from_path(path, &fw_priv->data, &size,
330                                                 msize, id);
331                 if (rc) {
332                         if (rc == -ENOENT)
333                                 dev_dbg(device, "loading %s failed with error %d\n",
334                                          path, rc);
335                         else
336                                 dev_warn(device, "loading %s failed with error %d\n",
337                                          path, rc);
338                         continue;
339                 }
340                 dev_dbg(device, "direct-loading %s\n", fw_priv->fw_name);
341                 fw_priv->size = size;
342                 fw_state_done(fw_priv);
343                 break;
344         }
345         __putname(path);
346
347         return rc;
348 }
349
350 /* firmware holds the ownership of pages */
351 static void firmware_free_data(const struct firmware *fw)
352 {
353         /* Loaded directly? */
354         if (!fw->priv) {
355                 vfree(fw->data);
356                 return;
357         }
358         free_fw_priv(fw->priv);
359 }
360
361 /* store the pages buffer info firmware from buf */
362 static void fw_set_page_data(struct fw_priv *fw_priv, struct firmware *fw)
363 {
364         fw->priv = fw_priv;
365 #ifdef CONFIG_FW_LOADER_USER_HELPER
366         fw->pages = fw_priv->pages;
367 #endif
368         fw->size = fw_priv->size;
369         fw->data = fw_priv->data;
370
371         pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
372                  __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
373                  (unsigned int)fw_priv->size);
374 }
375
376 #ifdef CONFIG_PM_SLEEP
377 static void fw_name_devm_release(struct device *dev, void *res)
378 {
379         struct fw_name_devm *fwn = res;
380
381         if (fwn->magic == (unsigned long)&fw_cache)
382                 pr_debug("%s: fw_name-%s devm-%p released\n",
383                                 __func__, fwn->name, res);
384         kfree_const(fwn->name);
385 }
386
387 static int fw_devm_match(struct device *dev, void *res,
388                 void *match_data)
389 {
390         struct fw_name_devm *fwn = res;
391
392         return (fwn->magic == (unsigned long)&fw_cache) &&
393                 !strcmp(fwn->name, match_data);
394 }
395
396 static struct fw_name_devm *fw_find_devm_name(struct device *dev,
397                 const char *name)
398 {
399         struct fw_name_devm *fwn;
400
401         fwn = devres_find(dev, fw_name_devm_release,
402                           fw_devm_match, (void *)name);
403         return fwn;
404 }
405
406 static bool fw_cache_is_setup(struct device *dev, const char *name)
407 {
408         struct fw_name_devm *fwn;
409
410         fwn = fw_find_devm_name(dev, name);
411         if (fwn)
412                 return true;
413
414         return false;
415 }
416
417 /* add firmware name into devres list */
418 static int fw_add_devm_name(struct device *dev, const char *name)
419 {
420         struct fw_name_devm *fwn;
421
422         if (fw_cache_is_setup(dev, name))
423                 return 0;
424
425         fwn = devres_alloc(fw_name_devm_release, sizeof(struct fw_name_devm),
426                            GFP_KERNEL);
427         if (!fwn)
428                 return -ENOMEM;
429         fwn->name = kstrdup_const(name, GFP_KERNEL);
430         if (!fwn->name) {
431                 devres_free(fwn);
432                 return -ENOMEM;
433         }
434
435         fwn->magic = (unsigned long)&fw_cache;
436         devres_add(dev, fwn);
437
438         return 0;
439 }
440 #else
441 static bool fw_cache_is_setup(struct device *dev, const char *name)
442 {
443         return false;
444 }
445
446 static int fw_add_devm_name(struct device *dev, const char *name)
447 {
448         return 0;
449 }
450 #endif
451
452 int assign_fw(struct firmware *fw, struct device *device,
453               enum fw_opt opt_flags)
454 {
455         struct fw_priv *fw_priv = fw->priv;
456         int ret;
457
458         mutex_lock(&fw_lock);
459         if (!fw_priv->size || fw_state_is_aborted(fw_priv)) {
460                 mutex_unlock(&fw_lock);
461                 return -ENOENT;
462         }
463
464         /*
465          * add firmware name into devres list so that we can auto cache
466          * and uncache firmware for device.
467          *
468          * device may has been deleted already, but the problem
469          * should be fixed in devres or driver core.
470          */
471         /* don't cache firmware handled without uevent */
472         if (device && (opt_flags & FW_OPT_UEVENT) &&
473             !(opt_flags & FW_OPT_NOCACHE)) {
474                 ret = fw_add_devm_name(device, fw_priv->fw_name);
475                 if (ret) {
476                         mutex_unlock(&fw_lock);
477                         return ret;
478                 }
479         }
480
481         /*
482          * After caching firmware image is started, let it piggyback
483          * on request firmware.
484          */
485         if (!(opt_flags & FW_OPT_NOCACHE) &&
486             fw_priv->fwc->state == FW_LOADER_START_CACHE) {
487                 if (fw_cache_piggyback_on_request(fw_priv->fw_name))
488                         kref_get(&fw_priv->ref);
489         }
490
491         /* pass the pages buffer to driver at the last minute */
492         fw_set_page_data(fw_priv, fw);
493         mutex_unlock(&fw_lock);
494         return 0;
495 }
496
497 /* prepare firmware and firmware_buf structs;
498  * return 0 if a firmware is already assigned, 1 if need to load one,
499  * or a negative error code
500  */
501 static int
502 _request_firmware_prepare(struct firmware **firmware_p, const char *name,
503                           struct device *device, void *dbuf, size_t size,
504                           enum fw_opt opt_flags)
505 {
506         struct firmware *firmware;
507         struct fw_priv *fw_priv;
508         int ret;
509
510         *firmware_p = firmware = kzalloc(sizeof(*firmware), GFP_KERNEL);
511         if (!firmware) {
512                 dev_err(device, "%s: kmalloc(struct firmware) failed\n",
513                         __func__);
514                 return -ENOMEM;
515         }
516
517         if (fw_get_builtin_firmware(firmware, name, dbuf, size)) {
518                 dev_dbg(device, "using built-in %s\n", name);
519                 return 0; /* assigned */
520         }
521
522         ret = alloc_lookup_fw_priv(name, &fw_cache, &fw_priv, dbuf, size,
523                                   opt_flags);
524
525         /*
526          * bind with 'priv' now to avoid warning in failure path
527          * of requesting firmware.
528          */
529         firmware->priv = fw_priv;
530
531         if (ret > 0) {
532                 ret = fw_state_wait(fw_priv);
533                 if (!ret) {
534                         fw_set_page_data(fw_priv, firmware);
535                         return 0; /* assigned */
536                 }
537         }
538
539         if (ret < 0)
540                 return ret;
541         return 1; /* need to load */
542 }
543
544 /*
545  * Batched requests need only one wake, we need to do this step last due to the
546  * fallback mechanism. The buf is protected with kref_get(), and it won't be
547  * released until the last user calls release_firmware().
548  *
549  * Failed batched requests are possible as well, in such cases we just share
550  * the struct fw_priv and won't release it until all requests are woken
551  * and have gone through this same path.
552  */
553 static void fw_abort_batch_reqs(struct firmware *fw)
554 {
555         struct fw_priv *fw_priv;
556
557         /* Loaded directly? */
558         if (!fw || !fw->priv)
559                 return;
560
561         fw_priv = fw->priv;
562         mutex_lock(&fw_lock);
563         if (!fw_state_is_aborted(fw_priv))
564                 fw_state_aborted(fw_priv);
565         mutex_unlock(&fw_lock);
566 }
567
568 /* called from request_firmware() and request_firmware_work_func() */
569 static int
570 _request_firmware(const struct firmware **firmware_p, const char *name,
571                   struct device *device, void *buf, size_t size,
572                   enum fw_opt opt_flags)
573 {
574         struct firmware *fw = NULL;
575         int ret;
576
577         if (!firmware_p)
578                 return -EINVAL;
579
580         if (!name || name[0] == '\0') {
581                 ret = -EINVAL;
582                 goto out;
583         }
584
585         ret = _request_firmware_prepare(&fw, name, device, buf, size,
586                                         opt_flags);
587         if (ret <= 0) /* error or already assigned */
588                 goto out;
589
590         ret = fw_get_filesystem_firmware(device, fw->priv);
591         if (ret) {
592                 if (!(opt_flags & FW_OPT_NO_WARN))
593                         dev_warn(device,
594                                  "Direct firmware load for %s failed with error %d\n",
595                                  name, ret);
596                 ret = firmware_fallback_sysfs(fw, name, device, opt_flags, ret);
597         } else
598                 ret = assign_fw(fw, device, opt_flags);
599
600  out:
601         if (ret < 0) {
602                 fw_abort_batch_reqs(fw);
603                 release_firmware(fw);
604                 fw = NULL;
605         }
606
607         *firmware_p = fw;
608         return ret;
609 }
610
611 /**
612  * request_firmware() - send firmware request and wait for it
613  * @firmware_p: pointer to firmware image
614  * @name: name of firmware file
615  * @device: device for which firmware is being loaded
616  *
617  *      @firmware_p will be used to return a firmware image by the name
618  *      of @name for device @device.
619  *
620  *      Should be called from user context where sleeping is allowed.
621  *
622  *      @name will be used as $FIRMWARE in the uevent environment and
623  *      should be distinctive enough not to be confused with any other
624  *      firmware image for this or any other device.
625  *
626  *      Caller must hold the reference count of @device.
627  *
628  *      The function can be called safely inside device's suspend and
629  *      resume callback.
630  **/
631 int
632 request_firmware(const struct firmware **firmware_p, const char *name,
633                  struct device *device)
634 {
635         int ret;
636
637         /* Need to pin this module until return */
638         __module_get(THIS_MODULE);
639         ret = _request_firmware(firmware_p, name, device, NULL, 0,
640                                 FW_OPT_UEVENT);
641         module_put(THIS_MODULE);
642         return ret;
643 }
644 EXPORT_SYMBOL(request_firmware);
645
646 /**
647  * firmware_request_nowarn() - request for an optional fw module
648  * @firmware: pointer to firmware image
649  * @name: name of firmware file
650  * @device: device for which firmware is being loaded
651  *
652  * This function is similar in behaviour to request_firmware(), except
653  * it doesn't produce warning messages when the file is not found.
654  * The sysfs fallback mechanism is enabled if direct filesystem lookup fails,
655  * however, however failures to find the firmware file with it are still
656  * suppressed. It is therefore up to the driver to check for the return value
657  * of this call and to decide when to inform the users of errors.
658  **/
659 int firmware_request_nowarn(const struct firmware **firmware, const char *name,
660                             struct device *device)
661 {
662         int ret;
663
664         /* Need to pin this module until return */
665         __module_get(THIS_MODULE);
666         ret = _request_firmware(firmware, name, device, NULL, 0,
667                                 FW_OPT_UEVENT | FW_OPT_NO_WARN);
668         module_put(THIS_MODULE);
669         return ret;
670 }
671 EXPORT_SYMBOL_GPL(firmware_request_nowarn);
672
673 /**
674  * request_firmware_direct() - load firmware directly without usermode helper
675  * @firmware_p: pointer to firmware image
676  * @name: name of firmware file
677  * @device: device for which firmware is being loaded
678  *
679  * This function works pretty much like request_firmware(), but this doesn't
680  * fall back to usermode helper even if the firmware couldn't be loaded
681  * directly from fs.  Hence it's useful for loading optional firmwares, which
682  * aren't always present, without extra long timeouts of udev.
683  **/
684 int request_firmware_direct(const struct firmware **firmware_p,
685                             const char *name, struct device *device)
686 {
687         int ret;
688
689         __module_get(THIS_MODULE);
690         ret = _request_firmware(firmware_p, name, device, NULL, 0,
691                                 FW_OPT_UEVENT | FW_OPT_NO_WARN |
692                                 FW_OPT_NOFALLBACK);
693         module_put(THIS_MODULE);
694         return ret;
695 }
696 EXPORT_SYMBOL_GPL(request_firmware_direct);
697
698 /**
699  * firmware_request_cache() - cache firmware for suspend so resume can use it
700  * @name: name of firmware file
701  * @device: device for which firmware should be cached for
702  *
703  * There are some devices with an optimization that enables the device to not
704  * require loading firmware on system reboot. This optimization may still
705  * require the firmware present on resume from suspend. This routine can be
706  * used to ensure the firmware is present on resume from suspend in these
707  * situations. This helper is not compatible with drivers which use
708  * request_firmware_into_buf() or request_firmware_nowait() with no uevent set.
709  **/
710 int firmware_request_cache(struct device *device, const char *name)
711 {
712         int ret;
713
714         mutex_lock(&fw_lock);
715         ret = fw_add_devm_name(device, name);
716         mutex_unlock(&fw_lock);
717
718         return ret;
719 }
720 EXPORT_SYMBOL_GPL(firmware_request_cache);
721
722 /**
723  * request_firmware_into_buf() - load firmware into a previously allocated buffer
724  * @firmware_p: pointer to firmware image
725  * @name: name of firmware file
726  * @device: device for which firmware is being loaded and DMA region allocated
727  * @buf: address of buffer to load firmware into
728  * @size: size of buffer
729  *
730  * This function works pretty much like request_firmware(), but it doesn't
731  * allocate a buffer to hold the firmware data. Instead, the firmware
732  * is loaded directly into the buffer pointed to by @buf and the @firmware_p
733  * data member is pointed at @buf.
734  *
735  * This function doesn't cache firmware either.
736  */
737 int
738 request_firmware_into_buf(const struct firmware **firmware_p, const char *name,
739                           struct device *device, void *buf, size_t size)
740 {
741         int ret;
742
743         if (fw_cache_is_setup(device, name))
744                 return -EOPNOTSUPP;
745
746         __module_get(THIS_MODULE);
747         ret = _request_firmware(firmware_p, name, device, buf, size,
748                                 FW_OPT_UEVENT | FW_OPT_NOCACHE);
749         module_put(THIS_MODULE);
750         return ret;
751 }
752 EXPORT_SYMBOL(request_firmware_into_buf);
753
754 /**
755  * release_firmware() - release the resource associated with a firmware image
756  * @fw: firmware resource to release
757  **/
758 void release_firmware(const struct firmware *fw)
759 {
760         if (fw) {
761                 if (!fw_is_builtin_firmware(fw))
762                         firmware_free_data(fw);
763                 kfree(fw);
764         }
765 }
766 EXPORT_SYMBOL(release_firmware);
767
768 /* Async support */
769 struct firmware_work {
770         struct work_struct work;
771         struct module *module;
772         const char *name;
773         struct device *device;
774         void *context;
775         void (*cont)(const struct firmware *fw, void *context);
776         enum fw_opt opt_flags;
777 };
778
779 static void request_firmware_work_func(struct work_struct *work)
780 {
781         struct firmware_work *fw_work;
782         const struct firmware *fw;
783
784         fw_work = container_of(work, struct firmware_work, work);
785
786         _request_firmware(&fw, fw_work->name, fw_work->device, NULL, 0,
787                           fw_work->opt_flags);
788         fw_work->cont(fw, fw_work->context);
789         put_device(fw_work->device); /* taken in request_firmware_nowait() */
790
791         module_put(fw_work->module);
792         kfree_const(fw_work->name);
793         kfree(fw_work);
794 }
795
796 /**
797  * request_firmware_nowait() - asynchronous version of request_firmware
798  * @module: module requesting the firmware
799  * @uevent: sends uevent to copy the firmware image if this flag
800  *      is non-zero else the firmware copy must be done manually.
801  * @name: name of firmware file
802  * @device: device for which firmware is being loaded
803  * @gfp: allocation flags
804  * @context: will be passed over to @cont, and
805  *      @fw may be %NULL if firmware request fails.
806  * @cont: function will be called asynchronously when the firmware
807  *      request is over.
808  *
809  *      Caller must hold the reference count of @device.
810  *
811  *      Asynchronous variant of request_firmware() for user contexts:
812  *              - sleep for as small periods as possible since it may
813  *                increase kernel boot time of built-in device drivers
814  *                requesting firmware in their ->probe() methods, if
815  *                @gfp is GFP_KERNEL.
816  *
817  *              - can't sleep at all if @gfp is GFP_ATOMIC.
818  **/
819 int
820 request_firmware_nowait(
821         struct module *module, bool uevent,
822         const char *name, struct device *device, gfp_t gfp, void *context,
823         void (*cont)(const struct firmware *fw, void *context))
824 {
825         struct firmware_work *fw_work;
826
827         fw_work = kzalloc(sizeof(struct firmware_work), gfp);
828         if (!fw_work)
829                 return -ENOMEM;
830
831         fw_work->module = module;
832         fw_work->name = kstrdup_const(name, gfp);
833         if (!fw_work->name) {
834                 kfree(fw_work);
835                 return -ENOMEM;
836         }
837         fw_work->device = device;
838         fw_work->context = context;
839         fw_work->cont = cont;
840         fw_work->opt_flags = FW_OPT_NOWAIT |
841                 (uevent ? FW_OPT_UEVENT : FW_OPT_USERHELPER);
842
843         if (!uevent && fw_cache_is_setup(device, name)) {
844                 kfree_const(fw_work->name);
845                 kfree(fw_work);
846                 return -EOPNOTSUPP;
847         }
848
849         if (!try_module_get(module)) {
850                 kfree_const(fw_work->name);
851                 kfree(fw_work);
852                 return -EFAULT;
853         }
854
855         get_device(fw_work->device);
856         INIT_WORK(&fw_work->work, request_firmware_work_func);
857         schedule_work(&fw_work->work);
858         return 0;
859 }
860 EXPORT_SYMBOL(request_firmware_nowait);
861
862 #ifdef CONFIG_PM_SLEEP
863 static ASYNC_DOMAIN_EXCLUSIVE(fw_cache_domain);
864
865 /**
866  * cache_firmware() - cache one firmware image in kernel memory space
867  * @fw_name: the firmware image name
868  *
869  * Cache firmware in kernel memory so that drivers can use it when
870  * system isn't ready for them to request firmware image from userspace.
871  * Once it returns successfully, driver can use request_firmware or its
872  * nowait version to get the cached firmware without any interacting
873  * with userspace
874  *
875  * Return 0 if the firmware image has been cached successfully
876  * Return !0 otherwise
877  *
878  */
879 static int cache_firmware(const char *fw_name)
880 {
881         int ret;
882         const struct firmware *fw;
883
884         pr_debug("%s: %s\n", __func__, fw_name);
885
886         ret = request_firmware(&fw, fw_name, NULL);
887         if (!ret)
888                 kfree(fw);
889
890         pr_debug("%s: %s ret=%d\n", __func__, fw_name, ret);
891
892         return ret;
893 }
894
895 static struct fw_priv *lookup_fw_priv(const char *fw_name)
896 {
897         struct fw_priv *tmp;
898         struct firmware_cache *fwc = &fw_cache;
899
900         spin_lock(&fwc->lock);
901         tmp = __lookup_fw_priv(fw_name);
902         spin_unlock(&fwc->lock);
903
904         return tmp;
905 }
906
907 /**
908  * uncache_firmware() - remove one cached firmware image
909  * @fw_name: the firmware image name
910  *
911  * Uncache one firmware image which has been cached successfully
912  * before.
913  *
914  * Return 0 if the firmware cache has been removed successfully
915  * Return !0 otherwise
916  *
917  */
918 static int uncache_firmware(const char *fw_name)
919 {
920         struct fw_priv *fw_priv;
921         struct firmware fw;
922
923         pr_debug("%s: %s\n", __func__, fw_name);
924
925         if (fw_get_builtin_firmware(&fw, fw_name, NULL, 0))
926                 return 0;
927
928         fw_priv = lookup_fw_priv(fw_name);
929         if (fw_priv) {
930                 free_fw_priv(fw_priv);
931                 return 0;
932         }
933
934         return -EINVAL;
935 }
936
937 static struct fw_cache_entry *alloc_fw_cache_entry(const char *name)
938 {
939         struct fw_cache_entry *fce;
940
941         fce = kzalloc(sizeof(*fce), GFP_ATOMIC);
942         if (!fce)
943                 goto exit;
944
945         fce->name = kstrdup_const(name, GFP_ATOMIC);
946         if (!fce->name) {
947                 kfree(fce);
948                 fce = NULL;
949                 goto exit;
950         }
951 exit:
952         return fce;
953 }
954
955 static int __fw_entry_found(const char *name)
956 {
957         struct firmware_cache *fwc = &fw_cache;
958         struct fw_cache_entry *fce;
959
960         list_for_each_entry(fce, &fwc->fw_names, list) {
961                 if (!strcmp(fce->name, name))
962                         return 1;
963         }
964         return 0;
965 }
966
967 static int fw_cache_piggyback_on_request(const char *name)
968 {
969         struct firmware_cache *fwc = &fw_cache;
970         struct fw_cache_entry *fce;
971         int ret = 0;
972
973         spin_lock(&fwc->name_lock);
974         if (__fw_entry_found(name))
975                 goto found;
976
977         fce = alloc_fw_cache_entry(name);
978         if (fce) {
979                 ret = 1;
980                 list_add(&fce->list, &fwc->fw_names);
981                 pr_debug("%s: fw: %s\n", __func__, name);
982         }
983 found:
984         spin_unlock(&fwc->name_lock);
985         return ret;
986 }
987
988 static void free_fw_cache_entry(struct fw_cache_entry *fce)
989 {
990         kfree_const(fce->name);
991         kfree(fce);
992 }
993
994 static void __async_dev_cache_fw_image(void *fw_entry,
995                                        async_cookie_t cookie)
996 {
997         struct fw_cache_entry *fce = fw_entry;
998         struct firmware_cache *fwc = &fw_cache;
999         int ret;
1000
1001         ret = cache_firmware(fce->name);
1002         if (ret) {
1003                 spin_lock(&fwc->name_lock);
1004                 list_del(&fce->list);
1005                 spin_unlock(&fwc->name_lock);
1006
1007                 free_fw_cache_entry(fce);
1008         }
1009 }
1010
1011 /* called with dev->devres_lock held */
1012 static void dev_create_fw_entry(struct device *dev, void *res,
1013                                 void *data)
1014 {
1015         struct fw_name_devm *fwn = res;
1016         const char *fw_name = fwn->name;
1017         struct list_head *head = data;
1018         struct fw_cache_entry *fce;
1019
1020         fce = alloc_fw_cache_entry(fw_name);
1021         if (fce)
1022                 list_add(&fce->list, head);
1023 }
1024
1025 static int devm_name_match(struct device *dev, void *res,
1026                            void *match_data)
1027 {
1028         struct fw_name_devm *fwn = res;
1029         return (fwn->magic == (unsigned long)match_data);
1030 }
1031
1032 static void dev_cache_fw_image(struct device *dev, void *data)
1033 {
1034         LIST_HEAD(todo);
1035         struct fw_cache_entry *fce;
1036         struct fw_cache_entry *fce_next;
1037         struct firmware_cache *fwc = &fw_cache;
1038
1039         devres_for_each_res(dev, fw_name_devm_release,
1040                             devm_name_match, &fw_cache,
1041                             dev_create_fw_entry, &todo);
1042
1043         list_for_each_entry_safe(fce, fce_next, &todo, list) {
1044                 list_del(&fce->list);
1045
1046                 spin_lock(&fwc->name_lock);
1047                 /* only one cache entry for one firmware */
1048                 if (!__fw_entry_found(fce->name)) {
1049                         list_add(&fce->list, &fwc->fw_names);
1050                 } else {
1051                         free_fw_cache_entry(fce);
1052                         fce = NULL;
1053                 }
1054                 spin_unlock(&fwc->name_lock);
1055
1056                 if (fce)
1057                         async_schedule_domain(__async_dev_cache_fw_image,
1058                                               (void *)fce,
1059                                               &fw_cache_domain);
1060         }
1061 }
1062
1063 static void __device_uncache_fw_images(void)
1064 {
1065         struct firmware_cache *fwc = &fw_cache;
1066         struct fw_cache_entry *fce;
1067
1068         spin_lock(&fwc->name_lock);
1069         while (!list_empty(&fwc->fw_names)) {
1070                 fce = list_entry(fwc->fw_names.next,
1071                                 struct fw_cache_entry, list);
1072                 list_del(&fce->list);
1073                 spin_unlock(&fwc->name_lock);
1074
1075                 uncache_firmware(fce->name);
1076                 free_fw_cache_entry(fce);
1077
1078                 spin_lock(&fwc->name_lock);
1079         }
1080         spin_unlock(&fwc->name_lock);
1081 }
1082
1083 /**
1084  * device_cache_fw_images() - cache devices' firmware
1085  *
1086  * If one device called request_firmware or its nowait version
1087  * successfully before, the firmware names are recored into the
1088  * device's devres link list, so device_cache_fw_images can call
1089  * cache_firmware() to cache these firmwares for the device,
1090  * then the device driver can load its firmwares easily at
1091  * time when system is not ready to complete loading firmware.
1092  */
1093 static void device_cache_fw_images(void)
1094 {
1095         struct firmware_cache *fwc = &fw_cache;
1096         DEFINE_WAIT(wait);
1097
1098         pr_debug("%s\n", __func__);
1099
1100         /* cancel uncache work */
1101         cancel_delayed_work_sync(&fwc->work);
1102
1103         fw_fallback_set_cache_timeout();
1104
1105         mutex_lock(&fw_lock);
1106         fwc->state = FW_LOADER_START_CACHE;
1107         dpm_for_each_dev(NULL, dev_cache_fw_image);
1108         mutex_unlock(&fw_lock);
1109
1110         /* wait for completion of caching firmware for all devices */
1111         async_synchronize_full_domain(&fw_cache_domain);
1112
1113         fw_fallback_set_default_timeout();
1114 }
1115
1116 /**
1117  * device_uncache_fw_images() - uncache devices' firmware
1118  *
1119  * uncache all firmwares which have been cached successfully
1120  * by device_uncache_fw_images earlier
1121  */
1122 static void device_uncache_fw_images(void)
1123 {
1124         pr_debug("%s\n", __func__);
1125         __device_uncache_fw_images();
1126 }
1127
1128 static void device_uncache_fw_images_work(struct work_struct *work)
1129 {
1130         device_uncache_fw_images();
1131 }
1132
1133 /**
1134  * device_uncache_fw_images_delay() - uncache devices firmwares
1135  * @delay: number of milliseconds to delay uncache device firmwares
1136  *
1137  * uncache all devices's firmwares which has been cached successfully
1138  * by device_cache_fw_images after @delay milliseconds.
1139  */
1140 static void device_uncache_fw_images_delay(unsigned long delay)
1141 {
1142         queue_delayed_work(system_power_efficient_wq, &fw_cache.work,
1143                            msecs_to_jiffies(delay));
1144 }
1145
1146 static int fw_pm_notify(struct notifier_block *notify_block,
1147                         unsigned long mode, void *unused)
1148 {
1149         switch (mode) {
1150         case PM_HIBERNATION_PREPARE:
1151         case PM_SUSPEND_PREPARE:
1152         case PM_RESTORE_PREPARE:
1153                 /*
1154                  * kill pending fallback requests with a custom fallback
1155                  * to avoid stalling suspend.
1156                  */
1157                 kill_pending_fw_fallback_reqs(true);
1158                 device_cache_fw_images();
1159                 break;
1160
1161         case PM_POST_SUSPEND:
1162         case PM_POST_HIBERNATION:
1163         case PM_POST_RESTORE:
1164                 /*
1165                  * In case that system sleep failed and syscore_suspend is
1166                  * not called.
1167                  */
1168                 mutex_lock(&fw_lock);
1169                 fw_cache.state = FW_LOADER_NO_CACHE;
1170                 mutex_unlock(&fw_lock);
1171
1172                 device_uncache_fw_images_delay(10 * MSEC_PER_SEC);
1173                 break;
1174         }
1175
1176         return 0;
1177 }
1178
1179 /* stop caching firmware once syscore_suspend is reached */
1180 static int fw_suspend(void)
1181 {
1182         fw_cache.state = FW_LOADER_NO_CACHE;
1183         return 0;
1184 }
1185
1186 static struct syscore_ops fw_syscore_ops = {
1187         .suspend = fw_suspend,
1188 };
1189
1190 static int __init register_fw_pm_ops(void)
1191 {
1192         int ret;
1193
1194         spin_lock_init(&fw_cache.name_lock);
1195         INIT_LIST_HEAD(&fw_cache.fw_names);
1196
1197         INIT_DELAYED_WORK(&fw_cache.work,
1198                           device_uncache_fw_images_work);
1199
1200         fw_cache.pm_notify.notifier_call = fw_pm_notify;
1201         ret = register_pm_notifier(&fw_cache.pm_notify);
1202         if (ret)
1203                 return ret;
1204
1205         register_syscore_ops(&fw_syscore_ops);
1206
1207         return ret;
1208 }
1209
1210 static inline void unregister_fw_pm_ops(void)
1211 {
1212         unregister_syscore_ops(&fw_syscore_ops);
1213         unregister_pm_notifier(&fw_cache.pm_notify);
1214 }
1215 #else
1216 static int fw_cache_piggyback_on_request(const char *name)
1217 {
1218         return 0;
1219 }
1220 static inline int register_fw_pm_ops(void)
1221 {
1222         return 0;
1223 }
1224 static inline void unregister_fw_pm_ops(void)
1225 {
1226 }
1227 #endif
1228
1229 static void __init fw_cache_init(void)
1230 {
1231         spin_lock_init(&fw_cache.lock);
1232         INIT_LIST_HEAD(&fw_cache.head);
1233         fw_cache.state = FW_LOADER_NO_CACHE;
1234 }
1235
1236 static int fw_shutdown_notify(struct notifier_block *unused1,
1237                               unsigned long unused2, void *unused3)
1238 {
1239         /*
1240          * Kill all pending fallback requests to avoid both stalling shutdown,
1241          * and avoid a deadlock with the usermode_lock.
1242          */
1243         kill_pending_fw_fallback_reqs(false);
1244
1245         return NOTIFY_DONE;
1246 }
1247
1248 static struct notifier_block fw_shutdown_nb = {
1249         .notifier_call = fw_shutdown_notify,
1250 };
1251
1252 static int __init firmware_class_init(void)
1253 {
1254         int ret;
1255
1256         /* No need to unfold these on exit */
1257         fw_cache_init();
1258
1259         ret = register_fw_pm_ops();
1260         if (ret)
1261                 return ret;
1262
1263         ret = register_reboot_notifier(&fw_shutdown_nb);
1264         if (ret)
1265                 goto out;
1266
1267         return register_sysfs_loader();
1268
1269 out:
1270         unregister_fw_pm_ops();
1271         return ret;
1272 }
1273
1274 static void __exit firmware_class_exit(void)
1275 {
1276         unregister_fw_pm_ops();
1277         unregister_reboot_notifier(&fw_shutdown_nb);
1278         unregister_sysfs_loader();
1279 }
1280
1281 fs_initcall(firmware_class_init);
1282 module_exit(firmware_class_exit);