android_kernel_samsung_sm8650/block/blk-crypto-fallback.c
Greg Kroah-Hartman 50874c58d8 Merge 6.1.47 into android14-6.1-lts
Changes in 6.1.47
	mmc: sdhci-f-sdh30: Replace with sdhci_pltfm
	cpuidle: psci: Extend information in log about OSI/PC mode
	cpuidle: psci: Move enabling OSI mode after power domains creation
	zsmalloc: consolidate zs_pool's migrate_lock and size_class's locks
	zsmalloc: fix races between modifications of fullness and isolated
	selftests: forwarding: tc_actions: cleanup temporary files when test is aborted
	selftests: forwarding: tc_actions: Use ncat instead of nc
	net/smc: replace mutex rmbs_lock and sndbufs_lock with rw_semaphore
	net/smc: Fix setsockopt and sysctl to specify same buffer size again
	net: phy: at803x: Use devm_regulator_get_enable_optional()
	net: phy: at803x: fix the wol setting functions
	drm/amdgpu: fix calltrace warning in amddrm_buddy_fini
	drm/amdgpu: Fix integer overflow in amdgpu_cs_pass1
	drm/amdgpu: fix memory leak in mes self test
	ASoC: Intel: sof_sdw: add quirk for MTL RVP
	ASoC: Intel: sof_sdw: add quirk for LNL RVP
	PCI: tegra194: Fix possible array out of bounds access
	ASoC: SOF: amd: Add pci revision id check
	drm/stm: ltdc: fix late dereference check
	drm: rcar-du: remove R-Car H3 ES1.* workarounds
	ASoC: amd: vangogh: Add check for acp config flags in vangogh platform
	ARM: dts: imx6dl: prtrvt, prtvt7, prti6q, prtwd2: fix USB related warnings
	ASoC: Intel: sof_sdw_rt_sdca_jack_common: test SOF_JACK_JDSRC in _exit
	ASoC: Intel: sof_sdw: Add support for Rex soundwire
	iopoll: Call cpu_relax() in busy loops
	ASoC: SOF: Intel: fix SoundWire/HDaudio mutual exclusion
	dma-remap: use kvmalloc_array/kvfree for larger dma memory remap
	accel/habanalabs: add pci health check during heartbeat
	HID: logitech-hidpp: Add USB and Bluetooth IDs for the Logitech G915 TKL Keyboard
	iommu/amd: Introduce Disable IRTE Caching Support
	drm/amdgpu: install stub fence into potential unused fence pointers
	drm/amd/display: Apply 60us prefetch for DCFCLK <= 300Mhz
	RDMA/mlx5: Return the firmware result upon destroying QP/RQ
	drm/amd/display: Skip DPP DTO update if root clock is gated
	drm/amd/display: Enable dcn314 DPP RCO
	ASoC: SOF: core: Free the firmware trace before calling snd_sof_shutdown()
	HID: intel-ish-hid: ipc: Add Arrow Lake PCI device ID
	ALSA: hda/realtek: Add quirks for ROG ALLY CS35l41 audio
	smb: client: fix warning in cifs_smb3_do_mount()
	cifs: fix session state check in reconnect to avoid use-after-free issue
	serial: stm32: Ignore return value of uart_remove_one_port() in .remove()
	led: qcom-lpg: Fix resource leaks in for_each_available_child_of_node() loops
	media: v4l2-mem2mem: add lock to protect parameter num_rdy
	media: camss: set VFE bpl_alignment to 16 for sdm845 and sm8250
	usb: gadget: u_serial: Avoid spinlock recursion in __gs_console_push
	usb: gadget: uvc: queue empty isoc requests if no video buffer is available
	media: platform: mediatek: vpu: fix NULL ptr dereference
	thunderbolt: Read retimer NVM authentication status prior tb_retimer_set_inbound_sbtx()
	usb: chipidea: imx: don't request QoS for imx8ulp
	usb: chipidea: imx: add missing USB PHY DPDM wakeup setting
	gfs2: Fix possible data races in gfs2_show_options()
	pcmcia: rsrc_nonstatic: Fix memory leak in nonstatic_release_resource_db()
	thunderbolt: Add Intel Barlow Ridge PCI ID
	thunderbolt: Limit Intel Barlow Ridge USB3 bandwidth
	firewire: net: fix use after free in fwnet_finish_incoming_packet()
	watchdog: sp5100_tco: support Hygon FCH/SCH (Server Controller Hub)
	Bluetooth: L2CAP: Fix use-after-free
	Bluetooth: btusb: Add MT7922 bluetooth ID for the Asus Ally
	ceph: try to dump the msgs when decoding fails
	drm/amdgpu: Fix potential fence use-after-free v2
	fs/ntfs3: Enhance sanity check while generating attr_list
	fs: ntfs3: Fix possible null-pointer dereferences in mi_read()
	fs/ntfs3: Mark ntfs dirty when on-disk struct is corrupted
	ALSA: hda/realtek: Add quirks for Unis H3C Desktop B760 & Q760
	ALSA: hda: fix a possible null-pointer dereference due to data race in snd_hdac_regmap_sync()
	ALSA: hda/realtek: Add quirk for ASUS ROG GX650P
	ALSA: hda/realtek: Add quirk for ASUS ROG GA402X
	ALSA: hda/realtek: Add quirk for ASUS ROG GZ301V
	powerpc/kasan: Disable KCOV in KASAN code
	Bluetooth: MGMT: Use correct address for memcpy()
	ring-buffer: Do not swap cpu_buffer during resize process
	igc: read before write to SRRCTL register
	drm/amd/display: save restore hdcp state when display is unplugged from mst hub
	drm/amd/display: phase3 mst hdcp for multiple displays
	drm/amd/display: fix access hdcp_workqueue assert
	KVM: arm64: vgic-v4: Make the doorbell request robust w.r.t preemption
	ARM: dts: nxp/imx6sll: fix wrong property name in usbphy node
	fbdev/hyperv-fb: Do not set struct fb_info.apertures
	video/aperture: Only remove sysfb on the default vga pci device
	btrfs: move out now unused BG from the reclaim list
	btrfs: convert btrfs_block_group::needs_free_space to runtime flag
	btrfs: convert btrfs_block_group::seq_zone to runtime flag
	btrfs: fix use-after-free of new block group that became unused
	virtio-mmio: don't break lifecycle of vm_dev
	vduse: Use proper spinlock for IRQ injection
	vdpa/mlx5: Fix mr->initialized semantics
	vdpa/mlx5: Delete control vq iotlb in destroy_mr only when necessary
	cifs: fix potential oops in cifs_oplock_break
	i2c: bcm-iproc: Fix bcm_iproc_i2c_isr deadlock issue
	i2c: hisi: Only handle the interrupt of the driver's transfer
	i2c: tegra: Fix i2c-tegra DMA config option processing
	fbdev: mmp: fix value check in mmphw_probe()
	powerpc/rtas_flash: allow user copy to flash block cache objects
	vdpa: Add features attr to vdpa_nl_policy for nlattr length check
	vdpa: Add queue index attr to vdpa_nl_policy for nlattr length check
	vdpa: Add max vqp attr to vdpa_nl_policy for nlattr length check
	vdpa: Enable strict validation for netlinks ops
	tty: n_gsm: fix the UAF caused by race condition in gsm_cleanup_mux
	tty: serial: fsl_lpuart: Clear the error flags by writing 1 for lpuart32 platforms
	btrfs: fix incorrect splitting in btrfs_drop_extent_map_range
	btrfs: fix BUG_ON condition in btrfs_cancel_balance
	i2c: designware: Correct length byte validation logic
	i2c: designware: Handle invalid SMBus block data response length value
	net: xfrm: Fix xfrm_address_filter OOB read
	net: af_key: fix sadb_x_filter validation
	net: xfrm: Amend XFRMA_SEC_CTX nla_policy structure
	xfrm: fix slab-use-after-free in decode_session6
	ip6_vti: fix slab-use-after-free in decode_session6
	ip_vti: fix potential slab-use-after-free in decode_session6
	xfrm: add NULL check in xfrm_update_ae_params
	xfrm: add forgotten nla_policy for XFRMA_MTIMER_THRESH
	virtio_net: notify MAC address change on device initialization
	virtio-net: set queues after driver_ok
	net: pcs: Add missing put_device call in miic_create
	net: phy: fix IRQ-based wake-on-lan over hibernate / power off
	selftests: mirror_gre_changes: Tighten up the TTL test match
	drm/panel: simple: Fix AUO G121EAN01 panel timings according to the docs
	net: macb: In ZynqMP resume always configure PS GTR for non-wakeup source
	octeon_ep: cancel tx_timeout_task later in remove sequence
	netfilter: nf_tables: fix false-positive lockdep splat
	netfilter: nf_tables: deactivate catchall elements in next generation
	ipvs: fix racy memcpy in proc_do_sync_threshold
	netfilter: nft_dynset: disallow object maps
	net: phy: broadcom: stub c45 read/write for 54810
	team: Fix incorrect deletion of ETH_P_8021AD protocol vid from slaves
	net: openvswitch: reject negative ifindex
	iavf: fix FDIR rule fields masks validation
	i40e: fix misleading debug logs
	net: dsa: mv88e6xxx: Wait for EEPROM done before HW reset
	sfc: don't unregister flow_indr if it was never registered
	sock: Fix misuse of sk_under_memory_pressure()
	net: do not allow gso_size to be set to GSO_BY_FRAGS
	qede: fix firmware halt over suspend and resume
	ice: Block switchdev mode when ADQ is active and vice versa
	bus: ti-sysc: Flush posted write on enable before reset
	arm64: dts: qcom: qrb5165-rb5: fix thermal zone conflict
	arm64: dts: rockchip: Disable HS400 for eMMC on ROCK Pi 4
	arm64: dts: rockchip: Disable HS400 for eMMC on ROCK 4C+
	ARM: dts: imx: align LED node names with dtschema
	ARM: dts: imx6: phytec: fix RTC interrupt level
	arm64: dts: imx8mm: Drop CSI1 PHY reference clock configuration
	ARM: dts: imx: Set default tuning step for imx6sx usdhc
	arm64: dts: imx93: Fix anatop node size
	ASoC: rt5665: add missed regulator_bulk_disable
	ASoC: meson: axg-tdm-formatter: fix channel slot allocation
	ALSA: hda/realtek: Add quirks for HP G11 Laptops
	soc: aspeed: uart-routing: Use __sysfs_match_string
	soc: aspeed: socinfo: Add kfree for kstrdup
	ALSA: hda/realtek - Remodified 3k pull low procedure
	riscv: uaccess: Return the number of bytes effectively not copied
	serial: 8250: Fix oops for port->pm on uart_change_pm()
	ALSA: usb-audio: Add support for Mythware XA001AU capture and playback interfaces.
	cifs: Release folio lock on fscache read hit.
	virtio-net: Zero max_tx_vq field for VIRTIO_NET_CTRL_MQ_HASH_CONFIG case
	arm64: dts: rockchip: Fix Wifi/Bluetooth on ROCK Pi 4 boards
	blk-crypto: dynamically allocate fallback profile
	mmc: wbsd: fix double mmc_free_host() in wbsd_init()
	mmc: block: Fix in_flight[issue_type] value error
	drm/qxl: fix UAF on handle creation
	drm/i915/sdvo: fix panel_type initialization
	drm/amd: flush any delayed gfxoff on suspend entry
	drm/amdgpu: skip fence GFX interrupts disable/enable for S0ix
	drm/amdgpu/pm: fix throttle_status for other than MP1 11.0.7
	ASoC: amd: vangogh: select CONFIG_SND_AMD_ACP_CONFIG
	drm/amd/display: disable RCO for DCN314
	zsmalloc: allow only one active pool compaction context
	sched/fair: unlink misfit task from cpu overutilized
	sched/fair: Remove capacity inversion detection
	drm/amd/display: Implement workaround for writing to OTG_PIXEL_RATE_DIV register
	hugetlb: do not clear hugetlb dtor until allocating vmemmap
	netfilter: set default timeout to 3 secs for sctp shutdown send and recv state
	arm64/ptrace: Ensure that SME is set up for target when writing SSVE state
	drm/amd/pm: skip the RLC stop when S0i3 suspend for SMU v13.0.4/11
	drm/amdgpu: keep irq count in amdgpu_irq_disable_all
	af_unix: Fix null-ptr-deref in unix_stream_sendpage().
	drm/nouveau/disp: fix use-after-free in error handling of nouveau_connector_create
	net: fix the RTO timer retransmitting skb every 1ms if linear option is enabled
	mmc: f-sdh30: fix order of function calls in sdhci_f_sdh30_remove
	Linux 6.1.47

