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