Skip to contentSkip to conversation

scsi: target: keep command bytes inside the sg

PATCH New Jia Jia 1 participant 9 messages Nov 18

Subsystems (2)
lore
Share & tools
lore

Jia Jia

author
#0 lore raw

v2 cover scsi: target: keep command bytes inside the sg

This series fixes eight target-core accesses past command-buffer or sg boundaries. vhost-scsi can supply guest buffers whose sg boundaries do not coincide with command fields, logical blocks or protection tuples.

Patch 1 builds the COMPARE AND WRITE write sg table from the entries that contain the write half.

Patch 2 limits each REPORT REFERRALS LBA store to the bytes remaining in the response buffer.

Patch 3 rejects SET TARGET PORT GROUPS parameter lists that end in a partial four-byte descriptor.

Patch 4 lets sbc_dif_generate() write an eight-byte protection tuple split across protection sg entries.

Patch 5 lets sbc_dif_verify() read a tuple split across protection sg entries and rejects a partial tuple at the end of the list.

Patch 6 limits each CRC update to the bytes available in the current data sg in both DIF generation and verification.

Patch 7 checks buffer lengths and uses sg copies for the pscsi MODE SENSE write-protect byte and tape MODE SELECT block descriptor.

Patch 8 makes sbc_dif_verify() advance past an escaped block spanning multiple data sg entries.

Patches 1, 2, 3 and 7 are independent. The DIF patches 4, 5, 6 and 8 fix separate bugs and are posted in that order: patch 4 can stand alone, patch 5 uses its tuple-copy helper, and patch 6 builds on both. Patch 8 covers escaped blocks, which bypass the CRC walk.

Changes in v2:
- Keep data sg advancement before the escape check in patch 5.
- Retain the existing atomic page mappings in the DIF paths.
- Fix escape advancement with the existing cursor loop in patch 8.
- Use the existing sg copy helpers for pscsi mode data in patch 7.
- Correct the Fixes tags in patches 1, 3 and 5.
- Explain why PI generation reads an existing tuple before updating it.
- Shorten the commit descriptions and retain the relevant trace frames.

Jia Jia (8):
scsi: target: take COMPARE AND WRITE data from the write half
scsi: target: keep REPORT REFERRALS stores inside the buffer
scsi: target: reject a short SET TARGET PORT GROUPS list
scsi: target: copy a DIF insert tuple across prot sgs
scsi: target: copy a DIF verify tuple across prot sgs
scsi: target: limit DIF block CRC to each data sg
scsi: target: keep pscsi mode bytes inside the data sgs
scsi: target: advance past escaped DIF blocks across data sgs

 drivers/target/target_core_alua.c      |  29 ++-
 drivers/target/target_core_pscsi.c     |  37 ++-
 drivers/target/target_core_sbc.c       | 422 ++++++++++++++++++++++-----------
 drivers/target/target_core_transport.c |  11 +-
 4 files changed, 338 insertions(+), 161 deletions(-)
author
#1 lore raw

PATCH v2 1/8 scsi: target: take COMPARE AND WRITE data from the write half

For block sizes smaller than a page, compare_and_write_callback() adds block_size to the first data sg's offset to locate the write half. This assumes that both halves fit in that sg. If the compare buffer ends at a page boundary, the write entry points past the page even though the write data is available in the following sg.

vhost-scsi splits guest buffers into sg entries that each stay within one page, so the backend can read beyond the supplied data.

Skip the compare bytes across the data sgs and build a table covering the write half. Pass its actual entry count to the backend and release it with sg_free_table(), including any chained allocations.

KASAN reports:

  BUG: KASAN: slab-use-after-free in copy_folio_from_iter_atomic
  Read of size 512

compare_and_write_callback
__target_execute_cmd
sbc_execute_rw
fd_execute_rw
fd_do_rw
vfs_iter_write
copy_folio_from_iter_atomic

Fixes d94e5a61357a ("target: fix COMPARE_AND_WRITE non zero SGL offset data corruption")
---
 drivers/target/target_core_sbc.c       | 100 +++++++++++++++++--------
 drivers/target/target_core_transport.c |  11 ++-
 2 files changed, 80 insertions(+), 31 deletions(-)
drivers/target/target_core_sbc.c +70 -30
index 21f5cb86d70c0..adef903652ac2 100644
@@ -433,19 +433,74 @@ out:
 	return ret;
 }
 
