xref: /freebsd/sys/cam/ctl/ctl_backend_block.c (revision bbb29a3c0f2c4565eff6fda70426807b6ed97f8b)
1 /*-
2  * Copyright (c) 2003 Silicon Graphics International Corp.
3  * Copyright (c) 2009-2011 Spectra Logic Corporation
4  * Copyright (c) 2012 The FreeBSD Foundation
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl_backend_block.c#5 $
36  */
37 /*
38  * CAM Target Layer driver backend for block devices.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/types.h>
49 #include <sys/kthread.h>
50 #include <sys/bio.h>
51 #include <sys/fcntl.h>
52 #include <sys/limits.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/condvar.h>
56 #include <sys/malloc.h>
57 #include <sys/conf.h>
58 #include <sys/ioccom.h>
59 #include <sys/queue.h>
60 #include <sys/sbuf.h>
61 #include <sys/endian.h>
62 #include <sys/uio.h>
63 #include <sys/buf.h>
64 #include <sys/taskqueue.h>
65 #include <sys/vnode.h>
66 #include <sys/namei.h>
67 #include <sys/mount.h>
68 #include <sys/disk.h>
69 #include <sys/fcntl.h>
70 #include <sys/filedesc.h>
71 #include <sys/filio.h>
72 #include <sys/proc.h>
73 #include <sys/pcpu.h>
74 #include <sys/module.h>
75 #include <sys/sdt.h>
76 #include <sys/devicestat.h>
77 #include <sys/sysctl.h>
78 
79 #include <geom/geom.h>
80 
81 #include <cam/cam.h>
82 #include <cam/scsi/scsi_all.h>
83 #include <cam/scsi/scsi_da.h>
84 #include <cam/ctl/ctl_io.h>
85 #include <cam/ctl/ctl.h>
86 #include <cam/ctl/ctl_backend.h>
87 #include <cam/ctl/ctl_frontend_internal.h>
88 #include <cam/ctl/ctl_ioctl.h>
89 #include <cam/ctl/ctl_scsi_all.h>
90 #include <cam/ctl/ctl_error.h>
91 
92 /*
93  * The idea here is that we'll allocate enough S/G space to hold a 1MB
94  * I/O.  If we get an I/O larger than that, we'll split it.
95  */
96 #define	CTLBLK_HALF_IO_SIZE	(512 * 1024)
97 #define	CTLBLK_MAX_IO_SIZE	(CTLBLK_HALF_IO_SIZE * 2)
98 #define	CTLBLK_MAX_SEG		MAXPHYS
99 #define	CTLBLK_HALF_SEGS	MAX(CTLBLK_HALF_IO_SIZE / CTLBLK_MAX_SEG, 1)
100 #define	CTLBLK_MAX_SEGS		(CTLBLK_HALF_SEGS * 2)
101 
102 #ifdef CTLBLK_DEBUG
103 #define DPRINTF(fmt, args...) \
104     printf("cbb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args)
105 #else
106 #define DPRINTF(fmt, args...) do {} while(0)
107 #endif
108 
109 #define PRIV(io)	\
110     ((struct ctl_ptr_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_BACKEND])
111 #define ARGS(io)	\
112     ((struct ctl_lba_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_LBA_LEN])
113 
114 SDT_PROVIDER_DEFINE(cbb);
115 
116 typedef enum {
117 	CTL_BE_BLOCK_LUN_UNCONFIGURED	= 0x01,
118 	CTL_BE_BLOCK_LUN_CONFIG_ERR	= 0x02,
119 	CTL_BE_BLOCK_LUN_WAITING	= 0x04,
120 	CTL_BE_BLOCK_LUN_MULTI_THREAD	= 0x08
121 } ctl_be_block_lun_flags;
122 
123 typedef enum {
124 	CTL_BE_BLOCK_NONE,
125 	CTL_BE_BLOCK_DEV,
126 	CTL_BE_BLOCK_FILE
127 } ctl_be_block_type;
128 
129 struct ctl_be_block_devdata {
130 	struct cdev *cdev;
131 	struct cdevsw *csw;
132 	int dev_ref;
133 };
134 
135 struct ctl_be_block_filedata {
136 	struct ucred *cred;
137 };
138 
139 union ctl_be_block_bedata {
140 	struct ctl_be_block_devdata dev;
141 	struct ctl_be_block_filedata file;
142 };
143 
144 struct ctl_be_block_io;
145 struct ctl_be_block_lun;
146 
147 typedef void (*cbb_dispatch_t)(struct ctl_be_block_lun *be_lun,
148 			       struct ctl_be_block_io *beio);
149 typedef uint64_t (*cbb_getattr_t)(struct ctl_be_block_lun *be_lun,
150 				  const char *attrname);
151 
152 /*
153  * Backend LUN structure.  There is a 1:1 mapping between a block device
154  * and a backend block LUN, and between a backend block LUN and a CTL LUN.
155  */
156 struct ctl_be_block_lun {
157 	struct ctl_lun_create_params params;
158 	struct ctl_block_disk *disk;
159 	char lunname[32];
160 	char *dev_path;
161 	ctl_be_block_type dev_type;
162 	struct vnode *vn;
163 	union ctl_be_block_bedata backend;
164 	cbb_dispatch_t dispatch;
165 	cbb_dispatch_t lun_flush;
166 	cbb_dispatch_t unmap;
167 	cbb_dispatch_t get_lba_status;
168 	cbb_getattr_t getattr;
169 	uma_zone_t lun_zone;
170 	uint64_t size_blocks;
171 	uint64_t size_bytes;
172 	uint32_t blocksize;
173 	int blocksize_shift;
174 	uint16_t pblockexp;
175 	uint16_t pblockoff;
176 	struct ctl_be_block_softc *softc;
177 	struct devstat *disk_stats;
178 	ctl_be_block_lun_flags flags;
179 	STAILQ_ENTRY(ctl_be_block_lun) links;
180 	struct ctl_be_lun ctl_be_lun;
181 	struct taskqueue *io_taskqueue;
182 	struct task io_task;
183 	int num_threads;
184 	STAILQ_HEAD(, ctl_io_hdr) input_queue;
185 	STAILQ_HEAD(, ctl_io_hdr) config_read_queue;
186 	STAILQ_HEAD(, ctl_io_hdr) config_write_queue;
187 	STAILQ_HEAD(, ctl_io_hdr) datamove_queue;
188 	struct mtx_padalign io_lock;
189 	struct mtx_padalign queue_lock;
190 };
191 
192 /*
193  * Overall softc structure for the block backend module.
194  */
195 struct ctl_be_block_softc {
196 	struct mtx			 lock;
197 	int				 num_disks;
198 	STAILQ_HEAD(, ctl_block_disk)	 disk_list;
199 	int				 num_luns;
200 	STAILQ_HEAD(, ctl_be_block_lun)	 lun_list;
201 };
202 
203 static struct ctl_be_block_softc backend_block_softc;
204 
205 /*
206  * Per-I/O information.
207  */
208 struct ctl_be_block_io {
209 	union ctl_io			*io;
210 	struct ctl_sg_entry		sg_segs[CTLBLK_MAX_SEGS];
211 	struct iovec			xiovecs[CTLBLK_MAX_SEGS];
212 	int				bio_cmd;
213 	int				num_segs;
214 	int				num_bios_sent;
215 	int				num_bios_done;
216 	int				send_complete;
217 	int				num_errors;
218 	struct bintime			ds_t0;
219 	devstat_tag_type		ds_tag_type;
220 	devstat_trans_flags		ds_trans_type;
221 	uint64_t			io_len;
222 	uint64_t			io_offset;
223 	struct ctl_be_block_softc	*softc;
224 	struct ctl_be_block_lun		*lun;
225 	void (*beio_cont)(struct ctl_be_block_io *beio); /* to continue processing */
226 };
227 
228 static int cbb_num_threads = 14;
229 SYSCTL_NODE(_kern_cam_ctl, OID_AUTO, block, CTLFLAG_RD, 0,
230 	    "CAM Target Layer Block Backend");
231 SYSCTL_INT(_kern_cam_ctl_block, OID_AUTO, num_threads, CTLFLAG_RWTUN,
232            &cbb_num_threads, 0, "Number of threads per backing file");
233 
234 static struct ctl_be_block_io *ctl_alloc_beio(struct ctl_be_block_softc *softc);
235 static void ctl_free_beio(struct ctl_be_block_io *beio);
236 static void ctl_complete_beio(struct ctl_be_block_io *beio);
237 static int ctl_be_block_move_done(union ctl_io *io);
238 static void ctl_be_block_biodone(struct bio *bio);
239 static void ctl_be_block_flush_file(struct ctl_be_block_lun *be_lun,
240 				    struct ctl_be_block_io *beio);
241 static void ctl_be_block_dispatch_file(struct ctl_be_block_lun *be_lun,
242 				       struct ctl_be_block_io *beio);
243 static void ctl_be_block_gls_file(struct ctl_be_block_lun *be_lun,
244 				  struct ctl_be_block_io *beio);
245 static uint64_t ctl_be_block_getattr_file(struct ctl_be_block_lun *be_lun,
246 					 const char *attrname);
247 static void ctl_be_block_flush_dev(struct ctl_be_block_lun *be_lun,
248 				   struct ctl_be_block_io *beio);
249 static void ctl_be_block_unmap_dev(struct ctl_be_block_lun *be_lun,
250 				   struct ctl_be_block_io *beio);
251 static void ctl_be_block_dispatch_dev(struct ctl_be_block_lun *be_lun,
252 				      struct ctl_be_block_io *beio);
253 static uint64_t ctl_be_block_getattr_dev(struct ctl_be_block_lun *be_lun,
254 					 const char *attrname);
255 static void ctl_be_block_cr_dispatch(struct ctl_be_block_lun *be_lun,
256 				    union ctl_io *io);
257 static void ctl_be_block_cw_dispatch(struct ctl_be_block_lun *be_lun,
258 				    union ctl_io *io);
259 static void ctl_be_block_dispatch(struct ctl_be_block_lun *be_lun,
260 				  union ctl_io *io);
261 static void ctl_be_block_worker(void *context, int pending);
262 static int ctl_be_block_submit(union ctl_io *io);
263 static int ctl_be_block_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
264 				   int flag, struct thread *td);
265 static int ctl_be_block_open_file(struct ctl_be_block_lun *be_lun,
266 				  struct ctl_lun_req *req);
267 static int ctl_be_block_open_dev(struct ctl_be_block_lun *be_lun,
268 				 struct ctl_lun_req *req);
269 static int ctl_be_block_close(struct ctl_be_block_lun *be_lun);
270 static int ctl_be_block_open(struct ctl_be_block_softc *softc,
271 			     struct ctl_be_block_lun *be_lun,
272 			     struct ctl_lun_req *req);
273 static int ctl_be_block_create(struct ctl_be_block_softc *softc,
274 			       struct ctl_lun_req *req);
275 static int ctl_be_block_rm(struct ctl_be_block_softc *softc,
276 			   struct ctl_lun_req *req);
277 static int ctl_be_block_modify_file(struct ctl_be_block_lun *be_lun,
278 				  struct ctl_lun_req *req);
279 static int ctl_be_block_modify_dev(struct ctl_be_block_lun *be_lun,
280 				 struct ctl_lun_req *req);
281 static int ctl_be_block_modify(struct ctl_be_block_softc *softc,
282 			   struct ctl_lun_req *req);
283 static void ctl_be_block_lun_shutdown(void *be_lun);
284 static void ctl_be_block_lun_config_status(void *be_lun,
285 					   ctl_lun_config_status status);
286 static int ctl_be_block_config_write(union ctl_io *io);
287 static int ctl_be_block_config_read(union ctl_io *io);
288 static int ctl_be_block_lun_info(void *be_lun, struct sbuf *sb);
289 static uint64_t ctl_be_block_lun_attr(void *be_lun, const char *attrname);
290 int ctl_be_block_init(void);
291 
292 static struct ctl_backend_driver ctl_be_block_driver =
293 {
294 	.name = "block",
295 	.flags = CTL_BE_FLAG_HAS_CONFIG,
296 	.init = ctl_be_block_init,
297 	.data_submit = ctl_be_block_submit,
298 	.data_move_done = ctl_be_block_move_done,
299 	.config_read = ctl_be_block_config_read,
300 	.config_write = ctl_be_block_config_write,
301 	.ioctl = ctl_be_block_ioctl,
302 	.lun_info = ctl_be_block_lun_info,
303 	.lun_attr = ctl_be_block_lun_attr
304 };
305 
306 MALLOC_DEFINE(M_CTLBLK, "ctlblk", "Memory used for CTL block backend");
307 CTL_BACKEND_DECLARE(cbb, ctl_be_block_driver);
308 
309 static uma_zone_t beio_zone;
310 
311 static struct ctl_be_block_io *
312 ctl_alloc_beio(struct ctl_be_block_softc *softc)
313 {
314 	struct ctl_be_block_io *beio;
315 
316 	beio = uma_zalloc(beio_zone, M_WAITOK | M_ZERO);
317 	beio->softc = softc;
318 	return (beio);
319 }
320 
321 static void
322 ctl_free_beio(struct ctl_be_block_io *beio)
323 {
324 	int duplicate_free;
325 	int i;
326 
327 	duplicate_free = 0;
328 
329 	for (i = 0; i < beio->num_segs; i++) {
330 		if (beio->sg_segs[i].addr == NULL)
331 			duplicate_free++;
332 
333 		uma_zfree(beio->lun->lun_zone, beio->sg_segs[i].addr);
334 		beio->sg_segs[i].addr = NULL;
335 
336 		/* For compare we had two equal S/G lists. */
337 		if (ARGS(beio->io)->flags & CTL_LLF_COMPARE) {
338 			uma_zfree(beio->lun->lun_zone,
339 			    beio->sg_segs[i + CTLBLK_HALF_SEGS].addr);
340 			beio->sg_segs[i + CTLBLK_HALF_SEGS].addr = NULL;
341 		}
342 	}
343 
344 	if (duplicate_free > 0) {
345 		printf("%s: %d duplicate frees out of %d segments\n", __func__,
346 		       duplicate_free, beio->num_segs);
347 	}
348 
349 	uma_zfree(beio_zone, beio);
350 }
351 
352 static void
353 ctl_complete_beio(struct ctl_be_block_io *beio)
354 {
355 	union ctl_io *io = beio->io;
356 
357 	if (beio->beio_cont != NULL) {
358 		beio->beio_cont(beio);
359 	} else {
360 		ctl_free_beio(beio);
361 		ctl_data_submit_done(io);
362 	}
363 }
364 
365 static int
366 ctl_be_block_move_done(union ctl_io *io)
367 {
368 	struct ctl_be_block_io *beio;
369 	struct ctl_be_block_lun *be_lun;
370 	struct ctl_lba_len_flags *lbalen;
371 #ifdef CTL_TIME_IO
372 	struct bintime cur_bt;
373 #endif
374 	int i;
375 
376 	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
377 	be_lun = beio->lun;
378 
379 	DPRINTF("entered\n");
380 
381 #ifdef CTL_TIME_IO
382 	getbintime(&cur_bt);
383 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
384 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
385 	io->io_hdr.num_dmas++;
386 #endif
387 	io->scsiio.kern_rel_offset += io->scsiio.kern_data_len;
388 
389 	/*
390 	 * We set status at this point for read commands, and write
391 	 * commands with errors.
392 	 */
393 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
394 		;
395 	} else if ((io->io_hdr.port_status == 0) &&
396 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)) {
397 		lbalen = ARGS(beio->io);
398 		if (lbalen->flags & CTL_LLF_READ) {
399 			ctl_set_success(&io->scsiio);
400 		} else if (lbalen->flags & CTL_LLF_COMPARE) {
401 			/* We have two data blocks ready for comparison. */
402 			for (i = 0; i < beio->num_segs; i++) {
403 				if (memcmp(beio->sg_segs[i].addr,
404 				    beio->sg_segs[i + CTLBLK_HALF_SEGS].addr,
405 				    beio->sg_segs[i].len) != 0)
406 					break;
407 			}
408 			if (i < beio->num_segs)
409 				ctl_set_sense(&io->scsiio,
410 				    /*current_error*/ 1,
411 				    /*sense_key*/ SSD_KEY_MISCOMPARE,
412 				    /*asc*/ 0x1D,
413 				    /*ascq*/ 0x00,
414 				    SSD_ELEM_NONE);
415 			else
416 				ctl_set_success(&io->scsiio);
417 		}
418 	} else if ((io->io_hdr.port_status != 0) &&
419 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
420 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
421 		/*
422 		 * For hardware error sense keys, the sense key
423 		 * specific value is defined to be a retry count,
424 		 * but we use it to pass back an internal FETD
425 		 * error code.  XXX KDM  Hopefully the FETD is only
426 		 * using 16 bits for an error code, since that's
427 		 * all the space we have in the sks field.
428 		 */
429 		ctl_set_internal_failure(&io->scsiio,
430 					 /*sks_valid*/ 1,
431 					 /*retry_count*/
432 					 io->io_hdr.port_status);
433 	}
434 
435 	/*
436 	 * If this is a read, or a write with errors, it is done.
437 	 */
438 	if ((beio->bio_cmd == BIO_READ)
439 	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)
440 	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)) {
441 		ctl_complete_beio(beio);
442 		return (0);
443 	}
444 
445 	/*
446 	 * At this point, we have a write and the DMA completed
447 	 * successfully.  We now have to queue it to the task queue to
448 	 * execute the backend I/O.  That is because we do blocking
449 	 * memory allocations, and in the file backing case, blocking I/O.
450 	 * This move done routine is generally called in the SIM's
451 	 * interrupt context, and therefore we cannot block.
452 	 */
453 	mtx_lock(&be_lun->queue_lock);
454 	/*
455 	 * XXX KDM make sure that links is okay to use at this point.
456 	 * Otherwise, we either need to add another field to ctl_io_hdr,
457 	 * or deal with resource allocation here.
458 	 */
459 	STAILQ_INSERT_TAIL(&be_lun->datamove_queue, &io->io_hdr, links);
460 	mtx_unlock(&be_lun->queue_lock);
461 
462 	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
463 
464 	return (0);
465 }
466 
467 static void
468 ctl_be_block_biodone(struct bio *bio)
469 {
470 	struct ctl_be_block_io *beio;
471 	struct ctl_be_block_lun *be_lun;
472 	union ctl_io *io;
473 	int error;
474 
475 	beio = bio->bio_caller1;
476 	be_lun = beio->lun;
477 	io = beio->io;
478 
479 	DPRINTF("entered\n");
480 
481 	error = bio->bio_error;
482 	mtx_lock(&be_lun->io_lock);
483 	if (error != 0)
484 		beio->num_errors++;
485 
486 	beio->num_bios_done++;
487 
488 	/*
489 	 * XXX KDM will this cause WITNESS to complain?  Holding a lock
490 	 * during the free might cause it to complain.
491 	 */
492 	g_destroy_bio(bio);
493 
494 	/*
495 	 * If the send complete bit isn't set, or we aren't the last I/O to
496 	 * complete, then we're done.
497 	 */
498 	if ((beio->send_complete == 0)
499 	 || (beio->num_bios_done < beio->num_bios_sent)) {
500 		mtx_unlock(&be_lun->io_lock);
501 		return;
502 	}
503 
504 	/*
505 	 * At this point, we've verified that we are the last I/O to
506 	 * complete, so it's safe to drop the lock.
507 	 */
508 	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
509 	    beio->ds_tag_type, beio->ds_trans_type,
510 	    /*now*/ NULL, /*then*/&beio->ds_t0);
511 	mtx_unlock(&be_lun->io_lock);
512 
513 	/*
514 	 * If there are any errors from the backing device, we fail the
515 	 * entire I/O with a medium error.
516 	 */
517 	if (beio->num_errors > 0) {
518 		if (error == EOPNOTSUPP) {
519 			ctl_set_invalid_opcode(&io->scsiio);
520 		} else if (error == ENOSPC) {
521 			ctl_set_space_alloc_fail(&io->scsiio);
522 		} else if (beio->bio_cmd == BIO_FLUSH) {
523 			/* XXX KDM is there is a better error here? */
524 			ctl_set_internal_failure(&io->scsiio,
525 						 /*sks_valid*/ 1,
526 						 /*retry_count*/ 0xbad2);
527 		} else
528 			ctl_set_medium_error(&io->scsiio);
529 		ctl_complete_beio(beio);
530 		return;
531 	}
532 
533 	/*
534 	 * If this is a write, a flush, a delete or verify, we're all done.
535 	 * If this is a read, we can now send the data to the user.
536 	 */
537 	if ((beio->bio_cmd == BIO_WRITE)
538 	 || (beio->bio_cmd == BIO_FLUSH)
539 	 || (beio->bio_cmd == BIO_DELETE)
540 	 || (ARGS(io)->flags & CTL_LLF_VERIFY)) {
541 		ctl_set_success(&io->scsiio);
542 		ctl_complete_beio(beio);
543 	} else {
544 		if ((ARGS(io)->flags & CTL_LLF_READ) &&
545 		    beio->beio_cont == NULL)
546 			ctl_set_success(&io->scsiio);
547 #ifdef CTL_TIME_IO
548         	getbintime(&io->io_hdr.dma_start_bt);
549 #endif
550 		ctl_datamove(io);
551 	}
552 }
553 
554 static void
555 ctl_be_block_flush_file(struct ctl_be_block_lun *be_lun,
556 			struct ctl_be_block_io *beio)
557 {
558 	union ctl_io *io = beio->io;
559 	struct mount *mountpoint;
560 	int error, lock_flags;
561 
562 	DPRINTF("entered\n");
563 
564 	binuptime(&beio->ds_t0);
565 	mtx_lock(&be_lun->io_lock);
566 	devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
567 	mtx_unlock(&be_lun->io_lock);
568 
569 	(void) vn_start_write(be_lun->vn, &mountpoint, V_WAIT);
570 
571 	if (MNT_SHARED_WRITES(mountpoint)
572 	 || ((mountpoint == NULL)
573 	  && MNT_SHARED_WRITES(be_lun->vn->v_mount)))
574 		lock_flags = LK_SHARED;
575 	else
576 		lock_flags = LK_EXCLUSIVE;
577 
578 	vn_lock(be_lun->vn, lock_flags | LK_RETRY);
579 
580 	error = VOP_FSYNC(be_lun->vn, MNT_WAIT, curthread);
581 	VOP_UNLOCK(be_lun->vn, 0);
582 
583 	vn_finished_write(mountpoint);
584 
585 	mtx_lock(&be_lun->io_lock);
586 	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
587 	    beio->ds_tag_type, beio->ds_trans_type,
588 	    /*now*/ NULL, /*then*/&beio->ds_t0);
589 	mtx_unlock(&be_lun->io_lock);
590 
591 	if (error == 0)
592 		ctl_set_success(&io->scsiio);
593 	else {
594 		/* XXX KDM is there is a better error here? */
595 		ctl_set_internal_failure(&io->scsiio,
596 					 /*sks_valid*/ 1,
597 					 /*retry_count*/ 0xbad1);
598 	}
599 
600 	ctl_complete_beio(beio);
601 }
602 
603 SDT_PROBE_DEFINE1(cbb, kernel, read, file_start, "uint64_t");
604 SDT_PROBE_DEFINE1(cbb, kernel, write, file_start, "uint64_t");
605 SDT_PROBE_DEFINE1(cbb, kernel, read, file_done,"uint64_t");
606 SDT_PROBE_DEFINE1(cbb, kernel, write, file_done, "uint64_t");
607 
608 static void
609 ctl_be_block_dispatch_file(struct ctl_be_block_lun *be_lun,
610 			   struct ctl_be_block_io *beio)
611 {
612 	struct ctl_be_block_filedata *file_data;
613 	union ctl_io *io;
614 	struct uio xuio;
615 	struct iovec *xiovec;
616 	int flags;
617 	int error, i;
618 
619 	DPRINTF("entered\n");
620 
621 	file_data = &be_lun->backend.file;
622 	io = beio->io;
623 	flags = 0;
624 	if (ARGS(io)->flags & CTL_LLF_DPO)
625 		flags |= IO_DIRECT;
626 	if (beio->bio_cmd == BIO_WRITE && ARGS(io)->flags & CTL_LLF_FUA)
627 		flags |= IO_SYNC;
628 
629 	bzero(&xuio, sizeof(xuio));
630 	if (beio->bio_cmd == BIO_READ) {
631 		SDT_PROBE(cbb, kernel, read, file_start, 0, 0, 0, 0, 0);
632 		xuio.uio_rw = UIO_READ;
633 	} else {
634 		SDT_PROBE(cbb, kernel, write, file_start, 0, 0, 0, 0, 0);
635 		xuio.uio_rw = UIO_WRITE;
636 	}
637 	xuio.uio_offset = beio->io_offset;
638 	xuio.uio_resid = beio->io_len;
639 	xuio.uio_segflg = UIO_SYSSPACE;
640 	xuio.uio_iov = beio->xiovecs;
641 	xuio.uio_iovcnt = beio->num_segs;
642 	xuio.uio_td = curthread;
643 
644 	for (i = 0, xiovec = xuio.uio_iov; i < xuio.uio_iovcnt; i++, xiovec++) {
645 		xiovec->iov_base = beio->sg_segs[i].addr;
646 		xiovec->iov_len = beio->sg_segs[i].len;
647 	}
648 
649 	binuptime(&beio->ds_t0);
650 	mtx_lock(&be_lun->io_lock);
651 	devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
652 	mtx_unlock(&be_lun->io_lock);
653 
654 	if (beio->bio_cmd == BIO_READ) {
655 		vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
656 
657 		/*
658 		 * UFS pays attention to IO_DIRECT for reads.  If the
659 		 * DIRECTIO option is configured into the kernel, it calls
660 		 * ffs_rawread().  But that only works for single-segment
661 		 * uios with user space addresses.  In our case, with a
662 		 * kernel uio, it still reads into the buffer cache, but it
663 		 * will just try to release the buffer from the cache later
664 		 * on in ffs_read().
665 		 *
666 		 * ZFS does not pay attention to IO_DIRECT for reads.
667 		 *
668 		 * UFS does not pay attention to IO_SYNC for reads.
669 		 *
670 		 * ZFS pays attention to IO_SYNC (which translates into the
671 		 * Solaris define FRSYNC for zfs_read()) for reads.  It
672 		 * attempts to sync the file before reading.
673 		 *
674 		 * So, to attempt to provide some barrier semantics in the
675 		 * BIO_ORDERED case, set both IO_DIRECT and IO_SYNC.
676 		 */
677 		error = VOP_READ(be_lun->vn, &xuio, flags, file_data->cred);
678 
679 		VOP_UNLOCK(be_lun->vn, 0);
680 		SDT_PROBE(cbb, kernel, read, file_done, 0, 0, 0, 0, 0);
681 	} else {
682 		struct mount *mountpoint;
683 		int lock_flags;
684 
685 		(void)vn_start_write(be_lun->vn, &mountpoint, V_WAIT);
686 
687 		if (MNT_SHARED_WRITES(mountpoint)
688 		 || ((mountpoint == NULL)
689 		  && MNT_SHARED_WRITES(be_lun->vn->v_mount)))
690 			lock_flags = LK_SHARED;
691 		else
692 			lock_flags = LK_EXCLUSIVE;
693 
694 		vn_lock(be_lun->vn, lock_flags | LK_RETRY);
695 
696 		/*
697 		 * UFS pays attention to IO_DIRECT for writes.  The write
698 		 * is done asynchronously.  (Normally the write would just
699 		 * get put into cache.
700 		 *
701 		 * UFS pays attention to IO_SYNC for writes.  It will
702 		 * attempt to write the buffer out synchronously if that
703 		 * flag is set.
704 		 *
705 		 * ZFS does not pay attention to IO_DIRECT for writes.
706 		 *
707 		 * ZFS pays attention to IO_SYNC (a.k.a. FSYNC or FRSYNC)
708 		 * for writes.  It will flush the transaction from the
709 		 * cache before returning.
710 		 *
711 		 * So if we've got the BIO_ORDERED flag set, we want
712 		 * IO_SYNC in either the UFS or ZFS case.
713 		 */
714 		error = VOP_WRITE(be_lun->vn, &xuio, flags, file_data->cred);
715 		VOP_UNLOCK(be_lun->vn, 0);
716 
717 		vn_finished_write(mountpoint);
718 		SDT_PROBE(cbb, kernel, write, file_done, 0, 0, 0, 0, 0);
719         }
720 
721 	mtx_lock(&be_lun->io_lock);
722 	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
723 	    beio->ds_tag_type, beio->ds_trans_type,
724 	    /*now*/ NULL, /*then*/&beio->ds_t0);
725 	mtx_unlock(&be_lun->io_lock);
726 
727 	/*
728 	 * If we got an error, set the sense data to "MEDIUM ERROR" and
729 	 * return the I/O to the user.
730 	 */
731 	if (error != 0) {
732 		char path_str[32];
733 
734 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
735 		printf("%s%s command returned errno %d\n", path_str,
736 		       (beio->bio_cmd == BIO_READ) ? "READ" : "WRITE", error);
737 		if (error == ENOSPC) {
738 			ctl_set_space_alloc_fail(&io->scsiio);
739 		} else
740 			ctl_set_medium_error(&io->scsiio);
741 		ctl_complete_beio(beio);
742 		return;
743 	}
744 
745 	/*
746 	 * If this is a write or a verify, we're all done.
747 	 * If this is a read, we can now send the data to the user.
748 	 */
749 	if ((beio->bio_cmd == BIO_WRITE) ||
750 	    (ARGS(io)->flags & CTL_LLF_VERIFY)) {
751 		ctl_set_success(&io->scsiio);
752 		ctl_complete_beio(beio);
753 	} else {
754 		if ((ARGS(io)->flags & CTL_LLF_READ) &&
755 		    beio->beio_cont == NULL)
756 			ctl_set_success(&io->scsiio);
757 #ifdef CTL_TIME_IO
758         	getbintime(&io->io_hdr.dma_start_bt);
759 #endif
760 		ctl_datamove(io);
761 	}
762 }
763 
764 static void
765 ctl_be_block_gls_file(struct ctl_be_block_lun *be_lun,
766 			struct ctl_be_block_io *beio)
767 {
768 	union ctl_io *io = beio->io;
769 	struct ctl_lba_len_flags *lbalen = ARGS(io);
770 	struct scsi_get_lba_status_data *data;
771 	off_t roff, off;
772 	int error, status;
773 
774 	DPRINTF("entered\n");
775 
776 	off = roff = ((off_t)lbalen->lba) << be_lun->blocksize_shift;
777 	vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
778 	error = VOP_IOCTL(be_lun->vn, FIOSEEKHOLE, &off,
779 	    0, curthread->td_ucred, curthread);
780 	if (error == 0 && off > roff)
781 		status = 0;	/* mapped up to off */
782 	else {
783 		error = VOP_IOCTL(be_lun->vn, FIOSEEKDATA, &off,
784 		    0, curthread->td_ucred, curthread);
785 		if (error == 0 && off > roff)
786 			status = 1;	/* deallocated up to off */
787 		else {
788 			status = 0;	/* unknown up to the end */
789 			off = be_lun->size_bytes;
790 		}
791 	}
792 	VOP_UNLOCK(be_lun->vn, 0);
793 
794 	off >>= be_lun->blocksize_shift;
795 	data = (struct scsi_get_lba_status_data *)io->scsiio.kern_data_ptr;
796 	scsi_u64to8b(lbalen->lba, data->descr[0].addr);
797 	scsi_ulto4b(MIN(UINT32_MAX, off - lbalen->lba),
798 	    data->descr[0].length);
799 	data->descr[0].status = status;
800 
801 	ctl_complete_beio(beio);
802 }
803 
804 static uint64_t
805 ctl_be_block_getattr_file(struct ctl_be_block_lun *be_lun, const char *attrname)
806 {
807 	struct vattr		vattr;
808 	struct statfs		statfs;
809 	int			error;
810 
811 	if (be_lun->vn == NULL)
812 		return (UINT64_MAX);
813 	if (strcmp(attrname, "blocksused") == 0) {
814 		error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
815 		if (error != 0)
816 			return (UINT64_MAX);
817 		return (vattr.va_bytes >> be_lun->blocksize_shift);
818 	}
819 	if (strcmp(attrname, "blocksavail") == 0) {
820 		error = VFS_STATFS(be_lun->vn->v_mount, &statfs);
821 		if (error != 0)
822 			return (UINT64_MAX);
823 		return ((statfs.f_bavail * statfs.f_bsize) >>
824 		    be_lun->blocksize_shift);
825 	}
826 	return (UINT64_MAX);
827 }
828 
829 static void
830 ctl_be_block_dispatch_zvol(struct ctl_be_block_lun *be_lun,
831 			   struct ctl_be_block_io *beio)
832 {
833 	struct ctl_be_block_devdata *dev_data;
834 	union ctl_io *io;
835 	struct uio xuio;
836 	struct iovec *xiovec;
837 	int flags;
838 	int error, i;
839 
840 	DPRINTF("entered\n");
841 
842 	dev_data = &be_lun->backend.dev;
843 	io = beio->io;
844 	flags = 0;
845 	if (ARGS(io)->flags & CTL_LLF_DPO)
846 		flags |= IO_DIRECT;
847 	if (beio->bio_cmd == BIO_WRITE && ARGS(io)->flags & CTL_LLF_FUA)
848 		flags |= IO_SYNC;
849 
850 	bzero(&xuio, sizeof(xuio));
851 	if (beio->bio_cmd == BIO_READ) {
852 		SDT_PROBE(cbb, kernel, read, file_start, 0, 0, 0, 0, 0);
853 		xuio.uio_rw = UIO_READ;
854 	} else {
855 		SDT_PROBE(cbb, kernel, write, file_start, 0, 0, 0, 0, 0);
856 		xuio.uio_rw = UIO_WRITE;
857 	}
858 	xuio.uio_offset = beio->io_offset;
859 	xuio.uio_resid = beio->io_len;
860 	xuio.uio_segflg = UIO_SYSSPACE;
861 	xuio.uio_iov = beio->xiovecs;
862 	xuio.uio_iovcnt = beio->num_segs;
863 	xuio.uio_td = curthread;
864 
865 	for (i = 0, xiovec = xuio.uio_iov; i < xuio.uio_iovcnt; i++, xiovec++) {
866 		xiovec->iov_base = beio->sg_segs[i].addr;
867 		xiovec->iov_len = beio->sg_segs[i].len;
868 	}
869 
870 	binuptime(&beio->ds_t0);
871 	mtx_lock(&be_lun->io_lock);
872 	devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
873 	mtx_unlock(&be_lun->io_lock);
874 
875 	if (beio->bio_cmd == BIO_READ) {
876 		error = (*dev_data->csw->d_read)(dev_data->cdev, &xuio, flags);
877 		SDT_PROBE(cbb, kernel, read, file_done, 0, 0, 0, 0, 0);
878 	} else {
879 		error = (*dev_data->csw->d_write)(dev_data->cdev, &xuio, flags);
880 		SDT_PROBE(cbb, kernel, write, file_done, 0, 0, 0, 0, 0);
881 	}
882 
883 	mtx_lock(&be_lun->io_lock);
884 	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
885 	    beio->ds_tag_type, beio->ds_trans_type,
886 	    /*now*/ NULL, /*then*/&beio->ds_t0);
887 	mtx_unlock(&be_lun->io_lock);
888 
889 	/*
890 	 * If we got an error, set the sense data to "MEDIUM ERROR" and
891 	 * return the I/O to the user.
892 	 */
893 	if (error != 0) {
894 		if (error == ENOSPC) {
895 			ctl_set_space_alloc_fail(&io->scsiio);
896 		} else
897 			ctl_set_medium_error(&io->scsiio);
898 		ctl_complete_beio(beio);
899 		return;
900 	}
901 
902 	/*
903 	 * If this is a write or a verify, we're all done.
904 	 * If this is a read, we can now send the data to the user.
905 	 */
906 	if ((beio->bio_cmd == BIO_WRITE) ||
907 	    (ARGS(io)->flags & CTL_LLF_VERIFY)) {
908 		ctl_set_success(&io->scsiio);
909 		ctl_complete_beio(beio);
910 	} else {
911 		if ((ARGS(io)->flags & CTL_LLF_READ) &&
912 		    beio->beio_cont == NULL)
913 			ctl_set_success(&io->scsiio);
914 #ifdef CTL_TIME_IO
915         	getbintime(&io->io_hdr.dma_start_bt);
916 #endif
917 		ctl_datamove(io);
918 	}
919 }
920 
921 static void
922 ctl_be_block_gls_zvol(struct ctl_be_block_lun *be_lun,
923 			struct ctl_be_block_io *beio)
924 {
925 	struct ctl_be_block_devdata *dev_data = &be_lun->backend.dev;
926 	union ctl_io *io = beio->io;
927 	struct ctl_lba_len_flags *lbalen = ARGS(io);
928 	struct scsi_get_lba_status_data *data;
929 	off_t roff, off;
930 	int error, status;
931 
932 	DPRINTF("entered\n");
933 
934 	off = roff = ((off_t)lbalen->lba) << be_lun->blocksize_shift;
935 	error = (*dev_data->csw->d_ioctl)(dev_data->cdev, FIOSEEKHOLE,
936 	    (caddr_t)&off, FREAD, curthread);
937 	if (error == 0 && off > roff)
938 		status = 0;	/* mapped up to off */
939 	else {
940 		error = (*dev_data->csw->d_ioctl)(dev_data->cdev, FIOSEEKDATA,
941 		    (caddr_t)&off, FREAD, curthread);
942 		if (error == 0 && off > roff)
943 			status = 1;	/* deallocated up to off */
944 		else {
945 			status = 0;	/* unknown up to the end */
946 			off = be_lun->size_bytes;
947 		}
948 	}
949 
950 	off >>= be_lun->blocksize_shift;
951 	data = (struct scsi_get_lba_status_data *)io->scsiio.kern_data_ptr;
952 	scsi_u64to8b(lbalen->lba, data->descr[0].addr);
953 	scsi_ulto4b(MIN(UINT32_MAX, off - lbalen->lba),
954 	    data->descr[0].length);
955 	data->descr[0].status = status;
956 
957 	ctl_complete_beio(beio);
958 }
959 
960 static void
961 ctl_be_block_flush_dev(struct ctl_be_block_lun *be_lun,
962 		       struct ctl_be_block_io *beio)
963 {
964 	struct bio *bio;
965 	union ctl_io *io;
966 	struct ctl_be_block_devdata *dev_data;
967 
968 	dev_data = &be_lun->backend.dev;
969 	io = beio->io;
970 
971 	DPRINTF("entered\n");
972 
973 	/* This can't fail, it's a blocking allocation. */
974 	bio = g_alloc_bio();
975 
976 	bio->bio_cmd	    = BIO_FLUSH;
977 	bio->bio_flags	   |= BIO_ORDERED;
978 	bio->bio_dev	    = dev_data->cdev;
979 	bio->bio_offset	    = 0;
980 	bio->bio_data	    = 0;
981 	bio->bio_done	    = ctl_be_block_biodone;
982 	bio->bio_caller1    = beio;
983 	bio->bio_pblkno	    = 0;
984 
985 	/*
986 	 * We don't need to acquire the LUN lock here, because we are only
987 	 * sending one bio, and so there is no other context to synchronize
988 	 * with.
989 	 */
990 	beio->num_bios_sent = 1;
991 	beio->send_complete = 1;
992 
993 	binuptime(&beio->ds_t0);
994 	mtx_lock(&be_lun->io_lock);
995 	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
996 	mtx_unlock(&be_lun->io_lock);
997 
998 	(*dev_data->csw->d_strategy)(bio);
999 }
1000 
1001 static void
1002 ctl_be_block_unmap_dev_range(struct ctl_be_block_lun *be_lun,
1003 		       struct ctl_be_block_io *beio,
1004 		       uint64_t off, uint64_t len, int last)
1005 {
1006 	struct bio *bio;
1007 	struct ctl_be_block_devdata *dev_data;
1008 	uint64_t maxlen;
1009 
1010 	dev_data = &be_lun->backend.dev;
1011 	maxlen = LONG_MAX - (LONG_MAX % be_lun->blocksize);
1012 	while (len > 0) {
1013 		bio = g_alloc_bio();
1014 		bio->bio_cmd	    = BIO_DELETE;
1015 		bio->bio_dev	    = dev_data->cdev;
1016 		bio->bio_offset	    = off;
1017 		bio->bio_length	    = MIN(len, maxlen);
1018 		bio->bio_data	    = 0;
1019 		bio->bio_done	    = ctl_be_block_biodone;
1020 		bio->bio_caller1    = beio;
1021 		bio->bio_pblkno     = off / be_lun->blocksize;
1022 
1023 		off += bio->bio_length;
1024 		len -= bio->bio_length;
1025 
1026 		mtx_lock(&be_lun->io_lock);
1027 		beio->num_bios_sent++;
1028 		if (last && len == 0)
1029 			beio->send_complete = 1;
1030 		mtx_unlock(&be_lun->io_lock);
1031 
1032 		(*dev_data->csw->d_strategy)(bio);
1033 	}
1034 }
1035 
1036 static void
1037 ctl_be_block_unmap_dev(struct ctl_be_block_lun *be_lun,
1038 		       struct ctl_be_block_io *beio)
1039 {
1040 	union ctl_io *io;
1041 	struct ctl_be_block_devdata *dev_data;
1042 	struct ctl_ptr_len_flags *ptrlen;
1043 	struct scsi_unmap_desc *buf, *end;
1044 	uint64_t len;
1045 
1046 	dev_data = &be_lun->backend.dev;
1047 	io = beio->io;
1048 
1049 	DPRINTF("entered\n");
1050 
1051 	binuptime(&beio->ds_t0);
1052 	mtx_lock(&be_lun->io_lock);
1053 	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
1054 	mtx_unlock(&be_lun->io_lock);
1055 
1056 	if (beio->io_offset == -1) {
1057 		beio->io_len = 0;
1058 		ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1059 		buf = (struct scsi_unmap_desc *)ptrlen->ptr;
1060 		end = buf + ptrlen->len / sizeof(*buf);
1061 		for (; buf < end; buf++) {
1062 			len = (uint64_t)scsi_4btoul(buf->length) *
1063 			    be_lun->blocksize;
1064 			beio->io_len += len;
1065 			ctl_be_block_unmap_dev_range(be_lun, beio,
1066 			    scsi_8btou64(buf->lba) * be_lun->blocksize, len,
1067 			    (end - buf < 2) ? TRUE : FALSE);
1068 		}
1069 	} else
1070 		ctl_be_block_unmap_dev_range(be_lun, beio,
1071 		    beio->io_offset, beio->io_len, TRUE);
1072 }
1073 
1074 static void
1075 ctl_be_block_dispatch_dev(struct ctl_be_block_lun *be_lun,
1076 			  struct ctl_be_block_io *beio)
1077 {
1078 	TAILQ_HEAD(, bio) queue = TAILQ_HEAD_INITIALIZER(queue);
1079 	int i;
1080 	struct bio *bio;
1081 	struct ctl_be_block_devdata *dev_data;
1082 	off_t cur_offset;
1083 	int max_iosize;
1084 
1085 	DPRINTF("entered\n");
1086 
1087 	dev_data = &be_lun->backend.dev;
1088 
1089 	/*
1090 	 * We have to limit our I/O size to the maximum supported by the
1091 	 * backend device.  Hopefully it is MAXPHYS.  If the driver doesn't
1092 	 * set it properly, use DFLTPHYS.
1093 	 */
1094 	max_iosize = dev_data->cdev->si_iosize_max;
1095 	if (max_iosize < PAGE_SIZE)
1096 		max_iosize = DFLTPHYS;
1097 
1098 	cur_offset = beio->io_offset;
1099 	for (i = 0; i < beio->num_segs; i++) {
1100 		size_t cur_size;
1101 		uint8_t *cur_ptr;
1102 
1103 		cur_size = beio->sg_segs[i].len;
1104 		cur_ptr = beio->sg_segs[i].addr;
1105 
1106 		while (cur_size > 0) {
1107 			/* This can't fail, it's a blocking allocation. */
1108 			bio = g_alloc_bio();
1109 
1110 			KASSERT(bio != NULL, ("g_alloc_bio() failed!\n"));
1111 
1112 			bio->bio_cmd = beio->bio_cmd;
1113 			bio->bio_dev = dev_data->cdev;
1114 			bio->bio_caller1 = beio;
1115 			bio->bio_length = min(cur_size, max_iosize);
1116 			bio->bio_offset = cur_offset;
1117 			bio->bio_data = cur_ptr;
1118 			bio->bio_done = ctl_be_block_biodone;
1119 			bio->bio_pblkno = cur_offset / be_lun->blocksize;
1120 
1121 			cur_offset += bio->bio_length;
1122 			cur_ptr += bio->bio_length;
1123 			cur_size -= bio->bio_length;
1124 
1125 			TAILQ_INSERT_TAIL(&queue, bio, bio_queue);
1126 			beio->num_bios_sent++;
1127 		}
1128 	}
1129 	binuptime(&beio->ds_t0);
1130 	mtx_lock(&be_lun->io_lock);
1131 	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
1132 	beio->send_complete = 1;
1133 	mtx_unlock(&be_lun->io_lock);
1134 
1135 	/*
1136 	 * Fire off all allocated requests!
1137 	 */
1138 	while ((bio = TAILQ_FIRST(&queue)) != NULL) {
1139 		TAILQ_REMOVE(&queue, bio, bio_queue);
1140 		(*dev_data->csw->d_strategy)(bio);
1141 	}
1142 }
1143 
1144 static uint64_t
1145 ctl_be_block_getattr_dev(struct ctl_be_block_lun *be_lun, const char *attrname)
1146 {
1147 	struct ctl_be_block_devdata	*dev_data = &be_lun->backend.dev;
1148 	struct diocgattr_arg	arg;
1149 	int			error;
1150 
1151 	if (dev_data->csw == NULL || dev_data->csw->d_ioctl == NULL)
1152 		return (UINT64_MAX);
1153 	strlcpy(arg.name, attrname, sizeof(arg.name));
1154 	arg.len = sizeof(arg.value.off);
1155 	error = dev_data->csw->d_ioctl(dev_data->cdev,
1156 	    DIOCGATTR, (caddr_t)&arg, FREAD, curthread);
1157 	if (error != 0)
1158 		return (UINT64_MAX);
1159 	return (arg.value.off);
1160 }
1161 
1162 static void
1163 ctl_be_block_cw_done_ws(struct ctl_be_block_io *beio)
1164 {
1165 	union ctl_io *io;
1166 
1167 	io = beio->io;
1168 	ctl_free_beio(beio);
1169 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
1170 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
1171 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
1172 		ctl_config_write_done(io);
1173 		return;
1174 	}
1175 
1176 	ctl_be_block_config_write(io);
1177 }
1178 
1179 static void
1180 ctl_be_block_cw_dispatch_ws(struct ctl_be_block_lun *be_lun,
1181 			    union ctl_io *io)
1182 {
1183 	struct ctl_be_block_io *beio;
1184 	struct ctl_be_block_softc *softc;
1185 	struct ctl_lba_len_flags *lbalen;
1186 	uint64_t len_left, lba;
1187 	int i, seglen;
1188 	uint8_t *buf, *end;
1189 
1190 	DPRINTF("entered\n");
1191 
1192 	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1193 	softc = be_lun->softc;
1194 	lbalen = ARGS(beio->io);
1195 
1196 	if (lbalen->flags & ~(SWS_LBDATA | SWS_UNMAP | SWS_ANCHOR | SWS_NDOB) ||
1197 	    (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR) && be_lun->unmap == NULL)) {
1198 		ctl_free_beio(beio);
1199 		ctl_set_invalid_field(&io->scsiio,
1200 				      /*sks_valid*/ 1,
1201 				      /*command*/ 1,
1202 				      /*field*/ 1,
1203 				      /*bit_valid*/ 0,
1204 				      /*bit*/ 0);
1205 		ctl_config_write_done(io);
1206 		return;
1207 	}
1208 
1209 	switch (io->scsiio.tag_type) {
1210 	case CTL_TAG_ORDERED:
1211 		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1212 		break;
1213 	case CTL_TAG_HEAD_OF_QUEUE:
1214 		beio->ds_tag_type = DEVSTAT_TAG_HEAD;
1215 		break;
1216 	case CTL_TAG_UNTAGGED:
1217 	case CTL_TAG_SIMPLE:
1218 	case CTL_TAG_ACA:
1219 	default:
1220 		beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1221 		break;
1222 	}
1223 
1224 	if (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR)) {
1225 		beio->io_offset = lbalen->lba * be_lun->blocksize;
1226 		beio->io_len = (uint64_t)lbalen->len * be_lun->blocksize;
1227 		beio->bio_cmd = BIO_DELETE;
1228 		beio->ds_trans_type = DEVSTAT_FREE;
1229 
1230 		be_lun->unmap(be_lun, beio);
1231 		return;
1232 	}
1233 
1234 	beio->bio_cmd = BIO_WRITE;
1235 	beio->ds_trans_type = DEVSTAT_WRITE;
1236 
1237 	DPRINTF("WRITE SAME at LBA %jx len %u\n",
1238 	       (uintmax_t)lbalen->lba, lbalen->len);
1239 
1240 	len_left = (uint64_t)lbalen->len * be_lun->blocksize;
1241 	for (i = 0, lba = 0; i < CTLBLK_MAX_SEGS && len_left > 0; i++) {
1242 
1243 		/*
1244 		 * Setup the S/G entry for this chunk.
1245 		 */
1246 		seglen = MIN(CTLBLK_MAX_SEG, len_left);
1247 		seglen -= seglen % be_lun->blocksize;
1248 		beio->sg_segs[i].len = seglen;
1249 		beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);
1250 
1251 		DPRINTF("segment %d addr %p len %zd\n", i,
1252 			beio->sg_segs[i].addr, beio->sg_segs[i].len);
1253 
1254 		beio->num_segs++;
1255 		len_left -= seglen;
1256 
1257 		buf = beio->sg_segs[i].addr;
1258 		end = buf + seglen;
1259 		for (; buf < end; buf += be_lun->blocksize) {
1260 			memcpy(buf, io->scsiio.kern_data_ptr, be_lun->blocksize);
1261 			if (lbalen->flags & SWS_LBDATA)
1262 				scsi_ulto4b(lbalen->lba + lba, buf);
1263 			lba++;
1264 		}
1265 	}
1266 
1267 	beio->io_offset = lbalen->lba * be_lun->blocksize;
1268 	beio->io_len = lba * be_lun->blocksize;
1269 
1270 	/* We can not do all in one run. Correct and schedule rerun. */
1271 	if (len_left > 0) {
1272 		lbalen->lba += lba;
1273 		lbalen->len -= lba;
1274 		beio->beio_cont = ctl_be_block_cw_done_ws;
1275 	}
1276 
1277 	be_lun->dispatch(be_lun, beio);
1278 }
1279 
1280 static void
1281 ctl_be_block_cw_dispatch_unmap(struct ctl_be_block_lun *be_lun,
1282 			    union ctl_io *io)
1283 {
1284 	struct ctl_be_block_io *beio;
1285 	struct ctl_be_block_softc *softc;
1286 	struct ctl_ptr_len_flags *ptrlen;
1287 
1288 	DPRINTF("entered\n");
1289 
1290 	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1291 	softc = be_lun->softc;
1292 	ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1293 
1294 	if ((ptrlen->flags & ~SU_ANCHOR) != 0 || be_lun->unmap == NULL) {
1295 		ctl_free_beio(beio);
1296 		ctl_set_invalid_field(&io->scsiio,
1297 				      /*sks_valid*/ 0,
1298 				      /*command*/ 1,
1299 				      /*field*/ 0,
1300 				      /*bit_valid*/ 0,
1301 				      /*bit*/ 0);
1302 		ctl_config_write_done(io);
1303 		return;
1304 	}
1305 
1306 	switch (io->scsiio.tag_type) {
1307 	case CTL_TAG_ORDERED:
1308 		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1309 		break;
1310 	case CTL_TAG_HEAD_OF_QUEUE:
1311 		beio->ds_tag_type = DEVSTAT_TAG_HEAD;
1312 		break;
1313 	case CTL_TAG_UNTAGGED:
1314 	case CTL_TAG_SIMPLE:
1315 	case CTL_TAG_ACA:
1316 	default:
1317 		beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1318 		break;
1319 	}
1320 
1321 	beio->io_len = 0;
1322 	beio->io_offset = -1;
1323 
1324 	beio->bio_cmd = BIO_DELETE;
1325 	beio->ds_trans_type = DEVSTAT_FREE;
1326 
1327 	DPRINTF("UNMAP\n");
1328 
1329 	be_lun->unmap(be_lun, beio);
1330 }
1331 
1332 static void
1333 ctl_be_block_cr_done(struct ctl_be_block_io *beio)
1334 {
1335 	union ctl_io *io;
1336 
1337 	io = beio->io;
1338 	ctl_free_beio(beio);
1339 	ctl_config_read_done(io);
1340 }
1341 
1342 static void
1343 ctl_be_block_cr_dispatch(struct ctl_be_block_lun *be_lun,
1344 			 union ctl_io *io)
1345 {
1346 	struct ctl_be_block_io *beio;
1347 	struct ctl_be_block_softc *softc;
1348 
1349 	DPRINTF("entered\n");
1350 
1351 	softc = be_lun->softc;
1352 	beio = ctl_alloc_beio(softc);
1353 	beio->io = io;
1354 	beio->lun = be_lun;
1355 	beio->beio_cont = ctl_be_block_cr_done;
1356 	PRIV(io)->ptr = (void *)beio;
1357 
1358 	switch (io->scsiio.cdb[0]) {
1359 	case SERVICE_ACTION_IN:		/* GET LBA STATUS */
1360 		beio->bio_cmd = -1;
1361 		beio->ds_trans_type = DEVSTAT_NO_DATA;
1362 		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1363 		beio->io_len = 0;
1364 		if (be_lun->get_lba_status)
1365 			be_lun->get_lba_status(be_lun, beio);
1366 		else
1367 			ctl_be_block_cr_done(beio);
1368 		break;
1369 	default:
1370 		panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
1371 		break;
1372 	}
1373 }
1374 
1375 static void
1376 ctl_be_block_cw_done(struct ctl_be_block_io *beio)
1377 {
1378 	union ctl_io *io;
1379 
1380 	io = beio->io;
1381 	ctl_free_beio(beio);
1382 	ctl_config_write_done(io);
1383 }
1384 
1385 static void
1386 ctl_be_block_cw_dispatch(struct ctl_be_block_lun *be_lun,
1387 			 union ctl_io *io)
1388 {
1389 	struct ctl_be_block_io *beio;
1390 	struct ctl_be_block_softc *softc;
1391 
1392 	DPRINTF("entered\n");
1393 
1394 	softc = be_lun->softc;
1395 	beio = ctl_alloc_beio(softc);
1396 	beio->io = io;
1397 	beio->lun = be_lun;
1398 	beio->beio_cont = ctl_be_block_cw_done;
1399 	PRIV(io)->ptr = (void *)beio;
1400 
1401 	switch (io->scsiio.cdb[0]) {
1402 	case SYNCHRONIZE_CACHE:
1403 	case SYNCHRONIZE_CACHE_16:
1404 		beio->bio_cmd = BIO_FLUSH;
1405 		beio->ds_trans_type = DEVSTAT_NO_DATA;
1406 		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1407 		beio->io_len = 0;
1408 		be_lun->lun_flush(be_lun, beio);
1409 		break;
1410 	case WRITE_SAME_10:
1411 	case WRITE_SAME_16:
1412 		ctl_be_block_cw_dispatch_ws(be_lun, io);
1413 		break;
1414 	case UNMAP:
1415 		ctl_be_block_cw_dispatch_unmap(be_lun, io);
1416 		break;
1417 	default:
1418 		panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
1419 		break;
1420 	}
1421 }
1422 
1423 SDT_PROBE_DEFINE1(cbb, kernel, read, start, "uint64_t");
1424 SDT_PROBE_DEFINE1(cbb, kernel, write, start, "uint64_t");
1425 SDT_PROBE_DEFINE1(cbb, kernel, read, alloc_done, "uint64_t");
1426 SDT_PROBE_DEFINE1(cbb, kernel, write, alloc_done, "uint64_t");
1427 
1428 static void
1429 ctl_be_block_next(struct ctl_be_block_io *beio)
1430 {
1431 	struct ctl_be_block_lun *be_lun;
1432 	union ctl_io *io;
1433 
1434 	io = beio->io;
1435 	be_lun = beio->lun;
1436 	ctl_free_beio(beio);
1437 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
1438 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
1439 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
1440 		ctl_data_submit_done(io);
1441 		return;
1442 	}
1443 
1444 	io->io_hdr.status &= ~CTL_STATUS_MASK;
1445 	io->io_hdr.status |= CTL_STATUS_NONE;
1446 
1447 	mtx_lock(&be_lun->queue_lock);
1448 	/*
1449 	 * XXX KDM make sure that links is okay to use at this point.
1450 	 * Otherwise, we either need to add another field to ctl_io_hdr,
1451 	 * or deal with resource allocation here.
1452 	 */
1453 	STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
1454 	mtx_unlock(&be_lun->queue_lock);
1455 
1456 	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
1457 }
1458 
1459 static void
1460 ctl_be_block_dispatch(struct ctl_be_block_lun *be_lun,
1461 			   union ctl_io *io)
1462 {
1463 	struct ctl_be_block_io *beio;
1464 	struct ctl_be_block_softc *softc;
1465 	struct ctl_lba_len_flags *lbalen;
1466 	struct ctl_ptr_len_flags *bptrlen;
1467 	uint64_t len_left, lbas;
1468 	int i;
1469 
1470 	softc = be_lun->softc;
1471 
1472 	DPRINTF("entered\n");
1473 
1474 	lbalen = ARGS(io);
1475 	if (lbalen->flags & CTL_LLF_WRITE) {
1476 		SDT_PROBE(cbb, kernel, write, start, 0, 0, 0, 0, 0);
1477 	} else {
1478 		SDT_PROBE(cbb, kernel, read, start, 0, 0, 0, 0, 0);
1479 	}
1480 
1481 	beio = ctl_alloc_beio(softc);
1482 	beio->io = io;
1483 	beio->lun = be_lun;
1484 	bptrlen = PRIV(io);
1485 	bptrlen->ptr = (void *)beio;
1486 
1487 	switch (io->scsiio.tag_type) {
1488 	case CTL_TAG_ORDERED:
1489 		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1490 		break;
1491 	case CTL_TAG_HEAD_OF_QUEUE:
1492 		beio->ds_tag_type = DEVSTAT_TAG_HEAD;
1493 		break;
1494 	case CTL_TAG_UNTAGGED:
1495 	case CTL_TAG_SIMPLE:
1496 	case CTL_TAG_ACA:
1497 	default:
1498 		beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1499 		break;
1500 	}
1501 
1502 	if (lbalen->flags & CTL_LLF_WRITE) {
1503 		beio->bio_cmd = BIO_WRITE;
1504 		beio->ds_trans_type = DEVSTAT_WRITE;
1505 	} else {
1506 		beio->bio_cmd = BIO_READ;
1507 		beio->ds_trans_type = DEVSTAT_READ;
1508 	}
1509 
1510 	DPRINTF("%s at LBA %jx len %u @%ju\n",
1511 	       (beio->bio_cmd == BIO_READ) ? "READ" : "WRITE",
1512 	       (uintmax_t)lbalen->lba, lbalen->len, bptrlen->len);
1513 	if (lbalen->flags & CTL_LLF_COMPARE)
1514 		lbas = CTLBLK_HALF_IO_SIZE;
1515 	else
1516 		lbas = CTLBLK_MAX_IO_SIZE;
1517 	lbas = MIN(lbalen->len - bptrlen->len, lbas / be_lun->blocksize);
1518 	beio->io_offset = (lbalen->lba + bptrlen->len) * be_lun->blocksize;
1519 	beio->io_len = lbas * be_lun->blocksize;
1520 	bptrlen->len += lbas;
1521 
1522 	for (i = 0, len_left = beio->io_len; len_left > 0; i++) {
1523 		KASSERT(i < CTLBLK_MAX_SEGS, ("Too many segs (%d >= %d)",
1524 		    i, CTLBLK_MAX_SEGS));
1525 
1526 		/*
1527 		 * Setup the S/G entry for this chunk.
1528 		 */
1529 		beio->sg_segs[i].len = min(CTLBLK_MAX_SEG, len_left);
1530 		beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);
1531 
1532 		DPRINTF("segment %d addr %p len %zd\n", i,
1533 			beio->sg_segs[i].addr, beio->sg_segs[i].len);
1534 
1535 		/* Set up second segment for compare operation. */
1536 		if (lbalen->flags & CTL_LLF_COMPARE) {
1537 			beio->sg_segs[i + CTLBLK_HALF_SEGS].len =
1538 			    beio->sg_segs[i].len;
1539 			beio->sg_segs[i + CTLBLK_HALF_SEGS].addr =
1540 			    uma_zalloc(be_lun->lun_zone, M_WAITOK);
1541 		}
1542 
1543 		beio->num_segs++;
1544 		len_left -= beio->sg_segs[i].len;
1545 	}
1546 	if (bptrlen->len < lbalen->len)
1547 		beio->beio_cont = ctl_be_block_next;
1548 	io->scsiio.be_move_done = ctl_be_block_move_done;
1549 	/* For compare we have separate S/G lists for read and datamove. */
1550 	if (lbalen->flags & CTL_LLF_COMPARE)
1551 		io->scsiio.kern_data_ptr = (uint8_t *)&beio->sg_segs[CTLBLK_HALF_SEGS];
1552 	else
1553 		io->scsiio.kern_data_ptr = (uint8_t *)beio->sg_segs;
1554 	io->scsiio.kern_data_len = beio->io_len;
1555 	io->scsiio.kern_data_resid = 0;
1556 	io->scsiio.kern_sg_entries = beio->num_segs;
1557 	io->io_hdr.flags |= CTL_FLAG_ALLOCATED | CTL_FLAG_KDPTR_SGLIST;
1558 
1559 	/*
1560 	 * For the read case, we need to read the data into our buffers and
1561 	 * then we can send it back to the user.  For the write case, we
1562 	 * need to get the data from the user first.
1563 	 */
1564 	if (beio->bio_cmd == BIO_READ) {
1565 		SDT_PROBE(cbb, kernel, read, alloc_done, 0, 0, 0, 0, 0);
1566 		be_lun->dispatch(be_lun, beio);
1567 	} else {
1568 		SDT_PROBE(cbb, kernel, write, alloc_done, 0, 0, 0, 0, 0);
1569 #ifdef CTL_TIME_IO
1570         	getbintime(&io->io_hdr.dma_start_bt);
1571 #endif
1572 		ctl_datamove(io);
1573 	}
1574 }
1575 
1576 static void
1577 ctl_be_block_worker(void *context, int pending)
1578 {
1579 	struct ctl_be_block_lun *be_lun;
1580 	struct ctl_be_block_softc *softc;
1581 	union ctl_io *io;
1582 
1583 	be_lun = (struct ctl_be_block_lun *)context;
1584 	softc = be_lun->softc;
1585 
1586 	DPRINTF("entered\n");
1587 
1588 	mtx_lock(&be_lun->queue_lock);
1589 	for (;;) {
1590 		io = (union ctl_io *)STAILQ_FIRST(&be_lun->datamove_queue);
1591 		if (io != NULL) {
1592 			struct ctl_be_block_io *beio;
1593 
1594 			DPRINTF("datamove queue\n");
1595 
1596 			STAILQ_REMOVE(&be_lun->datamove_queue, &io->io_hdr,
1597 				      ctl_io_hdr, links);
1598 
1599 			mtx_unlock(&be_lun->queue_lock);
1600 
1601 			beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1602 
1603 			be_lun->dispatch(be_lun, beio);
1604 
1605 			mtx_lock(&be_lun->queue_lock);
1606 			continue;
1607 		}
1608 		io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_write_queue);
1609 		if (io != NULL) {
1610 			DPRINTF("config write queue\n");
1611 			STAILQ_REMOVE(&be_lun->config_write_queue, &io->io_hdr,
1612 				      ctl_io_hdr, links);
1613 			mtx_unlock(&be_lun->queue_lock);
1614 			ctl_be_block_cw_dispatch(be_lun, io);
1615 			mtx_lock(&be_lun->queue_lock);
1616 			continue;
1617 		}
1618 		io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_read_queue);
1619 		if (io != NULL) {
1620 			DPRINTF("config read queue\n");
1621 			STAILQ_REMOVE(&be_lun->config_read_queue, &io->io_hdr,
1622 				      ctl_io_hdr, links);
1623 			mtx_unlock(&be_lun->queue_lock);
1624 			ctl_be_block_cr_dispatch(be_lun, io);
1625 			mtx_lock(&be_lun->queue_lock);
1626 			continue;
1627 		}
1628 		io = (union ctl_io *)STAILQ_FIRST(&be_lun->input_queue);
1629 		if (io != NULL) {
1630 			DPRINTF("input queue\n");
1631 
1632 			STAILQ_REMOVE(&be_lun->input_queue, &io->io_hdr,
1633 				      ctl_io_hdr, links);
1634 			mtx_unlock(&be_lun->queue_lock);
1635 
1636 			/*
1637 			 * We must drop the lock, since this routine and
1638 			 * its children may sleep.
1639 			 */
1640 			ctl_be_block_dispatch(be_lun, io);
1641 
1642 			mtx_lock(&be_lun->queue_lock);
1643 			continue;
1644 		}
1645 
1646 		/*
1647 		 * If we get here, there is no work left in the queues, so
1648 		 * just break out and let the task queue go to sleep.
1649 		 */
1650 		break;
1651 	}
1652 	mtx_unlock(&be_lun->queue_lock);
1653 }
1654 
1655 /*
1656  * Entry point from CTL to the backend for I/O.  We queue everything to a
1657  * work thread, so this just puts the I/O on a queue and wakes up the
1658  * thread.
1659  */
1660 static int
1661 ctl_be_block_submit(union ctl_io *io)
1662 {
1663 	struct ctl_be_block_lun *be_lun;
1664 	struct ctl_be_lun *ctl_be_lun;
1665 
1666 	DPRINTF("entered\n");
1667 
1668 	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
1669 		CTL_PRIV_BACKEND_LUN].ptr;
1670 	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
1671 
1672 	/*
1673 	 * Make sure we only get SCSI I/O.
1674 	 */
1675 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI, ("Non-SCSI I/O (type "
1676 		"%#x) encountered", io->io_hdr.io_type));
1677 
1678 	PRIV(io)->len = 0;
1679 
1680 	mtx_lock(&be_lun->queue_lock);
1681 	/*
1682 	 * XXX KDM make sure that links is okay to use at this point.
1683 	 * Otherwise, we either need to add another field to ctl_io_hdr,
1684 	 * or deal with resource allocation here.
1685 	 */
1686 	STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
1687 	mtx_unlock(&be_lun->queue_lock);
1688 	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
1689 
1690 	return (CTL_RETVAL_COMPLETE);
1691 }
1692 
1693 static int
1694 ctl_be_block_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
1695 			int flag, struct thread *td)
1696 {
1697 	struct ctl_be_block_softc *softc;
1698 	int error;
1699 
1700 	softc = &backend_block_softc;
1701 
1702 	error = 0;
1703 
1704 	switch (cmd) {
1705 	case CTL_LUN_REQ: {
1706 		struct ctl_lun_req *lun_req;
1707 
1708 		lun_req = (struct ctl_lun_req *)addr;
1709 
1710 		switch (lun_req->reqtype) {
1711 		case CTL_LUNREQ_CREATE:
1712 			error = ctl_be_block_create(softc, lun_req);
1713 			break;
1714 		case CTL_LUNREQ_RM:
1715 			error = ctl_be_block_rm(softc, lun_req);
1716 			break;
1717 		case CTL_LUNREQ_MODIFY:
1718 			error = ctl_be_block_modify(softc, lun_req);
1719 			break;
1720 		default:
1721 			lun_req->status = CTL_LUN_ERROR;
1722 			snprintf(lun_req->error_str, sizeof(lun_req->error_str),
1723 				 "invalid LUN request type %d",
1724 				 lun_req->reqtype);
1725 			break;
1726 		}
1727 		break;
1728 	}
1729 	default:
1730 		error = ENOTTY;
1731 		break;
1732 	}
1733 
1734 	return (error);
1735 }
1736 
1737 static int
1738 ctl_be_block_open_file(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
1739 {
1740 	struct ctl_be_block_filedata *file_data;
1741 	struct ctl_lun_create_params *params;
1742 	struct vattr		      vattr;
1743 	off_t			      pss;
1744 	int			      error;
1745 
1746 	error = 0;
1747 	file_data = &be_lun->backend.file;
1748 	params = &be_lun->params;
1749 
1750 	be_lun->dev_type = CTL_BE_BLOCK_FILE;
1751 	be_lun->dispatch = ctl_be_block_dispatch_file;
1752 	be_lun->lun_flush = ctl_be_block_flush_file;
1753 	be_lun->get_lba_status = ctl_be_block_gls_file;
1754 	be_lun->getattr = ctl_be_block_getattr_file;
1755 
1756 	error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
1757 	if (error != 0) {
1758 		snprintf(req->error_str, sizeof(req->error_str),
1759 			 "error calling VOP_GETATTR() for file %s",
1760 			 be_lun->dev_path);
1761 		return (error);
1762 	}
1763 
1764 	/*
1765 	 * Verify that we have the ability to upgrade to exclusive
1766 	 * access on this file so we can trap errors at open instead
1767 	 * of reporting them during first access.
1768 	 */
1769 	if (VOP_ISLOCKED(be_lun->vn) != LK_EXCLUSIVE) {
1770 		vn_lock(be_lun->vn, LK_UPGRADE | LK_RETRY);
1771 		if (be_lun->vn->v_iflag & VI_DOOMED) {
1772 			error = EBADF;
1773 			snprintf(req->error_str, sizeof(req->error_str),
1774 				 "error locking file %s", be_lun->dev_path);
1775 			return (error);
1776 		}
1777 	}
1778 
1779 
1780 	file_data->cred = crhold(curthread->td_ucred);
1781 	if (params->lun_size_bytes != 0)
1782 		be_lun->size_bytes = params->lun_size_bytes;
1783 	else
1784 		be_lun->size_bytes = vattr.va_size;
1785 	/*
1786 	 * We set the multi thread flag for file operations because all
1787 	 * filesystems (in theory) are capable of allowing multiple readers
1788 	 * of a file at once.  So we want to get the maximum possible
1789 	 * concurrency.
1790 	 */
1791 	be_lun->flags |= CTL_BE_BLOCK_LUN_MULTI_THREAD;
1792 
1793 	/*
1794 	 * For files we can use any logical block size.  Prefer 512 bytes
1795 	 * for compatibility reasons.  If file's vattr.va_blocksize
1796 	 * (preferred I/O block size) is bigger and multiple to chosen
1797 	 * logical block size -- report it as physical block size.
1798 	 */
1799 	if (params->blocksize_bytes != 0)
1800 		be_lun->blocksize = params->blocksize_bytes;
1801 	else
1802 		be_lun->blocksize = 512;
1803 	pss = vattr.va_blocksize / be_lun->blocksize;
1804 	if ((pss > 0) && (pss * be_lun->blocksize == vattr.va_blocksize) &&
1805 	    ((pss & (pss - 1)) == 0)) {
1806 		be_lun->pblockexp = fls(pss) - 1;
1807 		be_lun->pblockoff = 0;
1808 	}
1809 
1810 	/*
1811 	 * Sanity check.  The media size has to be at least one
1812 	 * sector long.
1813 	 */
1814 	if (be_lun->size_bytes < be_lun->blocksize) {
1815 		error = EINVAL;
1816 		snprintf(req->error_str, sizeof(req->error_str),
1817 			 "file %s size %ju < block size %u", be_lun->dev_path,
1818 			 (uintmax_t)be_lun->size_bytes, be_lun->blocksize);
1819 	}
1820 	return (error);
1821 }
1822 
1823 static int
1824 ctl_be_block_open_dev(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
1825 {
1826 	struct ctl_lun_create_params *params;
1827 	struct vattr		      vattr;
1828 	struct cdev		     *dev;
1829 	struct cdevsw		     *devsw;
1830 	int			      error;
1831 	off_t			      ps, pss, po, pos;
1832 
1833 	params = &be_lun->params;
1834 
1835 	be_lun->dev_type = CTL_BE_BLOCK_DEV;
1836 	be_lun->backend.dev.cdev = be_lun->vn->v_rdev;
1837 	be_lun->backend.dev.csw = dev_refthread(be_lun->backend.dev.cdev,
1838 					     &be_lun->backend.dev.dev_ref);
1839 	if (be_lun->backend.dev.csw == NULL)
1840 		panic("Unable to retrieve device switch");
1841 	if (strcmp(be_lun->backend.dev.csw->d_name, "zvol") == 0) {
1842 		be_lun->dispatch = ctl_be_block_dispatch_zvol;
1843 		be_lun->get_lba_status = ctl_be_block_gls_zvol;
1844 	} else
1845 		be_lun->dispatch = ctl_be_block_dispatch_dev;
1846 	be_lun->lun_flush = ctl_be_block_flush_dev;
1847 	be_lun->unmap = ctl_be_block_unmap_dev;
1848 	be_lun->getattr = ctl_be_block_getattr_dev;
1849 
1850 	error = VOP_GETATTR(be_lun->vn, &vattr, NOCRED);
1851 	if (error) {
1852 		snprintf(req->error_str, sizeof(req->error_str),
1853 			 "error getting vnode attributes for device %s",
1854 			 be_lun->dev_path);
1855 		return (error);
1856 	}
1857 
1858 	dev = be_lun->vn->v_rdev;
1859 	devsw = dev->si_devsw;
1860 	if (!devsw->d_ioctl) {
1861 		snprintf(req->error_str, sizeof(req->error_str),
1862 			 "no d_ioctl for device %s!",
1863 			 be_lun->dev_path);
1864 		return (ENODEV);
1865 	}
1866 
1867 	error = devsw->d_ioctl(dev, DIOCGSECTORSIZE,
1868 			       (caddr_t)&be_lun->blocksize, FREAD,
1869 			       curthread);
1870 	if (error) {
1871 		snprintf(req->error_str, sizeof(req->error_str),
1872 			 "error %d returned for DIOCGSECTORSIZE ioctl "
1873 			 "on %s!", error, be_lun->dev_path);
1874 		return (error);
1875 	}
1876 
1877 	/*
1878 	 * If the user has asked for a blocksize that is greater than the
1879 	 * backing device's blocksize, we can do it only if the blocksize
1880 	 * the user is asking for is an even multiple of the underlying
1881 	 * device's blocksize.
1882 	 */
1883 	if ((params->blocksize_bytes != 0)
1884 	 && (params->blocksize_bytes > be_lun->blocksize)) {
1885 		uint32_t bs_multiple, tmp_blocksize;
1886 
1887 		bs_multiple = params->blocksize_bytes / be_lun->blocksize;
1888 
1889 		tmp_blocksize = bs_multiple * be_lun->blocksize;
1890 
1891 		if (tmp_blocksize == params->blocksize_bytes) {
1892 			be_lun->blocksize = params->blocksize_bytes;
1893 		} else {
1894 			snprintf(req->error_str, sizeof(req->error_str),
1895 				 "requested blocksize %u is not an even "
1896 				 "multiple of backing device blocksize %u",
1897 				 params->blocksize_bytes,
1898 				 be_lun->blocksize);
1899 			return (EINVAL);
1900 
1901 		}
1902 	} else if ((params->blocksize_bytes != 0)
1903 		&& (params->blocksize_bytes != be_lun->blocksize)) {
1904 		snprintf(req->error_str, sizeof(req->error_str),
1905 			 "requested blocksize %u < backing device "
1906 			 "blocksize %u", params->blocksize_bytes,
1907 			 be_lun->blocksize);
1908 		return (EINVAL);
1909 	}
1910 
1911 	error = devsw->d_ioctl(dev, DIOCGMEDIASIZE,
1912 			       (caddr_t)&be_lun->size_bytes, FREAD,
1913 			       curthread);
1914 	if (error) {
1915 		snprintf(req->error_str, sizeof(req->error_str),
1916 			 "error %d returned for DIOCGMEDIASIZE "
1917 			 " ioctl on %s!", error,
1918 			 be_lun->dev_path);
1919 		return (error);
1920 	}
1921 
1922 	if (params->lun_size_bytes != 0) {
1923 		if (params->lun_size_bytes > be_lun->size_bytes) {
1924 			snprintf(req->error_str, sizeof(req->error_str),
1925 				 "requested LUN size %ju > backing device "
1926 				 "size %ju",
1927 				 (uintmax_t)params->lun_size_bytes,
1928 				 (uintmax_t)be_lun->size_bytes);
1929 			return (EINVAL);
1930 		}
1931 
1932 		be_lun->size_bytes = params->lun_size_bytes;
1933 	}
1934 
1935 	error = devsw->d_ioctl(dev, DIOCGSTRIPESIZE,
1936 			       (caddr_t)&ps, FREAD, curthread);
1937 	if (error)
1938 		ps = po = 0;
1939 	else {
1940 		error = devsw->d_ioctl(dev, DIOCGSTRIPEOFFSET,
1941 				       (caddr_t)&po, FREAD, curthread);
1942 		if (error)
1943 			po = 0;
1944 	}
1945 	pss = ps / be_lun->blocksize;
1946 	pos = po / be_lun->blocksize;
1947 	if ((pss > 0) && (pss * be_lun->blocksize == ps) && (pss >= pos) &&
1948 	    ((pss & (pss - 1)) == 0) && (pos * be_lun->blocksize == po)) {
1949 		be_lun->pblockexp = fls(pss) - 1;
1950 		be_lun->pblockoff = (pss - pos) % pss;
1951 	}
1952 
1953 	return (0);
1954 }
1955 
1956 static int
1957 ctl_be_block_close(struct ctl_be_block_lun *be_lun)
1958 {
1959 	DROP_GIANT();
1960 	if (be_lun->vn) {
1961 		int flags = FREAD | FWRITE;
1962 
1963 		switch (be_lun->dev_type) {
1964 		case CTL_BE_BLOCK_DEV:
1965 			if (be_lun->backend.dev.csw) {
1966 				dev_relthread(be_lun->backend.dev.cdev,
1967 					      be_lun->backend.dev.dev_ref);
1968 				be_lun->backend.dev.csw  = NULL;
1969 				be_lun->backend.dev.cdev = NULL;
1970 			}
1971 			break;
1972 		case CTL_BE_BLOCK_FILE:
1973 			break;
1974 		case CTL_BE_BLOCK_NONE:
1975 			break;
1976 		default:
1977 			panic("Unexpected backend type.");
1978 			break;
1979 		}
1980 
1981 		(void)vn_close(be_lun->vn, flags, NOCRED, curthread);
1982 		be_lun->vn = NULL;
1983 
1984 		switch (be_lun->dev_type) {
1985 		case CTL_BE_BLOCK_DEV:
1986 			break;
1987 		case CTL_BE_BLOCK_FILE:
1988 			if (be_lun->backend.file.cred != NULL) {
1989 				crfree(be_lun->backend.file.cred);
1990 				be_lun->backend.file.cred = NULL;
1991 			}
1992 			break;
1993 		case CTL_BE_BLOCK_NONE:
1994 			break;
1995 		default:
1996 			panic("Unexpected backend type.");
1997 			break;
1998 		}
1999 		be_lun->dev_type = CTL_BE_BLOCK_NONE;
2000 	}
2001 	PICKUP_GIANT();
2002 
2003 	return (0);
2004 }
2005 
2006 static int
2007 ctl_be_block_open(struct ctl_be_block_softc *softc,
2008 		       struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
2009 {
2010 	struct nameidata nd;
2011 	int		 flags;
2012 	int		 error;
2013 
2014 	/*
2015 	 * XXX KDM allow a read-only option?
2016 	 */
2017 	flags = FREAD | FWRITE;
2018 	error = 0;
2019 
2020 	if (rootvnode == NULL) {
2021 		snprintf(req->error_str, sizeof(req->error_str),
2022 			 "Root filesystem is not mounted");
2023 		return (1);
2024 	}
2025 
2026 	if (!curthread->td_proc->p_fd->fd_cdir) {
2027 		curthread->td_proc->p_fd->fd_cdir = rootvnode;
2028 		VREF(rootvnode);
2029 	}
2030 	if (!curthread->td_proc->p_fd->fd_rdir) {
2031 		curthread->td_proc->p_fd->fd_rdir = rootvnode;
2032 		VREF(rootvnode);
2033 	}
2034 	if (!curthread->td_proc->p_fd->fd_jdir) {
2035 		curthread->td_proc->p_fd->fd_jdir = rootvnode;
2036 		VREF(rootvnode);
2037 	}
2038 
2039  again:
2040 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, be_lun->dev_path, curthread);
2041 	error = vn_open(&nd, &flags, 0, NULL);
2042 	if (error) {
2043 		/*
2044 		 * This is the only reasonable guess we can make as far as
2045 		 * path if the user doesn't give us a fully qualified path.
2046 		 * If they want to specify a file, they need to specify the
2047 		 * full path.
2048 		 */
2049 		if (be_lun->dev_path[0] != '/') {
2050 			char *dev_path = "/dev/";
2051 			char *dev_name;
2052 
2053 			/* Try adding device path at beginning of name */
2054 			dev_name = malloc(strlen(be_lun->dev_path)
2055 					+ strlen(dev_path) + 1,
2056 					  M_CTLBLK, M_WAITOK);
2057 			if (dev_name) {
2058 				sprintf(dev_name, "%s%s", dev_path,
2059 					be_lun->dev_path);
2060 				free(be_lun->dev_path, M_CTLBLK);
2061 				be_lun->dev_path = dev_name;
2062 				goto again;
2063 			}
2064 		}
2065 		snprintf(req->error_str, sizeof(req->error_str),
2066 		    "error opening %s: %d", be_lun->dev_path, error);
2067 		return (error);
2068 	}
2069 
2070 	NDFREE(&nd, NDF_ONLY_PNBUF);
2071 
2072 	be_lun->vn = nd.ni_vp;
2073 
2074 	/* We only support disks and files. */
2075 	if (vn_isdisk(be_lun->vn, &error)) {
2076 		error = ctl_be_block_open_dev(be_lun, req);
2077 	} else if (be_lun->vn->v_type == VREG) {
2078 		error = ctl_be_block_open_file(be_lun, req);
2079 	} else {
2080 		error = EINVAL;
2081 		snprintf(req->error_str, sizeof(req->error_str),
2082 			 "%s is not a disk or plain file", be_lun->dev_path);
2083 	}
2084 	VOP_UNLOCK(be_lun->vn, 0);
2085 
2086 	if (error != 0) {
2087 		ctl_be_block_close(be_lun);
2088 		return (error);
2089 	}
2090 
2091 	be_lun->blocksize_shift = fls(be_lun->blocksize) - 1;
2092 	be_lun->size_blocks = be_lun->size_bytes >> be_lun->blocksize_shift;
2093 
2094 	return (0);
2095 }
2096 
2097 static int
2098 ctl_be_block_create(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2099 {
2100 	struct ctl_be_block_lun *be_lun;
2101 	struct ctl_lun_create_params *params;
2102 	char num_thread_str[16];
2103 	char tmpstr[32];
2104 	char *value;
2105 	int retval, num_threads, unmap;
2106 	int tmp_num_threads;
2107 
2108 	params = &req->reqdata.create;
2109 	retval = 0;
2110 	req->status = CTL_LUN_OK;
2111 
2112 	num_threads = cbb_num_threads;
2113 
2114 	be_lun = malloc(sizeof(*be_lun), M_CTLBLK, M_ZERO | M_WAITOK);
2115 
2116 	be_lun->params = req->reqdata.create;
2117 	be_lun->softc = softc;
2118 	STAILQ_INIT(&be_lun->input_queue);
2119 	STAILQ_INIT(&be_lun->config_read_queue);
2120 	STAILQ_INIT(&be_lun->config_write_queue);
2121 	STAILQ_INIT(&be_lun->datamove_queue);
2122 	sprintf(be_lun->lunname, "cblk%d", softc->num_luns);
2123 	mtx_init(&be_lun->io_lock, "cblk io lock", NULL, MTX_DEF);
2124 	mtx_init(&be_lun->queue_lock, "cblk queue lock", NULL, MTX_DEF);
2125 	ctl_init_opts(&be_lun->ctl_be_lun.options,
2126 	    req->num_be_args, req->kern_be_args);
2127 
2128 	be_lun->lun_zone = uma_zcreate(be_lun->lunname, CTLBLK_MAX_SEG,
2129 	    NULL, NULL, NULL, NULL, /*align*/ 0, /*flags*/0);
2130 
2131 	if (be_lun->lun_zone == NULL) {
2132 		snprintf(req->error_str, sizeof(req->error_str),
2133 			 "error allocating UMA zone");
2134 		goto bailout_error;
2135 	}
2136 
2137 	if (params->flags & CTL_LUN_FLAG_DEV_TYPE)
2138 		be_lun->ctl_be_lun.lun_type = params->device_type;
2139 	else
2140 		be_lun->ctl_be_lun.lun_type = T_DIRECT;
2141 
2142 	if (be_lun->ctl_be_lun.lun_type == T_DIRECT) {
2143 		value = ctl_get_opt(&be_lun->ctl_be_lun.options, "file");
2144 		if (value == NULL) {
2145 			snprintf(req->error_str, sizeof(req->error_str),
2146 				 "no file argument specified");
2147 			goto bailout_error;
2148 		}
2149 		be_lun->dev_path = strdup(value, M_CTLBLK);
2150 		be_lun->blocksize = 512;
2151 		be_lun->blocksize_shift = fls(be_lun->blocksize) - 1;
2152 
2153 		retval = ctl_be_block_open(softc, be_lun, req);
2154 		if (retval != 0) {
2155 			retval = 0;
2156 			req->status = CTL_LUN_WARNING;
2157 		}
2158 	} else {
2159 		/*
2160 		 * For processor devices, we don't have any size.
2161 		 */
2162 		be_lun->blocksize = 0;
2163 		be_lun->pblockexp = 0;
2164 		be_lun->pblockoff = 0;
2165 		be_lun->size_blocks = 0;
2166 		be_lun->size_bytes = 0;
2167 		be_lun->ctl_be_lun.maxlba = 0;
2168 
2169 		/*
2170 		 * Default to just 1 thread for processor devices.
2171 		 */
2172 		num_threads = 1;
2173 	}
2174 
2175 	/*
2176 	 * XXX This searching loop might be refactored to be combined with
2177 	 * the loop above,
2178 	 */
2179 	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "num_threads");
2180 	if (value != NULL) {
2181 		tmp_num_threads = strtol(value, NULL, 0);
2182 
2183 		/*
2184 		 * We don't let the user specify less than one
2185 		 * thread, but hope he's clueful enough not to
2186 		 * specify 1000 threads.
2187 		 */
2188 		if (tmp_num_threads < 1) {
2189 			snprintf(req->error_str, sizeof(req->error_str),
2190 				 "invalid number of threads %s",
2191 				 num_thread_str);
2192 			goto bailout_error;
2193 		}
2194 		num_threads = tmp_num_threads;
2195 	}
2196 	unmap = (be_lun->dispatch == ctl_be_block_dispatch_zvol);
2197 	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "unmap");
2198 	if (value != NULL)
2199 		unmap = (strcmp(value, "on") == 0);
2200 
2201 	be_lun->flags = CTL_BE_BLOCK_LUN_UNCONFIGURED;
2202 	be_lun->ctl_be_lun.flags = CTL_LUN_FLAG_PRIMARY;
2203 	if (be_lun->vn == NULL)
2204 		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_OFFLINE;
2205 	if (unmap)
2206 		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_UNMAP;
2207 	be_lun->ctl_be_lun.be_lun = be_lun;
2208 	be_lun->ctl_be_lun.maxlba = (be_lun->size_blocks == 0) ?
2209 	    0 : (be_lun->size_blocks - 1);
2210 	be_lun->ctl_be_lun.blocksize = be_lun->blocksize;
2211 	be_lun->ctl_be_lun.pblockexp = be_lun->pblockexp;
2212 	be_lun->ctl_be_lun.pblockoff = be_lun->pblockoff;
2213 	if (be_lun->dispatch == ctl_be_block_dispatch_zvol &&
2214 	    be_lun->blocksize != 0)
2215 		be_lun->ctl_be_lun.atomicblock = CTLBLK_MAX_IO_SIZE /
2216 		    be_lun->blocksize;
2217 	/* Tell the user the blocksize we ended up using */
2218 	params->lun_size_bytes = be_lun->size_bytes;
2219 	params->blocksize_bytes = be_lun->blocksize;
2220 	if (params->flags & CTL_LUN_FLAG_ID_REQ) {
2221 		be_lun->ctl_be_lun.req_lun_id = params->req_lun_id;
2222 		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_ID_REQ;
2223 	} else
2224 		be_lun->ctl_be_lun.req_lun_id = 0;
2225 
2226 	be_lun->ctl_be_lun.lun_shutdown = ctl_be_block_lun_shutdown;
2227 	be_lun->ctl_be_lun.lun_config_status =
2228 		ctl_be_block_lun_config_status;
2229 	be_lun->ctl_be_lun.be = &ctl_be_block_driver;
2230 
2231 	if ((params->flags & CTL_LUN_FLAG_SERIAL_NUM) == 0) {
2232 		snprintf(tmpstr, sizeof(tmpstr), "MYSERIAL%4d",
2233 			 softc->num_luns);
2234 		strncpy((char *)be_lun->ctl_be_lun.serial_num, tmpstr,
2235 			ctl_min(sizeof(be_lun->ctl_be_lun.serial_num),
2236 			sizeof(tmpstr)));
2237 
2238 		/* Tell the user what we used for a serial number */
2239 		strncpy((char *)params->serial_num, tmpstr,
2240 			ctl_min(sizeof(params->serial_num), sizeof(tmpstr)));
2241 	} else {
2242 		strncpy((char *)be_lun->ctl_be_lun.serial_num,
2243 			params->serial_num,
2244 			ctl_min(sizeof(be_lun->ctl_be_lun.serial_num),
2245 			sizeof(params->serial_num)));
2246 	}
2247 	if ((params->flags & CTL_LUN_FLAG_DEVID) == 0) {
2248 		snprintf(tmpstr, sizeof(tmpstr), "MYDEVID%4d", softc->num_luns);
2249 		strncpy((char *)be_lun->ctl_be_lun.device_id, tmpstr,
2250 			ctl_min(sizeof(be_lun->ctl_be_lun.device_id),
2251 			sizeof(tmpstr)));
2252 
2253 		/* Tell the user what we used for a device ID */
2254 		strncpy((char *)params->device_id, tmpstr,
2255 			ctl_min(sizeof(params->device_id), sizeof(tmpstr)));
2256 	} else {
2257 		strncpy((char *)be_lun->ctl_be_lun.device_id,
2258 			params->device_id,
2259 			ctl_min(sizeof(be_lun->ctl_be_lun.device_id),
2260 				sizeof(params->device_id)));
2261 	}
2262 
2263 	TASK_INIT(&be_lun->io_task, /*priority*/0, ctl_be_block_worker, be_lun);
2264 
2265 	be_lun->io_taskqueue = taskqueue_create(be_lun->lunname, M_WAITOK,
2266 	    taskqueue_thread_enqueue, /*context*/&be_lun->io_taskqueue);
2267 
2268 	if (be_lun->io_taskqueue == NULL) {
2269 		snprintf(req->error_str, sizeof(req->error_str),
2270 			 "unable to create taskqueue");
2271 		goto bailout_error;
2272 	}
2273 
2274 	/*
2275 	 * Note that we start the same number of threads by default for
2276 	 * both the file case and the block device case.  For the file
2277 	 * case, we need multiple threads to allow concurrency, because the
2278 	 * vnode interface is designed to be a blocking interface.  For the
2279 	 * block device case, ZFS zvols at least will block the caller's
2280 	 * context in many instances, and so we need multiple threads to
2281 	 * overcome that problem.  Other block devices don't need as many
2282 	 * threads, but they shouldn't cause too many problems.
2283 	 *
2284 	 * If the user wants to just have a single thread for a block
2285 	 * device, he can specify that when the LUN is created, or change
2286 	 * the tunable/sysctl to alter the default number of threads.
2287 	 */
2288 	retval = taskqueue_start_threads(&be_lun->io_taskqueue,
2289 					 /*num threads*/num_threads,
2290 					 /*priority*/PWAIT,
2291 					 /*thread name*/
2292 					 "%s taskq", be_lun->lunname);
2293 
2294 	if (retval != 0)
2295 		goto bailout_error;
2296 
2297 	be_lun->num_threads = num_threads;
2298 
2299 	mtx_lock(&softc->lock);
2300 	softc->num_luns++;
2301 	STAILQ_INSERT_TAIL(&softc->lun_list, be_lun, links);
2302 
2303 	mtx_unlock(&softc->lock);
2304 
2305 	retval = ctl_add_lun(&be_lun->ctl_be_lun);
2306 	if (retval != 0) {
2307 		mtx_lock(&softc->lock);
2308 		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2309 			      links);
2310 		softc->num_luns--;
2311 		mtx_unlock(&softc->lock);
2312 		snprintf(req->error_str, sizeof(req->error_str),
2313 			 "ctl_add_lun() returned error %d, see dmesg for "
2314 			 "details", retval);
2315 		retval = 0;
2316 		goto bailout_error;
2317 	}
2318 
2319 	mtx_lock(&softc->lock);
2320 
2321 	/*
2322 	 * Tell the config_status routine that we're waiting so it won't
2323 	 * clean up the LUN in the event of an error.
2324 	 */
2325 	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2326 
2327 	while (be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) {
2328 		retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2329 		if (retval == EINTR)
2330 			break;
2331 	}
2332 	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2333 
2334 	if (be_lun->flags & CTL_BE_BLOCK_LUN_CONFIG_ERR) {
2335 		snprintf(req->error_str, sizeof(req->error_str),
2336 			 "LUN configuration error, see dmesg for details");
2337 		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2338 			      links);
2339 		softc->num_luns--;
2340 		mtx_unlock(&softc->lock);
2341 		goto bailout_error;
2342 	} else {
2343 		params->req_lun_id = be_lun->ctl_be_lun.lun_id;
2344 	}
2345 
2346 	mtx_unlock(&softc->lock);
2347 
2348 	be_lun->disk_stats = devstat_new_entry("cbb", params->req_lun_id,
2349 					       be_lun->blocksize,
2350 					       DEVSTAT_ALL_SUPPORTED,
2351 					       be_lun->ctl_be_lun.lun_type
2352 					       | DEVSTAT_TYPE_IF_OTHER,
2353 					       DEVSTAT_PRIORITY_OTHER);
2354 
2355 	return (retval);
2356 
2357 bailout_error:
2358 	req->status = CTL_LUN_ERROR;
2359 
2360 	if (be_lun->io_taskqueue != NULL)
2361 		taskqueue_free(be_lun->io_taskqueue);
2362 	ctl_be_block_close(be_lun);
2363 	if (be_lun->dev_path != NULL)
2364 		free(be_lun->dev_path, M_CTLBLK);
2365 	if (be_lun->lun_zone != NULL)
2366 		uma_zdestroy(be_lun->lun_zone);
2367 	ctl_free_opts(&be_lun->ctl_be_lun.options);
2368 	mtx_destroy(&be_lun->queue_lock);
2369 	mtx_destroy(&be_lun->io_lock);
2370 	free(be_lun, M_CTLBLK);
2371 
2372 	return (retval);
2373 }
2374 
2375 static int
2376 ctl_be_block_rm(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2377 {
2378 	struct ctl_lun_rm_params *params;
2379 	struct ctl_be_block_lun *be_lun;
2380 	int retval;
2381 
2382 	params = &req->reqdata.rm;
2383 
2384 	mtx_lock(&softc->lock);
2385 
2386 	be_lun = NULL;
2387 
2388 	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2389 		if (be_lun->ctl_be_lun.lun_id == params->lun_id)
2390 			break;
2391 	}
2392 	mtx_unlock(&softc->lock);
2393 
2394 	if (be_lun == NULL) {
2395 		snprintf(req->error_str, sizeof(req->error_str),
2396 			 "LUN %u is not managed by the block backend",
2397 			 params->lun_id);
2398 		goto bailout_error;
2399 	}
2400 
2401 	retval = ctl_disable_lun(&be_lun->ctl_be_lun);
2402 
2403 	if (retval != 0) {
2404 		snprintf(req->error_str, sizeof(req->error_str),
2405 			 "error %d returned from ctl_disable_lun() for "
2406 			 "LUN %d", retval, params->lun_id);
2407 		goto bailout_error;
2408 
2409 	}
2410 
2411 	retval = ctl_invalidate_lun(&be_lun->ctl_be_lun);
2412 	if (retval != 0) {
2413 		snprintf(req->error_str, sizeof(req->error_str),
2414 			 "error %d returned from ctl_invalidate_lun() for "
2415 			 "LUN %d", retval, params->lun_id);
2416 		goto bailout_error;
2417 	}
2418 
2419 	mtx_lock(&softc->lock);
2420 
2421 	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2422 
2423 	while ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2424                 retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2425                 if (retval == EINTR)
2426                         break;
2427         }
2428 
2429 	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2430 
2431 	if ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2432 		snprintf(req->error_str, sizeof(req->error_str),
2433 			 "interrupted waiting for LUN to be freed");
2434 		mtx_unlock(&softc->lock);
2435 		goto bailout_error;
2436 	}
2437 
2438 	STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun, links);
2439 
2440 	softc->num_luns--;
2441 	mtx_unlock(&softc->lock);
2442 
2443 	taskqueue_drain(be_lun->io_taskqueue, &be_lun->io_task);
2444 
2445 	taskqueue_free(be_lun->io_taskqueue);
2446 
2447 	ctl_be_block_close(be_lun);
2448 
2449 	if (be_lun->disk_stats != NULL)
2450 		devstat_remove_entry(be_lun->disk_stats);
2451 
2452 	uma_zdestroy(be_lun->lun_zone);
2453 
2454 	ctl_free_opts(&be_lun->ctl_be_lun.options);
2455 	free(be_lun->dev_path, M_CTLBLK);
2456 	mtx_destroy(&be_lun->queue_lock);
2457 	mtx_destroy(&be_lun->io_lock);
2458 	free(be_lun, M_CTLBLK);
2459 
2460 	req->status = CTL_LUN_OK;
2461 
2462 	return (0);
2463 
2464 bailout_error:
2465 
2466 	req->status = CTL_LUN_ERROR;
2467 
2468 	return (0);
2469 }
2470 
2471 static int
2472 ctl_be_block_modify_file(struct ctl_be_block_lun *be_lun,
2473 			 struct ctl_lun_req *req)
2474 {
2475 	struct vattr vattr;
2476 	int error;
2477 	struct ctl_lun_create_params *params = &be_lun->params;
2478 
2479 	if (params->lun_size_bytes != 0) {
2480 		be_lun->size_bytes = params->lun_size_bytes;
2481 	} else  {
2482 		vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
2483 		error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
2484 		VOP_UNLOCK(be_lun->vn, 0);
2485 		if (error != 0) {
2486 			snprintf(req->error_str, sizeof(req->error_str),
2487 				 "error calling VOP_GETATTR() for file %s",
2488 				 be_lun->dev_path);
2489 			return (error);
2490 		}
2491 
2492 		be_lun->size_bytes = vattr.va_size;
2493 	}
2494 
2495 	return (0);
2496 }
2497 
2498 static int
2499 ctl_be_block_modify_dev(struct ctl_be_block_lun *be_lun,
2500 			struct ctl_lun_req *req)
2501 {
2502 	struct ctl_be_block_devdata *dev_data;
2503 	int error;
2504 	struct ctl_lun_create_params *params = &be_lun->params;
2505 	uint64_t size_bytes;
2506 
2507 	dev_data = &be_lun->backend.dev;
2508 	if (!dev_data->csw->d_ioctl) {
2509 		snprintf(req->error_str, sizeof(req->error_str),
2510 			 "no d_ioctl for device %s!", be_lun->dev_path);
2511 		return (ENODEV);
2512 	}
2513 
2514 	error = dev_data->csw->d_ioctl(dev_data->cdev, DIOCGMEDIASIZE,
2515 			       (caddr_t)&size_bytes, FREAD,
2516 			       curthread);
2517 	if (error) {
2518 		snprintf(req->error_str, sizeof(req->error_str),
2519 			 "error %d returned for DIOCGMEDIASIZE ioctl "
2520 			 "on %s!", error, be_lun->dev_path);
2521 		return (error);
2522 	}
2523 
2524 	if (params->lun_size_bytes != 0) {
2525 		if (params->lun_size_bytes > size_bytes) {
2526 			snprintf(req->error_str, sizeof(req->error_str),
2527 				 "requested LUN size %ju > backing device "
2528 				 "size %ju",
2529 				 (uintmax_t)params->lun_size_bytes,
2530 				 (uintmax_t)size_bytes);
2531 			return (EINVAL);
2532 		}
2533 
2534 		be_lun->size_bytes = params->lun_size_bytes;
2535 	} else {
2536 		be_lun->size_bytes = size_bytes;
2537 	}
2538 
2539 	return (0);
2540 }
2541 
2542 static int
2543 ctl_be_block_modify(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2544 {
2545 	struct ctl_lun_modify_params *params;
2546 	struct ctl_be_block_lun *be_lun;
2547 	uint64_t oldsize;
2548 	int error;
2549 
2550 	params = &req->reqdata.modify;
2551 
2552 	mtx_lock(&softc->lock);
2553 	be_lun = NULL;
2554 	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2555 		if (be_lun->ctl_be_lun.lun_id == params->lun_id)
2556 			break;
2557 	}
2558 	mtx_unlock(&softc->lock);
2559 
2560 	if (be_lun == NULL) {
2561 		snprintf(req->error_str, sizeof(req->error_str),
2562 			 "LUN %u is not managed by the block backend",
2563 			 params->lun_id);
2564 		goto bailout_error;
2565 	}
2566 
2567 	be_lun->params.lun_size_bytes = params->lun_size_bytes;
2568 
2569 	oldsize = be_lun->size_bytes;
2570 	if (be_lun->vn == NULL)
2571 		error = ctl_be_block_open(softc, be_lun, req);
2572 	else if (be_lun->vn->v_type == VREG)
2573 		error = ctl_be_block_modify_file(be_lun, req);
2574 	else
2575 		error = ctl_be_block_modify_dev(be_lun, req);
2576 
2577 	if (error == 0 && be_lun->size_bytes != oldsize) {
2578 		be_lun->size_blocks = be_lun->size_bytes >>
2579 		    be_lun->blocksize_shift;
2580 
2581 		/*
2582 		 * The maximum LBA is the size - 1.
2583 		 *
2584 		 * XXX: Note that this field is being updated without locking,
2585 		 * 	which might cause problems on 32-bit architectures.
2586 		 */
2587 		be_lun->ctl_be_lun.maxlba = (be_lun->size_blocks == 0) ?
2588 		    0 : (be_lun->size_blocks - 1);
2589 		be_lun->ctl_be_lun.blocksize = be_lun->blocksize;
2590 		be_lun->ctl_be_lun.pblockexp = be_lun->pblockexp;
2591 		be_lun->ctl_be_lun.pblockoff = be_lun->pblockoff;
2592 		if (be_lun->dispatch == ctl_be_block_dispatch_zvol &&
2593 		    be_lun->blocksize != 0)
2594 			be_lun->ctl_be_lun.atomicblock = CTLBLK_MAX_IO_SIZE /
2595 			    be_lun->blocksize;
2596 		ctl_lun_capacity_changed(&be_lun->ctl_be_lun);
2597 		if (oldsize == 0 && be_lun->size_blocks != 0)
2598 			ctl_lun_online(&be_lun->ctl_be_lun);
2599 	}
2600 
2601 	/* Tell the user the exact size we ended up using */
2602 	params->lun_size_bytes = be_lun->size_bytes;
2603 
2604 	req->status = error ? CTL_LUN_WARNING : CTL_LUN_OK;
2605 
2606 	return (0);
2607 
2608 bailout_error:
2609 	req->status = CTL_LUN_ERROR;
2610 
2611 	return (0);
2612 }
2613 
2614 static void
2615 ctl_be_block_lun_shutdown(void *be_lun)
2616 {
2617 	struct ctl_be_block_lun *lun;
2618 	struct ctl_be_block_softc *softc;
2619 
2620 	lun = (struct ctl_be_block_lun *)be_lun;
2621 
2622 	softc = lun->softc;
2623 
2624 	mtx_lock(&softc->lock);
2625 	lun->flags |= CTL_BE_BLOCK_LUN_UNCONFIGURED;
2626 	if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2627 		wakeup(lun);
2628 	mtx_unlock(&softc->lock);
2629 
2630 }
2631 
2632 static void
2633 ctl_be_block_lun_config_status(void *be_lun, ctl_lun_config_status status)
2634 {
2635 	struct ctl_be_block_lun *lun;
2636 	struct ctl_be_block_softc *softc;
2637 
2638 	lun = (struct ctl_be_block_lun *)be_lun;
2639 	softc = lun->softc;
2640 
2641 	if (status == CTL_LUN_CONFIG_OK) {
2642 		mtx_lock(&softc->lock);
2643 		lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2644 		if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2645 			wakeup(lun);
2646 		mtx_unlock(&softc->lock);
2647 
2648 		/*
2649 		 * We successfully added the LUN, attempt to enable it.
2650 		 */
2651 		if (ctl_enable_lun(&lun->ctl_be_lun) != 0) {
2652 			printf("%s: ctl_enable_lun() failed!\n", __func__);
2653 			if (ctl_invalidate_lun(&lun->ctl_be_lun) != 0) {
2654 				printf("%s: ctl_invalidate_lun() failed!\n",
2655 				       __func__);
2656 			}
2657 		}
2658 
2659 		return;
2660 	}
2661 
2662 
2663 	mtx_lock(&softc->lock);
2664 	lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2665 	lun->flags |= CTL_BE_BLOCK_LUN_CONFIG_ERR;
2666 	wakeup(lun);
2667 	mtx_unlock(&softc->lock);
2668 }
2669 
2670 
2671 static int
2672 ctl_be_block_config_write(union ctl_io *io)
2673 {
2674 	struct ctl_be_block_lun *be_lun;
2675 	struct ctl_be_lun *ctl_be_lun;
2676 	int retval;
2677 
2678 	retval = 0;
2679 
2680 	DPRINTF("entered\n");
2681 
2682 	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2683 		CTL_PRIV_BACKEND_LUN].ptr;
2684 	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
2685 
2686 	switch (io->scsiio.cdb[0]) {
2687 	case SYNCHRONIZE_CACHE:
2688 	case SYNCHRONIZE_CACHE_16:
2689 	case WRITE_SAME_10:
2690 	case WRITE_SAME_16:
2691 	case UNMAP:
2692 		/*
2693 		 * The upper level CTL code will filter out any CDBs with
2694 		 * the immediate bit set and return the proper error.
2695 		 *
2696 		 * We don't really need to worry about what LBA range the
2697 		 * user asked to be synced out.  When they issue a sync
2698 		 * cache command, we'll sync out the whole thing.
2699 		 */
2700 		mtx_lock(&be_lun->queue_lock);
2701 		STAILQ_INSERT_TAIL(&be_lun->config_write_queue, &io->io_hdr,
2702 				   links);
2703 		mtx_unlock(&be_lun->queue_lock);
2704 		taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
2705 		break;
2706 	case START_STOP_UNIT: {
2707 		struct scsi_start_stop_unit *cdb;
2708 
2709 		cdb = (struct scsi_start_stop_unit *)io->scsiio.cdb;
2710 
2711 		if (cdb->how & SSS_START)
2712 			retval = ctl_start_lun(ctl_be_lun);
2713 		else {
2714 			retval = ctl_stop_lun(ctl_be_lun);
2715 			/*
2716 			 * XXX KDM Copan-specific offline behavior.
2717 			 * Figure out a reasonable way to port this?
2718 			 */
2719 #ifdef NEEDTOPORT
2720 			if ((retval == 0)
2721 			 && (cdb->byte2 & SSS_ONOFFLINE))
2722 				retval = ctl_lun_offline(ctl_be_lun);
2723 #endif
2724 		}
2725 
2726 		/*
2727 		 * In general, the above routines should not fail.  They
2728 		 * just set state for the LUN.  So we've got something
2729 		 * pretty wrong here if we can't start or stop the LUN.
2730 		 */
2731 		if (retval != 0) {
2732 			ctl_set_internal_failure(&io->scsiio,
2733 						 /*sks_valid*/ 1,
2734 						 /*retry_count*/ 0xf051);
2735 			retval = CTL_RETVAL_COMPLETE;
2736 		} else {
2737 			ctl_set_success(&io->scsiio);
2738 		}
2739 		ctl_config_write_done(io);
2740 		break;
2741 	}
2742 	default:
2743 		ctl_set_invalid_opcode(&io->scsiio);
2744 		ctl_config_write_done(io);
2745 		retval = CTL_RETVAL_COMPLETE;
2746 		break;
2747 	}
2748 
2749 	return (retval);
2750 }
2751 
2752 static int
2753 ctl_be_block_config_read(union ctl_io *io)
2754 {
2755 	struct ctl_be_block_lun *be_lun;
2756 	struct ctl_be_lun *ctl_be_lun;
2757 	int retval = 0;
2758 
2759 	DPRINTF("entered\n");
2760 
2761 	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2762 		CTL_PRIV_BACKEND_LUN].ptr;
2763 	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
2764 
2765 	switch (io->scsiio.cdb[0]) {
2766 	case SERVICE_ACTION_IN:
2767 		if (io->scsiio.cdb[1] == SGLS_SERVICE_ACTION) {
2768 			mtx_lock(&be_lun->queue_lock);
2769 			STAILQ_INSERT_TAIL(&be_lun->config_read_queue,
2770 			    &io->io_hdr, links);
2771 			mtx_unlock(&be_lun->queue_lock);
2772 			taskqueue_enqueue(be_lun->io_taskqueue,
2773 			    &be_lun->io_task);
2774 			retval = CTL_RETVAL_QUEUED;
2775 			break;
2776 		}
2777 		ctl_set_invalid_field(&io->scsiio,
2778 				      /*sks_valid*/ 1,
2779 				      /*command*/ 1,
2780 				      /*field*/ 1,
2781 				      /*bit_valid*/ 1,
2782 				      /*bit*/ 4);
2783 		ctl_config_read_done(io);
2784 		retval = CTL_RETVAL_COMPLETE;
2785 		break;
2786 	default:
2787 		ctl_set_invalid_opcode(&io->scsiio);
2788 		ctl_config_read_done(io);
2789 		retval = CTL_RETVAL_COMPLETE;
2790 		break;
2791 	}
2792 
2793 	return (retval);
2794 }
2795 
2796 static int
2797 ctl_be_block_lun_info(void *be_lun, struct sbuf *sb)
2798 {
2799 	struct ctl_be_block_lun *lun;
2800 	int retval;
2801 
2802 	lun = (struct ctl_be_block_lun *)be_lun;
2803 	retval = 0;
2804 
2805 	retval = sbuf_printf(sb, "\t<num_threads>");
2806 
2807 	if (retval != 0)
2808 		goto bailout;
2809 
2810 	retval = sbuf_printf(sb, "%d", lun->num_threads);
2811 
2812 	if (retval != 0)
2813 		goto bailout;
2814 
2815 	retval = sbuf_printf(sb, "</num_threads>\n");
2816 
2817 bailout:
2818 
2819 	return (retval);
2820 }
2821 
2822 static uint64_t
2823 ctl_be_block_lun_attr(void *be_lun, const char *attrname)
2824 {
2825 	struct ctl_be_block_lun *lun = (struct ctl_be_block_lun *)be_lun;
2826 
2827 	if (lun->getattr == NULL)
2828 		return (UINT64_MAX);
2829 	return (lun->getattr(lun, attrname));
2830 }
2831 
2832 int
2833 ctl_be_block_init(void)
2834 {
2835 	struct ctl_be_block_softc *softc;
2836 	int retval;
2837 
2838 	softc = &backend_block_softc;
2839 	retval = 0;
2840 
2841 	mtx_init(&softc->lock, "ctlblock", NULL, MTX_DEF);
2842 	beio_zone = uma_zcreate("beio", sizeof(struct ctl_be_block_io),
2843 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
2844 	STAILQ_INIT(&softc->disk_list);
2845 	STAILQ_INIT(&softc->lun_list);
2846 
2847 	return (retval);
2848 }
2849