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