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