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