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