android_kernel_xiaomi_sm8450/block/blk-crypto.c
Greg Kroah-Hartman 2300418cc6 This is the 5.10.65 stable release
-----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEZH8oZUiU471FcZm+ONu9yGCSaT4FAmFBpvcACgkQONu9yGCS
 aT7JVxAAof4h5rPObKwhFBu4qOHXEtlHrFAF1xTEaQZnIbv9CkEF0LPufWXP+nKS
 mQDOdDmX3rZhWXZbnNK3ZxBADJXyHS6M0jHByuGrzQ8dmMONJtpjYUjxou6k/xg2
 4ECHqzeVbwbWuKrJrAfC1xuZofIHXZBHrkAQmLoMw8ERp309lgPS2cXDOXRzn/n/
 ri+5AhTaw1ZG1JXrXvyfoxjbdE/eEeJXx8N/zJf0sas5lYpsqeAWTgXBkNpPeJm7
 G66ISwEVp6TPxihpRSKwUhADjuM2+EAok2WXwwTvO0s00vE7LL5ijK27hhP5ual1
 +xtxBHag95oIZ+sq1t3z4BgmE1n3z/lHkQki98JQaWShABLGhMdKYPF75hMzR6Pw
 j0TvLHdkPRSrtUelc7rGtqaT9tF9+RU59I5fPGlBpGckOJ5u2IHCKdjk1WadRgrj
 JF7R8ApfP18y1X46tDfr/CIPIZfTVNJyd7hZ1zt11wdBYFmaw/oNyg81OalqzaWf
 ckUIt6AucRQ04uuFfhSaTuxLSEl5Uuh6W30HuO/0N3CoDsfD1RMc+76sXORt/JdK
 MPxTy124KM6VZADVW4tQXHMoGkLftqTAIgRKt4iRPz80rdhACJFoZJlmVON0MmKV
 tSODsqGBxIxhkLj197vQzT152G4wBkmzPtqJfJH7lkGKmBpoKZE=
 =lJCV
 -----END PGP SIGNATURE-----

Merge 5.10.65 into android12-5.10-lts

