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