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