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