main.c 30.4 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
L
Linus Torvalds 已提交
2
/*
3
 * main.c - Multi purpose firmware loading support
L
Linus Torvalds 已提交
4
 *
5
 * Copyright (c) 2003 Manuel Estrada Sainz
L
Linus Torvalds 已提交
6 7 8 9 10
 *
 * Please see Documentation/firmware_class/ for more information.
 *
 */

L
Luis R. Rodriguez 已提交
11 12
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

13
#include <linux/capability.h>
L
Linus Torvalds 已提交
14 15 16 17 18 19 20
#include <linux/device.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/vmalloc.h>
#include <linux/interrupt.h>
#include <linux/bitops.h>
21
#include <linux/mutex.h>
22
#include <linux/workqueue.h>
23
#include <linux/highmem.h>
L
Linus Torvalds 已提交
24
#include <linux/firmware.h>
25
#include <linux/slab.h>
26
#include <linux/sched.h>
27
#include <linux/file.h>
28
#include <linux/list.h>
29
#include <linux/fs.h>
30 31
#include <linux/async.h>
#include <linux/pm.h>
32
#include <linux/suspend.h>
33
#include <linux/syscore_ops.h>
34
#include <linux/reboot.h>
35
#include <linux/security.h>
36

37 38
#include <generated/utsrelease.h>

39 40 41
#include "../base.h"
#include "firmware.h"
#include "fallback.h"
L
Linus Torvalds 已提交
42

43
MODULE_AUTHOR("Manuel Estrada Sainz");
L
Linus Torvalds 已提交
44 45 46
MODULE_DESCRIPTION("Multi purpose firmware loading support");
MODULE_LICENSE("GPL");

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
struct firmware_cache {
	/* firmware_buf instance will be added into the below list */
	spinlock_t lock;
	struct list_head head;
	int state;

#ifdef CONFIG_PM_SLEEP
	/*
	 * Names of firmware images which have been cached successfully
	 * will be added into the below list so that device uncache
	 * helper can trace which firmware images have been cached
	 * before.
	 */
	spinlock_t name_lock;
	struct list_head fw_names;

	struct delayed_work work;

	struct notifier_block   pm_notify;
#endif
};

struct fw_cache_entry {
	struct list_head list;
	const char *name;
};

struct fw_name_devm {
	unsigned long magic;
	const char *name;
};

79 80 81 82
static inline struct fw_priv *to_fw_priv(struct kref *ref)
{
	return container_of(ref, struct fw_priv, ref);
}
83 84 85 86 87 88

#define	FW_LOADER_NO_CACHE	0
#define	FW_LOADER_START_CACHE	1

/* fw_lock could be moved to 'struct fw_sysfs' but since it is just
 * guarding for corner cases a global lock should be OK */
89
DEFINE_MUTEX(fw_lock);
90 91 92

static struct firmware_cache fw_cache;

93 94 95 96 97 98 99
/* Builtin firmware support */

#ifdef CONFIG_FW_LOADER

extern struct builtin_fw __start_builtin_fw[];
extern struct builtin_fw __end_builtin_fw[];

100 101 102 103 104 105 106 107
static void fw_copy_to_prealloc_buf(struct firmware *fw,
				    void *buf, size_t size)
{
	if (!buf || size < fw->size)
		return;
	memcpy(buf, fw->data, fw->size);
}

108 109
static bool fw_get_builtin_firmware(struct firmware *fw, const char *name,
				    void *buf, size_t size)
110 111 112 113 114 115 116
{
	struct builtin_fw *b_fw;

	for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++) {
		if (strcmp(name, b_fw->name) == 0) {
			fw->size = b_fw->size;
			fw->data = b_fw->data;
117
			fw_copy_to_prealloc_buf(fw, buf, size);
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
			return true;
		}
	}

	return false;
}

static bool fw_is_builtin_firmware(const struct firmware *fw)
{
	struct builtin_fw *b_fw;

	for (b_fw = __start_builtin_fw; b_fw != __end_builtin_fw; b_fw++)
		if (fw->data == b_fw->data)
			return true;

	return false;
}

#else /* Module case - no builtin firmware support */

139 140 141
static inline bool fw_get_builtin_firmware(struct firmware *fw,
					   const char *name, void *buf,
					   size_t size)
142 143 144 145 146 147 148 149 150 151
{
	return false;
}

static inline bool fw_is_builtin_firmware(const struct firmware *fw)
{
	return false;
}
#endif

152
static void fw_state_init(struct fw_priv *fw_priv)
D
Daniel Wagner 已提交
153
{
154 155
	struct fw_state *fw_st = &fw_priv->fw_st;

156
	init_completion(&fw_st->completion);
D
Daniel Wagner 已提交
157 158 159
	fw_st->status = FW_STATUS_UNKNOWN;
}

160 161 162 163
static inline int fw_state_wait(struct fw_priv *fw_priv)
{
	return __fw_state_wait_common(fw_priv, MAX_SCHEDULE_TIMEOUT);
}
D
Daniel Wagner 已提交
164

165 166
static int fw_cache_piggyback_on_request(const char *name);

167 168 169
static struct fw_priv *__allocate_fw_priv(const char *fw_name,
					  struct firmware_cache *fwc,
					  void *dbuf, size_t size)
