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