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