170
{
171
	struct fw_priv *fw_priv;
172

173 174
	fw_priv = kzalloc(sizeof(*fw_priv), GFP_ATOMIC);
	if (!fw_priv)
175 176
		return NULL;

177 178
	fw_priv->fw_name = kstrdup_const(fw_name, GFP_ATOMIC);
	if (!fw_priv->fw_name) {
179
		kfree(fw_priv);
180 181
		return NULL;
	}
182

183 184 185 186
	kref_init(&fw_priv->ref);
	fw_priv->fwc = fwc;
	fw_priv->data = dbuf;
	fw_priv->allocated_size = size;
187
	fw_state_init(fw_priv);
188
#ifdef CONFIG_FW_LOADER_USER_HELPER
189
	INIT_LIST_HEAD(&fw_priv->pending_list);
190
#endif
191

192
	pr_debug("%s: fw-%s fw_priv=%p\n", __func__, fw_name, fw_priv);
193

194
	return fw_priv;
195 196
}

197
static struct fw_priv *__lookup_fw_priv(const char *fw_name)
198
{
199
	struct fw_priv *tmp;
200 201 202
	struct firmware_cache *fwc = &fw_cache;

	list_for_each_entry(tmp, &fwc->head, list)
203
		if (!strcmp(tmp->fw_name, fw_name))
204 205 206 207
			return tmp;
	return NULL;
}

208
/* Returns 1 for batching firmware requests with the same name */
209 210 211
static int alloc_lookup_fw_priv(const char *fw_name,
				struct firmware_cache *fwc,
				struct fw_priv **fw_priv, void *dbuf,
212
				size_t size, enum fw_opt opt_flags)
213
{
214
	struct fw_priv *tmp;
215 216

	spin_lock(&fwc->lock);
217 218 219 220 221 222 223 224 225
	if (!(opt_flags & FW_OPT_NOCACHE)) {
		tmp = __lookup_fw_priv(fw_name);
		if (tmp) {
			kref_get(&tmp->ref);
			spin_unlock(&fwc->lock);
			*fw_priv = tmp;
			pr_debug("batched request - sharing the same struct fw_priv and lookup for multiple requests\n");
			return 1;
		}
226
	}
227

228
	tmp = __allocate_fw_priv(fw_name, fwc, dbuf, size);
229 230 231 232 233
	if (tmp) {
		INIT_LIST_HEAD(&tmp->list);
		if (!(opt_flags & FW_OPT_NOCACHE))
			list_add(&tmp->list, &fwc->head);
	}
234 235
	spin_unlock(&fwc->lock);

236
	*fw_priv = tmp;
237 238 239 240

	return tmp ? 0 : -ENOMEM;
}

241
static void __free_fw_priv(struct kref *ref)
242
	__releases(&fwc->lock)
243
{
244 245
	struct fw_priv *fw_priv = to_fw_priv(ref);
	struct firmware_cache *fwc = fw_priv->fwc;
246

247
	pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
248
		 __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
249
		 (unsigned int)fw_priv->size);
250

251
	list_del(&fw_priv->list);
252 253
	spin_unlock(&fwc->lock);

254
#ifdef CONFIG_FW_LOADER_USER_HELPER
255
	if (fw_priv->is_paged_buf) {
256
		int i;
257 258 259 260
		vunmap(fw_priv->data);
		for (i = 0; i < fw_priv->nr_pages; i++)
			__free_page(fw_priv->pages[i]);
		vfree(fw_priv->pages);
261
	} else
262
#endif
263 264
	if (!fw_priv->allocated_size)
		vfree(fw_priv->data);
265
	kfree_const(fw_priv->fw_name);
266
	kfree(fw_priv);
267 268
}

269
static void free_fw_priv(struct fw_priv *fw_priv)
270
{
271
	struct firmware_cache *fwc = fw_priv->fwc;
272
	spin_lock(&fwc->lock);
273
	if (!kref_put(&fw_priv->ref, __free_fw_priv))
274
		spin_unlock(&fwc->lock);
275 276
}

277
/* direct firmware loading support */
278 279 280
static char fw_path_para[256];
static const char * const fw_path[] = {
	fw_path_para,
281 282 283 284 285 286
	"/lib/firmware/updates/" UTS_RELEASE,
	"/lib/firmware/updates",
	"/lib/firmware/" UTS_RELEASE,
	"/lib/firmware"
};

287 288 289 290 291 292 293 294
/*
 * Typical usage is that passing 'firmware_class.path=$CUSTOMIZED_PATH'
 * from kernel command line because firmware_class is generally built in
 * kernel instead of module.
 */
module_param_string(path, fw_path_para, sizeof(fw_path_para), 0644);
MODULE_PARM_DESC(path, "customized firmware image search path with a higher priority than default path");

295
static int
296
fw_get_filesystem_firmware(struct device *device, struct fw_priv *fw_priv)
297
{
298
	loff_t size;
299
	int i, len;
300
	int rc = -ENOENT;
301
	char *path;
302 303 304 305
	enum kernel_read_file_id id = READING_FIRMWARE;
	size_t msize = INT_MAX;

	/* Already populated data member means we're loading into a buffer */
306
	if (fw_priv->data) {
307
		id = READING_FIRMWARE_PREALLOC_BUFFER;
308
		msize = fw_priv->allocated_size;
309
	}
310 311 312 313

	path = __getname();
	if (!path)
		return -ENOMEM;
314 315

	for (i = 0; i < ARRAY_SIZE(fw_path); i++) {
316 317 318 319
		/* skip the unset customized path */
		if (!fw_path[i][0])
			continue;

320
		len = snprintf(path, PATH_MAX, "%s/%s",
321
			       fw_path[i], fw_priv->fw_name);
322 323 324 325
		if (len >= PATH_MAX) {
			rc = -ENAMETOOLONG;
			break;
		}
326

327 328 329
		fw_priv->size = 0;
		rc = kernel_read_file_from_path(path, &fw_priv->data, &size,
						msize, id);
330
		if (rc) {
331 332 333 334 335 336
			if (rc == -ENOENT)
				dev_dbg(device, "loading %s failed with error %d\n",
					 path, rc);
			else
				dev_warn(device, "loading %s failed with error %d\n",
					 path, rc);
337 338
			continue;
		}
339
		dev_dbg(device, "direct-loading %s\n", fw_priv->fw_name);
340
		fw_priv->size = size;
341
		fw_state_done(fw_priv);
342
		break;
343
	}
344
	__putname(path);
345

346
	return rc;
347 348
}

