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