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