349 350 351 352 353 354 355 356
/* firmware holds the ownership of pages */
static void firmware_free_data(const struct firmware *fw)
{
	/* Loaded directly? */
	if (!fw->priv) {
		vfree(fw->data);
		return;
	}
357
	free_fw_priv(fw->priv);
358 359
}

360
/* store the pages buffer info firmware from buf */
361
static void fw_set_page_data(struct fw_priv *fw_priv, struct firmware *fw)
362
{
363
	fw->priv = fw_priv;
364
#ifdef CONFIG_FW_LOADER_USER_HELPER
365
	fw->pages = fw_priv->pages;
366
#endif
367 368
	fw->size = fw_priv->size;
	fw->data = fw_priv->data;
369

370
	pr_debug("%s: fw-%s fw_priv=%p data=%p size=%u\n",
371
		 __func__, fw_priv->fw_name, fw_priv, fw_priv->data,
372
		 (unsigned int)fw_priv->size);
373 374 375 376 377 378 379 380 381 382
}

#ifdef CONFIG_PM_SLEEP
static void fw_name_devm_release(struct device *dev, void *res)
{
	struct fw_name_devm *fwn = res;

	if (fwn->magic == (unsigned long)&fw_cache)
		pr_debug("%s: fw_name-%s devm-%p released\n",
				__func__, fwn->name, res);
383
	kfree_const(fwn->name);
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
}

static int fw_devm_match(struct device *dev, void *res,
		void *match_data)
{
	struct fw_name_devm *fwn = res;

	return (fwn->magic == (unsigned long)&fw_cache) &&
		!strcmp(fwn->name, match_data);
}

static struct fw_name_devm *fw_find_devm_name(struct device *dev,
		const char *name)
{
	struct fw_name_devm *fwn;

	fwn = devres_find(dev, fw_name_devm_release,
			  fw_devm_match, (void *)name);
	return fwn;
}

405
static bool fw_cache_is_setup(struct device *dev, const char *name)
406 407 408 409 410
{
	struct fw_name_devm *fwn;

	fwn = fw_find_devm_name(dev, name);
	if (fwn)
411 412 413 414 415 416 417 418 419 420 421
		return true;

	return false;
}

/* add firmware name into devres list */
static int fw_add_devm_name(struct device *dev, const char *name)
{
	struct fw_name_devm *fwn;

	if (fw_cache_is_setup(dev, name))
422
		return 0;
423

424 425
	fwn = devres_alloc(fw_name_devm_release, sizeof(struct fw_name_devm),
			   GFP_KERNEL);
426 427
	if (!fwn)
		return -ENOMEM;
428 429
	fwn->name = kstrdup_const(name, GFP_KERNEL);
	if (!fwn->name) {
430
		devres_free(fwn);
431 432
		return -ENOMEM;
	}
433 434 435 436 437 438 439

	fwn->magic = (unsigned long)&fw_cache;
	devres_add(dev, fwn);

	return 0;
}
#else
440 441 442 443 444
static bool fw_cache_is_setup(struct device *dev, const char *name)
{
	return false;
}

445 446 447 448 449 450
static int fw_add_devm_name(struct device *dev, const char *name)
{
	return 0;
}
#endif

451
int assign_fw(struct firmware *fw, struct device *device,
452
	      enum fw_opt opt_flags)
453
{
454
	struct fw_priv *fw_priv = fw->priv;
455
	int ret;
456 457

	mutex_lock(&fw_lock);
458
	if (!fw_priv->size || fw_state_is_aborted(fw_priv)) {
459 460 461 462 463 464 465 466 467 468 469 470 471
		mutex_unlock(&fw_lock);
		return -ENOENT;
	}

	/*
	 * add firmware name into devres list so that we can auto cache
	 * and uncache firmware for device.
	 *
	 * device may has been deleted already, but the problem
	 * should be fixed in devres or driver core.
	 */
	/* don't cache firmware handled without uevent */
	if (device && (opt_flags & FW_OPT_UEVENT) &&
472 473 474 475 476 477 478
	    !(opt_flags & FW_OPT_NOCACHE)) {
		ret = fw_add_devm_name(device, fw_priv->fw_name);
		if (ret) {
			mutex_unlock(&fw_lock);
			return ret;
		}
	}
479 480 481 482 483 484

	/*
	 * After caching firmware image is started, let it piggyback
	 * on request firmware.
	 */
	if (!(opt_flags & FW_OPT_NOCACHE) &&
485
	    fw_priv->fwc->state == FW_LOADER_START_CACHE) {
486
		if (fw_cache_piggyback_on_request(fw_priv->fw_name))
487
			kref_get(&fw_priv->ref);
488 489 490
	}

	/* pass the pages buffer to driver at the last minute */
491
	fw_set_page_data(fw_priv, fw);
492 493 494
	mutex_unlock(&fw_lock);
	return 0;
}
495

