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