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