496 497 498 499 500 501
/* prepare firmware and firmware_buf structs;
 * return 0 if a firmware is already assigned, 1 if need to load one,
 * or a negative error code
 */
static int
_request_firmware_prepare(struct firmware **firmware_p, const char *name,
502 503
			  struct device *device, void *dbuf, size_t size,
			  enum fw_opt opt_flags)
L
Linus Torvalds 已提交
504 505
{
	struct firmware *firmware;
506
	struct fw_priv *fw_priv;
507
	int ret;
L
Linus Torvalds 已提交
508

509
	*firmware_p = firmware = kzalloc(sizeof(*firmware), GFP_KERNEL);
L
Linus Torvalds 已提交
510
	if (!firmware) {
511 512
		dev_err(device, "%s: kmalloc(struct firmware) failed\n",
			__func__);
513
		return -ENOMEM;
L
Linus Torvalds 已提交
514 515
	}

516
	if (fw_get_builtin_firmware(firmware, name, dbuf, size)) {
517
		dev_dbg(device, "using built-in %s\n", name);
518
		return 0; /* assigned */
519 520
	}

521 522
	ret = alloc_lookup_fw_priv(name, &fw_cache, &fw_priv, dbuf, size,
				  opt_flags);
523 524

	/*
525
	 * bind with 'priv' now to avoid warning in failure path
526 527
	 * of requesting firmware.
	 */
528
	firmware->priv = fw_priv;
529 530

	if (ret > 0) {
531
		ret = fw_state_wait(fw_priv);
532
		if (!ret) {
533
			fw_set_page_data(fw_priv, firmware);
534 535
			return 0; /* assigned */
		}
536
	}
537

538 539 540 541 542
	if (ret < 0)
		return ret;
	return 1; /* need to load */
}

543 544 545 546 547 548
/*
 * Batched requests need only one wake, we need to do this step last due to the
 * fallback mechanism. The buf is protected with kref_get(), and it won't be
 * released until the last user calls release_firmware().
 *
 * Failed batched requests are possible as well, in such cases we just share
549
 * the struct fw_priv and won't release it until all requests are woken
550 551 552 553
 * and have gone through this same path.
 */
static void fw_abort_batch_reqs(struct firmware *fw)
{
554
	struct fw_priv *fw_priv;
555 556 557 558 559

	/* Loaded directly? */
	if (!fw || !fw->priv)
		return;

560
	fw_priv = fw->priv;
561 562
	if (!fw_state_is_aborted(fw_priv))
		fw_state_aborted(fw_priv);
563 564
}

565 566 567
/* called from request_firmware() and request_firmware_work_func() */
static int
_request_firmware(const struct firmware **firmware_p, const char *name,
568
		  struct device *device, void *buf, size_t size,
569
		  enum fw_opt opt_flags)
570
{
571
	struct firmware *fw = NULL;
572 573 574 575 576
	int ret;

	if (!firmware_p)
		return -EINVAL;

577 578 579 580
	if (!name || name[0] == '\0') {
		ret = -EINVAL;
		goto out;
	}
581

582 583
	ret = _request_firmware_prepare(&fw, name, device, buf, size,
					opt_flags);
584 585 586
	if (ret <= 0) /* error or already assigned */
		goto out;

587 588
	ret = fw_get_filesystem_firmware(device, fw->priv);
	if (ret) {
589
		if (!(opt_flags & FW_OPT_NO_WARN))
590
			dev_warn(device,
591 592
				 "Direct firmware load for %s failed with error %d\n",
				 name, ret);
593
		ret = firmware_fallback_sysfs(fw, name, device, opt_flags, ret);
594
	} else
595
		ret = assign_fw(fw, device, opt_flags);
596 597 598

 out:
	if (ret < 0) {
599
		fw_abort_batch_reqs(fw);
600 601 602 603 604 605 606 607
		release_firmware(fw);
		fw = NULL;
	}

	*firmware_p = fw;
	return ret;
}

608
/**
609
 * request_firmware() - send firmware request and wait for it
610 611 612 613 614
 * @firmware_p: pointer to firmware image
 * @name: name of firmware file
 * @device: device for which firmware is being loaded
 *
 *      @firmware_p will be used to return a firmware image by the name
615 616 617 618
 *      of @name for device @device.
 *
 *      Should be called from user context where sleeping is allowed.
 *
619
 *      @name will be used as $FIRMWARE in the uevent environment and
620 621
 *      should be distinctive enough not to be confused with any other
 *      firmware image for this or any other device.
M
Ming Lei 已提交
622 623
 *
 *	Caller must hold the reference count of @device.
624 625 626
 *
 *	The function can be called safely inside device's suspend and
 *	resume callback.
627 628 629
 **/
int
request_firmware(const struct firmware **firmware_p, const char *name,
630
		 struct device *device)
631
{
632 633 634 635
	int ret;

	/* Need to pin this module until return */
	__module_get(THIS_MODULE);
636
	ret = _request_firmware(firmware_p, name, device, NULL, 0,
637
				FW_OPT_UEVENT);
638 639
	module_put(THIS_MODULE);
	return ret;
640
}
641
EXPORT_SYMBOL(request_firmware);
642

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
/**
 * firmware_request_nowarn() - request for an optional fw module
 * @firmware: pointer to firmware image
 * @name: name of firmware file
 * @device: device for which firmware is being loaded
 *
 * This function is similar in behaviour to request_firmware(), except
 * it doesn't produce warning messages when the file is not found.
 * The sysfs fallback mechanism is enabled if direct filesystem lookup fails,
 * however, however failures to find the firmware file with it are still
 * suppressed. It is therefore up to the driver to check for the return value
 * of this call and to decide when to inform the users of errors.
 **/
