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/driver-api/firmware/ 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/kernel_read_file.h>
16 #include <linux/module.h>
17 #include <linux/init.h>
18 #include <linux/initrd.h>
19 #include <linux/timer.h>
20 #include <linux/vmalloc.h>
21 #include <linux/interrupt.h>
22 #include <linux/bitops.h>
23 #include <linux/mutex.h>
24 #include <linux/workqueue.h>
25 #include <linux/highmem.h>
26 #include <linux/firmware.h>
27 #include <linux/slab.h>
28 #include <linux/sched.h>
29 #include <linux/file.h>
30 #include <linux/list.h>
31 #include <linux/fs.h>
32 #include <linux/async.h>
33 #include <linux/pm.h>
34 #include <linux/suspend.h>
35 #include <linux/syscore_ops.h>
36 #include <linux/reboot.h>
37 #include <linux/security.h>
38 #include <linux/zstd.h>
39 #include <linux/xz.h>
40 
41 #include <generated/utsrelease.h>
42 
43 #include "../base.h"
44 #include "firmware.h"
45 #include "fallback.h"
46 
47 MODULE_AUTHOR("Manuel Estrada Sainz");
48 MODULE_DESCRIPTION("Multi purpose firmware loading support");
49 MODULE_LICENSE("GPL");
50 
51 struct firmware_cache {
52 	/* firmware_buf instance will be added into the below list */
53 	spinlock_t lock;
54 	struct list_head head;
55 	int state;
56 
57 #ifdef CONFIG_FW_CACHE
58 	/*
59 	 * Names of firmware images which have been cached successfully
60 	 * will be added into the below list so that device uncache
61 	 * helper can trace which firmware images have been cached
62 	 * before.
63 	 */
64 	spinlock_t name_lock;
65 	struct list_head fw_names;
66 
67 	struct delayed_work work;
68 
69 	struct notifier_block   pm_notify;
70 #endif
71 };
72 
73 struct fw_cache_entry {
74 	struct list_head list;
75 	const char *name;
76 };
77 
78 struct fw_name_devm {
79 	unsigned long magic;
80 	const char *name;
81 };
82 
83 static inline struct fw_priv *to_fw_priv(struct kref *ref)
84 {
85 	return container_of(ref, struct fw_priv, ref);
86 }
87 
88 #define	FW_LOADER_NO_CACHE	0
89 #define	FW_LOADER_START_CACHE	1
90 
91 /* fw_lock could be moved to 'struct fw_sysfs' but since it is just
92  * guarding for corner cases a global lock should be OK */
93 DEFINE_MUTEX(fw_lock);
94 
95 static struct firmware_cache fw_cache;
96 
97 static void fw_state_init(struct fw_priv *fw_priv)
98 {
99 	struct fw_state *fw_st = &fw_priv->fw_st;
100 
101 	init_completion(&fw_st->completion);
102 	fw_st->status = FW_STATUS_UNKNOWN;
103 }
104 
105 static inline int fw_state_wait(struct fw_priv *fw_priv)
106 {
107 	return __fw_state_wait_common(fw_priv, MAX_SCHEDULE_TIMEOUT);
108 }
109 
110 static void fw_cache_piggyback_on_request(struct fw_priv *fw_priv);
111 
112 static struct fw_priv *__allocate_fw_priv(const char *fw_name,
113 					  struct firmware_cache *fwc,
114 					  void *dbuf,
115 					  size_t size,
116 					  size_t offset,
117 					  u32 opt_flags)
118 {
119 	struct fw_priv *fw_priv;
120 
121 	/* For a partial read, the buffer must be preallocated. */
122 	if ((opt_flags & FW_OPT_PARTIAL) && !dbuf)
123 		return NULL;
124 
125 	/* Only partial reads are allowed to use an offset. */
126 	if (offset != 0 && !(opt_flags & FW_OPT_PARTIAL))
127 		return NULL;
128 
129 	fw_priv = kzalloc(sizeof(*fw_priv), GFP_ATOMIC);
130 	if (!fw_priv)
131 		return NULL;
132 
133 	fw_priv->fw_name = kstrdup_const(fw_name, GFP_ATOMIC);
134 	if (!fw_priv->fw_name) {
135 		kfree(fw_priv);
136 		return NULL;
137 	}
138 
139 	kref_init(&fw_priv->ref);
140 	fw_priv->fwc = fwc;
141 	fw_priv->data = dbuf;
142 	fw_priv->allocated_size = size;
143 	fw_priv->offset = offset;
144 	fw_priv->opt_flags = opt_flags;
145 	fw_state_init(fw_priv);
146 #ifdef CONFIG_FW_LOADER_USER_HELPER
147 	INIT_LIST_HEAD(&fw_priv->pending_list);
148 #endif
149 
150 	pr_debug("%s: fw-%s fw_priv=%p\n", __func__, fw_name, fw_priv);
151 
152 	return fw_priv;
153 }
154 
155 static struct fw_priv *__lookup_fw_priv(const char *fw_name)
156 {
157 	struct fw_priv *tmp;
158 	struct firmware_cache *fwc = &fw_cache;
159 
160 	list_for_each_entry(tmp, &fwc->head, list)
161 		if (!strcmp(tmp->fw_name, fw_name))
162 			return tmp;
163 	return NULL;
164 }
165 
166 /* Returns 1 for batching firmware requests with the same name */
167 static int alloc_lookup_fw_priv(const char *fw_name,
168 				struct firmware_cache *fwc,
169 				struct fw_priv **fw_priv,
170 				void *dbuf,
171 				size_t size,
172 				size_t offset,
173 				u32 opt_flags)
174 {
175 	struct fw_priv *tmp;
176 
177 	spin_lock(&fwc->lock);
178 	/*
179 	 * Do not merge requests that are marked to be non-cached or
180 	 * are performing partial reads.
181 	 */
182 	if (!(opt_flags & (FW_OPT_NOCACHE | FW_OPT_PARTIAL))) {
183 		tmp = __lookup_fw_priv(fw_name);
184 		if (tmp) {
185 			kref_get(&tmp->ref);
186 			spin_unlock(&fwc->lock);
187 			*fw_priv = tmp;
188 			pr_debug("batched request - sharing the same struct fw_priv and lookup for multiple requests\n");
189 			return 1;
190 		}
191 	}
192 
193 	tmp = __allocate_fw_priv(fw_name, fwc, dbuf, size, offset, opt_flags);
194 	if (tmp) {
195 		INIT_LIST_HEAD(&tmp->list);
196 		if (!(opt_flags & FW_OPT_NOCACHE))
197 			list_add(&tmp->list, &fwc->head);
198 	}
199 	spin_unlock(&fwc->lock);
200 
201 	*fw_priv = tmp;
202 
203 	return tmp ? 0 : -ENOMEM;
204 }
205 
206 static void __free_fw_priv(struct kref *ref)
207 	__releases(&fwc->lock)
208 {
209 	struct fw_priv *fw_priv = to_fw_priv(ref);
210 	struct firmware_cache *fwc = fw_priv->fwc;
211 
212 	pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
213 		 __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
214 		 (unsigned int)fw_priv->size);
215 
216 	list_del(&fw_priv->list);
217 	spin_unlock(&fwc->lock);
218 
219 	if (fw_is_paged_buf(fw_priv))
220 		fw_free_paged_buf(fw_priv);
221 	else if (!fw_priv->allocated_size)
222 		vfree(fw_priv->data);
223 
224 	kfree_const(fw_priv->fw_name);
225 	kfree(fw_priv);
226 }
227 
228 static void free_fw_priv(struct fw_priv *fw_priv)
229 {
230 	struct firmware_cache *fwc = fw_priv->fwc;
231 	spin_lock(&fwc->lock);
232 	if (!kref_put(&fw_priv->ref, __free_fw_priv))
233 		spin_unlock(&fwc->lock);
234 }
235 
236 #ifdef CONFIG_FW_LOADER_PAGED_BUF
237 bool fw_is_paged_buf(struct fw_priv *fw_priv)
238 {
239 	return fw_priv->is_paged_buf;
240 }
241 
242 void fw_free_paged_buf(struct fw_priv *fw_priv)
243 {
244 	int i;
245 
246 	if (!fw_priv->pages)
247 		return;
248 
249 	vunmap(fw_priv->data);
250 
251 	for (i = 0; i < fw_priv->nr_pages; i++)
252 		__free_page(fw_priv->pages[i]);
253 	kvfree(fw_priv->pages);
254 	fw_priv->pages = NULL;
255 	fw_priv->page_array_size = 0;
256 	fw_priv->nr_pages = 0;
257 }
258 
259 int fw_grow_paged_buf(struct fw_priv *fw_priv, int pages_needed)
260 {
261 	/* If the array of pages is too small, grow it */
262 	if (fw_priv->page_array_size < pages_needed) {
263 		int new_array_size = max(pages_needed,
264 					 fw_priv->page_array_size * 2);
265 		struct page **new_pages;
266 
267 		new_pages = kvmalloc_array(new_array_size, sizeof(void *),
268 					   GFP_KERNEL);
269 		if (!new_pages)
270 			return -ENOMEM;
271 		memcpy(new_pages, fw_priv->pages,
272 		       fw_priv->page_array_size * sizeof(void *));
273 		memset(&new_pages[fw_priv->page_array_size], 0, sizeof(void *) *
274 		       (new_array_size - fw_priv->page_array_size));
275 		kvfree(fw_priv->pages);
276 		fw_priv->pages = new_pages;
277 		fw_priv->page_array_size = new_array_size;
278 	}
279 
280 	while (fw_priv->nr_pages < pages_needed) {
281 		fw_priv->pages[fw_priv->nr_pages] =
282 			alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
283 
284 		if (!fw_priv->pages[fw_priv->nr_pages])
285 			return -ENOMEM;
286 		fw_priv->nr_pages++;
287 	}
288 
289 	return 0;
290 }
291 
292 int fw_map_paged_buf(struct fw_priv *fw_priv)
293 {
294 	/* one pages buffer should be mapped/unmapped only once */
295 	if (!fw_priv->pages)
296 		return 0;
297 
298 	vunmap(fw_priv->data);
299 	fw_priv->data = vmap(fw_priv->pages, fw_priv->nr_pages, 0,
300 			     PAGE_KERNEL_RO);
301 	if (!fw_priv->data)
302 		return -ENOMEM;
303 
304 	return 0;
305 }
306 #endif
307 
308 /*
309  * ZSTD-compressed firmware support
310  */
311 #ifdef CONFIG_FW_LOADER_COMPRESS_ZSTD
312 static int fw_decompress_zstd(struct device *dev, struct fw_priv *fw_priv,
313 			      size_t in_size, const void *in_buffer)
314 {
315 	size_t len, out_size, workspace_size;
316 	void *workspace, *out_buf;
317 	zstd_dctx *ctx;
318 	int err;
319 
320 	if (fw_priv->allocated_size) {
321 		out_size = fw_priv->allocated_size;
322 		out_buf = fw_priv->data;
323 	} else {
324 		zstd_frame_header params;
325 
326 		if (zstd_get_frame_header(&params, in_buffer, in_size) ||
327 		    params.frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN) {
328 			dev_dbg(dev, "%s: invalid zstd header\n", __func__);
329 			return -EINVAL;
330 		}
331 		out_size = params.frameContentSize;
332 		out_buf = vzalloc(out_size);
333 		if (!out_buf)
334 			return -ENOMEM;
335 	}
336 
337 	workspace_size = zstd_dctx_workspace_bound();
338 	workspace = kvzalloc(workspace_size, GFP_KERNEL);
339 	if (!workspace) {
340 		err = -ENOMEM;
341 		goto error;
342 	}
343 
344 	ctx = zstd_init_dctx(workspace, workspace_size);
345 	if (!ctx) {
346 		dev_dbg(dev, "%s: failed to initialize context\n", __func__);
347 		err = -EINVAL;
348 		goto error;
349 	}
350 
351 	len = zstd_decompress_dctx(ctx, out_buf, out_size, in_buffer, in_size);
352 	if (zstd_is_error(len)) {
353 		dev_dbg(dev, "%s: failed to decompress: %d\n", __func__,
354 			zstd_get_error_code(len));
355 		err = -EINVAL;
356 		goto error;
357 	}
358 
359 	if (!fw_priv->allocated_size)
360 		fw_priv->data = out_buf;
361 	fw_priv->size = len;
362 	err = 0;
363 
364  error:
365 	kvfree(workspace);
366 	if (err && !fw_priv->allocated_size)
367 		vfree(out_buf);
368 	return err;
369 }
370 #endif /* CONFIG_FW_LOADER_COMPRESS_ZSTD */
371 
372 /*
373  * XZ-compressed firmware support
374  */
375 #ifdef CONFIG_FW_LOADER_COMPRESS_XZ
376 /* show an error and return the standard error code */
377 static int fw_decompress_xz_error(struct device *dev, enum xz_ret xz_ret)
378 {
379 	if (xz_ret != XZ_STREAM_END) {
380 		dev_warn(dev, "xz decompression failed (xz_ret=%d)\n", xz_ret);
381 		return xz_ret == XZ_MEM_ERROR ? -ENOMEM : -EINVAL;
382 	}
383 	return 0;
384 }
385 
386 /* single-shot decompression onto the pre-allocated buffer */
387 static int fw_decompress_xz_single(struct device *dev, struct fw_priv *fw_priv,
388 				   size_t in_size, const void *in_buffer)
389 {
390 	struct xz_dec *xz_dec;
391 	struct xz_buf xz_buf;
392 	enum xz_ret xz_ret;
393 
394 	xz_dec = xz_dec_init(XZ_SINGLE, (u32)-1);
395 	if (!xz_dec)
396 		return -ENOMEM;
397 
398 	xz_buf.in_size = in_size;
399 	xz_buf.in = in_buffer;
400 	xz_buf.in_pos = 0;
401 	xz_buf.out_size = fw_priv->allocated_size;
402 	xz_buf.out = fw_priv->data;
403 	xz_buf.out_pos = 0;
404 
405 	xz_ret = xz_dec_run(xz_dec, &xz_buf);
406 	xz_dec_end(xz_dec);
407 
408 	fw_priv->size = xz_buf.out_pos;
409 	return fw_decompress_xz_error(dev, xz_ret);
410 }
411 
412 /* decompression on paged buffer and map it */
413 static int fw_decompress_xz_pages(struct device *dev, struct fw_priv *fw_priv,
414 				  size_t in_size, const void *in_buffer)
415 {
416 	struct xz_dec *xz_dec;
417 	struct xz_buf xz_buf;
418 	enum xz_ret xz_ret;
419 	struct page *page;
420 	int err = 0;
421 
422 	xz_dec = xz_dec_init(XZ_DYNALLOC, (u32)-1);
423 	if (!xz_dec)
424 		return -ENOMEM;
425 
426 	xz_buf.in_size = in_size;
427 	xz_buf.in = in_buffer;
428 	xz_buf.in_pos = 0;
429 
430 	fw_priv->is_paged_buf = true;
431 	fw_priv->size = 0;
432 	do {
433 		if (fw_grow_paged_buf(fw_priv, fw_priv->nr_pages + 1)) {
434 			err = -ENOMEM;
435 			goto out;
436 		}
437 
438 		/* decompress onto the new allocated page */
439 		page = fw_priv->pages[fw_priv->nr_pages - 1];
440 		xz_buf.out = kmap(page);
441 		xz_buf.out_pos = 0;
442 		xz_buf.out_size = PAGE_SIZE;
443 		xz_ret = xz_dec_run(xz_dec, &xz_buf);
444 		kunmap(page);
445 		fw_priv->size += xz_buf.out_pos;
446 		/* partial decompression means either end or error */
447 		if (xz_buf.out_pos != PAGE_SIZE)
448 			break;
449 	} while (xz_ret == XZ_OK);
450 
451 	err = fw_decompress_xz_error(dev, xz_ret);
452 	if (!err)
453 		err = fw_map_paged_buf(fw_priv);
454 
455  out:
456 	xz_dec_end(xz_dec);
457 	return err;
458 }
459 
460 static int fw_decompress_xz(struct device *dev, struct fw_priv *fw_priv,
461 			    size_t in_size, const void *in_buffer)
462 {
463 	/* if the buffer is pre-allocated, we can perform in single-shot mode */
464 	if (fw_priv->data)
465 		return fw_decompress_xz_single(dev, fw_priv, in_size, in_buffer);
466 	else
467 		return fw_decompress_xz_pages(dev, fw_priv, in_size, in_buffer);
468 }
469 #endif /* CONFIG_FW_LOADER_COMPRESS_XZ */
470 
471 /* direct firmware loading support */
472 static char fw_path_para[256];
473 static const char * const fw_path[] = {
474 	fw_path_para,
475 	"/lib/firmware/updates/" UTS_RELEASE,
476 	"/lib/firmware/updates",
477 	"/lib/firmware/" UTS_RELEASE,
478 	"/lib/firmware"
479 };
480 
481 /*
482  * Typical usage is that passing 'firmware_class.path=$CUSTOMIZED_PATH'
483  * from kernel command line because firmware_class is generally built in
484  * kernel instead of module.
485  */
486 module_param_string(path, fw_path_para, sizeof(fw_path_para), 0644);
487 MODULE_PARM_DESC(path, "customized firmware image search path with a higher priority than default path");
488 
489 static int
490 fw_get_filesystem_firmware(struct device *device, struct fw_priv *fw_priv,
491 			   const char *suffix,
492 			   int (*decompress)(struct device *dev,
493 					     struct fw_priv *fw_priv,
494 					     size_t in_size,
495 					     const void *in_buffer))
496 {
497 	size_t size;
498 	int i, len;
499 	int rc = -ENOENT;
500 	char *path;
501 	size_t msize = INT_MAX;
502 	void *buffer = NULL;
503 
504 	/* Already populated data member means we're loading into a buffer */
505 	if (!decompress && fw_priv->data) {
506 		buffer = fw_priv->data;
507 		msize = fw_priv->allocated_size;
508 	}
509 
510 	path = __getname();
511 	if (!path)
512 		return -ENOMEM;
513 
514 	wait_for_initramfs();
515 	for (i = 0; i < ARRAY_SIZE(fw_path); i++) {
516 		size_t file_size = 0;
517 		size_t *file_size_ptr = NULL;
518 
519 		/* skip the unset customized path */
520 		if (!fw_path[i][0])
521 			continue;
522 
523 		len = snprintf(path, PATH_MAX, "%s/%s%s",
524 			       fw_path[i], fw_priv->fw_name, suffix);
525 		if (len >= PATH_MAX) {
526 			rc = -ENAMETOOLONG;
527 			break;
528 		}
529 
530 		fw_priv->size = 0;
531 
532 		/*
533 		 * The total file size is only examined when doing a partial
534 		 * read; the "full read" case needs to fail if the whole
535 		 * firmware was not completely loaded.
536 		 */
537 		if ((fw_priv->opt_flags & FW_OPT_PARTIAL) && buffer)
538 			file_size_ptr = &file_size;
539 
540 		/* load firmware files from the mount namespace of init */
541 		rc = kernel_read_file_from_path_initns(path, fw_priv->offset,
542 						       &buffer, msize,
543 						       file_size_ptr,
544 						       READING_FIRMWARE);
545 		if (rc < 0) {
546 			if (rc != -ENOENT)
547 				dev_warn(device, "loading %s failed with error %d\n",
548 					 path, rc);
549 			else
550 				dev_dbg(device, "loading %s failed for no such file or directory.\n",
551 					 path);
552 			continue;
553 		}
554 		size = rc;
555 		rc = 0;
556 
557 		dev_dbg(device, "Loading firmware from %s\n", path);
558 		if (decompress) {
559 			dev_dbg(device, "f/w decompressing %s\n",
560 				fw_priv->fw_name);
561 			rc = decompress(device, fw_priv, size, buffer);
562 			/* discard the superfluous original content */
563 			vfree(buffer);
564 			buffer = NULL;
565 			if (rc) {
566 				fw_free_paged_buf(fw_priv);
567 				continue;
568 			}
569 		} else {
570 			dev_dbg(device, "direct-loading %s\n",
571 				fw_priv->fw_name);
572 			if (!fw_priv->data)
573 				fw_priv->data = buffer;
574 			fw_priv->size = size;
575 		}
576 		fw_state_done(fw_priv);
577 		break;
578 	}
579 	__putname(path);
580 
581 	return rc;
582 }
583 
584 /* firmware holds the ownership of pages */
585 static void firmware_free_data(const struct firmware *fw)
586 {
587 	/* Loaded directly? */
588 	if (!fw->priv) {
589 		vfree(fw->data);
590 		return;
591 	}
592 	free_fw_priv(fw->priv);
593 }
594 
595 /* store the pages buffer info firmware from buf */
596 static void fw_set_page_data(struct fw_priv *fw_priv, struct firmware *fw)
597 {
598 	fw->priv = fw_priv;
599 	fw->size = fw_priv->size;
600 	fw->data = fw_priv->data;
601 
602 	pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
603 		 __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
604 		 (unsigned int)fw_priv->size);
605 }
606 
607 #ifdef CONFIG_FW_CACHE
608 static void fw_name_devm_release(struct device *dev, void *res)
609 {
610 	struct fw_name_devm *fwn = res;
611 
612 	if (fwn->magic == (unsigned long)&fw_cache)
613 		pr_debug("%s: fw_name-%s devm-%p released\n",
614 				__func__, fwn->name, res);
615 	kfree_const(fwn->name);
616 }
617 
618 static int fw_devm_match(struct device *dev, void *res,
619 		void *match_data)
620 {
621 	struct fw_name_devm *fwn = res;
622 
623 	return (fwn->magic == (unsigned long)&fw_cache) &&
624 		!strcmp(fwn->name, match_data);
625 }
626 
627 static struct fw_name_devm *fw_find_devm_name(struct device *dev,
628 		const char *name)
629 {
630 	struct fw_name_devm *fwn;
631 
632 	fwn = devres_find(dev, fw_name_devm_release,
633 			  fw_devm_match, (void *)name);
634 	return fwn;
635 }
636 
637 static bool fw_cache_is_setup(struct device *dev, const char *name)
638 {
639 	struct fw_name_devm *fwn;
640 
641 	fwn = fw_find_devm_name(dev, name);
642 	if (fwn)
643 		return true;
644 
645 	return false;
646 }
647 
648 /* add firmware name into devres list */
649 static int fw_add_devm_name(struct device *dev, const char *name)
650 {
651 	struct fw_name_devm *fwn;
652 
653 	if (fw_cache_is_setup(dev, name))
654 		return 0;
655 
656 	fwn = devres_alloc(fw_name_devm_release, sizeof(struct fw_name_devm),
657 			   GFP_KERNEL);
658 	if (!fwn)
659 		return -ENOMEM;
660 	fwn->name = kstrdup_const(name, GFP_KERNEL);
661 	if (!fwn->name) {
662 		devres_free(fwn);
663 		return -ENOMEM;
664 	}
665 
666 	fwn->magic = (unsigned long)&fw_cache;
667 	devres_add(dev, fwn);
668 
669 	return 0;
670 }
671 #else
672 static bool fw_cache_is_setup(struct device *dev, const char *name)
673 {
674 	return false;
675 }
676 
677 static int fw_add_devm_name(struct device *dev, const char *name)
678 {
679 	return 0;
680 }
681 #endif
682 
683 int assign_fw(struct firmware *fw, struct device *device)
684 {
685 	struct fw_priv *fw_priv = fw->priv;
686 	int ret;
687 
688 	mutex_lock(&fw_lock);
689 	if (!fw_priv->size || fw_state_is_aborted(fw_priv)) {
690 		mutex_unlock(&fw_lock);
691 		return -ENOENT;
692 	}
693 
694 	/*
695 	 * add firmware name into devres list so that we can auto cache
696 	 * and uncache firmware for device.
697 	 *
698 	 * device may has been deleted already, but the problem
699 	 * should be fixed in devres or driver core.
700 	 */
701 	/* don't cache firmware handled without uevent */
702 	if (device && (fw_priv->opt_flags & FW_OPT_UEVENT) &&
703 	    !(fw_priv->opt_flags & FW_OPT_NOCACHE)) {
704 		ret = fw_add_devm_name(device, fw_priv->fw_name);
705 		if (ret) {
706 			mutex_unlock(&fw_lock);
707 			return ret;
708 		}
709 	}
710 
711 	/*
712 	 * After caching firmware image is started, let it piggyback
713 	 * on request firmware.
714 	 */
715 	if (!(fw_priv->opt_flags & FW_OPT_NOCACHE) &&
716 	    fw_priv->fwc->state == FW_LOADER_START_CACHE)
717 		fw_cache_piggyback_on_request(fw_priv);
718 
719 	/* pass the pages buffer to driver at the last minute */
720 	fw_set_page_data(fw_priv, fw);
721 	mutex_unlock(&fw_lock);
722 	return 0;
723 }
724 
725 /* prepare firmware and firmware_buf structs;
726  * return 0 if a firmware is already assigned, 1 if need to load one,
727  * or a negative error code
728  */
729 static int
730 _request_firmware_prepare(struct firmware **firmware_p, const char *name,
731 			  struct device *device, void *dbuf, size_t size,
732 			  size_t offset, u32 opt_flags)
733 {
734 	struct firmware *firmware;
735 	struct fw_priv *fw_priv;
736 	int ret;
737 
738 	*firmware_p = firmware = kzalloc(sizeof(*firmware), GFP_KERNEL);
739 	if (!firmware) {
740 		dev_err(device, "%s: kmalloc(struct firmware) failed\n",
741 			__func__);
742 		return -ENOMEM;
743 	}
744 
745 	if (firmware_request_builtin_buf(firmware, name, dbuf, size)) {
746 		dev_dbg(device, "using built-in %s\n", name);
747 		return 0; /* assigned */
748 	}
749 
750 	ret = alloc_lookup_fw_priv(name, &fw_cache, &fw_priv, dbuf, size,
751 				   offset, opt_flags);
752 
753 	/*
754 	 * bind with 'priv' now to avoid warning in failure path
755 	 * of requesting firmware.
756 	 */
757 	firmware->priv = fw_priv;
758 
759 	if (ret > 0) {
760 		ret = fw_state_wait(fw_priv);
761 		if (!ret) {
762 			fw_set_page_data(fw_priv, firmware);
763 			return 0; /* assigned */
764 		}
765 	}
766 
767 	if (ret < 0)
768 		return ret;
769 	return 1; /* need to load */
770 }
771 
772 /*
773  * Batched requests need only one wake, we need to do this step last due to the
774  * fallback mechanism. The buf is protected with kref_get(), and it won't be
775  * released until the last user calls release_firmware().
776  *
777  * Failed batched requests are possible as well, in such cases we just share
778  * the struct fw_priv and won't release it until all requests are woken
779  * and have gone through this same path.
780  */
781 static void fw_abort_batch_reqs(struct firmware *fw)
782 {
783 	struct fw_priv *fw_priv;
784 
785 	/* Loaded directly? */
786 	if (!fw || !fw->priv)
787 		return;
788 
789 	fw_priv = fw->priv;
790 	mutex_lock(&fw_lock);
791 	if (!fw_state_is_aborted(fw_priv))
792 		fw_state_aborted(fw_priv);
793 	mutex_unlock(&fw_lock);
794 }
795 
796 /* called from request_firmware() and request_firmware_work_func() */
797 static int
798 _request_firmware(const struct firmware **firmware_p, const char *name,
799 		  struct device *device, void *buf, size_t size,
800 		  size_t offset, u32 opt_flags)
801 {
802 	struct firmware *fw = NULL;
803 	bool nondirect = false;
804 	int ret;
805 
806 	if (!firmware_p)
807 		return -EINVAL;
808 
809 	if (!name || name[0] == '\0') {
810 		ret = -EINVAL;
811 		goto out;
812 	}
813 
814 	ret = _request_firmware_prepare(&fw, name, device, buf, size,
815 					offset, opt_flags);
816 	if (ret <= 0) /* error or already assigned */
817 		goto out;
818 
819 	ret = fw_get_filesystem_firmware(device, fw->priv, "", NULL);
820 
821 	/* Only full reads can support decompression, platform, and sysfs. */
822 	if (!(opt_flags & FW_OPT_PARTIAL))
823 		nondirect = true;
824 
825 #ifdef CONFIG_FW_LOADER_COMPRESS_ZSTD
826 	if (ret == -ENOENT && nondirect)
827 		ret = fw_get_filesystem_firmware(device, fw->priv, ".zst",
828 						 fw_decompress_zstd);
829 #endif
830 #ifdef CONFIG_FW_LOADER_COMPRESS_XZ
831 	if (ret == -ENOENT && nondirect)
832 		ret = fw_get_filesystem_firmware(device, fw->priv, ".xz",
833 						 fw_decompress_xz);
834 #endif
835 	if (ret == -ENOENT && nondirect)
836 		ret = firmware_fallback_platform(fw->priv);
837 
838 	if (ret) {
839 		if (!(opt_flags & FW_OPT_NO_WARN))
840 			dev_warn(device,
841 				 "Direct firmware load for %s failed with error %d\n",
842 				 name, ret);
843 		if (nondirect)
844 			ret = firmware_fallback_sysfs(fw, name, device,
845 						      opt_flags, ret);
846 	} else
847 		ret = assign_fw(fw, device);
848 
849  out:
850 	if (ret < 0) {
851 		fw_abort_batch_reqs(fw);
852 		release_firmware(fw);
853 		fw = NULL;
854 	}
855 
856 	*firmware_p = fw;
857 	return ret;
858 }
859 
860 /**
861  * request_firmware() - send firmware request and wait for it
862  * @firmware_p: pointer to firmware image
863  * @name: name of firmware file
864  * @device: device for which firmware is being loaded
865  *
866  *      @firmware_p will be used to return a firmware image by the name
867  *      of @name for device @device.
868  *
869  *      Should be called from user context where sleeping is allowed.
870  *
871  *      @name will be used as $FIRMWARE in the uevent environment and
872  *      should be distinctive enough not to be confused with any other
873  *      firmware image for this or any other device.
874  *
875  *	Caller must hold the reference count of @device.
876  *
877  *	The function can be called safely inside device's suspend and
878  *	resume callback.
879  **/
880 int
881 request_firmware(const struct firmware **firmware_p, const char *name,
882 		 struct device *device)
883 {
884 	int ret;
885 
886 	/* Need to pin this module until return */
887 	__module_get(THIS_MODULE);
888 	ret = _request_firmware(firmware_p, name, device, NULL, 0, 0,
889 				FW_OPT_UEVENT);
890 	module_put(THIS_MODULE);
891 	return ret;
892 }
893 EXPORT_SYMBOL(request_firmware);
894 
895 /**
896  * firmware_request_nowarn() - request for an optional fw module
897  * @firmware: pointer to firmware image
898  * @name: name of firmware file
899  * @device: device for which firmware is being loaded
900  *
901  * This function is similar in behaviour to request_firmware(), except it
902  * doesn't produce warning messages when the file is not found. The sysfs
903  * fallback mechanism is enabled if direct filesystem lookup fails. However,
904  * failures to find the firmware file with it are still suppressed. It is
905  * therefore up to the driver to check for the return value of this call and to
906  * decide when to inform the users of errors.
907  **/
908 int firmware_request_nowarn(const struct firmware **firmware, const char *name,
909 			    struct device *device)
910 {
911 	int ret;
912 
913 	/* Need to pin this module until return */
914 	__module_get(THIS_MODULE);
915 	ret = _request_firmware(firmware, name, device, NULL, 0, 0,
916 				FW_OPT_UEVENT | FW_OPT_NO_WARN);
917 	module_put(THIS_MODULE);
918 	return ret;
919 }
920 EXPORT_SYMBOL_GPL(firmware_request_nowarn);
921 
922 /**
923  * request_firmware_direct() - load firmware directly without usermode helper
924  * @firmware_p: pointer to firmware image
925  * @name: name of firmware file
926  * @device: device for which firmware is being loaded
927  *
928  * This function works pretty much like request_firmware(), but this doesn't
929  * fall back to usermode helper even if the firmware couldn't be loaded
930  * directly from fs.  Hence it's useful for loading optional firmwares, which
931  * aren't always present, without extra long timeouts of udev.
932  **/
933 int request_firmware_direct(const struct firmware **firmware_p,
934 			    const char *name, struct device *device)
935 {
936 	int ret;
937 
938 	__module_get(THIS_MODULE);
939 	ret = _request_firmware(firmware_p, name, device, NULL, 0, 0,
940 				FW_OPT_UEVENT | FW_OPT_NO_WARN |
941 				FW_OPT_NOFALLBACK_SYSFS);
942 	module_put(THIS_MODULE);
943 	return ret;
944 }
945 EXPORT_SYMBOL_GPL(request_firmware_direct);
946 
947 /**
948  * firmware_request_platform() - request firmware with platform-fw fallback
949  * @firmware: pointer to firmware image
950  * @name: name of firmware file
951  * @device: device for which firmware is being loaded
952  *
953  * This function is similar in behaviour to request_firmware, except that if
954  * direct filesystem lookup fails, it will fallback to looking for a copy of the
955  * requested firmware embedded in the platform's main (e.g. UEFI) firmware.
956  **/
957 int firmware_request_platform(const struct firmware **firmware,
958 			      const char *name, struct device *device)
959 {
960 	int ret;
961 
962 	/* Need to pin this module until return */
963 	__module_get(THIS_MODULE);
964 	ret = _request_firmware(firmware, name, device, NULL, 0, 0,
965 				FW_OPT_UEVENT | FW_OPT_FALLBACK_PLATFORM);
966 	module_put(THIS_MODULE);
967 	return ret;
968 }
969 EXPORT_SYMBOL_GPL(firmware_request_platform);
970 
971 /**
972  * firmware_request_cache() - cache firmware for suspend so resume can use it
973  * @name: name of firmware file
974  * @device: device for which firmware should be cached for
975  *
976  * There are some devices with an optimization that enables the device to not
977  * require loading firmware on system reboot. This optimization may still
978  * require the firmware present on resume from suspend. This routine can be
979  * used to ensure the firmware is present on resume from suspend in these
980  * situations. This helper is not compatible with drivers which use
981  * request_firmware_into_buf() or request_firmware_nowait() with no uevent set.
982  **/
983 int firmware_request_cache(struct device *device, const char *name)
984 {
985 	int ret;
986 
987 	mutex_lock(&fw_lock);
988 	ret = fw_add_devm_name(device, name);
989 	mutex_unlock(&fw_lock);
990 
991 	return ret;
992 }
993 EXPORT_SYMBOL_GPL(firmware_request_cache);
994 
995 /**
996  * request_firmware_into_buf() - load firmware into a previously allocated buffer
997  * @firmware_p: pointer to firmware image
998  * @name: name of firmware file
999  * @device: device for which firmware is being loaded and DMA region allocated
1000  * @buf: address of buffer to load firmware into
1001  * @size: size of buffer
1002  *
1003  * This function works pretty much like request_firmware(), but it doesn't
1004  * allocate a buffer to hold the firmware data. Instead, the firmware
1005  * is loaded directly into the buffer pointed to by @buf and the @firmware_p
1006  * data member is pointed at @buf.
1007  *
1008  * This function doesn't cache firmware either.
1009  */
1010 int
1011 request_firmware_into_buf(const struct firmware **firmware_p, const char *name,
1012 			  struct device *device, void *buf, size_t size)
1013 {
1014 	int ret;
1015 
1016 	if (fw_cache_is_setup(device, name))
1017 		return -EOPNOTSUPP;
1018 
1019 	__module_get(THIS_MODULE);
1020 	ret = _request_firmware(firmware_p, name, device, buf, size, 0,
1021 				FW_OPT_UEVENT | FW_OPT_NOCACHE);
1022 	module_put(THIS_MODULE);
1023 	return ret;
1024 }
1025 EXPORT_SYMBOL(request_firmware_into_buf);
1026 
1027 /**
1028  * request_partial_firmware_into_buf() - load partial firmware into a previously allocated buffer
1029  * @firmware_p: pointer to firmware image
1030  * @name: name of firmware file
1031  * @device: device for which firmware is being loaded and DMA region allocated
1032  * @buf: address of buffer to load firmware into
1033  * @size: size of buffer
1034  * @offset: offset into file to read
1035  *
1036  * This function works pretty much like request_firmware_into_buf except
1037  * it allows a partial read of the file.
1038  */
1039 int
1040 request_partial_firmware_into_buf(const struct firmware **firmware_p,
1041 				  const char *name, struct device *device,
1042 				  void *buf, size_t size, size_t offset)
1043 {
1044 	int ret;
1045 
1046 	if (fw_cache_is_setup(device, name))
1047 		return -EOPNOTSUPP;
1048 
1049 	__module_get(THIS_MODULE);
1050 	ret = _request_firmware(firmware_p, name, device, buf, size, offset,
1051 				FW_OPT_UEVENT | FW_OPT_NOCACHE |
1052 				FW_OPT_PARTIAL);
1053 	module_put(THIS_MODULE);
1054 	return ret;
1055 }
1056 EXPORT_SYMBOL(request_partial_firmware_into_buf);
1057 
1058 /**
1059  * release_firmware() - release the resource associated with a firmware image
1060  * @fw: firmware resource to release
1061  **/
1062 void release_firmware(const struct firmware *fw)
1063 {
1064 	if (fw) {
1065 		if (!firmware_is_builtin(fw))
1066 			firmware_free_data(fw);
1067 		kfree(fw);
1068 	}
1069 }
1070 EXPORT_SYMBOL(release_firmware);
1071 
1072 /* Async support */
1073 struct firmware_work {
1074 	struct work_struct work;
1075 	struct module *module;
1076 	const char *name;
1077 	struct device *device;
1078 	void *context;
1079 	void (*cont)(const struct firmware *fw, void *context);
1080 	u32 opt_flags;
1081 };
1082 
1083 static void request_firmware_work_func(struct work_struct *work)
1084 {
1085 	struct firmware_work *fw_work;
1086 	const struct firmware *fw;
1087 
1088 	fw_work = container_of(work, struct firmware_work, work);
1089 
1090 	_request_firmware(&fw, fw_work->name, fw_work->device, NULL, 0, 0,
1091 			  fw_work->opt_flags);
1092 	fw_work->cont(fw, fw_work->context);
1093 	put_device(fw_work->device); /* taken in request_firmware_nowait() */
1094 
1095 	module_put(fw_work->module);
1096 	kfree_const(fw_work->name);
1097 	kfree(fw_work);
1098 }
1099 
1100 /**
1101  * request_firmware_nowait() - asynchronous version of request_firmware
1102  * @module: module requesting the firmware
1103  * @uevent: sends uevent to copy the firmware image if this flag
1104  *	is non-zero else the firmware copy must be done manually.
1105  * @name: name of firmware file
1106  * @device: device for which firmware is being loaded
1107  * @gfp: allocation flags
1108  * @context: will be passed over to @cont, and
1109  *	@fw may be %NULL if firmware request fails.
1110  * @cont: function will be called asynchronously when the firmware
1111  *	request is over.
1112  *
1113  *	Caller must hold the reference count of @device.
1114  *
1115  *	Asynchronous variant of request_firmware() for user contexts:
1116  *		- sleep for as small periods as possible since it may
1117  *		  increase kernel boot time of built-in device drivers
1118  *		  requesting firmware in their ->probe() methods, if
1119  *		  @gfp is GFP_KERNEL.
1120  *
1121  *		- can't sleep at all if @gfp is GFP_ATOMIC.
1122  **/
1123 int
1124 request_firmware_nowait(
1125 	struct module *module, bool uevent,
1126 	const char *name, struct device *device, gfp_t gfp, void *context,
1127 	void (*cont)(const struct firmware *fw, void *context))
1128 {
1129 	struct firmware_work *fw_work;
1130 
1131 	fw_work = kzalloc(sizeof(struct firmware_work), gfp);
1132 	if (!fw_work)
1133 		return -ENOMEM;
1134 
1135 	fw_work->module = module;
1136 	fw_work->name = kstrdup_const(name, gfp);
1137 	if (!fw_work->name) {
1138 		kfree(fw_work);
1139 		return -ENOMEM;
1140 	}
1141 	fw_work->device = device;
1142 	fw_work->context = context;
1143 	fw_work->cont = cont;
1144 	fw_work->opt_flags = FW_OPT_NOWAIT |
1145 		(uevent ? FW_OPT_UEVENT : FW_OPT_USERHELPER);
1146 
1147 	if (!uevent && fw_cache_is_setup(device, name)) {
1148 		kfree_const(fw_work->name);
1149 		kfree(fw_work);
1150 		return -EOPNOTSUPP;
1151 	}
1152 
1153 	if (!try_module_get(module)) {
1154 		kfree_const(fw_work->name);
1155 		kfree(fw_work);
1156 		return -EFAULT;
1157 	}
1158 
1159 	get_device(fw_work->device);
1160 	INIT_WORK(&fw_work->work, request_firmware_work_func);
1161 	schedule_work(&fw_work->work);
1162 	return 0;
1163 }
1164 EXPORT_SYMBOL(request_firmware_nowait);
1165 
1166 #ifdef CONFIG_FW_CACHE
1167 static ASYNC_DOMAIN_EXCLUSIVE(fw_cache_domain);
1168 
1169 /**
1170  * cache_firmware() - cache one firmware image in kernel memory space
1171  * @fw_name: the firmware image name
1172  *
1173  * Cache firmware in kernel memory so that drivers can use it when
1174  * system isn't ready for them to request firmware image from userspace.
1175  * Once it returns successfully, driver can use request_firmware or its
1176  * nowait version to get the cached firmware without any interacting
1177  * with userspace
1178  *
1179  * Return 0 if the firmware image has been cached successfully
1180  * Return !0 otherwise
1181  *
1182  */
1183 static int cache_firmware(const char *fw_name)
1184 {
1185 	int ret;
1186 	const struct firmware *fw;
1187 
1188 	pr_debug("%s: %s\n", __func__, fw_name);
1189 
1190 	ret = request_firmware(&fw, fw_name, NULL);
1191 	if (!ret)
1192 		kfree(fw);
1193 
1194 	pr_debug("%s: %s ret=%d\n", __func__, fw_name, ret);
1195 
1196 	return ret;
1197 }
1198 
1199 static struct fw_priv *lookup_fw_priv(const char *fw_name)
1200 {
1201 	struct fw_priv *tmp;
1202 	struct firmware_cache *fwc = &fw_cache;
1203 
1204 	spin_lock(&fwc->lock);
1205 	tmp = __lookup_fw_priv(fw_name);
1206 	spin_unlock(&fwc->lock);
1207 
1208 	return tmp;
1209 }
1210 
1211 /**
1212  * uncache_firmware() - remove one cached firmware image
1213  * @fw_name: the firmware image name
1214  *
1215  * Uncache one firmware image which has been cached successfully
1216  * before.
1217  *
1218  * Return 0 if the firmware cache has been removed successfully
1219  * Return !0 otherwise
1220  *
1221  */
1222 static int uncache_firmware(const char *fw_name)
1223 {
1224 	struct fw_priv *fw_priv;
1225 	struct firmware fw;
1226 
1227 	pr_debug("%s: %s\n", __func__, fw_name);
1228 
1229 	if (firmware_request_builtin(&fw, fw_name))
1230 		return 0;
1231 
1232 	fw_priv = lookup_fw_priv(fw_name);
1233 	if (fw_priv) {
1234 		free_fw_priv(fw_priv);
1235 		return 0;
1236 	}
1237 
1238 	return -EINVAL;
1239 }
1240 
1241 static struct fw_cache_entry *alloc_fw_cache_entry(const char *name)
1242 {
1243 	struct fw_cache_entry *fce;
1244 
1245 	fce = kzalloc(sizeof(*fce), GFP_ATOMIC);
1246 	if (!fce)
1247 		goto exit;
1248 
1249 	fce->name = kstrdup_const(name, GFP_ATOMIC);
1250 	if (!fce->name) {
1251 		kfree(fce);
1252 		fce = NULL;
1253 		goto exit;
1254 	}
1255 exit:
1256 	return fce;
1257 }
1258 
1259 static int __fw_entry_found(const char *name)
1260 {
1261 	struct firmware_cache *fwc = &fw_cache;
1262 	struct fw_cache_entry *fce;
1263 
1264 	list_for_each_entry(fce, &fwc->fw_names, list) {
1265 		if (!strcmp(fce->name, name))
1266 			return 1;
1267 	}
1268 	return 0;
1269 }
1270 
1271 static void fw_cache_piggyback_on_request(struct fw_priv *fw_priv)
1272 {
1273 	const char *name = fw_priv->fw_name;
1274 	struct firmware_cache *fwc = fw_priv->fwc;
1275 	struct fw_cache_entry *fce;
1276 
1277 	spin_lock(&fwc->name_lock);
1278 	if (__fw_entry_found(name))
1279 		goto found;
1280 
1281 	fce = alloc_fw_cache_entry(name);
1282 	if (fce) {
1283 		list_add(&fce->list, &fwc->fw_names);
1284 		kref_get(&fw_priv->ref);
1285 		pr_debug("%s: fw: %s\n", __func__, name);
1286 	}
1287 found:
1288 	spin_unlock(&fwc->name_lock);
1289 }
1290 
1291 static void free_fw_cache_entry(struct fw_cache_entry *fce)
1292 {
1293 	kfree_const(fce->name);
1294 	kfree(fce);
1295 }
1296 
1297 static void __async_dev_cache_fw_image(void *fw_entry,
1298 				       async_cookie_t cookie)
1299 {
1300 	struct fw_cache_entry *fce = fw_entry;
1301 	struct firmware_cache *fwc = &fw_cache;
1302 	int ret;
1303 
1304 	ret = cache_firmware(fce->name);
1305 	if (ret) {
1306 		spin_lock(&fwc->name_lock);
1307 		list_del(&fce->list);
1308 		spin_unlock(&fwc->name_lock);
1309 
1310 		free_fw_cache_entry(fce);
1311 	}
1312 }
1313 
1314 /* called with dev->devres_lock held */
1315 static void dev_create_fw_entry(struct device *dev, void *res,
1316 				void *data)
1317 {
1318 	struct fw_name_devm *fwn = res;
1319 	const char *fw_name = fwn->name;
1320 	struct list_head *head = data;
1321 	struct fw_cache_entry *fce;
1322 
1323 	fce = alloc_fw_cache_entry(fw_name);
1324 	if (fce)
1325 		list_add(&fce->list, head);
1326 }
1327 
1328 static int devm_name_match(struct device *dev, void *res,
1329 			   void *match_data)
1330 {
1331 	struct fw_name_devm *fwn = res;
1332 	return (fwn->magic == (unsigned long)match_data);
1333 }
1334 
1335 static void dev_cache_fw_image(struct device *dev, void *data)
1336 {
1337 	LIST_HEAD(todo);
1338 	struct fw_cache_entry *fce;
1339 	struct fw_cache_entry *fce_next;
1340 	struct firmware_cache *fwc = &fw_cache;
1341 
1342 	devres_for_each_res(dev, fw_name_devm_release,
1343 			    devm_name_match, &fw_cache,
1344 			    dev_create_fw_entry, &todo);
1345 
1346 	list_for_each_entry_safe(fce, fce_next, &todo, list) {
1347 		list_del(&fce->list);
1348 
1349 		spin_lock(&fwc->name_lock);
1350 		/* only one cache entry for one firmware */
1351 		if (!__fw_entry_found(fce->name)) {
1352 			list_add(&fce->list, &fwc->fw_names);
1353 		} else {
1354 			free_fw_cache_entry(fce);
1355 			fce = NULL;
1356 		}
1357 		spin_unlock(&fwc->name_lock);
1358 
1359 		if (fce)
1360 			async_schedule_domain(__async_dev_cache_fw_image,
1361 					      (void *)fce,
1362 					      &fw_cache_domain);
1363 	}
1364 }
1365 
1366 static void __device_uncache_fw_images(void)
1367 {
1368 	struct firmware_cache *fwc = &fw_cache;
1369 	struct fw_cache_entry *fce;
1370 
1371 	spin_lock(&fwc->name_lock);
1372 	while (!list_empty(&fwc->fw_names)) {
1373 		fce = list_entry(fwc->fw_names.next,
1374 				struct fw_cache_entry, list);
1375 		list_del(&fce->list);
1376 		spin_unlock(&fwc->name_lock);
1377 
1378 		uncache_firmware(fce->name);
1379 		free_fw_cache_entry(fce);
1380 
1381 		spin_lock(&fwc->name_lock);
1382 	}
1383 	spin_unlock(&fwc->name_lock);
1384 }
1385 
1386 /**
1387  * device_cache_fw_images() - cache devices' firmware
1388  *
1389  * If one device called request_firmware or its nowait version
1390  * successfully before, the firmware names are recored into the
1391  * device's devres link list, so device_cache_fw_images can call
1392  * cache_firmware() to cache these firmwares for the device,
1393  * then the device driver can load its firmwares easily at
1394  * time when system is not ready to complete loading firmware.
1395  */
1396 static void device_cache_fw_images(void)
1397 {
1398 	struct firmware_cache *fwc = &fw_cache;
1399 	DEFINE_WAIT(wait);
1400 
1401 	pr_debug("%s\n", __func__);
1402 
1403 	/* cancel uncache work */
1404 	cancel_delayed_work_sync(&fwc->work);
1405 
1406 	fw_fallback_set_cache_timeout();
1407 
1408 	mutex_lock(&fw_lock);
1409 	fwc->state = FW_LOADER_START_CACHE;
1410 	dpm_for_each_dev(NULL, dev_cache_fw_image);
1411 	mutex_unlock(&fw_lock);
1412 
1413 	/* wait for completion of caching firmware for all devices */
1414 	async_synchronize_full_domain(&fw_cache_domain);
1415 
1416 	fw_fallback_set_default_timeout();
1417 }
1418 
1419 /**
1420  * device_uncache_fw_images() - uncache devices' firmware
1421  *
1422  * uncache all firmwares which have been cached successfully
1423  * by device_uncache_fw_images earlier
1424  */
1425 static void device_uncache_fw_images(void)
1426 {
1427 	pr_debug("%s\n", __func__);
1428 	__device_uncache_fw_images();
1429 }
1430 
1431 static void device_uncache_fw_images_work(struct work_struct *work)
1432 {
1433 	device_uncache_fw_images();
1434 }
1435 
1436 /**
1437  * device_uncache_fw_images_delay() - uncache devices firmwares
1438  * @delay: number of milliseconds to delay uncache device firmwares
1439  *
1440  * uncache all devices's firmwares which has been cached successfully
1441  * by device_cache_fw_images after @delay milliseconds.
1442  */
1443 static void device_uncache_fw_images_delay(unsigned long delay)
1444 {
1445 	queue_delayed_work(system_power_efficient_wq, &fw_cache.work,
1446 			   msecs_to_jiffies(delay));
1447 }
1448 
1449 static int fw_pm_notify(struct notifier_block *notify_block,
1450 			unsigned long mode, void *unused)
1451 {
1452 	switch (mode) {
1453 	case PM_HIBERNATION_PREPARE:
1454 	case PM_SUSPEND_PREPARE:
1455 	case PM_RESTORE_PREPARE:
1456 		/*
1457 		 * kill pending fallback requests with a custom fallback
1458 		 * to avoid stalling suspend.
1459 		 */
1460 		kill_pending_fw_fallback_reqs(true);
1461 		device_cache_fw_images();
1462 		break;
1463 
1464 	case PM_POST_SUSPEND:
1465 	case PM_POST_HIBERNATION:
1466 	case PM_POST_RESTORE:
1467 		/*
1468 		 * In case that system sleep failed and syscore_suspend is
1469 		 * not called.
1470 		 */
1471 		mutex_lock(&fw_lock);
1472 		fw_cache.state = FW_LOADER_NO_CACHE;
1473 		mutex_unlock(&fw_lock);
1474 
1475 		device_uncache_fw_images_delay(10 * MSEC_PER_SEC);
1476 		break;
1477 	}
1478 
1479 	return 0;
1480 }
1481 
1482 /* stop caching firmware once syscore_suspend is reached */
1483 static int fw_suspend(void)
1484 {
1485 	fw_cache.state = FW_LOADER_NO_CACHE;
1486 	return 0;
1487 }
1488 
1489 static struct syscore_ops fw_syscore_ops = {
1490 	.suspend = fw_suspend,
1491 };
1492 
1493 static int __init register_fw_pm_ops(void)
1494 {
1495 	int ret;
1496 
1497 	spin_lock_init(&fw_cache.name_lock);
1498 	INIT_LIST_HEAD(&fw_cache.fw_names);
1499 
1500 	INIT_DELAYED_WORK(&fw_cache.work,
1501 			  device_uncache_fw_images_work);
1502 
1503 	fw_cache.pm_notify.notifier_call = fw_pm_notify;
1504 	ret = register_pm_notifier(&fw_cache.pm_notify);
1505 	if (ret)
1506 		return ret;
1507 
1508 	register_syscore_ops(&fw_syscore_ops);
1509 
1510 	return ret;
1511 }
1512 
1513 static inline void unregister_fw_pm_ops(void)
1514 {
1515 	unregister_syscore_ops(&fw_syscore_ops);
1516 	unregister_pm_notifier(&fw_cache.pm_notify);
1517 }
1518 #else
1519 static void fw_cache_piggyback_on_request(struct fw_priv *fw_priv)
1520 {
1521 }
1522 static inline int register_fw_pm_ops(void)
1523 {
1524 	return 0;
1525 }
1526 static inline void unregister_fw_pm_ops(void)
1527 {
1528 }
1529 #endif
1530 
1531 static void __init fw_cache_init(void)
1532 {
1533 	spin_lock_init(&fw_cache.lock);
1534 	INIT_LIST_HEAD(&fw_cache.head);
1535 	fw_cache.state = FW_LOADER_NO_CACHE;
1536 }
1537 
1538 static int fw_shutdown_notify(struct notifier_block *unused1,
1539 			      unsigned long unused2, void *unused3)
1540 {
1541 	/*
1542 	 * Kill all pending fallback requests to avoid both stalling shutdown,
1543 	 * and avoid a deadlock with the usermode_lock.
1544 	 */
1545 	kill_pending_fw_fallback_reqs(false);
1546 
1547 	return NOTIFY_DONE;
1548 }
1549 
1550 static struct notifier_block fw_shutdown_nb = {
1551 	.notifier_call = fw_shutdown_notify,
1552 };
1553 
1554 static int __init firmware_class_init(void)
1555 {
1556 	int ret;
1557 
1558 	/* No need to unfold these on exit */
1559 	fw_cache_init();
1560 
1561 	ret = register_fw_pm_ops();
1562 	if (ret)
1563 		return ret;
1564 
1565 	ret = register_reboot_notifier(&fw_shutdown_nb);
1566 	if (ret)
1567 		goto out;
1568 
1569 	return register_sysfs_loader();
1570 
1571 out:
1572 	unregister_fw_pm_ops();
1573 	return ret;
1574 }
1575 
1576 static void __exit firmware_class_exit(void)
1577 {
1578 	unregister_fw_pm_ops();
1579 	unregister_reboot_notifier(&fw_shutdown_nb);
1580 	unregister_sysfs_loader();
1581 }
1582 
1583 fs_initcall(firmware_class_init);
1584 module_exit(firmware_class_exit);
1585