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