int firmware_request_nowarn(const struct firmware **firmware, const char *name,
			    struct device *device)
{
	int ret;

	/* Need to pin this module until return */
	__module_get(THIS_MODULE);
	ret = _request_firmware(firmware, name, device, NULL, 0,
				FW_OPT_UEVENT | FW_OPT_NO_WARN);
	module_put(THIS_MODULE);
	return ret;
}
EXPORT_SYMBOL_GPL(firmware_request_nowarn);

670
/**
671
 * request_firmware_direct() - load firmware directly without usermode helper
672 673 674 675 676 677 678 679 680 681 682 683 684
 * @firmware_p: pointer to firmware image
 * @name: name of firmware file
 * @device: device for which firmware is being loaded
 *
 * This function works pretty much like request_firmware(), but this doesn't
 * fall back to usermode helper even if the firmware couldn't be loaded
 * directly from fs.  Hence it's useful for loading optional firmwares, which
 * aren't always present, without extra long timeouts of udev.
 **/
int request_firmware_direct(const struct firmware **firmware_p,
			    const char *name, struct device *device)
{
	int ret;
685

686
	__module_get(THIS_MODULE);
687
	ret = _request_firmware(firmware_p, name, device, NULL, 0,
688 689
				FW_OPT_UEVENT | FW_OPT_NO_WARN |
				FW_OPT_NOFALLBACK);
690 691 692 693 694
	module_put(THIS_MODULE);
	return ret;
}
EXPORT_SYMBOL_GPL(request_firmware_direct);

695
/**
696
 * firmware_request_cache() - cache firmware for suspend so resume can use it
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
 * @name: name of firmware file
 * @device: device for which firmware should be cached for
 *
 * There are some devices with an optimization that enables the device to not
 * require loading firmware on system reboot. This optimization may still
 * require the firmware present on resume from suspend. This routine can be
 * used to ensure the firmware is present on resume from suspend in these
 * situations. This helper is not compatible with drivers which use
 * request_firmware_into_buf() or request_firmware_nowait() with no uevent set.
 **/
int firmware_request_cache(struct device *device, const char *name)
{
	int ret;

	mutex_lock(&fw_lock);
	ret = fw_add_devm_name(device, name);
	mutex_unlock(&fw_lock);

	return ret;
}
EXPORT_SYMBOL_GPL(firmware_request_cache);

719
/**
720
 * request_firmware_into_buf() - load firmware into a previously allocated buffer
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
 * @firmware_p: pointer to firmware image
 * @name: name of firmware file
 * @device: device for which firmware is being loaded and DMA region allocated
 * @buf: address of buffer to load firmware into
 * @size: size of buffer
 *
 * This function works pretty much like request_firmware(), but it doesn't
 * allocate a buffer to hold the firmware data. Instead, the firmware
 * is loaded directly into the buffer pointed to by @buf and the @firmware_p
 * data member is pointed at @buf.
 *
 * This function doesn't cache firmware either.
 */
int
request_firmware_into_buf(const struct firmware **firmware_p, const char *name,
			  struct device *device, void *buf, size_t size)
{
	int ret;

740 741 742
	if (fw_cache_is_setup(device, name))
		return -EOPNOTSUPP;

743 744
	__module_get(THIS_MODULE);
	ret = _request_firmware(firmware_p, name, device, buf, size,
745
				FW_OPT_UEVENT | FW_OPT_NOCACHE);
746 747 748 749 750
	module_put(THIS_MODULE);
	return ret;
}
EXPORT_SYMBOL(request_firmware_into_buf);

L
Linus Torvalds 已提交
751
/**
752
 * release_firmware() - release the resource associated with a firmware image
753
 * @fw: firmware resource to release
L
Linus Torvalds 已提交
754
 **/
755
void release_firmware(const struct firmware *fw)
L
Linus Torvalds 已提交
756 757
{
	if (fw) {
758 759
		if (!fw_is_builtin_firmware(fw))
			firmware_free_data(fw);
L
Linus Torvalds 已提交
760 761 762
		kfree(fw);
	}
}
763
EXPORT_SYMBOL(release_firmware);
L
Linus Torvalds 已提交
764 765 766 767 768 769 770 771 772

/* Async support */
struct firmware_work {
	struct work_struct work;
	struct module *module;
	const char *name;
	struct device *device;
	void *context;
	void (*cont)(const struct firmware *fw, void *context);
773
	enum fw_opt opt_flags;
L
Linus Torvalds 已提交
774 775
};

776
static void request_firmware_work_func(struct work_struct *work)
L
Linus Torvalds 已提交
777
{
778
	struct firmware_work *fw_work;
L
Linus Torvalds 已提交
779
	const struct firmware *fw;
780

781
	fw_work = container_of(work, struct firmware_work, work);
782

783
	_request_firmware(&fw, fw_work->name, fw_work->device, NULL, 0,
784
			  fw_work->opt_flags);
785
	fw_work->cont(fw, fw_work->context);
786
	put_device(fw_work->device); /* taken in request_firmware_nowait() */
787

L
Linus Torvalds 已提交
788
	module_put(fw_work->module);
789
	kfree_const(fw_work->name);
L
Linus Torvalds 已提交
790 791 792 793
	kfree(fw_work);
}

