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