[PATCH v2 7/8] scsi: target: keep pscsi mode bytes inside the data sgs
From: Jia Jia
Date: Tue Nov 17 2026 - 23:15:03 EST
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")
Signed-off-by: Jia Jia <physicalmtea@xxxxxxxxx>
---
drivers/target/target_core_pscsi.c | 37 ++++++++++++++----------------
1 file changed, 17 insertions(+), 20 deletions(-)
diff --git a/drivers/target/target_core_pscsi.c b/drivers/target/target_core_pscsi.c
index fd1b82fc72902..ccf5933da7f0d 100644
--- a/drivers/target/target_core_pscsi.c
+++ b/drivers/target/target_core_pscsi.c
@@ -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];