/**
794
 * request_firmware_nowait() - asynchronous version of request_firmware
795
 * @module: module requesting the firmware
796
 * @uevent: sends uevent to copy the firmware image if this flag
797 798 799
 *	is non-zero else the firmware copy must be done manually.
 * @name: name of firmware file
 * @device: device for which firmware is being loaded
800
 * @gfp: allocation flags
801 802 803 804
 * @context: will be passed over to @cont, and
 *	@fw may be %NULL if firmware request fails.
 * @cont: function will be called asynchronously when the firmware
 *	request is over.
L
Linus Torvalds 已提交
805
 *
M
Ming Lei 已提交
806 807
 *	Caller must hold the reference count of @device.
 *
808 809
 *	Asynchronous variant of request_firmware() for user contexts:
 *		- sleep for as small periods as possible since it may
810 811 812
 *		  increase kernel boot time of built-in device drivers
 *		  requesting firmware in their ->probe() methods, if
 *		  @gfp is GFP_KERNEL.
813 814
 *
 *		- can't sleep at all if @gfp is GFP_ATOMIC.
L
Linus Torvalds 已提交
815 816 817
 **/
int
request_firmware_nowait(
818
	struct module *module, bool uevent,
819
	const char *name, struct device *device, gfp_t gfp, void *context,
L
Linus Torvalds 已提交
820 821
	void (*cont)(const struct firmware *fw, void *context))
{
822
	struct firmware_work *fw_work;
L
Linus Torvalds 已提交
823

824
	fw_work = kzalloc(sizeof(struct firmware_work), gfp);
L
Linus Torvalds 已提交
825 826
	if (!fw_work)
		return -ENOMEM;
827 828

	fw_work->module = module;
829
	fw_work->name = kstrdup_const(name, gfp);
830 831
	if (!fw_work->name) {
		kfree(fw_work);
832
		return -ENOMEM;
833
	}
834 835 836
	fw_work->device = device;
	fw_work->context = context;
	fw_work->cont = cont;
837
	fw_work->opt_flags = FW_OPT_NOWAIT |
838
		(uevent ? FW_OPT_UEVENT : FW_OPT_USERHELPER);
839

840 841 842 843 844 845
	if (!uevent && fw_cache_is_setup(device, name)) {
		kfree_const(fw_work->name);
		kfree(fw_work);
		return -EOPNOTSUPP;
	}

L
Linus Torvalds 已提交
846
	if (!try_module_get(module)) {
847
		kfree_const(fw_work->name);
L
Linus Torvalds 已提交
848 849 850 851
		kfree(fw_work);
		return -EFAULT;
	}

M
Ming Lei 已提交
852
	get_device(fw_work->device);
853 854
	INIT_WORK(&fw_work->work, request_firmware_work_func);
	schedule_work(&fw_work->work);
L
Linus Torvalds 已提交
855 856
	return 0;
}
857
EXPORT_SYMBOL(request_firmware_nowait);
L
Linus Torvalds 已提交
858

859 860 861
#ifdef CONFIG_PM_SLEEP
static ASYNC_DOMAIN_EXCLUSIVE(fw_cache_domain);

862
/**
863
 * cache_firmware() - cache one firmware image in kernel memory space
864 865 866 867 868 869 870 871 872 873 874 875
 * @fw_name: the firmware image name
 *
 * Cache firmware in kernel memory so that drivers can use it when
 * system isn't ready for them to request firmware image from userspace.
 * Once it returns successfully, driver can use request_firmware or its
 * nowait version to get the cached firmware without any interacting
 * with userspace
 *
 * Return 0 if the firmware image has been cached successfully
 * Return !0 otherwise
 *
 */
876
static int cache_firmware(const char *fw_name)
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
{
	int ret;
	const struct firmware *fw;

	pr_debug("%s: %s\n", __func__, fw_name);

	ret = request_firmware(&fw, fw_name, NULL);
	if (!ret)
		kfree(fw);

	pr_debug("%s: %s ret=%d\n", __func__, fw_name, ret);

	return ret;
}

892
static struct fw_priv *lookup_fw_priv(const char *fw_name)
893
{
894
	struct fw_priv *tmp;
895 896 897
	struct firmware_cache *fwc = &fw_cache;

	spin_lock(&fwc->lock);
898
	tmp = __lookup_fw_priv(fw_name);
899 900 901 902 903
	spin_unlock(&fwc->lock);

	return tmp;
}

904
/**
905
 * uncache_firmware() - remove one cached firmware image
906 907 908 909 910 911 912 913 914
 * @fw_name: the firmware image name
 *
 * Uncache one firmware image which has been cached successfully
 * before.
 *
 * Return 0 if the firmware cache has been removed successfully
 * Return !0 otherwise
 *
 */
915
static int uncache_firmware(const char *fw_name)
916
{
917
	struct fw_priv *fw_priv;
918 919 920 921
	struct firmware fw;

	pr_debug("%s: %s\n", __func__, fw_name);

922
	if (fw_get_builtin_firmware(&fw, fw_name, NULL, 0))
923 924
		return 0;

925 926 927
	fw_priv = lookup_fw_priv(fw_name);
	if (fw_priv) {
		free_fw_priv(fw_priv);
928 929 930 931 932 933
		return 0;
	}

	return -EINVAL;
}