+/*
+ * Data-out is compare bytes followed by write bytes.  Take the write
+ * half from whatever sg entries hold it.  Do not add block_size onto
+ * the first sg offset: that page may end before the write half.
+ */
+static int sbc_caw_build_write_sg(struct sg_table *tbl,
+				  struct scatterlist *data_sg,
+				  unsigned int data_nents, unsigned int skip,
+				  unsigned int len)
+{
+	struct scatterlist *sg, *out;
+	unsigned int nents = 0, left = len, left_skip = skip;
+	unsigned int avail, chunk;
+	int i;
+
+	for_each_sg(data_sg, sg, data_nents, i) {
+		if (!sg->length)
+			continue;
+		if (!left)
+			break;
+		if (left_skip >= sg->length) {
+			left_skip -= sg->length;
+			continue;
+		}
+		avail = sg->length - left_skip;
+		chunk = min(left, avail);
+		nents++;
+		left -= chunk;
+		left_skip = 0;
+	}
+	if (!nents || left)
+		return -EINVAL;
+
+	if (sg_alloc_table(tbl, nents, GFP_KERNEL))
+		return -ENOMEM;
+
+	left = len;
+	left_skip = skip;
+	out = tbl->sgl;
+	for_each_sg(data_sg, sg, data_nents, i) {
+		if (!sg->length)
+			continue;
+		if (!left)
+			break;
+		if (left_skip >= sg->length) {
+			left_skip -= sg->length;
+			continue;
+		}
+		avail = sg->length - left_skip;
+		chunk = min(left, avail);
+		sg_set_page(out, sg_page(sg), chunk, sg->offset + left_skip);
+		left -= chunk;
+		left_skip = 0;
+		out = sg_next(out);
+	}
+	return 0;
+}
+
 static sense_reason_t compare_and_write_callback(struct se_cmd *cmd, bool success,
 						 int *post_ret)
 {
 	struct se_device *dev = cmd->se_dev;
 	struct sg_table write_tbl = { };
 	struct scatterlist *write_sg;
-	struct sg_mapping_iter m;
-	unsigned int len;
-	unsigned int block_size = dev->dev_attrib.block_size;
-	unsigned int compare_len = (cmd->t_task_nolb * block_size);
+	unsigned int compare_len = (cmd->t_task_nolb * dev->dev_attrib.block_size);
 	unsigned int miscmp_off = 0;
 	sense_reason_t ret = TCM_NO_SENSE;
-	int i;
+	int rc;
 
 	if (!success) {
 		/*
@@ -499,34 +554,19 @@ static sense_reason_t compare_and_write_callback(struct se_cmd *cmd, bool succes
 	} else if (ret)
 		goto out;
 
-	if (sg_alloc_table(&write_tbl, cmd->t_data_nents, GFP_KERNEL) < 0) {
-		pr_err("Unable to allocate compare_and_write sg\n");
-		ret = TCM_OUT_OF_RESOURCES;
+	rc = sbc_caw_build_write_sg(&write_tbl, cmd->t_data_sg,
+				    cmd->t_data_nents, compare_len,
+				    compare_len);
+	if (rc) {
+		pr_err("Unable to build compare_and_write sg\n");
+		if (rc == -ENOMEM)
+			ret = TCM_OUT_OF_RESOURCES;
+		else
+			ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
 		goto out;
 	}
 	write_sg = write_tbl.sgl;
 
-	i = 0;
-	len = compare_len;
-	sg_miter_start(&m, cmd->t_data_sg, cmd->t_data_nents, SG_MITER_TO_SG);
-	/*
-	 * Currently assumes NoLB=1 and SGLs are PAGE_SIZE..
-	 */
-	while (len) {
-		sg_miter_next(&m);
-
-		if (block_size < PAGE_SIZE) {
-			sg_set_page(&write_sg[i], m.page, block_size,
-				    m.piter.sg->offset + block_size);
-		} else {
-			sg_miter_next(&m);
-			sg_set_page(&write_sg[i], m.page, block_size,
-				    m.piter.sg->offset);
-		}
-		len -= block_size;
-		i++;
-	}
-	sg_miter_stop(&m);
 	/*
 	 * Save the original SGL + nents values before updating to new
 	 * assignments, to be released in transport_free_pages() ->
@@ -535,7 +575,7 @@ static sense_reason_t compare_and_write_callback(struct se_cmd *cmd, bool succes
 	cmd->t_data_sg_orig = cmd->t_data_sg;
 	cmd->t_data_sg = write_sg;
 	cmd->t_data_nents_orig = cmd->t_data_nents;
-	cmd->t_data_nents = 1;
+	cmd->t_data_nents = write_tbl.nents;
 
 	cmd->sam_task_attr = TCM_HEAD_TAG;
 	cmd->transport_complete_callback = compare_and_write_post;
drivers/target/target_core_transport.c +10 -1
index dcfe945949167..3cae5ed67d417 100644
@@ -22,6 +22,7 @@
 #include <linux/module.h>
 #include <linux/ratelimit.h>
 #include <linux/vmalloc.h>
+#include <linux/scatterlist.h>
 #include <linux/unaligned.h>
 #include <net/sock.h>
 #include <net/tcp.h>
@@ -2724,10 +2725,18 @@ static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
 	 * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
 	 * emulation, and free + reset pointers if necessary..
 	 */
+	struct sg_table table = { };
+
 	if (!cmd->t_data_sg_orig)
 		return;
 
-	kfree(cmd->t_data_sg);
+	/*
+	 * compare_and_write_callback() built this with sg_alloc_table().
+	 * Above SG_MAX_SINGLE_ALLOC the tail is a separate allocation.
+	 */
+	table.sgl = cmd->t_data_sg;
+	table.orig_nents = cmd->t_data_nents;
+	sg_free_table(&table);
 	cmd->t_data_sg = cmd->t_data_sg_orig;
 	cmd->t_data_sg_orig = NULL;
 	cmd->t_data_nents = cmd->t_data_nents_orig;
author
#2 lore raw

PATCH v2 2/8 scsi: target: keep REPORT REFERRALS stores inside the buffer

In reply to Jia Jia

target_emulate_report_referrals() checks only that the start of an LBA field is inside cmd->data_length before storing all eight bytes. A short response buffer can therefore make the store run past its end. For example, a nine-byte allocation reaches the LBA at buf[8].

The response builder must still visit the remaining LBA maps to compute the reported length. Encode each LBA in a local array and copy only the part that fits in the command buffer.

KASAN reports:

  BUG: KASAN: use-after-free in target_emulate_report_referrals+0x100/0x380 [target_core_mod]
  Write of size 8

target_emulate_report_referrals
__target_execute_cmd
target_execute_cmd
transport_generic_new_cmd

Fixes 38edd7245771 ("target_core_alua: check for buffer overflow")
---
 drivers/target/target_core_alua.c | 23 +++++++++++++++++++----
 1 file changed, 19 insertions(+), 4 deletions(-)
drivers/target/target_core_alua.c +19 -4
index 140154d93c430..c110914b7b78b 100644
@@ -49,6 +49,19 @@ static LIST_HEAD(lu_gps_list);
 
 struct t10_alua_lu_gp *default_lu_gp;
 
+static void
+target_emulate_report_referrals_copy_lba(unsigned char *buf, u32 off,
+					 u32 data_length, u64 lba)
+{
+	unsigned char lba_buf[sizeof(lba)];
+
+	if (off >= data_length)
+		return;
+	put_unaligned_be64(lba, lba_buf);
+	memcpy(&buf[off], lba_buf,
+	       min_t(u32, sizeof(lba_buf), data_length - off));
+}
+
 /*
  * REPORT REFERRALS
  *
@@ -88,11 +101,13 @@ target_emulate_report_referrals(struct se_cmd *cmd)
 		int pg_num;
 
 		off += 4;
-		if (cmd->data_length > off)
-			put_unaligned_be64(map->lba_map_first_lba, &buf[off]);
+		target_emulate_report_referrals_copy_lba(buf, off,
+							 cmd->data_length,
+							 map->lba_map_first_lba);
 		off += 8;
-		if (cmd->data_length > off)
-			put_unaligned_be64(map->lba_map_last_lba, &buf[off]);
+		target_emulate_report_referrals_copy_lba(buf, off,
+							 cmd->data_length,
+							 map->lba_map_last_lba);
 		off += 8;
 		rd_len += 20;
 		pg_num = 0;
author
#3 lore raw

PATCH v2 3/8 scsi: target: reject a short SET TARGET PORT GROUPS list

In reply to Jia Jia

SET TARGET PORT GROUPS has a four-byte header followed by four-byte descriptors. target_emulate_set_target_port_groups() accepts any list at least four bytes long, then walks a descriptor whenever bytes remain. A five-byte list can therefore make get_unaligned_be16() read past the parameter data.

Reject lists whose lengths are not multiples of four before walking them or changing port group state.

KASAN reports:

  BUG: KASAN: use-after-free in target_emulate_set_target_port_groups+0x1dc/0x540 [target_core_mod]
  Read of size 2

target_emulate_set_target_port_groups
__target_execute_cmd
target_execute_cmd
vhost_scsi_write_pending
transport_generic_new_cmd

Fixes c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6")
---
 drivers/target/target_core_alua.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/target/target_core_alua.c +3 -3
index c110914b7b78b..22b4c39748704 100644
@@ -298,9 +298,9 @@ target_emulate_set_target_port_groups(struct se_cmd *cmd)
 	int alua_access_state, primary = 0, valid_states;
 	u16 tg_pt_id, rtpi;
 
-	if (cmd->data_length < 4) {
-		pr_warn("SET TARGET PORT GROUPS parameter list length %u too"
-			" small\n", cmd->data_length);
+	if (cmd->data_length < 4 || (cmd->data_length & 3)) {
+		pr_warn("SET TARGET PORT GROUPS invalid list length %u\n",
+			cmd->data_length);
 		return TCM_INVALID_PARAMETER_LIST;
 	}
 
author
#4 lore raw

PATCH v2 4/8 scsi: target: copy a DIF insert tuple across prot sgs

In reply to Jia Jia

sbc_dif_generate() writes a complete eight-byte t10_pi_tuple whenever any bytes remain in a protection sg. A tuple split across entries can therefore be written past the end of the first entry.

Copy each tuple through a stack object, walking the protection sgs as needed. Read the existing tuple before updating it to preserve ref_tag for protection types other than Type 1. This also checks that the full tuple is available before writing any of it.

Stop generation on a truncated final tuple without changing the caller's completion status.

KASAN reports:

  BUG: KASAN: use-after-free in sbc_dif_generate+0x20c/0x640 [target_core_mod]
  Write of size 4

sbc_dif_generate
target_complete_ok_work

Fixes 66a3d5bc47d2 ("target/sbc: Add sbc_dif_generate software emulation")
---
 drivers/target/target_core_sbc.c | 180 ++++++++++++++++++++++---------
 1 file changed, 131 insertions(+), 49 deletions(-)
drivers/target/target_core_sbc.c +131 -49
index adef903652ac2..780f526c4d931 100644
@@ -1250,72 +1250,154 @@ err:
 	return ret;
 }
 
+/*
+ * Copy one 8 byte PI tuple to or from the prot sg.  The data page sits
+ * above the prot map, so a prot sg change drops and restores it.  A
+ * short tail releases both maps and returns false.
+ */
+static bool
+sbc_dif_prot_copy(struct scatterlist **psgp, void **paddrp,
+		  unsigned int *poffp, struct scatterlist *dsg,
+		  void **daddrp, void *buf, bool to_prot)
+{
+	struct scatterlist *psg = *psgp;
+	void *paddr = *paddrp;
+	void *daddr = *daddrp;
+	unsigned int poff = *poffp;
+	unsigned int len = sizeof(struct t10_pi_tuple);
+	u8 *p = buf;
+
+	while (len) {
+		unsigned int take;
+
+		if (!psg || poff >= psg->length) {
+			if (daddr)
+				kunmap_atomic(daddr - dsg->offset);
+			if (paddr)
+				kunmap_atomic(paddr - psg->offset);
+			daddr = NULL;
+			paddr = NULL;
+			psg = psg ? sg_next(psg) : NULL;
+			if (!psg) {
+				*psgp = NULL;
+				*paddrp = NULL;
+				*daddrp = NULL;
+				return false;
+			}
+			poff = 0;
+			if (!psg->length)
+				continue;
+			paddr = kmap_atomic(sg_page(psg)) + psg->offset;
+			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+		}
+
+		take = min_t(unsigned int, len, psg->length - poff);
+		if (to_prot)
+			memcpy(paddr + poff, p, take);
+		else
+			memcpy(p, paddr + poff, take);
+		p += take;
+		poff += take;
+		len -= take;
+	}
+
+	*psgp = psg;
+	*paddrp = paddr;
+	*poffp = poff;
+	*daddrp = daddr;
+	return true;
+}
+
 void
 sbc_dif_generate(struct se_cmd *cmd)
 {
 	struct se_device *dev = cmd->se_dev;
-	struct t10_pi_tuple *sdt;
-	struct scatterlist *dsg = cmd->t_data_sg, *psg;
+	struct scatterlist *dsg = cmd->t_data_sg;
+	struct scatterlist *psg = cmd->t_prot_sg;
 	sector_t sector = cmd->t_task_lba;
 	void *daddr, *paddr;
-	int i, j, offset = 0;
+	unsigned int poff = 0;
+	int offset = 0;
 	unsigned int block_size = dev->dev_attrib.block_size;
 
-	for_each_sg(cmd->t_prot_sg, psg, cmd->t_prot_nents, i) {
-		paddr = kmap_atomic(sg_page(psg)) + psg->offset;
-		daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+	if (!psg || !dsg)
+		return;
 
-		for (j = 0; j < psg->length;
-				j += sizeof(*sdt)) {
-			__u16 crc;
-			unsigned int avail;
+	paddr = kmap_atomic(sg_page(psg)) + psg->offset;
+	daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
 
-			if (offset >= dsg->length) {
-				offset -= dsg->length;
-				kunmap_atomic(daddr - dsg->offset);
-				dsg = sg_next(dsg);
-				if (!dsg) {
-					kunmap_atomic(paddr - psg->offset);
-					return;
-				}
-				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
-			}
+	for (;;) {
+		struct t10_pi_tuple sdt;
+		struct scatterlist *mark_psg;
+		unsigned int mark_off;
+		__u16 crc;
+		unsigned int avail;
 
-			sdt = paddr + j;
-			avail = min(block_size, dsg->length - offset);
-			crc = crc_t10dif(daddr + offset, avail);
-			if (avail < block_size) {
-				kunmap_atomic(daddr - dsg->offset);
-				dsg = sg_next(dsg);
-				if (!dsg) {
-					kunmap_atomic(paddr - psg->offset);
-					return;
-				}
-				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
-				offset = block_size - avail;
-				crc = crc_t10dif_update(crc, daddr, offset);
-			} else {
-				offset += block_size;
-			}
+		if (poff >= psg->length && !sg_next(psg))
+			break;
 
-			sdt->guard_tag = cpu_to_be16(crc);
-			if (cmd->prot_type == TARGET_DIF_TYPE1_PROT)
-				sdt->ref_tag = cpu_to_be32(sector & 0xffffffff);
-			sdt->app_tag = 0;
+		mark_psg = psg;
+		mark_off = poff;
+		if (!sbc_dif_prot_copy(&psg, &paddr, &poff, dsg, &daddr,
+				       &sdt, false))
+			return;
+
+		if (offset >= dsg->length) {
+			offset -= dsg->length;
+			kunmap_atomic(daddr - dsg->offset);
+			dsg = sg_next(dsg);
+			if (!dsg) {
+				kunmap_atomic(paddr - psg->offset);
+				return;
+			}
+			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+		}
 
-			pr_debug("DIF %s INSERT sector: %llu guard_tag: 0x%04x"
-				 " app_tag: 0x%04x ref_tag: %u\n",
-				 (cmd->data_direction == DMA_TO_DEVICE) ?
-				 "WRITE" : "READ", (unsigned long long)sector,
-				 sdt->guard_tag, sdt->app_tag,
-				 be32_to_cpu(sdt->ref_tag));
+		avail = min(block_size, dsg->length - offset);
+		crc = crc_t10dif(daddr + offset, avail);
+		if (avail < block_size) {
+			kunmap_atomic(daddr - dsg->offset);
+			dsg = sg_next(dsg);
+			if (!dsg) {
+				kunmap_atomic(paddr - psg->offset);
+				return;
+			}
+			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+			offset = block_size - avail;
+			crc = crc_t10dif_update(crc, daddr, offset);
+		} else {
+			offset += block_size;
+		}
 
-			sector++;
+		sdt.guard_tag = cpu_to_be16(crc);
+		if (cmd->prot_type == TARGET_DIF_TYPE1_PROT)
+			sdt.ref_tag = cpu_to_be32(sector & 0xffffffff);
+		sdt.app_tag = 0;
+
+		pr_debug("DIF %s INSERT sector: %llu guard_tag: 0x%04x"
+			 " app_tag: 0x%04x ref_tag: %u\n",
+			 (cmd->data_direction == DMA_TO_DEVICE) ?
+			 "WRITE" : "READ", (unsigned long long)sector,
+			 sdt.guard_tag, sdt.app_tag,
+			 be32_to_cpu(sdt.ref_tag));
+
+		if (psg != mark_psg) {
+			kunmap_atomic(daddr - dsg->offset);
+			kunmap_atomic(paddr - psg->offset);
+			psg = mark_psg;
+			paddr = kmap_atomic(sg_page(psg)) + psg->offset;
+			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
 		}
+		poff = mark_off;
+		if (!sbc_dif_prot_copy(&psg, &paddr, &poff, dsg, &daddr,
+				       &sdt, true))
+			return;
 
-		kunmap_atomic(daddr - dsg->offset);
-		kunmap_atomic(paddr - psg->offset);
+		sector++;
 	}
+
+	kunmap_atomic(daddr - dsg->offset);
+	kunmap_atomic(paddr - psg->offset);
 }
 
 static sense_reason_t
author
#5 lore raw

PATCH v2 5/8 scsi: target: copy a DIF verify tuple across prot sgs

In reply to Jia Jia

sbc_dif_verify() enters its loop when any byte remains in a protection sg, then accesses a complete eight-byte t10_pi_tuple. A tuple split across entries can therefore be read past the end of the current sg.

Use the tuple-copy helper to assemble a complete tuple before checking it. If the protection list ends partway through a tuple, return a guard-check failure. Keep the data-cursor adjustment ahead of the escape check so consecutive escaped blocks still advance the cursor.

KASAN reports:

  BUG: KASAN: use-after-free in sbc_dif_verify+0x5ab/0x790 [target_core_mod]
  Read of size 4

sbc_dif_verify
target_execute_cmd
vhost_scsi_write_pending
transport_generic_new_cmd

Fixes 41861fa831af ("target/sbc: Add DIF TYPE1+TYPE3 read/write verify emulation")
---
 drivers/target/target_core_sbc.c | 112 ++++++++++++++++---------------
 1 file changed, 58 insertions(+), 54 deletions(-)
drivers/target/target_core_sbc.c +58 -54
index 780f526c4d931..360a9af0cf66f 100644
@@ -1491,81 +1491,85 @@ sbc_dif_verify(struct se_cmd *cmd, sector_t start, unsigned int sectors,
 	       unsigned int ei_lba, struct scatterlist *psg, int psg_off)
 {
 	struct se_device *dev = cmd->se_dev;
-	struct t10_pi_tuple *sdt;
 	struct scatterlist *dsg = cmd->t_data_sg;
 	sector_t sector = start;
 	void *daddr, *paddr;
-	int i;
 	sense_reason_t rc;
+	unsigned int poff = psg_off;
 	int dsg_off = 0;
 	unsigned int block_size = dev->dev_attrib.block_size;
 
-	for (; psg && sector < start + sectors; psg = sg_next(psg)) {
-		paddr = kmap_atomic(sg_page(psg)) + psg->offset;
-		daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+	if (!psg || !dsg)
+		return 0;
 
-		for (i = psg_off; i < psg->length &&
-				sector < start + sectors;
-				i += sizeof(*sdt)) {
-			__u16 crc;
-			unsigned int avail;
+	paddr = kmap_atomic(sg_page(psg)) + psg->offset;
+	daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
 
-			if (dsg_off >= dsg->length) {
-				dsg_off -= dsg->length;
-				kunmap_atomic(daddr - dsg->offset);
-				dsg = sg_next(dsg);
-				if (!dsg) {
-					kunmap_atomic(paddr - psg->offset);
-					return 0;
-				}
-				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
-			}
+	while (sector < start + sectors) {
+		struct t10_pi_tuple sdt;
+		__u16 crc;
+		unsigned int avail;
 
-			sdt = paddr + i;
+		if (poff >= psg->length && !sg_next(psg))
+			break;
 
-			pr_debug("DIF READ sector: %llu guard_tag: 0x%04x"
-				 " app_tag: 0x%04x ref_tag: %u\n",
-				 (unsigned long long)sector, sdt->guard_tag,
-				 sdt->app_tag, be32_to_cpu(sdt->ref_tag));
+		if (!sbc_dif_prot_copy(&psg, &paddr, &poff, dsg, &daddr,
+				       &sdt, false)) {
+			cmd->sense_info = sector;
+			return TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED;
+		}
 
-			if (sdt->app_tag == T10_PI_APP_ESCAPE) {
-				dsg_off += block_size;
-				goto next;
+		if (dsg_off >= dsg->length) {
+			dsg_off -= dsg->length;
+			kunmap_atomic(daddr - dsg->offset);
+			dsg = sg_next(dsg);
+			if (!dsg) {
+				kunmap_atomic(paddr - psg->offset);
+				return 0;
 			}
+			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+		}
 
-			avail = min(block_size, dsg->length - dsg_off);
-			crc = crc_t10dif(daddr + dsg_off, avail);
-			if (avail < block_size) {
-				kunmap_atomic(daddr - dsg->offset);
-				dsg = sg_next(dsg);
-				if (!dsg) {
-					kunmap_atomic(paddr - psg->offset);
-					return 0;
-				}
-				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
-				dsg_off = block_size - avail;
-				crc = crc_t10dif_update(crc, daddr, dsg_off);
-			} else {
-				dsg_off += block_size;
-			}
+		pr_debug("DIF READ sector: %llu guard_tag: 0x%04x"
+			 " app_tag: 0x%04x ref_tag: %u\n",
+			 (unsigned long long)sector, sdt.guard_tag,
+			 sdt.app_tag, be32_to_cpu(sdt.ref_tag));
 
-			rc = sbc_dif_v1_verify(cmd, sdt, crc, sector, ei_lba);
-			if (rc) {
-				kunmap_atomic(daddr - dsg->offset);
+		if (sdt.app_tag == T10_PI_APP_ESCAPE) {
+			dsg_off += block_size;
+			goto next;
+		}
+
+		avail = min(block_size, dsg->length - dsg_off);
+		crc = crc_t10dif(daddr + dsg_off, avail);
+		if (avail < block_size) {
+			kunmap_atomic(daddr - dsg->offset);
+			dsg = sg_next(dsg);
+			if (!dsg) {
 				kunmap_atomic(paddr - psg->offset);
-				cmd->sense_info = sector;
-				return rc;
+				return 0;
 			}
-next:
-			sector++;
-			ei_lba++;
+			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+			dsg_off = block_size - avail;
+			crc = crc_t10dif_update(crc, daddr, dsg_off);
+		} else {
+			dsg_off += block_size;
 		}
 
-		psg_off = 0;
-		kunmap_atomic(daddr - dsg->offset);
-		kunmap_atomic(paddr - psg->offset);
+		rc = sbc_dif_v1_verify(cmd, &sdt, crc, sector, ei_lba);
+		if (rc) {
+			kunmap_atomic(daddr - dsg->offset);
+			kunmap_atomic(paddr - psg->offset);
+			cmd->sense_info = sector;
+			return rc;
+		}
+next:
+		sector++;
+		ei_lba++;
 	}
 
+	kunmap_atomic(daddr - dsg->offset);
+	kunmap_atomic(paddr - psg->offset);
 	return 0;
 }
 EXPORT_SYMBOL(sbc_dif_verify);
author
#6 lore raw

PATCH v2 6/8 scsi: target: limit DIF block CRC to each data sg

In reply to Jia Jia

sbc_dif_generate() and sbc_dif_verify() start a CRC from the current data sg and handle one transition to the following entry. They pass all remaining block bytes to crc_t10dif_update(), even if the next sg is shorter than that remainder.

A 512-byte block split into 256, 100 and 156 bytes makes the CRC read 256 bytes from the 100-byte entry. Walk the remaining entries and limit each CRC update to the bytes that entry holds. Share the walk between the generation and verification paths.

KASAN reports:

  BUG: KASAN: use-after-free in crc_t10dif_update+0x91/0xf0
  Read of size 1

crc_t10dif_update
sbc_dif_verify
target_execute_cmd
vhost_scsi_write_pending
transport_generic_new_cmd

Fixes 18213afbd8ce ("target: handle odd SG mapping for data transfer memory")
---
 drivers/target/target_core_sbc.c | 54 +++++++++++++++++++++++++-------
 1 file changed, 42 insertions(+), 12 deletions(-)
drivers/target/target_core_sbc.c +42 -12
index 360a9af0cf66f..e752b23b1bef7 100644
@@ -1308,6 +1308,44 @@ sbc_dif_prot_copy(struct scatterlist **psgp, void **paddrp,
 	return true;
 }
 
+/*
+ * CRC the rest of one logical block.  @need is the byte count still
+ * unread.  Take only what each following data sg holds.
+ */
+static bool
+sbc_dif_crc_rest(struct scatterlist **dsgp, void **daddrp, int *offp,
+		 unsigned int need, __u16 *crc)
+{
+	struct scatterlist *dsg = *dsgp;
+	void *daddr = *daddrp;
+
+	kunmap_atomic(daddr - dsg->offset);
+	while (need) {
+		unsigned int take;
+
+		dsg = sg_next(dsg);
+		if (!dsg)
+			return false;
+
+		daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
+		if (!dsg->length) {
+			kunmap_atomic(daddr - dsg->offset);
+			return false;
+		}
+
+		take = min_t(unsigned int, need, dsg->length);
+		*crc = crc_t10dif_update(*crc, daddr, take);
+		need -= take;
+		*offp = take;
+		if (need)
+			kunmap_atomic(daddr - dsg->offset);
+	}
+
+	*dsgp = dsg;
+	*daddrp = daddr;
+	return true;
+}
+
 void
 sbc_dif_generate(struct se_cmd *cmd)
 {
@@ -1356,15 +1394,11 @@ sbc_dif_generate(struct se_cmd *cmd)
 		avail = min(block_size, dsg->length - offset);
 		crc = crc_t10dif(daddr + offset, avail);
 		if (avail < block_size) {
-			kunmap_atomic(daddr - dsg->offset);
-			dsg = sg_next(dsg);
-			if (!dsg) {
+			if (!sbc_dif_crc_rest(&dsg, &daddr, &offset,
+					      block_size - avail, &crc)) {
 				kunmap_atomic(paddr - psg->offset);
 				return;
 			}
-			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
-			offset = block_size - avail;
-			crc = crc_t10dif_update(crc, daddr, offset);
 		} else {
 			offset += block_size;
 		}
@@ -1543,15 +1577,11 @@ sbc_dif_verify(struct se_cmd *cmd, sector_t start, unsigned int sectors,
 		avail = min(block_size, dsg->length - dsg_off);
 		crc = crc_t10dif(daddr + dsg_off, avail);
 		if (avail < block_size) {
-			kunmap_atomic(daddr - dsg->offset);
-			dsg = sg_next(dsg);
-			if (!dsg) {
+			if (!sbc_dif_crc_rest(&dsg, &daddr, &dsg_off,
+					      block_size - avail, &crc)) {
 				kunmap_atomic(paddr - psg->offset);
 				return 0;
 			}
-			daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
-			dsg_off = block_size - avail;
-			crc = crc_t10dif_update(crc, daddr, dsg_off);
 		} else {
 			dsg_off += block_size;
 		}
author
#7 lore raw

PATCH v2 7/8 scsi: target: keep pscsi mode bytes inside the data sgs

In reply to Jia Jia

pscsi_complete_cmd() updates the write-protect byte without checking that the response is long enough to contain it. MODE SENSE (6) needs byte 2 and MODE SENSE (10) needs byte 3. A shorter allocation can make the access run past the command buffer.

On tape devices, MODE SELECT reads the block descriptor through sg_virt() of the first sg. The block length ends at byte 11 for MODE SELECT (6) and byte 15 for MODE SELECT (10), but neither the command length nor the first sg's length is checked.

Use the sg copy helpers to access the write-protect byte and copy the required MODE SELECT prefix into a local buffer. Check both the command length and the number of bytes copied before using the fields. This also handles headers and descriptors split across sg entries.

Fixes c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6")
---
 drivers/target/target_core_pscsi.c | 37 ++++++++++++++----------------
 1 file changed, 17 insertions(+), 20 deletions(-)
drivers/target/target_core_pscsi.c +17 -20
index fd1b82fc72902..ccf5933da7f0d 100644
@@ -21,6 +21,7 @@
 #include <linux/ratelimit.h>
 #include <linux/module.h>
 #include <linux/unaligned.h>
+#include <linux/scatterlist.h>
 
 #include <scsi/scsi_device.h>
 #include <scsi/scsi_host.h>
@@ -610,21 +611,17 @@ static void pscsi_complete_cmd(struct se_cmd *cmd, u8 scsi_status,
 		bool read_only = target_lun_is_rdonly(cmd);
 
 		if (read_only) {
-			unsigned char *buf;
-
-			buf = transport_kmap_data_sg(cmd);
-			if (!buf) {
-				; /* XXX: TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE */
-			} else {
-				if (cdb[0] == MODE_SENSE_10) {
-					if (!(buf[3] & 0x80))
-						buf[3] |= 0x80;
-				} else {
-					if (!(buf[2] & 0x80))
-						buf[2] |= 0x80;
-				}
-
-				transport_kunmap_data_sg(cmd);
+			unsigned char wp;
+			unsigned int wp_off = (cdb[0] == MODE_SENSE_10) ? 3 : 2;
+
+			if (cmd->data_length > wp_off && cmd->t_data_sg &&
+			    sg_pcopy_to_buffer(cmd->t_data_sg, cmd->t_data_nents,
+					       &wp, 1, wp_off) == 1 &&
+			    !(wp & 0x80)) {
+				wp |= 0x80;
+				sg_pcopy_from_buffer(cmd->t_data_sg,
+						     cmd->t_data_nents, &wp, 1,
+						     wp_off);
 			}
 		}
 	}
@@ -643,15 +640,15 @@ after_mode_sense:
 	 */
 	if (((cdb[0] == MODE_SELECT) || (cdb[0] == MODE_SELECT_10)) &&
 	     scsi_status == SAM_STAT_GOOD) {
-		unsigned char *buf;
+		unsigned char buf[16];
+		unsigned int len = cdb[0] == MODE_SELECT ? 12 : 16;
 		u16 bdl;
 		u32 blocksize;
 
-		buf = sg_virt(&cmd->t_data_sg[0]);
-		if (!buf) {
-			pr_err("Unable to get buf for scatterlist\n");
+		if (cmd->data_length < len || !cmd->t_data_sg ||
+		    sg_copy_to_buffer(cmd->t_data_sg, cmd->t_data_nents,
+				      buf, len) != len)
 			goto after_mode_select;
-		}
 
 		if (cdb[0] == MODE_SELECT)
 			bdl = buf[3];
author
#8 lore raw

PATCH v2 8/8 scsi: target: advance past escaped DIF blocks across data sgs

In reply to Jia Jia

An escaped protection tuple advances dsg_off by one logical block. sbc_dif_verify() adjusts the cursor across only one data sg on the next iteration. When the skipped block spans several short entries, the offset can still exceed the next sg's length and the following CRC reads beyond that entry.

Advance through data sgs until the offset is within the current entry before checking the next block.

KASAN reports:

  BUG: KASAN: use-after-free in crc_t10dif_update+0x91/0xf0
  Read of size 1

crc_t10dif_update
sbc_dif_verify
target_execute_cmd
vhost_scsi_write_pending
transport_generic_new_cmd

Fixes 18213afbd8ce ("target: handle odd SG mapping for data transfer memory")
---
 drivers/target/target_core_sbc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/target/target_core_sbc.c +1 -1
index e752b23b1bef7..671427d9ae74a 100644
@@ -1553,7 +1553,7 @@ sbc_dif_verify(struct se_cmd *cmd, sector_t start, unsigned int sectors,
 			return TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED;
 		}
 
-		if (dsg_off >= dsg->length) {
+		while (dsg_off >= dsg->length) {
 			dsg_off -= dsg->length;
 			kunmap_atomic(daddr - dsg->offset);
 			dsg = sg_next(dsg);