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