934 935 936 937
static struct fw_cache_entry *alloc_fw_cache_entry(const char *name)
{
	struct fw_cache_entry *fce;

938
	fce = kzalloc(sizeof(*fce), GFP_ATOMIC);
939 940 941
	if (!fce)
		goto exit;

942 943 944 945 946 947
	fce->name = kstrdup_const(name, GFP_ATOMIC);
	if (!fce->name) {
		kfree(fce);
		fce = NULL;
		goto exit;
	}
948 949 950 951
exit:
	return fce;
}

952
static int __fw_entry_found(const char *name)
953 954 955 956 957 958
{
	struct firmware_cache *fwc = &fw_cache;
	struct fw_cache_entry *fce;

	list_for_each_entry(fce, &fwc->fw_names, list) {
		if (!strcmp(fce->name, name))
959
			return 1;
960
	}
961 962 963 964 965 966 967 968 969 970 971 972
	return 0;
}

static int fw_cache_piggyback_on_request(const char *name)
{
	struct firmware_cache *fwc = &fw_cache;
	struct fw_cache_entry *fce;
	int ret = 0;

	spin_lock(&fwc->name_lock);
	if (__fw_entry_found(name))
		goto found;
973 974 975 976 977 978 979 980 981 982 983 984

	fce = alloc_fw_cache_entry(name);
	if (fce) {
		ret = 1;
		list_add(&fce->list, &fwc->fw_names);
		pr_debug("%s: fw: %s\n", __func__, name);
	}
found:
	spin_unlock(&fwc->name_lock);
	return ret;
}

985 986
static void free_fw_cache_entry(struct fw_cache_entry *fce)
{
987
	kfree_const(fce->name);
988 989 990 991 992 993 994 995 996 997 998
	kfree(fce);
}

static void __async_dev_cache_fw_image(void *fw_entry,
				       async_cookie_t cookie)
{
	struct fw_cache_entry *fce = fw_entry;
	struct firmware_cache *fwc = &fw_cache;
	int ret;

	ret = cache_firmware(fce->name);
999 1000 1001 1002
	if (ret) {
		spin_lock(&fwc->name_lock);
		list_del(&fce->list);
		spin_unlock(&fwc->name_lock);
1003

1004 1005
		free_fw_cache_entry(fce);
	}
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
}

/* called with dev->devres_lock held */
static void dev_create_fw_entry(struct device *dev, void *res,
				void *data)
{
	struct fw_name_devm *fwn = res;
	const char *fw_name = fwn->name;
	struct list_head *head = data;
	struct fw_cache_entry *fce;

	fce = alloc_fw_cache_entry(fw_name);
	if (fce)
		list_add(&fce->list, head);
}

static int devm_name_match(struct device *dev, void *res,
			   void *match_data)
{
	struct fw_name_devm *fwn = res;
	return (fwn->magic == (unsigned long)match_data);
}

1029
static void dev_cache_fw_image(struct device *dev, void *data)
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
{
	LIST_HEAD(todo);
	struct fw_cache_entry *fce;
	struct fw_cache_entry *fce_next;
	struct firmware_cache *fwc = &fw_cache;

	devres_for_each_res(dev, fw_name_devm_release,
			    devm_name_match, &fw_cache,
			    dev_create_fw_entry, &todo);

	list_for_each_entry_safe(fce, fce_next, &todo, list) {
		list_del(&fce->list);

		spin_lock(&fwc->name_lock);
1044 1045 1046 1047 1048 1049 1050
		/* only one cache entry for one firmware */
		if (!__fw_entry_found(fce->name)) {
			list_add(&fce->list, &fwc->fw_names);
		} else {
			free_fw_cache_entry(fce);
			fce = NULL;
		}
1051 1052
		spin_unlock(&fwc->name_lock);

1053
		if (fce)
1054 1055 1056
			async_schedule_domain(__async_dev_cache_fw_image,
					      (void *)fce,
					      &fw_cache_domain);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
	}
}

static void __device_uncache_fw_images(void)
{
	struct firmware_cache *fwc = &fw_cache;
	struct fw_cache_entry *fce;

	spin_lock(&fwc->name_lock);
	while (!list_empty(&fwc->fw_names)) {
		fce = list_entry(fwc->fw_names.next,
				struct fw_cache_entry, list);
		list_del(&fce->list);
		spin_unlock(&fwc->name_lock);

		uncache_firmware(fce->name);
		free_fw_cache_entry(fce);

		spin_lock(&fwc->name_lock);
	}
	spin_unlock(&fwc->name_lock);
}

/**
1081
 * device_cache_fw_images() - cache devices' firmware
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
 *
 * If one device called request_firmware or its nowait version
 * successfully before, the firmware names are recored into the
 * device's devres link list, so device_cache_fw_images can call
 * cache_firmware() to cache these firmwares for the device,
 * then the device driver can load its firmwares easily at
 * time when system is not ready to complete loading firmware.
 */
static void device_cache_fw_images(void)
{
	struct firmware_cache *fwc = &fw_cache;
	DEFINE_WAIT(wait);

	pr_debug("%s\n", __func__);

1097 1098 1099
	/* cancel uncache work */
	cancel_delayed_work_sync(&fwc->work);

1100
	fw_fallback_set_cache_timeout();
1101

1102 1103
	mutex_lock(&fw_lock);
	fwc->state = FW_LOADER_START_CACHE;
1104
	dpm_for_each_dev(NULL, dev_cache_fw_image);
1105
	mutex_unlock(&fw_lock);
1106 1107

	/* wait for completion of caching firmware for all devices */
1108
	async_synchronize_full_domain(&fw_cache_domain);
1109

1110
	fw_fallback_set_default_timeout();
1111 1112 1113
}

