1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * SCSI Block Commands (SBC) parsing and emulation.
4  *
5  * (c) Copyright 2002-2013 Datera, Inc.
6  *
7  * Nicholas A. Bellinger <nab@kernel.org>
8  */
9 
10 #include <linux/kernel.h>
11 #include <linux/module.h>
12 #include <linux/ratelimit.h>
13 #include <linux/crc-t10dif.h>
14 #include <linux/t10-pi.h>
15 #include <asm/unaligned.h>
16 #include <scsi/scsi_proto.h>
17 #include <scsi/scsi_tcq.h>
18 
19 #include <target/target_core_base.h>
20 #include <target/target_core_backend.h>
21 #include <target/target_core_fabric.h>
22 
23 #include "target_core_internal.h"
24 #include "target_core_ua.h"
25 #include "target_core_alua.h"
26 
27 static sense_reason_t
28 sbc_check_prot(struct se_device *, struct se_cmd *, unsigned char, u32, bool);
29 static sense_reason_t sbc_execute_unmap(struct se_cmd *cmd);
30 
31 static sense_reason_t
32 sbc_emulate_readcapacity(struct se_cmd *cmd)
33 {
34 	struct se_device *dev = cmd->se_dev;
35 	unsigned char *cdb = cmd->t_task_cdb;
36 	unsigned long long blocks_long = dev->transport->get_blocks(dev);
37 	unsigned char *rbuf;
38 	unsigned char buf[8];
39 	u32 blocks;
40 
41 	/*
42 	 * SBC-2 says:
43 	 *   If the PMI bit is set to zero and the LOGICAL BLOCK
44 	 *   ADDRESS field is not set to zero, the device server shall
45 	 *   terminate the command with CHECK CONDITION status with
46 	 *   the sense key set to ILLEGAL REQUEST and the additional
47 	 *   sense code set to INVALID FIELD IN CDB.
48 	 *
49 	 * In SBC-3, these fields are obsolete, but some SCSI
50 	 * compliance tests actually check this, so we might as well
51 	 * follow SBC-2.
52 	 */
53 	if (!(cdb[8] & 1) && !!(cdb[2] | cdb[3] | cdb[4] | cdb[5]))
54 		return TCM_INVALID_CDB_FIELD;
55 
56 	if (blocks_long >= 0x00000000ffffffff)
57 		blocks = 0xffffffff;
58 	else
59 		blocks = (u32)blocks_long;
60 
61 	put_unaligned_be32(blocks, &buf[0]);
62 	put_unaligned_be32(dev->dev_attrib.block_size, &buf[4]);
63 
64 	rbuf = transport_kmap_data_sg(cmd);
65 	if (rbuf) {
66 		memcpy(rbuf, buf, min_t(u32, sizeof(buf), cmd->data_length));
67 		transport_kunmap_data_sg(cmd);
68 	}
69 
70 	target_complete_cmd_with_length(cmd, SAM_STAT_GOOD, 8);
71 	return 0;
72 }
73 
74 static sense_reason_t
75 sbc_emulate_readcapacity_16(struct se_cmd *cmd)
76 {
77 	struct se_device *dev = cmd->se_dev;
78 	struct se_session *sess = cmd->se_sess;
79 	int pi_prot_type = dev->dev_attrib.pi_prot_type;
80 
81 	unsigned char *rbuf;
82 	unsigned char buf[32];
83 	unsigned long long blocks = dev->transport->get_blocks(dev);
84 
85 	memset(buf, 0, sizeof(buf));
86 	put_unaligned_be64(blocks, &buf[0]);
87 	put_unaligned_be32(dev->dev_attrib.block_size, &buf[8]);
88 	/*
89 	 * Set P_TYPE and PROT_EN bits for DIF support
90 	 */
91 	if (sess->sup_prot_ops & (TARGET_PROT_DIN_PASS | TARGET_PROT_DOUT_PASS)) {
92 		/*
93 		 * Only override a device's pi_prot_type if no T10-PI is
94 		 * available, and sess_prot_type has been explicitly enabled.
95 		 */
96 		if (!pi_prot_type)
97 			pi_prot_type = sess->sess_prot_type;
98 
99 		if (pi_prot_type)
100 			buf[12] = (pi_prot_type - 1) << 1 | 0x1;
101 	}
102 
103 	if (dev->transport->get_lbppbe)
104 		buf[13] = dev->transport->get_lbppbe(dev) & 0x0f;
105 
106 	if (dev->transport->get_alignment_offset_lbas) {
107 		u16 lalba = dev->transport->get_alignment_offset_lbas(dev);
108 
109 		put_unaligned_be16(lalba, &buf[14]);
110 	}
111 
112 	/*
113 	 * Set Thin Provisioning Enable bit following sbc3r22 in section
114 	 * READ CAPACITY (16) byte 14 if emulate_tpu or emulate_tpws is enabled.
115 	 */
116 	if (dev->dev_attrib.emulate_tpu || dev->dev_attrib.emulate_tpws) {
117 		buf[14] |= 0x80;
118 
119 		/*
120 		 * LBPRZ signifies that zeroes will be read back from an LBA after
121 		 * an UNMAP or WRITE SAME w/ unmap bit (sbc3r36 5.16.2)
122 		 */
123 		if (dev->dev_attrib.unmap_zeroes_data)
124 			buf[14] |= 0x40;
125 	}
126 
127 	rbuf = transport_kmap_data_sg(cmd);
128 	if (rbuf) {
129 		memcpy(rbuf, buf, min_t(u32, sizeof(buf), cmd->data_length));
130 		transport_kunmap_data_sg(cmd);
131 	}
132 
133 	target_complete_cmd_with_length(cmd, SAM_STAT_GOOD, 32);
134 	return 0;
135 }
136 
137 static sense_reason_t
138 sbc_emulate_startstop(struct se_cmd *cmd)
139 {
140 	unsigned char *cdb = cmd->t_task_cdb;
141 
142 	/*
143 	 * See sbc3r36 section 5.25
144 	 * Immediate bit should be set since there is nothing to complete
145 	 * POWER CONDITION MODIFIER 0h
146 	 */
147 	if (!(cdb[1] & 1) || cdb[2] || cdb[3])
148 		return TCM_INVALID_CDB_FIELD;
149 
150 	/*
151 	 * See sbc3r36 section 5.25
152 	 * POWER CONDITION 0h START_VALID - process START and LOEJ
153 	 */
154 	if (cdb[4] >> 4 & 0xf)
155 		return TCM_INVALID_CDB_FIELD;
156 
157 	/*
158 	 * See sbc3r36 section 5.25
159 	 * LOEJ 0h - nothing to load or unload
160 	 * START 1h - we are ready
161 	 */
162 	if (!(cdb[4] & 1) || (cdb[4] & 2) || (cdb[4] & 4))
163 		return TCM_INVALID_CDB_FIELD;
164 
165 	target_complete_cmd(cmd, SAM_STAT_GOOD);
166 	return 0;
167 }
168 
169 sector_t sbc_get_write_same_sectors(struct se_cmd *cmd)
170 {
171 	u32 num_blocks;
172 
173 	if (cmd->t_task_cdb[0] == WRITE_SAME)
174 		num_blocks = get_unaligned_be16(&cmd->t_task_cdb[7]);
175 	else if (cmd->t_task_cdb[0] == WRITE_SAME_16)
176 		num_blocks = get_unaligned_be32(&cmd->t_task_cdb[10]);
177 	else /* WRITE_SAME_32 via VARIABLE_LENGTH_CMD */
178 		num_blocks = get_unaligned_be32(&cmd->t_task_cdb[28]);
179 
180 	/*
181 	 * Use the explicit range when non zero is supplied, otherwise calculate
182 	 * the remaining range based on ->get_blocks() - starting LBA.
183 	 */
184 	if (num_blocks)
185 		return num_blocks;
186 
187 	return cmd->se_dev->transport->get_blocks(cmd->se_dev) -
188 		cmd->t_task_lba + 1;
189 }
190 EXPORT_SYMBOL(sbc_get_write_same_sectors);
191 
192 static sense_reason_t
193 sbc_execute_write_same_unmap(struct se_cmd *cmd)
194 {
195 	struct sbc_ops *ops = cmd->protocol_data;
196 	sector_t nolb = sbc_get_write_same_sectors(cmd);
197 	sense_reason_t ret;
198 
199 	if (nolb) {
200 		ret = ops->execute_unmap(cmd, cmd->t_task_lba, nolb);
201 		if (ret)
202 			return ret;
203 	}
204 
205 	target_complete_cmd(cmd, SAM_STAT_GOOD);
206 	return 0;
207 }
208 
209 static sense_reason_t
210 sbc_emulate_noop(struct se_cmd *cmd)
211 {
212 	target_complete_cmd(cmd, SAM_STAT_GOOD);
213 	return 0;
214 }
215 
216 static inline u32 sbc_get_size(struct se_cmd *cmd, u32 sectors)
217 {
218 	return cmd->se_dev->dev_attrib.block_size * sectors;
219 }
220 
221 static inline u32 transport_get_sectors_6(unsigned char *cdb)
222 {
223 	/*
224 	 * Use 8-bit sector value.  SBC-3 says:
225 	 *
226 	 *   A TRANSFER LENGTH field set to zero specifies that 256
227 	 *   logical blocks shall be written.  Any other value
228 	 *   specifies the number of logical blocks that shall be
229 	 *   written.
230 	 */
231 	return cdb[4] ? : 256;
232 }
233 
234 static inline u32 transport_get_sectors_10(unsigned char *cdb)
235 {
236 	return get_unaligned_be16(&cdb[7]);
237 }
238 
239 static inline u32 transport_get_sectors_12(unsigned char *cdb)
240 {
241 	return get_unaligned_be32(&cdb[6]);
242 }
243 
244 static inline u32 transport_get_sectors_16(unsigned char *cdb)
245 {
246 	return get_unaligned_be32(&cdb[10]);
247 }
248 
249 /*
250  * Used for VARIABLE_LENGTH_CDB WRITE_32 and READ_32 variants
251  */
252 static inline u32 transport_get_sectors_32(unsigned char *cdb)
253 {
254 	return get_unaligned_be32(&cdb[28]);
255 
256 }
257 
258 static inline u32 transport_lba_21(unsigned char *cdb)
259 {
260 	return get_unaligned_be24(&cdb[1]) & 0x1fffff;
261 }
262 
263 static inline u32 transport_lba_32(unsigned char *cdb)
264 {
265 	return get_unaligned_be32(&cdb[2]);
266 }
267 
268 static inline unsigned long long transport_lba_64(unsigned char *cdb)
269 {
270 	return get_unaligned_be64(&cdb[2]);
271 }
272 
273 static sense_reason_t
274 sbc_setup_write_same(struct se_cmd *cmd, unsigned char flags, struct sbc_ops *ops)
275 {
276 	struct se_device *dev = cmd->se_dev;
277 	sector_t end_lba = dev->transport->get_blocks(dev) + 1;
278 	unsigned int sectors = sbc_get_write_same_sectors(cmd);
279 	sense_reason_t ret;
280 
281 	if ((flags & 0x04) || (flags & 0x02)) {
282 		pr_err("WRITE_SAME PBDATA and LBDATA"
283 			" bits not supported for Block Discard"
284 			" Emulation\n");
285 		return TCM_UNSUPPORTED_SCSI_OPCODE;
286 	}
287 	if (sectors > cmd->se_dev->dev_attrib.max_write_same_len) {
288 		pr_warn("WRITE_SAME sectors: %u exceeds max_write_same_len: %u\n",
289 			sectors, cmd->se_dev->dev_attrib.max_write_same_len);
290 		return TCM_INVALID_CDB_FIELD;
291 	}
292 	/*
293 	 * Sanity check for LBA wrap and request past end of device.
294 	 */
295 	if (((cmd->t_task_lba + sectors) < cmd->t_task_lba) ||
296 	    ((cmd->t_task_lba + sectors) > end_lba)) {
297 		pr_err("WRITE_SAME exceeds last lba %llu (lba %llu, sectors %u)\n",
298 		       (unsigned long long)end_lba, cmd->t_task_lba, sectors);
299 		return TCM_ADDRESS_OUT_OF_RANGE;
300 	}
301 
302 	/* We always have ANC_SUP == 0 so setting ANCHOR is always an error */
303 	if (flags & 0x10) {
304 		pr_warn("WRITE SAME with ANCHOR not supported\n");
305 		return TCM_INVALID_CDB_FIELD;
306 	}
307 
308 	if (flags & 0x01) {
309 		pr_warn("WRITE SAME with NDOB not supported\n");
310 		return TCM_INVALID_CDB_FIELD;
311 	}
312 
313 	/*
314 	 * Special case for WRITE_SAME w/ UNMAP=1 that ends up getting
315 	 * translated into block discard requests within backend code.
316 	 */
317 	if (flags & 0x08) {
318 		if (!ops->execute_unmap)
319 			return TCM_UNSUPPORTED_SCSI_OPCODE;
320 
321 		if (!dev->dev_attrib.emulate_tpws) {
322 			pr_err("Got WRITE_SAME w/ UNMAP=1, but backend device"
323 			       " has emulate_tpws disabled\n");
324 			return TCM_UNSUPPORTED_SCSI_OPCODE;
325 		}
326 		cmd->execute_cmd = sbc_execute_write_same_unmap;
327 		return 0;
328 	}
329 	if (!ops->execute_write_same)
330 		return TCM_UNSUPPORTED_SCSI_OPCODE;
331 
332 	ret = sbc_check_prot(dev, cmd, flags >> 5, sectors, true);
333 	if (ret)
334 		return ret;
335 
336 	cmd->execute_cmd = ops->execute_write_same;
337 	return 0;
338 }
339 
340 static sense_reason_t
341 sbc_execute_rw(struct se_cmd *cmd)
342 {
343 	struct sbc_ops *ops = cmd->protocol_data;
344 
345 	return ops->execute_rw(cmd, cmd->t_data_sg, cmd->t_data_nents,
346 			       cmd->data_direction);
347 }
348 
349 static sense_reason_t compare_and_write_post(struct se_cmd *cmd, bool success,
350 					     int *post_ret)
351 {
352 	struct se_device *dev = cmd->se_dev;
353 	sense_reason_t ret = TCM_NO_SENSE;
354 
355 	spin_lock_irq(&cmd->t_state_lock);
356 	if (success) {
357 		*post_ret = 1;
358 
359 		if (cmd->scsi_status == SAM_STAT_CHECK_CONDITION)
360 			ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
361 	}
362 	spin_unlock_irq(&cmd->t_state_lock);
363 
364 	/*
365 	 * Unlock ->caw_sem originally obtained during sbc_compare_and_write()
366 	 * before the original READ I/O submission.
367 	 */
368 	up(&dev->caw_sem);
369 
370 	return ret;
371 }
372 
373 /*
374  * compare @cmp_len bytes of @read_sgl with @cmp_sgl. On miscompare, fill
375  * @miscmp_off and return TCM_MISCOMPARE_VERIFY.
376  */
377 static sense_reason_t
378 compare_and_write_do_cmp(struct scatterlist *read_sgl, unsigned int read_nents,
379 			 struct scatterlist *cmp_sgl, unsigned int cmp_nents,
380 			 unsigned int cmp_len, unsigned int *miscmp_off)
381 {
382 	unsigned char *buf = NULL;
383 	struct scatterlist *sg;
384 	sense_reason_t ret;
385 	unsigned int offset;
386 	size_t rc;
387 	int sg_cnt;
388 
389 	buf = kzalloc(cmp_len, GFP_KERNEL);
390 	if (!buf) {
391 		ret = TCM_OUT_OF_RESOURCES;
392 		goto out;
393 	}
394 
395 	rc = sg_copy_to_buffer(cmp_sgl, cmp_nents, buf, cmp_len);
396 	if (!rc) {
397 		pr_err("sg_copy_to_buffer() failed for compare_and_write\n");
398 		ret = TCM_OUT_OF_RESOURCES;
399 		goto out;
400 	}
401 	/*
402 	 * Compare SCSI READ payload against verify payload
403 	 */
404 	offset = 0;
405 	ret = TCM_NO_SENSE;
406 	for_each_sg(read_sgl, sg, read_nents, sg_cnt) {
407 		unsigned int len = min(sg->length, cmp_len);
408 		unsigned char *addr = kmap_atomic(sg_page(sg));
409 
410 		if (memcmp(addr, buf + offset, len)) {
411 			unsigned int i;
412 
413 			for (i = 0; i < len && addr[i] == buf[offset + i]; i++)
414 				;
415 			*miscmp_off = offset + i;
416 			pr_warn("Detected MISCOMPARE at offset %u\n",
417 				*miscmp_off);
418 			ret = TCM_MISCOMPARE_VERIFY;
419 		}
420 		kunmap_atomic(addr);
421 		if (ret != TCM_NO_SENSE)
422 			goto out;
423 
424 		offset += len;
425 		cmp_len -= len;
426 		if (!cmp_len)
427 			break;
428 	}
429 	pr_debug("COMPARE AND WRITE read data matches compare data\n");
430 out:
431 	kfree(buf);
432 	return ret;
433 }
434 
435 static sense_reason_t compare_and_write_callback(struct se_cmd *cmd, bool success,
436 						 int *post_ret)
437 {
438 	struct se_device *dev = cmd->se_dev;
439 	struct sg_table write_tbl = { };
440 	struct scatterlist *write_sg;
441 	struct sg_mapping_iter m;
442 	unsigned int len;
443 	unsigned int block_size = dev->dev_attrib.block_size;
444 	unsigned int compare_len = (cmd->t_task_nolb * block_size);
445 	unsigned int miscmp_off = 0;
446 	sense_reason_t ret = TCM_NO_SENSE;
447 	int i;
448 
449 	if (!success) {
450 		/*
451 		 * Handle early failure in transport_generic_request_failure(),
452 		 * which will not have taken ->caw_sem yet..
453 		 */
454 		if (!cmd->t_data_sg || !cmd->t_bidi_data_sg)
455 			return TCM_NO_SENSE;
456 
457 		/*
458 		 * The command has been stopped or aborted so
459 		 * we don't have to perform the write operation.
460 		 */
461 		WARN_ON(!(cmd->transport_state &
462 			(CMD_T_ABORTED | CMD_T_STOP)));
463 		goto out;
464 	}
465 	/*
466 	 * Handle special case for zero-length COMPARE_AND_WRITE
467 	 */
468 	if (!cmd->data_length)
469 		goto out;
470 	/*
471 	 * Immediately exit + release dev->caw_sem if command has already
472 	 * been failed with a non-zero SCSI status.
473 	 */
474 	if (cmd->scsi_status) {
475 		pr_debug("compare_and_write_callback: non zero scsi_status:"
476 			" 0x%02x\n", cmd->scsi_status);
477 		*post_ret = 1;
478 		if (cmd->scsi_status == SAM_STAT_CHECK_CONDITION)
479 			ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
480 		goto out;
481 	}
482 
483 	ret = compare_and_write_do_cmp(cmd->t_bidi_data_sg,
484 				       cmd->t_bidi_data_nents,
485 				       cmd->t_data_sg,
486 				       cmd->t_data_nents,
487 				       compare_len,
488 				       &miscmp_off);
489 	if (ret == TCM_MISCOMPARE_VERIFY) {
490 		/*
491 		 * SBC-4 r15: 5.3 COMPARE AND WRITE command
492 		 * In the sense data (see 4.18 and SPC-5) the offset from the
493 		 * start of the Data-Out Buffer to the first byte of data that
494 		 * was not equal shall be reported in the INFORMATION field.
495 		 */
496 		cmd->sense_info = miscmp_off;
497 		goto out;
498 	} else if (ret)
499 		goto out;
500 
501 	if (sg_alloc_table(&write_tbl, cmd->t_data_nents, GFP_KERNEL) < 0) {
502 		pr_err("Unable to allocate compare_and_write sg\n");
503 		ret = TCM_OUT_OF_RESOURCES;
504 		goto out;
505 	}
506 	write_sg = write_tbl.sgl;
507 
508 	i = 0;
509 	len = compare_len;
510 	sg_miter_start(&m, cmd->t_data_sg, cmd->t_data_nents, SG_MITER_TO_SG);
511 	/*
512 	 * Currently assumes NoLB=1 and SGLs are PAGE_SIZE..
513 	 */
514 	while (len) {
515 		sg_miter_next(&m);
516 
517 		if (block_size < PAGE_SIZE) {
518 			sg_set_page(&write_sg[i], m.page, block_size,
519 				    m.piter.sg->offset + block_size);
520 		} else {
521 			sg_miter_next(&m);
522 			sg_set_page(&write_sg[i], m.page, block_size,
523 				    m.piter.sg->offset);
524 		}
525 		len -= block_size;
526 		i++;
527 	}
528 	sg_miter_stop(&m);
529 	/*
530 	 * Save the original SGL + nents values before updating to new
531 	 * assignments, to be released in transport_free_pages() ->
532 	 * transport_reset_sgl_orig()
533 	 */
534 	cmd->t_data_sg_orig = cmd->t_data_sg;
535 	cmd->t_data_sg = write_sg;
536 	cmd->t_data_nents_orig = cmd->t_data_nents;
537 	cmd->t_data_nents = 1;
538 
539 	cmd->sam_task_attr = TCM_HEAD_TAG;
540 	cmd->transport_complete_callback = compare_and_write_post;
541 	/*
542 	 * Now reset ->execute_cmd() to the normal sbc_execute_rw() handler
543 	 * for submitting the adjusted SGL to write instance user-data.
544 	 */
545 	cmd->execute_cmd = sbc_execute_rw;
546 
547 	spin_lock_irq(&cmd->t_state_lock);
548 	cmd->t_state = TRANSPORT_PROCESSING;
549 	cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
550 	spin_unlock_irq(&cmd->t_state_lock);
551 
552 	__target_execute_cmd(cmd, false);
553 
554 	return ret;
555 
556 out:
557 	/*
558 	 * In the MISCOMPARE or failure case, unlock ->caw_sem obtained in
559 	 * sbc_compare_and_write() before the original READ I/O submission.
560 	 */
561 	up(&dev->caw_sem);
562 	sg_free_table(&write_tbl);
563 	return ret;
564 }
565 
566 static sense_reason_t
567 sbc_compare_and_write(struct se_cmd *cmd)
568 {
569 	struct sbc_ops *ops = cmd->protocol_data;
570 	struct se_device *dev = cmd->se_dev;
571 	sense_reason_t ret;
572 	int rc;
573 	/*
574 	 * Submit the READ first for COMPARE_AND_WRITE to perform the
575 	 * comparision using SGLs at cmd->t_bidi_data_sg..
576 	 */
577 	rc = down_interruptible(&dev->caw_sem);
578 	if (rc != 0) {
579 		cmd->transport_complete_callback = NULL;
580 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
581 	}
582 	/*
583 	 * Reset cmd->data_length to individual block_size in order to not
584 	 * confuse backend drivers that depend on this value matching the
585 	 * size of the I/O being submitted.
586 	 */
587 	cmd->data_length = cmd->t_task_nolb * dev->dev_attrib.block_size;
588 
589 	ret = ops->execute_rw(cmd, cmd->t_bidi_data_sg, cmd->t_bidi_data_nents,
590 			      DMA_FROM_DEVICE);
591 	if (ret) {
592 		cmd->transport_complete_callback = NULL;
593 		up(&dev->caw_sem);
594 		return ret;
595 	}
596 	/*
597 	 * Unlock of dev->caw_sem to occur in compare_and_write_callback()
598 	 * upon MISCOMPARE, or in compare_and_write_done() upon completion
599 	 * of WRITE instance user-data.
600 	 */
601 	return TCM_NO_SENSE;
602 }
603 
604 static int
605 sbc_set_prot_op_checks(u8 protect, bool fabric_prot, enum target_prot_type prot_type,
606 		       bool is_write, struct se_cmd *cmd)
607 {
608 	if (is_write) {
609 		cmd->prot_op = fabric_prot ? TARGET_PROT_DOUT_STRIP :
610 			       protect ? TARGET_PROT_DOUT_PASS :
611 			       TARGET_PROT_DOUT_INSERT;
612 		switch (protect) {
613 		case 0x0:
614 		case 0x3:
615 			cmd->prot_checks = 0;
616 			break;
617 		case 0x1:
618 		case 0x5:
619 			cmd->prot_checks = TARGET_DIF_CHECK_GUARD;
620 			if (prot_type == TARGET_DIF_TYPE1_PROT)
621 				cmd->prot_checks |= TARGET_DIF_CHECK_REFTAG;
622 			break;
623 		case 0x2:
624 			if (prot_type == TARGET_DIF_TYPE1_PROT)
625 				cmd->prot_checks = TARGET_DIF_CHECK_REFTAG;
626 			break;
627 		case 0x4:
628 			cmd->prot_checks = TARGET_DIF_CHECK_GUARD;
629 			break;
630 		default:
631 			pr_err("Unsupported protect field %d\n", protect);
632 			return -EINVAL;
633 		}
634 	} else {
635 		cmd->prot_op = fabric_prot ? TARGET_PROT_DIN_INSERT :
636 			       protect ? TARGET_PROT_DIN_PASS :
637 			       TARGET_PROT_DIN_STRIP;
638 		switch (protect) {
639 		case 0x0:
640 		case 0x1:
641 		case 0x5:
642 			cmd->prot_checks = TARGET_DIF_CHECK_GUARD;
643 			if (prot_type == TARGET_DIF_TYPE1_PROT)
644 				cmd->prot_checks |= TARGET_DIF_CHECK_REFTAG;
645 			break;
646 		case 0x2:
647 			if (prot_type == TARGET_DIF_TYPE1_PROT)
648 				cmd->prot_checks = TARGET_DIF_CHECK_REFTAG;
649 			break;
650 		case 0x3:
651 			cmd->prot_checks = 0;
652 			break;
653 		case 0x4:
654 			cmd->prot_checks = TARGET_DIF_CHECK_GUARD;
655 			break;
656 		default:
657 			pr_err("Unsupported protect field %d\n", protect);
658 			return -EINVAL;
659 		}
660 	}
661 
662 	return 0;
663 }
664 
665 static sense_reason_t
666 sbc_check_prot(struct se_device *dev, struct se_cmd *cmd, unsigned char protect,
667 	       u32 sectors, bool is_write)
668 {
669 	int sp_ops = cmd->se_sess->sup_prot_ops;
670 	int pi_prot_type = dev->dev_attrib.pi_prot_type;
671 	bool fabric_prot = false;
672 
673 	if (!cmd->t_prot_sg || !cmd->t_prot_nents) {
674 		if (unlikely(protect &&
675 		    !dev->dev_attrib.pi_prot_type && !cmd->se_sess->sess_prot_type)) {
676 			pr_err("CDB contains protect bit, but device + fabric does"
677 			       " not advertise PROTECT=1 feature bit\n");
678 			return TCM_INVALID_CDB_FIELD;
679 		}
680 		if (cmd->prot_pto)
681 			return TCM_NO_SENSE;
682 	}
683 
684 	switch (dev->dev_attrib.pi_prot_type) {
685 	case TARGET_DIF_TYPE3_PROT:
686 		cmd->reftag_seed = 0xffffffff;
687 		break;
688 	case TARGET_DIF_TYPE2_PROT:
689 		if (protect)
690 			return TCM_INVALID_CDB_FIELD;
691 
692 		cmd->reftag_seed = cmd->t_task_lba;
693 		break;
694 	case TARGET_DIF_TYPE1_PROT:
695 		cmd->reftag_seed = cmd->t_task_lba;
696 		break;
697 	case TARGET_DIF_TYPE0_PROT:
698 		/*
699 		 * See if the fabric supports T10-PI, and the session has been
700 		 * configured to allow export PROTECT=1 feature bit with backend
701 		 * devices that don't support T10-PI.
702 		 */
703 		fabric_prot = is_write ?
704 			      !!(sp_ops & (TARGET_PROT_DOUT_PASS | TARGET_PROT_DOUT_STRIP)) :
705 			      !!(sp_ops & (TARGET_PROT_DIN_PASS | TARGET_PROT_DIN_INSERT));
706 
707 		if (fabric_prot && cmd->se_sess->sess_prot_type) {
708 			pi_prot_type = cmd->se_sess->sess_prot_type;
709 			break;
710 		}
711 		if (!protect)
712 			return TCM_NO_SENSE;
713 		fallthrough;
714 	default:
715 		pr_err("Unable to determine pi_prot_type for CDB: 0x%02x "
716 		       "PROTECT: 0x%02x\n", cmd->t_task_cdb[0], protect);
717 		return TCM_INVALID_CDB_FIELD;
718 	}
719 
720 	if (sbc_set_prot_op_checks(protect, fabric_prot, pi_prot_type, is_write, cmd))
721 		return TCM_INVALID_CDB_FIELD;
722 
723 	cmd->prot_type = pi_prot_type;
724 	cmd->prot_length = dev->prot_length * sectors;
725 
726 	/**
727 	 * In case protection information exists over the wire
728 	 * we modify command data length to describe pure data.
729 	 * The actual transfer length is data length + protection
730 	 * length
731 	 **/
732 	if (protect)
733 		cmd->data_length = sectors * dev->dev_attrib.block_size;
734 
735 	pr_debug("%s: prot_type=%d, data_length=%d, prot_length=%d "
736 		 "prot_op=%d prot_checks=%d\n",
737 		 __func__, cmd->prot_type, cmd->data_length, cmd->prot_length,
738 		 cmd->prot_op, cmd->prot_checks);
739 
740 	return TCM_NO_SENSE;
741 }
742 
743 static int
744 sbc_check_dpofua(struct se_device *dev, struct se_cmd *cmd, unsigned char *cdb)
745 {
746 	if (cdb[1] & 0x10) {
747 		/* see explanation in spc_emulate_modesense */
748 		if (!target_check_fua(dev)) {
749 			pr_err("Got CDB: 0x%02x with DPO bit set, but device"
750 			       " does not advertise support for DPO\n", cdb[0]);
751 			return -EINVAL;
752 		}
753 	}
754 	if (cdb[1] & 0x8) {
755 		if (!target_check_fua(dev)) {
756 			pr_err("Got CDB: 0x%02x with FUA bit set, but device"
757 			       " does not advertise support for FUA write\n",
758 			       cdb[0]);
759 			return -EINVAL;
760 		}
761 		cmd->se_cmd_flags |= SCF_FUA;
762 	}
763 	return 0;
764 }
765 
766 sense_reason_t
767 sbc_parse_cdb(struct se_cmd *cmd, struct sbc_ops *ops)
768 {
769 	struct se_device *dev = cmd->se_dev;
770 	unsigned char *cdb = cmd->t_task_cdb;
771 	unsigned int size;
772 	u32 sectors = 0;
773 	sense_reason_t ret;
774 
775 	cmd->protocol_data = ops;
776 
777 	switch (cdb[0]) {
778 	case READ_6:
779 		sectors = transport_get_sectors_6(cdb);
780 		cmd->t_task_lba = transport_lba_21(cdb);
781 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
782 		cmd->execute_cmd = sbc_execute_rw;
783 		break;
784 	case READ_10:
785 		sectors = transport_get_sectors_10(cdb);
786 		cmd->t_task_lba = transport_lba_32(cdb);
787 
788 		if (sbc_check_dpofua(dev, cmd, cdb))
789 			return TCM_INVALID_CDB_FIELD;
790 
791 		ret = sbc_check_prot(dev, cmd, cdb[1] >> 5, sectors, false);
792 		if (ret)
793 			return ret;
794 
795 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
796 		cmd->execute_cmd = sbc_execute_rw;
797 		break;
798 	case READ_12:
799 		sectors = transport_get_sectors_12(cdb);
800 		cmd->t_task_lba = transport_lba_32(cdb);
801 
802 		if (sbc_check_dpofua(dev, cmd, cdb))
803 			return TCM_INVALID_CDB_FIELD;
804 
805 		ret = sbc_check_prot(dev, cmd, cdb[1] >> 5, sectors, false);
806 		if (ret)
807 			return ret;
808 
809 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
810 		cmd->execute_cmd = sbc_execute_rw;
811 		break;
812 	case READ_16:
813 		sectors = transport_get_sectors_16(cdb);
814 		cmd->t_task_lba = transport_lba_64(cdb);
815 
816 		if (sbc_check_dpofua(dev, cmd, cdb))
817 			return TCM_INVALID_CDB_FIELD;
818 
819 		ret = sbc_check_prot(dev, cmd, cdb[1] >> 5, sectors, false);
820 		if (ret)
821 			return ret;
822 
823 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
824 		cmd->execute_cmd = sbc_execute_rw;
825 		break;
826 	case WRITE_6:
827 		sectors = transport_get_sectors_6(cdb);
828 		cmd->t_task_lba = transport_lba_21(cdb);
829 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
830 		cmd->execute_cmd = sbc_execute_rw;
831 		break;
832 	case WRITE_10:
833 	case WRITE_VERIFY:
834 		sectors = transport_get_sectors_10(cdb);
835 		cmd->t_task_lba = transport_lba_32(cdb);
836 
837 		if (sbc_check_dpofua(dev, cmd, cdb))
838 			return TCM_INVALID_CDB_FIELD;
839 
840 		ret = sbc_check_prot(dev, cmd, cdb[1] >> 5, sectors, true);
841 		if (ret)
842 			return ret;
843 
844 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
845 		cmd->execute_cmd = sbc_execute_rw;
846 		break;
847 	case WRITE_12:
848 		sectors = transport_get_sectors_12(cdb);
849 		cmd->t_task_lba = transport_lba_32(cdb);
850 
851 		if (sbc_check_dpofua(dev, cmd, cdb))
852 			return TCM_INVALID_CDB_FIELD;
853 
854 		ret = sbc_check_prot(dev, cmd, cdb[1] >> 5, sectors, true);
855 		if (ret)
856 			return ret;
857 
858 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
859 		cmd->execute_cmd = sbc_execute_rw;
860 		break;
861 	case WRITE_16:
862 	case WRITE_VERIFY_16:
863 		sectors = transport_get_sectors_16(cdb);
864 		cmd->t_task_lba = transport_lba_64(cdb);
865 
866 		if (sbc_check_dpofua(dev, cmd, cdb))
867 			return TCM_INVALID_CDB_FIELD;
868 
869 		ret = sbc_check_prot(dev, cmd, cdb[1] >> 5, sectors, true);
870 		if (ret)
871 			return ret;
872 
873 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB;
874 		cmd->execute_cmd = sbc_execute_rw;
875 		break;
876 	case VARIABLE_LENGTH_CMD:
877 	{
878 		u16 service_action = get_unaligned_be16(&cdb[8]);
879 		switch (service_action) {
880 		case WRITE_SAME_32:
881 			sectors = transport_get_sectors_32(cdb);
882 			if (!sectors) {
883 				pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not"
884 				       " supported\n");
885 				return TCM_INVALID_CDB_FIELD;
886 			}
887 
888 			size = sbc_get_size(cmd, 1);
889 			cmd->t_task_lba = get_unaligned_be64(&cdb[12]);
890 
891 			ret = sbc_setup_write_same(cmd, cdb[10], ops);
892 			if (ret)
893 				return ret;
894 			break;
895 		default:
896 			pr_err("VARIABLE_LENGTH_CMD service action"
897 				" 0x%04x not supported\n", service_action);
898 			return TCM_UNSUPPORTED_SCSI_OPCODE;
899 		}
900 		break;
901 	}
902 	case COMPARE_AND_WRITE:
903 		if (!dev->dev_attrib.emulate_caw) {
904 			pr_err_ratelimited("se_device %s/%s (vpd_unit_serial %s) reject COMPARE_AND_WRITE\n",
905 					   dev->se_hba->backend->ops->name,
906 					   config_item_name(&dev->dev_group.cg_item),
907 					   dev->t10_wwn.unit_serial);
908 			return TCM_UNSUPPORTED_SCSI_OPCODE;
909 		}
910 		sectors = cdb[13];
911 		/*
912 		 * Currently enforce COMPARE_AND_WRITE for a single sector
913 		 */
914 		if (sectors > 1) {
915 			pr_err("COMPARE_AND_WRITE contains NoLB: %u greater"
916 			       " than 1\n", sectors);
917 			return TCM_INVALID_CDB_FIELD;
918 		}
919 		if (sbc_check_dpofua(dev, cmd, cdb))
920 			return TCM_INVALID_CDB_FIELD;
921 
922 		/*
923 		 * Double size because we have two buffers, note that
924 		 * zero is not an error..
925 		 */
926 		size = 2 * sbc_get_size(cmd, sectors);
927 		cmd->t_task_lba = get_unaligned_be64(&cdb[2]);
928 		cmd->t_task_nolb = sectors;
929 		cmd->se_cmd_flags |= SCF_SCSI_DATA_CDB | SCF_COMPARE_AND_WRITE;
930 		cmd->execute_cmd = sbc_compare_and_write;
931 		cmd->transport_complete_callback = compare_and_write_callback;
932 		break;
933 	case READ_CAPACITY:
934 		size = READ_CAP_LEN;
935 		cmd->execute_cmd = sbc_emulate_readcapacity;
936 		break;
937 	case SERVICE_ACTION_IN_16:
938 		switch (cmd->t_task_cdb[1] & 0x1f) {
939 		case SAI_READ_CAPACITY_16:
940 			cmd->execute_cmd = sbc_emulate_readcapacity_16;
941 			break;
942 		case SAI_REPORT_REFERRALS:
943 			cmd->execute_cmd = target_emulate_report_referrals;
944 			break;
945 		default:
946 			pr_err("Unsupported SA: 0x%02x\n",
947 				cmd->t_task_cdb[1] & 0x1f);
948 			return TCM_INVALID_CDB_FIELD;
949 		}
950 		size = get_unaligned_be32(&cdb[10]);
951 		break;
952 	case SYNCHRONIZE_CACHE:
953 	case SYNCHRONIZE_CACHE_16:
954 		if (cdb[0] == SYNCHRONIZE_CACHE) {
955 			sectors = transport_get_sectors_10(cdb);
956 			cmd->t_task_lba = transport_lba_32(cdb);
957 		} else {
958 			sectors = transport_get_sectors_16(cdb);
959 			cmd->t_task_lba = transport_lba_64(cdb);
960 		}
961 		if (ops->execute_sync_cache) {
962 			cmd->execute_cmd = ops->execute_sync_cache;
963 			goto check_lba;
964 		}
965 		size = 0;
966 		cmd->execute_cmd = sbc_emulate_noop;
967 		break;
968 	case UNMAP:
969 		if (!ops->execute_unmap)
970 			return TCM_UNSUPPORTED_SCSI_OPCODE;
971 
972 		if (!dev->dev_attrib.emulate_tpu) {
973 			pr_err("Got UNMAP, but backend device has"
974 			       " emulate_tpu disabled\n");
975 			return TCM_UNSUPPORTED_SCSI_OPCODE;
976 		}
977 		size = get_unaligned_be16(&cdb[7]);
978 		cmd->execute_cmd = sbc_execute_unmap;
979 		break;
980 	case WRITE_SAME_16:
981 		sectors = transport_get_sectors_16(cdb);
982 		if (!sectors) {
983 			pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
984 			return TCM_INVALID_CDB_FIELD;
985 		}
986 
987 		size = sbc_get_size(cmd, 1);
988 		cmd->t_task_lba = get_unaligned_be64(&cdb[2]);
989 
990 		ret = sbc_setup_write_same(cmd, cdb[1], ops);
991 		if (ret)
992 			return ret;
993 		break;
994 	case WRITE_SAME:
995 		sectors = transport_get_sectors_10(cdb);
996 		if (!sectors) {
997 			pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
998 			return TCM_INVALID_CDB_FIELD;
999 		}
1000 
1001 		size = sbc_get_size(cmd, 1);
1002 		cmd->t_task_lba = get_unaligned_be32(&cdb[2]);
1003 
1004 		/*
1005 		 * Follow sbcr26 with WRITE_SAME (10) and check for the existence
1006 		 * of byte 1 bit 3 UNMAP instead of original reserved field
1007 		 */
1008 		ret = sbc_setup_write_same(cmd, cdb[1], ops);
1009 		if (ret)
1010 			return ret;
1011 		break;
1012 	case VERIFY:
1013 	case VERIFY_16:
1014 		size = 0;
1015 		if (cdb[0] == VERIFY) {
1016 			sectors = transport_get_sectors_10(cdb);
1017 			cmd->t_task_lba = transport_lba_32(cdb);
1018 		} else {
1019 			sectors = transport_get_sectors_16(cdb);
1020 			cmd->t_task_lba = transport_lba_64(cdb);
1021 		}
1022 		cmd->execute_cmd = sbc_emulate_noop;
1023 		goto check_lba;
1024 	case REZERO_UNIT:
1025 	case SEEK_6:
1026 	case SEEK_10:
1027 		/*
1028 		 * There are still clients out there which use these old SCSI-2
1029 		 * commands. This mainly happens when running VMs with legacy
1030 		 * guest systems, connected via SCSI command pass-through to
1031 		 * iSCSI targets. Make them happy and return status GOOD.
1032 		 */
1033 		size = 0;
1034 		cmd->execute_cmd = sbc_emulate_noop;
1035 		break;
1036 	case START_STOP:
1037 		size = 0;
1038 		cmd->execute_cmd = sbc_emulate_startstop;
1039 		break;
1040 	default:
1041 		ret = spc_parse_cdb(cmd, &size);
1042 		if (ret)
1043 			return ret;
1044 	}
1045 
1046 	/* reject any command that we don't have a handler for */
1047 	if (!cmd->execute_cmd)
1048 		return TCM_UNSUPPORTED_SCSI_OPCODE;
1049 
1050 	if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1051 		unsigned long long end_lba;
1052 check_lba:
1053 		end_lba = dev->transport->get_blocks(dev) + 1;
1054 		if (((cmd->t_task_lba + sectors) < cmd->t_task_lba) ||
1055 		    ((cmd->t_task_lba + sectors) > end_lba)) {
1056 			pr_err("cmd exceeds last lba %llu "
1057 				"(lba %llu, sectors %u)\n",
1058 				end_lba, cmd->t_task_lba, sectors);
1059 			return TCM_ADDRESS_OUT_OF_RANGE;
1060 		}
1061 
1062 		if (!(cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE))
1063 			size = sbc_get_size(cmd, sectors);
1064 	}
1065 
1066 	return target_cmd_size_check(cmd, size);
1067 }
1068 EXPORT_SYMBOL(sbc_parse_cdb);
1069 
1070 u32 sbc_get_device_type(struct se_device *dev)
1071 {
1072 	return TYPE_DISK;
1073 }
1074 EXPORT_SYMBOL(sbc_get_device_type);
1075 
1076 static sense_reason_t
1077 sbc_execute_unmap(struct se_cmd *cmd)
1078 {
1079 	struct sbc_ops *ops = cmd->protocol_data;
1080 	struct se_device *dev = cmd->se_dev;
1081 	unsigned char *buf, *ptr = NULL;
1082 	sector_t lba;
1083 	int size;
1084 	u32 range;
1085 	sense_reason_t ret = 0;
1086 	int dl, bd_dl;
1087 
1088 	/* We never set ANC_SUP */
1089 	if (cmd->t_task_cdb[1])
1090 		return TCM_INVALID_CDB_FIELD;
1091 
1092 	if (cmd->data_length == 0) {
1093 		target_complete_cmd(cmd, SAM_STAT_GOOD);
1094 		return 0;
1095 	}
1096 
1097 	if (cmd->data_length < 8) {
1098 		pr_warn("UNMAP parameter list length %u too small\n",
1099 			cmd->data_length);
1100 		return TCM_PARAMETER_LIST_LENGTH_ERROR;
1101 	}
1102 
1103 	buf = transport_kmap_data_sg(cmd);
1104 	if (!buf)
1105 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1106 
1107 	dl = get_unaligned_be16(&buf[0]);
1108 	bd_dl = get_unaligned_be16(&buf[2]);
1109 
1110 	size = cmd->data_length - 8;
1111 	if (bd_dl > size)
1112 		pr_warn("UNMAP parameter list length %u too small, ignoring bd_dl %u\n",
1113 			cmd->data_length, bd_dl);
1114 	else
1115 		size = bd_dl;
1116 
1117 	if (size / 16 > dev->dev_attrib.max_unmap_block_desc_count) {
1118 		ret = TCM_INVALID_PARAMETER_LIST;
1119 		goto err;
1120 	}
1121 
1122 	/* First UNMAP block descriptor starts at 8 byte offset */
1123 	ptr = &buf[8];
1124 	pr_debug("UNMAP: Sub: %s Using dl: %u bd_dl: %u size: %u"
1125 		" ptr: %p\n", dev->transport->name, dl, bd_dl, size, ptr);
1126 
1127 	while (size >= 16) {
1128 		lba = get_unaligned_be64(&ptr[0]);
1129 		range = get_unaligned_be32(&ptr[8]);
1130 		pr_debug("UNMAP: Using lba: %llu and range: %u\n",
1131 				 (unsigned long long)lba, range);
1132 
1133 		if (range > dev->dev_attrib.max_unmap_lba_count) {
1134 			ret = TCM_INVALID_PARAMETER_LIST;
1135 			goto err;
1136 		}
1137 
1138 		if (lba + range > dev->transport->get_blocks(dev) + 1) {
1139 			ret = TCM_ADDRESS_OUT_OF_RANGE;
1140 			goto err;
1141 		}
1142 
1143 		if (range) {
1144 			ret = ops->execute_unmap(cmd, lba, range);
1145 			if (ret)
1146 				goto err;
1147 		}
1148 
1149 		ptr += 16;
1150 		size -= 16;
1151 	}
1152 
1153 err:
1154 	transport_kunmap_data_sg(cmd);
1155 	if (!ret)
1156 		target_complete_cmd(cmd, SAM_STAT_GOOD);
1157 	return ret;
1158 }
1159 
1160 void
1161 sbc_dif_generate(struct se_cmd *cmd)
1162 {
1163 	struct se_device *dev = cmd->se_dev;
1164 	struct t10_pi_tuple *sdt;
1165 	struct scatterlist *dsg = cmd->t_data_sg, *psg;
1166 	sector_t sector = cmd->t_task_lba;
1167 	void *daddr, *paddr;
1168 	int i, j, offset = 0;
1169 	unsigned int block_size = dev->dev_attrib.block_size;
1170 
1171 	for_each_sg(cmd->t_prot_sg, psg, cmd->t_prot_nents, i) {
1172 		paddr = kmap_atomic(sg_page(psg)) + psg->offset;
1173 		daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
1174 
1175 		for (j = 0; j < psg->length;
1176 				j += sizeof(*sdt)) {
1177 			__u16 crc;
1178 			unsigned int avail;
1179 
1180 			if (offset >= dsg->length) {
1181 				offset -= dsg->length;
1182 				kunmap_atomic(daddr - dsg->offset);
1183 				dsg = sg_next(dsg);
1184 				if (!dsg) {
1185 					kunmap_atomic(paddr - psg->offset);
1186 					return;
1187 				}
1188 				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
1189 			}
1190 
1191 			sdt = paddr + j;
1192 			avail = min(block_size, dsg->length - offset);
1193 			crc = crc_t10dif(daddr + offset, avail);
1194 			if (avail < block_size) {
1195 				kunmap_atomic(daddr - dsg->offset);
1196 				dsg = sg_next(dsg);
1197 				if (!dsg) {
1198 					kunmap_atomic(paddr - psg->offset);
1199 					return;
1200 				}
1201 				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
1202 				offset = block_size - avail;
1203 				crc = crc_t10dif_update(crc, daddr, offset);
1204 			} else {
1205 				offset += block_size;
1206 			}
1207 
1208 			sdt->guard_tag = cpu_to_be16(crc);
1209 			if (cmd->prot_type == TARGET_DIF_TYPE1_PROT)
1210 				sdt->ref_tag = cpu_to_be32(sector & 0xffffffff);
1211 			sdt->app_tag = 0;
1212 
1213 			pr_debug("DIF %s INSERT sector: %llu guard_tag: 0x%04x"
1214 				 " app_tag: 0x%04x ref_tag: %u\n",
1215 				 (cmd->data_direction == DMA_TO_DEVICE) ?
1216 				 "WRITE" : "READ", (unsigned long long)sector,
1217 				 sdt->guard_tag, sdt->app_tag,
1218 				 be32_to_cpu(sdt->ref_tag));
1219 
1220 			sector++;
1221 		}
1222 
1223 		kunmap_atomic(daddr - dsg->offset);
1224 		kunmap_atomic(paddr - psg->offset);
1225 	}
1226 }
1227 
1228 static sense_reason_t
1229 sbc_dif_v1_verify(struct se_cmd *cmd, struct t10_pi_tuple *sdt,
1230 		  __u16 crc, sector_t sector, unsigned int ei_lba)
1231 {
1232 	__be16 csum;
1233 
1234 	if (!(cmd->prot_checks & TARGET_DIF_CHECK_GUARD))
1235 		goto check_ref;
1236 
1237 	csum = cpu_to_be16(crc);
1238 
1239 	if (sdt->guard_tag != csum) {
1240 		pr_err("DIFv1 checksum failed on sector %llu guard tag 0x%04x"
1241 			" csum 0x%04x\n", (unsigned long long)sector,
1242 			be16_to_cpu(sdt->guard_tag), be16_to_cpu(csum));
1243 		return TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED;
1244 	}
1245 
1246 check_ref:
1247 	if (!(cmd->prot_checks & TARGET_DIF_CHECK_REFTAG))
1248 		return 0;
1249 
1250 	if (cmd->prot_type == TARGET_DIF_TYPE1_PROT &&
1251 	    be32_to_cpu(sdt->ref_tag) != (sector & 0xffffffff)) {
1252 		pr_err("DIFv1 Type 1 reference failed on sector: %llu tag: 0x%08x"
1253 		       " sector MSB: 0x%08x\n", (unsigned long long)sector,
1254 		       be32_to_cpu(sdt->ref_tag), (u32)(sector & 0xffffffff));
1255 		return TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED;
1256 	}
1257 
1258 	if (cmd->prot_type == TARGET_DIF_TYPE2_PROT &&
1259 	    be32_to_cpu(sdt->ref_tag) != ei_lba) {
1260 		pr_err("DIFv1 Type 2 reference failed on sector: %llu tag: 0x%08x"
1261 		       " ei_lba: 0x%08x\n", (unsigned long long)sector,
1262 			be32_to_cpu(sdt->ref_tag), ei_lba);
1263 		return TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED;
1264 	}
1265 
1266 	return 0;
1267 }
1268 
1269 void sbc_dif_copy_prot(struct se_cmd *cmd, unsigned int sectors, bool read,
1270 		       struct scatterlist *sg, int sg_off)
1271 {
1272 	struct se_device *dev = cmd->se_dev;
1273 	struct scatterlist *psg;
1274 	void *paddr, *addr;
1275 	unsigned int i, len, left;
1276 	unsigned int offset = sg_off;
1277 
1278 	if (!sg)
1279 		return;
1280 
1281 	left = sectors * dev->prot_length;
1282 
1283 	for_each_sg(cmd->t_prot_sg, psg, cmd->t_prot_nents, i) {
1284 		unsigned int psg_len, copied = 0;
1285 
1286 		paddr = kmap_atomic(sg_page(psg)) + psg->offset;
1287 		psg_len = min(left, psg->length);
1288 		while (psg_len) {
1289 			len = min(psg_len, sg->length - offset);
1290 			addr = kmap_atomic(sg_page(sg)) + sg->offset + offset;
1291 
1292 			if (read)
1293 				memcpy(paddr + copied, addr, len);
1294 			else
1295 				memcpy(addr, paddr + copied, len);
1296 
1297 			left -= len;
1298 			offset += len;
1299 			copied += len;
1300 			psg_len -= len;
1301 
1302 			kunmap_atomic(addr - sg->offset - offset);
1303 
1304 			if (offset >= sg->length) {
1305 				sg = sg_next(sg);
1306 				offset = 0;
1307 			}
1308 		}
1309 		kunmap_atomic(paddr - psg->offset);
1310 	}
1311 }
1312 EXPORT_SYMBOL(sbc_dif_copy_prot);
1313 
1314 sense_reason_t
1315 sbc_dif_verify(struct se_cmd *cmd, sector_t start, unsigned int sectors,
1316 	       unsigned int ei_lba, struct scatterlist *psg, int psg_off)
1317 {
1318 	struct se_device *dev = cmd->se_dev;
1319 	struct t10_pi_tuple *sdt;
1320 	struct scatterlist *dsg = cmd->t_data_sg;
1321 	sector_t sector = start;
1322 	void *daddr, *paddr;
1323 	int i;
1324 	sense_reason_t rc;
1325 	int dsg_off = 0;
1326 	unsigned int block_size = dev->dev_attrib.block_size;
1327 
1328 	for (; psg && sector < start + sectors; psg = sg_next(psg)) {
1329 		paddr = kmap_atomic(sg_page(psg)) + psg->offset;
1330 		daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
1331 
1332 		for (i = psg_off; i < psg->length &&
1333 				sector < start + sectors;
1334 				i += sizeof(*sdt)) {
1335 			__u16 crc;
1336 			unsigned int avail;
1337 
1338 			if (dsg_off >= dsg->length) {
1339 				dsg_off -= dsg->length;
1340 				kunmap_atomic(daddr - dsg->offset);
1341 				dsg = sg_next(dsg);
1342 				if (!dsg) {
1343 					kunmap_atomic(paddr - psg->offset);
1344 					return 0;
1345 				}
1346 				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
1347 			}
1348 
1349 			sdt = paddr + i;
1350 
1351 			pr_debug("DIF READ sector: %llu guard_tag: 0x%04x"
1352 				 " app_tag: 0x%04x ref_tag: %u\n",
1353 				 (unsigned long long)sector, sdt->guard_tag,
1354 				 sdt->app_tag, be32_to_cpu(sdt->ref_tag));
1355 
1356 			if (sdt->app_tag == T10_PI_APP_ESCAPE) {
1357 				dsg_off += block_size;
1358 				goto next;
1359 			}
1360 
1361 			avail = min(block_size, dsg->length - dsg_off);
1362 			crc = crc_t10dif(daddr + dsg_off, avail);
1363 			if (avail < block_size) {
1364 				kunmap_atomic(daddr - dsg->offset);
1365 				dsg = sg_next(dsg);
1366 				if (!dsg) {
1367 					kunmap_atomic(paddr - psg->offset);
1368 					return 0;
1369 				}
1370 				daddr = kmap_atomic(sg_page(dsg)) + dsg->offset;
1371 				dsg_off = block_size - avail;
1372 				crc = crc_t10dif_update(crc, daddr, dsg_off);
1373 			} else {
1374 				dsg_off += block_size;
1375 			}
1376 
1377 			rc = sbc_dif_v1_verify(cmd, sdt, crc, sector, ei_lba);
1378 			if (rc) {
1379 				kunmap_atomic(daddr - dsg->offset);
1380 				kunmap_atomic(paddr - psg->offset);
1381 				cmd->sense_info = sector;
1382 				return rc;
1383 			}
1384 next:
1385 			sector++;
1386 			ei_lba++;
1387 		}
1388 
1389 		psg_off = 0;
1390 		kunmap_atomic(daddr - dsg->offset);
1391 		kunmap_atomic(paddr - psg->offset);
1392 	}
1393 
1394 	return 0;
1395 }
1396 EXPORT_SYMBOL(sbc_dif_verify);
1397