1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * main.c - Multi purpose firmware loading support
4  *
5  * Copyright (c) 2003 Manuel Estrada Sainz
6  *
7  * Please see Documentation/firmware_class/ for more information.
8  *
9  */
10 
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/capability.h>
14 #include <linux/device.h>
15 #include <linux/module.h>
16 #include <linux/init.h>
17 #include <linux/timer.h>
18 #include <linux/vmalloc.h>
19 #include <linux/interrupt.h>
20 #include <linux/bitops.h>
21 #include <linux/mutex.h>
22 #include <linux/workqueue.h>
23 #include <linux/highmem.h>
24 #include <linux/firmware.h>
25 #include <linux/slab.h>
26 #include <linux/sched.h>
27 #include <linux/file.h>
28 #include <linux/list.h>
29 #include <linux/fs.h>
30 #include <linux/async.h>
31 #include <linux/pm.h>
32 #include <linux/suspend.h>
33 #include <linux/syscore_ops.h>
34 #include <linux/reboot.h>
35 #include <linux/security.h>
36 
37 #include <generated/utsrelease.h>
38 
39 #include "../base.h"
40 #include "firmware.h"
41 #include "fallback.h"
42 
43 MODULE_AUTHOR("Manuel Estrada Sainz");
44 MODULE_DESCRIPTION("Multi purpose firmware loading support");
45 MODULE_LICENSE("GPL");
46 
47 struct firmware_cache {
48 	/* firmware_buf instance will be added into the below list */
49 	spinlock_t lock;
50 	struct list_head head;
51 	int state;
52 
53 #ifdef CONFIG_PM_SLEEP
54 	/*
55 	 * Names of firmware images which have been cached successfully
56 	 * will be added into the below list so that device uncache
57 	 * helper can trace which firmware images have been cached
58 	 * before.
59 	 */
60 	spinlock_t name_lock;
61 	struct list_head fw_names;
62 
63 	struct delayed_work work;
64 
65 	struct notifier_block   pm_notify;
66 #endif
67 };
68 
69 struct fw_cache_entry {
70 	struct list_head list;
71 	const char *name;
72 };
73 
74 struct fw_name_devm {
75 	unsigned long magic;
76 	const char *name;
77 };
78 
79 static inline struct fw_priv *to_fw_priv(struct kref *ref)
80 {
81 	return container_of(ref, struct fw_priv, ref);
82 }
83 
84 #define	FW_LOADER_NO_CACHE	0
85 #define	FW_LOADER_START_CACHE	1
86 
87 /* fw_lock could be moved to 'struct fw_sysfs' but since it is just
88  * guarding for corner cases a global lock should be OK */
89 DEFINE_MUTEX(fw_lock);
90 
91 static struct firmware_cache fw_cache;
92 
93 /* Builtin firmware support */
94 
95 #ifdef CONFIG_FW_LOADER
96 
97 extern struct builtin_fw __start_builtin_fw[];
98 extern struct builtin_fw __end_builtin_fw[];
99 
100 static void fw_copy_to_prealloc_buf(struct firmware *fw,
101 				    void *buf, size_t size)
102 {
103 	if (!buf || size < fw->size)
104 		return;
105 	memcpy(buf, fw->data, fw->size);
106 }
107 
108 static bool fw_get_builtin_firmware(struct firmware *fw, const char *name,
109 				    void *buf, size_t size)
110 {
111 	struct builtin_fw *b_fw;
112 
113 	for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++) {
114 		if (strcmp(name, b_fw->name) == 0) {
115 			fw->size = b_fw->size;
116 			fw->data = b_fw->data;
117 			fw_copy_to_prealloc_buf(fw, buf, size);
118 
119 			return true;
120 		}
121 	}
122 
123 	return false;
124 }
125 
126 static bool fw_is_builtin_firmware(const struct firmware *fw)
127 {
128 	struct builtin_fw *b_fw;
129 
130 	for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++)
131 		if (fw->data == b_fw->data)
132 			return true;
133 
134 	return false;
135 }
136 
137 #else /* Module case - no builtin firmware support */
138 
139 static inline bool fw_get_builtin_firmware(struct firmware *fw,
140 					   const char *name, void *buf,
141 					   size_t size)
142 {
143 	return false;
144 }
145 
146 static inline bool fw_is_builtin_firmware(const struct firmware *fw)
147 {
148 	return false;
149 }
150 #endif
151 
152 static void fw_state_init(struct fw_priv *fw_priv)
153 {
154 	struct fw_state *fw_st = &fw_priv->fw_st;
155 
156 	init_completion(&fw_st->completion);
157 	fw_st->status = FW_STATUS_UNKNOWN;
158 }
159 
160 static inline int fw_state_wait(struct fw_priv *fw_priv)
161 {
162 	return __fw_state_wait_common(fw_priv, MAX_SCHEDULE_TIMEOUT);
163 }
164 
165 static int fw_cache_piggyback_on_request(const char *name);
166 
167 static struct fw_priv *__allocate_fw_priv(const char *fw_name,
168 					  struct firmware_cache *fwc,
169 					  void *dbuf, size_t size)
170 {
171 	struct fw_priv *fw_priv;
172 
173 	fw_priv = kzalloc(sizeof(*fw_priv), GFP_ATOMIC);
174 	if (!fw_priv)
175 		return NULL;
176 
177 	fw_priv->fw_name = kstrdup_const(fw_name, GFP_ATOMIC);
178 	if (!fw_priv->fw_name) {
179 		kfree(fw_priv);
180 		return NULL;
181 	}
182 
183 	kref_init(&fw_priv->ref);
184 	fw_priv->fwc = fwc;
185 	fw_priv->data = dbuf;
186 	fw_priv->allocated_size = size;
187 	fw_state_init(fw_priv);
188 #ifdef CONFIG_FW_LOADER_USER_HELPER
189 	INIT_LIST_HEAD(&fw_priv->pending_list);
190 #endif
191 
192 	pr_debug("%s: fw-%s fw_priv=%p\n", __func__, fw_name, fw_priv);
193 
194 	return fw_priv;
195 }
196 
197 static struct fw_priv *__lookup_fw_priv(const char *fw_name)
198 {
199 	struct fw_priv *tmp;
200 	struct firmware_cache *fwc = &fw_cache;
201 
202 	list_for_each_entry(tmp, &fwc->head, list)
203 		if (!strcmp(tmp->fw_name, fw_name))
204 			return tmp;
205 	return NULL;
206 }
207 
208 /* Returns 1 for batching firmware requests with the same name */
209 static int alloc_lookup_fw_priv(const char *fw_name,
210 				struct firmware_cache *fwc,
211 				struct fw_priv **fw_priv, void *dbuf,
212 				size_t size, enum fw_opt opt_flags)
213 {
214 	struct fw_priv *tmp;
215 
216 	spin_lock(&fwc->lock);
217 	if (!(opt_flags & FW_OPT_NOCACHE)) {
218 		tmp = __lookup_fw_priv(fw_name);
219 		if (tmp) {
220 			kref_get(&tmp->ref);
221 			spin_unlock(&fwc->lock);
222 			*fw_priv = tmp;
223 			pr_debug("batched request - sharing the same struct fw_priv and lookup for multiple requests\n");
224 			return 1;
225 		}
226 	}
227 
228 	tmp = __allocate_fw_priv(fw_name, fwc, dbuf, size);
229 	if (tmp) {
230 		INIT_LIST_HEAD(&tmp->list);
231 		if (!(opt_flags & FW_OPT_NOCACHE))
232 			list_add(&tmp->list, &fwc->head);
233 	}
234 	spin_unlock(&fwc->lock);
235 
236 	*fw_priv = tmp;
237 
238 	return tmp ? 0 : -ENOMEM;
239 }
240 
241 static void __free_fw_priv(struct kref *ref)
242 	__releases(&fwc->lock)
243 {
244 	struct fw_priv *fw_priv = to_fw_priv(ref);
245 	struct firmware_cache *fwc = fw_priv->fwc;
246 
247 	pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
248 		 __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
249 		 (unsigned int)fw_priv->size);
250 
251 	list_del(&fw_priv->list);
252 	spin_unlock(&fwc->lock);
253 
254 #ifdef CONFIG_FW_LOADER_USER_HELPER
255 	if (fw_priv->is_paged_buf) {
256 		int i;
257 		vunmap(fw_priv->data);
258 		for (i = 0; i < fw_priv->nr_pages; i++)
259 			__free_page(fw_priv->pages[i]);
260 		vfree(fw_priv->pages);
261 	} else
262 #endif
263 	if (!fw_priv->allocated_size)
264 		vfree(fw_priv->data);
265 	kfree_const(fw_priv->fw_name);
266 	kfree(fw_priv);
267 }
268 
269 static void free_fw_priv(struct fw_priv *fw_priv)
270 {
271 	struct firmware_cache *fwc = fw_priv->fwc;
272 	spin_lock(&fwc->lock);
273 	if (!kref_put(&fw_priv->ref, __free_fw_priv))
274 		spin_unlock(&fwc->lock);
275 }
276 
277 /* direct firmware loading support */
278 static char fw_path_para[256];
279 static const char * const fw_path[] = {
280 	fw_path_para,
281 	"/lib/firmware/updates/" UTS_RELEASE,
282 	"/lib/firmware/updates",
283 	"/lib/firmware/" UTS_RELEASE,
284 	"/lib/firmware"
285 };
286 
287 /*
288  * Typical usage is that passing 'firmware_class.path=$CUSTOMIZED_PATH'
289  * from kernel command line because firmware_class is generally built in
290  * kernel instead of module.
291  */
292 module_param_string(path, fw_path_para, sizeof(fw_path_para), 0644);
293 MODULE_PARM_DESC(path, "customized firmware image search path with a higher priority than default path");
294 
295 static int
296 fw_get_filesystem_firmware(struct device *device, struct fw_priv *fw_priv)
297 {
298 	loff_t size;
299 	int i, len;
300 	int rc = -ENOENT;
301 	char *path;
302 	enum kernel_read_file_id id = READING_FIRMWARE;
303 	size_t msize = INT_MAX;
304 
305 	/* Already populated data member means we're loading into a buffer */
306 	if (fw_priv->data) {
307 		id = READING_FIRMWARE_PREALLOC_BUFFER;
308 		msize = fw_priv->allocated_size;
309 	}
310 
311 	path = __getname();
312 	if (!path)
313 		return -ENOMEM;
314 
315 	for (i = 0; i < ARRAY_SIZE(fw_path); i++) {
316 		/* skip the unset customized path */
317 		if (!fw_path[i][0])
318 			continue;
319 
320 		len = snprintf(path, PATH_MAX, "%s/%s",
321 			       fw_path[i], fw_priv->fw_name);
322 		if (len >= PATH_MAX) {
323 			rc = -ENAMETOOLONG;
324 			break;
325 		}
326 
327 		fw_priv->size = 0;
328 		rc = kernel_read_file_from_path(path, &fw_priv->data, &size,
329 						msize, id);
330 		if (rc) {
331 			if (rc == -ENOENT)
332 				dev_dbg(device, "loading %s failed with error %d\n",
333 					 path, rc);
334 			else
335 				dev_warn(device, "loading %s failed with error %d\n",
336 					 path, rc);
337 			continue;
338 		}
339 		dev_dbg(device, "direct-loading %s\n", fw_priv->fw_name);
340 		fw_priv->size = size;
341 		fw_state_done(fw_priv);
342 		break;
343 	}
344 	__putname(path);
345 
346 	return rc;
347 }
348 
349 /* firmware holds the ownership of pages */
350 static void firmware_free_data(const struct firmware *fw)
351 {
352 	/* Loaded directly? */
353 	if (!fw->priv) {
354 		vfree(fw->data);
355 		return;
356 	}
357 	free_fw_priv(fw->priv);
358 }
359 
360 /* store the pages buffer info firmware from buf */
361 static void fw_set_page_data(struct fw_priv *fw_priv, struct firmware *fw)
362 {
363 	fw->priv = fw_priv;
364 #ifdef CONFIG_FW_LOADER_USER_HELPER
365 	fw->pages = fw_priv->pages;
366 #endif
367 	fw->size = fw_priv->size;
368 	fw->data = fw_priv->data;
369 
370 	pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
371 		 __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
372 		 (unsigned int)fw_priv->size);
373 }
374 
375 #ifdef CONFIG_PM_SLEEP
376 static void fw_name_devm_release(struct device *dev, void *res)
377 {
378 	struct fw_name_devm *fwn = res;
379 
380 	if (fwn->magic == (unsigned long)&fw_cache)
381 		pr_debug("%s: fw_name-%s devm-%p released\n",
382 				__func__, fwn->name, res);
383 	kfree_const(fwn->name);
384 }
385 
386 static int fw_devm_match(struct device *dev, void *res,
387 		void *match_data)
388 {
389 	struct fw_name_devm *fwn = res;
390 
391 	return (fwn->magic == (unsigned long)&fw_cache) &&
392 		!strcmp(fwn->name, match_data);
393 }
394 
395 static struct fw_name_devm *fw_find_devm_name(struct device *dev,
396 		const char *name)
397 {
398 	struct fw_name_devm *fwn;
399 
400 	fwn = devres_find(dev, fw_name_devm_release,
401 			  fw_devm_match, (void *)name);
402 	return fwn;
403 }
404 
405 static bool fw_cache_is_setup(struct device *dev, const char *name)
406 {
407 	struct fw_name_devm *fwn;
408 
409 	fwn = fw_find_devm_name(dev, name);
410 	if (fwn)
411 		return true;
412 
413 	return false;
414 }
415 
416 /* add firmware name into devres list */
417 static int fw_add_devm_name(struct device *dev, const char *name)
418 {
419 	struct fw_name_devm *fwn;
420 
421 	if (fw_cache_is_setup(dev, name))
422 		return 0;
423 
424 	fwn = devres_alloc(fw_name_devm_release, sizeof(struct fw_name_devm),
425 			   GFP_KERNEL);
426 	if (!fwn)
427 		return -ENOMEM;
428 	fwn->name = kstrdup_const(name, GFP_KERNEL);
429 	if (!fwn->name) {
430 		devres_free(fwn);
431 		return -ENOMEM;
432 	}
433 
434 	fwn->magic = (unsigned long)&fw_cache;
435 	devres_add(dev, fwn);
436 
437 	return 0;
438 }
439 #else
440 static bool fw_cache_is_setup(struct device *dev, const char *name)
441 {
442 	return false;
443 }
444 
445 static int fw_add_devm_name(struct device *dev, const char *name)
446 {
447 	return 0;
448 }
449 #endif
450 
451 int assign_fw(struct firmware *fw, struct device *device,
452 	      enum fw_opt opt_flags)
453 {
454 	struct fw_priv *fw_priv = fw->priv;
455 	int ret;
456 
457 	mutex_lock(&fw_lock);
458 	if (!fw_priv->size || fw_state_is_aborted(fw_priv)) {
459 		mutex_unlock(&fw_lock);
460 		return -ENOENT;
461 	}
462 
463 	/*
464 	 * add firmware name into devres list so that we can auto cache
465 	 * and uncache firmware for device.
466 	 *
467 	 * device may has been deleted already, but the problem
468 	 * should be fixed in devres or driver core.
469 	 */
470 	/* don't cache firmware handled without uevent */
471 	if (device && (opt_flags & FW_OPT_UEVENT) &&
472 	    !(opt_flags & FW_OPT_NOCACHE)) {
473 		ret = fw_add_devm_name(device, fw_priv->fw_name);
474 		if (ret) {
475 			mutex_unlock(&fw_lock);
476 			return ret;
477 		}
478 	}
479 
480 	/*
481 	 * After caching firmware image is started, let it piggyback
482 	 * on request firmware.
483 	 */
484 	if (!(opt_flags & FW_OPT_NOCACHE) &&
485 	    fw_priv->fwc->state == FW_LOADER_START_CACHE) {
486 		if (fw_cache_piggyback_on_request(fw_priv->fw_name))
487 			kref_get(&fw_priv->ref);
488 	}
489 
490 	/* pass the pages buffer to driver at the last minute */
491 	fw_set_page_data(fw_priv, fw);
492 	mutex_unlock(&fw_lock);
493 	return 0;
494 }
495 
496 /* prepare firmware and firmware_buf structs;
497  * return 0 if a firmware is already assigned, 1 if need to load one,
498  * or a negative error code
499  */
500 static int
501 _request_firmware_prepare(struct firmware **firmware_p, const char *name,
502 			  struct device *device, void *dbuf, size_t size,
503 			  enum fw_opt opt_flags)
504 {
505 	struct firmware *firmware;
506 	struct fw_priv *fw_priv;
507 	int ret;
508 
509 	*firmware_p = firmware = kzalloc(sizeof(*firmware), GFP_KERNEL);
510 	if (!firmware) {
511 		dev_err(device, "%s: kmalloc(struct firmware) failed\n",
512 			__func__);
513 		return -ENOMEM;
514 	}
515 
516 	if (fw_get_builtin_firmware(firmware, name, dbuf, size)) {
517 		dev_dbg(device, "using built-in %s\n", name);
518 		return 0; /* assigned */
519 	}
520 
521 	ret = alloc_lookup_fw_priv(name, &fw_cache, &fw_priv, dbuf, size,
522 				  opt_flags);
523 
524 	/*
525 	 * bind with 'priv' now to avoid warning in failure path
526 	 * of requesting firmware.
527 	 */
528 	firmware->priv = fw_priv;
529 
530 	if (ret > 0) {
531 		ret = fw_state_wait(fw_priv);
532 		if (!ret) {
533 			fw_set_page_data(fw_priv, firmware);
534 			return 0; /* assigned */
535 		}
536 	}
537 
538 	if (ret < 0)
539 		return ret;
540 	return 1; /* need to load */
541 }
542 
543 /*
544  * Batched requests need only one wake, we need to do this step last due to the
545  * fallback mechanism. The buf is protected with kref_get(), and it won't be
546  * released until the last user calls release_firmware().
547  *
548  * Failed batched requests are possible as well, in such cases we just share
549  * the struct fw_priv and won't release it until all requests are woken
550  * and have gone through this same path.
551  */
552 static void fw_abort_batch_reqs(struct firmware *fw)
553 {
554 	struct fw_priv *fw_priv;
555 
556 	/* Loaded directly? */
557 	if (!fw || !fw->priv)
558 		return;
559 
560 	fw_priv = fw->priv;
561 	if (!fw_state_is_aborted(fw_priv))
562 		fw_state_aborted(fw_priv);
563 }
564 
565 /* called from request_firmware() and request_firmware_work_func() */
566 static int
567 _request_firmware(const struct firmware **firmware_p, const char *name,
568 		  struct device *device, void *buf, size_t size,
569 		  enum fw_opt opt_flags)
570 {
571 	struct firmware *fw = NULL;
572 	int ret;
573 
574 	if (!firmware_p)
575 		return -EINVAL;
576 
577 	if (!name || name[0] == '\0') {
578 		ret = -EINVAL;
579 		goto out;
580 	}
581 
582 	ret = _request_firmware_prepare(&fw, name, device, buf, size,
583 					opt_flags);
584 	if (ret <= 0) /* error or already assigned */
585 		goto out;
586 
587 	ret = fw_get_filesystem_firmware(device, fw->priv);
588 	if (ret) {
589 		if (!(opt_flags & FW_OPT_NO_WARN))
590 			dev_warn(device,
591 				 "Direct firmware load for %s failed with error %d\n",
592 				 name, ret);
593 		ret = firmware_fallback_sysfs(fw, name, device, opt_flags, ret);
594 	} else
595 		ret = assign_fw(fw, device, opt_flags);
596 
597  out:
598 	if (ret < 0) {
599 		fw_abort_batch_reqs(fw);
600 		release_firmware(fw);
601 		fw = NULL;
602 	}
603 
604 	*firmware_p = fw;
605 	return ret;
606 }
607 
608 /**
609  * request_firmware() - send firmware request and wait for it
610  * @firmware_p: pointer to firmware image
611  * @name: name of firmware file
612  * @device: device for which firmware is being loaded
613  *
614  *      @firmware_p will be used to return a firmware image by the name
615  *      of @name for device @device.
616  *
617  *      Should be called from user context where sleeping is allowed.
618  *
619  *      @name will be used as $FIRMWARE in the uevent environment and
620  *      should be distinctive enough not to be confused with any other
621  *      firmware image for this or any other device.
622  *
623  *	Caller must hold the reference count of @device.
624  *
625  *	The function can be called safely inside device's suspend and
626  *	resume callback.
627  **/
628 int
629 request_firmware(const struct firmware **firmware_p, const char *name,
630 		 struct device *device)
631 {
632 	int ret;
633 
634 	/* Need to pin this module until return */
635 	__module_get(THIS_MODULE);
636 	ret = _request_firmware(firmware_p, name, device, NULL, 0,
637 				FW_OPT_UEVENT);
638 	module_put(THIS_MODULE);
639 	return ret;
640 }
641 EXPORT_SYMBOL(request_firmware);
642 
643 /**
644  * firmware_request_nowarn() - request for an optional fw module
645  * @firmware: pointer to firmware image
646  * @name: name of firmware file
647  * @device: device for which firmware is being loaded
648  *
649  * This function is similar in behaviour to request_firmware(), except
650  * it doesn't produce warning messages when the file is not found.
651  * The sysfs fallback mechanism is enabled if direct filesystem lookup fails,
652  * however, however failures to find the firmware file with it are still
653  * suppressed. It is therefore up to the driver to check for the return value
654  * of this call and to decide when to inform the users of errors.
655  **/
656 int firmware_request_nowarn(const struct firmware **firmware, const char *name,
657 			    struct device *device)
658 {
659 	int ret;
660 
661 	/* Need to pin this module until return */
662 	__module_get(THIS_MODULE);
663 	ret = _request_firmware(firmware, name, device, NULL, 0,
664 				FW_OPT_UEVENT | FW_OPT_NO_WARN);
665 	module_put(THIS_MODULE);
666 	return ret;
667 }
668 EXPORT_SYMBOL_GPL(firmware_request_nowarn);
669 
670 /**
671  * request_firmware_direct() - load firmware directly without usermode helper
672  * @firmware_p: pointer to firmware image
673  * @name: name of firmware file
674  * @device: device for which firmware is being loaded
675  *
676  * This function works pretty much like request_firmware(), but this doesn't
677  * fall back to usermode helper even if the firmware couldn't be loaded
678  * directly from fs.  Hence it's useful for loading optional firmwares, which
679  * aren't always present, without extra long timeouts of udev.
680  **/
681 int request_firmware_direct(const struct firmware **firmware_p,
682 			    const char *name, struct device *device)
683 {
684 	int ret;
685 
686 	__module_get(THIS_MODULE);
687 	ret = _request_firmware(firmware_p, name, device, NULL, 0,
688 				FW_OPT_UEVENT | FW_OPT_NO_WARN |
689 				FW_OPT_NOFALLBACK);
690 	module_put(THIS_MODULE);
691 	return ret;
692 }
693 EXPORT_SYMBOL_GPL(request_firmware_direct);
694 
695 /**
696  * firmware_request_cache() - cache firmware for suspend so resume can use it
697  * @name: name of firmware file
698  * @device: device for which firmware should be cached for
699  *
700  * There are some devices with an optimization that enables the device to not
701  * require loading firmware on system reboot. This optimization may still
702  * require the firmware present on resume from suspend. This routine can be
703  * used to ensure the firmware is present on resume from suspend in these
704  * situations. This helper is not compatible with drivers which use
705  * request_firmware_into_buf() or request_firmware_nowait() with no uevent set.
706  **/
707 int firmware_request_cache(struct device *device, const char *name)
708 {
709 	int ret;
710 
711 	mutex_lock(&fw_lock);
712 	ret = fw_add_devm_name(device, name);
713 	mutex_unlock(&fw_lock);
714 
715 	return ret;
716 }
717 EXPORT_SYMBOL_GPL(firmware_request_cache);
718 
719 /**
720  * request_firmware_into_buf() - load firmware into a previously allocated buffer
721  * @firmware_p: pointer to firmware image
722  * @name: name of firmware file
723  * @device: device for which firmware is being loaded and DMA region allocated
724  * @buf: address of buffer to load firmware into
725  * @size: size of buffer
726  *
727  * This function works pretty much like request_firmware(), but it doesn't
728  * allocate a buffer to hold the firmware data. Instead, the firmware
729  * is loaded directly into the buffer pointed to by @buf and the @firmware_p
730  * data member is pointed at @buf.
731  *
732  * This function doesn't cache firmware either.
733  */
734 int
735 request_firmware_into_buf(const struct firmware **firmware_p, const char *name,
736 			  struct device *device, void *buf, size_t size)
737 {
738 	int ret;
739 
740 	if (fw_cache_is_setup(device, name))
741 		return -EOPNOTSUPP;
742 
743 	__module_get(THIS_MODULE);
744 	ret = _request_firmware(firmware_p, name, device, buf, size,
745 				FW_OPT_UEVENT | FW_OPT_NOCACHE);
746 	module_put(THIS_MODULE);
747 	return ret;
748 }
749 EXPORT_SYMBOL(request_firmware_into_buf);
750 
751 /**
752  * release_firmware() - release the resource associated with a firmware image
753  * @fw: firmware resource to release
754  **/
755 void release_firmware(const struct firmware *fw)
756 {
757 	if (fw) {
758 		if (!fw_is_builtin_firmware(fw))
759 			firmware_free_data(fw);
760 		kfree(fw);
761 	}
762 }
763 EXPORT_SYMBOL(release_firmware);
764 
765 /* Async support */
766 struct firmware_work {
767 	struct work_struct work;
768 	struct module *module;
769 	const char *name;
770 	struct device *device;
771 	void *context;
772 	void (*cont)(const struct firmware *fw, void *context);
773 	enum fw_opt opt_flags;
774 };
775 
776 static void request_firmware_work_func(struct work_struct *work)
777 {
778 	struct firmware_work *fw_work;
779 	const struct firmware *fw;
780 
781 	fw_work = container_of(work, struct firmware_work, work);
782 
783 	_request_firmware(&fw, fw_work->name, fw_work->device, NULL, 0,
784 			  fw_work->opt_flags);
785 	fw_work->cont(fw, fw_work->context);
786 	put_device(fw_work->device); /* taken in request_firmware_nowait() */
787 
788 	module_put(fw_work->module);
789 	kfree_const(fw_work->name);
790 	kfree(fw_work);
791 }
792 
793 /**
794  * request_firmware_nowait() - asynchronous version of request_firmware
795  * @module: module requesting the firmware
796  * @uevent: sends uevent to copy the firmware image if this flag
797  *	is non-zero else the firmware copy must be done manually.
798  * @name: name of firmware file
799  * @device: device for which firmware is being loaded
800  * @gfp: allocation flags
801  * @context: will be passed over to @cont, and
802  *	@fw may be %NULL if firmware request fails.
803  * @cont: function will be called asynchronously when the firmware
804  *	request is over.
805  *
806  *	Caller must hold the reference count of @device.
807  *
808  *	Asynchronous variant of request_firmware() for user contexts:
809  *		- sleep for as small periods as possible since it may
810  *		  increase kernel boot time of built-in device drivers
811  *		  requesting firmware in their ->probe() methods, if
812  *		  @gfp is GFP_KERNEL.
813  *
814  *		- can't sleep at all if @gfp is GFP_ATOMIC.
815  **/
816 int
817 request_firmware_nowait(
818 	struct module *module, bool uevent,
819 	const char *name, struct device *device, gfp_t gfp, void *context,
820 	void (*cont)(const struct firmware *fw, void *context))
821 {
822 	struct firmware_work *fw_work;
823 
824 	fw_work = kzalloc(sizeof(struct firmware_work), gfp);
825 	if (!fw_work)
826 		return -ENOMEM;
827 
828 	fw_work->module = module;
829 	fw_work->name = kstrdup_const(name, gfp);
830 	if (!fw_work->name) {
831 		kfree(fw_work);
832 		return -ENOMEM;
833 	}
834 	fw_work->device = device;
835 	fw_work->context = context;
836 	fw_work->cont = cont;
837 	fw_work->opt_flags = FW_OPT_NOWAIT |
838 		(uevent ? FW_OPT_UEVENT : FW_OPT_USERHELPER);
839 
840 	if (!uevent && fw_cache_is_setup(device, name)) {
841 		kfree_const(fw_work->name);
842 		kfree(fw_work);
843 		return -EOPNOTSUPP;
844 	}
845 
846 	if (!try_module_get(module)) {
847 		kfree_const(fw_work->name);
848 		kfree(fw_work);
849 		return -EFAULT;
850 	}
851 
852 	get_device(fw_work->device);
853 	INIT_WORK(&fw_work->work, request_firmware_work_func);
854 	schedule_work(&fw_work->work);
855 	return 0;
856 }
857 EXPORT_SYMBOL(request_firmware_nowait);
858 
859 #ifdef CONFIG_PM_SLEEP
860 static ASYNC_DOMAIN_EXCLUSIVE(fw_cache_domain);
861 
862 /**
863  * cache_firmware() - cache one firmware image in kernel memory space
864  * @fw_name: the firmware image name
865  *
866  * Cache firmware in kernel memory so that drivers can use it when
867  * system isn't ready for them to request firmware image from userspace.
868  * Once it returns successfully, driver can use request_firmware or its
869  * nowait version to get the cached firmware without any interacting
870  * with userspace
871  *
872  * Return 0 if the firmware image has been cached successfully
873  * Return !0 otherwise
874  *
875  */
876 static int cache_firmware(const char *fw_name)
877 {
878 	int ret;
879 	const struct firmware *fw;
880 
881 	pr_debug("%s: %s\n", __func__, fw_name);
882 
883 	ret = request_firmware(&fw, fw_name, NULL);
884 	if (!ret)
885 		kfree(fw);
886 
887 	pr_debug("%s: %s ret=%d\n", __func__, fw_name, ret);
888 
889 	return ret;
890 }
891 
892 static struct fw_priv *lookup_fw_priv(const char *fw_name)
893 {
894 	struct fw_priv *tmp;
895 	struct firmware_cache *fwc = &fw_cache;
896 
897 	spin_lock(&fwc->lock);
898 	tmp = __lookup_fw_priv(fw_name);
899 	spin_unlock(&fwc->lock);
900 
901 	return tmp;
902 }
903 
904 /**
905  * uncache_firmware() - remove one cached firmware image
906  * @fw_name: the firmware image name
907  *
908  * Uncache one firmware image which has been cached successfully
909  * before.
910  *
911  * Return 0 if the firmware cache has been removed successfully
912  * Return !0 otherwise
913  *
914  */
915 static int uncache_firmware(const char *fw_name)
916 {
917 	struct fw_priv *fw_priv;
918 	struct firmware fw;
919 
920 	pr_debug("%s: %s\n", __func__, fw_name);
921 
922 	if (fw_get_builtin_firmware(&fw, fw_name, NULL, 0))
923 		return 0;
924 
925 	fw_priv = lookup_fw_priv(fw_name);
926 	if (fw_priv) {
927 		free_fw_priv(fw_priv);
928 		return 0;
929 	}
930 
931 	return -EINVAL;
932 }
933 
934 static struct fw_cache_entry *alloc_fw_cache_entry(const char *name)
935 {
936 	struct fw_cache_entry *fce;
937 
938 	fce = kzalloc(sizeof(*fce), GFP_ATOMIC);
939 	if (!fce)
940 		goto exit;
941 
942 	fce->name = kstrdup_const(name, GFP_ATOMIC);
943 	if (!fce->name) {
944 		kfree(fce);
945 		fce = NULL;
946 		goto exit;
947 	}
948 exit:
949 	return fce;
950 }
951 
952 static int __fw_entry_found(const char *name)
953 {
954 	struct firmware_cache *fwc = &fw_cache;
955 	struct fw_cache_entry *fce;
956 
957 	list_for_each_entry(fce, &fwc->fw_names, list) {
958 		if (!strcmp(fce->name, name))
959 			return 1;
960 	}
961 	return 0;
962 }
963 
964 static int fw_cache_piggyback_on_request(const char *name)
965 {
966 	struct firmware_cache *fwc = &fw_cache;
967 	struct fw_cache_entry *fce;
968 	int ret = 0;
969 
970 	spin_lock(&fwc->name_lock);
971 	if (__fw_entry_found(name))
972 		goto found;
973 
974 	fce = alloc_fw_cache_entry(name);
975 	if (fce) {
976 		ret = 1;
977 		list_add(&fce->list, &fwc->fw_names);
978 		pr_debug("%s: fw: %s\n", __func__, name);
979 	}
980 found:
981 	spin_unlock(&fwc->name_lock);
982 	return ret;
983 }
984 
985 static void free_fw_cache_entry(struct fw_cache_entry *fce)
986 {
987 	kfree_const(fce->name);
988 	kfree(fce);
989 }
990 
991 static void __async_dev_cache_fw_image(void *fw_entry,
992 				       async_cookie_t cookie)
993 {
994 	struct fw_cache_entry *fce = fw_entry;
995 	struct firmware_cache *fwc = &fw_cache;
996 	int ret;
997 
998 	ret = cache_firmware(fce->name);
999 	if (ret) {
1000 		spin_lock(&fwc->name_lock);
1001 		list_del(&fce->list);
1002 		spin_unlock(&fwc->name_lock);
1003 
1004 		free_fw_cache_entry(fce);
1005 	}
1006 }
1007 
1008 /* called with dev->devres_lock held */
1009 static void dev_create_fw_entry(struct device *dev, void *res,
1010 				void *data)
1011 {
1012 	struct fw_name_devm *fwn = res;
1013 	const char *fw_name = fwn->name;
1014 	struct list_head *head = data;
1015 	struct fw_cache_entry *fce;
1016 
1017 	fce = alloc_fw_cache_entry(fw_name);
1018 	if (fce)
1019 		list_add(&fce->list, head);
1020 }
1021 
1022 static int devm_name_match(struct device *dev, void *res,
1023 			   void *match_data)
1024 {
1025 	struct fw_name_devm *fwn = res;
1026 	return (fwn->magic == (unsigned long)match_data);
1027 }
1028 
1029 static void dev_cache_fw_image(struct device *dev, void *data)
1030 {
1031 	LIST_HEAD(todo);
1032 	struct fw_cache_entry *fce;
1033 	struct fw_cache_entry *fce_next;
1034 	struct firmware_cache *fwc = &fw_cache;
1035 
1036 	devres_for_each_res(dev, fw_name_devm_release,
1037 			    devm_name_match, &fw_cache,
1038 			    dev_create_fw_entry, &todo);
1039 
1040 	list_for_each_entry_safe(fce, fce_next, &todo, list) {
1041 		list_del(&fce->list);
1042 
1043 		spin_lock(&fwc->name_lock);
1044 		/* only one cache entry for one firmware */
1045 		if (!__fw_entry_found(fce->name)) {
1046 			list_add(&fce->list, &fwc->fw_names);
1047 		} else {
1048 			free_fw_cache_entry(fce);
1049 			fce = NULL;
1050 		}
1051 		spin_unlock(&fwc->name_lock);
1052 
1053 		if (fce)
1054 			async_schedule_domain(__async_dev_cache_fw_image,
1055 					      (void *)fce,
1056 					      &fw_cache_domain);
1057 	}
1058 }
1059 
1060 static void __device_uncache_fw_images(void)
1061 {
1062 	struct firmware_cache *fwc = &fw_cache;
1063 	struct fw_cache_entry *fce;
1064 
1065 	spin_lock(&fwc->name_lock);
1066 	while (!list_empty(&fwc->fw_names)) {
1067 		fce = list_entry(fwc->fw_names.next,
1068 				struct fw_cache_entry, list);
1069 		list_del(&fce->list);
1070 		spin_unlock(&fwc->name_lock);
1071 
1072 		uncache_firmware(fce->name);
1073 		free_fw_cache_entry(fce);
1074 
1075 		spin_lock(&fwc->name_lock);
1076 	}
1077 	spin_unlock(&fwc->name_lock);
1078 }
1079 
1080 /**
1081  * device_cache_fw_images() - cache devices' firmware
1082  *
1083  * If one device called request_firmware or its nowait version
1084  * successfully before, the firmware names are recored into the
1085  * device's devres link list, so device_cache_fw_images can call
1086  * cache_firmware() to cache these firmwares for the device,
1087  * then the device driver can load its firmwares easily at
1088  * time when system is not ready to complete loading firmware.
1089  */
1090 static void device_cache_fw_images(void)
1091 {
1092 	struct firmware_cache *fwc = &fw_cache;
1093 	DEFINE_WAIT(wait);
1094 
1095 	pr_debug("%s\n", __func__);
1096 
1097 	/* cancel uncache work */
1098 	cancel_delayed_work_sync(&fwc->work);
1099 
1100 	fw_fallback_set_cache_timeout();
1101 
1102 	mutex_lock(&fw_lock);
1103 	fwc->state = FW_LOADER_START_CACHE;
1104 	dpm_for_each_dev(NULL, dev_cache_fw_image);
1105 	mutex_unlock(&fw_lock);
1106 
1107 	/* wait for completion of caching firmware for all devices */
1108 	async_synchronize_full_domain(&fw_cache_domain);
1109 
1110 	fw_fallback_set_default_timeout();
1111 }
1112 
1113 /**
1114  * device_uncache_fw_images() - uncache devices' firmware
1115  *
1116  * uncache all firmwares which have been cached successfully
1117  * by device_uncache_fw_images earlier
1118  */
1119 static void device_uncache_fw_images(void)
1120 {
1121 	pr_debug("%s\n", __func__);
1122 	__device_uncache_fw_images();
1123 }
1124 
1125 static void device_uncache_fw_images_work(struct work_struct *work)
1126 {
1127 	device_uncache_fw_images();
1128 }
1129 
1130 /**
1131  * device_uncache_fw_images_delay() - uncache devices firmwares
1132  * @delay: number of milliseconds to delay uncache device firmwares
1133  *
1134  * uncache all devices's firmwares which has been cached successfully
1135  * by device_cache_fw_images after @delay milliseconds.
1136  */
1137 static void device_uncache_fw_images_delay(unsigned long delay)
1138 {
1139 	queue_delayed_work(system_power_efficient_wq, &fw_cache.work,
1140 			   msecs_to_jiffies(delay));
1141 }
1142 
1143 static int fw_pm_notify(struct notifier_block *notify_block,
1144 			unsigned long mode, void *unused)
1145 {
1146 	switch (mode) {
1147 	case PM_HIBERNATION_PREPARE:
1148 	case PM_SUSPEND_PREPARE:
1149 	case PM_RESTORE_PREPARE:
1150 		/*
1151 		 * kill pending fallback requests with a custom fallback
1152 		 * to avoid stalling suspend.
1153 		 */
1154 		kill_pending_fw_fallback_reqs(true);
1155 		device_cache_fw_images();
1156 		break;
1157 
1158 	case PM_POST_SUSPEND:
1159 	case PM_POST_HIBERNATION:
1160 	case PM_POST_RESTORE:
1161 		/*
1162 		 * In case that system sleep failed and syscore_suspend is
1163 		 * not called.
1164 		 */
1165 		mutex_lock(&fw_lock);
1166 		fw_cache.state = FW_LOADER_NO_CACHE;
1167 		mutex_unlock(&fw_lock);
1168 
1169 		device_uncache_fw_images_delay(10 * MSEC_PER_SEC);
1170 		break;
1171 	}
1172 
1173 	return 0;
1174 }
1175 
1176 /* stop caching firmware once syscore_suspend is reached */
1177 static int fw_suspend(void)
1178 {
1179 	fw_cache.state = FW_LOADER_NO_CACHE;
1180 	return 0;
1181 }
1182 
1183 static struct syscore_ops fw_syscore_ops = {
1184 	.suspend = fw_suspend,
1185 };
1186 
1187 static int __init register_fw_pm_ops(void)
1188 {
1189 	int ret;
1190 
1191 	spin_lock_init(&fw_cache.name_lock);
1192 	INIT_LIST_HEAD(&fw_cache.fw_names);
1193 
1194 	INIT_DELAYED_WORK(&fw_cache.work,
1195 			  device_uncache_fw_images_work);
1196 
1197 	fw_cache.pm_notify.notifier_call = fw_pm_notify;
1198 	ret = register_pm_notifier(&fw_cache.pm_notify);
1199 	if (ret)
1200 		return ret;
1201 
1202 	register_syscore_ops(&fw_syscore_ops);
1203 
1204 	return ret;
1205 }
1206 
1207 static inline void unregister_fw_pm_ops(void)
1208 {
1209 	unregister_syscore_ops(&fw_syscore_ops);
1210 	unregister_pm_notifier(&fw_cache.pm_notify);
1211 }
1212 #else
1213 static int fw_cache_piggyback_on_request(const char *name)
1214 {
1215 	return 0;
1216 }
1217 static inline int register_fw_pm_ops(void)
1218 {
1219 	return 0;
1220 }
1221 static inline void unregister_fw_pm_ops(void)
1222 {
1223 }
1224 #endif
1225 
1226 static void __init fw_cache_init(void)
1227 {
1228 	spin_lock_init(&fw_cache.lock);
1229 	INIT_LIST_HEAD(&fw_cache.head);
1230 	fw_cache.state = FW_LOADER_NO_CACHE;
1231 }
1232 
1233 static int fw_shutdown_notify(struct notifier_block *unused1,
1234 			      unsigned long unused2, void *unused3)
1235 {
1236 	/*
1237 	 * Kill all pending fallback requests to avoid both stalling shutdown,
1238 	 * and avoid a deadlock with the usermode_lock.
1239 	 */
1240 	kill_pending_fw_fallback_reqs(false);
1241 
1242 	return NOTIFY_DONE;
1243 }
1244 
1245 static struct notifier_block fw_shutdown_nb = {
1246 	.notifier_call = fw_shutdown_notify,
1247 };
1248 
1249 static int __init firmware_class_init(void)
1250 {
1251 	int ret;
1252 
1253 	/* No need to unfold these on exit */
1254 	fw_cache_init();
1255 
1256 	ret = register_fw_pm_ops();
1257 	if (ret)
1258 		return ret;
1259 
1260 	ret = register_reboot_notifier(&fw_shutdown_nb);
1261 	if (ret)
1262 		goto out;
1263 
1264 	return register_sysfs_loader();
1265 
1266 out:
1267 	unregister_fw_pm_ops();
1268 	return ret;
1269 }
1270 
1271 static void __exit firmware_class_exit(void)
1272 {
1273 	unregister_fw_pm_ops();
1274 	unregister_reboot_notifier(&fw_shutdown_nb);
1275 	unregister_sysfs_loader();
1276 }
1277 
1278 fs_initcall(firmware_class_init);
1279 module_exit(firmware_class_exit);
1280