/**
1114
 * device_uncache_fw_images() - uncache devices' firmware
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
 *
 * uncache all firmwares which have been cached successfully
 * by device_uncache_fw_images earlier
 */
static void device_uncache_fw_images(void)
{
	pr_debug("%s\n", __func__);
	__device_uncache_fw_images();
}

static void device_uncache_fw_images_work(struct work_struct *work)
{
	device_uncache_fw_images();
}

/**
1131
 * device_uncache_fw_images_delay() - uncache devices firmwares
1132 1133 1134 1135 1136 1137 1138
 * @delay: number of milliseconds to delay uncache device firmwares
 *
 * uncache all devices's firmwares which has been cached successfully
 * by device_cache_fw_images after @delay milliseconds.
 */
static void device_uncache_fw_images_delay(unsigned long delay)
{
1139 1140
	queue_delayed_work(system_power_efficient_wq, &fw_cache.work,
			   msecs_to_jiffies(delay));
1141 1142
}

1143 1144 1145 1146 1147 1148
static int fw_pm_notify(struct notifier_block *notify_block,
			unsigned long mode, void *unused)
{
	switch (mode) {
	case PM_HIBERNATION_PREPARE:
	case PM_SUSPEND_PREPARE:
1149
	case PM_RESTORE_PREPARE:
1150 1151 1152 1153 1154
		/*
		 * kill pending fallback requests with a custom fallback
		 * to avoid stalling suspend.
		 */
		kill_pending_fw_fallback_reqs(true);
1155 1156 1157 1158 1159 1160
		device_cache_fw_images();
		break;

	case PM_POST_SUSPEND:
	case PM_POST_HIBERNATION:
	case PM_POST_RESTORE:
1161 1162 1163 1164 1165 1166 1167 1168
		/*
		 * In case that system sleep failed and syscore_suspend is
		 * not called.
		 */
		mutex_lock(&fw_lock);
		fw_cache.state = FW_LOADER_NO_CACHE;
		mutex_unlock(&fw_lock);

1169 1170 1171 1172 1173 1174 1175
		device_uncache_fw_images_delay(10 * MSEC_PER_SEC);
		break;
	}

	return 0;
}

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
/* stop caching firmware once syscore_suspend is reached */
static int fw_suspend(void)
{
	fw_cache.state = FW_LOADER_NO_CACHE;
	return 0;
}

static struct syscore_ops fw_syscore_ops = {
	.suspend = fw_suspend,
};
1186

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
static int __init register_fw_pm_ops(void)
{
	int ret;

	spin_lock_init(&fw_cache.name_lock);
	INIT_LIST_HEAD(&fw_cache.fw_names);

	INIT_DELAYED_WORK(&fw_cache.work,
			  device_uncache_fw_images_work);

	fw_cache.pm_notify.notifier_call = fw_pm_notify;
	ret = register_pm_notifier(&fw_cache.pm_notify);
	if (ret)
		return ret;

	register_syscore_ops(&fw_syscore_ops);

	return ret;
}

1207 1208 1209 1210 1211
static inline void unregister_fw_pm_ops(void)
{
	unregister_syscore_ops(&fw_syscore_ops);
	unregister_pm_notifier(&fw_cache.pm_notify);
}
1212 1213 1214 1215 1216
#else
static int fw_cache_piggyback_on_request(const char *name)
{
	return 0;
}
1217 1218 1219 1220
static inline int register_fw_pm_ops(void)
{
	return 0;
}
1221 1222 1223
static inline void unregister_fw_pm_ops(void)
{
}
1224
#endif
1225

1226 1227 1228 1229
static void __init fw_cache_init(void)
{
	spin_lock_init(&fw_cache.lock);
	INIT_LIST_HEAD(&fw_cache.head);
1230
	fw_cache.state = FW_LOADER_NO_CACHE;
1231 1232
}

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
static int fw_shutdown_notify(struct notifier_block *unused1,
			      unsigned long unused2, void *unused3)
{
	/*
	 * Kill all pending fallback requests to avoid both stalling shutdown,
	 * and avoid a deadlock with the usermode_lock.
	 */
	kill_pending_fw_fallback_reqs(false);

	return NOTIFY_DONE;
}

static struct notifier_block fw_shutdown_nb = {
	.notifier_call = fw_shutdown_notify,
};

1249
static int __init firmware_class_init(void)
L
Linus Torvalds 已提交
1250
{
1251 1252 1253
	int ret;

	/* No need to unfold these on exit */
1254
	fw_cache_init();
1255 1256 1257 1258 1259

	ret = register_fw_pm_ops();
	if (ret)
		return ret;

1260 1261 1262 1263
	ret = register_reboot_notifier(&fw_shutdown_nb);
	if (ret)
		goto out;

1264
	return register_sysfs_loader();
1265 1266 1267 1268

out:
	unregister_fw_pm_ops();
	return ret;
L
Linus Torvalds 已提交
1269
}
1270 1271

static void __exit firmware_class_exit(void)
L
Linus Torvalds 已提交
1272
{
1273
	unregister_fw_pm_ops();
1274
	unregister_reboot_notifier(&fw_shutdown_nb);
1275
	unregister_sysfs_loader();
L
Linus Torvalds 已提交
1276 1277
}

1278
fs_initcall(firmware_class_init);
L
Linus Torvalds 已提交
1279
module_exit(firmware_class_exit);