Changes in 5.10.65
	locking/mutex: Fix HANDOFF condition
	regmap: fix the offset of register error log
	regulator: tps65910: Silence deferred probe error
	crypto: mxs-dcp - Check for DMA mapping errors
	sched/deadline: Fix reset_on_fork reporting of DL tasks
	power: supply: axp288_fuel_gauge: Report register-address on readb / writeb errors
	crypto: omap-sham - clear dma flags only after omap_sham_update_dma_stop()
	sched/deadline: Fix missing clock update in migrate_task_rq_dl()
	rcu/tree: Handle VM stoppage in stall detection
	EDAC/mce_amd: Do not load edac_mce_amd module on guests
	posix-cpu-timers: Force next expiration recalc after itimer reset
	hrtimer: Avoid double reprogramming in __hrtimer_start_range_ns()
	hrtimer: Ensure timerfd notification for HIGHRES=n
	udf: Check LVID earlier
	udf: Fix iocharset=utf8 mount option
	isofs: joliet: Fix iocharset=utf8 mount option
	bcache: add proper error unwinding in bcache_device_init
	blk-throtl: optimize IOPS throttle for large IO scenarios
	nvme-tcp: don't update queue count when failing to set io queues
	nvme-rdma: don't update queue count when failing to set io queues
	nvmet: pass back cntlid on successful completion
	power: supply: smb347-charger: Add missing pin control activation
	power: supply: max17042_battery: fix typo in MAx17042_TOFF
	s390/cio: add dev_busid sysfs entry for each subchannel
	s390/zcrypt: fix wrong offset index for APKA master key valid state
	libata: fix ata_host_start()
	crypto: omap - Fix inconsistent locking of device lists
	crypto: qat - do not ignore errors from enable_vf2pf_comms()
	crypto: qat - handle both source of interrupt in VF ISR
	crypto: qat - fix reuse of completion variable
	crypto: qat - fix naming for init/shutdown VF to PF notifications
	crypto: qat - do not export adf_iov_putmsg()
	fcntl: fix potential deadlock for &fasync_struct.fa_lock
	udf_get_extendedattr() had no boundary checks.
	s390/kasan: fix large PMD pages address alignment check
	s390/pci: fix misleading rc in clp_set_pci_fn()
	s390/debug: keep debug data on resize
	s390/debug: fix debug area life cycle
	s390/ap: fix state machine hang after failure to enable irq
	power: supply: cw2015: use dev_err_probe to allow deferred probe
	m68k: emu: Fix invalid free in nfeth_cleanup()
	sched/numa: Fix is_core_idle()
	sched: Fix UCLAMP_FLAG_IDLE setting
	rcu: Fix to include first blocked task in stall warning
	rcu: Add lockdep_assert_irqs_disabled() to rcu_sched_clock_irq() and callees
	rcu: Fix stall-warning deadlock due to non-release of rcu_node ->lock
	m68k: Fix invalid RMW_INSNS on CPUs that lack CAS
	block: return ELEVATOR_DISCARD_MERGE if possible
	spi: spi-fsl-dspi: Fix issue with uninitialized dma_slave_config
	spi: spi-pic32: Fix issue with uninitialized dma_slave_config
	genirq/timings: Fix error return code in irq_timings_test_irqs()
	irqchip/loongson-pch-pic: Improve edge triggered interrupt support
	lib/mpi: use kcalloc in mpi_resize
	clocksource/drivers/sh_cmt: Fix wrong setting if don't request IRQ for clock source channel
	block: nbd: add sanity check for first_minor
	spi: coldfire-qspi: Use clk_disable_unprepare in the remove function
	irqchip/gic-v3: Fix priority comparison when non-secure priorities are used
	crypto: qat - use proper type for vf_mask
	certs: Trigger creation of RSA module signing key if it's not an RSA key
	tpm: ibmvtpm: Avoid error message when process gets signal while waiting
	x86/mce: Defer processing of early errors
	spi: davinci: invoke chipselect callback
	blk-crypto: fix check for too-large dun_bytes
	regulator: vctrl: Use locked regulator_get_voltage in probe path
	regulator: vctrl: Avoid lockdep warning in enable/disable ops
	spi: sprd: Fix the wrong WDG_LOAD_VAL
	spi: spi-zynq-qspi: use wait_for_completion_timeout to make zynq_qspi_exec_mem_op not interruptible
	EDAC/i10nm: Fix NVDIMM detection
	drm/panfrost: Fix missing clk_disable_unprepare() on error in panfrost_clk_init()
	drm/gma500: Fix end of loop tests for list_for_each_entry
	ASoC: mediatek: mt8183: Fix Unbalanced pm_runtime_enable in mt8183_afe_pcm_dev_probe
	media: TDA1997x: enable EDID support
	leds: is31fl32xx: Fix missing error code in is31fl32xx_parse_dt()
	soc: rockchip: ROCKCHIP_GRF should not default to y, unconditionally
	media: cxd2880-spi: Fix an error handling path
	drm/of: free the right object
	bpf: Fix a typo of reuseport map in bpf.h.
	bpf: Fix potential memleak and UAF in the verifier.
	drm/of: free the iterator object on failure
	gve: fix the wrong AdminQ buffer overflow check
	libbpf: Fix the possible memory leak on error
	ARM: dts: aspeed-g6: Fix HVI3C function-group in pinctrl dtsi
	arm64: dts: renesas: r8a77995: draak: Remove bogus adv7511w properties
	i40e: improve locking of mac_filter_hash
	soc: qcom: rpmhpd: Use corner in power_off
	libbpf: Fix removal of inner map in bpf_object__create_map
	gfs2: Fix memory leak of object lsi on error return path
	firmware: fix theoretical UAF race with firmware cache and resume
	driver core: Fix error return code in really_probe()
	ionic: cleanly release devlink instance
	media: dvb-usb: fix uninit-value in dvb_usb_adapter_dvb_init
	media: dvb-usb: fix uninit-value in vp702x_read_mac_addr
	media: dvb-usb: Fix error handling in dvb_usb_i2c_init
	media: go7007: fix memory leak in go7007_usb_probe
	media: go7007: remove redundant initialization
	media: rockchip/rga: use pm_runtime_resume_and_get()
	media: rockchip/rga: fix error handling in probe
	media: coda: fix frame_mem_ctrl for YUV420 and YVU420 formats
	media: atomisp: fix the uninitialized use and rename "retvalue"
	Bluetooth: sco: prevent information leak in sco_conn_defer_accept()
	6lowpan: iphc: Fix an off-by-one check of array index
	drm/amdgpu/acp: Make PM domain really work
	tcp: seq_file: Avoid skipping sk during tcp_seek_last_pos
	ARM: dts: meson8: Use a higher default GPU clock frequency
	ARM: dts: meson8b: odroidc1: Fix the pwm regulator supply properties
	ARM: dts: meson8b: mxq: Fix the pwm regulator supply properties
	ARM: dts: meson8b: ec100: Fix the pwm regulator supply properties
	net/mlx5e: Prohibit inner indir TIRs in IPoIB
	net/mlx5e: Block LRO if firmware asks for tunneled LRO
	cgroup/cpuset: Fix a partition bug with hotplug
	drm: mxsfb: Enable recovery on underflow
	drm: mxsfb: Increase number of outstanding requests on V4 and newer HW
	drm: mxsfb: Clear FIFO_CLEAR bit
	net: cipso: fix warnings in netlbl_cipsov4_add_std
	Bluetooth: mgmt: Fix wrong opcode in the response for add_adv cmd
	arm64: dts: renesas: rzg2: Convert EtherAVB to explicit delay handling
	arm64: dts: renesas: hihope-rzg2-ex: Add EtherAVB internal rx delay
	devlink: Break parameter notification sequence to be before/after unload/load driver
	net/mlx5: Fix missing return value in mlx5_devlink_eswitch_inline_mode_set()
	i2c: highlander: add IRQ check
	leds: lt3593: Put fwnode in any case during ->probe()
	leds: trigger: audio: Add an activate callback to ensure the initial brightness is set
	media: em28xx-input: fix refcount bug in em28xx_usb_disconnect
	media: venus: venc: Fix potential null pointer dereference on pointer fmt
	PCI: PM: Avoid forcing PCI_D0 for wakeup reasons inconsistently
	PCI: PM: Enable PME if it can be signaled from D3cold
	bpf, samples: Add missing mprog-disable to xdp_redirect_cpu's optstring
	soc: qcom: smsm: Fix missed interrupts if state changes while masked
	debugfs: Return error during {full/open}_proxy_open() on rmmod
	Bluetooth: increase BTNAMSIZ to 21 chars to fix potential buffer overflow
	PM: EM: Increase energy calculation precision
	selftests/bpf: Fix bpf-iter-tcp4 test to print correctly the dest IP
	drm/msm/mdp4: refactor HW revision detection into read_mdp_hw_revision
	drm/msm/mdp4: move HW revision detection to earlier phase
	drm/msm/dpu: make dpu_hw_ctl_clear_all_blendstages clear necessary LMs
	arm64: dts: exynos: correct GIC CPU interfaces address range on Exynos7
	counter: 104-quad-8: Return error when invalid mode during ceiling_write
	cgroup/cpuset: Miscellaneous code cleanup
	cgroup/cpuset: Fix violation of cpuset locking rule
	ASoC: Intel: Fix platform ID matching
	Bluetooth: fix repeated calls to sco_sock_kill
	drm/msm/dsi: Fix some reference counted resource leaks
	net/mlx5: Register to devlink ingress VLAN filter trap
	net/mlx5: Fix unpublish devlink parameters
	ASoC: rt5682: Implement remove callback
	ASoC: rt5682: Properly turn off regulators if wrong device ID
	usb: dwc3: meson-g12a: add IRQ check
	usb: dwc3: qcom: add IRQ check
	usb: gadget: udc: at91: add IRQ check
	usb: gadget: udc: s3c2410: add IRQ check
	usb: phy: fsl-usb: add IRQ check
	usb: phy: twl6030: add IRQ checks
	usb: gadget: udc: renesas_usb3: Fix soc_device_match() abuse
	selftests/bpf: Fix test_core_autosize on big-endian machines
	devlink: Clear whole devlink_flash_notify struct
	samples: pktgen: add missing IPv6 option to pktgen scripts
	Bluetooth: Move shutdown callback before flushing tx and rx queue
	PM: cpu: Make notifier chain use a raw_spinlock_t
	usb: host: ohci-tmio: add IRQ check
	usb: phy: tahvo: add IRQ check
	libbpf: Re-build libbpf.so when libbpf.map changes
	mac80211: Fix insufficient headroom issue for AMSDU
	locking/lockdep: Mark local_lock_t
	locking/local_lock: Add missing owner initialization
	lockd: Fix invalid lockowner cast after vfs_test_lock
	nfsd4: Fix forced-expiry locking
	arm64: dts: marvell: armada-37xx: Extend PCIe MEM space
	clk: staging: correct reference to config IOMEM to config HAS_IOMEM
	i2c: synquacer: fix deferred probing
	firmware: raspberrypi: Keep count of all consumers
	firmware: raspberrypi: Fix a leak in 'rpi_firmware_get()'
	usb: gadget: mv_u3d: request_irq() after initializing UDC
	mm/swap: consider max pages in iomap_swapfile_add_extent
	lkdtm: replace SCSI_DISPATCH_CMD with SCSI_QUEUE_RQ
	Bluetooth: add timeout sanity check to hci_inquiry
	i2c: iop3xx: fix deferred probing
	i2c: s3c2410: fix IRQ check
	i2c: fix platform_get_irq.cocci warnings
	i2c: hix5hd2: fix IRQ check
	gfs2: init system threads before freeze lock
	rsi: fix error code in rsi_load_9116_firmware()
	rsi: fix an error code in rsi_probe()
	ASoC: Intel: kbl_da7219_max98927: Fix format selection for max98373
	ASoC: Intel: Skylake: Leave data as is when invoking TLV IPCs
	ASoC: Intel: Skylake: Fix module resource and format selection
	mmc: sdhci: Fix issue with uninitialized dma_slave_config
	mmc: dw_mmc: Fix issue with uninitialized dma_slave_config
	mmc: moxart: Fix issue with uninitialized dma_slave_config
	bpf: Fix possible out of bound write in narrow load handling
	CIFS: Fix a potencially linear read overflow
	i2c: mt65xx: fix IRQ check
	i2c: xlp9xx: fix main IRQ check
	usb: ehci-orion: Handle errors of clk_prepare_enable() in probe
	usb: bdc: Fix an error handling path in 'bdc_probe()' when no suitable DMA config is available
	usb: bdc: Fix a resource leak in the error handling path of 'bdc_probe()'
	tty: serial: fsl_lpuart: fix the wrong mapbase value
	ASoC: wcd9335: Fix a double irq free in the remove function
	ASoC: wcd9335: Fix a memory leak in the error handling path of the probe function
	ASoC: wcd9335: Disable irq on slave ports in the remove function
	iwlwifi: follow the new inclusive terminology
	iwlwifi: skip first element in the WTAS ACPI table
	ice: Only lock to update netdev dev_addr
	ath6kl: wmi: fix an error code in ath6kl_wmi_sync_point()
	atlantic: Fix driver resume flow.
	bcma: Fix memory leak for internally-handled cores
	brcmfmac: pcie: fix oops on failure to resume and reprobe
	ipv6: make exception cache less predictible
	ipv4: make exception cache less predictible
	net: sched: Fix qdisc_rate_table refcount leak when get tcf_block failed
	net: qualcomm: fix QCA7000 checksum handling
	octeontx2-af: Fix loop in free and unmap counter
	octeontx2-af: Fix static code analyzer reported issues
	octeontx2-af: Set proper errorcode for IPv4 checksum errors
	ipv4: fix endianness issue in inet_rtm_getroute_build_skb()
	ASoC: rt5682: Remove unused variable in rt5682_i2c_remove()
	iwlwifi Add support for ax201 in Samsung Galaxy Book Flex2 Alpha
	f2fs: guarantee to write dirty data when enabling checkpoint back
	time: Handle negative seconds correctly in timespec64_to_ns()
	io_uring: IORING_OP_WRITE needs hash_reg_file set
	bio: fix page leak bio_add_hw_page failure
	tty: Fix data race between tiocsti() and flush_to_ldisc()
	perf/x86/amd/ibs: Extend PERF_PMU_CAP_NO_EXCLUDE to IBS Op
	x86/resctrl: Fix a maybe-uninitialized build warning treated as error
	Revert "KVM: x86: mmu: Add guest physical address check in translate_gpa()"
	KVM: s390: index kvm->arch.idle_mask by vcpu_idx
	KVM: x86: Update vCPU's hv_clock before back to guest when tsc_offset is adjusted
	KVM: VMX: avoid running vmx_handle_exit_irqoff in case of emulation
	KVM: nVMX: Unconditionally clear nested.pi_pending on nested VM-Enter
	ARM: dts: at91: add pinctrl-{names, 0} for all gpios
	fuse: truncate pagecache on atomic_o_trunc
	fuse: flush extending writes
	IMA: remove -Wmissing-prototypes warning
	IMA: remove the dependency on CRYPTO_MD5
	fbmem: don't allow too huge resolutions
	backlight: pwm_bl: Improve bootloader/kernel device handover
	clk: kirkwood: Fix a clocking boot regression
	Linux 5.10.65

