base/firmware retry firmware load after rootfs mount
[platform/kernel/linux-exynos.git] / drivers / base / firmware_class.c
1 /*
2  * firmware_class.c - Multi purpose firmware loading support
3  *
4  * Copyright (c) 2003 Manuel Estrada Sainz
5  *
6  * Please see Documentation/firmware_class/ for more information.
7  *
8  */
9
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11
12 #include <linux/capability.h>
13 #include <linux/device.h>
14 #include <linux/module.h>
15 #include <linux/init.h>
16 #include <linux/timer.h>
17 #include <linux/vmalloc.h>
18 #include <linux/interrupt.h>
19 #include <linux/bitops.h>
20 #include <linux/mutex.h>
21 #include <linux/workqueue.h>
22 #include <linux/highmem.h>
23 #include <linux/firmware.h>
24 #include <linux/slab.h>
25 #include <linux/sched.h>
26 #include <linux/file.h>
27 #include <linux/list.h>
28 #include <linux/fs.h>
29 #include <linux/async.h>
30 #include <linux/pm.h>
31 #include <linux/suspend.h>
32 #include <linux/syscore_ops.h>
33 #include <linux/reboot.h>
34 #include <linux/security.h>
35 #include <linux/root_dev.h>
36
37 #include <generated/utsrelease.h>
38
39 #include "base.h"
40
41 MODULE_AUTHOR("Manuel Estrada Sainz");
42 MODULE_DESCRIPTION("Multi purpose firmware loading support");
43 MODULE_LICENSE("GPL");
44
45 /* Builtin firmware support */
46
47 #ifdef CONFIG_FW_LOADER
48
49 extern struct builtin_fw __start_builtin_fw[];
50 extern struct builtin_fw __end_builtin_fw[];
51
52 static bool fw_get_builtin_firmware(struct firmware *fw, const char *name,
53                                     void *buf, size_t size)
54 {
55         struct builtin_fw *b_fw;
56
57         for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++) {
58                 if (strcmp(name, b_fw->name) == 0) {
59                         fw->size = b_fw->size;
60                         fw->data = b_fw->data;
61
62                         if (buf && fw->size <= size)
63                                 memcpy(buf, fw->data, fw->size);
64                         return true;
65                 }
66         }
67
68         return false;
69 }
70
71 static bool fw_is_builtin_firmware(const struct firmware *fw)
72 {
73         struct builtin_fw *b_fw;
74
75         for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++)
76                 if (fw->data == b_fw->data)
77                         return true;
78
79         return false;
80 }
81
82 #else /* Module case - no builtin firmware support */
83
84 static inline bool fw_get_builtin_firmware(struct firmware *fw,
85                                            const char *name, void *buf,
86                                            size_t size)
87 {
88         return false;
89 }
90
91 static inline bool fw_is_builtin_firmware(const struct firmware *fw)
92 {
93         return false;
94 }
95 #endif
96
97 enum fw_status {
98         FW_STATUS_UNKNOWN,
99         FW_STATUS_LOADING,
100         FW_STATUS_DONE,
101         FW_STATUS_ABORTED,
102 };
103
104 static int loading_timeout = 60;        /* In seconds */
105
106 static inline long firmware_loading_timeout(void)
107 {
108         return loading_timeout > 0 ? loading_timeout * HZ : MAX_JIFFY_OFFSET;
109 }
110
111 /*
112  * Concurrent request_firmware() for the same firmware need to be
113  * serialized.  struct fw_state is simple state machine which hold the
114  * state of the firmware loading.
115  */
116 struct fw_state {
117         struct completion completion;
118         enum fw_status status;
119 };
120
121 static void fw_state_init(struct fw_state *fw_st)
122 {
123         init_completion(&fw_st->completion);
124         fw_st->status = FW_STATUS_UNKNOWN;
125 }
126
127 static inline bool __fw_state_is_done(enum fw_status status)
128 {
129         return status == FW_STATUS_DONE || status == FW_STATUS_ABORTED;
130 }
131
132 static int __fw_state_wait_common(struct fw_state *fw_st, long timeout)
133 {
134         long ret;
135
136         ret = wait_for_completion_killable_timeout(&fw_st->completion, timeout);
137         if (ret != 0 && fw_st->status == FW_STATUS_ABORTED)
138                 return -ENOENT;
139         if (!ret)
140                 return -ETIMEDOUT;
141
142         return ret < 0 ? ret : 0;
143 }
144
145 static void __fw_state_set(struct fw_state *fw_st,
146                            enum fw_status status)
147 {
148         WRITE_ONCE(fw_st->status, status);
149
150         if (status == FW_STATUS_DONE || status == FW_STATUS_ABORTED)
151                 complete_all(&fw_st->completion);
152 }
153
154 #define fw_state_start(fw_st)                                   \
155         __fw_state_set(fw_st, FW_STATUS_LOADING)
156 #define fw_state_done(fw_st)                                    \
157         __fw_state_set(fw_st, FW_STATUS_DONE)
158 #define fw_state_aborted(fw_st)                                 \
159         __fw_state_set(fw_st, FW_STATUS_ABORTED)
160 #define fw_state_wait(fw_st)                                    \
161         __fw_state_wait_common(fw_st, MAX_SCHEDULE_TIMEOUT)
162
163 static int __fw_state_check(struct fw_state *fw_st, enum fw_status status)
164 {
165         return fw_st->status == status;
166 }
167
168 #define fw_state_is_aborted(fw_st)                              \
169         __fw_state_check(fw_st, FW_STATUS_ABORTED)
170
171 #ifdef CONFIG_FW_LOADER_USER_HELPER
172
173 #define fw_state_aborted(fw_st)                                 \
174         __fw_state_set(fw_st, FW_STATUS_ABORTED)
175 #define fw_state_is_done(fw_st)                                 \
176         __fw_state_check(fw_st, FW_STATUS_DONE)
177 #define fw_state_is_loading(fw_st)                              \
178         __fw_state_check(fw_st, FW_STATUS_LOADING)
179 #define fw_state_wait_timeout(fw_st, timeout)                   \
180         __fw_state_wait_common(fw_st, timeout)
181
182 #endif /* CONFIG_FW_LOADER_USER_HELPER */
183
184 /* firmware behavior options */
185 #define FW_OPT_UEVENT   (1U << 0)
186 #define FW_OPT_NOWAIT   (1U << 1)
187 #ifdef CONFIG_FW_LOADER_USER_HELPER
188 #define FW_OPT_USERHELPER       (1U << 2)
189 #else
190 #define FW_OPT_USERHELPER       0
191 #endif
192 #ifdef CONFIG_FW_LOADER_USER_HELPER_FALLBACK
193 #define FW_OPT_FALLBACK         FW_OPT_USERHELPER
194 #else
195 #define FW_OPT_FALLBACK         0
196 #endif
197 #define FW_OPT_NO_WARN  (1U << 3)
198 #define FW_OPT_NOCACHE  (1U << 4)
199
200 struct firmware_cache {
201         /* firmware_buf instance will be added into the below list */
202         spinlock_t lock;
203         struct list_head head;
204         int state;
205
206 #ifdef CONFIG_PM_SLEEP
207         /*
208          * Names of firmware images which have been cached successfully
209          * will be added into the below list so that device uncache
210          * helper can trace which firmware images have been cached
211          * before.
212          */
213         spinlock_t name_lock;
214         struct list_head fw_names;
215
216         struct delayed_work work;
217
218         struct notifier_block   pm_notify;
219 #endif
220 };
221
222 struct firmware_buf {
223         struct kref ref;
224         struct list_head list;
225         struct firmware_cache *fwc;
226         struct fw_state fw_st;
227         void *data;
228         size_t size;
229         size_t allocated_size;
230 #ifdef CONFIG_FW_LOADER_USER_HELPER
231         bool is_paged_buf;
232         bool need_uevent;
233         struct page **pages;
234         int nr_pages;
235         int page_array_size;
236         struct list_head pending_list;
237 #endif
238         const char *fw_id;
239 };
240
241 struct fw_cache_entry {
242         struct list_head list;
243         const char *name;
244 };
245
246 struct fw_name_devm {
247         unsigned long magic;
248         const char *name;
249 };
250
251 #define to_fwbuf(d) container_of(d, struct firmware_buf, ref)
252
253 #define FW_LOADER_NO_CACHE      0
254 #define FW_LOADER_START_CACHE   1
255
256 static int fw_cache_piggyback_on_request(const char *name);
257
258 /* fw_lock could be moved to 'struct firmware_priv' but since it is just
259  * guarding for corner cases a global lock should be OK */
260 static DEFINE_MUTEX(fw_lock);
261
262 static struct firmware_cache fw_cache;
263
264 static struct firmware_buf *__allocate_fw_buf(const char *fw_name,
265                                               struct firmware_cache *fwc,
266                                               void *dbuf, size_t size)
267 {
268         struct firmware_buf *buf;
269
270         buf = kzalloc(sizeof(*buf), GFP_ATOMIC);
271         if (!buf)
272                 return NULL;
273
274         buf->fw_id = kstrdup_const(fw_name, GFP_ATOMIC);
275         if (!buf->fw_id) {
276                 kfree(buf);
277                 return NULL;
278         }
279
280         kref_init(&buf->ref);
281         buf->fwc = fwc;
282         buf->data = dbuf;
283         buf->allocated_size = size;
284         fw_state_init(&buf->fw_st);
285 #ifdef CONFIG_FW_LOADER_USER_HELPER
286         INIT_LIST_HEAD(&buf->pending_list);
287 #endif
288
289         pr_debug("%s: fw-%s buf=%p\n", __func__, fw_name, buf);
290
291         return buf;
292 }
293
294 static struct firmware_buf *__fw_lookup_buf(const char *fw_name)
295 {
296         struct firmware_buf *tmp;
297         struct firmware_cache *fwc = &fw_cache;
298
299         list_for_each_entry(tmp, &fwc->head, list)
300                 if (!strcmp(tmp->fw_id, fw_name))
301                         return tmp;
302         return NULL;
303 }
304
305 /* Returns 1 for batching firmware requests with the same name */
306 static int fw_lookup_and_allocate_buf(const char *fw_name,
307                                       struct firmware_cache *fwc,
308                                       struct firmware_buf **buf, void *dbuf,
309                                       size_t size)
310 {
311         struct firmware_buf *tmp;
312
313         spin_lock(&fwc->lock);
314         tmp = __fw_lookup_buf(fw_name);
315         if (tmp) {
316                 kref_get(&tmp->ref);
317                 spin_unlock(&fwc->lock);
318                 *buf = tmp;
319                 pr_debug("batched request - sharing the same struct firmware_buf and lookup for multiple requests\n");
320                 return 1;
321         }
322         tmp = __allocate_fw_buf(fw_name, fwc, dbuf, size);
323         if (tmp)
324                 list_add(&tmp->list, &fwc->head);
325         spin_unlock(&fwc->lock);
326
327         *buf = tmp;
328
329         return tmp ? 0 : -ENOMEM;
330 }
331
332 static void __fw_free_buf(struct kref *ref)
333         __releases(&fwc->lock)
334 {
335         struct firmware_buf *buf = to_fwbuf(ref);
336         struct firmware_cache *fwc = buf->fwc;
337
338         pr_debug("%s: fw-%s buf=%p data=%p size=%u\n",
339                  __func__, buf->fw_id, buf, buf->data,
340                  (unsigned int)buf->size);
341
342         list_del(&buf->list);
343         spin_unlock(&fwc->lock);
344
345 #ifdef CONFIG_FW_LOADER_USER_HELPER
346         if (buf->is_paged_buf) {
347                 int i;
348                 vunmap(buf->data);
349                 for (i = 0; i < buf->nr_pages; i++)
350                         __free_page(buf->pages[i]);
351                 vfree(buf->pages);
352         } else
353 #endif
354         if (!buf->allocated_size)
355                 vfree(buf->data);
356         kfree_const(buf->fw_id);
357         kfree(buf);
358 }
359
360 static void fw_free_buf(struct firmware_buf *buf)
361 {
362         struct firmware_cache *fwc = buf->fwc;
363         spin_lock(&fwc->lock);
364         if (!kref_put(&buf->ref, __fw_free_buf))
365                 spin_unlock(&fwc->lock);
366 }
367
368 /* direct firmware loading support */
369 static char fw_path_para[256];
370 static const char * const fw_path[] = {
371         fw_path_para,
372         "/lib/firmware/updates/" UTS_RELEASE,
373         "/lib/firmware/updates",
374         "/lib/firmware/" UTS_RELEASE,
375         "/lib/firmware"
376 };
377
378 /*
379  * Typical usage is that passing 'firmware_class.path=$CUSTOMIZED_PATH'
380  * from kernel command line because firmware_class is generally built in
381  * kernel instead of module.
382  */
383 module_param_string(path, fw_path_para, sizeof(fw_path_para), 0644);
384 MODULE_PARM_DESC(path, "customized firmware image search path with a higher priority than default path");
385
386 static int
387 fw_get_filesystem_firmware(struct device *device, struct firmware_buf *buf)
388 {
389         loff_t size;
390         int i, len;
391         int rc = -ENOENT;
392         char *path;
393         enum kernel_read_file_id id = READING_FIRMWARE;
394         size_t msize = INT_MAX;
395
396         if (ROOT_DEV == 0)
397                 return -EPROBE_DEFER;
398
399         /* Already populated data member means we're loading into a buffer */
400         if (buf->data) {
401                 id = READING_FIRMWARE_PREALLOC_BUFFER;
402                 msize = buf->allocated_size;
403         }
404
405         path = __getname();
406         if (!path)
407                 return -ENOMEM;
408
409         for (i = 0; i < ARRAY_SIZE(fw_path); i++) {
410                 /* skip the unset customized path */
411                 if (!fw_path[i][0])
412                         continue;
413
414                 len = snprintf(path, PATH_MAX, "%s/%s",
415                                fw_path[i], buf->fw_id);
416                 if (len >= PATH_MAX) {
417                         rc = -ENAMETOOLONG;
418                         break;
419                 }
420
421                 buf->size = 0;
422                 rc = kernel_read_file_from_path(path, &buf->data, &size, msize,
423                                                 id);
424                 if (rc) {
425                         if (rc == -ENOENT)
426                                 dev_dbg(device, "loading %s failed with error %d\n",
427                                          path, rc);
428                         else
429                                 dev_warn(device, "loading %s failed with error %d\n",
430                                          path, rc);
431                         continue;
432                 }
433                 dev_dbg(device, "direct-loading %s\n", buf->fw_id);
434                 buf->size = size;
435                 fw_state_done(&buf->fw_st);
436                 break;
437         }
438         __putname(path);
439
440         return rc;
441 }
442
443 /* firmware holds the ownership of pages */
444 static void firmware_free_data(const struct firmware *fw)
445 {
446         /* Loaded directly? */
447         if (!fw->priv) {
448                 vfree(fw->data);
449                 return;
450         }
451         fw_free_buf(fw->priv);
452 }
453
454 /* store the pages buffer info firmware from buf */
455 static void fw_set_page_data(struct firmware_buf *buf, struct firmware *fw)
456 {
457         fw->priv = buf;
458 #ifdef CONFIG_FW_LOADER_USER_HELPER
459         fw->pages = buf->pages;
460 #endif
461         fw->size = buf->size;
462         fw->data = buf->data;
463
464         pr_debug("%s: fw-%s buf=%p data=%p size=%u\n",
465                  __func__, buf->fw_id, buf, buf->data,
466                  (unsigned int)buf->size);
467 }
468
469 #ifdef CONFIG_PM_SLEEP
470 static void fw_name_devm_release(struct device *dev, void *res)
471 {
472         struct fw_name_devm *fwn = res;
473
474         if (fwn->magic == (unsigned long)&fw_cache)
475                 pr_debug("%s: fw_name-%s devm-%p released\n",
476                                 __func__, fwn->name, res);
477         kfree_const(fwn->name);
478 }
479
480 static int fw_devm_match(struct device *dev, void *res,
481                 void *match_data)
482 {
483         struct fw_name_devm *fwn = res;
484
485         return (fwn->magic == (unsigned long)&fw_cache) &&
486                 !strcmp(fwn->name, match_data);
487 }
488
489 static struct fw_name_devm *fw_find_devm_name(struct device *dev,
490                 const char *name)
491 {
492         struct fw_name_devm *fwn;
493
494         fwn = devres_find(dev, fw_name_devm_release,
495                           fw_devm_match, (void *)name);
496         return fwn;
497 }
498
499 /* add firmware name into devres list */
500 static int fw_add_devm_name(struct device *dev, const char *name)
501 {
502         struct fw_name_devm *fwn;
503
504         fwn = fw_find_devm_name(dev, name);
505         if (fwn)
506                 return 1;
507
508         fwn = devres_alloc(fw_name_devm_release, sizeof(struct fw_name_devm),
509                            GFP_KERNEL);
510         if (!fwn)
511                 return -ENOMEM;
512         fwn->name = kstrdup_const(name, GFP_KERNEL);
513         if (!fwn->name) {
514                 devres_free(fwn);
515                 return -ENOMEM;
516         }
517
518         fwn->magic = (unsigned long)&fw_cache;
519         devres_add(dev, fwn);
520
521         return 0;
522 }
523 #else
524 static int fw_add_devm_name(struct device *dev, const char *name)
525 {
526         return 0;
527 }
528 #endif
529
530 static int assign_firmware_buf(struct firmware *fw, struct device *device,
531                                unsigned int opt_flags)
532 {
533         struct firmware_buf *buf = fw->priv;
534
535         mutex_lock(&fw_lock);
536         if (!buf->size || fw_state_is_aborted(&buf->fw_st)) {
537                 mutex_unlock(&fw_lock);
538                 return -ENOENT;
539         }
540
541         /*
542          * add firmware name into devres list so that we can auto cache
543          * and uncache firmware for device.
544          *
545          * device may has been deleted already, but the problem
546          * should be fixed in devres or driver core.
547          */
548         /* don't cache firmware handled without uevent */
549         if (device && (opt_flags & FW_OPT_UEVENT) &&
550             !(opt_flags & FW_OPT_NOCACHE))
551                 fw_add_devm_name(device, buf->fw_id);
552
553         /*
554          * After caching firmware image is started, let it piggyback
555          * on request firmware.
556          */
557         if (!(opt_flags & FW_OPT_NOCACHE) &&
558             buf->fwc->state == FW_LOADER_START_CACHE) {
559                 if (fw_cache_piggyback_on_request(buf->fw_id))
560                         kref_get(&buf->ref);
561         }
562
563         /* pass the pages buffer to driver at the last minute */
564         fw_set_page_data(buf, fw);
565         mutex_unlock(&fw_lock);
566         return 0;
567 }
568
569 /*
570  * user-mode helper code
571  */
572 #ifdef CONFIG_FW_LOADER_USER_HELPER
573 struct firmware_priv {
574         bool nowait;
575         struct device dev;
576         struct firmware_buf *buf;
577         struct firmware *fw;
578 };
579
580 static struct firmware_priv *to_firmware_priv(struct device *dev)
581 {
582         return container_of(dev, struct firmware_priv, dev);
583 }
584
585 static void __fw_load_abort(struct firmware_buf *buf)
586 {
587         /*
588          * There is a small window in which user can write to 'loading'
589          * between loading done and disappearance of 'loading'
590          */
591         if (fw_state_is_done(&buf->fw_st))
592                 return;
593
594         list_del_init(&buf->pending_list);
595         fw_state_aborted(&buf->fw_st);
596 }
597
598 static void fw_load_abort(struct firmware_priv *fw_priv)
599 {
600         struct firmware_buf *buf = fw_priv->buf;
601
602         __fw_load_abort(buf);
603 }
604
605 static LIST_HEAD(pending_fw_head);
606
607 static void kill_pending_fw_fallback_reqs(bool only_kill_custom)
608 {
609         struct firmware_buf *buf;
610         struct firmware_buf *next;
611
612         mutex_lock(&fw_lock);
613         list_for_each_entry_safe(buf, next, &pending_fw_head, pending_list) {
614                 if (!buf->need_uevent || !only_kill_custom)
615                          __fw_load_abort(buf);
616         }
617         mutex_unlock(&fw_lock);
618 }
619
620 static ssize_t timeout_show(struct class *class, struct class_attribute *attr,
621                             char *buf)
622 {
623         return sprintf(buf, "%d\n", loading_timeout);
624 }
625
626 /**
627  * firmware_timeout_store - set number of seconds to wait for firmware
628  * @class: device class pointer
629  * @attr: device attribute pointer
630  * @buf: buffer to scan for timeout value
631  * @count: number of bytes in @buf
632  *
633  *      Sets the number of seconds to wait for the firmware.  Once
634  *      this expires an error will be returned to the driver and no
635  *      firmware will be provided.
636  *
637  *      Note: zero means 'wait forever'.
638  **/
639 static ssize_t timeout_store(struct class *class, struct class_attribute *attr,
640                              const char *buf, size_t count)
641 {
642         loading_timeout = simple_strtol(buf, NULL, 10);
643         if (loading_timeout < 0)
644                 loading_timeout = 0;
645
646         return count;
647 }
648 static CLASS_ATTR_RW(timeout);
649
650 static struct attribute *firmware_class_attrs[] = {
651         &class_attr_timeout.attr,
652         NULL,
653 };
654 ATTRIBUTE_GROUPS(firmware_class);
655
656 static void fw_dev_release(struct device *dev)
657 {
658         struct firmware_priv *fw_priv = to_firmware_priv(dev);
659
660         kfree(fw_priv);
661 }
662
663 static int do_firmware_uevent(struct firmware_priv *fw_priv, struct kobj_uevent_env *env)
664 {
665         if (add_uevent_var(env, "FIRMWARE=%s", fw_priv->buf->fw_id))
666                 return -ENOMEM;
667         if (add_uevent_var(env, "TIMEOUT=%i", loading_timeout))
668                 return -ENOMEM;
669         if (add_uevent_var(env, "ASYNC=%d", fw_priv->nowait))
670                 return -ENOMEM;
671
672         return 0;
673 }
674
675 static int firmware_uevent(struct device *dev, struct kobj_uevent_env *env)
676 {
677         struct firmware_priv *fw_priv = to_firmware_priv(dev);
678         int err = 0;
679
680         mutex_lock(&fw_lock);
681         if (fw_priv->buf)
682                 err = do_firmware_uevent(fw_priv, env);
683         mutex_unlock(&fw_lock);
684         return err;
685 }
686
687 static struct class firmware_class = {
688         .name           = "firmware",
689         .class_groups   = firmware_class_groups,
690         .dev_uevent     = firmware_uevent,
691         .dev_release    = fw_dev_release,
692 };
693
694 static ssize_t firmware_loading_show(struct device *dev,
695                                      struct device_attribute *attr, char *buf)
696 {
697         struct firmware_priv *fw_priv = to_firmware_priv(dev);
698         int loading = 0;
699
700         mutex_lock(&fw_lock);
701         if (fw_priv->buf)
702                 loading = fw_state_is_loading(&fw_priv->buf->fw_st);
703         mutex_unlock(&fw_lock);
704
705         return sprintf(buf, "%d\n", loading);
706 }
707
708 /* Some architectures don't have PAGE_KERNEL_RO */
709 #ifndef PAGE_KERNEL_RO
710 #define PAGE_KERNEL_RO PAGE_KERNEL
711 #endif
712
713 /* one pages buffer should be mapped/unmapped only once */
714 static int fw_map_pages_buf(struct firmware_buf *buf)
715 {
716         if (!buf->is_paged_buf)
717                 return 0;
718
719         vunmap(buf->data);
720         buf->data = vmap(buf->pages, buf->nr_pages, 0, PAGE_KERNEL_RO);
721         if (!buf->data)
722                 return -ENOMEM;
723         return 0;
724 }
725
726 /**
727  * firmware_loading_store - set value in the 'loading' control file
728  * @dev: device pointer
729  * @attr: device attribute pointer
730  * @buf: buffer to scan for loading control value
731  * @count: number of bytes in @buf
732  *
733  *      The relevant values are:
734  *
735  *       1: Start a load, discarding any previous partial load.
736  *       0: Conclude the load and hand the data to the driver code.
737  *      -1: Conclude the load with an error and discard any written data.
738  **/
739 static ssize_t firmware_loading_store(struct device *dev,
740                                       struct device_attribute *attr,
741                                       const char *buf, size_t count)
742 {
743         struct firmware_priv *fw_priv = to_firmware_priv(dev);
744         struct firmware_buf *fw_buf;
745         ssize_t written = count;
746         int loading = simple_strtol(buf, NULL, 10);
747         int i;
748
749         mutex_lock(&fw_lock);
750         fw_buf = fw_priv->buf;
751         if (fw_state_is_aborted(&fw_buf->fw_st))
752                 goto out;
753
754         switch (loading) {
755         case 1:
756                 /* discarding any previous partial load */
757                 if (!fw_state_is_done(&fw_buf->fw_st)) {
758                         for (i = 0; i < fw_buf->nr_pages; i++)
759                                 __free_page(fw_buf->pages[i]);
760                         vfree(fw_buf->pages);
761                         fw_buf->pages = NULL;
762                         fw_buf->page_array_size = 0;
763                         fw_buf->nr_pages = 0;
764                         fw_state_start(&fw_buf->fw_st);
765                 }
766                 break;
767         case 0:
768                 if (fw_state_is_loading(&fw_buf->fw_st)) {
769                         int rc;
770
771                         /*
772                          * Several loading requests may be pending on
773                          * one same firmware buf, so let all requests
774                          * see the mapped 'buf->data' once the loading
775                          * is completed.
776                          * */
777                         rc = fw_map_pages_buf(fw_buf);
778                         if (rc)
779                                 dev_err(dev, "%s: map pages failed\n",
780                                         __func__);
781                         else
782                                 rc = security_kernel_post_read_file(NULL,
783                                                 fw_buf->data, fw_buf->size,
784                                                 READING_FIRMWARE);
785
786                         /*
787                          * Same logic as fw_load_abort, only the DONE bit
788                          * is ignored and we set ABORT only on failure.
789                          */
790                         list_del_init(&fw_buf->pending_list);
791                         if (rc) {
792                                 fw_state_aborted(&fw_buf->fw_st);
793                                 written = rc;
794                         } else {
795                                 fw_state_done(&fw_buf->fw_st);
796                         }
797                         break;
798                 }
799                 /* fallthrough */
800         default:
801                 dev_err(dev, "%s: unexpected value (%d)\n", __func__, loading);
802                 /* fallthrough */
803         case -1:
804                 fw_load_abort(fw_priv);
805                 break;
806         }
807 out:
808         mutex_unlock(&fw_lock);
809         return written;
810 }
811
812 static DEVICE_ATTR(loading, 0644, firmware_loading_show, firmware_loading_store);
813
814 static void firmware_rw_buf(struct firmware_buf *buf, char *buffer,
815                            loff_t offset, size_t count, bool read)
816 {
817         if (read)
818                 memcpy(buffer, buf->data + offset, count);
819         else
820                 memcpy(buf->data + offset, buffer, count);
821 }
822
823 static void firmware_rw(struct firmware_buf *buf, char *buffer,
824                         loff_t offset, size_t count, bool read)
825 {
826         while (count) {
827                 void *page_data;
828                 int page_nr = offset >> PAGE_SHIFT;
829                 int page_ofs = offset & (PAGE_SIZE-1);
830                 int page_cnt = min_t(size_t, PAGE_SIZE - page_ofs, count);
831
832                 page_data = kmap(buf->pages[page_nr]);
833
834                 if (read)
835                         memcpy(buffer, page_data + page_ofs, page_cnt);
836                 else
837                         memcpy(page_data + page_ofs, buffer, page_cnt);
838
839                 kunmap(buf->pages[page_nr]);
840                 buffer += page_cnt;
841                 offset += page_cnt;
842                 count -= page_cnt;
843         }
844 }
845
846 static ssize_t firmware_data_read(struct file *filp, struct kobject *kobj,
847                                   struct bin_attribute *bin_attr,
848                                   char *buffer, loff_t offset, size_t count)
849 {
850         struct device *dev = kobj_to_dev(kobj);
851         struct firmware_priv *fw_priv = to_firmware_priv(dev);
852         struct firmware_buf *buf;
853         ssize_t ret_count;
854
855         mutex_lock(&fw_lock);
856         buf = fw_priv->buf;
857         if (!buf || fw_state_is_done(&buf->fw_st)) {
858                 ret_count = -ENODEV;
859                 goto out;
860         }
861         if (offset > buf->size) {
862                 ret_count = 0;
863                 goto out;
864         }
865         if (count > buf->size - offset)
866                 count = buf->size - offset;
867
868         ret_count = count;
869
870         if (buf->data)
871                 firmware_rw_buf(buf, buffer, offset, count, true);
872         else
873                 firmware_rw(buf, buffer, offset, count, true);
874
875 out:
876         mutex_unlock(&fw_lock);
877         return ret_count;
878 }
879
880 static int fw_realloc_buffer(struct firmware_priv *fw_priv, int min_size)
881 {
882         struct firmware_buf *buf = fw_priv->buf;
883         int pages_needed = PAGE_ALIGN(min_size) >> PAGE_SHIFT;
884
885         /* If the array of pages is too small, grow it... */
886         if (buf->page_array_size < pages_needed) {
887                 int new_array_size = max(pages_needed,
888                                          buf->page_array_size * 2);
889                 struct page **new_pages;
890
891                 new_pages = vmalloc(new_array_size * sizeof(void *));
892                 if (!new_pages) {
893                         fw_load_abort(fw_priv);
894                         return -ENOMEM;
895                 }
896                 memcpy(new_pages, buf->pages,
897                        buf->page_array_size * sizeof(void *));
898                 memset(&new_pages[buf->page_array_size], 0, sizeof(void *) *
899                        (new_array_size - buf->page_array_size));
900                 vfree(buf->pages);
901                 buf->pages = new_pages;
902                 buf->page_array_size = new_array_size;
903         }
904
905         while (buf->nr_pages < pages_needed) {
906                 buf->pages[buf->nr_pages] =
907                         alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
908
909                 if (!buf->pages[buf->nr_pages]) {
910                         fw_load_abort(fw_priv);
911                         return -ENOMEM;
912                 }
913                 buf->nr_pages++;
914         }
915         return 0;
916 }
917
918 /**
919  * firmware_data_write - write method for firmware
920  * @filp: open sysfs file
921  * @kobj: kobject for the device
922  * @bin_attr: bin_attr structure
923  * @buffer: buffer being written
924  * @offset: buffer offset for write in total data store area
925  * @count: buffer size
926  *
927  *      Data written to the 'data' attribute will be later handed to
928  *      the driver as a firmware image.
929  **/
930 static ssize_t firmware_data_write(struct file *filp, struct kobject *kobj,
931                                    struct bin_attribute *bin_attr,
932                                    char *buffer, loff_t offset, size_t count)
933 {
934         struct device *dev = kobj_to_dev(kobj);
935         struct firmware_priv *fw_priv = to_firmware_priv(dev);
936         struct firmware_buf *buf;
937         ssize_t retval;
938
939         if (!capable(CAP_SYS_RAWIO))
940                 return -EPERM;
941
942         mutex_lock(&fw_lock);
943         buf = fw_priv->buf;
944         if (!buf || fw_state_is_done(&buf->fw_st)) {
945                 retval = -ENODEV;
946                 goto out;
947         }
948
949         if (buf->data) {
950                 if (offset + count > buf->allocated_size) {
951                         retval = -ENOMEM;
952                         goto out;
953                 }
954                 firmware_rw_buf(buf, buffer, offset, count, false);
955                 retval = count;
956         } else {
957                 retval = fw_realloc_buffer(fw_priv, offset + count);
958                 if (retval)
959                         goto out;
960
961                 retval = count;
962                 firmware_rw(buf, buffer, offset, count, false);
963         }
964
965         buf->size = max_t(size_t, offset + count, buf->size);
966 out:
967         mutex_unlock(&fw_lock);
968         return retval;
969 }
970
971 static struct bin_attribute firmware_attr_data = {
972         .attr = { .name = "data", .mode = 0644 },
973         .size = 0,
974         .read = firmware_data_read,
975         .write = firmware_data_write,
976 };
977
978 static struct attribute *fw_dev_attrs[] = {
979         &dev_attr_loading.attr,
980         NULL
981 };
982
983 static struct bin_attribute *fw_dev_bin_attrs[] = {
984         &firmware_attr_data,
985         NULL
986 };
987
988 static const struct attribute_group fw_dev_attr_group = {
989         .attrs = fw_dev_attrs,
990         .bin_attrs = fw_dev_bin_attrs,
991 };
992
993 static const struct attribute_group *fw_dev_attr_groups[] = {
994         &fw_dev_attr_group,
995         NULL
996 };
997
998 static struct firmware_priv *
999 fw_create_instance(struct firmware *firmware, const char *fw_name,
1000                    struct device *device, unsigned int opt_flags)
1001 {
1002         struct firmware_priv *fw_priv;
1003         struct device *f_dev;
1004
1005         fw_priv = kzalloc(sizeof(*fw_priv), GFP_KERNEL);
1006         if (!fw_priv) {
1007                 fw_priv = ERR_PTR(-ENOMEM);
1008                 goto exit;
1009         }
1010
1011         fw_priv->nowait = !!(opt_flags & FW_OPT_NOWAIT);
1012         fw_priv->fw = firmware;
1013         f_dev = &fw_priv->dev;
1014
1015         device_initialize(f_dev);
1016         dev_set_name(f_dev, "%s", fw_name);
1017         f_dev->parent = device;
1018         f_dev->class = &firmware_class;
1019         f_dev->groups = fw_dev_attr_groups;
1020 exit:
1021         return fw_priv;
1022 }
1023
1024 /* load a firmware via user helper */
1025 static int _request_firmware_load(struct firmware_priv *fw_priv,
1026                                   unsigned int opt_flags, long timeout)
1027 {
1028         int retval = 0;
1029         struct device *f_dev = &fw_priv->dev;
1030         struct firmware_buf *buf = fw_priv->buf;
1031
1032         /* fall back on userspace loading */
1033         if (!buf->data)
1034                 buf->is_paged_buf = true;
1035
1036         dev_set_uevent_suppress(f_dev, true);
1037
1038         retval = device_add(f_dev);
1039         if (retval) {
1040                 dev_err(f_dev, "%s: device_register failed\n", __func__);
1041                 goto err_put_dev;
1042         }
1043
1044         mutex_lock(&fw_lock);
1045         list_add(&buf->pending_list, &pending_fw_head);
1046         mutex_unlock(&fw_lock);
1047
1048         if (opt_flags & FW_OPT_UEVENT) {
1049                 buf->need_uevent = true;
1050                 dev_set_uevent_suppress(f_dev, false);
1051                 dev_dbg(f_dev, "firmware: requesting %s\n", buf->fw_id);
1052                 kobject_uevent(&fw_priv->dev.kobj, KOBJ_ADD);
1053         } else {
1054                 timeout = MAX_JIFFY_OFFSET;
1055         }
1056
1057         retval = fw_state_wait_timeout(&buf->fw_st, timeout);
1058         if (retval < 0) {
1059                 mutex_lock(&fw_lock);
1060                 fw_load_abort(fw_priv);
1061                 mutex_unlock(&fw_lock);
1062         }
1063
1064         if (fw_state_is_aborted(&buf->fw_st)) {
1065                 if (retval == -ERESTARTSYS)
1066                         retval = -EINTR;
1067                 else
1068                         retval = -EAGAIN;
1069         } else if (buf->is_paged_buf && !buf->data)
1070                 retval = -ENOMEM;
1071
1072         device_del(f_dev);
1073 err_put_dev:
1074         put_device(f_dev);
1075         return retval;
1076 }
1077
1078 static int fw_load_from_user_helper(struct firmware *firmware,
1079                                     const char *name, struct device *device,
1080                                     unsigned int opt_flags)
1081 {
1082         struct firmware_priv *fw_priv;
1083         long timeout;
1084         int ret;
1085
1086         timeout = firmware_loading_timeout();
1087         if (opt_flags & FW_OPT_NOWAIT) {
1088                 timeout = usermodehelper_read_lock_wait(timeout);
1089                 if (!timeout) {
1090                         dev_dbg(device, "firmware: %s loading timed out\n",
1091                                 name);
1092                         return -EBUSY;
1093                 }
1094         } else {
1095                 ret = usermodehelper_read_trylock();
1096                 if (WARN_ON(ret)) {
1097                         dev_err(device, "firmware: %s will not be loaded\n",
1098                                 name);
1099                         return ret;
1100                 }
1101         }
1102
1103         fw_priv = fw_create_instance(firmware, name, device, opt_flags);
1104         if (IS_ERR(fw_priv)) {
1105                 ret = PTR_ERR(fw_priv);
1106                 goto out_unlock;
1107         }
1108
1109         fw_priv->buf = firmware->priv;
1110         ret = _request_firmware_load(fw_priv, opt_flags, timeout);
1111
1112         if (!ret)
1113                 ret = assign_firmware_buf(firmware, device, opt_flags);
1114
1115 out_unlock:
1116         usermodehelper_read_unlock();
1117
1118         return ret;
1119 }
1120
1121 #else /* CONFIG_FW_LOADER_USER_HELPER */
1122 static inline int
1123 fw_load_from_user_helper(struct firmware *firmware, const char *name,
1124                          struct device *device, unsigned int opt_flags)
1125 {
1126         return -ENOENT;
1127 }
1128
1129 static inline void kill_pending_fw_fallback_reqs(bool only_kill_custom) { }
1130
1131 #endif /* CONFIG_FW_LOADER_USER_HELPER */
1132
1133 /* prepare firmware and firmware_buf structs;
1134  * return 0 if a firmware is already assigned, 1 if need to load one,
1135  * or a negative error code
1136  */
1137 static int
1138 _request_firmware_prepare(struct firmware **firmware_p, const char *name,
1139                           struct device *device, void *dbuf, size_t size)
1140 {
1141         struct firmware *firmware;
1142         struct firmware_buf *buf;
1143         int ret;
1144
1145         *firmware_p = firmware = kzalloc(sizeof(*firmware), GFP_KERNEL);
1146         if (!firmware) {
1147                 dev_err(device, "%s: kmalloc(struct firmware) failed\n",
1148                         __func__);
1149                 return -ENOMEM;
1150         }
1151
1152         if (fw_get_builtin_firmware(firmware, name, dbuf, size)) {
1153                 dev_dbg(device, "using built-in %s\n", name);
1154                 return 0; /* assigned */
1155         }
1156
1157         ret = fw_lookup_and_allocate_buf(name, &fw_cache, &buf, dbuf, size);
1158
1159         /*
1160          * bind with 'buf' now to avoid warning in failure path
1161          * of requesting firmware.
1162          */
1163         firmware->priv = buf;
1164
1165         if (ret > 0) {
1166                 ret = fw_state_wait(&buf->fw_st);
1167                 if (!ret) {
1168                         fw_set_page_data(buf, firmware);
1169                         return 0; /* assigned */
1170                 }
1171         }
1172
1173         if (ret < 0)
1174                 return ret;
1175         return 1; /* need to load */
1176 }
1177
1178 /*
1179  * Batched requests need only one wake, we need to do this step last due to the
1180  * fallback mechanism. The buf is protected with kref_get(), and it won't be
1181  * released until the last user calls release_firmware().
1182  *
1183  * Failed batched requests are possible as well, in such cases we just share
1184  * the struct firmware_buf and won't release it until all requests are woken
1185  * and have gone through this same path.
1186  */
1187 static void fw_abort_batch_reqs(struct firmware *fw)
1188 {
1189         struct firmware_buf *buf;
1190
1191         /* Loaded directly? */
1192         if (!fw || !fw->priv)
1193                 return;
1194
1195         buf = fw->priv;
1196         if (!fw_state_is_aborted(&buf->fw_st))
1197                 fw_state_aborted(&buf->fw_st);
1198 }
1199
1200 /* called from request_firmware() and request_firmware_work_func() */
1201 static int
1202 _request_firmware(const struct firmware **firmware_p, const char *name,
1203                   struct device *device, void *buf, size_t size,
1204                   unsigned int opt_flags)
1205 {
1206         struct firmware *fw = NULL;
1207         int ret;
1208
1209         if (!firmware_p)
1210                 return -EINVAL;
1211
1212         if (!name || name[0] == '\0') {
1213                 ret = -EINVAL;
1214                 goto out;
1215         }
1216
1217         ret = _request_firmware_prepare(&fw, name, device, buf, size);
1218         if (ret <= 0) /* error or already assigned */
1219                 goto out;
1220
1221         ret = fw_get_filesystem_firmware(device, fw->priv);
1222         if (ret) {
1223                 if (!(opt_flags & FW_OPT_NO_WARN))
1224                         dev_warn(device,
1225                                  "Direct firmware load for %s failed with error %d\n",
1226                                  name, ret);
1227                 if (opt_flags & FW_OPT_USERHELPER) {
1228                         dev_warn(device, "Falling back to user helper\n");
1229                         ret = fw_load_from_user_helper(fw, name, device,
1230                                                        opt_flags);
1231                 }
1232         } else
1233                 ret = assign_firmware_buf(fw, device, opt_flags);
1234
1235  out:
1236         if (ret < 0) {
1237                 fw_abort_batch_reqs(fw);
1238                 release_firmware(fw);
1239                 fw = NULL;
1240         }
1241
1242         *firmware_p = fw;
1243         return ret;
1244 }
1245
1246 /**
1247  * request_firmware: - send firmware request and wait for it
1248  * @firmware_p: pointer to firmware image
1249  * @name: name of firmware file
1250  * @device: device for which firmware is being loaded
1251  *
1252  *      @firmware_p will be used to return a firmware image by the name
1253  *      of @name for device @device.
1254  *
1255  *      Should be called from user context where sleeping is allowed.
1256  *
1257  *      @name will be used as $FIRMWARE in the uevent environment and
1258  *      should be distinctive enough not to be confused with any other
1259  *      firmware image for this or any other device.
1260  *
1261  *      Caller must hold the reference count of @device.
1262  *
1263  *      The function can be called safely inside device's suspend and
1264  *      resume callback.
1265  **/
1266 int
1267 request_firmware(const struct firmware **firmware_p, const char *name,
1268                  struct device *device)
1269 {
1270         int ret;
1271
1272         /* Need to pin this module until return */
1273         __module_get(THIS_MODULE);
1274         ret = _request_firmware(firmware_p, name, device, NULL, 0,
1275                                 FW_OPT_UEVENT | FW_OPT_FALLBACK);
1276         module_put(THIS_MODULE);
1277         return ret;
1278 }
1279 EXPORT_SYMBOL(request_firmware);
1280
1281 /**
1282  * request_firmware_direct: - load firmware directly without usermode helper
1283  * @firmware_p: pointer to firmware image
1284  * @name: name of firmware file
1285  * @device: device for which firmware is being loaded
1286  *
1287  * This function works pretty much like request_firmware(), but this doesn't
1288  * fall back to usermode helper even if the firmware couldn't be loaded
1289  * directly from fs.  Hence it's useful for loading optional firmwares, which
1290  * aren't always present, without extra long timeouts of udev.
1291  **/
1292 int request_firmware_direct(const struct firmware **firmware_p,
1293                             const char *name, struct device *device)
1294 {
1295         int ret;
1296
1297         __module_get(THIS_MODULE);
1298         ret = _request_firmware(firmware_p, name, device, NULL, 0,
1299                                 FW_OPT_UEVENT | FW_OPT_NO_WARN);
1300         module_put(THIS_MODULE);
1301         return ret;
1302 }
1303 EXPORT_SYMBOL_GPL(request_firmware_direct);
1304
1305 /**
1306  * request_firmware_into_buf - load firmware into a previously allocated buffer
1307  * @firmware_p: pointer to firmware image
1308  * @name: name of firmware file
1309  * @device: device for which firmware is being loaded and DMA region allocated
1310  * @buf: address of buffer to load firmware into
1311  * @size: size of buffer
1312  *
1313  * This function works pretty much like request_firmware(), but it doesn't
1314  * allocate a buffer to hold the firmware data. Instead, the firmware
1315  * is loaded directly into the buffer pointed to by @buf and the @firmware_p
1316  * data member is pointed at @buf.
1317  *
1318  * This function doesn't cache firmware either.
1319  */
1320 int
1321 request_firmware_into_buf(const struct firmware **firmware_p, const char *name,
1322                           struct device *device, void *buf, size_t size)
1323 {
1324         int ret;
1325
1326         __module_get(THIS_MODULE);
1327         ret = _request_firmware(firmware_p, name, device, buf, size,
1328                                 FW_OPT_UEVENT | FW_OPT_FALLBACK |
1329                                 FW_OPT_NOCACHE);
1330         module_put(THIS_MODULE);
1331         return ret;
1332 }
1333 EXPORT_SYMBOL(request_firmware_into_buf);
1334
1335 /**
1336  * release_firmware: - release the resource associated with a firmware image
1337  * @fw: firmware resource to release
1338  **/
1339 void release_firmware(const struct firmware *fw)
1340 {
1341         if (fw) {
1342                 if (!fw_is_builtin_firmware(fw))
1343                         firmware_free_data(fw);
1344                 kfree(fw);
1345         }
1346 }
1347 EXPORT_SYMBOL(release_firmware);
1348
1349 /* Async support */
1350 struct firmware_work {
1351         struct work_struct work;
1352         struct module *module;
1353         const char *name;
1354         struct device *device;
1355         void *context;
1356         void (*cont)(const struct firmware *fw, void *context);
1357         unsigned int opt_flags;
1358         struct list_head node;
1359 };
1360 static LIST_HEAD(firmware_work_list);
1361 static DEFINE_SPINLOCK(firmware_work_list_lock);
1362
1363 static void request_firmware_work_func(struct work_struct *work)
1364 {
1365         struct firmware_work *fw_work;
1366         const struct firmware *fw;
1367         int err = 0;
1368
1369         fw_work = container_of(work, struct firmware_work, work);
1370
1371         err = _request_firmware(&fw, fw_work->name, fw_work->device, NULL, 0,
1372                         fw_work->opt_flags);
1373         if (err == -EPROBE_DEFER) {
1374                 spin_lock(&firmware_work_list_lock);
1375                 list_add_tail(&fw_work->node, &firmware_work_list);
1376                 spin_unlock(&firmware_work_list_lock);
1377                 return;
1378         }
1379
1380         fw_work->cont(fw, fw_work->context);
1381         put_device(fw_work->device); /* taken in request_firmware_nowait() */
1382
1383         module_put(fw_work->module);
1384         kfree_const(fw_work->name);
1385         kfree(fw_work);
1386 }
1387
1388 void retry_request_firmware(void)
1389 {
1390         struct firmware_work *fw_work;
1391
1392         spin_lock(&firmware_work_list_lock);
1393         while (!list_empty(&firmware_work_list)) {
1394                 fw_work = list_first_entry(&firmware_work_list,
1395                                            struct firmware_work, node);
1396                 list_del(&fw_work->node);
1397                 spin_unlock(&firmware_work_list_lock);
1398
1399                 request_firmware_work_func(&fw_work->work);
1400
1401                 spin_lock(&firmware_work_list_lock);
1402         }
1403         spin_unlock(&firmware_work_list_lock);
1404 }
1405
1406 /**
1407  * request_firmware_nowait - asynchronous version of request_firmware
1408  * @module: module requesting the firmware
1409  * @uevent: sends uevent to copy the firmware image if this flag
1410  *      is non-zero else the firmware copy must be done manually.
1411  * @name: name of firmware file
1412  * @device: device for which firmware is being loaded
1413  * @gfp: allocation flags
1414  * @context: will be passed over to @cont, and
1415  *      @fw may be %NULL if firmware request fails.
1416  * @cont: function will be called asynchronously when the firmware
1417  *      request is over.
1418  *
1419  *      Caller must hold the reference count of @device.
1420  *
1421  *      Asynchronous variant of request_firmware() for user contexts:
1422  *              - sleep for as small periods as possible since it may
1423  *                increase kernel boot time of built-in device drivers
1424  *                requesting firmware in their ->probe() methods, if
1425  *                @gfp is GFP_KERNEL.
1426  *
1427  *              - can't sleep at all if @gfp is GFP_ATOMIC.
1428  **/
1429 int
1430 request_firmware_nowait(
1431         struct module *module, bool uevent,
1432         const char *name, struct device *device, gfp_t gfp, void *context,
1433         void (*cont)(const struct firmware *fw, void *context))
1434 {
1435         struct firmware_work *fw_work;
1436
1437         fw_work = kzalloc(sizeof(struct firmware_work), gfp);
1438         if (!fw_work)
1439                 return -ENOMEM;
1440
1441         fw_work->module = module;
1442         fw_work->name = kstrdup_const(name, gfp);
1443         if (!fw_work->name) {
1444                 kfree(fw_work);
1445                 return -ENOMEM;
1446         }
1447         fw_work->device = device;
1448         fw_work->context = context;
1449         fw_work->cont = cont;
1450         fw_work->opt_flags = FW_OPT_NOWAIT | FW_OPT_FALLBACK |
1451                 (uevent ? FW_OPT_UEVENT : FW_OPT_USERHELPER);
1452         INIT_LIST_HEAD(&fw_work->node);
1453
1454         if (!try_module_get(module)) {
1455                 kfree_const(fw_work->name);
1456                 kfree(fw_work);
1457                 return -EFAULT;
1458         }
1459
1460         get_device(fw_work->device);
1461         INIT_WORK(&fw_work->work, request_firmware_work_func);
1462         schedule_work(&fw_work->work);
1463         return 0;
1464 }
1465 EXPORT_SYMBOL(request_firmware_nowait);
1466
1467 #ifdef CONFIG_PM_SLEEP
1468 static ASYNC_DOMAIN_EXCLUSIVE(fw_cache_domain);
1469
1470 /**
1471  * cache_firmware - cache one firmware image in kernel memory space
1472  * @fw_name: the firmware image name
1473  *
1474  * Cache firmware in kernel memory so that drivers can use it when
1475  * system isn't ready for them to request firmware image from userspace.
1476  * Once it returns successfully, driver can use request_firmware or its
1477  * nowait version to get the cached firmware without any interacting
1478  * with userspace
1479  *
1480  * Return 0 if the firmware image has been cached successfully
1481  * Return !0 otherwise
1482  *
1483  */
1484 static int cache_firmware(const char *fw_name)
1485 {
1486         int ret;
1487         const struct firmware *fw;
1488
1489         pr_debug("%s: %s\n", __func__, fw_name);
1490
1491         ret = request_firmware(&fw, fw_name, NULL);
1492         if (!ret)
1493                 kfree(fw);
1494
1495         pr_debug("%s: %s ret=%d\n", __func__, fw_name, ret);
1496
1497         return ret;
1498 }
1499
1500 static struct firmware_buf *fw_lookup_buf(const char *fw_name)
1501 {
1502         struct firmware_buf *tmp;
1503         struct firmware_cache *fwc = &fw_cache;
1504
1505         spin_lock(&fwc->lock);
1506         tmp = __fw_lookup_buf(fw_name);
1507         spin_unlock(&fwc->lock);
1508
1509         return tmp;
1510 }
1511
1512 /**
1513  * uncache_firmware - remove one cached firmware image
1514  * @fw_name: the firmware image name
1515  *
1516  * Uncache one firmware image which has been cached successfully
1517  * before.
1518  *
1519  * Return 0 if the firmware cache has been removed successfully
1520  * Return !0 otherwise
1521  *
1522  */
1523 static int uncache_firmware(const char *fw_name)
1524 {
1525         struct firmware_buf *buf;
1526         struct firmware fw;
1527
1528         pr_debug("%s: %s\n", __func__, fw_name);
1529
1530         if (fw_get_builtin_firmware(&fw, fw_name, NULL, 0))
1531                 return 0;
1532
1533         buf = fw_lookup_buf(fw_name);
1534         if (buf) {
1535                 fw_free_buf(buf);
1536                 return 0;
1537         }
1538
1539         return -EINVAL;
1540 }
1541
1542 static struct fw_cache_entry *alloc_fw_cache_entry(const char *name)
1543 {
1544         struct fw_cache_entry *fce;
1545
1546         fce = kzalloc(sizeof(*fce), GFP_ATOMIC);
1547         if (!fce)
1548                 goto exit;
1549
1550         fce->name = kstrdup_const(name, GFP_ATOMIC);
1551         if (!fce->name) {
1552                 kfree(fce);
1553                 fce = NULL;
1554                 goto exit;
1555         }
1556 exit:
1557         return fce;
1558 }
1559
1560 static int __fw_entry_found(const char *name)
1561 {
1562         struct firmware_cache *fwc = &fw_cache;
1563         struct fw_cache_entry *fce;
1564
1565         list_for_each_entry(fce, &fwc->fw_names, list) {
1566                 if (!strcmp(fce->name, name))
1567                         return 1;
1568         }
1569         return 0;
1570 }
1571
1572 static int fw_cache_piggyback_on_request(const char *name)
1573 {
1574         struct firmware_cache *fwc = &fw_cache;
1575         struct fw_cache_entry *fce;
1576         int ret = 0;
1577
1578         spin_lock(&fwc->name_lock);
1579         if (__fw_entry_found(name))
1580                 goto found;
1581
1582         fce = alloc_fw_cache_entry(name);
1583         if (fce) {
1584                 ret = 1;
1585                 list_add(&fce->list, &fwc->fw_names);
1586                 pr_debug("%s: fw: %s\n", __func__, name);
1587         }
1588 found:
1589         spin_unlock(&fwc->name_lock);
1590         return ret;
1591 }
1592
1593 static void free_fw_cache_entry(struct fw_cache_entry *fce)
1594 {
1595         kfree_const(fce->name);
1596         kfree(fce);
1597 }
1598
1599 static void __async_dev_cache_fw_image(void *fw_entry,
1600                                        async_cookie_t cookie)
1601 {
1602         struct fw_cache_entry *fce = fw_entry;
1603         struct firmware_cache *fwc = &fw_cache;
1604         int ret;
1605
1606         ret = cache_firmware(fce->name);
1607         if (ret) {
1608                 spin_lock(&fwc->name_lock);
1609                 list_del(&fce->list);
1610                 spin_unlock(&fwc->name_lock);
1611
1612                 free_fw_cache_entry(fce);
1613         }
1614 }
1615
1616 /* called with dev->devres_lock held */
1617 static void dev_create_fw_entry(struct device *dev, void *res,
1618                                 void *data)
1619 {
1620         struct fw_name_devm *fwn = res;
1621         const char *fw_name = fwn->name;
1622         struct list_head *head = data;
1623         struct fw_cache_entry *fce;
1624
1625         fce = alloc_fw_cache_entry(fw_name);
1626         if (fce)
1627                 list_add(&fce->list, head);
1628 }
1629
1630 static int devm_name_match(struct device *dev, void *res,
1631                            void *match_data)
1632 {
1633         struct fw_name_devm *fwn = res;
1634         return (fwn->magic == (unsigned long)match_data);
1635 }
1636
1637 static void dev_cache_fw_image(struct device *dev, void *data)
1638 {
1639         LIST_HEAD(todo);
1640         struct fw_cache_entry *fce;
1641         struct fw_cache_entry *fce_next;
1642         struct firmware_cache *fwc = &fw_cache;
1643
1644         devres_for_each_res(dev, fw_name_devm_release,
1645                             devm_name_match, &fw_cache,
1646                             dev_create_fw_entry, &todo);
1647
1648         list_for_each_entry_safe(fce, fce_next, &todo, list) {
1649                 list_del(&fce->list);
1650
1651                 spin_lock(&fwc->name_lock);
1652                 /* only one cache entry for one firmware */
1653                 if (!__fw_entry_found(fce->name)) {
1654                         list_add(&fce->list, &fwc->fw_names);
1655                 } else {
1656                         free_fw_cache_entry(fce);
1657                         fce = NULL;
1658                 }
1659                 spin_unlock(&fwc->name_lock);
1660
1661                 if (fce)
1662                         async_schedule_domain(__async_dev_cache_fw_image,
1663                                               (void *)fce,
1664                                               &fw_cache_domain);
1665         }
1666 }
1667
1668 static void __device_uncache_fw_images(void)
1669 {
1670         struct firmware_cache *fwc = &fw_cache;
1671         struct fw_cache_entry *fce;
1672
1673         spin_lock(&fwc->name_lock);
1674         while (!list_empty(&fwc->fw_names)) {
1675                 fce = list_entry(fwc->fw_names.next,
1676                                 struct fw_cache_entry, list);
1677                 list_del(&fce->list);
1678                 spin_unlock(&fwc->name_lock);
1679
1680                 uncache_firmware(fce->name);
1681                 free_fw_cache_entry(fce);
1682
1683                 spin_lock(&fwc->name_lock);
1684         }
1685         spin_unlock(&fwc->name_lock);
1686 }
1687
1688 /**
1689  * device_cache_fw_images - cache devices' firmware
1690  *
1691  * If one device called request_firmware or its nowait version
1692  * successfully before, the firmware names are recored into the
1693  * device's devres link list, so device_cache_fw_images can call
1694  * cache_firmware() to cache these firmwares for the device,
1695  * then the device driver can load its firmwares easily at
1696  * time when system is not ready to complete loading firmware.
1697  */
1698 static void device_cache_fw_images(void)
1699 {
1700         struct firmware_cache *fwc = &fw_cache;
1701         int old_timeout;
1702         DEFINE_WAIT(wait);
1703
1704         pr_debug("%s\n", __func__);
1705
1706         /* cancel uncache work */
1707         cancel_delayed_work_sync(&fwc->work);
1708
1709         /*
1710          * use small loading timeout for caching devices' firmware
1711          * because all these firmware images have been loaded
1712          * successfully at lease once, also system is ready for
1713          * completing firmware loading now. The maximum size of
1714          * firmware in current distributions is about 2M bytes,
1715          * so 10 secs should be enough.
1716          */
1717         old_timeout = loading_timeout;
1718         loading_timeout = 10;
1719
1720         mutex_lock(&fw_lock);
1721         fwc->state = FW_LOADER_START_CACHE;
1722         dpm_for_each_dev(NULL, dev_cache_fw_image);
1723         mutex_unlock(&fw_lock);
1724
1725         /* wait for completion of caching firmware for all devices */
1726         async_synchronize_full_domain(&fw_cache_domain);
1727
1728         loading_timeout = old_timeout;
1729 }
1730
1731 /**
1732  * device_uncache_fw_images - uncache devices' firmware
1733  *
1734  * uncache all firmwares which have been cached successfully
1735  * by device_uncache_fw_images earlier
1736  */
1737 static void device_uncache_fw_images(void)
1738 {
1739         pr_debug("%s\n", __func__);
1740         __device_uncache_fw_images();
1741 }
1742
1743 static void device_uncache_fw_images_work(struct work_struct *work)
1744 {
1745         device_uncache_fw_images();
1746 }
1747
1748 /**
1749  * device_uncache_fw_images_delay - uncache devices firmwares
1750  * @delay: number of milliseconds to delay uncache device firmwares
1751  *
1752  * uncache all devices's firmwares which has been cached successfully
1753  * by device_cache_fw_images after @delay milliseconds.
1754  */
1755 static void device_uncache_fw_images_delay(unsigned long delay)
1756 {
1757         queue_delayed_work(system_power_efficient_wq, &fw_cache.work,
1758                            msecs_to_jiffies(delay));
1759 }
1760
1761 static int fw_pm_notify(struct notifier_block *notify_block,
1762                         unsigned long mode, void *unused)
1763 {
1764         switch (mode) {
1765         case PM_HIBERNATION_PREPARE:
1766         case PM_SUSPEND_PREPARE:
1767         case PM_RESTORE_PREPARE:
1768                 /*
1769                  * kill pending fallback requests with a custom fallback
1770                  * to avoid stalling suspend.
1771                  */
1772                 kill_pending_fw_fallback_reqs(true);
1773                 device_cache_fw_images();
1774                 break;
1775
1776         case PM_POST_SUSPEND:
1777         case PM_POST_HIBERNATION:
1778         case PM_POST_RESTORE:
1779                 /*
1780                  * In case that system sleep failed and syscore_suspend is
1781                  * not called.
1782                  */
1783                 mutex_lock(&fw_lock);
1784                 fw_cache.state = FW_LOADER_NO_CACHE;
1785                 mutex_unlock(&fw_lock);
1786
1787                 device_uncache_fw_images_delay(10 * MSEC_PER_SEC);
1788                 break;
1789         }
1790
1791         return 0;
1792 }
1793
1794 /* stop caching firmware once syscore_suspend is reached */
1795 static int fw_suspend(void)
1796 {
1797         fw_cache.state = FW_LOADER_NO_CACHE;
1798         return 0;
1799 }
1800
1801 static struct syscore_ops fw_syscore_ops = {
1802         .suspend = fw_suspend,
1803 };
1804 #else
1805 static int fw_cache_piggyback_on_request(const char *name)
1806 {
1807         return 0;
1808 }
1809 #endif
1810
1811 static void __init fw_cache_init(void)
1812 {
1813         spin_lock_init(&fw_cache.lock);
1814         INIT_LIST_HEAD(&fw_cache.head);
1815         fw_cache.state = FW_LOADER_NO_CACHE;
1816
1817 #ifdef CONFIG_PM_SLEEP
1818         spin_lock_init(&fw_cache.name_lock);
1819         INIT_LIST_HEAD(&fw_cache.fw_names);
1820
1821         INIT_DELAYED_WORK(&fw_cache.work,
1822                           device_uncache_fw_images_work);
1823
1824         fw_cache.pm_notify.notifier_call = fw_pm_notify;
1825         register_pm_notifier(&fw_cache.pm_notify);
1826
1827         register_syscore_ops(&fw_syscore_ops);
1828 #endif
1829 }
1830
1831 static int fw_shutdown_notify(struct notifier_block *unused1,
1832                               unsigned long unused2, void *unused3)
1833 {
1834         /*
1835          * Kill all pending fallback requests to avoid both stalling shutdown,
1836          * and avoid a deadlock with the usermode_lock.
1837          */
1838         kill_pending_fw_fallback_reqs(false);
1839
1840         return NOTIFY_DONE;
1841 }
1842
1843 static struct notifier_block fw_shutdown_nb = {
1844         .notifier_call = fw_shutdown_notify,
1845 };
1846
1847 static int __init firmware_class_init(void)
1848 {
1849         fw_cache_init();
1850         register_reboot_notifier(&fw_shutdown_nb);
1851 #ifdef CONFIG_FW_LOADER_USER_HELPER
1852         return class_register(&firmware_class);
1853 #else
1854         return 0;
1855 #endif
1856 }
1857
1858 static void __exit firmware_class_exit(void)
1859 {
1860 #ifdef CONFIG_PM_SLEEP
1861         unregister_syscore_ops(&fw_syscore_ops);
1862         unregister_pm_notifier(&fw_cache.pm_notify);
1863 #endif
1864         unregister_reboot_notifier(&fw_shutdown_nb);
1865 #ifdef CONFIG_FW_LOADER_USER_HELPER
1866         class_unregister(&firmware_class);
1867 #endif
1868 }
1869
1870 fs_initcall(firmware_class_init);
1871 module_exit(firmware_class_exit);