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