android_kernel_samsung_sm8650/fs/verity/verify.c
Greg Kroah-Hartman db50ac4d0a Merge 6.1.22 into android14-6.1
Changes in 6.1.22
	interconnect: qcom: osm-l3: fix icc_onecell_data allocation
	interconnect: qcom: sm8450: switch to qcom_icc_rpmh_* function
	interconnect: qcom: qcm2290: Fix MASTER_SNOC_BIMC_NRT
	perf/core: Fix perf_output_begin parameter is incorrectly invoked in perf_event_bpf_output
	perf: fix perf_event_context->time
	tracing/hwlat: Replace sched_setaffinity with set_cpus_allowed_ptr
	drm/amd/display: Include virtual signal to set k1 and k2 values
	drm/amd/display: fix k1 k2 divider programming for phantom streams
	drm/amd/display: Remove OTG DIV register write for Virtual signals.
	mptcp: refactor passive socket initialization
	mptcp: use the workqueue to destroy unaccepted sockets
	mptcp: fix UaF in listener shutdown
	drm/amd/display: Fix DP MST sinks removal issue
	arm64: dts: qcom: sm8450: Mark UFS controller as cache coherent
	power: supply: bq24190: Fix use after free bug in bq24190_remove due to race condition
	power: supply: da9150: Fix use after free bug in da9150_charger_remove due to race condition
	arm64: dts: imx8dxl-evk: Disable hibernation mode of AR8031 for EQOS
	arm64: dts: imx8dxl-evk: Fix eqos phy reset gpio
	ARM: dts: imx6sll: e70k02: fix usbotg1 pinctrl
	ARM: dts: imx6sll: e60k02: fix usbotg1 pinctrl
	ARM: dts: imx6sl: tolino-shine2hd: fix usbotg1 pinctrl
	arm64: dts: imx8mn: specify #sound-dai-cells for SAI nodes
	arm64: dts: imx93: add missing #address-cells and #size-cells to i2c nodes
	NFS: Fix /proc/PID/io read_bytes for buffered reads
	xsk: Add missing overflow check in xdp_umem_reg
	iavf: fix inverted Rx hash condition leading to disabled hash
	iavf: fix non-tunneled IPv6 UDP packet type and hashing
	iavf: do not track VLAN 0 filters
	intel/igbvf: free irq on the error path in igbvf_request_msix()
	igbvf: Regard vf reset nack as success
	igc: fix the validation logic for taprio's gate list
	i2c: imx-lpi2c: check only for enabled interrupt flags
	i2c: mxs: ensure that DMA buffers are safe for DMA
	i2c: hisi: Only use the completion interrupt to finish the transfer
	scsi: scsi_dh_alua: Fix memleak for 'qdata' in alua_activate()
	nfsd: don't replace page in rq_pages if it's a continuation of last page
	net: dsa: b53: mmap: fix device tree support
	net: usb: smsc95xx: Limit packet length to skb->len
	efi/libstub: smbios: Use length member instead of record struct size
	qed/qed_sriov: guard against NULL derefs from qed_iov_get_vf_info
	xirc2ps_cs: Fix use after free bug in xirc2ps_detach
	net: phy: Ensure state transitions are processed from phy_stop()
	net: mdio: fix owner field for mdio buses registered using device-tree
	net: mdio: fix owner field for mdio buses registered using ACPI
	net: stmmac: Fix for mismatched host/device DMA address width
	thermal/drivers/mellanox: Use generic thermal_zone_get_trip() function
	mlxsw: core_thermal: Fix fan speed in maximum cooling state
	drm/i915: Print return value on error
	drm/i915/fbdev: lock the fbdev obj before vma pin
	drm/i915/guc: Rename GuC register state capture node to be more obvious
	drm/i915/guc: Fix missing ecodes
	drm/i915/gt: perform uc late init after probe error injection
	net: qcom/emac: Fix use after free bug in emac_remove due to race condition
	net: usb: lan78xx: Limit packet length to skb->len
	net/ps3_gelic_net: Fix RX sk_buff length
	net/ps3_gelic_net: Use dma_mapping_error
	octeontx2-vf: Add missing free for alloc_percpu
	bootconfig: Fix testcase to increase max node
	keys: Do not cache key in task struct if key is requested from kernel thread
	ice: check if VF exists before mode check
	iavf: fix hang on reboot with ice
	i40e: fix flow director packet filter programming
	bpf: Adjust insufficient default bpf_jit_limit
	net/mlx5e: Set uplink rep as NETNS_LOCAL
	net/mlx5e: Block entering switchdev mode with ns inconsistency
	net/mlx5: Fix steering rules cleanup
	net/mlx5e: Overcome slow response for first macsec ASO WQE
	net/mlx5: Read the TC mapping of all priorities on ETS query
	net/mlx5: E-Switch, Fix an Oops in error handling code
	net: dsa: tag_brcm: legacy: fix daisy-chained switches
	atm: idt77252: fix kmemleak when rmmod idt77252
	erspan: do not use skb_mac_header() in ndo_start_xmit()
	net/sonic: use dma_mapping_error() for error check
	nvme-tcp: fix nvme_tcp_term_pdu to match spec
	mlxsw: spectrum_fid: Fix incorrect local port type
	hvc/xen: prevent concurrent accesses to the shared ring
	ksmbd: add low bound validation to FSCTL_SET_ZERO_DATA
	ksmbd: add low bound validation to FSCTL_QUERY_ALLOCATED_RANGES
	ksmbd: fix possible refcount leak in smb2_open()
	Bluetooth: hci_sync: Resume adv with no RPA when active scan
	Bluetooth: hci_core: Detect if an ACL packet is in fact an ISO packet
	Bluetooth: btusb: Remove detection of ISO packets over bulk
	Bluetooth: ISO: fix timestamped HCI ISO data packet parsing
	Bluetooth: Remove "Power-on" check from Mesh feature
	gve: Cache link_speed value from device
	net: asix: fix modprobe "sysfs: cannot create duplicate filename"
	net: dsa: mt7530: move enabling disabling core clock to mt7530_pll_setup()
	net: dsa: mt7530: move lowering TRGMII driving to mt7530_setup()
	net: dsa: mt7530: move setting ssc_delta to PHY_INTERFACE_MODE_TRGMII case
	net: mdio: thunder: Add missing fwnode_handle_put()
	drm/amd/display: Set dcn32 caps.seamless_odm
	Bluetooth: btqcomsmd: Fix command timeout after setting BD address
	Bluetooth: L2CAP: Fix responding with wrong PDU type
	Bluetooth: btsdio: fix use after free bug in btsdio_remove due to unfinished work
	Bluetooth: mgmt: Fix MGMT add advmon with RSSI command
	Bluetooth: HCI: Fix global-out-of-bounds
	platform/chrome: cros_ec_chardev: fix kernel data leak from ioctl
	entry: Fix noinstr warning in __enter_from_user_mode()
	perf/x86/amd/core: Always clear status for idx
	entry/rcu: Check TIF_RESCHED _after_ delayed RCU wake-up
	hwmon: fix potential sensor registration fail if of_node is missing
	hwmon (it87): Fix voltage scaling for chips with 10.9mV ADCs
	scsi: qla2xxx: Synchronize the IOCB count to be in order
	scsi: qla2xxx: Perform lockless command completion in abort path
	smb3: lower default deferred close timeout to address perf regression
	smb3: fix unusable share after force unmount failure
	uas: Add US_FL_NO_REPORT_OPCODES for JMicron JMS583Gen 2
	thunderbolt: Use scale field when allocating USB3 bandwidth
	thunderbolt: Call tb_check_quirks() after initializing adapters
	thunderbolt: Add quirk to disable CLx
	thunderbolt: Fix memory leak in margining
	thunderbolt: Disable interrupt auto clear for rings
	thunderbolt: Add missing UNSET_INBOUND_SBTX for retimer access
	thunderbolt: Use const qualifier for `ring_interrupt_index`
	thunderbolt: Rename shadowed variables bit to interrupt_bit and auto_clear_bit
	ASoC: amd: yp: Add OMEN by HP Gaming Laptop 16z-n000 to quirks
	ASoC: amd: yc: Add DMI entries to support HP OMEN 16-n0xxx (8A43)
	ACPI: x86: Drop quirk for HP Elitebook
	ACPI: x86: utils: Add Cezanne to the list for forcing StorageD3Enable
	riscv: Bump COMMAND_LINE_SIZE value to 1024
	drm/cirrus: NULL-check pipe->plane.state->fb in cirrus_pipe_update()
	HID: cp2112: Fix driver not registering GPIO IRQ chip as threaded
	ca8210: fix mac_len negative array access
	HID: logitech-hidpp: Add support for Logitech MX Master 3S mouse
	HID: intel-ish-hid: ipc: Fix potential use-after-free in work function
	m68k: mm: Fix systems with memory at end of 32-bit address space
	m68k: Only force 030 bus error if PC not in exception table
	selftests/bpf: check that modifier resolves after pointer
	scsi: target: iscsi: Fix an error message in iscsi_check_key()
	scsi: qla2xxx: Add option to disable FC2 Target support
	scsi: hisi_sas: Check devm_add_action() return value
	scsi: ufs: core: Add soft dependency on governor_simpleondemand
	scsi: lpfc: Check kzalloc() in lpfc_sli4_cgn_params_read()
	scsi: lpfc: Avoid usage of list iterator variable after loop
	scsi: mpi3mr: Driver unload crashes host when enhanced logging is enabled
	scsi: mpi3mr: Wait for diagnostic save during controller init
	scsi: mpi3mr: NVMe command size greater than 8K fails
	scsi: mpi3mr: Bad drive in topology results kernel crash
	scsi: storvsc: Handle BlockSize change in Hyper-V VHD/VHDX file
	platform/x86: int3472: Add GPIOs to Surface Go 3 Board data
	net: usb: cdc_mbim: avoid altsetting toggling for Telit FE990
	net: usb: qmi_wwan: add Telit 0x1080 composition
	drm/amd/display: Update clock table to include highest clock setting
	sh: sanitize the flags on sigreturn
	drm/amdgpu: Fix call trace warning and hang when removing amdgpu device
	drm/amd: Fix initialization mistake for NBIO 7.3.0
	net/sched: act_mirred: better wording on protection against excessive stack growth
	act_mirred: use the backlog for nested calls to mirred ingress
	cifs: lock chan_lock outside match_session
	cifs: append path to open_enter trace event
	cifs: do not poll server interfaces too regularly
	cifs: empty interface list when server doesn't support query interfaces
	cifs: dump pending mids for all channels in DebugData
	cifs: print session id while listing open files
	cifs: fix dentry lookups in directory handle cache
	x86/fpu/xstate: Prevent false-positive warning in __copy_xstate_uabi_buf()
	selftests/x86/amx: Add a ptrace test
	scsi: core: Add BLIST_SKIP_VPD_PAGES for SKhynix H28U74301AMR
	usb: misc: onboard-hub: add support for Microchip USB2517 USB 2.0 hub
	usb: dwc2: drd: fix inconsistent mode if role-switch-default-mode="host"
	usb: dwc2: fix a devres leak in hw_enable upon suspend resume
	usb: gadget: u_audio: don't let userspace block driver unbind
	btrfs: zoned: fix btrfs_can_activate_zone() to support DUP profile
	Bluetooth: Fix race condition in hci_cmd_sync_clear
	efi: sysfb_efi: Fix DMI quirks not working for simpledrm
	mm/slab: Fix undefined init_cache_node_node() for NUMA and !SMP
	fscrypt: destroy keyring after security_sb_delete()
	fsverity: Remove WQ_UNBOUND from fsverity read workqueue
	lockd: set file_lock start and end when decoding nlm4 testargs
	arm64: dts: imx8mm-nitrogen-r2: fix WM8960 clock name
	igb: revert rtnl_lock() that causes deadlock
	dm thin: fix deadlock when swapping to thin device
	usb: typec: tcpm: fix create duplicate source-capabilities file
	usb: typec: tcpm: fix warning when handle discover_identity message
	usb: cdns3: Fix issue with using incorrect PCI device function
	usb: cdnsp: Fixes issue with redundant Status Stage
	usb: cdnsp: changes PCI Device ID to fix conflict with CNDS3 driver
	usb: chipdea: core: fix return -EINVAL if request role is the same with current role
	usb: chipidea: core: fix possible concurrent when switch role
	usb: dwc3: gadget: Add 1ms delay after end transfer command without IOC
	usb: ucsi: Fix NULL pointer deref in ucsi_connector_change()
	usb: ucsi_acpi: Increase the command completion timeout
	mm: kfence: fix using kfence_metadata without initialization in show_object()
	kfence: avoid passing -g for test
	io_uring/net: avoid sending -ECONNABORTED on repeated connection requests
	io_uring/rsrc: fix null-ptr-deref in io_file_bitmap_get()
	Revert "kasan: drop skip_kasan_poison variable in free_pages_prepare"
	test_maple_tree: add more testing for mas_empty_area()
	maple_tree: fix mas_skip_node() end slot detection
	ksmbd: fix wrong signingkey creation when encryption is AES256
	ksmbd: set FILE_NAMED_STREAMS attribute in FS_ATTRIBUTE_INFORMATION
	ksmbd: don't terminate inactive sessions after a few seconds
	ksmbd: return STATUS_NOT_SUPPORTED on unsupported smb2.0 dialect
	ksmbd: return unsupported error on smb1 mount
	wifi: mac80211: fix qos on mesh interfaces
	nilfs2: fix kernel-infoleak in nilfs_ioctl_wrap_copy()
	drm/bridge: lt8912b: return EPROBE_DEFER if bridge is not found
	drm/amd/display: fix wrong index used in dccg32_set_dpstreamclk
	drm/meson: fix missing component unbind on bind errors
	drm/amdgpu/nv: Apply ASPM quirk on Intel ADL + AMD Navi
	drm/i915/active: Fix missing debug object activation
	drm/i915: Preserve crtc_state->inherited during state clearing
	drm/amdgpu: skip ASIC reset for APUs when go to S4
	drm/amdgpu: reposition the gpu reset checking for reuse
	riscv: mm: Fix incorrect ASID argument when flushing TLB
	riscv: Handle zicsr/zifencei issues between clang and binutils
	tee: amdtee: fix race condition in amdtee_open_session
	firmware: arm_scmi: Fix device node validation for mailbox transport
	arm64: dts: qcom: sc7280: Mark PCIe controller as cache coherent
	arm64: dts: qcom: sm8150: Fix the iommu mask used for PCIe controllers
	soc: qcom: llcc: Fix slice configuration values for SC8280XP
	mm/ksm: fix race with VMA iteration and mm_struct teardown
	bus: imx-weim: fix branch condition evaluates to a garbage value
	i2c: xgene-slimpro: Fix out-of-bounds bug in xgene_slimpro_i2c_xfer()
	dm stats: check for and propagate alloc_percpu failure
	dm crypt: add cond_resched() to dmcrypt_write()
	dm crypt: avoid accessing uninitialized tasklet
	sched/fair: sanitize vruntime of entity being placed
	sched/fair: Sanitize vruntime of entity being migrated
	drm/amdkfd: introduce dummy cache info for property asic
	drm/amdkfd: Fix the warning of array-index-out-of-bounds
	drm/amdkfd: add GC 11.0.4 KFD support
	drm/amdkfd: Fix the memory overrun
	Linux 6.1.22

