ctl_backend_block.c revision 288706
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 288706 2015-10-05 08:09:34Z 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	uint64_t		val;
813	int			error;
814
815	val = UINT64_MAX;
816	if (be_lun->vn == NULL)
817		return (val);
818	vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
819	if (strcmp(attrname, "blocksused") == 0) {
820		error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
821		if (error == 0)
822			val = vattr.va_bytes >> be_lun->blocksize_shift;
823	}
824	if (strcmp(attrname, "blocksavail") == 0 &&
825	    (be_lun->vn->v_iflag & VI_DOOMED) == 0) {
826		error = VFS_STATFS(be_lun->vn->v_mount, &statfs);
827		if (error == 0)
828			val = (statfs.f_bavail * statfs.f_bsize) >>
829			    be_lun->blocksize_shift;
830	}
831	VOP_UNLOCK(be_lun->vn, 0);
832	return (val);
833}
834
835static void
836ctl_be_block_dispatch_zvol(struct ctl_be_block_lun *be_lun,
837			   struct ctl_be_block_io *beio)
838{
839	struct ctl_be_block_devdata *dev_data;
840	union ctl_io *io;
841	struct uio xuio;
842	struct iovec *xiovec;
843	int flags;
844	int error, i;
845
846	DPRINTF("entered\n");
847
848	dev_data = &be_lun->backend.dev;
849	io = beio->io;
850	flags = 0;
851	if (ARGS(io)->flags & CTL_LLF_DPO)
852		flags |= IO_DIRECT;
853	if (beio->bio_cmd == BIO_WRITE && ARGS(io)->flags & CTL_LLF_FUA)
854		flags |= IO_SYNC;
855
856	bzero(&xuio, sizeof(xuio));
857	if (beio->bio_cmd == BIO_READ) {
858		SDT_PROBE(cbb, kernel, read, file_start, 0, 0, 0, 0, 0);
859		xuio.uio_rw = UIO_READ;
860	} else {
861		SDT_PROBE(cbb, kernel, write, file_start, 0, 0, 0, 0, 0);
862		xuio.uio_rw = UIO_WRITE;
863	}
864	xuio.uio_offset = beio->io_offset;
865	xuio.uio_resid = beio->io_len;
866	xuio.uio_segflg = UIO_SYSSPACE;
867	xuio.uio_iov = beio->xiovecs;
868	xuio.uio_iovcnt = beio->num_segs;
869	xuio.uio_td = curthread;
870
871	for (i = 0, xiovec = xuio.uio_iov; i < xuio.uio_iovcnt; i++, xiovec++) {
872		xiovec->iov_base = beio->sg_segs[i].addr;
873		xiovec->iov_len = beio->sg_segs[i].len;
874	}
875
876	binuptime(&beio->ds_t0);
877	mtx_lock(&be_lun->io_lock);
878	devstat_start_transaction(beio->lun->disk_stats, &beio->ds_t0);
879	mtx_unlock(&be_lun->io_lock);
880
881	if (beio->bio_cmd == BIO_READ) {
882		error = (*dev_data->csw->d_read)(dev_data->cdev, &xuio, flags);
883		SDT_PROBE(cbb, kernel, read, file_done, 0, 0, 0, 0, 0);
884	} else {
885		error = (*dev_data->csw->d_write)(dev_data->cdev, &xuio, flags);
886		SDT_PROBE(cbb, kernel, write, file_done, 0, 0, 0, 0, 0);
887	}
888
889	mtx_lock(&be_lun->io_lock);
890	devstat_end_transaction(beio->lun->disk_stats, beio->io_len,
891	    beio->ds_tag_type, beio->ds_trans_type,
892	    /*now*/ NULL, /*then*/&beio->ds_t0);
893	mtx_unlock(&be_lun->io_lock);
894
895	/*
896	 * If we got an error, set the sense data to "MEDIUM ERROR" and
897	 * return the I/O to the user.
898	 */
899	if (error != 0) {
900		if (error == ENOSPC || error == EDQUOT) {
901			ctl_set_space_alloc_fail(&io->scsiio);
902		} else
903			ctl_set_medium_error(&io->scsiio);
904		ctl_complete_beio(beio);
905		return;
906	}
907
908	/*
909	 * If this is a write or a verify, we're all done.
910	 * If this is a read, we can now send the data to the user.
911	 */
912	if ((beio->bio_cmd == BIO_WRITE) ||
913	    (ARGS(io)->flags & CTL_LLF_VERIFY)) {
914		ctl_set_success(&io->scsiio);
915		ctl_complete_beio(beio);
916	} else {
917		if ((ARGS(io)->flags & CTL_LLF_READ) &&
918		    beio->beio_cont == NULL)
919			ctl_set_success(&io->scsiio);
920#ifdef CTL_TIME_IO
921        	getbintime(&io->io_hdr.dma_start_bt);
922#endif
923		ctl_datamove(io);
924	}
925}
926
927static void
928ctl_be_block_gls_zvol(struct ctl_be_block_lun *be_lun,
929			struct ctl_be_block_io *beio)
930{
931	struct ctl_be_block_devdata *dev_data = &be_lun->backend.dev;
932	union ctl_io *io = beio->io;
933	struct ctl_lba_len_flags *lbalen = ARGS(io);
934	struct scsi_get_lba_status_data *data;
935	off_t roff, off;
936	int error, status;
937
938	DPRINTF("entered\n");
939
940	off = roff = ((off_t)lbalen->lba) << be_lun->blocksize_shift;
941	error = (*dev_data->csw->d_ioctl)(dev_data->cdev, FIOSEEKHOLE,
942	    (caddr_t)&off, FREAD, curthread);
943	if (error == 0 && off > roff)
944		status = 0;	/* mapped up to off */
945	else {
946		error = (*dev_data->csw->d_ioctl)(dev_data->cdev, FIOSEEKDATA,
947		    (caddr_t)&off, FREAD, curthread);
948		if (error == 0 && off > roff)
949			status = 1;	/* deallocated up to off */
950		else {
951			status = 0;	/* unknown up to the end */
952			off = be_lun->size_bytes;
953		}
954	}
955
956	off >>= be_lun->blocksize_shift;
957	data = (struct scsi_get_lba_status_data *)io->scsiio.kern_data_ptr;
958	scsi_u64to8b(lbalen->lba, data->descr[0].addr);
959	scsi_ulto4b(MIN(UINT32_MAX, off - lbalen->lba),
960	    data->descr[0].length);
961	data->descr[0].status = status;
962
963	ctl_complete_beio(beio);
964}
965
966static void
967ctl_be_block_flush_dev(struct ctl_be_block_lun *be_lun,
968		       struct ctl_be_block_io *beio)
969{
970	struct bio *bio;
971	union ctl_io *io;
972	struct ctl_be_block_devdata *dev_data;
973
974	dev_data = &be_lun->backend.dev;
975	io = beio->io;
976
977	DPRINTF("entered\n");
978
979	/* This can't fail, it's a blocking allocation. */
980	bio = g_alloc_bio();
981
982	bio->bio_cmd	    = BIO_FLUSH;
983	bio->bio_dev	    = dev_data->cdev;
984	bio->bio_offset	    = 0;
985	bio->bio_data	    = 0;
986	bio->bio_done	    = ctl_be_block_biodone;
987	bio->bio_caller1    = beio;
988	bio->bio_pblkno	    = 0;
989
990	/*
991	 * We don't need to acquire the LUN lock here, because we are only
992	 * sending one bio, and so there is no other context to synchronize
993	 * with.
994	 */
995	beio->num_bios_sent = 1;
996	beio->send_complete = 1;
997
998	binuptime(&beio->ds_t0);
999	mtx_lock(&be_lun->io_lock);
1000	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
1001	mtx_unlock(&be_lun->io_lock);
1002
1003	(*dev_data->csw->d_strategy)(bio);
1004}
1005
1006static void
1007ctl_be_block_unmap_dev_range(struct ctl_be_block_lun *be_lun,
1008		       struct ctl_be_block_io *beio,
1009		       uint64_t off, uint64_t len, int last)
1010{
1011	struct bio *bio;
1012	struct ctl_be_block_devdata *dev_data;
1013	uint64_t maxlen;
1014
1015	dev_data = &be_lun->backend.dev;
1016	maxlen = LONG_MAX - (LONG_MAX % be_lun->blocksize);
1017	while (len > 0) {
1018		bio = g_alloc_bio();
1019		bio->bio_cmd	    = BIO_DELETE;
1020		bio->bio_dev	    = dev_data->cdev;
1021		bio->bio_offset	    = off;
1022		bio->bio_length	    = MIN(len, maxlen);
1023		bio->bio_data	    = 0;
1024		bio->bio_done	    = ctl_be_block_biodone;
1025		bio->bio_caller1    = beio;
1026		bio->bio_pblkno     = off / be_lun->blocksize;
1027
1028		off += bio->bio_length;
1029		len -= bio->bio_length;
1030
1031		mtx_lock(&be_lun->io_lock);
1032		beio->num_bios_sent++;
1033		if (last && len == 0)
1034			beio->send_complete = 1;
1035		mtx_unlock(&be_lun->io_lock);
1036
1037		(*dev_data->csw->d_strategy)(bio);
1038	}
1039}
1040
1041static void
1042ctl_be_block_unmap_dev(struct ctl_be_block_lun *be_lun,
1043		       struct ctl_be_block_io *beio)
1044{
1045	union ctl_io *io;
1046	struct ctl_be_block_devdata *dev_data;
1047	struct ctl_ptr_len_flags *ptrlen;
1048	struct scsi_unmap_desc *buf, *end;
1049	uint64_t len;
1050
1051	dev_data = &be_lun->backend.dev;
1052	io = beio->io;
1053
1054	DPRINTF("entered\n");
1055
1056	binuptime(&beio->ds_t0);
1057	mtx_lock(&be_lun->io_lock);
1058	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
1059	mtx_unlock(&be_lun->io_lock);
1060
1061	if (beio->io_offset == -1) {
1062		beio->io_len = 0;
1063		ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1064		buf = (struct scsi_unmap_desc *)ptrlen->ptr;
1065		end = buf + ptrlen->len / sizeof(*buf);
1066		for (; buf < end; buf++) {
1067			len = (uint64_t)scsi_4btoul(buf->length) *
1068			    be_lun->blocksize;
1069			beio->io_len += len;
1070			ctl_be_block_unmap_dev_range(be_lun, beio,
1071			    scsi_8btou64(buf->lba) * be_lun->blocksize, len,
1072			    (end - buf < 2) ? TRUE : FALSE);
1073		}
1074	} else
1075		ctl_be_block_unmap_dev_range(be_lun, beio,
1076		    beio->io_offset, beio->io_len, TRUE);
1077}
1078
1079static void
1080ctl_be_block_dispatch_dev(struct ctl_be_block_lun *be_lun,
1081			  struct ctl_be_block_io *beio)
1082{
1083	TAILQ_HEAD(, bio) queue = TAILQ_HEAD_INITIALIZER(queue);
1084	int i;
1085	struct bio *bio;
1086	struct ctl_be_block_devdata *dev_data;
1087	off_t cur_offset;
1088	int max_iosize;
1089
1090	DPRINTF("entered\n");
1091
1092	dev_data = &be_lun->backend.dev;
1093
1094	/*
1095	 * We have to limit our I/O size to the maximum supported by the
1096	 * backend device.  Hopefully it is MAXPHYS.  If the driver doesn't
1097	 * set it properly, use DFLTPHYS.
1098	 */
1099	max_iosize = dev_data->cdev->si_iosize_max;
1100	if (max_iosize < PAGE_SIZE)
1101		max_iosize = DFLTPHYS;
1102
1103	cur_offset = beio->io_offset;
1104	for (i = 0; i < beio->num_segs; i++) {
1105		size_t cur_size;
1106		uint8_t *cur_ptr;
1107
1108		cur_size = beio->sg_segs[i].len;
1109		cur_ptr = beio->sg_segs[i].addr;
1110
1111		while (cur_size > 0) {
1112			/* This can't fail, it's a blocking allocation. */
1113			bio = g_alloc_bio();
1114
1115			KASSERT(bio != NULL, ("g_alloc_bio() failed!\n"));
1116
1117			bio->bio_cmd = beio->bio_cmd;
1118			bio->bio_dev = dev_data->cdev;
1119			bio->bio_caller1 = beio;
1120			bio->bio_length = min(cur_size, max_iosize);
1121			bio->bio_offset = cur_offset;
1122			bio->bio_data = cur_ptr;
1123			bio->bio_done = ctl_be_block_biodone;
1124			bio->bio_pblkno = cur_offset / be_lun->blocksize;
1125
1126			cur_offset += bio->bio_length;
1127			cur_ptr += bio->bio_length;
1128			cur_size -= bio->bio_length;
1129
1130			TAILQ_INSERT_TAIL(&queue, bio, bio_queue);
1131			beio->num_bios_sent++;
1132		}
1133	}
1134	binuptime(&beio->ds_t0);
1135	mtx_lock(&be_lun->io_lock);
1136	devstat_start_transaction(be_lun->disk_stats, &beio->ds_t0);
1137	beio->send_complete = 1;
1138	mtx_unlock(&be_lun->io_lock);
1139
1140	/*
1141	 * Fire off all allocated requests!
1142	 */
1143	while ((bio = TAILQ_FIRST(&queue)) != NULL) {
1144		TAILQ_REMOVE(&queue, bio, bio_queue);
1145		(*dev_data->csw->d_strategy)(bio);
1146	}
1147}
1148
1149static uint64_t
1150ctl_be_block_getattr_dev(struct ctl_be_block_lun *be_lun, const char *attrname)
1151{
1152	struct ctl_be_block_devdata	*dev_data = &be_lun->backend.dev;
1153	struct diocgattr_arg	arg;
1154	int			error;
1155
1156	if (dev_data->csw == NULL || dev_data->csw->d_ioctl == NULL)
1157		return (UINT64_MAX);
1158	strlcpy(arg.name, attrname, sizeof(arg.name));
1159	arg.len = sizeof(arg.value.off);
1160	error = dev_data->csw->d_ioctl(dev_data->cdev,
1161	    DIOCGATTR, (caddr_t)&arg, FREAD, curthread);
1162	if (error != 0)
1163		return (UINT64_MAX);
1164	return (arg.value.off);
1165}
1166
1167static void
1168ctl_be_block_cw_dispatch_sync(struct ctl_be_block_lun *be_lun,
1169			    union ctl_io *io)
1170{
1171	struct ctl_be_block_io *beio;
1172	struct ctl_lba_len_flags *lbalen;
1173
1174	DPRINTF("entered\n");
1175	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1176	lbalen = (struct ctl_lba_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1177
1178	beio->io_len = lbalen->len * be_lun->blocksize;
1179	beio->io_offset = lbalen->lba * be_lun->blocksize;
1180	beio->io_arg = (lbalen->flags & SSC_IMMED) != 0;
1181	beio->bio_cmd = BIO_FLUSH;
1182	beio->ds_trans_type = DEVSTAT_NO_DATA;
1183	DPRINTF("SYNC\n");
1184	be_lun->lun_flush(be_lun, beio);
1185}
1186
1187static void
1188ctl_be_block_cw_done_ws(struct ctl_be_block_io *beio)
1189{
1190	union ctl_io *io;
1191
1192	io = beio->io;
1193	ctl_free_beio(beio);
1194	if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
1195	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
1196	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
1197		ctl_config_write_done(io);
1198		return;
1199	}
1200
1201	ctl_be_block_config_write(io);
1202}
1203
1204static void
1205ctl_be_block_cw_dispatch_ws(struct ctl_be_block_lun *be_lun,
1206			    union ctl_io *io)
1207{
1208	struct ctl_be_block_io *beio;
1209	struct ctl_lba_len_flags *lbalen;
1210	uint64_t len_left, lba;
1211	uint32_t pb, pbo, adj;
1212	int i, seglen;
1213	uint8_t *buf, *end;
1214
1215	DPRINTF("entered\n");
1216
1217	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1218	lbalen = ARGS(beio->io);
1219
1220	if (lbalen->flags & ~(SWS_LBDATA | SWS_UNMAP | SWS_ANCHOR | SWS_NDOB) ||
1221	    (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR) && be_lun->unmap == NULL)) {
1222		ctl_free_beio(beio);
1223		ctl_set_invalid_field(&io->scsiio,
1224				      /*sks_valid*/ 1,
1225				      /*command*/ 1,
1226				      /*field*/ 1,
1227				      /*bit_valid*/ 0,
1228				      /*bit*/ 0);
1229		ctl_config_write_done(io);
1230		return;
1231	}
1232
1233	if (lbalen->flags & (SWS_UNMAP | SWS_ANCHOR)) {
1234		beio->io_offset = lbalen->lba * be_lun->blocksize;
1235		beio->io_len = (uint64_t)lbalen->len * be_lun->blocksize;
1236		beio->bio_cmd = BIO_DELETE;
1237		beio->ds_trans_type = DEVSTAT_FREE;
1238
1239		be_lun->unmap(be_lun, beio);
1240		return;
1241	}
1242
1243	beio->bio_cmd = BIO_WRITE;
1244	beio->ds_trans_type = DEVSTAT_WRITE;
1245
1246	DPRINTF("WRITE SAME at LBA %jx len %u\n",
1247	       (uintmax_t)lbalen->lba, lbalen->len);
1248
1249	pb = be_lun->blocksize << be_lun->pblockexp;
1250	if (be_lun->pblockoff > 0)
1251		pbo = pb - be_lun->blocksize * be_lun->pblockoff;
1252	else
1253		pbo = 0;
1254	len_left = (uint64_t)lbalen->len * be_lun->blocksize;
1255	for (i = 0, lba = 0; i < CTLBLK_MAX_SEGS && len_left > 0; i++) {
1256
1257		/*
1258		 * Setup the S/G entry for this chunk.
1259		 */
1260		seglen = MIN(CTLBLK_MAX_SEG, len_left);
1261		if (pb > be_lun->blocksize) {
1262			adj = ((lbalen->lba + lba) * be_lun->blocksize +
1263			    seglen - pbo) % pb;
1264			if (seglen > adj)
1265				seglen -= adj;
1266			else
1267				seglen -= seglen % be_lun->blocksize;
1268		} else
1269			seglen -= seglen % be_lun->blocksize;
1270		beio->sg_segs[i].len = seglen;
1271		beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);
1272
1273		DPRINTF("segment %d addr %p len %zd\n", i,
1274			beio->sg_segs[i].addr, beio->sg_segs[i].len);
1275
1276		beio->num_segs++;
1277		len_left -= seglen;
1278
1279		buf = beio->sg_segs[i].addr;
1280		end = buf + seglen;
1281		for (; buf < end; buf += be_lun->blocksize) {
1282			memcpy(buf, io->scsiio.kern_data_ptr, be_lun->blocksize);
1283			if (lbalen->flags & SWS_LBDATA)
1284				scsi_ulto4b(lbalen->lba + lba, buf);
1285			lba++;
1286		}
1287	}
1288
1289	beio->io_offset = lbalen->lba * be_lun->blocksize;
1290	beio->io_len = lba * be_lun->blocksize;
1291
1292	/* We can not do all in one run. Correct and schedule rerun. */
1293	if (len_left > 0) {
1294		lbalen->lba += lba;
1295		lbalen->len -= lba;
1296		beio->beio_cont = ctl_be_block_cw_done_ws;
1297	}
1298
1299	be_lun->dispatch(be_lun, beio);
1300}
1301
1302static void
1303ctl_be_block_cw_dispatch_unmap(struct ctl_be_block_lun *be_lun,
1304			    union ctl_io *io)
1305{
1306	struct ctl_be_block_io *beio;
1307	struct ctl_ptr_len_flags *ptrlen;
1308
1309	DPRINTF("entered\n");
1310
1311	beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1312	ptrlen = (struct ctl_ptr_len_flags *)&io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
1313
1314	if ((ptrlen->flags & ~SU_ANCHOR) != 0 || be_lun->unmap == NULL) {
1315		ctl_free_beio(beio);
1316		ctl_set_invalid_field(&io->scsiio,
1317				      /*sks_valid*/ 0,
1318				      /*command*/ 1,
1319				      /*field*/ 0,
1320				      /*bit_valid*/ 0,
1321				      /*bit*/ 0);
1322		ctl_config_write_done(io);
1323		return;
1324	}
1325
1326	beio->io_len = 0;
1327	beio->io_offset = -1;
1328	beio->bio_cmd = BIO_DELETE;
1329	beio->ds_trans_type = DEVSTAT_FREE;
1330	DPRINTF("UNMAP\n");
1331	be_lun->unmap(be_lun, beio);
1332}
1333
1334static void
1335ctl_be_block_cr_done(struct ctl_be_block_io *beio)
1336{
1337	union ctl_io *io;
1338
1339	io = beio->io;
1340	ctl_free_beio(beio);
1341	ctl_config_read_done(io);
1342}
1343
1344static void
1345ctl_be_block_cr_dispatch(struct ctl_be_block_lun *be_lun,
1346			 union ctl_io *io)
1347{
1348	struct ctl_be_block_io *beio;
1349	struct ctl_be_block_softc *softc;
1350
1351	DPRINTF("entered\n");
1352
1353	softc = be_lun->softc;
1354	beio = ctl_alloc_beio(softc);
1355	beio->io = io;
1356	beio->lun = be_lun;
1357	beio->beio_cont = ctl_be_block_cr_done;
1358	PRIV(io)->ptr = (void *)beio;
1359
1360	switch (io->scsiio.cdb[0]) {
1361	case SERVICE_ACTION_IN:		/* GET LBA STATUS */
1362		beio->bio_cmd = -1;
1363		beio->ds_trans_type = DEVSTAT_NO_DATA;
1364		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1365		beio->io_len = 0;
1366		if (be_lun->get_lba_status)
1367			be_lun->get_lba_status(be_lun, beio);
1368		else
1369			ctl_be_block_cr_done(beio);
1370		break;
1371	default:
1372		panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
1373		break;
1374	}
1375}
1376
1377static void
1378ctl_be_block_cw_done(struct ctl_be_block_io *beio)
1379{
1380	union ctl_io *io;
1381
1382	io = beio->io;
1383	ctl_free_beio(beio);
1384	ctl_config_write_done(io);
1385}
1386
1387static void
1388ctl_be_block_cw_dispatch(struct ctl_be_block_lun *be_lun,
1389			 union ctl_io *io)
1390{
1391	struct ctl_be_block_io *beio;
1392	struct ctl_be_block_softc *softc;
1393
1394	DPRINTF("entered\n");
1395
1396	softc = be_lun->softc;
1397	beio = ctl_alloc_beio(softc);
1398	beio->io = io;
1399	beio->lun = be_lun;
1400	beio->beio_cont = ctl_be_block_cw_done;
1401	switch (io->scsiio.tag_type) {
1402	case CTL_TAG_ORDERED:
1403		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1404		break;
1405	case CTL_TAG_HEAD_OF_QUEUE:
1406		beio->ds_tag_type = DEVSTAT_TAG_HEAD;
1407		break;
1408	case CTL_TAG_UNTAGGED:
1409	case CTL_TAG_SIMPLE:
1410	case CTL_TAG_ACA:
1411	default:
1412		beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1413		break;
1414	}
1415	PRIV(io)->ptr = (void *)beio;
1416
1417	switch (io->scsiio.cdb[0]) {
1418	case SYNCHRONIZE_CACHE:
1419	case SYNCHRONIZE_CACHE_16:
1420		ctl_be_block_cw_dispatch_sync(be_lun, io);
1421		break;
1422	case WRITE_SAME_10:
1423	case WRITE_SAME_16:
1424		ctl_be_block_cw_dispatch_ws(be_lun, io);
1425		break;
1426	case UNMAP:
1427		ctl_be_block_cw_dispatch_unmap(be_lun, io);
1428		break;
1429	default:
1430		panic("Unhandled CDB type %#x", io->scsiio.cdb[0]);
1431		break;
1432	}
1433}
1434
1435SDT_PROBE_DEFINE1(cbb, kernel, read, start, "uint64_t");
1436SDT_PROBE_DEFINE1(cbb, kernel, write, start, "uint64_t");
1437SDT_PROBE_DEFINE1(cbb, kernel, read, alloc_done, "uint64_t");
1438SDT_PROBE_DEFINE1(cbb, kernel, write, alloc_done, "uint64_t");
1439
1440static void
1441ctl_be_block_next(struct ctl_be_block_io *beio)
1442{
1443	struct ctl_be_block_lun *be_lun;
1444	union ctl_io *io;
1445
1446	io = beio->io;
1447	be_lun = beio->lun;
1448	ctl_free_beio(beio);
1449	if ((io->io_hdr.flags & CTL_FLAG_ABORT) ||
1450	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
1451	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
1452		ctl_data_submit_done(io);
1453		return;
1454	}
1455
1456	io->io_hdr.status &= ~CTL_STATUS_MASK;
1457	io->io_hdr.status |= CTL_STATUS_NONE;
1458
1459	mtx_lock(&be_lun->queue_lock);
1460	/*
1461	 * XXX KDM make sure that links is okay to use at this point.
1462	 * Otherwise, we either need to add another field to ctl_io_hdr,
1463	 * or deal with resource allocation here.
1464	 */
1465	STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
1466	mtx_unlock(&be_lun->queue_lock);
1467
1468	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
1469}
1470
1471static void
1472ctl_be_block_dispatch(struct ctl_be_block_lun *be_lun,
1473			   union ctl_io *io)
1474{
1475	struct ctl_be_block_io *beio;
1476	struct ctl_be_block_softc *softc;
1477	struct ctl_lba_len_flags *lbalen;
1478	struct ctl_ptr_len_flags *bptrlen;
1479	uint64_t len_left, lbas;
1480	int i;
1481
1482	softc = be_lun->softc;
1483
1484	DPRINTF("entered\n");
1485
1486	lbalen = ARGS(io);
1487	if (lbalen->flags & CTL_LLF_WRITE) {
1488		SDT_PROBE(cbb, kernel, write, start, 0, 0, 0, 0, 0);
1489	} else {
1490		SDT_PROBE(cbb, kernel, read, start, 0, 0, 0, 0, 0);
1491	}
1492
1493	beio = ctl_alloc_beio(softc);
1494	beio->io = io;
1495	beio->lun = be_lun;
1496	bptrlen = PRIV(io);
1497	bptrlen->ptr = (void *)beio;
1498
1499	switch (io->scsiio.tag_type) {
1500	case CTL_TAG_ORDERED:
1501		beio->ds_tag_type = DEVSTAT_TAG_ORDERED;
1502		break;
1503	case CTL_TAG_HEAD_OF_QUEUE:
1504		beio->ds_tag_type = DEVSTAT_TAG_HEAD;
1505		break;
1506	case CTL_TAG_UNTAGGED:
1507	case CTL_TAG_SIMPLE:
1508	case CTL_TAG_ACA:
1509	default:
1510		beio->ds_tag_type = DEVSTAT_TAG_SIMPLE;
1511		break;
1512	}
1513
1514	if (lbalen->flags & CTL_LLF_WRITE) {
1515		beio->bio_cmd = BIO_WRITE;
1516		beio->ds_trans_type = DEVSTAT_WRITE;
1517	} else {
1518		beio->bio_cmd = BIO_READ;
1519		beio->ds_trans_type = DEVSTAT_READ;
1520	}
1521
1522	DPRINTF("%s at LBA %jx len %u @%ju\n",
1523	       (beio->bio_cmd == BIO_READ) ? "READ" : "WRITE",
1524	       (uintmax_t)lbalen->lba, lbalen->len, bptrlen->len);
1525	if (lbalen->flags & CTL_LLF_COMPARE)
1526		lbas = CTLBLK_HALF_IO_SIZE;
1527	else
1528		lbas = CTLBLK_MAX_IO_SIZE;
1529	lbas = MIN(lbalen->len - bptrlen->len, lbas / be_lun->blocksize);
1530	beio->io_offset = (lbalen->lba + bptrlen->len) * be_lun->blocksize;
1531	beio->io_len = lbas * be_lun->blocksize;
1532	bptrlen->len += lbas;
1533
1534	for (i = 0, len_left = beio->io_len; len_left > 0; i++) {
1535		KASSERT(i < CTLBLK_MAX_SEGS, ("Too many segs (%d >= %d)",
1536		    i, CTLBLK_MAX_SEGS));
1537
1538		/*
1539		 * Setup the S/G entry for this chunk.
1540		 */
1541		beio->sg_segs[i].len = min(CTLBLK_MAX_SEG, len_left);
1542		beio->sg_segs[i].addr = uma_zalloc(be_lun->lun_zone, M_WAITOK);
1543
1544		DPRINTF("segment %d addr %p len %zd\n", i,
1545			beio->sg_segs[i].addr, beio->sg_segs[i].len);
1546
1547		/* Set up second segment for compare operation. */
1548		if (lbalen->flags & CTL_LLF_COMPARE) {
1549			beio->sg_segs[i + CTLBLK_HALF_SEGS].len =
1550			    beio->sg_segs[i].len;
1551			beio->sg_segs[i + CTLBLK_HALF_SEGS].addr =
1552			    uma_zalloc(be_lun->lun_zone, M_WAITOK);
1553		}
1554
1555		beio->num_segs++;
1556		len_left -= beio->sg_segs[i].len;
1557	}
1558	if (bptrlen->len < lbalen->len)
1559		beio->beio_cont = ctl_be_block_next;
1560	io->scsiio.be_move_done = ctl_be_block_move_done;
1561	/* For compare we have separate S/G lists for read and datamove. */
1562	if (lbalen->flags & CTL_LLF_COMPARE)
1563		io->scsiio.kern_data_ptr = (uint8_t *)&beio->sg_segs[CTLBLK_HALF_SEGS];
1564	else
1565		io->scsiio.kern_data_ptr = (uint8_t *)beio->sg_segs;
1566	io->scsiio.kern_data_len = beio->io_len;
1567	io->scsiio.kern_data_resid = 0;
1568	io->scsiio.kern_sg_entries = beio->num_segs;
1569	io->io_hdr.flags |= CTL_FLAG_ALLOCATED | CTL_FLAG_KDPTR_SGLIST;
1570
1571	/*
1572	 * For the read case, we need to read the data into our buffers and
1573	 * then we can send it back to the user.  For the write case, we
1574	 * need to get the data from the user first.
1575	 */
1576	if (beio->bio_cmd == BIO_READ) {
1577		SDT_PROBE(cbb, kernel, read, alloc_done, 0, 0, 0, 0, 0);
1578		be_lun->dispatch(be_lun, beio);
1579	} else {
1580		SDT_PROBE(cbb, kernel, write, alloc_done, 0, 0, 0, 0, 0);
1581#ifdef CTL_TIME_IO
1582        	getbintime(&io->io_hdr.dma_start_bt);
1583#endif
1584		ctl_datamove(io);
1585	}
1586}
1587
1588static void
1589ctl_be_block_worker(void *context, int pending)
1590{
1591	struct ctl_be_block_lun *be_lun;
1592	struct ctl_be_block_softc *softc;
1593	union ctl_io *io;
1594
1595	be_lun = (struct ctl_be_block_lun *)context;
1596	softc = be_lun->softc;
1597
1598	DPRINTF("entered\n");
1599
1600	mtx_lock(&be_lun->queue_lock);
1601	for (;;) {
1602		io = (union ctl_io *)STAILQ_FIRST(&be_lun->datamove_queue);
1603		if (io != NULL) {
1604			struct ctl_be_block_io *beio;
1605
1606			DPRINTF("datamove queue\n");
1607
1608			STAILQ_REMOVE(&be_lun->datamove_queue, &io->io_hdr,
1609				      ctl_io_hdr, links);
1610
1611			mtx_unlock(&be_lun->queue_lock);
1612
1613			beio = (struct ctl_be_block_io *)PRIV(io)->ptr;
1614
1615			be_lun->dispatch(be_lun, beio);
1616
1617			mtx_lock(&be_lun->queue_lock);
1618			continue;
1619		}
1620		io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_write_queue);
1621		if (io != NULL) {
1622			DPRINTF("config write queue\n");
1623			STAILQ_REMOVE(&be_lun->config_write_queue, &io->io_hdr,
1624				      ctl_io_hdr, links);
1625			mtx_unlock(&be_lun->queue_lock);
1626			ctl_be_block_cw_dispatch(be_lun, io);
1627			mtx_lock(&be_lun->queue_lock);
1628			continue;
1629		}
1630		io = (union ctl_io *)STAILQ_FIRST(&be_lun->config_read_queue);
1631		if (io != NULL) {
1632			DPRINTF("config read queue\n");
1633			STAILQ_REMOVE(&be_lun->config_read_queue, &io->io_hdr,
1634				      ctl_io_hdr, links);
1635			mtx_unlock(&be_lun->queue_lock);
1636			ctl_be_block_cr_dispatch(be_lun, io);
1637			mtx_lock(&be_lun->queue_lock);
1638			continue;
1639		}
1640		io = (union ctl_io *)STAILQ_FIRST(&be_lun->input_queue);
1641		if (io != NULL) {
1642			DPRINTF("input queue\n");
1643
1644			STAILQ_REMOVE(&be_lun->input_queue, &io->io_hdr,
1645				      ctl_io_hdr, links);
1646			mtx_unlock(&be_lun->queue_lock);
1647
1648			/*
1649			 * We must drop the lock, since this routine and
1650			 * its children may sleep.
1651			 */
1652			ctl_be_block_dispatch(be_lun, io);
1653
1654			mtx_lock(&be_lun->queue_lock);
1655			continue;
1656		}
1657
1658		/*
1659		 * If we get here, there is no work left in the queues, so
1660		 * just break out and let the task queue go to sleep.
1661		 */
1662		break;
1663	}
1664	mtx_unlock(&be_lun->queue_lock);
1665}
1666
1667/*
1668 * Entry point from CTL to the backend for I/O.  We queue everything to a
1669 * work thread, so this just puts the I/O on a queue and wakes up the
1670 * thread.
1671 */
1672static int
1673ctl_be_block_submit(union ctl_io *io)
1674{
1675	struct ctl_be_block_lun *be_lun;
1676	struct ctl_be_lun *ctl_be_lun;
1677
1678	DPRINTF("entered\n");
1679
1680	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
1681		CTL_PRIV_BACKEND_LUN].ptr;
1682	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
1683
1684	/*
1685	 * Make sure we only get SCSI I/O.
1686	 */
1687	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI, ("Non-SCSI I/O (type "
1688		"%#x) encountered", io->io_hdr.io_type));
1689
1690	PRIV(io)->len = 0;
1691
1692	mtx_lock(&be_lun->queue_lock);
1693	/*
1694	 * XXX KDM make sure that links is okay to use at this point.
1695	 * Otherwise, we either need to add another field to ctl_io_hdr,
1696	 * or deal with resource allocation here.
1697	 */
1698	STAILQ_INSERT_TAIL(&be_lun->input_queue, &io->io_hdr, links);
1699	mtx_unlock(&be_lun->queue_lock);
1700	taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
1701
1702	return (CTL_RETVAL_COMPLETE);
1703}
1704
1705static int
1706ctl_be_block_ioctl(struct cdev *dev, u_long cmd, caddr_t addr,
1707			int flag, struct thread *td)
1708{
1709	struct ctl_be_block_softc *softc;
1710	int error;
1711
1712	softc = &backend_block_softc;
1713
1714	error = 0;
1715
1716	switch (cmd) {
1717	case CTL_LUN_REQ: {
1718		struct ctl_lun_req *lun_req;
1719
1720		lun_req = (struct ctl_lun_req *)addr;
1721
1722		switch (lun_req->reqtype) {
1723		case CTL_LUNREQ_CREATE:
1724			error = ctl_be_block_create(softc, lun_req);
1725			break;
1726		case CTL_LUNREQ_RM:
1727			error = ctl_be_block_rm(softc, lun_req);
1728			break;
1729		case CTL_LUNREQ_MODIFY:
1730			error = ctl_be_block_modify(softc, lun_req);
1731			break;
1732		default:
1733			lun_req->status = CTL_LUN_ERROR;
1734			snprintf(lun_req->error_str, sizeof(lun_req->error_str),
1735				 "invalid LUN request type %d",
1736				 lun_req->reqtype);
1737			break;
1738		}
1739		break;
1740	}
1741	default:
1742		error = ENOTTY;
1743		break;
1744	}
1745
1746	return (error);
1747}
1748
1749static int
1750ctl_be_block_open_file(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
1751{
1752	struct ctl_be_block_filedata *file_data;
1753	struct ctl_lun_create_params *params;
1754	char			     *value;
1755	struct vattr		      vattr;
1756	off_t			      ps, pss, po, pos, us, uss, uo, uos;
1757	int			      error;
1758
1759	error = 0;
1760	file_data = &be_lun->backend.file;
1761	params = &be_lun->params;
1762
1763	be_lun->dev_type = CTL_BE_BLOCK_FILE;
1764	be_lun->dispatch = ctl_be_block_dispatch_file;
1765	be_lun->lun_flush = ctl_be_block_flush_file;
1766	be_lun->get_lba_status = ctl_be_block_gls_file;
1767	be_lun->getattr = ctl_be_block_getattr_file;
1768
1769	error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
1770	if (error != 0) {
1771		snprintf(req->error_str, sizeof(req->error_str),
1772			 "error calling VOP_GETATTR() for file %s",
1773			 be_lun->dev_path);
1774		return (error);
1775	}
1776
1777	/*
1778	 * Verify that we have the ability to upgrade to exclusive
1779	 * access on this file so we can trap errors at open instead
1780	 * of reporting them during first access.
1781	 */
1782	if (VOP_ISLOCKED(be_lun->vn) != LK_EXCLUSIVE) {
1783		vn_lock(be_lun->vn, LK_UPGRADE | LK_RETRY);
1784		if (be_lun->vn->v_iflag & VI_DOOMED) {
1785			error = EBADF;
1786			snprintf(req->error_str, sizeof(req->error_str),
1787				 "error locking file %s", be_lun->dev_path);
1788			return (error);
1789		}
1790	}
1791
1792
1793	file_data->cred = crhold(curthread->td_ucred);
1794	if (params->lun_size_bytes != 0)
1795		be_lun->size_bytes = params->lun_size_bytes;
1796	else
1797		be_lun->size_bytes = vattr.va_size;
1798	/*
1799	 * We set the multi thread flag for file operations because all
1800	 * filesystems (in theory) are capable of allowing multiple readers
1801	 * of a file at once.  So we want to get the maximum possible
1802	 * concurrency.
1803	 */
1804	be_lun->flags |= CTL_BE_BLOCK_LUN_MULTI_THREAD;
1805
1806	/*
1807	 * For files we can use any logical block size.  Prefer 512 bytes
1808	 * for compatibility reasons.  If file's vattr.va_blocksize
1809	 * (preferred I/O block size) is bigger and multiple to chosen
1810	 * logical block size -- report it as physical block size.
1811	 */
1812	if (params->blocksize_bytes != 0)
1813		be_lun->blocksize = params->blocksize_bytes;
1814	else
1815		be_lun->blocksize = 512;
1816
1817	us = ps = vattr.va_blocksize;
1818	uo = po = 0;
1819
1820	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "pblocksize");
1821	if (value != NULL)
1822		ctl_expand_number(value, &ps);
1823	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "pblockoffset");
1824	if (value != NULL)
1825		ctl_expand_number(value, &po);
1826	pss = ps / be_lun->blocksize;
1827	pos = po / be_lun->blocksize;
1828	if ((pss > 0) && (pss * be_lun->blocksize == ps) && (pss >= pos) &&
1829	    ((pss & (pss - 1)) == 0) && (pos * be_lun->blocksize == po)) {
1830		be_lun->pblockexp = fls(pss) - 1;
1831		be_lun->pblockoff = (pss - pos) % pss;
1832	}
1833
1834	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "ublocksize");
1835	if (value != NULL)
1836		ctl_expand_number(value, &us);
1837	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "ublockoffset");
1838	if (value != NULL)
1839		ctl_expand_number(value, &uo);
1840	uss = us / be_lun->blocksize;
1841	uos = uo / be_lun->blocksize;
1842	if ((uss > 0) && (uss * be_lun->blocksize == us) && (uss >= uos) &&
1843	    ((uss & (uss - 1)) == 0) && (uos * be_lun->blocksize == uo)) {
1844		be_lun->ublockexp = fls(uss) - 1;
1845		be_lun->ublockoff = (uss - uos) % uss;
1846	}
1847
1848	/*
1849	 * Sanity check.  The media size has to be at least one
1850	 * sector long.
1851	 */
1852	if (be_lun->size_bytes < be_lun->blocksize) {
1853		error = EINVAL;
1854		snprintf(req->error_str, sizeof(req->error_str),
1855			 "file %s size %ju < block size %u", be_lun->dev_path,
1856			 (uintmax_t)be_lun->size_bytes, be_lun->blocksize);
1857	}
1858
1859	be_lun->opttxferlen = CTLBLK_MAX_IO_SIZE / be_lun->blocksize;
1860	return (error);
1861}
1862
1863static int
1864ctl_be_block_open_dev(struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
1865{
1866	struct ctl_lun_create_params *params;
1867	struct vattr		      vattr;
1868	struct cdev		     *dev;
1869	struct cdevsw		     *devsw;
1870	char			     *value;
1871	int			      error, atomic, maxio, unmap;
1872	off_t			      ps, pss, po, pos, us, uss, uo, uos;
1873
1874	params = &be_lun->params;
1875
1876	be_lun->dev_type = CTL_BE_BLOCK_DEV;
1877	be_lun->backend.dev.cdev = be_lun->vn->v_rdev;
1878	be_lun->backend.dev.csw = dev_refthread(be_lun->backend.dev.cdev,
1879					     &be_lun->backend.dev.dev_ref);
1880	if (be_lun->backend.dev.csw == NULL)
1881		panic("Unable to retrieve device switch");
1882	if (strcmp(be_lun->backend.dev.csw->d_name, "zvol") == 0) {
1883		be_lun->dispatch = ctl_be_block_dispatch_zvol;
1884		be_lun->get_lba_status = ctl_be_block_gls_zvol;
1885		atomic = maxio = CTLBLK_MAX_IO_SIZE;
1886	} else {
1887		be_lun->dispatch = ctl_be_block_dispatch_dev;
1888		atomic = 0;
1889		maxio = be_lun->backend.dev.cdev->si_iosize_max;
1890		if (maxio <= 0)
1891			maxio = DFLTPHYS;
1892		if (maxio > CTLBLK_MAX_IO_SIZE)
1893			maxio = CTLBLK_MAX_IO_SIZE;
1894	}
1895	be_lun->lun_flush = ctl_be_block_flush_dev;
1896	be_lun->getattr = ctl_be_block_getattr_dev;
1897
1898	error = VOP_GETATTR(be_lun->vn, &vattr, NOCRED);
1899	if (error) {
1900		snprintf(req->error_str, sizeof(req->error_str),
1901			 "error getting vnode attributes for device %s",
1902			 be_lun->dev_path);
1903		return (error);
1904	}
1905
1906	dev = be_lun->vn->v_rdev;
1907	devsw = dev->si_devsw;
1908	if (!devsw->d_ioctl) {
1909		snprintf(req->error_str, sizeof(req->error_str),
1910			 "no d_ioctl for device %s!",
1911			 be_lun->dev_path);
1912		return (ENODEV);
1913	}
1914
1915	error = devsw->d_ioctl(dev, DIOCGSECTORSIZE,
1916			       (caddr_t)&be_lun->blocksize, FREAD,
1917			       curthread);
1918	if (error) {
1919		snprintf(req->error_str, sizeof(req->error_str),
1920			 "error %d returned for DIOCGSECTORSIZE ioctl "
1921			 "on %s!", error, be_lun->dev_path);
1922		return (error);
1923	}
1924
1925	/*
1926	 * If the user has asked for a blocksize that is greater than the
1927	 * backing device's blocksize, we can do it only if the blocksize
1928	 * the user is asking for is an even multiple of the underlying
1929	 * device's blocksize.
1930	 */
1931	if ((params->blocksize_bytes != 0)
1932	 && (params->blocksize_bytes > be_lun->blocksize)) {
1933		uint32_t bs_multiple, tmp_blocksize;
1934
1935		bs_multiple = params->blocksize_bytes / be_lun->blocksize;
1936
1937		tmp_blocksize = bs_multiple * be_lun->blocksize;
1938
1939		if (tmp_blocksize == params->blocksize_bytes) {
1940			be_lun->blocksize = params->blocksize_bytes;
1941		} else {
1942			snprintf(req->error_str, sizeof(req->error_str),
1943				 "requested blocksize %u is not an even "
1944				 "multiple of backing device blocksize %u",
1945				 params->blocksize_bytes,
1946				 be_lun->blocksize);
1947			return (EINVAL);
1948
1949		}
1950	} else if ((params->blocksize_bytes != 0)
1951		&& (params->blocksize_bytes != be_lun->blocksize)) {
1952		snprintf(req->error_str, sizeof(req->error_str),
1953			 "requested blocksize %u < backing device "
1954			 "blocksize %u", params->blocksize_bytes,
1955			 be_lun->blocksize);
1956		return (EINVAL);
1957	}
1958
1959	error = devsw->d_ioctl(dev, DIOCGMEDIASIZE,
1960			       (caddr_t)&be_lun->size_bytes, FREAD,
1961			       curthread);
1962	if (error) {
1963		snprintf(req->error_str, sizeof(req->error_str),
1964			 "error %d returned for DIOCGMEDIASIZE "
1965			 " ioctl on %s!", error,
1966			 be_lun->dev_path);
1967		return (error);
1968	}
1969
1970	if (params->lun_size_bytes != 0) {
1971		if (params->lun_size_bytes > be_lun->size_bytes) {
1972			snprintf(req->error_str, sizeof(req->error_str),
1973				 "requested LUN size %ju > backing device "
1974				 "size %ju",
1975				 (uintmax_t)params->lun_size_bytes,
1976				 (uintmax_t)be_lun->size_bytes);
1977			return (EINVAL);
1978		}
1979
1980		be_lun->size_bytes = params->lun_size_bytes;
1981	}
1982
1983	error = devsw->d_ioctl(dev, DIOCGSTRIPESIZE,
1984			       (caddr_t)&ps, FREAD, curthread);
1985	if (error)
1986		ps = po = 0;
1987	else {
1988		error = devsw->d_ioctl(dev, DIOCGSTRIPEOFFSET,
1989				       (caddr_t)&po, FREAD, curthread);
1990		if (error)
1991			po = 0;
1992	}
1993	us = ps;
1994	uo = po;
1995
1996	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "pblocksize");
1997	if (value != NULL)
1998		ctl_expand_number(value, &ps);
1999	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "pblockoffset");
2000	if (value != NULL)
2001		ctl_expand_number(value, &po);
2002	pss = ps / be_lun->blocksize;
2003	pos = po / be_lun->blocksize;
2004	if ((pss > 0) && (pss * be_lun->blocksize == ps) && (pss >= pos) &&
2005	    ((pss & (pss - 1)) == 0) && (pos * be_lun->blocksize == po)) {
2006		be_lun->pblockexp = fls(pss) - 1;
2007		be_lun->pblockoff = (pss - pos) % pss;
2008	}
2009
2010	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "ublocksize");
2011	if (value != NULL)
2012		ctl_expand_number(value, &us);
2013	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "ublockoffset");
2014	if (value != NULL)
2015		ctl_expand_number(value, &uo);
2016	uss = us / be_lun->blocksize;
2017	uos = uo / be_lun->blocksize;
2018	if ((uss > 0) && (uss * be_lun->blocksize == us) && (uss >= uos) &&
2019	    ((uss & (uss - 1)) == 0) && (uos * be_lun->blocksize == uo)) {
2020		be_lun->ublockexp = fls(uss) - 1;
2021		be_lun->ublockoff = (uss - uos) % uss;
2022	}
2023
2024	be_lun->atomicblock = atomic / be_lun->blocksize;
2025	be_lun->opttxferlen = maxio / be_lun->blocksize;
2026
2027	if (be_lun->dispatch == ctl_be_block_dispatch_zvol) {
2028		unmap = 1;
2029	} else {
2030		struct diocgattr_arg	arg;
2031
2032		strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
2033		arg.len = sizeof(arg.value.i);
2034		error = devsw->d_ioctl(dev, DIOCGATTR,
2035		    (caddr_t)&arg, FREAD, curthread);
2036		unmap = (error == 0) ? arg.value.i : 0;
2037	}
2038	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "unmap");
2039	if (value != NULL)
2040		unmap = (strcmp(value, "on") == 0);
2041	if (unmap)
2042		be_lun->unmap = ctl_be_block_unmap_dev;
2043
2044	return (0);
2045}
2046
2047static int
2048ctl_be_block_close(struct ctl_be_block_lun *be_lun)
2049{
2050	DROP_GIANT();
2051	if (be_lun->vn) {
2052		int flags = FREAD | FWRITE;
2053
2054		switch (be_lun->dev_type) {
2055		case CTL_BE_BLOCK_DEV:
2056			if (be_lun->backend.dev.csw) {
2057				dev_relthread(be_lun->backend.dev.cdev,
2058					      be_lun->backend.dev.dev_ref);
2059				be_lun->backend.dev.csw  = NULL;
2060				be_lun->backend.dev.cdev = NULL;
2061			}
2062			break;
2063		case CTL_BE_BLOCK_FILE:
2064			break;
2065		case CTL_BE_BLOCK_NONE:
2066			break;
2067		default:
2068			panic("Unexpected backend type.");
2069			break;
2070		}
2071
2072		(void)vn_close(be_lun->vn, flags, NOCRED, curthread);
2073		be_lun->vn = NULL;
2074
2075		switch (be_lun->dev_type) {
2076		case CTL_BE_BLOCK_DEV:
2077			break;
2078		case CTL_BE_BLOCK_FILE:
2079			if (be_lun->backend.file.cred != NULL) {
2080				crfree(be_lun->backend.file.cred);
2081				be_lun->backend.file.cred = NULL;
2082			}
2083			break;
2084		case CTL_BE_BLOCK_NONE:
2085			break;
2086		default:
2087			panic("Unexpected backend type.");
2088			break;
2089		}
2090		be_lun->dev_type = CTL_BE_BLOCK_NONE;
2091	}
2092	PICKUP_GIANT();
2093
2094	return (0);
2095}
2096
2097static int
2098ctl_be_block_open(struct ctl_be_block_softc *softc,
2099		       struct ctl_be_block_lun *be_lun, struct ctl_lun_req *req)
2100{
2101	struct nameidata nd;
2102	int		 flags;
2103	int		 error;
2104
2105	/*
2106	 * XXX KDM allow a read-only option?
2107	 */
2108	flags = FREAD | FWRITE;
2109	error = 0;
2110
2111	if (rootvnode == NULL) {
2112		snprintf(req->error_str, sizeof(req->error_str),
2113			 "Root filesystem is not mounted");
2114		return (1);
2115	}
2116
2117	if (!curthread->td_proc->p_fd->fd_cdir) {
2118		curthread->td_proc->p_fd->fd_cdir = rootvnode;
2119		VREF(rootvnode);
2120	}
2121	if (!curthread->td_proc->p_fd->fd_rdir) {
2122		curthread->td_proc->p_fd->fd_rdir = rootvnode;
2123		VREF(rootvnode);
2124	}
2125	if (!curthread->td_proc->p_fd->fd_jdir) {
2126		curthread->td_proc->p_fd->fd_jdir = rootvnode;
2127		VREF(rootvnode);
2128	}
2129
2130 again:
2131	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, be_lun->dev_path, curthread);
2132	error = vn_open(&nd, &flags, 0, NULL);
2133	if (error) {
2134		/*
2135		 * This is the only reasonable guess we can make as far as
2136		 * path if the user doesn't give us a fully qualified path.
2137		 * If they want to specify a file, they need to specify the
2138		 * full path.
2139		 */
2140		if (be_lun->dev_path[0] != '/') {
2141			char *dev_path = "/dev/";
2142			char *dev_name;
2143
2144			/* Try adding device path at beginning of name */
2145			dev_name = malloc(strlen(be_lun->dev_path)
2146					+ strlen(dev_path) + 1,
2147					  M_CTLBLK, M_WAITOK);
2148			if (dev_name) {
2149				sprintf(dev_name, "%s%s", dev_path,
2150					be_lun->dev_path);
2151				free(be_lun->dev_path, M_CTLBLK);
2152				be_lun->dev_path = dev_name;
2153				goto again;
2154			}
2155		}
2156		snprintf(req->error_str, sizeof(req->error_str),
2157		    "error opening %s: %d", be_lun->dev_path, error);
2158		return (error);
2159	}
2160
2161	NDFREE(&nd, NDF_ONLY_PNBUF);
2162
2163	be_lun->vn = nd.ni_vp;
2164
2165	/* We only support disks and files. */
2166	if (vn_isdisk(be_lun->vn, &error)) {
2167		error = ctl_be_block_open_dev(be_lun, req);
2168	} else if (be_lun->vn->v_type == VREG) {
2169		error = ctl_be_block_open_file(be_lun, req);
2170	} else {
2171		error = EINVAL;
2172		snprintf(req->error_str, sizeof(req->error_str),
2173			 "%s is not a disk or plain file", be_lun->dev_path);
2174	}
2175	VOP_UNLOCK(be_lun->vn, 0);
2176
2177	if (error != 0) {
2178		ctl_be_block_close(be_lun);
2179		return (error);
2180	}
2181
2182	be_lun->blocksize_shift = fls(be_lun->blocksize) - 1;
2183	be_lun->size_blocks = be_lun->size_bytes >> be_lun->blocksize_shift;
2184
2185	return (0);
2186}
2187
2188static int
2189ctl_be_block_create(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2190{
2191	struct ctl_be_block_lun *be_lun;
2192	struct ctl_lun_create_params *params;
2193	char num_thread_str[16];
2194	char tmpstr[32];
2195	char *value;
2196	int retval, num_threads;
2197	int tmp_num_threads;
2198
2199	params = &req->reqdata.create;
2200	retval = 0;
2201	req->status = CTL_LUN_OK;
2202
2203	num_threads = cbb_num_threads;
2204
2205	be_lun = malloc(sizeof(*be_lun), M_CTLBLK, M_ZERO | M_WAITOK);
2206
2207	be_lun->params = req->reqdata.create;
2208	be_lun->softc = softc;
2209	STAILQ_INIT(&be_lun->input_queue);
2210	STAILQ_INIT(&be_lun->config_read_queue);
2211	STAILQ_INIT(&be_lun->config_write_queue);
2212	STAILQ_INIT(&be_lun->datamove_queue);
2213	sprintf(be_lun->lunname, "cblk%d", softc->num_luns);
2214	mtx_init(&be_lun->io_lock, "cblk io lock", NULL, MTX_DEF);
2215	mtx_init(&be_lun->queue_lock, "cblk queue lock", NULL, MTX_DEF);
2216	ctl_init_opts(&be_lun->ctl_be_lun.options,
2217	    req->num_be_args, req->kern_be_args);
2218
2219	be_lun->lun_zone = uma_zcreate(be_lun->lunname, CTLBLK_MAX_SEG,
2220	    NULL, NULL, NULL, NULL, /*align*/ 0, /*flags*/0);
2221
2222	if (be_lun->lun_zone == NULL) {
2223		snprintf(req->error_str, sizeof(req->error_str),
2224			 "error allocating UMA zone");
2225		goto bailout_error;
2226	}
2227
2228	if (params->flags & CTL_LUN_FLAG_DEV_TYPE)
2229		be_lun->ctl_be_lun.lun_type = params->device_type;
2230	else
2231		be_lun->ctl_be_lun.lun_type = T_DIRECT;
2232
2233	if (be_lun->ctl_be_lun.lun_type == T_DIRECT) {
2234		value = ctl_get_opt(&be_lun->ctl_be_lun.options, "file");
2235		if (value == NULL) {
2236			snprintf(req->error_str, sizeof(req->error_str),
2237				 "no file argument specified");
2238			goto bailout_error;
2239		}
2240		be_lun->dev_path = strdup(value, M_CTLBLK);
2241		be_lun->blocksize = 512;
2242		be_lun->blocksize_shift = fls(be_lun->blocksize) - 1;
2243
2244		retval = ctl_be_block_open(softc, be_lun, req);
2245		if (retval != 0) {
2246			retval = 0;
2247			req->status = CTL_LUN_WARNING;
2248		}
2249	} else {
2250		/*
2251		 * For processor devices, we don't have any size.
2252		 */
2253		be_lun->blocksize = 0;
2254		be_lun->pblockexp = 0;
2255		be_lun->pblockoff = 0;
2256		be_lun->ublockexp = 0;
2257		be_lun->ublockoff = 0;
2258		be_lun->size_blocks = 0;
2259		be_lun->size_bytes = 0;
2260		be_lun->ctl_be_lun.maxlba = 0;
2261
2262		/*
2263		 * Default to just 1 thread for processor devices.
2264		 */
2265		num_threads = 1;
2266	}
2267
2268	/*
2269	 * XXX This searching loop might be refactored to be combined with
2270	 * the loop above,
2271	 */
2272	value = ctl_get_opt(&be_lun->ctl_be_lun.options, "num_threads");
2273	if (value != NULL) {
2274		tmp_num_threads = strtol(value, NULL, 0);
2275
2276		/*
2277		 * We don't let the user specify less than one
2278		 * thread, but hope he's clueful enough not to
2279		 * specify 1000 threads.
2280		 */
2281		if (tmp_num_threads < 1) {
2282			snprintf(req->error_str, sizeof(req->error_str),
2283				 "invalid number of threads %s",
2284				 num_thread_str);
2285			goto bailout_error;
2286		}
2287		num_threads = tmp_num_threads;
2288	}
2289
2290	be_lun->flags = CTL_BE_BLOCK_LUN_UNCONFIGURED;
2291	be_lun->ctl_be_lun.flags = CTL_LUN_FLAG_PRIMARY;
2292	if (be_lun->vn == NULL)
2293		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_OFFLINE;
2294	if (be_lun->unmap != NULL)
2295		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_UNMAP;
2296	if (be_lun->dispatch != ctl_be_block_dispatch_dev)
2297		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_SERSEQ_READ;
2298	be_lun->ctl_be_lun.be_lun = be_lun;
2299	be_lun->ctl_be_lun.maxlba = (be_lun->size_blocks == 0) ?
2300	    0 : (be_lun->size_blocks - 1);
2301	be_lun->ctl_be_lun.blocksize = be_lun->blocksize;
2302	be_lun->ctl_be_lun.pblockexp = be_lun->pblockexp;
2303	be_lun->ctl_be_lun.pblockoff = be_lun->pblockoff;
2304	be_lun->ctl_be_lun.ublockexp = be_lun->ublockexp;
2305	be_lun->ctl_be_lun.ublockoff = be_lun->ublockoff;
2306	be_lun->ctl_be_lun.atomicblock = be_lun->atomicblock;
2307	be_lun->ctl_be_lun.opttxferlen = be_lun->opttxferlen;
2308	/* Tell the user the blocksize we ended up using */
2309	params->lun_size_bytes = be_lun->size_bytes;
2310	params->blocksize_bytes = be_lun->blocksize;
2311	if (params->flags & CTL_LUN_FLAG_ID_REQ) {
2312		be_lun->ctl_be_lun.req_lun_id = params->req_lun_id;
2313		be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_ID_REQ;
2314	} else
2315		be_lun->ctl_be_lun.req_lun_id = 0;
2316
2317	be_lun->ctl_be_lun.lun_shutdown = ctl_be_block_lun_shutdown;
2318	be_lun->ctl_be_lun.lun_config_status =
2319		ctl_be_block_lun_config_status;
2320	be_lun->ctl_be_lun.be = &ctl_be_block_driver;
2321
2322	if ((params->flags & CTL_LUN_FLAG_SERIAL_NUM) == 0) {
2323		snprintf(tmpstr, sizeof(tmpstr), "MYSERIAL%4d",
2324			 softc->num_luns);
2325		strncpy((char *)be_lun->ctl_be_lun.serial_num, tmpstr,
2326			MIN(sizeof(be_lun->ctl_be_lun.serial_num),
2327			sizeof(tmpstr)));
2328
2329		/* Tell the user what we used for a serial number */
2330		strncpy((char *)params->serial_num, tmpstr,
2331			MIN(sizeof(params->serial_num), sizeof(tmpstr)));
2332	} else {
2333		strncpy((char *)be_lun->ctl_be_lun.serial_num,
2334			params->serial_num,
2335			MIN(sizeof(be_lun->ctl_be_lun.serial_num),
2336			sizeof(params->serial_num)));
2337	}
2338	if ((params->flags & CTL_LUN_FLAG_DEVID) == 0) {
2339		snprintf(tmpstr, sizeof(tmpstr), "MYDEVID%4d", softc->num_luns);
2340		strncpy((char *)be_lun->ctl_be_lun.device_id, tmpstr,
2341			MIN(sizeof(be_lun->ctl_be_lun.device_id),
2342			sizeof(tmpstr)));
2343
2344		/* Tell the user what we used for a device ID */
2345		strncpy((char *)params->device_id, tmpstr,
2346			MIN(sizeof(params->device_id), sizeof(tmpstr)));
2347	} else {
2348		strncpy((char *)be_lun->ctl_be_lun.device_id,
2349			params->device_id,
2350			MIN(sizeof(be_lun->ctl_be_lun.device_id),
2351			    sizeof(params->device_id)));
2352	}
2353
2354	TASK_INIT(&be_lun->io_task, /*priority*/0, ctl_be_block_worker, be_lun);
2355
2356	be_lun->io_taskqueue = taskqueue_create(be_lun->lunname, M_WAITOK,
2357	    taskqueue_thread_enqueue, /*context*/&be_lun->io_taskqueue);
2358
2359	if (be_lun->io_taskqueue == NULL) {
2360		snprintf(req->error_str, sizeof(req->error_str),
2361			 "unable to create taskqueue");
2362		goto bailout_error;
2363	}
2364
2365	/*
2366	 * Note that we start the same number of threads by default for
2367	 * both the file case and the block device case.  For the file
2368	 * case, we need multiple threads to allow concurrency, because the
2369	 * vnode interface is designed to be a blocking interface.  For the
2370	 * block device case, ZFS zvols at least will block the caller's
2371	 * context in many instances, and so we need multiple threads to
2372	 * overcome that problem.  Other block devices don't need as many
2373	 * threads, but they shouldn't cause too many problems.
2374	 *
2375	 * If the user wants to just have a single thread for a block
2376	 * device, he can specify that when the LUN is created, or change
2377	 * the tunable/sysctl to alter the default number of threads.
2378	 */
2379	retval = taskqueue_start_threads(&be_lun->io_taskqueue,
2380					 /*num threads*/num_threads,
2381					 /*priority*/PWAIT,
2382					 /*thread name*/
2383					 "%s taskq", be_lun->lunname);
2384
2385	if (retval != 0)
2386		goto bailout_error;
2387
2388	be_lun->num_threads = num_threads;
2389
2390	mtx_lock(&softc->lock);
2391	softc->num_luns++;
2392	STAILQ_INSERT_TAIL(&softc->lun_list, be_lun, links);
2393
2394	mtx_unlock(&softc->lock);
2395
2396	retval = ctl_add_lun(&be_lun->ctl_be_lun);
2397	if (retval != 0) {
2398		mtx_lock(&softc->lock);
2399		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2400			      links);
2401		softc->num_luns--;
2402		mtx_unlock(&softc->lock);
2403		snprintf(req->error_str, sizeof(req->error_str),
2404			 "ctl_add_lun() returned error %d, see dmesg for "
2405			 "details", retval);
2406		retval = 0;
2407		goto bailout_error;
2408	}
2409
2410	mtx_lock(&softc->lock);
2411
2412	/*
2413	 * Tell the config_status routine that we're waiting so it won't
2414	 * clean up the LUN in the event of an error.
2415	 */
2416	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2417
2418	while (be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) {
2419		retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2420		if (retval == EINTR)
2421			break;
2422	}
2423	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2424
2425	if (be_lun->flags & CTL_BE_BLOCK_LUN_CONFIG_ERR) {
2426		snprintf(req->error_str, sizeof(req->error_str),
2427			 "LUN configuration error, see dmesg for details");
2428		STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun,
2429			      links);
2430		softc->num_luns--;
2431		mtx_unlock(&softc->lock);
2432		goto bailout_error;
2433	} else {
2434		params->req_lun_id = be_lun->ctl_be_lun.lun_id;
2435	}
2436
2437	mtx_unlock(&softc->lock);
2438
2439	be_lun->disk_stats = devstat_new_entry("cbb", params->req_lun_id,
2440					       be_lun->blocksize,
2441					       DEVSTAT_ALL_SUPPORTED,
2442					       be_lun->ctl_be_lun.lun_type
2443					       | DEVSTAT_TYPE_IF_OTHER,
2444					       DEVSTAT_PRIORITY_OTHER);
2445
2446	return (retval);
2447
2448bailout_error:
2449	req->status = CTL_LUN_ERROR;
2450
2451	if (be_lun->io_taskqueue != NULL)
2452		taskqueue_free(be_lun->io_taskqueue);
2453	ctl_be_block_close(be_lun);
2454	if (be_lun->dev_path != NULL)
2455		free(be_lun->dev_path, M_CTLBLK);
2456	if (be_lun->lun_zone != NULL)
2457		uma_zdestroy(be_lun->lun_zone);
2458	ctl_free_opts(&be_lun->ctl_be_lun.options);
2459	mtx_destroy(&be_lun->queue_lock);
2460	mtx_destroy(&be_lun->io_lock);
2461	free(be_lun, M_CTLBLK);
2462
2463	return (retval);
2464}
2465
2466static int
2467ctl_be_block_rm(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2468{
2469	struct ctl_lun_rm_params *params;
2470	struct ctl_be_block_lun *be_lun;
2471	int retval;
2472
2473	params = &req->reqdata.rm;
2474
2475	mtx_lock(&softc->lock);
2476
2477	be_lun = NULL;
2478
2479	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2480		if (be_lun->ctl_be_lun.lun_id == params->lun_id)
2481			break;
2482	}
2483	mtx_unlock(&softc->lock);
2484
2485	if (be_lun == NULL) {
2486		snprintf(req->error_str, sizeof(req->error_str),
2487			 "LUN %u is not managed by the block backend",
2488			 params->lun_id);
2489		goto bailout_error;
2490	}
2491
2492	retval = ctl_disable_lun(&be_lun->ctl_be_lun);
2493
2494	if (retval != 0) {
2495		snprintf(req->error_str, sizeof(req->error_str),
2496			 "error %d returned from ctl_disable_lun() for "
2497			 "LUN %d", retval, params->lun_id);
2498		goto bailout_error;
2499
2500	}
2501
2502	retval = ctl_invalidate_lun(&be_lun->ctl_be_lun);
2503	if (retval != 0) {
2504		snprintf(req->error_str, sizeof(req->error_str),
2505			 "error %d returned from ctl_invalidate_lun() for "
2506			 "LUN %d", retval, params->lun_id);
2507		goto bailout_error;
2508	}
2509
2510	mtx_lock(&softc->lock);
2511
2512	be_lun->flags |= CTL_BE_BLOCK_LUN_WAITING;
2513
2514	while ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2515                retval = msleep(be_lun, &softc->lock, PCATCH, "ctlblk", 0);
2516                if (retval == EINTR)
2517                        break;
2518        }
2519
2520	be_lun->flags &= ~CTL_BE_BLOCK_LUN_WAITING;
2521
2522	if ((be_lun->flags & CTL_BE_BLOCK_LUN_UNCONFIGURED) == 0) {
2523		snprintf(req->error_str, sizeof(req->error_str),
2524			 "interrupted waiting for LUN to be freed");
2525		mtx_unlock(&softc->lock);
2526		goto bailout_error;
2527	}
2528
2529	STAILQ_REMOVE(&softc->lun_list, be_lun, ctl_be_block_lun, links);
2530
2531	softc->num_luns--;
2532	mtx_unlock(&softc->lock);
2533
2534	taskqueue_drain(be_lun->io_taskqueue, &be_lun->io_task);
2535
2536	taskqueue_free(be_lun->io_taskqueue);
2537
2538	ctl_be_block_close(be_lun);
2539
2540	if (be_lun->disk_stats != NULL)
2541		devstat_remove_entry(be_lun->disk_stats);
2542
2543	uma_zdestroy(be_lun->lun_zone);
2544
2545	ctl_free_opts(&be_lun->ctl_be_lun.options);
2546	free(be_lun->dev_path, M_CTLBLK);
2547	mtx_destroy(&be_lun->queue_lock);
2548	mtx_destroy(&be_lun->io_lock);
2549	free(be_lun, M_CTLBLK);
2550
2551	req->status = CTL_LUN_OK;
2552
2553	return (0);
2554
2555bailout_error:
2556
2557	req->status = CTL_LUN_ERROR;
2558
2559	return (0);
2560}
2561
2562static int
2563ctl_be_block_modify_file(struct ctl_be_block_lun *be_lun,
2564			 struct ctl_lun_req *req)
2565{
2566	struct vattr vattr;
2567	int error;
2568	struct ctl_lun_create_params *params = &be_lun->params;
2569
2570	if (params->lun_size_bytes != 0) {
2571		be_lun->size_bytes = params->lun_size_bytes;
2572	} else  {
2573		vn_lock(be_lun->vn, LK_SHARED | LK_RETRY);
2574		error = VOP_GETATTR(be_lun->vn, &vattr, curthread->td_ucred);
2575		VOP_UNLOCK(be_lun->vn, 0);
2576		if (error != 0) {
2577			snprintf(req->error_str, sizeof(req->error_str),
2578				 "error calling VOP_GETATTR() for file %s",
2579				 be_lun->dev_path);
2580			return (error);
2581		}
2582
2583		be_lun->size_bytes = vattr.va_size;
2584	}
2585
2586	return (0);
2587}
2588
2589static int
2590ctl_be_block_modify_dev(struct ctl_be_block_lun *be_lun,
2591			struct ctl_lun_req *req)
2592{
2593	struct ctl_be_block_devdata *dev_data;
2594	int error;
2595	struct ctl_lun_create_params *params = &be_lun->params;
2596	uint64_t size_bytes;
2597
2598	dev_data = &be_lun->backend.dev;
2599	if (!dev_data->csw->d_ioctl) {
2600		snprintf(req->error_str, sizeof(req->error_str),
2601			 "no d_ioctl for device %s!", be_lun->dev_path);
2602		return (ENODEV);
2603	}
2604
2605	error = dev_data->csw->d_ioctl(dev_data->cdev, DIOCGMEDIASIZE,
2606			       (caddr_t)&size_bytes, FREAD,
2607			       curthread);
2608	if (error) {
2609		snprintf(req->error_str, sizeof(req->error_str),
2610			 "error %d returned for DIOCGMEDIASIZE ioctl "
2611			 "on %s!", error, be_lun->dev_path);
2612		return (error);
2613	}
2614
2615	if (params->lun_size_bytes != 0) {
2616		if (params->lun_size_bytes > size_bytes) {
2617			snprintf(req->error_str, sizeof(req->error_str),
2618				 "requested LUN size %ju > backing device "
2619				 "size %ju",
2620				 (uintmax_t)params->lun_size_bytes,
2621				 (uintmax_t)size_bytes);
2622			return (EINVAL);
2623		}
2624
2625		be_lun->size_bytes = params->lun_size_bytes;
2626	} else {
2627		be_lun->size_bytes = size_bytes;
2628	}
2629
2630	return (0);
2631}
2632
2633static int
2634ctl_be_block_modify(struct ctl_be_block_softc *softc, struct ctl_lun_req *req)
2635{
2636	struct ctl_lun_modify_params *params;
2637	struct ctl_be_block_lun *be_lun;
2638	uint64_t oldsize;
2639	int error;
2640
2641	params = &req->reqdata.modify;
2642
2643	mtx_lock(&softc->lock);
2644	be_lun = NULL;
2645	STAILQ_FOREACH(be_lun, &softc->lun_list, links) {
2646		if (be_lun->ctl_be_lun.lun_id == params->lun_id)
2647			break;
2648	}
2649	mtx_unlock(&softc->lock);
2650
2651	if (be_lun == NULL) {
2652		snprintf(req->error_str, sizeof(req->error_str),
2653			 "LUN %u is not managed by the block backend",
2654			 params->lun_id);
2655		goto bailout_error;
2656	}
2657
2658	be_lun->params.lun_size_bytes = params->lun_size_bytes;
2659
2660	oldsize = be_lun->size_bytes;
2661	if (be_lun->vn == NULL)
2662		error = ctl_be_block_open(softc, be_lun, req);
2663	else if (vn_isdisk(be_lun->vn, &error))
2664		error = ctl_be_block_modify_dev(be_lun, req);
2665	else if (be_lun->vn->v_type == VREG)
2666		error = ctl_be_block_modify_file(be_lun, req);
2667	else
2668		error = EINVAL;
2669
2670	if (error == 0 && be_lun->size_bytes != oldsize) {
2671		be_lun->size_blocks = be_lun->size_bytes >>
2672		    be_lun->blocksize_shift;
2673
2674		/*
2675		 * The maximum LBA is the size - 1.
2676		 *
2677		 * XXX: Note that this field is being updated without locking,
2678		 * 	which might cause problems on 32-bit architectures.
2679		 */
2680		if (be_lun->unmap != NULL)
2681			be_lun->ctl_be_lun.flags |= CTL_LUN_FLAG_UNMAP;
2682		be_lun->ctl_be_lun.maxlba = (be_lun->size_blocks == 0) ?
2683		    0 : (be_lun->size_blocks - 1);
2684		be_lun->ctl_be_lun.blocksize = be_lun->blocksize;
2685		be_lun->ctl_be_lun.pblockexp = be_lun->pblockexp;
2686		be_lun->ctl_be_lun.pblockoff = be_lun->pblockoff;
2687		be_lun->ctl_be_lun.ublockexp = be_lun->ublockexp;
2688		be_lun->ctl_be_lun.ublockoff = be_lun->ublockoff;
2689		be_lun->ctl_be_lun.atomicblock = be_lun->atomicblock;
2690		be_lun->ctl_be_lun.opttxferlen = be_lun->opttxferlen;
2691		ctl_lun_capacity_changed(&be_lun->ctl_be_lun);
2692		if (oldsize == 0 && be_lun->size_blocks != 0)
2693			ctl_lun_online(&be_lun->ctl_be_lun);
2694	}
2695
2696	/* Tell the user the exact size we ended up using */
2697	params->lun_size_bytes = be_lun->size_bytes;
2698
2699	req->status = error ? CTL_LUN_WARNING : CTL_LUN_OK;
2700
2701	return (0);
2702
2703bailout_error:
2704	req->status = CTL_LUN_ERROR;
2705
2706	return (0);
2707}
2708
2709static void
2710ctl_be_block_lun_shutdown(void *be_lun)
2711{
2712	struct ctl_be_block_lun *lun;
2713	struct ctl_be_block_softc *softc;
2714
2715	lun = (struct ctl_be_block_lun *)be_lun;
2716
2717	softc = lun->softc;
2718
2719	mtx_lock(&softc->lock);
2720	lun->flags |= CTL_BE_BLOCK_LUN_UNCONFIGURED;
2721	if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2722		wakeup(lun);
2723	mtx_unlock(&softc->lock);
2724
2725}
2726
2727static void
2728ctl_be_block_lun_config_status(void *be_lun, ctl_lun_config_status status)
2729{
2730	struct ctl_be_block_lun *lun;
2731	struct ctl_be_block_softc *softc;
2732
2733	lun = (struct ctl_be_block_lun *)be_lun;
2734	softc = lun->softc;
2735
2736	if (status == CTL_LUN_CONFIG_OK) {
2737		mtx_lock(&softc->lock);
2738		lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2739		if (lun->flags & CTL_BE_BLOCK_LUN_WAITING)
2740			wakeup(lun);
2741		mtx_unlock(&softc->lock);
2742
2743		/*
2744		 * We successfully added the LUN, attempt to enable it.
2745		 */
2746		if (ctl_enable_lun(&lun->ctl_be_lun) != 0) {
2747			printf("%s: ctl_enable_lun() failed!\n", __func__);
2748			if (ctl_invalidate_lun(&lun->ctl_be_lun) != 0) {
2749				printf("%s: ctl_invalidate_lun() failed!\n",
2750				       __func__);
2751			}
2752		}
2753
2754		return;
2755	}
2756
2757
2758	mtx_lock(&softc->lock);
2759	lun->flags &= ~CTL_BE_BLOCK_LUN_UNCONFIGURED;
2760	lun->flags |= CTL_BE_BLOCK_LUN_CONFIG_ERR;
2761	wakeup(lun);
2762	mtx_unlock(&softc->lock);
2763}
2764
2765
2766static int
2767ctl_be_block_config_write(union ctl_io *io)
2768{
2769	struct ctl_be_block_lun *be_lun;
2770	struct ctl_be_lun *ctl_be_lun;
2771	int retval;
2772
2773	retval = 0;
2774
2775	DPRINTF("entered\n");
2776
2777	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2778		CTL_PRIV_BACKEND_LUN].ptr;
2779	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
2780
2781	switch (io->scsiio.cdb[0]) {
2782	case SYNCHRONIZE_CACHE:
2783	case SYNCHRONIZE_CACHE_16:
2784	case WRITE_SAME_10:
2785	case WRITE_SAME_16:
2786	case UNMAP:
2787		/*
2788		 * The upper level CTL code will filter out any CDBs with
2789		 * the immediate bit set and return the proper error.
2790		 *
2791		 * We don't really need to worry about what LBA range the
2792		 * user asked to be synced out.  When they issue a sync
2793		 * cache command, we'll sync out the whole thing.
2794		 */
2795		mtx_lock(&be_lun->queue_lock);
2796		STAILQ_INSERT_TAIL(&be_lun->config_write_queue, &io->io_hdr,
2797				   links);
2798		mtx_unlock(&be_lun->queue_lock);
2799		taskqueue_enqueue(be_lun->io_taskqueue, &be_lun->io_task);
2800		break;
2801	case START_STOP_UNIT: {
2802		struct scsi_start_stop_unit *cdb;
2803
2804		cdb = (struct scsi_start_stop_unit *)io->scsiio.cdb;
2805
2806		if (cdb->how & SSS_START)
2807			retval = ctl_start_lun(ctl_be_lun);
2808		else {
2809			retval = ctl_stop_lun(ctl_be_lun);
2810			/*
2811			 * XXX KDM Copan-specific offline behavior.
2812			 * Figure out a reasonable way to port this?
2813			 */
2814#ifdef NEEDTOPORT
2815			if ((retval == 0)
2816			 && (cdb->byte2 & SSS_ONOFFLINE))
2817				retval = ctl_lun_offline(ctl_be_lun);
2818#endif
2819		}
2820
2821		/*
2822		 * In general, the above routines should not fail.  They
2823		 * just set state for the LUN.  So we've got something
2824		 * pretty wrong here if we can't start or stop the LUN.
2825		 */
2826		if (retval != 0) {
2827			ctl_set_internal_failure(&io->scsiio,
2828						 /*sks_valid*/ 1,
2829						 /*retry_count*/ 0xf051);
2830			retval = CTL_RETVAL_COMPLETE;
2831		} else {
2832			ctl_set_success(&io->scsiio);
2833		}
2834		ctl_config_write_done(io);
2835		break;
2836	}
2837	default:
2838		ctl_set_invalid_opcode(&io->scsiio);
2839		ctl_config_write_done(io);
2840		retval = CTL_RETVAL_COMPLETE;
2841		break;
2842	}
2843
2844	return (retval);
2845}
2846
2847static int
2848ctl_be_block_config_read(union ctl_io *io)
2849{
2850	struct ctl_be_block_lun *be_lun;
2851	struct ctl_be_lun *ctl_be_lun;
2852	int retval = 0;
2853
2854	DPRINTF("entered\n");
2855
2856	ctl_be_lun = (struct ctl_be_lun *)io->io_hdr.ctl_private[
2857		CTL_PRIV_BACKEND_LUN].ptr;
2858	be_lun = (struct ctl_be_block_lun *)ctl_be_lun->be_lun;
2859
2860	switch (io->scsiio.cdb[0]) {
2861	case SERVICE_ACTION_IN:
2862		if (io->scsiio.cdb[1] == SGLS_SERVICE_ACTION) {
2863			mtx_lock(&be_lun->queue_lock);
2864			STAILQ_INSERT_TAIL(&be_lun->config_read_queue,
2865			    &io->io_hdr, links);
2866			mtx_unlock(&be_lun->queue_lock);
2867			taskqueue_enqueue(be_lun->io_taskqueue,
2868			    &be_lun->io_task);
2869			retval = CTL_RETVAL_QUEUED;
2870			break;
2871		}
2872		ctl_set_invalid_field(&io->scsiio,
2873				      /*sks_valid*/ 1,
2874				      /*command*/ 1,
2875				      /*field*/ 1,
2876				      /*bit_valid*/ 1,
2877				      /*bit*/ 4);
2878		ctl_config_read_done(io);
2879		retval = CTL_RETVAL_COMPLETE;
2880		break;
2881	default:
2882		ctl_set_invalid_opcode(&io->scsiio);
2883		ctl_config_read_done(io);
2884		retval = CTL_RETVAL_COMPLETE;
2885		break;
2886	}
2887
2888	return (retval);
2889}
2890
2891static int
2892ctl_be_block_lun_info(void *be_lun, struct sbuf *sb)
2893{
2894	struct ctl_be_block_lun *lun;
2895	int retval;
2896
2897	lun = (struct ctl_be_block_lun *)be_lun;
2898	retval = 0;
2899
2900	retval = sbuf_printf(sb, "\t<num_threads>");
2901
2902	if (retval != 0)
2903		goto bailout;
2904
2905	retval = sbuf_printf(sb, "%d", lun->num_threads);
2906
2907	if (retval != 0)
2908		goto bailout;
2909
2910	retval = sbuf_printf(sb, "</num_threads>\n");
2911
2912bailout:
2913
2914	return (retval);
2915}
2916
2917static uint64_t
2918ctl_be_block_lun_attr(void *be_lun, const char *attrname)
2919{
2920	struct ctl_be_block_lun *lun = (struct ctl_be_block_lun *)be_lun;
2921
2922	if (lun->getattr == NULL)
2923		return (UINT64_MAX);
2924	return (lun->getattr(lun, attrname));
2925}
2926
2927int
2928ctl_be_block_init(void)
2929{
2930	struct ctl_be_block_softc *softc;
2931	int retval;
2932
2933	softc = &backend_block_softc;
2934	retval = 0;
2935
2936	mtx_init(&softc->lock, "ctlblock", NULL, MTX_DEF);
2937	beio_zone = uma_zcreate("beio", sizeof(struct ctl_be_block_io),
2938	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
2939	STAILQ_INIT(&softc->disk_list);
2940	STAILQ_INIT(&softc->lun_list);
2941
2942	return (retval);
2943}
2944