Signed-off-by: Greg Kroah-Hartman <gregkh@google.com>
Change-Id: Ie0b9306ba6ee4193de3200df7cdacaeba152b83e
2021-09-15 14:16:47 +02:00

438 lines
13 KiB
C

// SPDX-License-Identifier: GPL-2.0
/*
* Copyright 2019 Google LLC
*/
/*
* Refer to Documentation/block/inline-encryption.rst for detailed explanation.
*/
#define pr_fmt(fmt) "blk-crypto: " fmt
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/keyslot-manager.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "blk-crypto-internal.h"
const struct blk_crypto_mode blk_crypto_modes[] = {
[BLK_ENCRYPTION_MODE_AES_256_XTS] = {
.cipher_str = "xts(aes)",
.keysize = 64,
.ivsize = 16,
},
[BLK_ENCRYPTION_MODE_AES_128_CBC_ESSIV] = {
.cipher_str = "essiv(cbc(aes),sha256)",
.keysize = 16,
.ivsize = 16,
},
[BLK_ENCRYPTION_MODE_ADIANTUM] = {
.cipher_str = "adiantum(xchacha12,aes)",
.keysize = 32,
.ivsize = 32,
},
};
/*
* This number needs to be at least (the number of threads doing IO
* concurrently) * (maximum recursive depth of a bio), so that we don't
* deadlock on crypt_ctx allocations. The default is chosen to be the same
* as the default number of post read contexts in both EXT4 and F2FS.
*/
static int num_prealloc_crypt_ctxs = 128;
module_param(num_prealloc_crypt_ctxs, int, 0444);
MODULE_PARM_DESC(num_prealloc_crypt_ctxs,
"Number of bio crypto contexts to preallocate");
static struct kmem_cache *bio_crypt_ctx_cache;
static mempool_t *bio_crypt_ctx_pool;
static int __init bio_crypt_ctx_init(void)
{
size_t i;
bio_crypt_ctx_cache = KMEM_CACHE(bio_crypt_ctx, 0);
if (!bio_crypt_ctx_cache)
goto out_no_mem;
bio_crypt_ctx_pool = mempool_create_slab_pool(num_prealloc_crypt_ctxs,
bio_crypt_ctx_cache);
if (!bio_crypt_ctx_pool)
goto out_no_mem;
/* This is assumed in various places. */
BUILD_BUG_ON(BLK_ENCRYPTION_MODE_INVALID != 0);
/* Sanity check that no algorithm exceeds the defined limits. */
for (i = 0; i < BLK_ENCRYPTION_MODE_MAX; i++) {
BUG_ON(blk_crypto_modes[i].keysize > BLK_CRYPTO_MAX_KEY_SIZE);
BUG_ON(blk_crypto_modes[i].ivsize > BLK_CRYPTO_MAX_IV_SIZE);
}
return 0;
out_no_mem:
panic("Failed to allocate mem for bio crypt ctxs\n");
}
subsys_initcall(bio_crypt_ctx_init);
void bio_crypt_set_ctx(struct bio *bio, const struct blk_crypto_key *key,
const u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE], gfp_t gfp_mask)
{
struct bio_crypt_ctx *bc;
/*
* The caller must use a gfp_mask that contains __GFP_DIRECT_RECLAIM so
* that the mempool_alloc() can't fail.
*/
WARN_ON_ONCE(!(gfp_mask & __GFP_DIRECT_RECLAIM));
bc = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
bc->bc_key = key;
memcpy(bc->bc_dun, dun, sizeof(bc->bc_dun));
bio->bi_crypt_context = bc;
}
EXPORT_SYMBOL_GPL(bio_crypt_set_ctx);
void __bio_crypt_free_ctx(struct bio *bio)
{
mempool_free(bio->bi_crypt_context, bio_crypt_ctx_pool);
bio->bi_crypt_context = NULL;
}
int __bio_crypt_clone(struct bio *dst, struct bio *src, gfp_t gfp_mask)
{
dst->bi_crypt_context = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
if (!dst->bi_crypt_context)
return -ENOMEM;
*dst->bi_crypt_context = *src->bi_crypt_context;
return 0;
}
EXPORT_SYMBOL_GPL(__bio_crypt_clone);
/* Increments @dun by @inc, treating @dun as a multi-limb integer. */
void bio_crypt_dun_increment(u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE],
unsigned int inc)
{
int i;
for (i = 0; inc && i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
dun[i] += inc;
/*
* If the addition in this limb overflowed, then we need to
* carry 1 into the next limb. Else the carry is 0.
*/
if (dun[i] < inc)
inc = 1;
else
inc = 0;
}
}
void __bio_crypt_advance(struct bio *bio, unsigned int bytes)
{
struct bio_crypt_ctx *bc = bio->bi_crypt_context;
bio_crypt_dun_increment(bc->bc_dun,
bytes >> bc->bc_key->data_unit_size_bits);
}
/*
* Returns true if @bc->bc_dun plus @bytes converted to data units is equal to
* @next_dun, treating the DUNs as multi-limb integers.
*/
bool bio_crypt_dun_is_contiguous(const struct bio_crypt_ctx *bc,
unsigned int bytes,
const u64 next_dun[BLK_CRYPTO_DUN_ARRAY_SIZE])
{
int i;
unsigned int carry = bytes >> bc->bc_key->data_unit_size_bits;
for (i = 0; i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++) {
if (bc->bc_dun[i] + carry != next_dun[i])
return false;
/*
* If the addition in this limb overflowed, then we need to
* carry 1 into the next limb. Else the carry is 0.
*/
if ((bc->bc_dun[i] + carry) < carry)
carry = 1;
else
carry = 0;
}
/* If the DUN wrapped through 0, don't treat it as contiguous. */
return carry == 0;
}
/*
* Checks that two bio crypt contexts are compatible - i.e. that
* they are mergeable except for data_unit_num continuity.
*/
static bool bio_crypt_ctx_compatible(struct bio_crypt_ctx *bc1,
struct bio_crypt_ctx *bc2)
{
if (!bc1)
return !bc2;
return bc2 && bc1->bc_key == bc2->bc_key;
}
bool bio_crypt_rq_ctx_compatible(struct request *rq, struct bio *bio)
{
return bio_crypt_ctx_compatible(rq->crypt_ctx, bio->bi_crypt_context);
}
/*
* Checks that two bio crypt contexts are compatible, and also
* that their data_unit_nums are continuous (and can hence be merged)
* in the order @bc1 followed by @bc2.
*/
bool bio_crypt_ctx_mergeable(struct bio_crypt_ctx *bc1, unsigned int bc1_bytes,
struct bio_crypt_ctx *bc2)
{
if (!bio_crypt_ctx_compatible(bc1, bc2))
return false;
return !bc1 || bio_crypt_dun_is_contiguous(bc1, bc1_bytes, bc2->bc_dun);
}
/* Check that all I/O segments are data unit aligned. */
static bool bio_crypt_check_alignment(struct bio *bio)
{
const unsigned int data_unit_size =
bio->bi_crypt_context->bc_key->crypto_cfg.data_unit_size;
struct bvec_iter iter;
struct bio_vec bv;
bio_for_each_segment(bv, bio, iter) {
if (!IS_ALIGNED(bv.bv_len | bv.bv_offset, data_unit_size))
return false;
}
return true;
}
blk_status_t __blk_crypto_init_request(struct request *rq)
{
return blk_ksm_get_slot_for_key(rq->q->ksm, rq->crypt_ctx->bc_key,
&rq->crypt_keyslot);
}
/**
* __blk_crypto_free_request - Uninitialize the crypto fields of a request.
*
* @rq: The request whose crypto fields to uninitialize.
*
* Completely uninitializes the crypto fields of a request. If a keyslot has
* been programmed into some inline encryption hardware, that keyslot is
* released. The rq->crypt_ctx is also freed.
*/
void __blk_crypto_free_request(struct request *rq)
{
blk_ksm_put_slot(rq->crypt_keyslot);
mempool_free(rq->crypt_ctx, bio_crypt_ctx_pool);
blk_crypto_rq_set_defaults(rq);
}
/**
* __blk_crypto_bio_prep - Prepare bio for inline encryption
*
* @bio_ptr: pointer to original bio pointer
*
* If the bio crypt context provided for the bio is supported by the underlying
* device's inline encryption hardware, do nothing.
*
* Otherwise, try to perform en/decryption for this bio by falling back to the
* kernel crypto API. When the crypto API fallback is used for encryption,
* blk-crypto may choose to split the bio into 2 - the first one that will
* continue to be processed and the second one that will be resubmitted via
* submit_bio_noacct. A bounce bio will be allocated to encrypt the contents
* of the aforementioned "first one", and *bio_ptr will be updated to this
* bounce bio.
*
* Caller must ensure bio has bio_crypt_ctx.
*
* Return: true on success; false on error (and bio->bi_status will be set
* appropriately, and bio_endio() will have been called so bio
* submission should abort).
*/
bool __blk_crypto_bio_prep(struct bio **bio_ptr)
{
struct bio *bio = *bio_ptr;
const struct blk_crypto_key *bc_key = bio->bi_crypt_context->bc_key;
/* Error if bio has no data. */
if (WARN_ON_ONCE(!bio_has_data(bio))) {
bio->bi_status = BLK_STS_IOERR;
goto fail;
}
if (!bio_crypt_check_alignment(bio)) {
bio->bi_status = BLK_STS_IOERR;
goto fail;
}
/*
* Success if device supports the encryption context, or if we succeeded
* in falling back to the crypto API.
*/
if (blk_ksm_crypto_cfg_supported(bio->bi_disk->queue->ksm,
&bc_key->crypto_cfg))
return true;
if (blk_crypto_fallback_bio_prep(bio_ptr))
return true;
fail:
bio_endio(*bio_ptr);
return false;
}
int __blk_crypto_rq_bio_prep(struct request *rq, struct bio *bio,
gfp_t gfp_mask)
{
if (!rq->crypt_ctx) {
rq->crypt_ctx = mempool_alloc(bio_crypt_ctx_pool, gfp_mask);
if (!rq->crypt_ctx)
return -ENOMEM;
}
*rq->crypt_ctx = *bio->bi_crypt_context;
return 0;
}
/**
* blk_crypto_init_key() - Prepare a key for use with blk-crypto
* @blk_key: Pointer to the blk_crypto_key to initialize.
* @raw_key: Pointer to the raw key.
* @raw_key_size: Size of raw key. Must be at least the required size for the
* chosen @crypto_mode; see blk_crypto_modes[]. (It's allowed
* to be longer than the mode's actual key size, in order to
* support inline encryption hardware that accepts wrapped keys.
* @is_hw_wrapped has to be set for such keys)
* @is_hw_wrapped: Denotes @raw_key is wrapped.
* @crypto_mode: identifier for the encryption algorithm to use
* @dun_bytes: number of bytes that will be used to specify the DUN when this
* key is used
* @data_unit_size: the data unit size to use for en/decryption
*
* Return: 0 on success, -errno on failure. The caller is responsible for
* zeroizing both blk_key and raw_key when done with them.
*/
int blk_crypto_init_key(struct blk_crypto_key *blk_key,
const u8 *raw_key, unsigned int raw_key_size,
bool is_hw_wrapped,
enum blk_crypto_mode_num crypto_mode,
unsigned int dun_bytes,
unsigned int data_unit_size)
{
const struct blk_crypto_mode *mode;
memset(blk_key, 0, sizeof(*blk_key));
if (crypto_mode >= ARRAY_SIZE(blk_crypto_modes))
return -EINVAL;
BUILD_BUG_ON(BLK_CRYPTO_MAX_WRAPPED_KEY_SIZE < BLK_CRYPTO_MAX_KEY_SIZE);
mode = &blk_crypto_modes[crypto_mode];
if (is_hw_wrapped) {
if (raw_key_size < mode->keysize ||
raw_key_size > BLK_CRYPTO_MAX_WRAPPED_KEY_SIZE)
return -EINVAL;
} else {
if (raw_key_size != mode->keysize)
return -EINVAL;
}
if (dun_bytes == 0 || dun_bytes > mode->ivsize)
return -EINVAL;
if (!is_power_of_2(data_unit_size))
return -EINVAL;
blk_key->crypto_cfg.crypto_mode = crypto_mode;
blk_key->crypto_cfg.dun_bytes = dun_bytes;
blk_key->crypto_cfg.data_unit_size = data_unit_size;
blk_key->crypto_cfg.is_hw_wrapped = is_hw_wrapped;
blk_key->data_unit_size_bits = ilog2(data_unit_size);
blk_key->size = raw_key_size;
memcpy(blk_key->raw, raw_key, raw_key_size);
return 0;
}
EXPORT_SYMBOL_GPL(blk_crypto_init_key);
/*
* Check if bios with @cfg can be en/decrypted by blk-crypto (i.e. either the
* request queue it's submitted to supports inline crypto, or the
* blk-crypto-fallback is enabled and supports the cfg).
*/
bool blk_crypto_config_supported(struct request_queue *q,
const struct blk_crypto_config *cfg)
{
if (IS_ENABLED(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) &&
!cfg->is_hw_wrapped)
return true;
return blk_ksm_crypto_cfg_supported(q->ksm, cfg);
}
/**
* blk_crypto_start_using_key() - Start using a blk_crypto_key on a device
* @key: A key to use on the device
* @q: the request queue for the device
*
* Upper layers must call this function to ensure that either the hardware
* supports the key's crypto settings, or the crypto API fallback has transforms
* for the needed mode allocated and ready to go. This function may allocate
* an skcipher, and *should not* be called from the data path, since that might
* cause a deadlock
*
* Return: 0 on success; -ENOPKG if the hardware doesn't support the key and
* blk-crypto-fallback is either disabled or the needed algorithm
* is disabled in the crypto API; or another -errno code.
*/
int blk_crypto_start_using_key(const struct blk_crypto_key *key,
struct request_queue *q)
{
if (blk_ksm_crypto_cfg_supported(q->ksm, &key->crypto_cfg))
return 0;
if (key->crypto_cfg.is_hw_wrapped) {
pr_warn_once("hardware doesn't support wrapped keys\n");
return -EOPNOTSUPP;
}
return blk_crypto_fallback_start_using_mode(key->crypto_cfg.crypto_mode);
}
EXPORT_SYMBOL_GPL(blk_crypto_start_using_key);
/**
* blk_crypto_evict_key() - Evict a key from any inline encryption hardware
* it may have been programmed into
* @q: The request queue who's associated inline encryption hardware this key
* might have been programmed into
* @key: The key to evict
*
* Upper layers (filesystems) must call this function to ensure that a key is
* evicted from any hardware that it might have been programmed into. The key
* must not be in use by any in-flight IO when this function is called.
*
* Return: 0 on success or if key is not present in the q's ksm, -err on error.
*/
int blk_crypto_evict_key(struct request_queue *q,
const struct blk_crypto_key *key)
{
if (blk_ksm_crypto_cfg_supported(q->ksm, &key->crypto_cfg))
return blk_ksm_evict_key(q->ksm, key);
/*
* If the request queue's associated inline encryption hardware didn't
* have support for the key, then the key might have been programmed
* into the fallback keyslot manager, so try to evict from there.
*/
return blk_crypto_fallback_evict_key(key);
}
EXPORT_SYMBOL_GPL(blk_crypto_evict_key);