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