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