1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*******************************************************************************
3  * Filename:  target_core_iblock.c
4  *
5  * This file contains the Storage Engine  <-> Linux BlockIO transport
6  * specific functions.
7  *
8  * (c) Copyright 2003-2013 Datera, Inc.
9  *
10  * Nicholas A. Bellinger <nab@kernel.org>
11  *
12  ******************************************************************************/
13 
14 #include <linux/string.h>
15 #include <linux/parser.h>
16 #include <linux/timer.h>
17 #include <linux/fs.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-integrity.h>
20 #include <linux/slab.h>
21 #include <linux/spinlock.h>
22 #include <linux/bio.h>
23 #include <linux/file.h>
24 #include <linux/module.h>
25 #include <linux/scatterlist.h>
26 #include <scsi/scsi_proto.h>
27 #include <asm/unaligned.h>
28 
29 #include <target/target_core_base.h>
30 #include <target/target_core_backend.h>
31 
32 #include "target_core_iblock.h"
33 
34 #define IBLOCK_MAX_BIO_PER_TASK	 32	/* max # of bios to submit at a time */
35 #define IBLOCK_BIO_POOL_SIZE	128
36 
37 static inline struct iblock_dev *IBLOCK_DEV(struct se_device *dev)
38 {
39 	return container_of(dev, struct iblock_dev, dev);
40 }
41 
42 
43 static int iblock_attach_hba(struct se_hba *hba, u32 host_id)
44 {
45 	pr_debug("CORE_HBA[%d] - TCM iBlock HBA Driver %s on"
46 		" Generic Target Core Stack %s\n", hba->hba_id,
47 		IBLOCK_VERSION, TARGET_CORE_VERSION);
48 	return 0;
49 }
50 
51 static void iblock_detach_hba(struct se_hba *hba)
52 {
53 }
54 
55 static struct se_device *iblock_alloc_device(struct se_hba *hba, const char *name)
56 {
57 	struct iblock_dev *ib_dev = NULL;
58 
59 	ib_dev = kzalloc(sizeof(struct iblock_dev), GFP_KERNEL);
60 	if (!ib_dev) {
61 		pr_err("Unable to allocate struct iblock_dev\n");
62 		return NULL;
63 	}
64 
65 	ib_dev->ibd_plug = kcalloc(nr_cpu_ids, sizeof(*ib_dev->ibd_plug),
66 				   GFP_KERNEL);
67 	if (!ib_dev->ibd_plug)
68 		goto free_dev;
69 
70 	pr_debug( "IBLOCK: Allocated ib_dev for %s\n", name);
71 
72 	return &ib_dev->dev;
73 
74 free_dev:
75 	kfree(ib_dev);
76 	return NULL;
77 }
78 
79 static int iblock_configure_device(struct se_device *dev)
80 {
81 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
82 	struct request_queue *q;
83 	struct block_device *bd = NULL;
84 	struct blk_integrity *bi;
85 	fmode_t mode;
86 	unsigned int max_write_zeroes_sectors;
87 	int ret;
88 
89 	if (!(ib_dev->ibd_flags & IBDF_HAS_UDEV_PATH)) {
90 		pr_err("Missing udev_path= parameters for IBLOCK\n");
91 		return -EINVAL;
92 	}
93 
94 	ret = bioset_init(&ib_dev->ibd_bio_set, IBLOCK_BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
95 	if (ret) {
96 		pr_err("IBLOCK: Unable to create bioset\n");
97 		goto out;
98 	}
99 
100 	pr_debug( "IBLOCK: Claiming struct block_device: %s\n",
101 			ib_dev->ibd_udev_path);
102 
103 	mode = FMODE_READ|FMODE_EXCL;
104 	if (!ib_dev->ibd_readonly)
105 		mode |= FMODE_WRITE;
106 	else
107 		dev->dev_flags |= DF_READ_ONLY;
108 
109 	bd = blkdev_get_by_path(ib_dev->ibd_udev_path, mode, ib_dev);
110 	if (IS_ERR(bd)) {
111 		ret = PTR_ERR(bd);
112 		goto out_free_bioset;
113 	}
114 	ib_dev->ibd_bd = bd;
115 
116 	q = bdev_get_queue(bd);
117 
118 	dev->dev_attrib.hw_block_size = bdev_logical_block_size(bd);
119 	dev->dev_attrib.hw_max_sectors = queue_max_hw_sectors(q);
120 	dev->dev_attrib.hw_queue_depth = q->nr_requests;
121 
122 	if (target_configure_unmap_from_queue(&dev->dev_attrib, q))
123 		pr_debug("IBLOCK: BLOCK Discard support available,"
124 			 " disabled by default\n");
125 
126 	/*
127 	 * Enable write same emulation for IBLOCK and use 0xFFFF as
128 	 * the smaller WRITE_SAME(10) only has a two-byte block count.
129 	 */
130 	max_write_zeroes_sectors = bdev_write_zeroes_sectors(bd);
131 	if (max_write_zeroes_sectors)
132 		dev->dev_attrib.max_write_same_len = max_write_zeroes_sectors;
133 	else
134 		dev->dev_attrib.max_write_same_len = 0xFFFF;
135 
136 	if (blk_queue_nonrot(q))
137 		dev->dev_attrib.is_nonrot = 1;
138 
139 	bi = bdev_get_integrity(bd);
140 	if (bi) {
141 		struct bio_set *bs = &ib_dev->ibd_bio_set;
142 
143 		if (!strcmp(bi->profile->name, "T10-DIF-TYPE3-IP") ||
144 		    !strcmp(bi->profile->name, "T10-DIF-TYPE1-IP")) {
145 			pr_err("IBLOCK export of blk_integrity: %s not"
146 			       " supported\n", bi->profile->name);
147 			ret = -ENOSYS;
148 			goto out_blkdev_put;
149 		}
150 
151 		if (!strcmp(bi->profile->name, "T10-DIF-TYPE3-CRC")) {
152 			dev->dev_attrib.pi_prot_type = TARGET_DIF_TYPE3_PROT;
153 		} else if (!strcmp(bi->profile->name, "T10-DIF-TYPE1-CRC")) {
154 			dev->dev_attrib.pi_prot_type = TARGET_DIF_TYPE1_PROT;
155 		}
156 
157 		if (dev->dev_attrib.pi_prot_type) {
158 			if (bioset_integrity_create(bs, IBLOCK_BIO_POOL_SIZE) < 0) {
159 				pr_err("Unable to allocate bioset for PI\n");
160 				ret = -ENOMEM;
161 				goto out_blkdev_put;
162 			}
163 			pr_debug("IBLOCK setup BIP bs->bio_integrity_pool: %p\n",
164 				 &bs->bio_integrity_pool);
165 		}
166 		dev->dev_attrib.hw_pi_prot_type = dev->dev_attrib.pi_prot_type;
167 	}
168 
169 	return 0;
170 
171 out_blkdev_put:
172 	blkdev_put(ib_dev->ibd_bd, FMODE_WRITE|FMODE_READ|FMODE_EXCL);
173 out_free_bioset:
174 	bioset_exit(&ib_dev->ibd_bio_set);
175 out:
176 	return ret;
177 }
178 
179 static void iblock_dev_call_rcu(struct rcu_head *p)
180 {
181 	struct se_device *dev = container_of(p, struct se_device, rcu_head);
182 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
183 
184 	kfree(ib_dev->ibd_plug);
185 	kfree(ib_dev);
186 }
187 
188 static void iblock_free_device(struct se_device *dev)
189 {
190 	call_rcu(&dev->rcu_head, iblock_dev_call_rcu);
191 }
192 
193 static void iblock_destroy_device(struct se_device *dev)
194 {
195 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
196 
197 	if (ib_dev->ibd_bd != NULL)
198 		blkdev_put(ib_dev->ibd_bd, FMODE_WRITE|FMODE_READ|FMODE_EXCL);
199 	bioset_exit(&ib_dev->ibd_bio_set);
200 }
201 
202 static struct se_dev_plug *iblock_plug_device(struct se_device *se_dev)
203 {
204 	struct iblock_dev *ib_dev = IBLOCK_DEV(se_dev);
205 	struct iblock_dev_plug *ib_dev_plug;
206 
207 	/*
208 	 * Each se_device has a per cpu work this can be run from. We
209 	 * shouldn't have multiple threads on the same cpu calling this
210 	 * at the same time.
211 	 */
212 	ib_dev_plug = &ib_dev->ibd_plug[raw_smp_processor_id()];
213 	if (test_and_set_bit(IBD_PLUGF_PLUGGED, &ib_dev_plug->flags))
214 		return NULL;
215 
216 	blk_start_plug(&ib_dev_plug->blk_plug);
217 	return &ib_dev_plug->se_plug;
218 }
219 
220 static void iblock_unplug_device(struct se_dev_plug *se_plug)
221 {
222 	struct iblock_dev_plug *ib_dev_plug = container_of(se_plug,
223 					struct iblock_dev_plug, se_plug);
224 
225 	blk_finish_plug(&ib_dev_plug->blk_plug);
226 	clear_bit(IBD_PLUGF_PLUGGED, &ib_dev_plug->flags);
227 }
228 
229 static unsigned long long iblock_emulate_read_cap_with_block_size(
230 	struct se_device *dev,
231 	struct block_device *bd,
232 	struct request_queue *q)
233 {
234 	u32 block_size = bdev_logical_block_size(bd);
235 	unsigned long long blocks_long =
236 		div_u64(bdev_nr_bytes(bd), block_size) - 1;
237 
238 	if (block_size == dev->dev_attrib.block_size)
239 		return blocks_long;
240 
241 	switch (block_size) {
242 	case 4096:
243 		switch (dev->dev_attrib.block_size) {
244 		case 2048:
245 			blocks_long <<= 1;
246 			break;
247 		case 1024:
248 			blocks_long <<= 2;
249 			break;
250 		case 512:
251 			blocks_long <<= 3;
252 			break;
253 		default:
254 			break;
255 		}
256 		break;
257 	case 2048:
258 		switch (dev->dev_attrib.block_size) {
259 		case 4096:
260 			blocks_long >>= 1;
261 			break;
262 		case 1024:
263 			blocks_long <<= 1;
264 			break;
265 		case 512:
266 			blocks_long <<= 2;
267 			break;
268 		default:
269 			break;
270 		}
271 		break;
272 	case 1024:
273 		switch (dev->dev_attrib.block_size) {
274 		case 4096:
275 			blocks_long >>= 2;
276 			break;
277 		case 2048:
278 			blocks_long >>= 1;
279 			break;
280 		case 512:
281 			blocks_long <<= 1;
282 			break;
283 		default:
284 			break;
285 		}
286 		break;
287 	case 512:
288 		switch (dev->dev_attrib.block_size) {
289 		case 4096:
290 			blocks_long >>= 3;
291 			break;
292 		case 2048:
293 			blocks_long >>= 2;
294 			break;
295 		case 1024:
296 			blocks_long >>= 1;
297 			break;
298 		default:
299 			break;
300 		}
301 		break;
302 	default:
303 		break;
304 	}
305 
306 	return blocks_long;
307 }
308 
309 static void iblock_complete_cmd(struct se_cmd *cmd)
310 {
311 	struct iblock_req *ibr = cmd->priv;
312 	u8 status;
313 
314 	if (!refcount_dec_and_test(&ibr->pending))
315 		return;
316 
317 	if (atomic_read(&ibr->ib_bio_err_cnt))
318 		status = SAM_STAT_CHECK_CONDITION;
319 	else
320 		status = SAM_STAT_GOOD;
321 
322 	target_complete_cmd(cmd, status);
323 	kfree(ibr);
324 }
325 
326 static void iblock_bio_done(struct bio *bio)
327 {
328 	struct se_cmd *cmd = bio->bi_private;
329 	struct iblock_req *ibr = cmd->priv;
330 
331 	if (bio->bi_status) {
332 		pr_err("bio error: %p,  err: %d\n", bio, bio->bi_status);
333 		/*
334 		 * Bump the ib_bio_err_cnt and release bio.
335 		 */
336 		atomic_inc(&ibr->ib_bio_err_cnt);
337 		smp_mb__after_atomic();
338 	}
339 
340 	bio_put(bio);
341 
342 	iblock_complete_cmd(cmd);
343 }
344 
345 static struct bio *iblock_get_bio(struct se_cmd *cmd, sector_t lba, u32 sg_num,
346 				  unsigned int opf)
347 {
348 	struct iblock_dev *ib_dev = IBLOCK_DEV(cmd->se_dev);
349 	struct bio *bio;
350 
351 	/*
352 	 * Only allocate as many vector entries as the bio code allows us to,
353 	 * we'll loop later on until we have handled the whole request.
354 	 */
355 	bio = bio_alloc_bioset(ib_dev->ibd_bd, bio_max_segs(sg_num), opf,
356 			       GFP_NOIO, &ib_dev->ibd_bio_set);
357 	if (!bio) {
358 		pr_err("Unable to allocate memory for bio\n");
359 		return NULL;
360 	}
361 
362 	bio->bi_private = cmd;
363 	bio->bi_end_io = &iblock_bio_done;
364 	bio->bi_iter.bi_sector = lba;
365 
366 	return bio;
367 }
368 
369 static void iblock_submit_bios(struct bio_list *list)
370 {
371 	struct blk_plug plug;
372 	struct bio *bio;
373 	/*
374 	 * The block layer handles nested plugs, so just plug/unplug to handle
375 	 * fabric drivers that didn't support batching and multi bio cmds.
376 	 */
377 	blk_start_plug(&plug);
378 	while ((bio = bio_list_pop(list)))
379 		submit_bio(bio);
380 	blk_finish_plug(&plug);
381 }
382 
383 static void iblock_end_io_flush(struct bio *bio)
384 {
385 	struct se_cmd *cmd = bio->bi_private;
386 
387 	if (bio->bi_status)
388 		pr_err("IBLOCK: cache flush failed: %d\n", bio->bi_status);
389 
390 	if (cmd) {
391 		if (bio->bi_status)
392 			target_complete_cmd(cmd, SAM_STAT_CHECK_CONDITION);
393 		else
394 			target_complete_cmd(cmd, SAM_STAT_GOOD);
395 	}
396 
397 	bio_put(bio);
398 }
399 
400 /*
401  * Implement SYCHRONIZE CACHE.  Note that we can't handle lba ranges and must
402  * always flush the whole cache.
403  */
404 static sense_reason_t
405 iblock_execute_sync_cache(struct se_cmd *cmd)
406 {
407 	struct iblock_dev *ib_dev = IBLOCK_DEV(cmd->se_dev);
408 	int immed = (cmd->t_task_cdb[1] & 0x2);
409 	struct bio *bio;
410 
411 	/*
412 	 * If the Immediate bit is set, queue up the GOOD response
413 	 * for this SYNCHRONIZE_CACHE op.
414 	 */
415 	if (immed)
416 		target_complete_cmd(cmd, SAM_STAT_GOOD);
417 
418 	bio = bio_alloc(GFP_KERNEL, 0);
419 	bio->bi_end_io = iblock_end_io_flush;
420 	bio_set_dev(bio, ib_dev->ibd_bd);
421 	bio->bi_opf = REQ_OP_WRITE | REQ_PREFLUSH;
422 	if (!immed)
423 		bio->bi_private = cmd;
424 	submit_bio(bio);
425 	return 0;
426 }
427 
428 static sense_reason_t
429 iblock_execute_unmap(struct se_cmd *cmd, sector_t lba, sector_t nolb)
430 {
431 	struct block_device *bdev = IBLOCK_DEV(cmd->se_dev)->ibd_bd;
432 	struct se_device *dev = cmd->se_dev;
433 	int ret;
434 
435 	ret = blkdev_issue_discard(bdev,
436 				   target_to_linux_sector(dev, lba),
437 				   target_to_linux_sector(dev,  nolb),
438 				   GFP_KERNEL, 0);
439 	if (ret < 0) {
440 		pr_err("blkdev_issue_discard() failed: %d\n", ret);
441 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
442 	}
443 
444 	return 0;
445 }
446 
447 static sense_reason_t
448 iblock_execute_zero_out(struct block_device *bdev, struct se_cmd *cmd)
449 {
450 	struct se_device *dev = cmd->se_dev;
451 	struct scatterlist *sg = &cmd->t_data_sg[0];
452 	unsigned char *buf, *not_zero;
453 	int ret;
454 
455 	buf = kmap(sg_page(sg)) + sg->offset;
456 	if (!buf)
457 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
458 	/*
459 	 * Fall back to block_execute_write_same() slow-path if
460 	 * incoming WRITE_SAME payload does not contain zeros.
461 	 */
462 	not_zero = memchr_inv(buf, 0x00, cmd->data_length);
463 	kunmap(sg_page(sg));
464 
465 	if (not_zero)
466 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
467 
468 	ret = blkdev_issue_zeroout(bdev,
469 				target_to_linux_sector(dev, cmd->t_task_lba),
470 				target_to_linux_sector(dev,
471 					sbc_get_write_same_sectors(cmd)),
472 				GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
473 	if (ret)
474 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
475 
476 	target_complete_cmd(cmd, SAM_STAT_GOOD);
477 	return 0;
478 }
479 
480 static sense_reason_t
481 iblock_execute_write_same(struct se_cmd *cmd)
482 {
483 	struct block_device *bdev = IBLOCK_DEV(cmd->se_dev)->ibd_bd;
484 	struct iblock_req *ibr;
485 	struct scatterlist *sg;
486 	struct bio *bio;
487 	struct bio_list list;
488 	struct se_device *dev = cmd->se_dev;
489 	sector_t block_lba = target_to_linux_sector(dev, cmd->t_task_lba);
490 	sector_t sectors = target_to_linux_sector(dev,
491 					sbc_get_write_same_sectors(cmd));
492 
493 	if (cmd->prot_op) {
494 		pr_err("WRITE_SAME: Protection information with IBLOCK"
495 		       " backends not supported\n");
496 		return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
497 	}
498 	sg = &cmd->t_data_sg[0];
499 
500 	if (cmd->t_data_nents > 1 ||
501 	    sg->length != cmd->se_dev->dev_attrib.block_size) {
502 		pr_err("WRITE_SAME: Illegal SGL t_data_nents: %u length: %u"
503 			" block_size: %u\n", cmd->t_data_nents, sg->length,
504 			cmd->se_dev->dev_attrib.block_size);
505 		return TCM_INVALID_CDB_FIELD;
506 	}
507 
508 	if (bdev_write_zeroes_sectors(bdev)) {
509 		if (!iblock_execute_zero_out(bdev, cmd))
510 			return 0;
511 	}
512 
513 	ibr = kzalloc(sizeof(struct iblock_req), GFP_KERNEL);
514 	if (!ibr)
515 		goto fail;
516 	cmd->priv = ibr;
517 
518 	bio = iblock_get_bio(cmd, block_lba, 1, REQ_OP_WRITE);
519 	if (!bio)
520 		goto fail_free_ibr;
521 
522 	bio_list_init(&list);
523 	bio_list_add(&list, bio);
524 
525 	refcount_set(&ibr->pending, 1);
526 
527 	while (sectors) {
528 		while (bio_add_page(bio, sg_page(sg), sg->length, sg->offset)
529 				!= sg->length) {
530 
531 			bio = iblock_get_bio(cmd, block_lba, 1, REQ_OP_WRITE);
532 			if (!bio)
533 				goto fail_put_bios;
534 
535 			refcount_inc(&ibr->pending);
536 			bio_list_add(&list, bio);
537 		}
538 
539 		/* Always in 512 byte units for Linux/Block */
540 		block_lba += sg->length >> SECTOR_SHIFT;
541 		sectors -= sg->length >> SECTOR_SHIFT;
542 	}
543 
544 	iblock_submit_bios(&list);
545 	return 0;
546 
547 fail_put_bios:
548 	while ((bio = bio_list_pop(&list)))
549 		bio_put(bio);
550 fail_free_ibr:
551 	kfree(ibr);
552 fail:
553 	return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
554 }
555 
556 enum {
557 	Opt_udev_path, Opt_readonly, Opt_force, Opt_err
558 };
559 
560 static match_table_t tokens = {
561 	{Opt_udev_path, "udev_path=%s"},
562 	{Opt_readonly, "readonly=%d"},
563 	{Opt_force, "force=%d"},
564 	{Opt_err, NULL}
565 };
566 
567 static ssize_t iblock_set_configfs_dev_params(struct se_device *dev,
568 		const char *page, ssize_t count)
569 {
570 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
571 	char *orig, *ptr, *arg_p, *opts;
572 	substring_t args[MAX_OPT_ARGS];
573 	int ret = 0, token;
574 	unsigned long tmp_readonly;
575 
576 	opts = kstrdup(page, GFP_KERNEL);
577 	if (!opts)
578 		return -ENOMEM;
579 
580 	orig = opts;
581 
582 	while ((ptr = strsep(&opts, ",\n")) != NULL) {
583 		if (!*ptr)
584 			continue;
585 
586 		token = match_token(ptr, tokens, args);
587 		switch (token) {
588 		case Opt_udev_path:
589 			if (ib_dev->ibd_bd) {
590 				pr_err("Unable to set udev_path= while"
591 					" ib_dev->ibd_bd exists\n");
592 				ret = -EEXIST;
593 				goto out;
594 			}
595 			if (match_strlcpy(ib_dev->ibd_udev_path, &args[0],
596 				SE_UDEV_PATH_LEN) == 0) {
597 				ret = -EINVAL;
598 				break;
599 			}
600 			pr_debug("IBLOCK: Referencing UDEV path: %s\n",
601 					ib_dev->ibd_udev_path);
602 			ib_dev->ibd_flags |= IBDF_HAS_UDEV_PATH;
603 			break;
604 		case Opt_readonly:
605 			arg_p = match_strdup(&args[0]);
606 			if (!arg_p) {
607 				ret = -ENOMEM;
608 				break;
609 			}
610 			ret = kstrtoul(arg_p, 0, &tmp_readonly);
611 			kfree(arg_p);
612 			if (ret < 0) {
613 				pr_err("kstrtoul() failed for"
614 						" readonly=\n");
615 				goto out;
616 			}
617 			ib_dev->ibd_readonly = tmp_readonly;
618 			pr_debug("IBLOCK: readonly: %d\n", ib_dev->ibd_readonly);
619 			break;
620 		case Opt_force:
621 			break;
622 		default:
623 			break;
624 		}
625 	}
626 
627 out:
628 	kfree(orig);
629 	return (!ret) ? count : ret;
630 }
631 
632 static ssize_t iblock_show_configfs_dev_params(struct se_device *dev, char *b)
633 {
634 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
635 	struct block_device *bd = ib_dev->ibd_bd;
636 	ssize_t bl = 0;
637 
638 	if (bd)
639 		bl += sprintf(b + bl, "iBlock device: %pg", bd);
640 	if (ib_dev->ibd_flags & IBDF_HAS_UDEV_PATH)
641 		bl += sprintf(b + bl, "  UDEV PATH: %s",
642 				ib_dev->ibd_udev_path);
643 	bl += sprintf(b + bl, "  readonly: %d\n", ib_dev->ibd_readonly);
644 
645 	bl += sprintf(b + bl, "        ");
646 	if (bd) {
647 		bl += sprintf(b + bl, "Major: %d Minor: %d  %s\n",
648 			MAJOR(bd->bd_dev), MINOR(bd->bd_dev),
649 			"CLAIMED: IBLOCK");
650 	} else {
651 		bl += sprintf(b + bl, "Major: 0 Minor: 0\n");
652 	}
653 
654 	return bl;
655 }
656 
657 static int
658 iblock_alloc_bip(struct se_cmd *cmd, struct bio *bio,
659 		 struct sg_mapping_iter *miter)
660 {
661 	struct se_device *dev = cmd->se_dev;
662 	struct blk_integrity *bi;
663 	struct bio_integrity_payload *bip;
664 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
665 	int rc;
666 	size_t resid, len;
667 
668 	bi = bdev_get_integrity(ib_dev->ibd_bd);
669 	if (!bi) {
670 		pr_err("Unable to locate bio_integrity\n");
671 		return -ENODEV;
672 	}
673 
674 	bip = bio_integrity_alloc(bio, GFP_NOIO, bio_max_segs(cmd->t_prot_nents));
675 	if (IS_ERR(bip)) {
676 		pr_err("Unable to allocate bio_integrity_payload\n");
677 		return PTR_ERR(bip);
678 	}
679 
680 	bip->bip_iter.bi_size = bio_integrity_bytes(bi, bio_sectors(bio));
681 	/* virtual start sector must be in integrity interval units */
682 	bip_set_seed(bip, bio->bi_iter.bi_sector >>
683 				  (bi->interval_exp - SECTOR_SHIFT));
684 
685 	pr_debug("IBLOCK BIP Size: %u Sector: %llu\n", bip->bip_iter.bi_size,
686 		 (unsigned long long)bip->bip_iter.bi_sector);
687 
688 	resid = bip->bip_iter.bi_size;
689 	while (resid > 0 && sg_miter_next(miter)) {
690 
691 		len = min_t(size_t, miter->length, resid);
692 		rc = bio_integrity_add_page(bio, miter->page, len,
693 					    offset_in_page(miter->addr));
694 		if (rc != len) {
695 			pr_err("bio_integrity_add_page() failed; %d\n", rc);
696 			sg_miter_stop(miter);
697 			return -ENOMEM;
698 		}
699 
700 		pr_debug("Added bio integrity page: %p length: %zu offset: %lu\n",
701 			  miter->page, len, offset_in_page(miter->addr));
702 
703 		resid -= len;
704 		if (len < miter->length)
705 			miter->consumed -= miter->length - len;
706 	}
707 	sg_miter_stop(miter);
708 
709 	return 0;
710 }
711 
712 static sense_reason_t
713 iblock_execute_rw(struct se_cmd *cmd, struct scatterlist *sgl, u32 sgl_nents,
714 		  enum dma_data_direction data_direction)
715 {
716 	struct se_device *dev = cmd->se_dev;
717 	sector_t block_lba = target_to_linux_sector(dev, cmd->t_task_lba);
718 	struct iblock_req *ibr;
719 	struct bio *bio;
720 	struct bio_list list;
721 	struct scatterlist *sg;
722 	u32 sg_num = sgl_nents;
723 	unsigned int opf;
724 	unsigned bio_cnt;
725 	int i, rc;
726 	struct sg_mapping_iter prot_miter;
727 	unsigned int miter_dir;
728 
729 	if (data_direction == DMA_TO_DEVICE) {
730 		struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
731 		struct request_queue *q = bdev_get_queue(ib_dev->ibd_bd);
732 		/*
733 		 * Force writethrough using REQ_FUA if a volatile write cache
734 		 * is not enabled, or if initiator set the Force Unit Access bit.
735 		 */
736 		opf = REQ_OP_WRITE;
737 		miter_dir = SG_MITER_TO_SG;
738 		if (test_bit(QUEUE_FLAG_FUA, &q->queue_flags)) {
739 			if (cmd->se_cmd_flags & SCF_FUA)
740 				opf |= REQ_FUA;
741 			else if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
742 				opf |= REQ_FUA;
743 		}
744 	} else {
745 		opf = REQ_OP_READ;
746 		miter_dir = SG_MITER_FROM_SG;
747 	}
748 
749 	ibr = kzalloc(sizeof(struct iblock_req), GFP_KERNEL);
750 	if (!ibr)
751 		goto fail;
752 	cmd->priv = ibr;
753 
754 	if (!sgl_nents) {
755 		refcount_set(&ibr->pending, 1);
756 		iblock_complete_cmd(cmd);
757 		return 0;
758 	}
759 
760 	bio = iblock_get_bio(cmd, block_lba, sgl_nents, opf);
761 	if (!bio)
762 		goto fail_free_ibr;
763 
764 	bio_list_init(&list);
765 	bio_list_add(&list, bio);
766 
767 	refcount_set(&ibr->pending, 2);
768 	bio_cnt = 1;
769 
770 	if (cmd->prot_type && dev->dev_attrib.pi_prot_type)
771 		sg_miter_start(&prot_miter, cmd->t_prot_sg, cmd->t_prot_nents,
772 			       miter_dir);
773 
774 	for_each_sg(sgl, sg, sgl_nents, i) {
775 		/*
776 		 * XXX: if the length the device accepts is shorter than the
777 		 *	length of the S/G list entry this will cause and
778 		 *	endless loop.  Better hope no driver uses huge pages.
779 		 */
780 		while (bio_add_page(bio, sg_page(sg), sg->length, sg->offset)
781 				!= sg->length) {
782 			if (cmd->prot_type && dev->dev_attrib.pi_prot_type) {
783 				rc = iblock_alloc_bip(cmd, bio, &prot_miter);
784 				if (rc)
785 					goto fail_put_bios;
786 			}
787 
788 			if (bio_cnt >= IBLOCK_MAX_BIO_PER_TASK) {
789 				iblock_submit_bios(&list);
790 				bio_cnt = 0;
791 			}
792 
793 			bio = iblock_get_bio(cmd, block_lba, sg_num, opf);
794 			if (!bio)
795 				goto fail_put_bios;
796 
797 			refcount_inc(&ibr->pending);
798 			bio_list_add(&list, bio);
799 			bio_cnt++;
800 		}
801 
802 		/* Always in 512 byte units for Linux/Block */
803 		block_lba += sg->length >> SECTOR_SHIFT;
804 		sg_num--;
805 	}
806 
807 	if (cmd->prot_type && dev->dev_attrib.pi_prot_type) {
808 		rc = iblock_alloc_bip(cmd, bio, &prot_miter);
809 		if (rc)
810 			goto fail_put_bios;
811 	}
812 
813 	iblock_submit_bios(&list);
814 	iblock_complete_cmd(cmd);
815 	return 0;
816 
817 fail_put_bios:
818 	while ((bio = bio_list_pop(&list)))
819 		bio_put(bio);
820 fail_free_ibr:
821 	kfree(ibr);
822 fail:
823 	return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
824 }
825 
826 static sector_t iblock_get_blocks(struct se_device *dev)
827 {
828 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
829 	struct block_device *bd = ib_dev->ibd_bd;
830 	struct request_queue *q = bdev_get_queue(bd);
831 
832 	return iblock_emulate_read_cap_with_block_size(dev, bd, q);
833 }
834 
835 static sector_t iblock_get_alignment_offset_lbas(struct se_device *dev)
836 {
837 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
838 	struct block_device *bd = ib_dev->ibd_bd;
839 	int ret;
840 
841 	ret = bdev_alignment_offset(bd);
842 	if (ret == -1)
843 		return 0;
844 
845 	/* convert offset-bytes to offset-lbas */
846 	return ret / bdev_logical_block_size(bd);
847 }
848 
849 static unsigned int iblock_get_lbppbe(struct se_device *dev)
850 {
851 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
852 	struct block_device *bd = ib_dev->ibd_bd;
853 	unsigned int logs_per_phys =
854 		bdev_physical_block_size(bd) / bdev_logical_block_size(bd);
855 
856 	return ilog2(logs_per_phys);
857 }
858 
859 static unsigned int iblock_get_io_min(struct se_device *dev)
860 {
861 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
862 	struct block_device *bd = ib_dev->ibd_bd;
863 
864 	return bdev_io_min(bd);
865 }
866 
867 static unsigned int iblock_get_io_opt(struct se_device *dev)
868 {
869 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
870 	struct block_device *bd = ib_dev->ibd_bd;
871 
872 	return bdev_io_opt(bd);
873 }
874 
875 static struct sbc_ops iblock_sbc_ops = {
876 	.execute_rw		= iblock_execute_rw,
877 	.execute_sync_cache	= iblock_execute_sync_cache,
878 	.execute_write_same	= iblock_execute_write_same,
879 	.execute_unmap		= iblock_execute_unmap,
880 };
881 
882 static sense_reason_t
883 iblock_parse_cdb(struct se_cmd *cmd)
884 {
885 	return sbc_parse_cdb(cmd, &iblock_sbc_ops);
886 }
887 
888 static bool iblock_get_write_cache(struct se_device *dev)
889 {
890 	struct iblock_dev *ib_dev = IBLOCK_DEV(dev);
891 	struct block_device *bd = ib_dev->ibd_bd;
892 	struct request_queue *q = bdev_get_queue(bd);
893 
894 	return test_bit(QUEUE_FLAG_WC, &q->queue_flags);
895 }
896 
897 static const struct target_backend_ops iblock_ops = {
898 	.name			= "iblock",
899 	.inquiry_prod		= "IBLOCK",
900 	.inquiry_rev		= IBLOCK_VERSION,
901 	.owner			= THIS_MODULE,
902 	.attach_hba		= iblock_attach_hba,
903 	.detach_hba		= iblock_detach_hba,
904 	.alloc_device		= iblock_alloc_device,
905 	.configure_device	= iblock_configure_device,
906 	.destroy_device		= iblock_destroy_device,
907 	.free_device		= iblock_free_device,
908 	.plug_device		= iblock_plug_device,
909 	.unplug_device		= iblock_unplug_device,
910 	.parse_cdb		= iblock_parse_cdb,
911 	.set_configfs_dev_params = iblock_set_configfs_dev_params,
912 	.show_configfs_dev_params = iblock_show_configfs_dev_params,
913 	.get_device_type	= sbc_get_device_type,
914 	.get_blocks		= iblock_get_blocks,
915 	.get_alignment_offset_lbas = iblock_get_alignment_offset_lbas,
916 	.get_lbppbe		= iblock_get_lbppbe,
917 	.get_io_min		= iblock_get_io_min,
918 	.get_io_opt		= iblock_get_io_opt,
919 	.get_write_cache	= iblock_get_write_cache,
920 	.tb_dev_attrib_attrs	= sbc_attrib_attrs,
921 };
922 
923 static int __init iblock_module_init(void)
924 {
925 	return transport_backend_register(&iblock_ops);
926 }
927 
928 static void __exit iblock_module_exit(void)
929 {
930 	target_backend_unregister(&iblock_ops);
931 }
932 
933 MODULE_DESCRIPTION("TCM IBLOCK subsystem plugin");
934 MODULE_AUTHOR("nab@Linux-iSCSI.org");
935 MODULE_LICENSE("GPL");
936 
937 module_init(iblock_module_init);
938 module_exit(iblock_module_exit);
939