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