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