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