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