Change-Id: I7c55c71f43f88a1d44d39c835e3f6e58d4c86279
Signed-off-by: Greg Kroah-Hartman <gregkh@google.com>
2023-09-13 19:35:46 +00:00

682 lines
19 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-fallback: " fmt
#include <crypto/skcipher.h>
#include <linux/blk-crypto.h>
#include <linux/blk-crypto-profile.h>
#include <linux/blkdev.h>
#include <linux/crypto.h>
#include <linux/mempool.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/scatterlist.h>
#include "blk-cgroup.h"
#include "blk-crypto-internal.h"
static unsigned int num_prealloc_bounce_pg = 32;
module_param(num_prealloc_bounce_pg, uint, 0);
MODULE_PARM_DESC(num_prealloc_bounce_pg,
"Number of preallocated bounce pages for the blk-crypto crypto API fallback");
static unsigned int blk_crypto_num_keyslots = 100;
module_param_named(num_keyslots, blk_crypto_num_keyslots, uint, 0);
MODULE_PARM_DESC(num_keyslots,
"Number of keyslots for the blk-crypto crypto API fallback");
static unsigned int num_prealloc_fallback_crypt_ctxs = 128;
module_param(num_prealloc_fallback_crypt_ctxs, uint, 0);
MODULE_PARM_DESC(num_prealloc_crypt_fallback_ctxs,
"Number of preallocated bio fallback crypto contexts for blk-crypto to use during crypto API fallback");
struct bio_fallback_crypt_ctx {
struct bio_crypt_ctx crypt_ctx;
/*
* Copy of the bvec_iter when this bio was submitted.
* We only want to en/decrypt the part of the bio as described by the
* bvec_iter upon submission because bio might be split before being
* resubmitted
*/
struct bvec_iter crypt_iter;
union {
struct {
struct work_struct work;
struct bio *bio;
};
struct {
void *bi_private_orig;
bio_end_io_t *bi_end_io_orig;
};
};
};
static struct kmem_cache *bio_fallback_crypt_ctx_cache;
static mempool_t *bio_fallback_crypt_ctx_pool;
/*
* Allocating a crypto tfm during I/O can deadlock, so we have to preallocate
* all of a mode's tfms when that mode starts being used. Since each mode may
* need all the keyslots at some point, each mode needs its own tfm for each
* keyslot; thus, a keyslot may contain tfms for multiple modes. However, to
* match the behavior of real inline encryption hardware (which only supports a
* single encryption context per keyslot), we only allow one tfm per keyslot to
* be used at a time - the rest of the unused tfms have their keys cleared.
*/
static DEFINE_MUTEX(tfms_init_lock);
static bool tfms_inited[BLK_ENCRYPTION_MODE_MAX];
static struct blk_crypto_fallback_keyslot {
enum blk_crypto_mode_num crypto_mode;
struct crypto_skcipher *tfms[BLK_ENCRYPTION_MODE_MAX];
} *blk_crypto_keyslots;
static struct blk_crypto_profile *blk_crypto_fallback_profile;
static struct workqueue_struct *blk_crypto_wq;
static mempool_t *blk_crypto_bounce_page_pool;
static struct bio_set crypto_bio_split;
/*
* This is the key we set when evicting a keyslot. This *should* be the all 0's
* key, but AES-XTS rejects that key, so we use some random bytes instead.
*/
static u8 blank_key[BLK_CRYPTO_MAX_STANDARD_KEY_SIZE];
static void blk_crypto_fallback_evict_keyslot(unsigned int slot)
{
struct blk_crypto_fallback_keyslot *slotp = &blk_crypto_keyslots[slot];
enum blk_crypto_mode_num crypto_mode = slotp->crypto_mode;
int err;
WARN_ON(slotp->crypto_mode == BLK_ENCRYPTION_MODE_INVALID);
/* Clear the key in the skcipher */
err = crypto_skcipher_setkey(slotp->tfms[crypto_mode], blank_key,
blk_crypto_modes[crypto_mode].keysize);
WARN_ON(err);
slotp->crypto_mode = BLK_ENCRYPTION_MODE_INVALID;
}
static int
blk_crypto_fallback_keyslot_program(struct blk_crypto_profile *profile,
const struct blk_crypto_key *key,
unsigned int slot)
{
struct blk_crypto_fallback_keyslot *slotp = &blk_crypto_keyslots[slot];
const enum blk_crypto_mode_num crypto_mode =
key->crypto_cfg.crypto_mode;
int err;
if (crypto_mode != slotp->crypto_mode &&
slotp->crypto_mode != BLK_ENCRYPTION_MODE_INVALID)
blk_crypto_fallback_evict_keyslot(slot);
slotp->crypto_mode = crypto_mode;
err = crypto_skcipher_setkey(slotp->tfms[crypto_mode], key->raw,
key->size);
if (err) {
blk_crypto_fallback_evict_keyslot(slot);
return err;
}
return 0;
}
static int blk_crypto_fallback_keyslot_evict(struct blk_crypto_profile *profile,
const struct blk_crypto_key *key,
unsigned int slot)
{
blk_crypto_fallback_evict_keyslot(slot);
return 0;
}
static const struct blk_crypto_ll_ops blk_crypto_fallback_ll_ops = {
.keyslot_program = blk_crypto_fallback_keyslot_program,
.keyslot_evict = blk_crypto_fallback_keyslot_evict,
};
static void blk_crypto_fallback_encrypt_endio(struct bio *enc_bio)
{
struct bio *src_bio = enc_bio->bi_private;
int i;
for (i = 0; i < enc_bio->bi_vcnt; i++)
mempool_free(enc_bio->bi_io_vec[i].bv_page,
blk_crypto_bounce_page_pool);
src_bio->bi_status = enc_bio->bi_status;
bio_uninit(enc_bio);
kfree(enc_bio);
bio_endio(src_bio);
}
static struct bio *blk_crypto_fallback_clone_bio(struct bio *bio_src)
{
unsigned int nr_segs = bio_segments(bio_src);
struct bvec_iter iter;
struct bio_vec bv;
struct bio *bio;
bio = bio_kmalloc(nr_segs, GFP_NOIO);
if (!bio)
return NULL;
bio_init(bio, bio_src->bi_bdev, bio->bi_inline_vecs, nr_segs,
bio_src->bi_opf);
if (bio_flagged(bio_src, BIO_REMAPPED))
bio_set_flag(bio, BIO_REMAPPED);
bio->bi_ioprio = bio_src->bi_ioprio;
bio->bi_iter.bi_sector = bio_src->bi_iter.bi_sector;
bio->bi_iter.bi_size = bio_src->bi_iter.bi_size;
bio_for_each_segment(bv, bio_src, iter)
bio->bi_io_vec[bio->bi_vcnt++] = bv;
bio_clone_blkg_association(bio, bio_src);
bio_clone_skip_dm_default_key(bio, bio_src);
return bio;
}
static bool
blk_crypto_fallback_alloc_cipher_req(struct blk_crypto_keyslot *slot,
struct skcipher_request **ciph_req_ret,
struct crypto_wait *wait)
{
struct skcipher_request *ciph_req;
const struct blk_crypto_fallback_keyslot *slotp;
int keyslot_idx = blk_crypto_keyslot_index(slot);
slotp = &blk_crypto_keyslots[keyslot_idx];
ciph_req = skcipher_request_alloc(slotp->tfms[slotp->crypto_mode],
GFP_NOIO);
if (!ciph_req)
return false;
skcipher_request_set_callback(ciph_req,
CRYPTO_TFM_REQ_MAY_BACKLOG |
CRYPTO_TFM_REQ_MAY_SLEEP,
crypto_req_done, wait);
*ciph_req_ret = ciph_req;
return true;
}
static bool blk_crypto_fallback_split_bio_if_needed(struct bio **bio_ptr)
{
struct bio *bio = *bio_ptr;
unsigned int i = 0;
unsigned int num_sectors = 0;
struct bio_vec bv;
struct bvec_iter iter;
bio_for_each_segment(bv, bio, iter) {
num_sectors += bv.bv_len >> SECTOR_SHIFT;
if (++i == BIO_MAX_VECS)
break;
}
if (num_sectors < bio_sectors(bio)) {
struct bio *split_bio;
split_bio = bio_split(bio, num_sectors, GFP_NOIO,
&crypto_bio_split);
if (!split_bio) {
bio->bi_status = BLK_STS_RESOURCE;
return false;
}
bio_chain(split_bio, bio);
submit_bio_noacct(bio);
*bio_ptr = split_bio;
}
return true;
}
union blk_crypto_iv {
__le64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
u8 bytes[BLK_CRYPTO_MAX_IV_SIZE];
};
static void blk_crypto_dun_to_iv(const u64 dun[BLK_CRYPTO_DUN_ARRAY_SIZE],
union blk_crypto_iv *iv)
{
int i;
for (i = 0; i < BLK_CRYPTO_DUN_ARRAY_SIZE; i++)
iv->dun[i] = cpu_to_le64(dun[i]);
}
/*
* The crypto API fallback's encryption routine.
* Allocate a bounce bio for encryption, encrypt the input bio using crypto API,
* and replace *bio_ptr with the bounce bio. May split input bio if it's too
* large. Returns true on success. Returns false and sets bio->bi_status on
* error.
*/
static bool blk_crypto_fallback_encrypt_bio(struct bio **bio_ptr)
{
struct bio *src_bio, *enc_bio;
struct bio_crypt_ctx *bc;
struct blk_crypto_keyslot *slot;
int data_unit_size;
struct skcipher_request *ciph_req = NULL;
DECLARE_CRYPTO_WAIT(wait);
u64 curr_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
struct scatterlist src, dst;
union blk_crypto_iv iv;
unsigned int i, j;
bool ret = false;
blk_status_t blk_st;
/* Split the bio if it's too big for single page bvec */
if (!blk_crypto_fallback_split_bio_if_needed(bio_ptr))
return false;
src_bio = *bio_ptr;
bc = src_bio->bi_crypt_context;
data_unit_size = bc->bc_key->crypto_cfg.data_unit_size;
/* Allocate bounce bio for encryption */
enc_bio = blk_crypto_fallback_clone_bio(src_bio);
if (!enc_bio) {
src_bio->bi_status = BLK_STS_RESOURCE;
return false;
}
/*
* Get a blk-crypto-fallback keyslot that contains a crypto_skcipher for
* this bio's algorithm and key.
*/
blk_st = blk_crypto_get_keyslot(blk_crypto_fallback_profile,
bc->bc_key, &slot);
if (blk_st != BLK_STS_OK) {
src_bio->bi_status = blk_st;
goto out_put_enc_bio;
}
/* and then allocate an skcipher_request for it */
if (!blk_crypto_fallback_alloc_cipher_req(slot, &ciph_req, &wait)) {
src_bio->bi_status = BLK_STS_RESOURCE;
goto out_release_keyslot;
}
memcpy(curr_dun, bc->bc_dun, sizeof(curr_dun));
sg_init_table(&src, 1);
sg_init_table(&dst, 1);
skcipher_request_set_crypt(ciph_req, &src, &dst, data_unit_size,
iv.bytes);
/* Encrypt each page in the bounce bio */
for (i = 0; i < enc_bio->bi_vcnt; i++) {
struct bio_vec *enc_bvec = &enc_bio->bi_io_vec[i];
struct page *plaintext_page = enc_bvec->bv_page;
struct page *ciphertext_page =
mempool_alloc(blk_crypto_bounce_page_pool, GFP_NOIO);
enc_bvec->bv_page = ciphertext_page;
if (!ciphertext_page) {
src_bio->bi_status = BLK_STS_RESOURCE;
goto out_free_bounce_pages;
}
sg_set_page(&src, plaintext_page, data_unit_size,
enc_bvec->bv_offset);
sg_set_page(&dst, ciphertext_page, data_unit_size,
enc_bvec->bv_offset);
/* Encrypt each data unit in this page */
for (j = 0; j < enc_bvec->bv_len; j += data_unit_size) {
blk_crypto_dun_to_iv(curr_dun, &iv);
if (crypto_wait_req(crypto_skcipher_encrypt(ciph_req),
&wait)) {
i++;
src_bio->bi_status = BLK_STS_IOERR;
goto out_free_bounce_pages;
}
bio_crypt_dun_increment(curr_dun, 1);
src.offset += data_unit_size;
dst.offset += data_unit_size;
}
}
enc_bio->bi_private = src_bio;
enc_bio->bi_end_io = blk_crypto_fallback_encrypt_endio;
*bio_ptr = enc_bio;
ret = true;
enc_bio = NULL;
goto out_free_ciph_req;
out_free_bounce_pages:
while (i > 0)
mempool_free(enc_bio->bi_io_vec[--i].bv_page,
blk_crypto_bounce_page_pool);
out_free_ciph_req:
skcipher_request_free(ciph_req);
out_release_keyslot:
blk_crypto_put_keyslot(slot);
out_put_enc_bio:
if (enc_bio)
bio_uninit(enc_bio);
kfree(enc_bio);
return ret;
}
/*
* The crypto API fallback's main decryption routine.
* Decrypts input bio in place, and calls bio_endio on the bio.
*/
static void blk_crypto_fallback_decrypt_bio(struct work_struct *work)
{
struct bio_fallback_crypt_ctx *f_ctx =
container_of(work, struct bio_fallback_crypt_ctx, work);
struct bio *bio = f_ctx->bio;
struct bio_crypt_ctx *bc = &f_ctx->crypt_ctx;
struct blk_crypto_keyslot *slot;
struct skcipher_request *ciph_req = NULL;
DECLARE_CRYPTO_WAIT(wait);
u64 curr_dun[BLK_CRYPTO_DUN_ARRAY_SIZE];
union blk_crypto_iv iv;
struct scatterlist sg;
struct bio_vec bv;
struct bvec_iter iter;
const int data_unit_size = bc->bc_key->crypto_cfg.data_unit_size;
unsigned int i;
blk_status_t blk_st;
/*
* Get a blk-crypto-fallback keyslot that contains a crypto_skcipher for
* this bio's algorithm and key.
*/
blk_st = blk_crypto_get_keyslot(blk_crypto_fallback_profile,
bc->bc_key, &slot);
if (blk_st != BLK_STS_OK) {
bio->bi_status = blk_st;
goto out_no_keyslot;
}
/* and then allocate an skcipher_request for it */
if (!blk_crypto_fallback_alloc_cipher_req(slot, &ciph_req, &wait)) {
bio->bi_status = BLK_STS_RESOURCE;
goto out;
}
memcpy(curr_dun, bc->bc_dun, sizeof(curr_dun));
sg_init_table(&sg, 1);
skcipher_request_set_crypt(ciph_req, &sg, &sg, data_unit_size,
iv.bytes);
/* Decrypt each segment in the bio */
__bio_for_each_segment(bv, bio, iter, f_ctx->crypt_iter) {
struct page *page = bv.bv_page;
sg_set_page(&sg, page, data_unit_size, bv.bv_offset);
/* Decrypt each data unit in the segment */
for (i = 0; i < bv.bv_len; i += data_unit_size) {
blk_crypto_dun_to_iv(curr_dun, &iv);
if (crypto_wait_req(crypto_skcipher_decrypt(ciph_req),
&wait)) {
bio->bi_status = BLK_STS_IOERR;
goto out;
}
bio_crypt_dun_increment(curr_dun, 1);
sg.offset += data_unit_size;
}
}
out:
skcipher_request_free(ciph_req);
blk_crypto_put_keyslot(slot);
out_no_keyslot:
mempool_free(f_ctx, bio_fallback_crypt_ctx_pool);
bio_endio(bio);
}
/**
* blk_crypto_fallback_decrypt_endio - queue bio for fallback decryption
*
* @bio: the bio to queue
*
* Restore bi_private and bi_end_io, and queue the bio for decryption into a
* workqueue, since this function will be called from an atomic context.
*/
static void blk_crypto_fallback_decrypt_endio(struct bio *bio)
{
struct bio_fallback_crypt_ctx *f_ctx = bio->bi_private;
bio->bi_private = f_ctx->bi_private_orig;
bio->bi_end_io = f_ctx->bi_end_io_orig;
/* If there was an IO error, don't queue for decrypt. */
if (bio->bi_status) {
mempool_free(f_ctx, bio_fallback_crypt_ctx_pool);
bio_endio(bio);
return;
}
INIT_WORK(&f_ctx->work, blk_crypto_fallback_decrypt_bio);
f_ctx->bio = bio;
queue_work(blk_crypto_wq, &f_ctx->work);
}
/**
* blk_crypto_fallback_bio_prep - Prepare a bio to use fallback en/decryption
*
* @bio_ptr: pointer to the bio to prepare
*
* If bio is doing a WRITE operation, this splits the bio into two parts if it's
* too big (see blk_crypto_fallback_split_bio_if_needed()). It then allocates a
* bounce bio for the first part, encrypts it, and updates bio_ptr to point to
* the bounce bio.
*
* For a READ operation, we mark the bio for decryption by using bi_private and
* bi_end_io.
*
* In either case, this function will make the bio look like a regular bio (i.e.
* as if no encryption context was ever specified) for the purposes of the rest
* of the stack except for blk-integrity (blk-integrity and blk-crypto are not
* currently supported together).
*
* Return: true on success. Sets bio->bi_status and returns false on error.
*/
bool blk_crypto_fallback_bio_prep(struct bio **bio_ptr)
{
struct bio *bio = *bio_ptr;
struct bio_crypt_ctx *bc = bio->bi_crypt_context;
struct bio_fallback_crypt_ctx *f_ctx;
if (WARN_ON_ONCE(!tfms_inited[bc->bc_key->crypto_cfg.crypto_mode])) {
/* User didn't call blk_crypto_start_using_key() first */
bio->bi_status = BLK_STS_IOERR;
return false;
}
if (!__blk_crypto_cfg_supported(blk_crypto_fallback_profile,
&bc->bc_key->crypto_cfg)) {
bio->bi_status = BLK_STS_NOTSUPP;
return false;
}
if (bio_data_dir(bio) == WRITE)
return blk_crypto_fallback_encrypt_bio(bio_ptr);
/*
* bio READ case: Set up a f_ctx in the bio's bi_private and set the
* bi_end_io appropriately to trigger decryption when the bio is ended.
*/
f_ctx = mempool_alloc(bio_fallback_crypt_ctx_pool, GFP_NOIO);
f_ctx->crypt_ctx = *bc;
f_ctx->crypt_iter = bio->bi_iter;
f_ctx->bi_private_orig = bio->bi_private;
f_ctx->bi_end_io_orig = bio->bi_end_io;
bio->bi_private = (void *)f_ctx;
bio->bi_end_io = blk_crypto_fallback_decrypt_endio;
bio_crypt_free_ctx(bio);
return true;
}
int blk_crypto_fallback_evict_key(const struct blk_crypto_key *key)
{
return __blk_crypto_evict_key(blk_crypto_fallback_profile, key);
}
static bool blk_crypto_fallback_inited;
static int blk_crypto_fallback_init(void)
{
int i;
int err;
if (blk_crypto_fallback_inited)
return 0;
get_random_bytes(blank_key, sizeof(blank_key));
err = bioset_init(&crypto_bio_split, 64, 0, 0);
if (err)
goto out;
/* Dynamic allocation is needed because of lockdep_register_key(). */
blk_crypto_fallback_profile =
kzalloc(sizeof(*blk_crypto_fallback_profile), GFP_KERNEL);
if (!blk_crypto_fallback_profile) {
err = -ENOMEM;
goto fail_free_bioset;
}
err = blk_crypto_profile_init(blk_crypto_fallback_profile,
blk_crypto_num_keyslots);
if (err)
goto fail_free_profile;
err = -ENOMEM;
blk_crypto_fallback_profile->ll_ops = blk_crypto_fallback_ll_ops;
blk_crypto_fallback_profile->max_dun_bytes_supported = BLK_CRYPTO_MAX_IV_SIZE;
blk_crypto_fallback_profile->key_types_supported = BLK_CRYPTO_KEY_TYPE_STANDARD;
/* All blk-crypto modes have a crypto API fallback. */
for (i = 0; i < BLK_ENCRYPTION_MODE_MAX; i++)
blk_crypto_fallback_profile->modes_supported[i] = 0xFFFFFFFF;
blk_crypto_fallback_profile->modes_supported[BLK_ENCRYPTION_MODE_INVALID] = 0;
blk_crypto_wq = alloc_workqueue("blk_crypto_wq",
WQ_UNBOUND | WQ_HIGHPRI |
WQ_MEM_RECLAIM, num_online_cpus());
if (!blk_crypto_wq)
goto fail_destroy_profile;
blk_crypto_keyslots = kcalloc(blk_crypto_num_keyslots,
sizeof(blk_crypto_keyslots[0]),
GFP_KERNEL);
if (!blk_crypto_keyslots)
goto fail_free_wq;
blk_crypto_bounce_page_pool =
mempool_create_page_pool(num_prealloc_bounce_pg, 0);
if (!blk_crypto_bounce_page_pool)
goto fail_free_keyslots;
bio_fallback_crypt_ctx_cache = KMEM_CACHE(bio_fallback_crypt_ctx, 0);
if (!bio_fallback_crypt_ctx_cache)
goto fail_free_bounce_page_pool;
bio_fallback_crypt_ctx_pool =
mempool_create_slab_pool(num_prealloc_fallback_crypt_ctxs,
bio_fallback_crypt_ctx_cache);
if (!bio_fallback_crypt_ctx_pool)
goto fail_free_crypt_ctx_cache;
blk_crypto_fallback_inited = true;
return 0;
fail_free_crypt_ctx_cache:
kmem_cache_destroy(bio_fallback_crypt_ctx_cache);
fail_free_bounce_page_pool:
mempool_destroy(blk_crypto_bounce_page_pool);
fail_free_keyslots:
kfree(blk_crypto_keyslots);
fail_free_wq:
destroy_workqueue(blk_crypto_wq);
fail_destroy_profile:
blk_crypto_profile_destroy(blk_crypto_fallback_profile);
fail_free_profile:
kfree(blk_crypto_fallback_profile);
fail_free_bioset:
bioset_exit(&crypto_bio_split);
out:
return err;
}
/*
* Prepare blk-crypto-fallback for the specified crypto mode.
* Returns -ENOPKG if the needed crypto API support is missing.
*/
int blk_crypto_fallback_start_using_mode(enum blk_crypto_mode_num mode_num)
{
const char *cipher_str = blk_crypto_modes[mode_num].cipher_str;
struct blk_crypto_fallback_keyslot *slotp;
unsigned int i;
int err = 0;
/*
* Fast path
* Ensure that updates to blk_crypto_keyslots[i].tfms[mode_num]
* for each i are visible before we try to access them.
*/
if (likely(smp_load_acquire(&tfms_inited[mode_num])))
return 0;
mutex_lock(&tfms_init_lock);
if (tfms_inited[mode_num])
goto out;
err = blk_crypto_fallback_init();
if (err)
goto out;
for (i = 0; i < blk_crypto_num_keyslots; i++) {
slotp = &blk_crypto_keyslots[i];
slotp->tfms[mode_num] = crypto_alloc_skcipher(cipher_str, 0, 0);
if (IS_ERR(slotp->tfms[mode_num])) {
err = PTR_ERR(slotp->tfms[mode_num]);
if (err == -ENOENT) {
pr_warn_once("Missing crypto API support for \"%s\"\n",
cipher_str);
err = -ENOPKG;
}
slotp->tfms[mode_num] = NULL;
goto out_free_tfms;
}
crypto_skcipher_set_flags(slotp->tfms[mode_num],
CRYPTO_TFM_REQ_FORBID_WEAK_KEYS);
}
/*
* Ensure that updates to blk_crypto_keyslots[i].tfms[mode_num]
* for each i are visible before we set tfms_inited[mode_num].
*/
smp_store_release(&tfms_inited[mode_num], true);
goto out;
out_free_tfms:
for (i = 0; i < blk_crypto_num_keyslots; i++) {
slotp = &blk_crypto_keyslots[i];
crypto_free_skcipher(slotp->tfms[mode_num]);
slotp->tfms[mode_num] = NULL;
}
out:
mutex_unlock(&tfms_init_lock);
return err;
}