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