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