ctl_backend_block.c revision 288726
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 288726 2015-10-05 08:50:15Z 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_ioctl.h>
90#include <cam/ctl/ctl_scsi_all.h>
91#include <cam/ctl/ctl_error.h>
92
93/*
94 * The idea here is that we'll allocate enough S/G space to hold a 1MB
95 * I/O.  If we get an I/O larger than that, we'll split it.
96 */
97#define	CTLBLK_HALF_IO_SIZE	(512 * 1024)
98#define	CTLBLK_MAX_IO_SIZE	(CTLBLK_HALF_IO_SIZE * 2)
99#define	CTLBLK_MAX_SEG		MAXPHYS
100#define	CTLBLK_HALF_SEGS	MAX(CTLBLK_HALF_IO_SIZE / CTLBLK_MAX_SEG, 1)
101#define	CTLBLK_MAX_SEGS		(CTLBLK_HALF_SEGS * 2)
102
103#ifdef CTLBLK_DEBUG
104#define DPRINTF(fmt, args...) \
105    printf("cbb(%s:%d): " fmt, __FUNCTION__, __LINE__, ##args)
106#else
107#define DPRINTF(fmt, args...) do {} while(0)
108#endif
109
110#define PRIV(io)	\
111    ((struct ctl_ptr_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_BACKEND])
112#define ARGS(io)	\
113    ((struct ctl_lba_len_flags *)&(io)->io_hdr.ctl_private[CTL_PRIV_LBA_LEN])
114
115SDT_PROVIDER_DEFINE(cbb);
116
117typedef enum {
118	CTL_BE_BLOCK_LUN_UNCONFIGURED	= 0x01,
119	CTL_BE_BLOCK_LUN_CONFIG_ERR	= 0x02,
120	CTL_BE_BLOCK_LUN_WAITING	= 0x04,
121	CTL_BE_BLOCK_LUN_MULTI_THREAD	= 0x08
122} ctl_be_block_lun_flags;
123
124typedef enum {
125	CTL_BE_BLOCK_NONE,
126	CTL_BE_BLOCK_DEV,
127	CTL_BE_BLOCK_FILE
128} ctl_be_block_type;
129
130struct ctl_be_block_devdata {
131	struct cdev *cdev;
132	struct cdevsw *csw;
133	int dev_ref;
134};
135
136struct ctl_be_block_filedata {
137	struct ucred *cred;
138};
139
140union ctl_be_block_bedata {
141	struct ctl_be_block_devdata dev;
142	struct ctl_be_block_filedata file;
143};
144
145struct ctl_be_block_io;
146struct ctl_be_block_lun;
147
148typedef void (*cbb_dispatch_t)(struct ctl_be_block_lun *be_lun,
149			       struct ctl_be_block_io *beio);
150typedef uint64_t (*cbb_getattr_t)(struct ctl_be_block_lun *be_lun,
151				  const char *attrname);
152
153/*
154 * Backend LUN structure.  There is a 1:1 mapping between a block device
155 * and a backend block LUN, and between a backend block LUN and a CTL LUN.
156 */
157struct ctl_be_block_lun {
158	struct ctl_lun_create_params params;
159	char lunname[32];
160	char *dev_path;
161	ctl_be_block_type dev_type;
162	struct vnode *vn;
163	union ctl_be_block_bedata backend;
164	cbb_dispatch_t dispatch;
165	cbb_dispatch_t lun_flush;
166	cbb_dispatch_t unmap;
167	cbb_dispatch_t get_lba_status;
168	cbb_getattr_t getattr;
169	uma_zone_t lun_zone;
170	uint64_t size_blocks;
171	uint64_t size_bytes;
172	uint32_t blocksize;
173	uint16_t pblockexp;
174	uint16_t pblockoff;
175	uint16_t ublockexp;
176	uint16_t ublockoff;
177	uint32_t atomicblock;
178	uint32_t opttxferlen;
179	struct ctl_be_block_softc *softc;
180	struct devstat *disk_stats;
181	ctl_be_block_lun_flags flags;
182	STAILQ_ENTRY(ctl_be_block_lun) links;
183	struct ctl_be_lun ctl_be_lun;
184	struct taskqueue *io_taskqueue;
185	struct task io_task;
186	int num_threads;
187	STAILQ_HEAD(, ctl_io_hdr) input_queue;
188	STAILQ_HEAD(, ctl_io_hdr) config_read_queue;
189	STAILQ_HEAD(, ctl_io_hdr) config_write_queue;
190	STAILQ_HEAD(, ctl_io_hdr) datamove_queue;
191	struct mtx_padalign io_lock;
192	struct mtx_padalign queue_lock;
193};
194
195/*
196 * Overall softc structure for the block backend module.
197 */
198struct ctl_be_block_softc {
199	struct mtx			 lock;
200	int				 num_luns;
201	STAILQ_HEAD(, ctl_be_block_lun)	 lun_list;
202};
203
204static struct ctl_be_block_softc backend_block_softc;
205
206/*
207 * Per-I/O information.
208 */
209struct ctl_be_block_io {
210	union ctl_io			*io;
211	struct ctl_sg_entry		sg_segs[CTLBLK_MAX_SEGS];
212	struct iovec			xiovecs[CTLBLK_MAX_SEGS];
213	int				bio_cmd;
214	int				num_segs;
215	int				num_bios_sent;
216	int				num_bios_done;
217	int				send_complete;
218	int				num_errors;
219	struct bintime			ds_t0;
220	devstat_tag_type		ds_tag_type;
221	devstat_trans_flags		ds_trans_type;
222	uint64_t			io_len;
223	uint64_t			io_offset;
224	int				io_arg;
225	struct ctl_be_block_softc	*softc;
226	struct ctl_be_block_lun		*lun;
227	void (*beio_cont)(struct ctl_be_block_io *beio); /* to continue processing */
228};
229
230static int cbb_num_threads = 14;
231TUNABLE_INT("kern.cam.ctl.block.num_threads", &cbb_num_threads);
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_RW,
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, tmp;
1865	off_t			      ps, pss, po, pos, us, uss, uo, uos, otmp;
1866
1867	params = &be_lun->params;
1868
1869	be_lun->dev_type = CTL_BE_BLOCK_DEV;
1870	be_lun->backend.dev.cdev = be_lun->vn->v_rdev;
1871	be_lun->backend.dev.csw = dev_refthread(be_lun->backend.dev.cdev,
1872					     &be_lun->backend.dev.dev_ref);
1873	if (be_lun->backend.dev.csw == NULL)
1874		panic("Unable to retrieve device switch");
1875	if (strcmp(be_lun->backend.dev.csw->d_name, "zvol") == 0) {
1876		be_lun->dispatch = ctl_be_block_dispatch_zvol;
1877		be_lun->get_lba_status = ctl_be_block_gls_zvol;
1878		atomic = maxio = CTLBLK_MAX_IO_SIZE;
1879	} else {
1880		be_lun->dispatch = ctl_be_block_dispatch_dev;
1881		atomic = 0;
1882		maxio = be_lun->backend.dev.cdev->si_iosize_max;
1883		if (maxio <= 0)
1884			maxio = DFLTPHYS;
1885		if (maxio > CTLBLK_MAX_IO_SIZE)
1886			maxio = CTLBLK_MAX_IO_SIZE;
1887	}
1888	be_lun->lun_flush = ctl_be_block_flush_dev;
1889	be_lun->getattr = ctl_be_block_getattr_dev;
1890
1891	error = VOP_GETATTR(be_lun->vn, &vattr, NOCRED);
1892	if (error) {
1893		snprintf(req->error_str, sizeof(req->error_str),
1894			 "error getting vnode attributes for device %s",
1895			 be_lun->dev_path);
1896		return (error);
1897	}
1898
1899	dev = be_lun->vn->v_rdev;
1900	devsw = dev->si_devsw;
1901	if (!devsw->d_ioctl) {
1902		snprintf(req->error_str, sizeof(req->error_str),
1903			 "no d_ioctl for device %s!",
1904			 be_lun->dev_path);
1905		return (ENODEV);
1906	}
1907
1908	error = devsw->d_ioctl(dev, DIOCGSECTORSIZE, (caddr_t)&tmp, FREAD,
1909			       curthread);
1910	if (error) {
1911		snprintf(req->error_str, sizeof(req->error_str),
1912			 "error %d returned for DIOCGSECTORSIZE ioctl "
1913			 "on %s!", error, be_lun->dev_path);
1914		return (error);
1915	}
1916
1917	/*
1918	 * If the user has asked for a blocksize that is greater than the
1919	 * backing device's blocksize, we can do it only if the blocksize
1920	 * the user is asking for is an even multiple of the underlying
1921	 * device's blocksize.
1922	 */
1923	if ((params->blocksize_bytes != 0) &&
1924	    (params->blocksize_bytes >= tmp)) {
1925		if (params->blocksize_bytes % tmp == 0) {
1926			be_lun->blocksize = params->blocksize_bytes;
1927		} else {
1928			snprintf(req->error_str, sizeof(req->error_str),
1929				 "requested blocksize %u is not an even "
1930				 "multiple of backing device blocksize %u",
1931				 params->blocksize_bytes, tmp);
1932			return (EINVAL);
1933
1934		}
1935	} else if (params->blocksize_bytes != 0) {
1936		snprintf(req->error_str, sizeof(req->error_str),
1937			 "requested blocksize %u < backing device "
1938			 "blocksize %u", params->blocksize_bytes, tmp);
1939		return (EINVAL);
1940	} else
1941		be_lun->blocksize = tmp;
1942
1943	error = devsw->d_ioctl(dev, DIOCGMEDIASIZE, (caddr_t)&otmp, FREAD,
1944			       curthread);
1945	if (error) {
1946		snprintf(req->error_str, sizeof(req->error_str),
1947			 "error %d returned for DIOCGMEDIASIZE "
1948			 " ioctl on %s!", error,
1949			 be_lun->dev_path);
1950		return (error);
1951	}
1952
1953	if (params->lun_size_bytes != 0) {
1954		if (params->lun_size_bytes > otmp) {
1955			snprintf(req->error_str, sizeof(req->error_str),
1956				 "requested LUN size %ju > backing device "
1957				 "size %ju",
1958				 (uintmax_t)params->lun_size_bytes,
1959				 (uintmax_t)otmp);
1960			return (EINVAL);
1961		}
1962
1963		be_lun->size_bytes = params->lun_size_bytes;
1964	} else
1965		be_lun->size_bytes = otmp;
1966
1967	error = devsw->d_ioctl(dev, DIOCGSTRIPESIZE,
1968			       (caddr_t)&ps, FREAD, curthread);
1969	if (error)
1970		ps = po = 0;
1971	else {
1972		error = devsw->d_ioctl(dev, DIOCGSTRIPEOFFSET,
1973				       (caddr_t)&po, FREAD, curthread);
1974		if (error)
1975			po = 0;
1976	}
1977	us = ps;
1978	uo = po;
1979
1980	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "pblocksize");
1981	if (value != NULL)
1982		ctl_expand_number(value, &ps);
1983	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "pblockoffset");
1984	if (value != NULL)
1985		ctl_expand_number(value, &po);
1986	pss = ps / be_lun->blocksize;
1987	pos = po / be_lun->blocksize;
1988	if ((pss > 0) && (pss * be_lun->blocksize == ps) && (pss >= pos) &&
1989	    ((pss & (pss - 1)) == 0) && (pos * be_lun->blocksize == po)) {
1990		be_lun->pblockexp = fls(pss) - 1;
1991		be_lun->pblockoff = (pss - pos) % pss;
1992	}
1993
1994	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "ublocksize");
1995	if (value != NULL)
1996		ctl_expand_number(value, &us);
1997	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "ublockoffset");
1998	if (value != NULL)
1999		ctl_expand_number(value, &uo);
2000	uss = us / be_lun->blocksize;
2001	uos = uo / be_lun->blocksize;
2002	if ((uss > 0) && (uss * be_lun->blocksize == us) && (uss >= uos) &&
2003	    ((uss & (uss - 1)) == 0) && (uos * be_lun->blocksize == uo)) {
2004		be_lun->ublockexp = fls(uss) - 1;
2005		be_lun->ublockoff = (uss - uos) % uss;
2006	}
2007
2008	be_lun->atomicblock = atomic / be_lun->blocksize;
2009	be_lun->opttxferlen = maxio / be_lun->blocksize;
2010
2011	if (be_lun->dispatch == ctl_be_block_dispatch_zvol) {
2012		unmap = 1;
2013	} else {
2014		struct diocgattr_arg	arg;
2015
2016		strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
2017		arg.len = sizeof(arg.value.i);
2018		error = devsw->d_ioctl(dev, DIOCGATTR,
2019		    (caddr_t)&arg, FREAD, curthread);
2020		unmap = (error == 0) ? arg.value.i : 0;
2021	}
2022	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "unmap");
2023	if (value != NULL)
2024		unmap = (strcmp(value, "on") == 0);
2025	if (unmap)
2026		be_lun->unmap = ctl_be_block_unmap_dev;
2027
2028	return (0);
2029}
2030
2031static int
2032ctl_be_block_close(struct ctl_be_block_lun *be_lun)
2033{
2034	DROP_GIANT();
2035	if (be_lun->vn) {
2036		int flags = FREAD | FWRITE;
2037
2038		switch (be_lun->dev_type) {
2039		case CTL_BE_BLOCK_DEV:
2040			if (be_lun->backend.dev.csw) {
2041				dev_relthread(be_lun->backend.dev.cdev,
2042					      be_lun->backend.dev.dev_ref);
2043				be_lun->backend.dev.csw  = NULL;
2044				be_lun->backend.dev.cdev = NULL;
2045			}
2046			break;
2047		case CTL_BE_BLOCK_FILE:
2048			break;
2049		case CTL_BE_BLOCK_NONE:
2050			break;
2051		default:
2052			panic("Unexpected backend type.");
2053			break;
2054		}
2055
2056		(void)vn_close(be_lun->vn, flags, NOCRED, curthread);
2057		be_lun->vn = NULL;
2058
2059		switch (be_lun->dev_type) {
2060		case CTL_BE_BLOCK_DEV:
2061			break;
2062		case CTL_BE_BLOCK_FILE:
2063			if (be_lun->backend.file.cred != NULL) {
2064				crfree(be_lun->backend.file.cred);
2065				be_lun->backend.file.cred = NULL;
2066			}
2067			break;
2068		case CTL_BE_BLOCK_NONE:
2069			break;
2070		default:
2071			panic("Unexpected backend type.");
2072			break;
2073		}
2074		be_lun->dev_type = CTL_BE_BLOCK_NONE;
2075	}
2076	PICKUP_GIANT();
2077
2078	return (0);
2079}
2080
2081static int
2082ctl_be_block_open(struct ctl_be_block_softc *softc,
2083		       struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
2084{
2085	struct nameidata nd;
2086	int		 flags;
2087	int		 error;
2088
2089	/*
2090	 * XXX KDM allow a read-only option?
2091	 */
2092	flags = FREAD | FWRITE;
2093	error = 0;
2094
2095	if (rootvnode == NULL) {
2096		snprintf(req->error_str, sizeof(req->error_str),
2097			 "Root filesystem is not mounted");
2098		return (1);
2099	}
2100
2101	if (!curthread->td_proc->p_fd->fd_cdir) {
2102		curthread->td_proc->p_fd->fd_cdir = rootvnode;
2103		VREF(rootvnode);
2104	}
2105	if (!curthread->td_proc->p_fd->fd_rdir) {
2106		curthread->td_proc->p_fd->fd_rdir = rootvnode;
2107		VREF(rootvnode);
2108	}
2109	if (!curthread->td_proc->p_fd->fd_jdir) {
2110		curthread->td_proc->p_fd->fd_jdir = rootvnode;
2111		VREF(rootvnode);
2112	}
2113
2114 again:
2115	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, be_lun->dev_path, curthread);
2116	error = vn_open(&nd, &flags, 0, NULL);
2117	if (error) {
2118		/*
2119		 * This is the only reasonable guess we can make as far as
2120		 * path if the user doesn't give us a fully qualified path.
2121		 * If they want to specify a file, they need to specify the
2122		 * full path.
2123		 */
2124		if (be_lun->dev_path[0] != '/') {
2125			char *dev_path = "/dev/";
2126			char *dev_name;
2127
2128			/* Try adding device path at beginning of name */
2129			dev_name = malloc(strlen(be_lun->dev_path)
2130					+ strlen(dev_path) + 1,
2131					  M_CTLBLK, M_WAITOK);
2132			if (dev_name) {
2133				sprintf(dev_name, "%s%s", dev_path,
2134					be_lun->dev_path);
2135				free(be_lun->dev_path, M_CTLBLK);
2136				be_lun->dev_path = dev_name;
2137				goto again;
2138			}
2139		}
2140		snprintf(req->error_str, sizeof(req->error_str),
2141		    "error opening %s: %d", be_lun->dev_path, error);
2142		return (error);
2143	}
2144
2145	NDFREE(&nd, NDF_ONLY_PNBUF);
2146
2147	be_lun->vn = nd.ni_vp;
2148
2149	/* We only support disks and files. */
2150	if (vn_isdisk(be_lun->vn, &error)) {
2151		error = ctl_be_block_open_dev(be_lun, req);
2152	} else if (be_lun->vn->v_type == VREG) {
2153		error = ctl_be_block_open_file(be_lun, req);
2154	} else {
2155		error = EINVAL;
2156		snprintf(req->error_str, sizeof(req->error_str),
2157			 "%s is not a disk or plain file", be_lun->dev_path);
2158	}
2159	VOP_UNLOCK(be_lun->vn, 0);
2160
2161	if (error != 0)
2162		ctl_be_block_close(be_lun);
2163	return (0);
2164}
2165
2166static int
2167ctl_be_block_create(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2168{
2169	struct ctl_be_block_lun *be_lun;
2170	struct ctl_lun_create_params *params;
2171	char num_thread_str[16];
2172	char tmpstr[32];
2173	char *value;
2174	int retval, num_threads;
2175	int tmp_num_threads;
2176
2177	params = &req->reqdata.create;
2178	retval = 0;
2179	req->status = CTL_LUN_OK;
2180
2181	num_threads = cbb_num_threads;
2182
2183	be_lun = malloc(sizeof(*be_lun), M_CTLBLK, M_ZERO | M_WAITOK);
2184
2185	be_lun->params = req->reqdata.create;
2186	be_lun->softc = softc;
2187	STAILQ_INIT(&be_lun->input_queue);
2188	STAILQ_INIT(&be_lun->config_read_queue);
2189	STAILQ_INIT(&be_lun->config_write_queue);
2190	STAILQ_INIT(&be_lun->datamove_queue);
2191	sprintf(be_lun->lunname, "cblk%d", softc->num_luns);
2192	mtx_init(&be_lun->io_lock, "cblk io lock", NULL, MTX_DEF);
2193	mtx_init(&be_lun->queue_lock, "cblk queue lock", NULL, MTX_DEF);
2194	ctl_init_opts(&be_lun->ctl_be_lun.options,
2195	    req->num_be_args, req->kern_be_args);
2196
2197	be_lun->lun_zone = uma_zcreate(be_lun->lunname, CTLBLK_MAX_SEG,
2198	    NULL, NULL, NULL, NULL, /*align*/ 0, /*flags*/0);
2199
2200	if (be_lun->lun_zone == NULL) {
2201		snprintf(req->error_str, sizeof(req->error_str),
2202			 "error allocating UMA zone");
2203		goto bailout_error;
2204	}
2205
2206	if (params->flags & CTL_LUN_FLAG_DEV_TYPE)
2207		be_lun->ctl_be_lun.lun_type = params->device_type;
2208	else
2209		be_lun->ctl_be_lun.lun_type = T_DIRECT;
2210
2211	if (be_lun->ctl_be_lun.lun_type == T_DIRECT) {
2212		value = ctl_get_opt(&be_lun->ctl_be_lun.options, "file");
2213		if (value == NULL) {
2214			snprintf(req->error_str, sizeof(req->error_str),
2215				 "no file argument specified");
2216			goto bailout_error;
2217		}
2218		be_lun->dev_path = strdup(value, M_CTLBLK);
2219		be_lun->size_bytes = params->lun_size_bytes;
2220		if (params->blocksize_bytes != 0)
2221			be_lun->blocksize = params->blocksize_bytes;
2222		else
2223			be_lun->blocksize = 512;
2224
2225		retval = ctl_be_block_open(softc, be_lun, req);
2226		be_lun->size_blocks = be_lun->size_bytes / be_lun->blocksize;
2227		if (retval != 0) {
2228			retval = 0;
2229			req->status = CTL_LUN_WARNING;
2230		}
2231	} else {
2232		/*
2233		 * For processor devices, we don't have any size.
2234		 */
2235		be_lun->blocksize = 0;
2236		be_lun->pblockexp = 0;
2237		be_lun->pblockoff = 0;
2238		be_lun->ublockexp = 0;
2239		be_lun->ublockoff = 0;
2240		be_lun->size_blocks = 0;
2241		be_lun->size_bytes = 0;
2242		be_lun->ctl_be_lun.maxlba = 0;
2243
2244		/*
2245		 * Default to just 1 thread for processor devices.
2246		 */
2247		num_threads = 1;
2248	}
2249
2250	/*
2251	 * XXX This searching loop might be refactored to be combined with
2252	 * the loop above,
2253	 */
2254	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "num_threads");
2255	if (value != NULL) {
2256		tmp_num_threads = strtol(value, NULL, 0);
2257
2258		/*
2259		 * We don't let the user specify less than one
2260		 * thread, but hope he's clueful enough not to
2261		 * specify 1000 threads.
2262		 */
2263		if (tmp_num_threads < 1) {
2264			snprintf(req->error_str, sizeof(req->error_str),
2265				 "invalid number of threads %s",
2266				 num_thread_str);
2267			goto bailout_error;
2268		}
2269		num_threads = tmp_num_threads;
2270	}
2271
2272	be_lun->flags = CTL_BE_BLOCK_LUN_UNCONFIGURED;
2273	be_lun->ctl_be_lun.flags = CTL_LUN_FLAG_PRIMARY;
2274	if (be_lun->vn == NULL)
2275		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_OFFLINE;
2276	if (be_lun->unmap != NULL)
2277		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_UNMAP;
2278	if (be_lun->dispatch != ctl_be_block_dispatch_dev)
2279		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_SERSEQ_READ;
2280	be_lun->ctl_be_lun.be_lun = be_lun;
2281	be_lun->ctl_be_lun.maxlba = (be_lun->size_blocks == 0) ?
2282	    0 : (be_lun->size_blocks - 1);
2283	be_lun->ctl_be_lun.blocksize = be_lun->blocksize;
2284	be_lun->ctl_be_lun.pblockexp = be_lun->pblockexp;
2285	be_lun->ctl_be_lun.pblockoff = be_lun->pblockoff;
2286	be_lun->ctl_be_lun.ublockexp = be_lun->ublockexp;
2287	be_lun->ctl_be_lun.ublockoff = be_lun->ublockoff;
2288	be_lun->ctl_be_lun.atomicblock = be_lun->atomicblock;
2289	be_lun->ctl_be_lun.opttxferlen = be_lun->opttxferlen;
2290	/* Tell the user the blocksize we ended up using */
2291	params->lun_size_bytes = be_lun->size_bytes;
2292	params->blocksize_bytes = be_lun->blocksize;
2293	if (params->flags & CTL_LUN_FLAG_ID_REQ) {
2294		be_lun->ctl_be_lun.req_lun_id = params->req_lun_id;
2295		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_ID_REQ;
2296	} else
2297		be_lun->ctl_be_lun.req_lun_id = 0;
2298
2299	be_lun->ctl_be_lun.lun_shutdown = ctl_be_block_lun_shutdown;
2300	be_lun->ctl_be_lun.lun_config_status =
2301		ctl_be_block_lun_config_status;
2302	be_lun->ctl_be_lun.be = &ctl_be_block_driver;
2303
2304	if ((params->flags & CTL_LUN_FLAG_SERIAL_NUM) == 0) {
2305		snprintf(tmpstr, sizeof(tmpstr), "MYSERIAL%4d",
2306			 softc->num_luns);
2307		strncpy((char *)be_lun->ctl_be_lun.serial_num, tmpstr,
2308			MIN(sizeof(be_lun->ctl_be_lun.serial_num),
2309			sizeof(tmpstr)));
2310
2311		/* Tell the user what we used for a serial number */
2312		strncpy((char *)params->serial_num, tmpstr,
2313			MIN(sizeof(params->serial_num), sizeof(tmpstr)));
2314	} else {
2315		strncpy((char *)be_lun->ctl_be_lun.serial_num,
2316			params->serial_num,
2317			MIN(sizeof(be_lun->ctl_be_lun.serial_num),
2318			sizeof(params->serial_num)));
2319	}
2320	if ((params->flags & CTL_LUN_FLAG_DEVID) == 0) {
2321		snprintf(tmpstr, sizeof(tmpstr), "MYDEVID%4d", softc->num_luns);
2322		strncpy((char *)be_lun->ctl_be_lun.device_id, tmpstr,
2323			MIN(sizeof(be_lun->ctl_be_lun.device_id),
2324			sizeof(tmpstr)));
2325
2326		/* Tell the user what we used for a device ID */
2327		strncpy((char *)params->device_id, tmpstr,
2328			MIN(sizeof(params->device_id), sizeof(tmpstr)));
2329	} else {
2330		strncpy((char *)be_lun->ctl_be_lun.device_id,
2331			params->device_id,
2332			MIN(sizeof(be_lun->ctl_be_lun.device_id),
2333			    sizeof(params->device_id)));
2334	}
2335
2336	TASK_INIT(&be_lun->io_task, /*priority*/0, ctl_be_block_worker, be_lun);
2337
2338	be_lun->io_taskqueue = taskqueue_create(be_lun->lunname, M_WAITOK,
2339	    taskqueue_thread_enqueue, /*context*/&be_lun->io_taskqueue);
2340
2341	if (be_lun->io_taskqueue == NULL) {
2342		snprintf(req->error_str, sizeof(req->error_str),
2343			 "unable to create taskqueue");
2344		goto bailout_error;
2345	}
2346
2347	/*
2348	 * Note that we start the same number of threads by default for
2349	 * both the file case and the block device case.  For the file
2350	 * case, we need multiple threads to allow concurrency, because the
2351	 * vnode interface is designed to be a blocking interface.  For the
2352	 * block device case, ZFS zvols at least will block the caller's
2353	 * context in many instances, and so we need multiple threads to
2354	 * overcome that problem.  Other block devices don't need as many
2355	 * threads, but they shouldn't cause too many problems.
2356	 *
2357	 * If the user wants to just have a single thread for a block
2358	 * device, he can specify that when the LUN is created, or change
2359	 * the tunable/sysctl to alter the default number of threads.
2360	 */
2361	retval = taskqueue_start_threads(&be_lun->io_taskqueue,
2362					 /*num threads*/num_threads,
2363					 /*priority*/PWAIT,
2364					 /*thread name*/
2365					 "%s taskq", be_lun->lunname);
2366
2367	if (retval != 0)
2368		goto bailout_error;
2369
2370	be_lun->num_threads = num_threads;
2371
2372	mtx_lock(&softc->lock);
2373	softc->num_luns++;
2374	STAILQ_INSERT_TAIL(&softc->lun_list, be_lun, links);
2375
2376	mtx_unlock(&softc->lock);
2377
2378	retval = ctl_add_lun(&be_lun->ctl_be_lun);
2379	if (retval != 0) {
2380		mtx_lock(&softc->lock);
2381		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2382			      links);
2383		softc->num_luns--;
2384		mtx_unlock(&softc->lock);
2385		snprintf(req->error_str, sizeof(req->error_str),
2386			 "ctl_add_lun() returned error %d, see dmesg for "
2387			 "details", retval);
2388		retval = 0;
2389		goto bailout_error;
2390	}
2391
2392	mtx_lock(&softc->lock);
2393
2394	/*
2395	 * Tell the config_status routine that we're waiting so it won't
2396	 * clean up the LUN in the event of an error.
2397	 */
2398	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2399
2400	while (be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) {
2401		retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2402		if (retval == EINTR)
2403			break;
2404	}
2405	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2406
2407	if (be_lun->flags & CTL_BE_BLOCK_LUN_CONFIG_ERR) {
2408		snprintf(req->error_str, sizeof(req->error_str),
2409			 "LUN configuration error, see dmesg for details");
2410		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2411			      links);
2412		softc->num_luns--;
2413		mtx_unlock(&softc->lock);
2414		goto bailout_error;
2415	} else {
2416		params->req_lun_id = be_lun->ctl_be_lun.lun_id;
2417	}
2418
2419	mtx_unlock(&softc->lock);
2420
2421	be_lun->disk_stats = devstat_new_entry("cbb", params->req_lun_id,
2422					       be_lun->blocksize,
2423					       DEVSTAT_ALL_SUPPORTED,
2424					       be_lun->ctl_be_lun.lun_type
2425					       | DEVSTAT_TYPE_IF_OTHER,
2426					       DEVSTAT_PRIORITY_OTHER);
2427
2428	return (retval);
2429
2430bailout_error:
2431	req->status = CTL_LUN_ERROR;
2432
2433	if (be_lun->io_taskqueue != NULL)
2434		taskqueue_free(be_lun->io_taskqueue);
2435	ctl_be_block_close(be_lun);
2436	if (be_lun->dev_path != NULL)
2437		free(be_lun->dev_path, M_CTLBLK);
2438	if (be_lun->lun_zone != NULL)
2439		uma_zdestroy(be_lun->lun_zone);
2440	ctl_free_opts(&be_lun->ctl_be_lun.options);
2441	mtx_destroy(&be_lun->queue_lock);
2442	mtx_destroy(&be_lun->io_lock);
2443	free(be_lun, M_CTLBLK);
2444
2445	return (retval);
2446}
2447
2448static int
2449ctl_be_block_rm(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2450{
2451	struct ctl_lun_rm_params *params;
2452	struct ctl_be_block_lun *be_lun;
2453	int retval;
2454
2455	params = &req->reqdata.rm;
2456
2457	mtx_lock(&softc->lock);
2458
2459	be_lun = NULL;
2460
2461	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2462		if (be_lun->ctl_be_lun.lun_id == params->lun_id)
2463			break;
2464	}
2465	mtx_unlock(&softc->lock);
2466
2467	if (be_lun == NULL) {
2468		snprintf(req->error_str, sizeof(req->error_str),
2469			 "LUN %u is not managed by the block backend",
2470			 params->lun_id);
2471		goto bailout_error;
2472	}
2473
2474	retval = ctl_disable_lun(&be_lun->ctl_be_lun);
2475
2476	if (retval != 0) {
2477		snprintf(req->error_str, sizeof(req->error_str),
2478			 "error %d returned from ctl_disable_lun() for "
2479			 "LUN %d", retval, params->lun_id);
2480		goto bailout_error;
2481
2482	}
2483
2484	retval = ctl_invalidate_lun(&be_lun->ctl_be_lun);
2485	if (retval != 0) {
2486		snprintf(req->error_str, sizeof(req->error_str),
2487			 "error %d returned from ctl_invalidate_lun() for "
2488			 "LUN %d", retval, params->lun_id);
2489		goto bailout_error;
2490	}
2491
2492	mtx_lock(&softc->lock);
2493
2494	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2495
2496	while ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2497                retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2498                if (retval == EINTR)
2499                        break;
2500        }
2501
2502	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2503
2504	if ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2505		snprintf(req->error_str, sizeof(req->error_str),
2506			 "interrupted waiting for LUN to be freed");
2507		mtx_unlock(&softc->lock);
2508		goto bailout_error;
2509	}
2510
2511	STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun, links);
2512
2513	softc->num_luns--;
2514	mtx_unlock(&softc->lock);
2515
2516	taskqueue_drain(be_lun->io_taskqueue, &be_lun->io_task);
2517
2518	taskqueue_free(be_lun->io_taskqueue);
2519
2520	ctl_be_block_close(be_lun);
2521
2522	if (be_lun->disk_stats != NULL)
2523		devstat_remove_entry(be_lun->disk_stats);
2524
2525	uma_zdestroy(be_lun->lun_zone);
2526
2527	ctl_free_opts(&be_lun->ctl_be_lun.options);
2528	free(be_lun->dev_path, M_CTLBLK);
2529	mtx_destroy(&be_lun->queue_lock);
2530	mtx_destroy(&be_lun->io_lock);
2531	free(be_lun, M_CTLBLK);
2532
2533	req->status = CTL_LUN_OK;
2534
2535	return (0);
2536
2537bailout_error:
2538
2539	req->status = CTL_LUN_ERROR;
2540
2541	return (0);
2542}
2543
2544static int
2545ctl_be_block_modify_file(struct ctl_be_block_lun *be_lun,
2546			 struct ctl_lun_req *req)
2547{
2548	struct vattr vattr;
2549	int error;
2550	struct ctl_lun_create_params *params = &be_lun->params;
2551
2552	if (params->lun_size_bytes != 0) {
2553		be_lun->size_bytes = params->lun_size_bytes;
2554	} else  {
2555		vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
2556		error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
2557		VOP_UNLOCK(be_lun->vn, 0);
2558		if (error != 0) {
2559			snprintf(req->error_str, sizeof(req->error_str),
2560				 "error calling VOP_GETATTR() for file %s",
2561				 be_lun->dev_path);
2562			return (error);
2563		}
2564
2565		be_lun->size_bytes = vattr.va_size;
2566	}
2567
2568	return (0);
2569}
2570
2571static int
2572ctl_be_block_modify_dev(struct ctl_be_block_lun *be_lun,
2573			struct ctl_lun_req *req)
2574{
2575	struct ctl_be_block_devdata *dev_data;
2576	int error;
2577	struct ctl_lun_create_params *params = &be_lun->params;
2578	uint64_t size_bytes;
2579
2580	dev_data = &be_lun->backend.dev;
2581	if (!dev_data->csw->d_ioctl) {
2582		snprintf(req->error_str, sizeof(req->error_str),
2583			 "no d_ioctl for device %s!", be_lun->dev_path);
2584		return (ENODEV);
2585	}
2586
2587	error = dev_data->csw->d_ioctl(dev_data->cdev, DIOCGMEDIASIZE,
2588			       (caddr_t)&size_bytes, FREAD,
2589			       curthread);
2590	if (error) {
2591		snprintf(req->error_str, sizeof(req->error_str),
2592			 "error %d returned for DIOCGMEDIASIZE ioctl "
2593			 "on %s!", error, be_lun->dev_path);
2594		return (error);
2595	}
2596
2597	if (params->lun_size_bytes != 0) {
2598		if (params->lun_size_bytes > size_bytes) {
2599			snprintf(req->error_str, sizeof(req->error_str),
2600				 "requested LUN size %ju > backing device "
2601				 "size %ju",
2602				 (uintmax_t)params->lun_size_bytes,
2603				 (uintmax_t)size_bytes);
2604			return (EINVAL);
2605		}
2606
2607		be_lun->size_bytes = params->lun_size_bytes;
2608	} else {
2609		be_lun->size_bytes = size_bytes;
2610	}
2611
2612	return (0);
2613}
2614
2615static int
2616ctl_be_block_modify(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2617{
2618	struct ctl_lun_modify_params *params;
2619	struct ctl_be_block_lun *be_lun;
2620	uint64_t oldsize;
2621	int error;
2622
2623	params = &req->reqdata.modify;
2624
2625	mtx_lock(&softc->lock);
2626	be_lun = NULL;
2627	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2628		if (be_lun->ctl_be_lun.lun_id == params->lun_id)
2629			break;
2630	}
2631	mtx_unlock(&softc->lock);
2632
2633	if (be_lun == NULL) {
2634		snprintf(req->error_str, sizeof(req->error_str),
2635			 "LUN %u is not managed by the block backend",
2636			 params->lun_id);
2637		goto bailout_error;
2638	}
2639
2640	be_lun->params.lun_size_bytes = params->lun_size_bytes;
2641
2642	oldsize = be_lun->size_bytes;
2643	if (be_lun->vn == NULL)
2644		error = ctl_be_block_open(softc, be_lun, req);
2645	else if (vn_isdisk(be_lun->vn, &error))
2646		error = ctl_be_block_modify_dev(be_lun, req);
2647	else if (be_lun->vn->v_type == VREG)
2648		error = ctl_be_block_modify_file(be_lun, req);
2649	else
2650		error = EINVAL;
2651	be_lun->size_blocks = be_lun->size_bytes / be_lun->blocksize;
2652
2653	if (error == 0 && be_lun->size_bytes != oldsize) {
2654
2655		/*
2656		 * The maximum LBA is the size - 1.
2657		 *
2658		 * XXX: Note that this field is being updated without locking,
2659		 * 	which might cause problems on 32-bit architectures.
2660		 */
2661		if (be_lun->unmap != NULL)
2662			be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_UNMAP;
2663		be_lun->ctl_be_lun.maxlba = (be_lun->size_blocks == 0) ?
2664		    0 : (be_lun->size_blocks - 1);
2665		be_lun->ctl_be_lun.blocksize = be_lun->blocksize;
2666		be_lun->ctl_be_lun.pblockexp = be_lun->pblockexp;
2667		be_lun->ctl_be_lun.pblockoff = be_lun->pblockoff;
2668		be_lun->ctl_be_lun.ublockexp = be_lun->ublockexp;
2669		be_lun->ctl_be_lun.ublockoff = be_lun->ublockoff;
2670		be_lun->ctl_be_lun.atomicblock = be_lun->atomicblock;
2671		be_lun->ctl_be_lun.opttxferlen = be_lun->opttxferlen;
2672		ctl_lun_capacity_changed(&be_lun->ctl_be_lun);
2673		if (oldsize == 0 && be_lun->size_blocks != 0)
2674			ctl_lun_online(&be_lun->ctl_be_lun);
2675	}
2676
2677	/* Tell the user the exact size we ended up using */
2678	params->lun_size_bytes = be_lun->size_bytes;
2679
2680	req->status = error ? CTL_LUN_WARNING : CTL_LUN_OK;
2681
2682	return (0);
2683
2684bailout_error:
2685	req->status = CTL_LUN_ERROR;
2686
2687	return (0);
2688}
2689
2690static void
2691ctl_be_block_lun_shutdown(void *be_lun)
2692{
2693	struct ctl_be_block_lun *lun;
2694	struct ctl_be_block_softc *softc;
2695
2696	lun = (struct ctl_be_block_lun *)be_lun;
2697
2698	softc = lun->softc;
2699
2700	mtx_lock(&softc->lock);
2701	lun->flags |= CTL_BE_BLOCK_LUN_UNCONFIGURED;
2702	if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2703		wakeup(lun);
2704	mtx_unlock(&softc->lock);
2705
2706}
2707
2708static void
2709ctl_be_block_lun_config_status(void *be_lun, ctl_lun_config_status status)
2710{
2711	struct ctl_be_block_lun *lun;
2712	struct ctl_be_block_softc *softc;
2713
2714	lun = (struct ctl_be_block_lun *)be_lun;
2715	softc = lun->softc;
2716
2717	if (status == CTL_LUN_CONFIG_OK) {
2718		mtx_lock(&softc->lock);
2719		lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2720		if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2721			wakeup(lun);
2722		mtx_unlock(&softc->lock);
2723
2724		/*
2725		 * We successfully added the LUN, attempt to enable it.
2726		 */
2727		if (ctl_enable_lun(&lun->ctl_be_lun) != 0) {
2728			printf("%s: ctl_enable_lun() failed!\n", __func__);
2729			if (ctl_invalidate_lun(&lun->ctl_be_lun) != 0) {
2730				printf("%s: ctl_invalidate_lun() failed!\n",
2731				       __func__);
2732			}
2733		}
2734
2735		return;
2736	}
2737
2738
2739	mtx_lock(&softc->lock);
2740	lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2741	lun->flags |= CTL_BE_BLOCK_LUN_CONFIG_ERR;
2742	wakeup(lun);
2743	mtx_unlock(&softc->lock);
2744}
2745
2746
2747static int
2748ctl_be_block_config_write(union ctl_io *io)
2749{
2750	struct ctl_be_block_lun *be_lun;
2751	struct ctl_be_lun *ctl_be_lun;
2752	int retval;
2753
2754	retval = 0;
2755
2756	DPRINTF("entered\n");
2757
2758	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2759		CTL_PRIV_BACKEND_LUN].ptr;
2760	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
2761
2762	switch (io->scsiio.cdb[0]) {
2763	case SYNCHRONIZE_CACHE:
2764	case SYNCHRONIZE_CACHE_16:
2765	case WRITE_SAME_10:
2766	case WRITE_SAME_16:
2767	case UNMAP:
2768		/*
2769		 * The upper level CTL code will filter out any CDBs with
2770		 * the immediate bit set and return the proper error.
2771		 *
2772		 * We don't really need to worry about what LBA range the
2773		 * user asked to be synced out.  When they issue a sync
2774		 * cache command, we'll sync out the whole thing.
2775		 */
2776		mtx_lock(&be_lun->queue_lock);
2777		STAILQ_INSERT_TAIL(&be_lun->config_write_queue, &io->io_hdr,
2778				   links);
2779		mtx_unlock(&be_lun->queue_lock);
2780		taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
2781		break;
2782	case START_STOP_UNIT: {
2783		struct scsi_start_stop_unit *cdb;
2784
2785		cdb = (struct scsi_start_stop_unit *)io->scsiio.cdb;
2786
2787		if (cdb->how & SSS_START)
2788			retval = ctl_start_lun(ctl_be_lun);
2789		else {
2790			retval = ctl_stop_lun(ctl_be_lun);
2791			/*
2792			 * XXX KDM Copan-specific offline behavior.
2793			 * Figure out a reasonable way to port this?
2794			 */
2795#ifdef NEEDTOPORT
2796			if ((retval == 0)
2797			 && (cdb->byte2 & SSS_ONOFFLINE))
2798				retval = ctl_lun_offline(ctl_be_lun);
2799#endif
2800		}
2801
2802		/*
2803		 * In general, the above routines should not fail.  They
2804		 * just set state for the LUN.  So we've got something
2805		 * pretty wrong here if we can't start or stop the LUN.
2806		 */
2807		if (retval != 0) {
2808			ctl_set_internal_failure(&io->scsiio,
2809						 /*sks_valid*/ 1,
2810						 /*retry_count*/ 0xf051);
2811			retval = CTL_RETVAL_COMPLETE;
2812		} else {
2813			ctl_set_success(&io->scsiio);
2814		}
2815		ctl_config_write_done(io);
2816		break;
2817	}
2818	default:
2819		ctl_set_invalid_opcode(&io->scsiio);
2820		ctl_config_write_done(io);
2821		retval = CTL_RETVAL_COMPLETE;
2822		break;
2823	}
2824
2825	return (retval);
2826}
2827
2828static int
2829ctl_be_block_config_read(union ctl_io *io)
2830{
2831	struct ctl_be_block_lun *be_lun;
2832	struct ctl_be_lun *ctl_be_lun;
2833	int retval = 0;
2834
2835	DPRINTF("entered\n");
2836
2837	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2838		CTL_PRIV_BACKEND_LUN].ptr;
2839	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
2840
2841	switch (io->scsiio.cdb[0]) {
2842	case SERVICE_ACTION_IN:
2843		if (io->scsiio.cdb[1] == SGLS_SERVICE_ACTION) {
2844			mtx_lock(&be_lun->queue_lock);
2845			STAILQ_INSERT_TAIL(&be_lun->config_read_queue,
2846			    &io->io_hdr, links);
2847			mtx_unlock(&be_lun->queue_lock);
2848			taskqueue_enqueue(be_lun->io_taskqueue,
2849			    &be_lun->io_task);
2850			retval = CTL_RETVAL_QUEUED;
2851			break;
2852		}
2853		ctl_set_invalid_field(&io->scsiio,
2854				      /*sks_valid*/ 1,
2855				      /*command*/ 1,
2856				      /*field*/ 1,
2857				      /*bit_valid*/ 1,
2858				      /*bit*/ 4);
2859		ctl_config_read_done(io);
2860		retval = CTL_RETVAL_COMPLETE;
2861		break;
2862	default:
2863		ctl_set_invalid_opcode(&io->scsiio);
2864		ctl_config_read_done(io);
2865		retval = CTL_RETVAL_COMPLETE;
2866		break;
2867	}
2868
2869	return (retval);
2870}
2871
2872static int
2873ctl_be_block_lun_info(void *be_lun, struct sbuf *sb)
2874{
2875	struct ctl_be_block_lun *lun;
2876	int retval;
2877
2878	lun = (struct ctl_be_block_lun *)be_lun;
2879	retval = 0;
2880
2881	retval = sbuf_printf(sb, "\t<num_threads>");
2882
2883	if (retval != 0)
2884		goto bailout;
2885
2886	retval = sbuf_printf(sb, "%d", lun->num_threads);
2887
2888	if (retval != 0)
2889		goto bailout;
2890
2891	retval = sbuf_printf(sb, "</num_threads>\n");
2892
2893bailout:
2894
2895	return (retval);
2896}
2897
2898static uint64_t
2899ctl_be_block_lun_attr(void *be_lun, const char *attrname)
2900{
2901	struct ctl_be_block_lun *lun = (struct ctl_be_block_lun *)be_lun;
2902
2903	if (lun->getattr == NULL)
2904		return (UINT64_MAX);
2905	return (lun->getattr(lun, attrname));
2906}
2907
2908int
2909ctl_be_block_init(void)
2910{
2911	struct ctl_be_block_softc *softc;
2912	int retval;
2913
2914	softc = &backend_block_softc;
2915	retval = 0;
2916
2917	mtx_init(&softc->lock, "ctlblock", NULL, MTX_DEF);
2918	beio_zone = uma_zcreate("beio", sizeof(struct ctl_be_block_io),
2919	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
2920	STAILQ_INIT(&softc->lun_list);
2921
2922	return (retval);
2923}
2924