Change-Id: Id13b4655dbfb59c29a0b8953e5e0cda3703f1879
Signed-off-by: Greg Kroah-Hartman <gregkh@google.com>
2023-03-31 08:15:39 +00:00

410 lines
13 KiB
C

// SPDX-License-Identifier: GPL-2.0
/*
* Data verification functions, i.e. hooks for ->readahead()
*
* Copyright 2019 Google LLC
*/
#include "fsverity_private.h"
#include <crypto/hash.h>
#include <linux/bio.h>
static struct workqueue_struct *fsverity_read_workqueue;
static inline int cmp_hashes(const struct fsverity_info *vi,
const u8 *want_hash, const u8 *real_hash,
u64 data_pos, int level)
{
const unsigned int hsize = vi->tree_params.digest_size;
if (memcmp(want_hash, real_hash, hsize) == 0)
return 0;
fsverity_err(vi->inode,
"FILE CORRUPTED! pos=%llu, level=%d, want_hash=%s:%*phN, real_hash=%s:%*phN",
data_pos, level,
vi->tree_params.hash_alg->name, hsize, want_hash,
vi->tree_params.hash_alg->name, hsize, real_hash);
return -EBADMSG;
}
static bool data_is_zeroed(struct inode *inode, struct page *page,
unsigned int len, unsigned int offset)
{
void *virt = kmap_local_page(page);
if (memchr_inv(virt + offset, 0, len)) {
kunmap_local(virt);
fsverity_err(inode,
"FILE CORRUPTED! Data past EOF is not zeroed");
return false;
}
kunmap_local(virt);
return true;
}
/*
* Returns true if the hash block with index @hblock_idx in the tree, located in
* @hpage, has already been verified.
*/
static bool is_hash_block_verified(struct fsverity_info *vi, struct page *hpage,
unsigned long hblock_idx)
{
bool verified;
unsigned int blocks_per_page;
unsigned int i;
/*
* When the Merkle tree block size and page size are the same, then the
* ->hash_block_verified bitmap isn't allocated, and we use PG_checked
* to directly indicate whether the page's block has been verified.
*
* Using PG_checked also guarantees that we re-verify hash pages that
* get evicted and re-instantiated from the backing storage, as new
* pages always start out with PG_checked cleared.
*/
if (!vi->hash_block_verified)
return PageChecked(hpage);
/*
* When the Merkle tree block size and page size differ, we use a bitmap
* to indicate whether each hash block has been verified.
*
* However, we still need to ensure that hash pages that get evicted and
* re-instantiated from the backing storage are re-verified. To do
* this, we use PG_checked again, but now it doesn't really mean
* "checked". Instead, now it just serves as an indicator for whether
* the hash page is newly instantiated or not.
*
* The first thread that sees PG_checked=0 must clear the corresponding
* bitmap bits, then set PG_checked=1. This requires a spinlock. To
* avoid having to take this spinlock in the common case of
* PG_checked=1, we start with an opportunistic lockless read.
*/
if (PageChecked(hpage)) {
/*
* A read memory barrier is needed here to give ACQUIRE
* semantics to the above PageChecked() test.
*/
smp_rmb();
return test_bit(hblock_idx, vi->hash_block_verified);
}
spin_lock(&vi->hash_page_init_lock);
if (PageChecked(hpage)) {
verified = test_bit(hblock_idx, vi->hash_block_verified);
} else {
blocks_per_page = vi->tree_params.blocks_per_page;
hblock_idx = round_down(hblock_idx, blocks_per_page);
for (i = 0; i < blocks_per_page; i++)
clear_bit(hblock_idx + i, vi->hash_block_verified);
/*
* A write memory barrier is needed here to give RELEASE
* semantics to the below SetPageChecked() operation.
*/
smp_wmb();
SetPageChecked(hpage);
verified = false;
}
spin_unlock(&vi->hash_page_init_lock);
return verified;
}
/*
* Verify a single data block against the file's Merkle tree.
*
* In principle, we need to verify the entire path to the root node. However,
* for efficiency the filesystem may cache the hash blocks. Therefore we need
* only ascend the tree until an already-verified hash block is seen, and then
* verify the path to that block.
*
* Return: %true if the data block is valid, else %false.
*/
static bool
verify_data_block(struct inode *inode, struct fsverity_info *vi,
struct ahash_request *req, struct page *data_page,
u64 data_pos, unsigned int dblock_offset_in_page,
unsigned long max_ra_pages)
{
const struct merkle_tree_params *params = &vi->tree_params;
const unsigned int hsize = params->digest_size;
int level;
u8 _want_hash[FS_VERITY_MAX_DIGEST_SIZE];
const u8 *want_hash;
u8 real_hash[FS_VERITY_MAX_DIGEST_SIZE];
/* The hash blocks that are traversed, indexed by level */
struct {
/* Page containing the hash block */
struct page *page;
/* Index of the hash block in the tree overall */
unsigned long index;
/* Byte offset of the hash block within @page */
unsigned int offset_in_page;
/* Byte offset of the wanted hash within @page */
unsigned int hoffset;
} hblocks[FS_VERITY_MAX_LEVELS];
/*
* The index of the previous level's block within that level; also the
* index of that block's hash within the current level.
*/
u64 hidx = data_pos >> params->log_blocksize;
int err;
if (unlikely(data_pos >= inode->i_size)) {
/*
* This can happen in the data page spanning EOF when the Merkle
* tree block size is less than the page size. The Merkle tree
* doesn't cover data blocks fully past EOF. But the entire
* page spanning EOF can be visible to userspace via a mmap, and
* any part past EOF should be all zeroes. Therefore, we need
* to verify that any data blocks fully past EOF are all zeroes.
*/
return data_is_zeroed(inode, data_page, params->block_size,
dblock_offset_in_page);
}
/*
* Starting at the leaf level, ascend the tree saving hash blocks along
* the way until we find a hash block that has already been verified, or
* until we reach the root.
*/
for (level = 0; level < params->num_levels; level++) {
unsigned long next_hidx;
unsigned long hblock_idx;
pgoff_t hpage_idx;
unsigned int hblock_offset_in_page;
unsigned int hoffset;
struct page *hpage;
/*
* The index of the block in the current level; also the index
* of that block's hash within the next level.
*/
next_hidx = hidx >> params->log_arity;
/* Index of the hash block in the tree overall */
hblock_idx = params->level_start[level] + next_hidx;
/* Index of the hash page in the tree overall */
hpage_idx = hblock_idx >> params->log_blocks_per_page;
/* Byte offset of the hash block within the page */
hblock_offset_in_page =
(hblock_idx << params->log_blocksize) & ~PAGE_MASK;
/* Byte offset of the hash within the page */
hoffset = hblock_offset_in_page +
((hidx << params->log_digestsize) &
(params->block_size - 1));
hpage = inode->i_sb->s_vop->read_merkle_tree_page(inode,
hpage_idx, level == 0 ? min(max_ra_pages,
params->tree_pages - hpage_idx) : 0);
if (IS_ERR(hpage)) {
err = PTR_ERR(hpage);
fsverity_err(inode,
"Error %d reading Merkle tree page %lu",
err, hpage_idx);
goto out;
}
if (is_hash_block_verified(vi, hpage, hblock_idx)) {
memcpy_from_page(_want_hash, hpage, hoffset, hsize);
want_hash = _want_hash;
put_page(hpage);
goto descend;
}
hblocks[level].page = hpage;
hblocks[level].index = hblock_idx;
hblocks[level].offset_in_page = hblock_offset_in_page;
hblocks[level].hoffset = hoffset;
hidx = next_hidx;
}
want_hash = vi->root_hash;
descend:
/* Descend the tree verifying hash blocks. */
for (; level > 0; level--) {
struct page *hpage = hblocks[level - 1].page;
unsigned long hblock_idx = hblocks[level - 1].index;
unsigned int hblock_offset_in_page =
hblocks[level - 1].offset_in_page;
unsigned int hoffset = hblocks[level - 1].hoffset;
err = fsverity_hash_block(params, inode, req, hpage,
hblock_offset_in_page, real_hash);
if (err)
goto out;
err = cmp_hashes(vi, want_hash, real_hash, data_pos, level - 1);
if (err)
goto out;
/*
* Mark the hash block as verified. This must be atomic and
* idempotent, as the same hash block might be verified by
* multiple threads concurrently.
*/
if (vi->hash_block_verified)
set_bit(hblock_idx, vi->hash_block_verified);
else
SetPageChecked(hpage);
memcpy_from_page(_want_hash, hpage, hoffset, hsize);
want_hash = _want_hash;
put_page(hpage);
}
/* Finally, verify the data block. */
err = fsverity_hash_block(params, inode, req, data_page,
dblock_offset_in_page, real_hash);
if (err)
goto out;
err = cmp_hashes(vi, want_hash, real_hash, data_pos, -1);
out:
for (; level > 0; level--)
put_page(hblocks[level - 1].page);
return err == 0;
}
static bool
verify_data_blocks(struct inode *inode, struct fsverity_info *vi,
struct ahash_request *req, struct folio *data_folio,
size_t len, size_t offset, unsigned long max_ra_pages)
{
const unsigned int block_size = vi->tree_params.block_size;
u64 pos = (u64)data_folio->index << PAGE_SHIFT;
if (WARN_ON_ONCE(len <= 0 || !IS_ALIGNED(len | offset, block_size)))
return false;
if (WARN_ON_ONCE(!folio_test_locked(data_folio) ||
folio_test_uptodate(data_folio)))
return false;
do {
struct page *data_page =
folio_page(data_folio, offset >> PAGE_SHIFT);
if (!verify_data_block(inode, vi, req, data_page, pos + offset,
offset & ~PAGE_MASK, max_ra_pages))
return false;
offset += block_size;
len -= block_size;
} while (len);
return true;
}
/**
* fsverity_verify_blocks() - verify data in a folio
* @folio: the folio containing the data to verify
* @len: the length of the data to verify in the folio
* @offset: the offset of the data to verify in the folio
*
* Verify data that has just been read from a verity file. The data must be
* located in a pagecache folio that is still locked and not yet uptodate. The
* length and offset of the data must be Merkle tree block size aligned.
*
* Return: %true if the data is valid, else %false.
*/
bool fsverity_verify_blocks(struct folio *folio, size_t len, size_t offset)
{
struct inode *inode = folio->mapping->host;
struct fsverity_info *vi = inode->i_verity_info;
struct ahash_request *req;
bool valid;
/* This allocation never fails, since it's mempool-backed. */
req = fsverity_alloc_hash_request(vi->tree_params.hash_alg, GFP_NOFS);
valid = verify_data_blocks(inode, vi, req, folio, len, offset, 0);
fsverity_free_hash_request(vi->tree_params.hash_alg, req);
return valid;
}
EXPORT_SYMBOL_GPL(fsverity_verify_blocks);
#ifdef CONFIG_BLOCK
/**
* fsverity_verify_bio() - verify a 'read' bio that has just completed
* @bio: the bio to verify
*
* Verify the bio's data against the file's Merkle tree. All bio data segments
* must be aligned to the file's Merkle tree block size. If any data fails
* verification, then bio->bi_status is set to an error status.
*
* This is a helper function for use by the ->readahead() method of filesystems
* that issue bios to read data directly into the page cache. Filesystems that
* populate the page cache without issuing bios (e.g. non block-based
* filesystems) must instead call fsverity_verify_page() directly on each page.
* All filesystems must also call fsverity_verify_page() on holes.
*/
void fsverity_verify_bio(struct bio *bio)
{
struct inode *inode = bio_first_page_all(bio)->mapping->host;
struct fsverity_info *vi = inode->i_verity_info;
struct ahash_request *req;
struct folio_iter fi;
unsigned long max_ra_pages = 0;
/* This allocation never fails, since it's mempool-backed. */
req = fsverity_alloc_hash_request(vi->tree_params.hash_alg, GFP_NOFS);
if (bio->bi_opf & REQ_RAHEAD) {
/*
* If this bio is for data readahead, then we also do readahead
* of the first (largest) level of the Merkle tree. Namely,
* when a Merkle tree page is read, we also try to piggy-back on
* some additional pages -- up to 1/4 the number of data pages.
*
* This improves sequential read performance, as it greatly
* reduces the number of I/O requests made to the Merkle tree.
*/
max_ra_pages = bio->bi_iter.bi_size >> (PAGE_SHIFT + 2);
}
bio_for_each_folio_all(fi, bio) {
if (!verify_data_blocks(inode, vi, req, fi.folio, fi.length,
fi.offset, max_ra_pages)) {
bio->bi_status = BLK_STS_IOERR;
break;
}
}
fsverity_free_hash_request(vi->tree_params.hash_alg, req);
}
EXPORT_SYMBOL_GPL(fsverity_verify_bio);
#endif /* CONFIG_BLOCK */
/**
* fsverity_enqueue_verify_work() - enqueue work on the fs-verity workqueue
* @work: the work to enqueue
*
* Enqueue verification work for asynchronous processing.
*/
void fsverity_enqueue_verify_work(struct work_struct *work)
{
queue_work(fsverity_read_workqueue, work);
}
EXPORT_SYMBOL_GPL(fsverity_enqueue_verify_work);
int __init fsverity_init_workqueue(void)
{
/*
* Use a high-priority workqueue to prioritize verification work, which
* blocks reads from completing, over regular application tasks.
*
* For performance reasons, don't use an unbound workqueue. Using an
* unbound workqueue for crypto operations causes excessive scheduler
* latency on ARM64.
*/
fsverity_read_workqueue = alloc_workqueue("fsverity_read_queue",
WQ_HIGHPRI,
num_online_cpus());
if (!fsverity_read_workqueue)
return -ENOMEM;
return 0;
}
void __init fsverity_exit_workqueue(void)
{
destroy_workqueue(fsverity_read_workqueue);
fsverity_read_workqueue = NULL;
}