xref: /freebsd/sys/cam/scsi/scsi_pass.c (revision f0cfa1b168014f56c02b83e5f28412cc5f78d117)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1997, 1998, 2000 Justin T. Gibbs.
5  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/conf.h>
37 #include <sys/types.h>
38 #include <sys/bio.h>
39 #include <sys/bus.h>
40 #include <sys/devicestat.h>
41 #include <sys/errno.h>
42 #include <sys/fcntl.h>
43 #include <sys/malloc.h>
44 #include <sys/proc.h>
45 #include <sys/poll.h>
46 #include <sys/selinfo.h>
47 #include <sys/sdt.h>
48 #include <sys/taskqueue.h>
49 #include <vm/uma.h>
50 #include <vm/vm.h>
51 #include <vm/vm_extern.h>
52 
53 #include <machine/bus.h>
54 
55 #include <cam/cam.h>
56 #include <cam/cam_ccb.h>
57 #include <cam/cam_periph.h>
58 #include <cam/cam_queue.h>
59 #include <cam/cam_xpt.h>
60 #include <cam/cam_xpt_periph.h>
61 #include <cam/cam_debug.h>
62 #include <cam/cam_compat.h>
63 #include <cam/cam_xpt_periph.h>
64 
65 #include <cam/scsi/scsi_all.h>
66 #include <cam/scsi/scsi_pass.h>
67 
68 typedef enum {
69 	PASS_FLAG_OPEN			= 0x01,
70 	PASS_FLAG_LOCKED		= 0x02,
71 	PASS_FLAG_INVALID		= 0x04,
72 	PASS_FLAG_INITIAL_PHYSPATH	= 0x08,
73 	PASS_FLAG_ZONE_INPROG		= 0x10,
74 	PASS_FLAG_ZONE_VALID		= 0x20,
75 	PASS_FLAG_UNMAPPED_CAPABLE	= 0x40,
76 	PASS_FLAG_ABANDONED_REF_SET	= 0x80
77 } pass_flags;
78 
79 typedef enum {
80 	PASS_STATE_NORMAL
81 } pass_state;
82 
83 typedef enum {
84 	PASS_CCB_BUFFER_IO,
85 	PASS_CCB_QUEUED_IO
86 } pass_ccb_types;
87 
88 #define ccb_type	ppriv_field0
89 #define ccb_ioreq	ppriv_ptr1
90 
91 /*
92  * The maximum number of memory segments we preallocate.
93  */
94 #define	PASS_MAX_SEGS	16
95 
96 typedef enum {
97 	PASS_IO_NONE		= 0x00,
98 	PASS_IO_USER_SEG_MALLOC	= 0x01,
99 	PASS_IO_KERN_SEG_MALLOC	= 0x02,
100 	PASS_IO_ABANDONED	= 0x04
101 } pass_io_flags;
102 
103 struct pass_io_req {
104 	union ccb			 ccb;
105 	union ccb			*alloced_ccb;
106 	union ccb			*user_ccb_ptr;
107 	camq_entry			 user_periph_links;
108 	ccb_ppriv_area			 user_periph_priv;
109 	struct cam_periph_map_info	 mapinfo;
110 	pass_io_flags			 flags;
111 	ccb_flags			 data_flags;
112 	int				 num_user_segs;
113 	bus_dma_segment_t		 user_segs[PASS_MAX_SEGS];
114 	int				 num_kern_segs;
115 	bus_dma_segment_t		 kern_segs[PASS_MAX_SEGS];
116 	bus_dma_segment_t		*user_segptr;
117 	bus_dma_segment_t		*kern_segptr;
118 	int				 num_bufs;
119 	uint32_t			 dirs[CAM_PERIPH_MAXMAPS];
120 	uint32_t			 lengths[CAM_PERIPH_MAXMAPS];
121 	uint8_t				*user_bufs[CAM_PERIPH_MAXMAPS];
122 	uint8_t				*kern_bufs[CAM_PERIPH_MAXMAPS];
123 	struct bintime			 start_time;
124 	TAILQ_ENTRY(pass_io_req)	 links;
125 };
126 
127 struct pass_softc {
128 	pass_state		  state;
129 	pass_flags		  flags;
130 	u_int8_t		  pd_type;
131 	union ccb		  saved_ccb;
132 	int			  open_count;
133 	u_int		 	  maxio;
134 	struct devstat		 *device_stats;
135 	struct cdev		 *dev;
136 	struct cdev		 *alias_dev;
137 	struct task		  add_physpath_task;
138 	struct task		  shutdown_kqueue_task;
139 	struct selinfo		  read_select;
140 	TAILQ_HEAD(, pass_io_req) incoming_queue;
141 	TAILQ_HEAD(, pass_io_req) active_queue;
142 	TAILQ_HEAD(, pass_io_req) abandoned_queue;
143 	TAILQ_HEAD(, pass_io_req) done_queue;
144 	struct cam_periph	 *periph;
145 	char			  zone_name[12];
146 	char			  io_zone_name[12];
147 	uma_zone_t		  pass_zone;
148 	uma_zone_t		  pass_io_zone;
149 	size_t			  io_zone_size;
150 };
151 
152 static	d_open_t	passopen;
153 static	d_close_t	passclose;
154 static	d_ioctl_t	passioctl;
155 static	d_ioctl_t	passdoioctl;
156 static	d_poll_t	passpoll;
157 static	d_kqfilter_t	passkqfilter;
158 static	void		passreadfiltdetach(struct knote *kn);
159 static	int		passreadfilt(struct knote *kn, long hint);
160 
161 static	periph_init_t	passinit;
162 static	periph_ctor_t	passregister;
163 static	periph_oninv_t	passoninvalidate;
164 static	periph_dtor_t	passcleanup;
165 static	periph_start_t	passstart;
166 static	void		pass_shutdown_kqueue(void *context, int pending);
167 static	void		pass_add_physpath(void *context, int pending);
168 static	void		passasync(void *callback_arg, u_int32_t code,
169 				  struct cam_path *path, void *arg);
170 static	void		passdone(struct cam_periph *periph,
171 				 union ccb *done_ccb);
172 static	int		passcreatezone(struct cam_periph *periph);
173 static	void		passiocleanup(struct pass_softc *softc,
174 				      struct pass_io_req *io_req);
175 static	int		passcopysglist(struct cam_periph *periph,
176 				       struct pass_io_req *io_req,
177 				       ccb_flags direction);
178 static	int		passmemsetup(struct cam_periph *periph,
179 				     struct pass_io_req *io_req);
180 static	int		passmemdone(struct cam_periph *periph,
181 				    struct pass_io_req *io_req);
182 static	int		passerror(union ccb *ccb, u_int32_t cam_flags,
183 				  u_int32_t sense_flags);
184 static 	int		passsendccb(struct cam_periph *periph, union ccb *ccb,
185 				    union ccb *inccb);
186 
187 static struct periph_driver passdriver =
188 {
189 	passinit, "pass",
190 	TAILQ_HEAD_INITIALIZER(passdriver.units), /* generation */ 0
191 };
192 
193 PERIPHDRIVER_DECLARE(pass, passdriver);
194 
195 static struct cdevsw pass_cdevsw = {
196 	.d_version =	D_VERSION,
197 	.d_flags =	D_TRACKCLOSE,
198 	.d_open =	passopen,
199 	.d_close =	passclose,
200 	.d_ioctl =	passioctl,
201 	.d_poll = 	passpoll,
202 	.d_kqfilter = 	passkqfilter,
203 	.d_name =	"pass",
204 };
205 
206 static struct filterops passread_filtops = {
207 	.f_isfd	=	1,
208 	.f_detach =	passreadfiltdetach,
209 	.f_event =	passreadfilt
210 };
211 
212 static MALLOC_DEFINE(M_SCSIPASS, "scsi_pass", "scsi passthrough buffers");
213 
214 static void
215 passinit(void)
216 {
217 	cam_status status;
218 
219 	/*
220 	 * Install a global async callback.  This callback will
221 	 * receive async callbacks like "new device found".
222 	 */
223 	status = xpt_register_async(AC_FOUND_DEVICE, passasync, NULL, NULL);
224 
225 	if (status != CAM_REQ_CMP) {
226 		printf("pass: Failed to attach master async callback "
227 		       "due to status 0x%x!\n", status);
228 	}
229 
230 }
231 
232 static void
233 passrejectios(struct cam_periph *periph)
234 {
235 	struct pass_io_req *io_req, *io_req2;
236 	struct pass_softc *softc;
237 
238 	softc = (struct pass_softc *)periph->softc;
239 
240 	/*
241 	 * The user can no longer get status for I/O on the done queue, so
242 	 * clean up all outstanding I/O on the done queue.
243 	 */
244 	TAILQ_FOREACH_SAFE(io_req, &softc->done_queue, links, io_req2) {
245 		TAILQ_REMOVE(&softc->done_queue, io_req, links);
246 		passiocleanup(softc, io_req);
247 		uma_zfree(softc->pass_zone, io_req);
248 	}
249 
250 	/*
251 	 * The underlying device is gone, so we can't issue these I/Os.
252 	 * The devfs node has been shut down, so we can't return status to
253 	 * the user.  Free any I/O left on the incoming queue.
254 	 */
255 	TAILQ_FOREACH_SAFE(io_req, &softc->incoming_queue, links, io_req2) {
256 		TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
257 		passiocleanup(softc, io_req);
258 		uma_zfree(softc->pass_zone, io_req);
259 	}
260 
261 	/*
262 	 * Normally we would put I/Os on the abandoned queue and acquire a
263 	 * reference when we saw the final close.  But, the device went
264 	 * away and devfs may have moved everything off to deadfs by the
265 	 * time the I/O done callback is called; as a result, we won't see
266 	 * any more closes.  So, if we have any active I/Os, we need to put
267 	 * them on the abandoned queue.  When the abandoned queue is empty,
268 	 * we'll release the remaining reference (see below) to the peripheral.
269 	 */
270 	TAILQ_FOREACH_SAFE(io_req, &softc->active_queue, links, io_req2) {
271 		TAILQ_REMOVE(&softc->active_queue, io_req, links);
272 		io_req->flags |= PASS_IO_ABANDONED;
273 		TAILQ_INSERT_TAIL(&softc->abandoned_queue, io_req, links);
274 	}
275 
276 	/*
277 	 * If we put any I/O on the abandoned queue, acquire a reference.
278 	 */
279 	if ((!TAILQ_EMPTY(&softc->abandoned_queue))
280 	 && ((softc->flags & PASS_FLAG_ABANDONED_REF_SET) == 0)) {
281 		cam_periph_doacquire(periph);
282 		softc->flags |= PASS_FLAG_ABANDONED_REF_SET;
283 	}
284 }
285 
286 static void
287 passdevgonecb(void *arg)
288 {
289 	struct cam_periph *periph;
290 	struct mtx *mtx;
291 	struct pass_softc *softc;
292 	int i;
293 
294 	periph = (struct cam_periph *)arg;
295 	mtx = cam_periph_mtx(periph);
296 	mtx_lock(mtx);
297 
298 	softc = (struct pass_softc *)periph->softc;
299 	KASSERT(softc->open_count >= 0, ("Negative open count %d",
300 		softc->open_count));
301 
302 	/*
303 	 * When we get this callback, we will get no more close calls from
304 	 * devfs.  So if we have any dangling opens, we need to release the
305 	 * reference held for that particular context.
306 	 */
307 	for (i = 0; i < softc->open_count; i++)
308 		cam_periph_release_locked(periph);
309 
310 	softc->open_count = 0;
311 
312 	/*
313 	 * Release the reference held for the device node, it is gone now.
314 	 * Accordingly, inform all queued I/Os of their fate.
315 	 */
316 	cam_periph_release_locked(periph);
317 	passrejectios(periph);
318 
319 	/*
320 	 * We reference the SIM lock directly here, instead of using
321 	 * cam_periph_unlock().  The reason is that the final call to
322 	 * cam_periph_release_locked() above could result in the periph
323 	 * getting freed.  If that is the case, dereferencing the periph
324 	 * with a cam_periph_unlock() call would cause a page fault.
325 	 */
326 	mtx_unlock(mtx);
327 
328 	/*
329 	 * We have to remove our kqueue context from a thread because it
330 	 * may sleep.  It would be nice if we could get a callback from
331 	 * kqueue when it is done cleaning up resources.
332 	 */
333 	taskqueue_enqueue(taskqueue_thread, &softc->shutdown_kqueue_task);
334 }
335 
336 static void
337 passoninvalidate(struct cam_periph *periph)
338 {
339 	struct pass_softc *softc;
340 
341 	softc = (struct pass_softc *)periph->softc;
342 
343 	/*
344 	 * De-register any async callbacks.
345 	 */
346 	xpt_register_async(0, passasync, periph, periph->path);
347 
348 	softc->flags |= PASS_FLAG_INVALID;
349 
350 	/*
351 	 * Tell devfs this device has gone away, and ask for a callback
352 	 * when it has cleaned up its state.
353 	 */
354 	destroy_dev_sched_cb(softc->dev, passdevgonecb, periph);
355 }
356 
357 static void
358 passcleanup(struct cam_periph *periph)
359 {
360 	struct pass_softc *softc;
361 
362 	softc = (struct pass_softc *)periph->softc;
363 
364 	cam_periph_assert(periph, MA_OWNED);
365 	KASSERT(TAILQ_EMPTY(&softc->active_queue),
366 		("%s called when there are commands on the active queue!\n",
367 		__func__));
368 	KASSERT(TAILQ_EMPTY(&softc->abandoned_queue),
369 		("%s called when there are commands on the abandoned queue!\n",
370 		__func__));
371 	KASSERT(TAILQ_EMPTY(&softc->incoming_queue),
372 		("%s called when there are commands on the incoming queue!\n",
373 		__func__));
374 	KASSERT(TAILQ_EMPTY(&softc->done_queue),
375 		("%s called when there are commands on the done queue!\n",
376 		__func__));
377 
378 	devstat_remove_entry(softc->device_stats);
379 
380 	cam_periph_unlock(periph);
381 
382 	/*
383 	 * We call taskqueue_drain() for the physpath task to make sure it
384 	 * is complete.  We drop the lock because this can potentially
385 	 * sleep.  XXX KDM that is bad.  Need a way to get a callback when
386 	 * a taskqueue is drained.
387 	 *
388  	 * Note that we don't drain the kqueue shutdown task queue.  This
389 	 * is because we hold a reference on the periph for kqueue, and
390 	 * release that reference from the kqueue shutdown task queue.  So
391 	 * we cannot come into this routine unless we've released that
392 	 * reference.  Also, because that could be the last reference, we
393 	 * could be called from the cam_periph_release() call in
394 	 * pass_shutdown_kqueue().  In that case, the taskqueue_drain()
395 	 * would deadlock.  It would be preferable if we had a way to
396 	 * get a callback when a taskqueue is done.
397 	 */
398 	taskqueue_drain(taskqueue_thread, &softc->add_physpath_task);
399 
400 	cam_periph_lock(periph);
401 
402 	free(softc, M_DEVBUF);
403 }
404 
405 static void
406 pass_shutdown_kqueue(void *context, int pending)
407 {
408 	struct cam_periph *periph;
409 	struct pass_softc *softc;
410 
411 	periph = context;
412 	softc = periph->softc;
413 
414 	knlist_clear(&softc->read_select.si_note, /*is_locked*/ 0);
415 	knlist_destroy(&softc->read_select.si_note);
416 
417 	/*
418 	 * Release the reference we held for kqueue.
419 	 */
420 	cam_periph_release(periph);
421 }
422 
423 static void
424 pass_add_physpath(void *context, int pending)
425 {
426 	struct cam_periph *periph;
427 	struct pass_softc *softc;
428 	struct mtx *mtx;
429 	char *physpath;
430 
431 	/*
432 	 * If we have one, create a devfs alias for our
433 	 * physical path.
434 	 */
435 	periph = context;
436 	softc = periph->softc;
437 	physpath = malloc(MAXPATHLEN, M_DEVBUF, M_WAITOK);
438 	mtx = cam_periph_mtx(periph);
439 	mtx_lock(mtx);
440 
441 	if (periph->flags & CAM_PERIPH_INVALID)
442 		goto out;
443 
444 	if (xpt_getattr(physpath, MAXPATHLEN,
445 			"GEOM::physpath", periph->path) == 0
446 	 && strlen(physpath) != 0) {
447 
448 		mtx_unlock(mtx);
449 		make_dev_physpath_alias(MAKEDEV_WAITOK, &softc->alias_dev,
450 					softc->dev, softc->alias_dev, physpath);
451 		mtx_lock(mtx);
452 	}
453 
454 out:
455 	/*
456 	 * Now that we've made our alias, we no longer have to have a
457 	 * reference to the device.
458 	 */
459 	if ((softc->flags & PASS_FLAG_INITIAL_PHYSPATH) == 0)
460 		softc->flags |= PASS_FLAG_INITIAL_PHYSPATH;
461 
462 	/*
463 	 * We always acquire a reference to the periph before queueing this
464 	 * task queue function, so it won't go away before we run.
465 	 */
466 	while (pending-- > 0)
467 		cam_periph_release_locked(periph);
468 	mtx_unlock(mtx);
469 
470 	free(physpath, M_DEVBUF);
471 }
472 
473 static void
474 passasync(void *callback_arg, u_int32_t code,
475 	  struct cam_path *path, void *arg)
476 {
477 	struct cam_periph *periph;
478 
479 	periph = (struct cam_periph *)callback_arg;
480 
481 	switch (code) {
482 	case AC_FOUND_DEVICE:
483 	{
484 		struct ccb_getdev *cgd;
485 		cam_status status;
486 
487 		cgd = (struct ccb_getdev *)arg;
488 		if (cgd == NULL)
489 			break;
490 
491 		/*
492 		 * Allocate a peripheral instance for
493 		 * this device and start the probe
494 		 * process.
495 		 */
496 		status = cam_periph_alloc(passregister, passoninvalidate,
497 					  passcleanup, passstart, "pass",
498 					  CAM_PERIPH_BIO, path,
499 					  passasync, AC_FOUND_DEVICE, cgd);
500 
501 		if (status != CAM_REQ_CMP
502 		 && status != CAM_REQ_INPROG) {
503 			const struct cam_status_entry *entry;
504 
505 			entry = cam_fetch_status_entry(status);
506 
507 			printf("passasync: Unable to attach new device "
508 			       "due to status %#x: %s\n", status, entry ?
509 			       entry->status_text : "Unknown");
510 		}
511 
512 		break;
513 	}
514 	case AC_ADVINFO_CHANGED:
515 	{
516 		uintptr_t buftype;
517 
518 		buftype = (uintptr_t)arg;
519 		if (buftype == CDAI_TYPE_PHYS_PATH) {
520 			struct pass_softc *softc;
521 			cam_status status;
522 
523 			softc = (struct pass_softc *)periph->softc;
524 			/*
525 			 * Acquire a reference to the periph before we
526 			 * start the taskqueue, so that we don't run into
527 			 * a situation where the periph goes away before
528 			 * the task queue has a chance to run.
529 			 */
530 			status = cam_periph_acquire(periph);
531 			if (status != CAM_REQ_CMP)
532 				break;
533 
534 			taskqueue_enqueue(taskqueue_thread,
535 					  &softc->add_physpath_task);
536 		}
537 		break;
538 	}
539 	default:
540 		cam_periph_async(periph, code, path, arg);
541 		break;
542 	}
543 }
544 
545 static cam_status
546 passregister(struct cam_periph *periph, void *arg)
547 {
548 	struct pass_softc *softc;
549 	struct ccb_getdev *cgd;
550 	struct ccb_pathinq cpi;
551 	struct make_dev_args args;
552 	int error, no_tags;
553 
554 	cgd = (struct ccb_getdev *)arg;
555 	if (cgd == NULL) {
556 		printf("%s: no getdev CCB, can't register device\n", __func__);
557 		return(CAM_REQ_CMP_ERR);
558 	}
559 
560 	softc = (struct pass_softc *)malloc(sizeof(*softc),
561 					    M_DEVBUF, M_NOWAIT);
562 
563 	if (softc == NULL) {
564 		printf("%s: Unable to probe new device. "
565 		       "Unable to allocate softc\n", __func__);
566 		return(CAM_REQ_CMP_ERR);
567 	}
568 
569 	bzero(softc, sizeof(*softc));
570 	softc->state = PASS_STATE_NORMAL;
571 	if (cgd->protocol == PROTO_SCSI || cgd->protocol == PROTO_ATAPI)
572 		softc->pd_type = SID_TYPE(&cgd->inq_data);
573 	else if (cgd->protocol == PROTO_SATAPM)
574 		softc->pd_type = T_ENCLOSURE;
575 	else
576 		softc->pd_type = T_DIRECT;
577 
578 	periph->softc = softc;
579 	softc->periph = periph;
580 	TAILQ_INIT(&softc->incoming_queue);
581 	TAILQ_INIT(&softc->active_queue);
582 	TAILQ_INIT(&softc->abandoned_queue);
583 	TAILQ_INIT(&softc->done_queue);
584 	snprintf(softc->zone_name, sizeof(softc->zone_name), "%s%d",
585 		 periph->periph_name, periph->unit_number);
586 	snprintf(softc->io_zone_name, sizeof(softc->io_zone_name), "%s%dIO",
587 		 periph->periph_name, periph->unit_number);
588 	softc->io_zone_size = MAXPHYS;
589 	knlist_init_mtx(&softc->read_select.si_note, cam_periph_mtx(periph));
590 
591 	bzero(&cpi, sizeof(cpi));
592 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
593 	cpi.ccb_h.func_code = XPT_PATH_INQ;
594 	xpt_action((union ccb *)&cpi);
595 
596 	if (cpi.maxio == 0)
597 		softc->maxio = DFLTPHYS;	/* traditional default */
598 	else if (cpi.maxio > MAXPHYS)
599 		softc->maxio = MAXPHYS;		/* for safety */
600 	else
601 		softc->maxio = cpi.maxio;	/* real value */
602 
603 	if (cpi.hba_misc & PIM_UNMAPPED)
604 		softc->flags |= PASS_FLAG_UNMAPPED_CAPABLE;
605 
606 	/*
607 	 * We pass in 0 for a blocksize, since we don't
608 	 * know what the blocksize of this device is, if
609 	 * it even has a blocksize.
610 	 */
611 	cam_periph_unlock(periph);
612 	no_tags = (cgd->inq_data.flags & SID_CmdQue) == 0;
613 	softc->device_stats = devstat_new_entry("pass",
614 			  periph->unit_number, 0,
615 			  DEVSTAT_NO_BLOCKSIZE
616 			  | (no_tags ? DEVSTAT_NO_ORDERED_TAGS : 0),
617 			  softc->pd_type |
618 			  XPORT_DEVSTAT_TYPE(cpi.transport) |
619 			  DEVSTAT_TYPE_PASS,
620 			  DEVSTAT_PRIORITY_PASS);
621 
622 	/*
623 	 * Initialize the taskqueue handler for shutting down kqueue.
624 	 */
625 	TASK_INIT(&softc->shutdown_kqueue_task, /*priority*/ 0,
626 		  pass_shutdown_kqueue, periph);
627 
628 	/*
629 	 * Acquire a reference to the periph that we can release once we've
630 	 * cleaned up the kqueue.
631 	 */
632 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
633 		xpt_print(periph->path, "%s: lost periph during "
634 			  "registration!\n", __func__);
635 		cam_periph_lock(periph);
636 		return (CAM_REQ_CMP_ERR);
637 	}
638 
639 	/*
640 	 * Acquire a reference to the periph before we create the devfs
641 	 * instance for it.  We'll release this reference once the devfs
642 	 * instance has been freed.
643 	 */
644 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
645 		xpt_print(periph->path, "%s: lost periph during "
646 			  "registration!\n", __func__);
647 		cam_periph_lock(periph);
648 		return (CAM_REQ_CMP_ERR);
649 	}
650 
651 	/* Register the device */
652 	make_dev_args_init(&args);
653 	args.mda_devsw = &pass_cdevsw;
654 	args.mda_unit = periph->unit_number;
655 	args.mda_uid = UID_ROOT;
656 	args.mda_gid = GID_OPERATOR;
657 	args.mda_mode = 0600;
658 	args.mda_si_drv1 = periph;
659 	error = make_dev_s(&args, &softc->dev, "%s%d", periph->periph_name,
660 	    periph->unit_number);
661 	if (error != 0) {
662 		cam_periph_lock(periph);
663 		cam_periph_release_locked(periph);
664 		return (CAM_REQ_CMP_ERR);
665 	}
666 
667 	/*
668 	 * Hold a reference to the periph before we create the physical
669 	 * path alias so it can't go away.
670 	 */
671 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
672 		xpt_print(periph->path, "%s: lost periph during "
673 			  "registration!\n", __func__);
674 		cam_periph_lock(periph);
675 		return (CAM_REQ_CMP_ERR);
676 	}
677 
678 	cam_periph_lock(periph);
679 
680 	TASK_INIT(&softc->add_physpath_task, /*priority*/0,
681 		  pass_add_physpath, periph);
682 
683 	/*
684 	 * See if physical path information is already available.
685 	 */
686 	taskqueue_enqueue(taskqueue_thread, &softc->add_physpath_task);
687 
688 	/*
689 	 * Add an async callback so that we get notified if
690 	 * this device goes away or its physical path
691 	 * (stored in the advanced info data of the EDT) has
692 	 * changed.
693 	 */
694 	xpt_register_async(AC_LOST_DEVICE | AC_ADVINFO_CHANGED,
695 			   passasync, periph, periph->path);
696 
697 	if (bootverbose)
698 		xpt_announce_periph(periph, NULL);
699 
700 	return(CAM_REQ_CMP);
701 }
702 
703 static int
704 passopen(struct cdev *dev, int flags, int fmt, struct thread *td)
705 {
706 	struct cam_periph *periph;
707 	struct pass_softc *softc;
708 	int error;
709 
710 	periph = (struct cam_periph *)dev->si_drv1;
711 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
712 		return (ENXIO);
713 
714 	cam_periph_lock(periph);
715 
716 	softc = (struct pass_softc *)periph->softc;
717 
718 	if (softc->flags & PASS_FLAG_INVALID) {
719 		cam_periph_release_locked(periph);
720 		cam_periph_unlock(periph);
721 		return(ENXIO);
722 	}
723 
724 	/*
725 	 * Don't allow access when we're running at a high securelevel.
726 	 */
727 	error = securelevel_gt(td->td_ucred, 1);
728 	if (error) {
729 		cam_periph_release_locked(periph);
730 		cam_periph_unlock(periph);
731 		return(error);
732 	}
733 
734 	/*
735 	 * Only allow read-write access.
736 	 */
737 	if (((flags & FWRITE) == 0) || ((flags & FREAD) == 0)) {
738 		cam_periph_release_locked(periph);
739 		cam_periph_unlock(periph);
740 		return(EPERM);
741 	}
742 
743 	/*
744 	 * We don't allow nonblocking access.
745 	 */
746 	if ((flags & O_NONBLOCK) != 0) {
747 		xpt_print(periph->path, "can't do nonblocking access\n");
748 		cam_periph_release_locked(periph);
749 		cam_periph_unlock(periph);
750 		return(EINVAL);
751 	}
752 
753 	softc->open_count++;
754 
755 	cam_periph_unlock(periph);
756 
757 	return (error);
758 }
759 
760 static int
761 passclose(struct cdev *dev, int flag, int fmt, struct thread *td)
762 {
763 	struct 	cam_periph *periph;
764 	struct  pass_softc *softc;
765 	struct mtx *mtx;
766 
767 	periph = (struct cam_periph *)dev->si_drv1;
768 	mtx = cam_periph_mtx(periph);
769 	mtx_lock(mtx);
770 
771 	softc = periph->softc;
772 	softc->open_count--;
773 
774 	if (softc->open_count == 0) {
775 		struct pass_io_req *io_req, *io_req2;
776 
777 		TAILQ_FOREACH_SAFE(io_req, &softc->done_queue, links, io_req2) {
778 			TAILQ_REMOVE(&softc->done_queue, io_req, links);
779 			passiocleanup(softc, io_req);
780 			uma_zfree(softc->pass_zone, io_req);
781 		}
782 
783 		TAILQ_FOREACH_SAFE(io_req, &softc->incoming_queue, links,
784 				   io_req2) {
785 			TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
786 			passiocleanup(softc, io_req);
787 			uma_zfree(softc->pass_zone, io_req);
788 		}
789 
790 		/*
791 		 * If there are any active I/Os, we need to forcibly acquire a
792 		 * reference to the peripheral so that we don't go away
793 		 * before they complete.  We'll release the reference when
794 		 * the abandoned queue is empty.
795 		 */
796 		io_req = TAILQ_FIRST(&softc->active_queue);
797 		if ((io_req != NULL)
798 		 && (softc->flags & PASS_FLAG_ABANDONED_REF_SET) == 0) {
799 			cam_periph_doacquire(periph);
800 			softc->flags |= PASS_FLAG_ABANDONED_REF_SET;
801 		}
802 
803 		/*
804 		 * Since the I/O in the active queue is not under our
805 		 * control, just set a flag so that we can clean it up when
806 		 * it completes and put it on the abandoned queue.  This
807 		 * will prevent our sending spurious completions in the
808 		 * event that the device is opened again before these I/Os
809 		 * complete.
810 		 */
811 		TAILQ_FOREACH_SAFE(io_req, &softc->active_queue, links,
812 				   io_req2) {
813 			TAILQ_REMOVE(&softc->active_queue, io_req, links);
814 			io_req->flags |= PASS_IO_ABANDONED;
815 			TAILQ_INSERT_TAIL(&softc->abandoned_queue, io_req,
816 					  links);
817 		}
818 	}
819 
820 	cam_periph_release_locked(periph);
821 
822 	/*
823 	 * We reference the lock directly here, instead of using
824 	 * cam_periph_unlock().  The reason is that the call to
825 	 * cam_periph_release_locked() above could result in the periph
826 	 * getting freed.  If that is the case, dereferencing the periph
827 	 * with a cam_periph_unlock() call would cause a page fault.
828 	 *
829 	 * cam_periph_release() avoids this problem using the same method,
830 	 * but we're manually acquiring and dropping the lock here to
831 	 * protect the open count and avoid another lock acquisition and
832 	 * release.
833 	 */
834 	mtx_unlock(mtx);
835 
836 	return (0);
837 }
838 
839 
840 static void
841 passstart(struct cam_periph *periph, union ccb *start_ccb)
842 {
843 	struct pass_softc *softc;
844 
845 	softc = (struct pass_softc *)periph->softc;
846 
847 	switch (softc->state) {
848 	case PASS_STATE_NORMAL: {
849 		struct pass_io_req *io_req;
850 
851 		/*
852 		 * Check for any queued I/O requests that require an
853 		 * allocated slot.
854 		 */
855 		io_req = TAILQ_FIRST(&softc->incoming_queue);
856 		if (io_req == NULL) {
857 			xpt_release_ccb(start_ccb);
858 			break;
859 		}
860 		TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
861 		TAILQ_INSERT_TAIL(&softc->active_queue, io_req, links);
862 		/*
863 		 * Merge the user's CCB into the allocated CCB.
864 		 */
865 		xpt_merge_ccb(start_ccb, &io_req->ccb);
866 		start_ccb->ccb_h.ccb_type = PASS_CCB_QUEUED_IO;
867 		start_ccb->ccb_h.ccb_ioreq = io_req;
868 		start_ccb->ccb_h.cbfcnp = passdone;
869 		io_req->alloced_ccb = start_ccb;
870 		binuptime(&io_req->start_time);
871 		devstat_start_transaction(softc->device_stats,
872 					  &io_req->start_time);
873 
874 		xpt_action(start_ccb);
875 
876 		/*
877 		 * If we have any more I/O waiting, schedule ourselves again.
878 		 */
879 		if (!TAILQ_EMPTY(&softc->incoming_queue))
880 			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
881 		break;
882 	}
883 	default:
884 		break;
885 	}
886 }
887 
888 static void
889 passdone(struct cam_periph *periph, union ccb *done_ccb)
890 {
891 	struct pass_softc *softc;
892 	struct ccb_scsiio *csio;
893 
894 	softc = (struct pass_softc *)periph->softc;
895 
896 	cam_periph_assert(periph, MA_OWNED);
897 
898 	csio = &done_ccb->csio;
899 	switch (csio->ccb_h.ccb_type) {
900 	case PASS_CCB_QUEUED_IO: {
901 		struct pass_io_req *io_req;
902 
903 		io_req = done_ccb->ccb_h.ccb_ioreq;
904 #if 0
905 		xpt_print(periph->path, "%s: called for user CCB %p\n",
906 			  __func__, io_req->user_ccb_ptr);
907 #endif
908 		if (((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
909 		 && (done_ccb->ccb_h.flags & CAM_PASS_ERR_RECOVER)
910 		 && ((io_req->flags & PASS_IO_ABANDONED) == 0)) {
911 			int error;
912 
913 			error = passerror(done_ccb, CAM_RETRY_SELTO,
914 					  SF_RETRY_UA | SF_NO_PRINT);
915 
916 			if (error == ERESTART) {
917 				/*
918 				 * A retry was scheduled, so
919  				 * just return.
920 				 */
921 				return;
922 			}
923 		}
924 
925 		/*
926 		 * Copy the allocated CCB contents back to the malloced CCB
927 		 * so we can give status back to the user when he requests it.
928 		 */
929 		bcopy(done_ccb, &io_req->ccb, sizeof(*done_ccb));
930 
931 		/*
932 		 * Log data/transaction completion with devstat(9).
933 		 */
934 		switch (done_ccb->ccb_h.func_code) {
935 		case XPT_SCSI_IO:
936 			devstat_end_transaction(softc->device_stats,
937 			    done_ccb->csio.dxfer_len - done_ccb->csio.resid,
938 			    done_ccb->csio.tag_action & 0x3,
939 			    ((done_ccb->ccb_h.flags & CAM_DIR_MASK) ==
940 			    CAM_DIR_NONE) ? DEVSTAT_NO_DATA :
941 			    (done_ccb->ccb_h.flags & CAM_DIR_OUT) ?
942 			    DEVSTAT_WRITE : DEVSTAT_READ, NULL,
943 			    &io_req->start_time);
944 			break;
945 		case XPT_ATA_IO:
946 			devstat_end_transaction(softc->device_stats,
947 			    done_ccb->ataio.dxfer_len - done_ccb->ataio.resid,
948 			    0, /* Not used in ATA */
949 			    ((done_ccb->ccb_h.flags & CAM_DIR_MASK) ==
950 			    CAM_DIR_NONE) ? DEVSTAT_NO_DATA :
951 			    (done_ccb->ccb_h.flags & CAM_DIR_OUT) ?
952 			    DEVSTAT_WRITE : DEVSTAT_READ, NULL,
953 			    &io_req->start_time);
954 			break;
955 		case XPT_SMP_IO:
956 			/*
957 			 * XXX KDM this isn't quite right, but there isn't
958 			 * currently an easy way to represent a bidirectional
959 			 * transfer in devstat.  The only way to do it
960 			 * and have the byte counts come out right would
961 			 * mean that we would have to record two
962 			 * transactions, one for the request and one for the
963 			 * response.  For now, so that we report something,
964 			 * just treat the entire thing as a read.
965 			 */
966 			devstat_end_transaction(softc->device_stats,
967 			    done_ccb->smpio.smp_request_len +
968 			    done_ccb->smpio.smp_response_len,
969 			    DEVSTAT_TAG_SIMPLE, DEVSTAT_READ, NULL,
970 			    &io_req->start_time);
971 			break;
972 		default:
973 			devstat_end_transaction(softc->device_stats, 0,
974 			    DEVSTAT_TAG_NONE, DEVSTAT_NO_DATA, NULL,
975 			    &io_req->start_time);
976 			break;
977 		}
978 
979 		/*
980 		 * In the normal case, take the completed I/O off of the
981 		 * active queue and put it on the done queue.  Notitfy the
982 		 * user that we have a completed I/O.
983 		 */
984 		if ((io_req->flags & PASS_IO_ABANDONED) == 0) {
985 			TAILQ_REMOVE(&softc->active_queue, io_req, links);
986 			TAILQ_INSERT_TAIL(&softc->done_queue, io_req, links);
987 			selwakeuppri(&softc->read_select, PRIBIO);
988 			KNOTE_LOCKED(&softc->read_select.si_note, 0);
989 		} else {
990 			/*
991 			 * In the case of an abandoned I/O (final close
992 			 * without fetching the I/O), take it off of the
993 			 * abandoned queue and free it.
994 			 */
995 			TAILQ_REMOVE(&softc->abandoned_queue, io_req, links);
996 			passiocleanup(softc, io_req);
997 			uma_zfree(softc->pass_zone, io_req);
998 
999 			/*
1000 			 * Release the done_ccb here, since we may wind up
1001 			 * freeing the peripheral when we decrement the
1002 			 * reference count below.
1003 			 */
1004 			xpt_release_ccb(done_ccb);
1005 
1006 			/*
1007 			 * If the abandoned queue is empty, we can release
1008 			 * our reference to the periph since we won't have
1009 			 * any more completions coming.
1010 			 */
1011 			if ((TAILQ_EMPTY(&softc->abandoned_queue))
1012 			 && (softc->flags & PASS_FLAG_ABANDONED_REF_SET)) {
1013 				softc->flags &= ~PASS_FLAG_ABANDONED_REF_SET;
1014 				cam_periph_release_locked(periph);
1015 			}
1016 
1017 			/*
1018 			 * We have already released the CCB, so we can
1019 			 * return.
1020 			 */
1021 			return;
1022 		}
1023 		break;
1024 	}
1025 	}
1026 	xpt_release_ccb(done_ccb);
1027 }
1028 
1029 static int
1030 passcreatezone(struct cam_periph *periph)
1031 {
1032 	struct pass_softc *softc;
1033 	int error;
1034 
1035 	error = 0;
1036 	softc = (struct pass_softc *)periph->softc;
1037 
1038 	cam_periph_assert(periph, MA_OWNED);
1039 	KASSERT(((softc->flags & PASS_FLAG_ZONE_VALID) == 0),
1040 		("%s called when the pass(4) zone is valid!\n", __func__));
1041 	KASSERT((softc->pass_zone == NULL),
1042 		("%s called when the pass(4) zone is allocated!\n", __func__));
1043 
1044 	if ((softc->flags & PASS_FLAG_ZONE_INPROG) == 0) {
1045 
1046 		/*
1047 		 * We're the first context through, so we need to create
1048 		 * the pass(4) UMA zone for I/O requests.
1049 		 */
1050 		softc->flags |= PASS_FLAG_ZONE_INPROG;
1051 
1052 		/*
1053 		 * uma_zcreate() does a blocking (M_WAITOK) allocation,
1054 		 * so we cannot hold a mutex while we call it.
1055 		 */
1056 		cam_periph_unlock(periph);
1057 
1058 		softc->pass_zone = uma_zcreate(softc->zone_name,
1059 		    sizeof(struct pass_io_req), NULL, NULL, NULL, NULL,
1060 		    /*align*/ 0, /*flags*/ 0);
1061 
1062 		softc->pass_io_zone = uma_zcreate(softc->io_zone_name,
1063 		    softc->io_zone_size, NULL, NULL, NULL, NULL,
1064 		    /*align*/ 0, /*flags*/ 0);
1065 
1066 		cam_periph_lock(periph);
1067 
1068 		if ((softc->pass_zone == NULL)
1069 		 || (softc->pass_io_zone == NULL)) {
1070 			if (softc->pass_zone == NULL)
1071 				xpt_print(periph->path, "unable to allocate "
1072 				    "IO Req UMA zone\n");
1073 			else
1074 				xpt_print(periph->path, "unable to allocate "
1075 				    "IO UMA zone\n");
1076 			softc->flags &= ~PASS_FLAG_ZONE_INPROG;
1077 			goto bailout;
1078 		}
1079 
1080 		/*
1081 		 * Set the flags appropriately and notify any other waiters.
1082 		 */
1083 		softc->flags &= PASS_FLAG_ZONE_INPROG;
1084 		softc->flags |= PASS_FLAG_ZONE_VALID;
1085 		wakeup(&softc->pass_zone);
1086 	} else {
1087 		/*
1088 		 * In this case, the UMA zone has not yet been created, but
1089 		 * another context is in the process of creating it.  We
1090 		 * need to sleep until the creation is either done or has
1091 		 * failed.
1092 		 */
1093 		while ((softc->flags & PASS_FLAG_ZONE_INPROG)
1094 		    && ((softc->flags & PASS_FLAG_ZONE_VALID) == 0)) {
1095 			error = msleep(&softc->pass_zone,
1096 				       cam_periph_mtx(periph), PRIBIO,
1097 				       "paszon", 0);
1098 			if (error != 0)
1099 				goto bailout;
1100 		}
1101 		/*
1102 		 * If the zone creation failed, no luck for the user.
1103 		 */
1104 		if ((softc->flags & PASS_FLAG_ZONE_VALID) == 0){
1105 			error = ENOMEM;
1106 			goto bailout;
1107 		}
1108 	}
1109 bailout:
1110 	return (error);
1111 }
1112 
1113 static void
1114 passiocleanup(struct pass_softc *softc, struct pass_io_req *io_req)
1115 {
1116 	union ccb *ccb;
1117 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1118 	int i, numbufs;
1119 
1120 	ccb = &io_req->ccb;
1121 
1122 	switch (ccb->ccb_h.func_code) {
1123 	case XPT_DEV_MATCH:
1124 		numbufs = min(io_req->num_bufs, 2);
1125 
1126 		if (numbufs == 1) {
1127 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1128 		} else {
1129 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1130 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1131 		}
1132 		break;
1133 	case XPT_SCSI_IO:
1134 	case XPT_CONT_TARGET_IO:
1135 		data_ptrs[0] = &ccb->csio.data_ptr;
1136 		numbufs = min(io_req->num_bufs, 1);
1137 		break;
1138 	case XPT_ATA_IO:
1139 		data_ptrs[0] = &ccb->ataio.data_ptr;
1140 		numbufs = min(io_req->num_bufs, 1);
1141 		break;
1142 	case XPT_SMP_IO:
1143 		numbufs = min(io_req->num_bufs, 2);
1144 		data_ptrs[0] = &ccb->smpio.smp_request;
1145 		data_ptrs[1] = &ccb->smpio.smp_response;
1146 		break;
1147 	case XPT_DEV_ADVINFO:
1148 		numbufs = min(io_req->num_bufs, 1);
1149 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1150 		break;
1151 	case XPT_NVME_IO:
1152 	case XPT_NVME_ADMIN:
1153 		data_ptrs[0] = &ccb->nvmeio.data_ptr;
1154 		numbufs = min(io_req->num_bufs, 1);
1155 		break;
1156 	default:
1157 		/* allow ourselves to be swapped once again */
1158 		return;
1159 		break; /* NOTREACHED */
1160 	}
1161 
1162 	if (io_req->flags & PASS_IO_USER_SEG_MALLOC) {
1163 		free(io_req->user_segptr, M_SCSIPASS);
1164 		io_req->user_segptr = NULL;
1165 	}
1166 
1167 	/*
1168 	 * We only want to free memory we malloced.
1169 	 */
1170 	if (io_req->data_flags == CAM_DATA_VADDR) {
1171 		for (i = 0; i < io_req->num_bufs; i++) {
1172 			if (io_req->kern_bufs[i] == NULL)
1173 				continue;
1174 
1175 			free(io_req->kern_bufs[i], M_SCSIPASS);
1176 			io_req->kern_bufs[i] = NULL;
1177 		}
1178 	} else if (io_req->data_flags == CAM_DATA_SG) {
1179 		for (i = 0; i < io_req->num_kern_segs; i++) {
1180 			if ((uint8_t *)(uintptr_t)
1181 			    io_req->kern_segptr[i].ds_addr == NULL)
1182 				continue;
1183 
1184 			uma_zfree(softc->pass_io_zone, (uint8_t *)(uintptr_t)
1185 			    io_req->kern_segptr[i].ds_addr);
1186 			io_req->kern_segptr[i].ds_addr = 0;
1187 		}
1188 	}
1189 
1190 	if (io_req->flags & PASS_IO_KERN_SEG_MALLOC) {
1191 		free(io_req->kern_segptr, M_SCSIPASS);
1192 		io_req->kern_segptr = NULL;
1193 	}
1194 
1195 	if (io_req->data_flags != CAM_DATA_PADDR) {
1196 		for (i = 0; i < numbufs; i++) {
1197 			/*
1198 			 * Restore the user's buffer pointers to their
1199 			 * previous values.
1200 			 */
1201 			if (io_req->user_bufs[i] != NULL)
1202 				*data_ptrs[i] = io_req->user_bufs[i];
1203 		}
1204 	}
1205 
1206 }
1207 
1208 static int
1209 passcopysglist(struct cam_periph *periph, struct pass_io_req *io_req,
1210 	       ccb_flags direction)
1211 {
1212 	bus_size_t kern_watermark, user_watermark, len_copied, len_to_copy;
1213 	bus_dma_segment_t *user_sglist, *kern_sglist;
1214 	int i, j, error;
1215 
1216 	error = 0;
1217 	kern_watermark = 0;
1218 	user_watermark = 0;
1219 	len_to_copy = 0;
1220 	len_copied = 0;
1221 	user_sglist = io_req->user_segptr;
1222 	kern_sglist = io_req->kern_segptr;
1223 
1224 	for (i = 0, j = 0; i < io_req->num_user_segs &&
1225 	     j < io_req->num_kern_segs;) {
1226 		uint8_t *user_ptr, *kern_ptr;
1227 
1228 		len_to_copy = min(user_sglist[i].ds_len -user_watermark,
1229 		    kern_sglist[j].ds_len - kern_watermark);
1230 
1231 		user_ptr = (uint8_t *)(uintptr_t)user_sglist[i].ds_addr;
1232 		user_ptr = user_ptr + user_watermark;
1233 		kern_ptr = (uint8_t *)(uintptr_t)kern_sglist[j].ds_addr;
1234 		kern_ptr = kern_ptr + kern_watermark;
1235 
1236 		user_watermark += len_to_copy;
1237 		kern_watermark += len_to_copy;
1238 
1239 		if (!useracc(user_ptr, len_to_copy,
1240 		    (direction == CAM_DIR_IN) ? VM_PROT_WRITE : VM_PROT_READ)) {
1241 			xpt_print(periph->path, "%s: unable to access user "
1242 				  "S/G list element %p len %zu\n", __func__,
1243 				  user_ptr, len_to_copy);
1244 			error = EFAULT;
1245 			goto bailout;
1246 		}
1247 
1248 		if (direction == CAM_DIR_IN) {
1249 			error = copyout(kern_ptr, user_ptr, len_to_copy);
1250 			if (error != 0) {
1251 				xpt_print(periph->path, "%s: copyout of %u "
1252 					  "bytes from %p to %p failed with "
1253 					  "error %d\n", __func__, len_to_copy,
1254 					  kern_ptr, user_ptr, error);
1255 				goto bailout;
1256 			}
1257 		} else {
1258 			error = copyin(user_ptr, kern_ptr, len_to_copy);
1259 			if (error != 0) {
1260 				xpt_print(periph->path, "%s: copyin of %u "
1261 					  "bytes from %p to %p failed with "
1262 					  "error %d\n", __func__, len_to_copy,
1263 					  user_ptr, kern_ptr, error);
1264 				goto bailout;
1265 			}
1266 		}
1267 
1268 		len_copied += len_to_copy;
1269 
1270 		if (user_sglist[i].ds_len == user_watermark) {
1271 			i++;
1272 			user_watermark = 0;
1273 		}
1274 
1275 		if (kern_sglist[j].ds_len == kern_watermark) {
1276 			j++;
1277 			kern_watermark = 0;
1278 		}
1279 	}
1280 
1281 bailout:
1282 
1283 	return (error);
1284 }
1285 
1286 static int
1287 passmemsetup(struct cam_periph *periph, struct pass_io_req *io_req)
1288 {
1289 	union ccb *ccb;
1290 	struct pass_softc *softc;
1291 	int numbufs, i;
1292 	uint8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1293 	uint32_t lengths[CAM_PERIPH_MAXMAPS];
1294 	uint32_t dirs[CAM_PERIPH_MAXMAPS];
1295 	uint32_t num_segs;
1296 	uint16_t *seg_cnt_ptr;
1297 	size_t maxmap;
1298 	int error;
1299 
1300 	cam_periph_assert(periph, MA_NOTOWNED);
1301 
1302 	softc = periph->softc;
1303 
1304 	error = 0;
1305 	ccb = &io_req->ccb;
1306 	maxmap = 0;
1307 	num_segs = 0;
1308 	seg_cnt_ptr = NULL;
1309 
1310 	switch(ccb->ccb_h.func_code) {
1311 	case XPT_DEV_MATCH:
1312 		if (ccb->cdm.match_buf_len == 0) {
1313 			printf("%s: invalid match buffer length 0\n", __func__);
1314 			return(EINVAL);
1315 		}
1316 		if (ccb->cdm.pattern_buf_len > 0) {
1317 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1318 			lengths[0] = ccb->cdm.pattern_buf_len;
1319 			dirs[0] = CAM_DIR_OUT;
1320 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1321 			lengths[1] = ccb->cdm.match_buf_len;
1322 			dirs[1] = CAM_DIR_IN;
1323 			numbufs = 2;
1324 		} else {
1325 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1326 			lengths[0] = ccb->cdm.match_buf_len;
1327 			dirs[0] = CAM_DIR_IN;
1328 			numbufs = 1;
1329 		}
1330 		io_req->data_flags = CAM_DATA_VADDR;
1331 		break;
1332 	case XPT_SCSI_IO:
1333 	case XPT_CONT_TARGET_IO:
1334 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
1335 			return(0);
1336 
1337 		/*
1338 		 * The user shouldn't be able to supply a bio.
1339 		 */
1340 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) == CAM_DATA_BIO)
1341 			return (EINVAL);
1342 
1343 		io_req->data_flags = ccb->ccb_h.flags & CAM_DATA_MASK;
1344 
1345 		data_ptrs[0] = &ccb->csio.data_ptr;
1346 		lengths[0] = ccb->csio.dxfer_len;
1347 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1348 		num_segs = ccb->csio.sglist_cnt;
1349 		seg_cnt_ptr = &ccb->csio.sglist_cnt;
1350 		numbufs = 1;
1351 		maxmap = softc->maxio;
1352 		break;
1353 	case XPT_ATA_IO:
1354 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
1355 			return(0);
1356 
1357 		/*
1358 		 * We only support a single virtual address for ATA I/O.
1359 		 */
1360 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
1361 			return (EINVAL);
1362 
1363 		io_req->data_flags = CAM_DATA_VADDR;
1364 
1365 		data_ptrs[0] = &ccb->ataio.data_ptr;
1366 		lengths[0] = ccb->ataio.dxfer_len;
1367 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1368 		numbufs = 1;
1369 		maxmap = softc->maxio;
1370 		break;
1371 	case XPT_SMP_IO:
1372 		io_req->data_flags = CAM_DATA_VADDR;
1373 
1374 		data_ptrs[0] = &ccb->smpio.smp_request;
1375 		lengths[0] = ccb->smpio.smp_request_len;
1376 		dirs[0] = CAM_DIR_OUT;
1377 		data_ptrs[1] = &ccb->smpio.smp_response;
1378 		lengths[1] = ccb->smpio.smp_response_len;
1379 		dirs[1] = CAM_DIR_IN;
1380 		numbufs = 2;
1381 		maxmap = softc->maxio;
1382 		break;
1383 	case XPT_DEV_ADVINFO:
1384 		if (ccb->cdai.bufsiz == 0)
1385 			return (0);
1386 
1387 		io_req->data_flags = CAM_DATA_VADDR;
1388 
1389 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1390 		lengths[0] = ccb->cdai.bufsiz;
1391 		dirs[0] = CAM_DIR_IN;
1392 		numbufs = 1;
1393 		break;
1394 	case XPT_NVME_ADMIN:
1395 	case XPT_NVME_IO:
1396 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
1397 			return (0);
1398 
1399 		io_req->data_flags = ccb->ccb_h.flags & CAM_DATA_MASK;
1400 
1401 		data_ptrs[0] = &ccb->nvmeio.data_ptr;
1402 		lengths[0] = ccb->nvmeio.dxfer_len;
1403 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1404 		num_segs = ccb->nvmeio.sglist_cnt;
1405 		seg_cnt_ptr = &ccb->nvmeio.sglist_cnt;
1406 		numbufs = 1;
1407 		maxmap = softc->maxio;
1408 		break;
1409 	default:
1410 		return(EINVAL);
1411 		break; /* NOTREACHED */
1412 	}
1413 
1414 	io_req->num_bufs = numbufs;
1415 
1416 	/*
1417 	 * If there is a maximum, check to make sure that the user's
1418 	 * request fits within the limit.  In general, we should only have
1419 	 * a maximum length for requests that go to hardware.  Otherwise it
1420 	 * is whatever we're able to malloc.
1421 	 */
1422 	for (i = 0; i < numbufs; i++) {
1423 		io_req->user_bufs[i] = *data_ptrs[i];
1424 		io_req->dirs[i] = dirs[i];
1425 		io_req->lengths[i] = lengths[i];
1426 
1427 		if (maxmap == 0)
1428 			continue;
1429 
1430 		if (lengths[i] <= maxmap)
1431 			continue;
1432 
1433 		xpt_print(periph->path, "%s: data length %u > max allowed %u "
1434 			  "bytes\n", __func__, lengths[i], maxmap);
1435 		error = EINVAL;
1436 		goto bailout;
1437 	}
1438 
1439 	switch (io_req->data_flags) {
1440 	case CAM_DATA_VADDR:
1441 		/* Map or copy the buffer into kernel address space */
1442 		for (i = 0; i < numbufs; i++) {
1443 			uint8_t *tmp_buf;
1444 
1445 			/*
1446 			 * If for some reason no length is specified, we
1447 			 * don't need to allocate anything.
1448 			 */
1449 			if (io_req->lengths[i] == 0)
1450 				continue;
1451 
1452 			/*
1453 			 * Make sure that the user's buffer is accessible
1454 			 * to that process.
1455 			 */
1456 			if (!useracc(io_req->user_bufs[i], io_req->lengths[i],
1457 			    (io_req->dirs[i] == CAM_DIR_IN) ? VM_PROT_WRITE :
1458 			     VM_PROT_READ)) {
1459 				xpt_print(periph->path, "%s: user address %p "
1460 				    "length %u is not accessible\n", __func__,
1461 				    io_req->user_bufs[i], io_req->lengths[i]);
1462 				error = EFAULT;
1463 				goto bailout;
1464 			}
1465 
1466 			tmp_buf = malloc(lengths[i], M_SCSIPASS,
1467 					 M_WAITOK | M_ZERO);
1468 			io_req->kern_bufs[i] = tmp_buf;
1469 			*data_ptrs[i] = tmp_buf;
1470 
1471 #if 0
1472 			xpt_print(periph->path, "%s: malloced %p len %u, user "
1473 				  "buffer %p, operation: %s\n", __func__,
1474 				  tmp_buf, lengths[i], io_req->user_bufs[i],
1475 				  (dirs[i] == CAM_DIR_IN) ? "read" : "write");
1476 #endif
1477 			/*
1478 			 * We only need to copy in if the user is writing.
1479 			 */
1480 			if (dirs[i] != CAM_DIR_OUT)
1481 				continue;
1482 
1483 			error = copyin(io_req->user_bufs[i],
1484 				       io_req->kern_bufs[i], lengths[i]);
1485 			if (error != 0) {
1486 				xpt_print(periph->path, "%s: copy of user "
1487 					  "buffer from %p to %p failed with "
1488 					  "error %d\n", __func__,
1489 					  io_req->user_bufs[i],
1490 					  io_req->kern_bufs[i], error);
1491 				goto bailout;
1492 			}
1493 		}
1494 		break;
1495 	case CAM_DATA_PADDR:
1496 		/* Pass down the pointer as-is */
1497 		break;
1498 	case CAM_DATA_SG: {
1499 		size_t sg_length, size_to_go, alloc_size;
1500 		uint32_t num_segs_needed;
1501 
1502 		/*
1503 		 * Copy the user S/G list in, and then copy in the
1504 		 * individual segments.
1505 		 */
1506 		/*
1507 		 * We shouldn't see this, but check just in case.
1508 		 */
1509 		if (numbufs != 1) {
1510 			xpt_print(periph->path, "%s: cannot currently handle "
1511 				  "more than one S/G list per CCB\n", __func__);
1512 			error = EINVAL;
1513 			goto bailout;
1514 		}
1515 
1516 		/*
1517 		 * We have to have at least one segment.
1518 		 */
1519 		if (num_segs == 0) {
1520 			xpt_print(periph->path, "%s: CAM_DATA_SG flag set, "
1521 				  "but sglist_cnt=0!\n", __func__);
1522 			error = EINVAL;
1523 			goto bailout;
1524 		}
1525 
1526 		/*
1527 		 * Make sure the user specified the total length and didn't
1528 		 * just leave it to us to decode the S/G list.
1529 		 */
1530 		if (lengths[0] == 0) {
1531 			xpt_print(periph->path, "%s: no dxfer_len specified, "
1532 				  "but CAM_DATA_SG flag is set!\n", __func__);
1533 			error = EINVAL;
1534 			goto bailout;
1535 		}
1536 
1537 		/*
1538 		 * We allocate buffers in io_zone_size increments for an
1539 		 * S/G list.  This will generally be MAXPHYS.
1540 		 */
1541 		if (lengths[0] <= softc->io_zone_size)
1542 			num_segs_needed = 1;
1543 		else {
1544 			num_segs_needed = lengths[0] / softc->io_zone_size;
1545 			if ((lengths[0] % softc->io_zone_size) != 0)
1546 				num_segs_needed++;
1547 		}
1548 
1549 		/* Figure out the size of the S/G list */
1550 		sg_length = num_segs * sizeof(bus_dma_segment_t);
1551 		io_req->num_user_segs = num_segs;
1552 		io_req->num_kern_segs = num_segs_needed;
1553 
1554 		/* Save the user's S/G list pointer for later restoration */
1555 		io_req->user_bufs[0] = *data_ptrs[0];
1556 
1557 		/*
1558 		 * If we have enough segments allocated by default to handle
1559 		 * the length of the user's S/G list,
1560 		 */
1561 		if (num_segs > PASS_MAX_SEGS) {
1562 			io_req->user_segptr = malloc(sizeof(bus_dma_segment_t) *
1563 			    num_segs, M_SCSIPASS, M_WAITOK | M_ZERO);
1564 			io_req->flags |= PASS_IO_USER_SEG_MALLOC;
1565 		} else
1566 			io_req->user_segptr = io_req->user_segs;
1567 
1568 		if (!useracc(*data_ptrs[0], sg_length, VM_PROT_READ)) {
1569 			xpt_print(periph->path, "%s: unable to access user "
1570 				  "S/G list at %p\n", __func__, *data_ptrs[0]);
1571 			error = EFAULT;
1572 			goto bailout;
1573 		}
1574 
1575 		error = copyin(*data_ptrs[0], io_req->user_segptr, sg_length);
1576 		if (error != 0) {
1577 			xpt_print(periph->path, "%s: copy of user S/G list "
1578 				  "from %p to %p failed with error %d\n",
1579 				  __func__, *data_ptrs[0], io_req->user_segptr,
1580 				  error);
1581 			goto bailout;
1582 		}
1583 
1584 		if (num_segs_needed > PASS_MAX_SEGS) {
1585 			io_req->kern_segptr = malloc(sizeof(bus_dma_segment_t) *
1586 			    num_segs_needed, M_SCSIPASS, M_WAITOK | M_ZERO);
1587 			io_req->flags |= PASS_IO_KERN_SEG_MALLOC;
1588 		} else {
1589 			io_req->kern_segptr = io_req->kern_segs;
1590 		}
1591 
1592 		/*
1593 		 * Allocate the kernel S/G list.
1594 		 */
1595 		for (size_to_go = lengths[0], i = 0;
1596 		     size_to_go > 0 && i < num_segs_needed;
1597 		     i++, size_to_go -= alloc_size) {
1598 			uint8_t *kern_ptr;
1599 
1600 			alloc_size = min(size_to_go, softc->io_zone_size);
1601 			kern_ptr = uma_zalloc(softc->pass_io_zone, M_WAITOK);
1602 			io_req->kern_segptr[i].ds_addr =
1603 			    (bus_addr_t)(uintptr_t)kern_ptr;
1604 			io_req->kern_segptr[i].ds_len = alloc_size;
1605 		}
1606 		if (size_to_go > 0) {
1607 			printf("%s: size_to_go = %zu, software error!\n",
1608 			       __func__, size_to_go);
1609 			error = EINVAL;
1610 			goto bailout;
1611 		}
1612 
1613 		*data_ptrs[0] = (uint8_t *)io_req->kern_segptr;
1614 		*seg_cnt_ptr = io_req->num_kern_segs;
1615 
1616 		/*
1617 		 * We only need to copy data here if the user is writing.
1618 		 */
1619 		if (dirs[0] == CAM_DIR_OUT)
1620 			error = passcopysglist(periph, io_req, dirs[0]);
1621 		break;
1622 	}
1623 	case CAM_DATA_SG_PADDR: {
1624 		size_t sg_length;
1625 
1626 		/*
1627 		 * We shouldn't see this, but check just in case.
1628 		 */
1629 		if (numbufs != 1) {
1630 			printf("%s: cannot currently handle more than one "
1631 			       "S/G list per CCB\n", __func__);
1632 			error = EINVAL;
1633 			goto bailout;
1634 		}
1635 
1636 		/*
1637 		 * We have to have at least one segment.
1638 		 */
1639 		if (num_segs == 0) {
1640 			xpt_print(periph->path, "%s: CAM_DATA_SG_PADDR flag "
1641 				  "set, but sglist_cnt=0!\n", __func__);
1642 			error = EINVAL;
1643 			goto bailout;
1644 		}
1645 
1646 		/*
1647 		 * Make sure the user specified the total length and didn't
1648 		 * just leave it to us to decode the S/G list.
1649 		 */
1650 		if (lengths[0] == 0) {
1651 			xpt_print(periph->path, "%s: no dxfer_len specified, "
1652 				  "but CAM_DATA_SG flag is set!\n", __func__);
1653 			error = EINVAL;
1654 			goto bailout;
1655 		}
1656 
1657 		/* Figure out the size of the S/G list */
1658 		sg_length = num_segs * sizeof(bus_dma_segment_t);
1659 		io_req->num_user_segs = num_segs;
1660 		io_req->num_kern_segs = io_req->num_user_segs;
1661 
1662 		/* Save the user's S/G list pointer for later restoration */
1663 		io_req->user_bufs[0] = *data_ptrs[0];
1664 
1665 		if (num_segs > PASS_MAX_SEGS) {
1666 			io_req->user_segptr = malloc(sizeof(bus_dma_segment_t) *
1667 			    num_segs, M_SCSIPASS, M_WAITOK | M_ZERO);
1668 			io_req->flags |= PASS_IO_USER_SEG_MALLOC;
1669 		} else
1670 			io_req->user_segptr = io_req->user_segs;
1671 
1672 		io_req->kern_segptr = io_req->user_segptr;
1673 
1674 		error = copyin(*data_ptrs[0], io_req->user_segptr, sg_length);
1675 		if (error != 0) {
1676 			xpt_print(periph->path, "%s: copy of user S/G list "
1677 				  "from %p to %p failed with error %d\n",
1678 				  __func__, *data_ptrs[0], io_req->user_segptr,
1679 				  error);
1680 			goto bailout;
1681 		}
1682 		break;
1683 	}
1684 	default:
1685 	case CAM_DATA_BIO:
1686 		/*
1687 		 * A user shouldn't be attaching a bio to the CCB.  It
1688 		 * isn't a user-accessible structure.
1689 		 */
1690 		error = EINVAL;
1691 		break;
1692 	}
1693 
1694 bailout:
1695 	if (error != 0)
1696 		passiocleanup(softc, io_req);
1697 
1698 	return (error);
1699 }
1700 
1701 static int
1702 passmemdone(struct cam_periph *periph, struct pass_io_req *io_req)
1703 {
1704 	struct pass_softc *softc;
1705 	union ccb *ccb;
1706 	int error;
1707 	int i;
1708 
1709 	error = 0;
1710 	softc = (struct pass_softc *)periph->softc;
1711 	ccb = &io_req->ccb;
1712 
1713 	switch (io_req->data_flags) {
1714 	case CAM_DATA_VADDR:
1715 		/*
1716 		 * Copy back to the user buffer if this was a read.
1717 		 */
1718 		for (i = 0; i < io_req->num_bufs; i++) {
1719 			if (io_req->dirs[i] != CAM_DIR_IN)
1720 				continue;
1721 
1722 			error = copyout(io_req->kern_bufs[i],
1723 			    io_req->user_bufs[i], io_req->lengths[i]);
1724 			if (error != 0) {
1725 				xpt_print(periph->path, "Unable to copy %u "
1726 					  "bytes from %p to user address %p\n",
1727 					  io_req->lengths[i],
1728 					  io_req->kern_bufs[i],
1729 					  io_req->user_bufs[i]);
1730 				goto bailout;
1731 			}
1732 
1733 		}
1734 		break;
1735 	case CAM_DATA_PADDR:
1736 		/* Do nothing.  The pointer is a physical address already */
1737 		break;
1738 	case CAM_DATA_SG:
1739 		/*
1740 		 * Copy back to the user buffer if this was a read.
1741 		 * Restore the user's S/G list buffer pointer.
1742 		 */
1743 		if (io_req->dirs[0] == CAM_DIR_IN)
1744 			error = passcopysglist(periph, io_req, io_req->dirs[0]);
1745 		break;
1746 	case CAM_DATA_SG_PADDR:
1747 		/*
1748 		 * Restore the user's S/G list buffer pointer.  No need to
1749 		 * copy.
1750 		 */
1751 		break;
1752 	default:
1753 	case CAM_DATA_BIO:
1754 		error = EINVAL;
1755 		break;
1756 	}
1757 
1758 bailout:
1759 	/*
1760 	 * Reset the user's pointers to their original values and free
1761 	 * allocated memory.
1762 	 */
1763 	passiocleanup(softc, io_req);
1764 
1765 	return (error);
1766 }
1767 
1768 static int
1769 passioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1770 {
1771 	int error;
1772 
1773 	if ((error = passdoioctl(dev, cmd, addr, flag, td)) == ENOTTY) {
1774 		error = cam_compat_ioctl(dev, cmd, addr, flag, td, passdoioctl);
1775 	}
1776 	return (error);
1777 }
1778 
1779 static int
1780 passdoioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1781 {
1782 	struct	cam_periph *periph;
1783 	struct	pass_softc *softc;
1784 	int	error;
1785 	uint32_t priority;
1786 
1787 	periph = (struct cam_periph *)dev->si_drv1;
1788 	cam_periph_lock(periph);
1789 	softc = (struct pass_softc *)periph->softc;
1790 
1791 	error = 0;
1792 
1793 	switch (cmd) {
1794 
1795 	case CAMIOCOMMAND:
1796 	{
1797 		union ccb *inccb;
1798 		union ccb *ccb;
1799 		int ccb_malloced;
1800 
1801 		inccb = (union ccb *)addr;
1802 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1803 		if (inccb->ccb_h.func_code == XPT_SCSI_IO)
1804 			inccb->csio.bio = NULL;
1805 #endif
1806 
1807 		if (inccb->ccb_h.flags & CAM_UNLOCKED) {
1808 			error = EINVAL;
1809 			break;
1810 		}
1811 
1812 		/*
1813 		 * Some CCB types, like scan bus and scan lun can only go
1814 		 * through the transport layer device.
1815 		 */
1816 		if (inccb->ccb_h.func_code & XPT_FC_XPT_ONLY) {
1817 			xpt_print(periph->path, "CCB function code %#x is "
1818 			    "restricted to the XPT device\n",
1819 			    inccb->ccb_h.func_code);
1820 			error = ENODEV;
1821 			break;
1822 		}
1823 
1824 		/* Compatibility for RL/priority-unaware code. */
1825 		priority = inccb->ccb_h.pinfo.priority;
1826 		if (priority <= CAM_PRIORITY_OOB)
1827 		    priority += CAM_PRIORITY_OOB + 1;
1828 
1829 		/*
1830 		 * Non-immediate CCBs need a CCB from the per-device pool
1831 		 * of CCBs, which is scheduled by the transport layer.
1832 		 * Immediate CCBs and user-supplied CCBs should just be
1833 		 * malloced.
1834 		 */
1835 		if ((inccb->ccb_h.func_code & XPT_FC_QUEUED)
1836 		 && ((inccb->ccb_h.func_code & XPT_FC_USER_CCB) == 0)) {
1837 			ccb = cam_periph_getccb(periph, priority);
1838 			ccb_malloced = 0;
1839 		} else {
1840 			ccb = xpt_alloc_ccb_nowait();
1841 
1842 			if (ccb != NULL)
1843 				xpt_setup_ccb(&ccb->ccb_h, periph->path,
1844 					      priority);
1845 			ccb_malloced = 1;
1846 		}
1847 
1848 		if (ccb == NULL) {
1849 			xpt_print(periph->path, "unable to allocate CCB\n");
1850 			error = ENOMEM;
1851 			break;
1852 		}
1853 
1854 		error = passsendccb(periph, ccb, inccb);
1855 
1856 		if (ccb_malloced)
1857 			xpt_free_ccb(ccb);
1858 		else
1859 			xpt_release_ccb(ccb);
1860 
1861 		break;
1862 	}
1863 	case CAMIOQUEUE:
1864 	{
1865 		struct pass_io_req *io_req;
1866 		union ccb **user_ccb, *ccb;
1867 		xpt_opcode fc;
1868 
1869 		if ((softc->flags & PASS_FLAG_ZONE_VALID) == 0) {
1870 			error = passcreatezone(periph);
1871 			if (error != 0)
1872 				goto bailout;
1873 		}
1874 
1875 		/*
1876 		 * We're going to do a blocking allocation for this I/O
1877 		 * request, so we have to drop the lock.
1878 		 */
1879 		cam_periph_unlock(periph);
1880 
1881 		io_req = uma_zalloc(softc->pass_zone, M_WAITOK | M_ZERO);
1882 		ccb = &io_req->ccb;
1883 		user_ccb = (union ccb **)addr;
1884 
1885 		/*
1886 		 * Unlike the CAMIOCOMMAND ioctl above, we only have a
1887 		 * pointer to the user's CCB, so we have to copy the whole
1888 		 * thing in to a buffer we have allocated (above) instead
1889 		 * of allowing the ioctl code to malloc a buffer and copy
1890 		 * it in.
1891 		 *
1892 		 * This is an advantage for this asynchronous interface,
1893 		 * since we don't want the memory to get freed while the
1894 		 * CCB is outstanding.
1895 		 */
1896 #if 0
1897 		xpt_print(periph->path, "Copying user CCB %p to "
1898 			  "kernel address %p\n", *user_ccb, ccb);
1899 #endif
1900 		error = copyin(*user_ccb, ccb, sizeof(*ccb));
1901 		if (error != 0) {
1902 			xpt_print(periph->path, "Copy of user CCB %p to "
1903 				  "kernel address %p failed with error %d\n",
1904 				  *user_ccb, ccb, error);
1905 			goto camioqueue_error;
1906 		}
1907 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1908 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
1909 			ccb->csio.bio = NULL;
1910 #endif
1911 
1912 		if (ccb->ccb_h.flags & CAM_UNLOCKED) {
1913 			error = EINVAL;
1914 			goto camioqueue_error;
1915 		}
1916 
1917 		if (ccb->ccb_h.flags & CAM_CDB_POINTER) {
1918 			if (ccb->csio.cdb_len > IOCDBLEN) {
1919 				error = EINVAL;
1920 				goto camioqueue_error;
1921 			}
1922 			error = copyin(ccb->csio.cdb_io.cdb_ptr,
1923 			    ccb->csio.cdb_io.cdb_bytes, ccb->csio.cdb_len);
1924 			if (error != 0)
1925 				goto camioqueue_error;
1926 			ccb->ccb_h.flags &= ~CAM_CDB_POINTER;
1927 		}
1928 
1929 		/*
1930 		 * Some CCB types, like scan bus and scan lun can only go
1931 		 * through the transport layer device.
1932 		 */
1933 		if (ccb->ccb_h.func_code & XPT_FC_XPT_ONLY) {
1934 			xpt_print(periph->path, "CCB function code %#x is "
1935 			    "restricted to the XPT device\n",
1936 			    ccb->ccb_h.func_code);
1937 			error = ENODEV;
1938 			goto camioqueue_error;
1939 		}
1940 
1941 		/*
1942 		 * Save the user's CCB pointer as well as his linked list
1943 		 * pointers and peripheral private area so that we can
1944 		 * restore these later.
1945 		 */
1946 		io_req->user_ccb_ptr = *user_ccb;
1947 		io_req->user_periph_links = ccb->ccb_h.periph_links;
1948 		io_req->user_periph_priv = ccb->ccb_h.periph_priv;
1949 
1950 		/*
1951 		 * Now that we've saved the user's values, we can set our
1952 		 * own peripheral private entry.
1953 		 */
1954 		ccb->ccb_h.ccb_ioreq = io_req;
1955 
1956 		/* Compatibility for RL/priority-unaware code. */
1957 		priority = ccb->ccb_h.pinfo.priority;
1958 		if (priority <= CAM_PRIORITY_OOB)
1959 		    priority += CAM_PRIORITY_OOB + 1;
1960 
1961 		/*
1962 		 * Setup fields in the CCB like the path and the priority.
1963 		 * The path in particular cannot be done in userland, since
1964 		 * it is a pointer to a kernel data structure.
1965 		 */
1966 		xpt_setup_ccb_flags(&ccb->ccb_h, periph->path, priority,
1967 				    ccb->ccb_h.flags);
1968 
1969 		/*
1970 		 * Setup our done routine.  There is no way for the user to
1971 		 * have a valid pointer here.
1972 		 */
1973 		ccb->ccb_h.cbfcnp = passdone;
1974 
1975 		fc = ccb->ccb_h.func_code;
1976 		/*
1977 		 * If this function code has memory that can be mapped in
1978 		 * or out, we need to call passmemsetup().
1979 		 */
1980 		if ((fc == XPT_SCSI_IO) || (fc == XPT_ATA_IO)
1981 		 || (fc == XPT_SMP_IO) || (fc == XPT_DEV_MATCH)
1982 		 || (fc == XPT_DEV_ADVINFO)
1983 		 || (fc == XPT_NVME_ADMIN) || (fc == XPT_NVME_IO)) {
1984 			error = passmemsetup(periph, io_req);
1985 			if (error != 0)
1986 				goto camioqueue_error;
1987 		} else
1988 			io_req->mapinfo.num_bufs_used = 0;
1989 
1990 		cam_periph_lock(periph);
1991 
1992 		/*
1993 		 * Everything goes on the incoming queue initially.
1994 		 */
1995 		TAILQ_INSERT_TAIL(&softc->incoming_queue, io_req, links);
1996 
1997 		/*
1998 		 * If the CCB is queued, and is not a user CCB, then
1999 		 * we need to allocate a slot for it.  Call xpt_schedule()
2000 		 * so that our start routine will get called when a CCB is
2001 		 * available.
2002 		 */
2003 		if ((fc & XPT_FC_QUEUED)
2004 		 && ((fc & XPT_FC_USER_CCB) == 0)) {
2005 			xpt_schedule(periph, priority);
2006 			break;
2007 		}
2008 
2009 		/*
2010 		 * At this point, the CCB in question is either an
2011 		 * immediate CCB (like XPT_DEV_ADVINFO) or it is a user CCB
2012 		 * and therefore should be malloced, not allocated via a slot.
2013 		 * Remove the CCB from the incoming queue and add it to the
2014 		 * active queue.
2015 		 */
2016 		TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
2017 		TAILQ_INSERT_TAIL(&softc->active_queue, io_req, links);
2018 
2019 		xpt_action(ccb);
2020 
2021 		/*
2022 		 * If this is not a queued CCB (i.e. it is an immediate CCB),
2023 		 * then it is already done.  We need to put it on the done
2024 		 * queue for the user to fetch.
2025 		 */
2026 		if ((fc & XPT_FC_QUEUED) == 0) {
2027 			TAILQ_REMOVE(&softc->active_queue, io_req, links);
2028 			TAILQ_INSERT_TAIL(&softc->done_queue, io_req, links);
2029 		}
2030 		break;
2031 
2032 camioqueue_error:
2033 		uma_zfree(softc->pass_zone, io_req);
2034 		cam_periph_lock(periph);
2035 		break;
2036 	}
2037 	case CAMIOGET:
2038 	{
2039 		union ccb **user_ccb;
2040 		struct pass_io_req *io_req;
2041 		int old_error;
2042 
2043 		user_ccb = (union ccb **)addr;
2044 		old_error = 0;
2045 
2046 		io_req = TAILQ_FIRST(&softc->done_queue);
2047 		if (io_req == NULL) {
2048 			error = ENOENT;
2049 			break;
2050 		}
2051 
2052 		/*
2053 		 * Remove the I/O from the done queue.
2054 		 */
2055 		TAILQ_REMOVE(&softc->done_queue, io_req, links);
2056 
2057 		/*
2058 		 * We have to drop the lock during the copyout because the
2059 		 * copyout can result in VM faults that require sleeping.
2060 		 */
2061 		cam_periph_unlock(periph);
2062 
2063 		/*
2064 		 * Do any needed copies (e.g. for reads) and revert the
2065 		 * pointers in the CCB back to the user's pointers.
2066 		 */
2067 		error = passmemdone(periph, io_req);
2068 
2069 		old_error = error;
2070 
2071 		io_req->ccb.ccb_h.periph_links = io_req->user_periph_links;
2072 		io_req->ccb.ccb_h.periph_priv = io_req->user_periph_priv;
2073 
2074 #if 0
2075 		xpt_print(periph->path, "Copying to user CCB %p from "
2076 			  "kernel address %p\n", *user_ccb, &io_req->ccb);
2077 #endif
2078 
2079 		error = copyout(&io_req->ccb, *user_ccb, sizeof(union ccb));
2080 		if (error != 0) {
2081 			xpt_print(periph->path, "Copy to user CCB %p from "
2082 				  "kernel address %p failed with error %d\n",
2083 				  *user_ccb, &io_req->ccb, error);
2084 		}
2085 
2086 		/*
2087 		 * Prefer the first error we got back, and make sure we
2088 		 * don't overwrite bad status with good.
2089 		 */
2090 		if (old_error != 0)
2091 			error = old_error;
2092 
2093 		cam_periph_lock(periph);
2094 
2095 		/*
2096 		 * At this point, if there was an error, we could potentially
2097 		 * re-queue the I/O and try again.  But why?  The error
2098 		 * would almost certainly happen again.  We might as well
2099 		 * not leak memory.
2100 		 */
2101 		uma_zfree(softc->pass_zone, io_req);
2102 		break;
2103 	}
2104 	default:
2105 		error = cam_periph_ioctl(periph, cmd, addr, passerror);
2106 		break;
2107 	}
2108 
2109 bailout:
2110 	cam_periph_unlock(periph);
2111 
2112 	return(error);
2113 }
2114 
2115 static int
2116 passpoll(struct cdev *dev, int poll_events, struct thread *td)
2117 {
2118 	struct cam_periph *periph;
2119 	struct pass_softc *softc;
2120 	int revents;
2121 
2122 	periph = (struct cam_periph *)dev->si_drv1;
2123 	softc = (struct pass_softc *)periph->softc;
2124 
2125 	revents = poll_events & (POLLOUT | POLLWRNORM);
2126 	if ((poll_events & (POLLIN | POLLRDNORM)) != 0) {
2127 		cam_periph_lock(periph);
2128 
2129 		if (!TAILQ_EMPTY(&softc->done_queue)) {
2130 			revents |= poll_events & (POLLIN | POLLRDNORM);
2131 		}
2132 		cam_periph_unlock(periph);
2133 		if (revents == 0)
2134 			selrecord(td, &softc->read_select);
2135 	}
2136 
2137 	return (revents);
2138 }
2139 
2140 static int
2141 passkqfilter(struct cdev *dev, struct knote *kn)
2142 {
2143 	struct cam_periph *periph;
2144 	struct pass_softc *softc;
2145 
2146 	periph = (struct cam_periph *)dev->si_drv1;
2147 	softc = (struct pass_softc *)periph->softc;
2148 
2149 	kn->kn_hook = (caddr_t)periph;
2150 	kn->kn_fop = &passread_filtops;
2151 	knlist_add(&softc->read_select.si_note, kn, 0);
2152 
2153 	return (0);
2154 }
2155 
2156 static void
2157 passreadfiltdetach(struct knote *kn)
2158 {
2159 	struct cam_periph *periph;
2160 	struct pass_softc *softc;
2161 
2162 	periph = (struct cam_periph *)kn->kn_hook;
2163 	softc = (struct pass_softc *)periph->softc;
2164 
2165 	knlist_remove(&softc->read_select.si_note, kn, 0);
2166 }
2167 
2168 static int
2169 passreadfilt(struct knote *kn, long hint)
2170 {
2171 	struct cam_periph *periph;
2172 	struct pass_softc *softc;
2173 	int retval;
2174 
2175 	periph = (struct cam_periph *)kn->kn_hook;
2176 	softc = (struct pass_softc *)periph->softc;
2177 
2178 	cam_periph_assert(periph, MA_OWNED);
2179 
2180 	if (TAILQ_EMPTY(&softc->done_queue))
2181 		retval = 0;
2182 	else
2183 		retval = 1;
2184 
2185 	return (retval);
2186 }
2187 
2188 /*
2189  * Generally, "ccb" should be the CCB supplied by the kernel.  "inccb"
2190  * should be the CCB that is copied in from the user.
2191  */
2192 static int
2193 passsendccb(struct cam_periph *periph, union ccb *ccb, union ccb *inccb)
2194 {
2195 	struct pass_softc *softc;
2196 	struct cam_periph_map_info mapinfo;
2197 	uint8_t *cmd;
2198 	xpt_opcode fc;
2199 	int error;
2200 
2201 	softc = (struct pass_softc *)periph->softc;
2202 
2203 	/*
2204 	 * There are some fields in the CCB header that need to be
2205 	 * preserved, the rest we get from the user.
2206 	 */
2207 	xpt_merge_ccb(ccb, inccb);
2208 
2209 	if (ccb->ccb_h.flags & CAM_CDB_POINTER) {
2210 		cmd = __builtin_alloca(ccb->csio.cdb_len);
2211 		error = copyin(ccb->csio.cdb_io.cdb_ptr, cmd, ccb->csio.cdb_len);
2212 		if (error)
2213 			return (error);
2214 		ccb->csio.cdb_io.cdb_ptr = cmd;
2215 	}
2216 
2217 	/*
2218 	 */
2219 	ccb->ccb_h.cbfcnp = passdone;
2220 
2221 	/*
2222 	 * Let cam_periph_mapmem do a sanity check on the data pointer format.
2223 	 * Even if no data transfer is needed, it's a cheap check and it
2224 	 * simplifies the code.
2225 	 */
2226 	fc = ccb->ccb_h.func_code;
2227 	if ((fc == XPT_SCSI_IO) || (fc == XPT_ATA_IO) || (fc == XPT_SMP_IO)
2228             || (fc == XPT_DEV_MATCH) || (fc == XPT_DEV_ADVINFO) || (fc == XPT_MMC_IO)
2229             || (fc == XPT_NVME_ADMIN) || (fc == XPT_NVME_IO)) {
2230 
2231 		bzero(&mapinfo, sizeof(mapinfo));
2232 
2233 		/*
2234 		 * cam_periph_mapmem calls into proc and vm functions that can
2235 		 * sleep as well as trigger I/O, so we can't hold the lock.
2236 		 * Dropping it here is reasonably safe.
2237 		 */
2238 		cam_periph_unlock(periph);
2239 		error = cam_periph_mapmem(ccb, &mapinfo, softc->maxio);
2240 		cam_periph_lock(periph);
2241 
2242 		/*
2243 		 * cam_periph_mapmem returned an error, we can't continue.
2244 		 * Return the error to the user.
2245 		 */
2246 		if (error)
2247 			return(error);
2248 	} else
2249 		/* Ensure that the unmap call later on is a no-op. */
2250 		mapinfo.num_bufs_used = 0;
2251 
2252 	/*
2253 	 * If the user wants us to perform any error recovery, then honor
2254 	 * that request.  Otherwise, it's up to the user to perform any
2255 	 * error recovery.
2256 	 */
2257 	cam_periph_runccb(ccb, (ccb->ccb_h.flags & CAM_PASS_ERR_RECOVER) ?
2258 	    passerror : NULL, /* cam_flags */ CAM_RETRY_SELTO,
2259 	    /* sense_flags */ SF_RETRY_UA | SF_NO_PRINT,
2260 	    softc->device_stats);
2261 
2262 	cam_periph_unmapmem(ccb, &mapinfo);
2263 
2264 	ccb->ccb_h.cbfcnp = NULL;
2265 	ccb->ccb_h.periph_priv = inccb->ccb_h.periph_priv;
2266 	bcopy(ccb, inccb, sizeof(union ccb));
2267 
2268 	return(0);
2269 }
2270 
2271 static int
2272 passerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2273 {
2274 	struct cam_periph *periph;
2275 	struct pass_softc *softc;
2276 
2277 	periph = xpt_path_periph(ccb->ccb_h.path);
2278 	softc = (struct pass_softc *)periph->softc;
2279 
2280 	return(cam_periph_error(ccb, cam_flags, sense_flags,
2281 				 &softc->saved_ccb));
2282 }
2283