xref: /freebsd/sys/cam/scsi/scsi_pass.c (revision 15c433351f54e7cd5bec8d36c8e89e6a7fa55b26)
1 /*-
2  * Copyright (c) 1997, 1998, 2000 Justin T. Gibbs.
3  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
19  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_kdtrace.h"
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 			    done_ccb->ataio.tag_action & 0x3,
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 	default:
1152 		/* allow ourselves to be swapped once again */
1153 		return;
1154 		break; /* NOTREACHED */
1155 	}
1156 
1157 	if (io_req->flags & PASS_IO_USER_SEG_MALLOC) {
1158 		free(io_req->user_segptr, M_SCSIPASS);
1159 		io_req->user_segptr = NULL;
1160 	}
1161 
1162 	/*
1163 	 * We only want to free memory we malloced.
1164 	 */
1165 	if (io_req->data_flags == CAM_DATA_VADDR) {
1166 		for (i = 0; i < io_req->num_bufs; i++) {
1167 			if (io_req->kern_bufs[i] == NULL)
1168 				continue;
1169 
1170 			free(io_req->kern_bufs[i], M_SCSIPASS);
1171 			io_req->kern_bufs[i] = NULL;
1172 		}
1173 	} else if (io_req->data_flags == CAM_DATA_SG) {
1174 		for (i = 0; i < io_req->num_kern_segs; i++) {
1175 			if ((uint8_t *)(uintptr_t)
1176 			    io_req->kern_segptr[i].ds_addr == NULL)
1177 				continue;
1178 
1179 			uma_zfree(softc->pass_io_zone, (uint8_t *)(uintptr_t)
1180 			    io_req->kern_segptr[i].ds_addr);
1181 			io_req->kern_segptr[i].ds_addr = 0;
1182 		}
1183 	}
1184 
1185 	if (io_req->flags & PASS_IO_KERN_SEG_MALLOC) {
1186 		free(io_req->kern_segptr, M_SCSIPASS);
1187 		io_req->kern_segptr = NULL;
1188 	}
1189 
1190 	if (io_req->data_flags != CAM_DATA_PADDR) {
1191 		for (i = 0; i < numbufs; i++) {
1192 			/*
1193 			 * Restore the user's buffer pointers to their
1194 			 * previous values.
1195 			 */
1196 			if (io_req->user_bufs[i] != NULL)
1197 				*data_ptrs[i] = io_req->user_bufs[i];
1198 		}
1199 	}
1200 
1201 }
1202 
1203 static int
1204 passcopysglist(struct cam_periph *periph, struct pass_io_req *io_req,
1205 	       ccb_flags direction)
1206 {
1207 	bus_size_t kern_watermark, user_watermark, len_copied, len_to_copy;
1208 	bus_dma_segment_t *user_sglist, *kern_sglist;
1209 	int i, j, error;
1210 
1211 	error = 0;
1212 	kern_watermark = 0;
1213 	user_watermark = 0;
1214 	len_to_copy = 0;
1215 	len_copied = 0;
1216 	user_sglist = io_req->user_segptr;
1217 	kern_sglist = io_req->kern_segptr;
1218 
1219 	for (i = 0, j = 0; i < io_req->num_user_segs &&
1220 	     j < io_req->num_kern_segs;) {
1221 		uint8_t *user_ptr, *kern_ptr;
1222 
1223 		len_to_copy = min(user_sglist[i].ds_len -user_watermark,
1224 		    kern_sglist[j].ds_len - kern_watermark);
1225 
1226 		user_ptr = (uint8_t *)(uintptr_t)user_sglist[i].ds_addr;
1227 		user_ptr = user_ptr + user_watermark;
1228 		kern_ptr = (uint8_t *)(uintptr_t)kern_sglist[j].ds_addr;
1229 		kern_ptr = kern_ptr + kern_watermark;
1230 
1231 		user_watermark += len_to_copy;
1232 		kern_watermark += len_to_copy;
1233 
1234 		if (!useracc(user_ptr, len_to_copy,
1235 		    (direction == CAM_DIR_IN) ? VM_PROT_WRITE : VM_PROT_READ)) {
1236 			xpt_print(periph->path, "%s: unable to access user "
1237 				  "S/G list element %p len %zu\n", __func__,
1238 				  user_ptr, len_to_copy);
1239 			error = EFAULT;
1240 			goto bailout;
1241 		}
1242 
1243 		if (direction == CAM_DIR_IN) {
1244 			error = copyout(kern_ptr, user_ptr, len_to_copy);
1245 			if (error != 0) {
1246 				xpt_print(periph->path, "%s: copyout of %u "
1247 					  "bytes from %p to %p failed with "
1248 					  "error %d\n", __func__, len_to_copy,
1249 					  kern_ptr, user_ptr, error);
1250 				goto bailout;
1251 			}
1252 		} else {
1253 			error = copyin(user_ptr, kern_ptr, len_to_copy);
1254 			if (error != 0) {
1255 				xpt_print(periph->path, "%s: copyin of %u "
1256 					  "bytes from %p to %p failed with "
1257 					  "error %d\n", __func__, len_to_copy,
1258 					  user_ptr, kern_ptr, error);
1259 				goto bailout;
1260 			}
1261 		}
1262 
1263 		len_copied += len_to_copy;
1264 
1265 		if (user_sglist[i].ds_len == user_watermark) {
1266 			i++;
1267 			user_watermark = 0;
1268 		}
1269 
1270 		if (kern_sglist[j].ds_len == kern_watermark) {
1271 			j++;
1272 			kern_watermark = 0;
1273 		}
1274 	}
1275 
1276 bailout:
1277 
1278 	return (error);
1279 }
1280 
1281 static int
1282 passmemsetup(struct cam_periph *periph, struct pass_io_req *io_req)
1283 {
1284 	union ccb *ccb;
1285 	struct pass_softc *softc;
1286 	int numbufs, i;
1287 	uint8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1288 	uint32_t lengths[CAM_PERIPH_MAXMAPS];
1289 	uint32_t dirs[CAM_PERIPH_MAXMAPS];
1290 	uint32_t num_segs;
1291 	uint16_t *seg_cnt_ptr;
1292 	size_t maxmap;
1293 	int error;
1294 
1295 	cam_periph_assert(periph, MA_NOTOWNED);
1296 
1297 	softc = periph->softc;
1298 
1299 	error = 0;
1300 	ccb = &io_req->ccb;
1301 	maxmap = 0;
1302 	num_segs = 0;
1303 	seg_cnt_ptr = NULL;
1304 
1305 	switch(ccb->ccb_h.func_code) {
1306 	case XPT_DEV_MATCH:
1307 		if (ccb->cdm.match_buf_len == 0) {
1308 			printf("%s: invalid match buffer length 0\n", __func__);
1309 			return(EINVAL);
1310 		}
1311 		if (ccb->cdm.pattern_buf_len > 0) {
1312 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1313 			lengths[0] = ccb->cdm.pattern_buf_len;
1314 			dirs[0] = CAM_DIR_OUT;
1315 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1316 			lengths[1] = ccb->cdm.match_buf_len;
1317 			dirs[1] = CAM_DIR_IN;
1318 			numbufs = 2;
1319 		} else {
1320 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1321 			lengths[0] = ccb->cdm.match_buf_len;
1322 			dirs[0] = CAM_DIR_IN;
1323 			numbufs = 1;
1324 		}
1325 		io_req->data_flags = CAM_DATA_VADDR;
1326 		break;
1327 	case XPT_SCSI_IO:
1328 	case XPT_CONT_TARGET_IO:
1329 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
1330 			return(0);
1331 
1332 		/*
1333 		 * The user shouldn't be able to supply a bio.
1334 		 */
1335 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) == CAM_DATA_BIO)
1336 			return (EINVAL);
1337 
1338 		io_req->data_flags = ccb->ccb_h.flags & CAM_DATA_MASK;
1339 
1340 		data_ptrs[0] = &ccb->csio.data_ptr;
1341 		lengths[0] = ccb->csio.dxfer_len;
1342 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1343 		num_segs = ccb->csio.sglist_cnt;
1344 		seg_cnt_ptr = &ccb->csio.sglist_cnt;
1345 		numbufs = 1;
1346 		maxmap = softc->maxio;
1347 		break;
1348 	case XPT_ATA_IO:
1349 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
1350 			return(0);
1351 
1352 		/*
1353 		 * We only support a single virtual address for ATA I/O.
1354 		 */
1355 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
1356 			return (EINVAL);
1357 
1358 		io_req->data_flags = CAM_DATA_VADDR;
1359 
1360 		data_ptrs[0] = &ccb->ataio.data_ptr;
1361 		lengths[0] = ccb->ataio.dxfer_len;
1362 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1363 		numbufs = 1;
1364 		maxmap = softc->maxio;
1365 		break;
1366 	case XPT_SMP_IO:
1367 		io_req->data_flags = CAM_DATA_VADDR;
1368 
1369 		data_ptrs[0] = &ccb->smpio.smp_request;
1370 		lengths[0] = ccb->smpio.smp_request_len;
1371 		dirs[0] = CAM_DIR_OUT;
1372 		data_ptrs[1] = &ccb->smpio.smp_response;
1373 		lengths[1] = ccb->smpio.smp_response_len;
1374 		dirs[1] = CAM_DIR_IN;
1375 		numbufs = 2;
1376 		maxmap = softc->maxio;
1377 		break;
1378 	case XPT_DEV_ADVINFO:
1379 		if (ccb->cdai.bufsiz == 0)
1380 			return (0);
1381 
1382 		io_req->data_flags = CAM_DATA_VADDR;
1383 
1384 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1385 		lengths[0] = ccb->cdai.bufsiz;
1386 		dirs[0] = CAM_DIR_IN;
1387 		numbufs = 1;
1388 		break;
1389 	default:
1390 		return(EINVAL);
1391 		break; /* NOTREACHED */
1392 	}
1393 
1394 	io_req->num_bufs = numbufs;
1395 
1396 	/*
1397 	 * If there is a maximum, check to make sure that the user's
1398 	 * request fits within the limit.  In general, we should only have
1399 	 * a maximum length for requests that go to hardware.  Otherwise it
1400 	 * is whatever we're able to malloc.
1401 	 */
1402 	for (i = 0; i < numbufs; i++) {
1403 		io_req->user_bufs[i] = *data_ptrs[i];
1404 		io_req->dirs[i] = dirs[i];
1405 		io_req->lengths[i] = lengths[i];
1406 
1407 		if (maxmap == 0)
1408 			continue;
1409 
1410 		if (lengths[i] <= maxmap)
1411 			continue;
1412 
1413 		xpt_print(periph->path, "%s: data length %u > max allowed %u "
1414 			  "bytes\n", __func__, lengths[i], maxmap);
1415 		error = EINVAL;
1416 		goto bailout;
1417 	}
1418 
1419 	switch (io_req->data_flags) {
1420 	case CAM_DATA_VADDR:
1421 		/* Map or copy the buffer into kernel address space */
1422 		for (i = 0; i < numbufs; i++) {
1423 			uint8_t *tmp_buf;
1424 
1425 			/*
1426 			 * If for some reason no length is specified, we
1427 			 * don't need to allocate anything.
1428 			 */
1429 			if (io_req->lengths[i] == 0)
1430 				continue;
1431 
1432 			/*
1433 			 * Make sure that the user's buffer is accessible
1434 			 * to that process.
1435 			 */
1436 			if (!useracc(io_req->user_bufs[i], io_req->lengths[i],
1437 			    (io_req->dirs[i] == CAM_DIR_IN) ? VM_PROT_WRITE :
1438 			     VM_PROT_READ)) {
1439 				xpt_print(periph->path, "%s: user address %p "
1440 				    "length %u is not accessible\n", __func__,
1441 				    io_req->user_bufs[i], io_req->lengths[i]);
1442 				error = EFAULT;
1443 				goto bailout;
1444 			}
1445 
1446 			tmp_buf = malloc(lengths[i], M_SCSIPASS,
1447 					 M_WAITOK | M_ZERO);
1448 			io_req->kern_bufs[i] = tmp_buf;
1449 			*data_ptrs[i] = tmp_buf;
1450 
1451 #if 0
1452 			xpt_print(periph->path, "%s: malloced %p len %u, user "
1453 				  "buffer %p, operation: %s\n", __func__,
1454 				  tmp_buf, lengths[i], io_req->user_bufs[i],
1455 				  (dirs[i] == CAM_DIR_IN) ? "read" : "write");
1456 #endif
1457 			/*
1458 			 * We only need to copy in if the user is writing.
1459 			 */
1460 			if (dirs[i] != CAM_DIR_OUT)
1461 				continue;
1462 
1463 			error = copyin(io_req->user_bufs[i],
1464 				       io_req->kern_bufs[i], lengths[i]);
1465 			if (error != 0) {
1466 				xpt_print(periph->path, "%s: copy of user "
1467 					  "buffer from %p to %p failed with "
1468 					  "error %d\n", __func__,
1469 					  io_req->user_bufs[i],
1470 					  io_req->kern_bufs[i], error);
1471 				goto bailout;
1472 			}
1473 		}
1474 		break;
1475 	case CAM_DATA_PADDR:
1476 		/* Pass down the pointer as-is */
1477 		break;
1478 	case CAM_DATA_SG: {
1479 		size_t sg_length, size_to_go, alloc_size;
1480 		uint32_t num_segs_needed;
1481 
1482 		/*
1483 		 * Copy the user S/G list in, and then copy in the
1484 		 * individual segments.
1485 		 */
1486 		/*
1487 		 * We shouldn't see this, but check just in case.
1488 		 */
1489 		if (numbufs != 1) {
1490 			xpt_print(periph->path, "%s: cannot currently handle "
1491 				  "more than one S/G list per CCB\n", __func__);
1492 			error = EINVAL;
1493 			goto bailout;
1494 		}
1495 
1496 		/*
1497 		 * We have to have at least one segment.
1498 		 */
1499 		if (num_segs == 0) {
1500 			xpt_print(periph->path, "%s: CAM_DATA_SG flag set, "
1501 				  "but sglist_cnt=0!\n", __func__);
1502 			error = EINVAL;
1503 			goto bailout;
1504 		}
1505 
1506 		/*
1507 		 * Make sure the user specified the total length and didn't
1508 		 * just leave it to us to decode the S/G list.
1509 		 */
1510 		if (lengths[0] == 0) {
1511 			xpt_print(periph->path, "%s: no dxfer_len specified, "
1512 				  "but CAM_DATA_SG flag is set!\n", __func__);
1513 			error = EINVAL;
1514 			goto bailout;
1515 		}
1516 
1517 		/*
1518 		 * We allocate buffers in io_zone_size increments for an
1519 		 * S/G list.  This will generally be MAXPHYS.
1520 		 */
1521 		if (lengths[0] <= softc->io_zone_size)
1522 			num_segs_needed = 1;
1523 		else {
1524 			num_segs_needed = lengths[0] / softc->io_zone_size;
1525 			if ((lengths[0] % softc->io_zone_size) != 0)
1526 				num_segs_needed++;
1527 		}
1528 
1529 		/* Figure out the size of the S/G list */
1530 		sg_length = num_segs * sizeof(bus_dma_segment_t);
1531 		io_req->num_user_segs = num_segs;
1532 		io_req->num_kern_segs = num_segs_needed;
1533 
1534 		/* Save the user's S/G list pointer for later restoration */
1535 		io_req->user_bufs[0] = *data_ptrs[0];
1536 
1537 		/*
1538 		 * If we have enough segments allocated by default to handle
1539 		 * the length of the user's S/G list,
1540 		 */
1541 		if (num_segs > PASS_MAX_SEGS) {
1542 			io_req->user_segptr = malloc(sizeof(bus_dma_segment_t) *
1543 			    num_segs, M_SCSIPASS, M_WAITOK | M_ZERO);
1544 			io_req->flags |= PASS_IO_USER_SEG_MALLOC;
1545 		} else
1546 			io_req->user_segptr = io_req->user_segs;
1547 
1548 		if (!useracc(*data_ptrs[0], sg_length, VM_PROT_READ)) {
1549 			xpt_print(periph->path, "%s: unable to access user "
1550 				  "S/G list at %p\n", __func__, *data_ptrs[0]);
1551 			error = EFAULT;
1552 			goto bailout;
1553 		}
1554 
1555 		error = copyin(*data_ptrs[0], io_req->user_segptr, sg_length);
1556 		if (error != 0) {
1557 			xpt_print(periph->path, "%s: copy of user S/G list "
1558 				  "from %p to %p failed with error %d\n",
1559 				  __func__, *data_ptrs[0], io_req->user_segptr,
1560 				  error);
1561 			goto bailout;
1562 		}
1563 
1564 		if (num_segs_needed > PASS_MAX_SEGS) {
1565 			io_req->kern_segptr = malloc(sizeof(bus_dma_segment_t) *
1566 			    num_segs_needed, M_SCSIPASS, M_WAITOK | M_ZERO);
1567 			io_req->flags |= PASS_IO_KERN_SEG_MALLOC;
1568 		} else {
1569 			io_req->kern_segptr = io_req->kern_segs;
1570 		}
1571 
1572 		/*
1573 		 * Allocate the kernel S/G list.
1574 		 */
1575 		for (size_to_go = lengths[0], i = 0;
1576 		     size_to_go > 0 && i < num_segs_needed;
1577 		     i++, size_to_go -= alloc_size) {
1578 			uint8_t *kern_ptr;
1579 
1580 			alloc_size = min(size_to_go, softc->io_zone_size);
1581 			kern_ptr = uma_zalloc(softc->pass_io_zone, M_WAITOK);
1582 			io_req->kern_segptr[i].ds_addr =
1583 			    (bus_addr_t)(uintptr_t)kern_ptr;
1584 			io_req->kern_segptr[i].ds_len = alloc_size;
1585 		}
1586 		if (size_to_go > 0) {
1587 			printf("%s: size_to_go = %zu, software error!\n",
1588 			       __func__, size_to_go);
1589 			error = EINVAL;
1590 			goto bailout;
1591 		}
1592 
1593 		*data_ptrs[0] = (uint8_t *)io_req->kern_segptr;
1594 		*seg_cnt_ptr = io_req->num_kern_segs;
1595 
1596 		/*
1597 		 * We only need to copy data here if the user is writing.
1598 		 */
1599 		if (dirs[0] == CAM_DIR_OUT)
1600 			error = passcopysglist(periph, io_req, dirs[0]);
1601 		break;
1602 	}
1603 	case CAM_DATA_SG_PADDR: {
1604 		size_t sg_length;
1605 
1606 		/*
1607 		 * We shouldn't see this, but check just in case.
1608 		 */
1609 		if (numbufs != 1) {
1610 			printf("%s: cannot currently handle more than one "
1611 			       "S/G list per CCB\n", __func__);
1612 			error = EINVAL;
1613 			goto bailout;
1614 		}
1615 
1616 		/*
1617 		 * We have to have at least one segment.
1618 		 */
1619 		if (num_segs == 0) {
1620 			xpt_print(periph->path, "%s: CAM_DATA_SG_PADDR flag "
1621 				  "set, but sglist_cnt=0!\n", __func__);
1622 			error = EINVAL;
1623 			goto bailout;
1624 		}
1625 
1626 		/*
1627 		 * Make sure the user specified the total length and didn't
1628 		 * just leave it to us to decode the S/G list.
1629 		 */
1630 		if (lengths[0] == 0) {
1631 			xpt_print(periph->path, "%s: no dxfer_len specified, "
1632 				  "but CAM_DATA_SG flag is set!\n", __func__);
1633 			error = EINVAL;
1634 			goto bailout;
1635 		}
1636 
1637 		/* Figure out the size of the S/G list */
1638 		sg_length = num_segs * sizeof(bus_dma_segment_t);
1639 		io_req->num_user_segs = num_segs;
1640 		io_req->num_kern_segs = io_req->num_user_segs;
1641 
1642 		/* Save the user's S/G list pointer for later restoration */
1643 		io_req->user_bufs[0] = *data_ptrs[0];
1644 
1645 		if (num_segs > PASS_MAX_SEGS) {
1646 			io_req->user_segptr = malloc(sizeof(bus_dma_segment_t) *
1647 			    num_segs, M_SCSIPASS, M_WAITOK | M_ZERO);
1648 			io_req->flags |= PASS_IO_USER_SEG_MALLOC;
1649 		} else
1650 			io_req->user_segptr = io_req->user_segs;
1651 
1652 		io_req->kern_segptr = io_req->user_segptr;
1653 
1654 		error = copyin(*data_ptrs[0], io_req->user_segptr, sg_length);
1655 		if (error != 0) {
1656 			xpt_print(periph->path, "%s: copy of user S/G list "
1657 				  "from %p to %p failed with error %d\n",
1658 				  __func__, *data_ptrs[0], io_req->user_segptr,
1659 				  error);
1660 			goto bailout;
1661 		}
1662 		break;
1663 	}
1664 	default:
1665 	case CAM_DATA_BIO:
1666 		/*
1667 		 * A user shouldn't be attaching a bio to the CCB.  It
1668 		 * isn't a user-accessible structure.
1669 		 */
1670 		error = EINVAL;
1671 		break;
1672 	}
1673 
1674 bailout:
1675 	if (error != 0)
1676 		passiocleanup(softc, io_req);
1677 
1678 	return (error);
1679 }
1680 
1681 static int
1682 passmemdone(struct cam_periph *periph, struct pass_io_req *io_req)
1683 {
1684 	struct pass_softc *softc;
1685 	union ccb *ccb;
1686 	int error;
1687 	int i;
1688 
1689 	error = 0;
1690 	softc = (struct pass_softc *)periph->softc;
1691 	ccb = &io_req->ccb;
1692 
1693 	switch (io_req->data_flags) {
1694 	case CAM_DATA_VADDR:
1695 		/*
1696 		 * Copy back to the user buffer if this was a read.
1697 		 */
1698 		for (i = 0; i < io_req->num_bufs; i++) {
1699 			if (io_req->dirs[i] != CAM_DIR_IN)
1700 				continue;
1701 
1702 			error = copyout(io_req->kern_bufs[i],
1703 			    io_req->user_bufs[i], io_req->lengths[i]);
1704 			if (error != 0) {
1705 				xpt_print(periph->path, "Unable to copy %u "
1706 					  "bytes from %p to user address %p\n",
1707 					  io_req->lengths[i],
1708 					  io_req->kern_bufs[i],
1709 					  io_req->user_bufs[i]);
1710 				goto bailout;
1711 			}
1712 
1713 		}
1714 		break;
1715 	case CAM_DATA_PADDR:
1716 		/* Do nothing.  The pointer is a physical address already */
1717 		break;
1718 	case CAM_DATA_SG:
1719 		/*
1720 		 * Copy back to the user buffer if this was a read.
1721 		 * Restore the user's S/G list buffer pointer.
1722 		 */
1723 		if (io_req->dirs[0] == CAM_DIR_IN)
1724 			error = passcopysglist(periph, io_req, io_req->dirs[0]);
1725 		break;
1726 	case CAM_DATA_SG_PADDR:
1727 		/*
1728 		 * Restore the user's S/G list buffer pointer.  No need to
1729 		 * copy.
1730 		 */
1731 		break;
1732 	default:
1733 	case CAM_DATA_BIO:
1734 		error = EINVAL;
1735 		break;
1736 	}
1737 
1738 bailout:
1739 	/*
1740 	 * Reset the user's pointers to their original values and free
1741 	 * allocated memory.
1742 	 */
1743 	passiocleanup(softc, io_req);
1744 
1745 	return (error);
1746 }
1747 
1748 static int
1749 passioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1750 {
1751 	int error;
1752 
1753 	if ((error = passdoioctl(dev, cmd, addr, flag, td)) == ENOTTY) {
1754 		error = cam_compat_ioctl(dev, cmd, addr, flag, td, passdoioctl);
1755 	}
1756 	return (error);
1757 }
1758 
1759 static int
1760 passdoioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1761 {
1762 	struct	cam_periph *periph;
1763 	struct	pass_softc *softc;
1764 	int	error;
1765 	uint32_t priority;
1766 
1767 	periph = (struct cam_periph *)dev->si_drv1;
1768 	cam_periph_lock(periph);
1769 	softc = (struct pass_softc *)periph->softc;
1770 
1771 	error = 0;
1772 
1773 	switch (cmd) {
1774 
1775 	case CAMIOCOMMAND:
1776 	{
1777 		union ccb *inccb;
1778 		union ccb *ccb;
1779 		int ccb_malloced;
1780 
1781 		inccb = (union ccb *)addr;
1782 
1783 		/*
1784 		 * Some CCB types, like scan bus and scan lun can only go
1785 		 * through the transport layer device.
1786 		 */
1787 		if (inccb->ccb_h.func_code & XPT_FC_XPT_ONLY) {
1788 			xpt_print(periph->path, "CCB function code %#x is "
1789 			    "restricted to the XPT device\n",
1790 			    inccb->ccb_h.func_code);
1791 			error = ENODEV;
1792 			break;
1793 		}
1794 
1795 		/* Compatibility for RL/priority-unaware code. */
1796 		priority = inccb->ccb_h.pinfo.priority;
1797 		if (priority <= CAM_PRIORITY_OOB)
1798 		    priority += CAM_PRIORITY_OOB + 1;
1799 
1800 		/*
1801 		 * Non-immediate CCBs need a CCB from the per-device pool
1802 		 * of CCBs, which is scheduled by the transport layer.
1803 		 * Immediate CCBs and user-supplied CCBs should just be
1804 		 * malloced.
1805 		 */
1806 		if ((inccb->ccb_h.func_code & XPT_FC_QUEUED)
1807 		 && ((inccb->ccb_h.func_code & XPT_FC_USER_CCB) == 0)) {
1808 			ccb = cam_periph_getccb(periph, priority);
1809 			ccb_malloced = 0;
1810 		} else {
1811 			ccb = xpt_alloc_ccb_nowait();
1812 
1813 			if (ccb != NULL)
1814 				xpt_setup_ccb(&ccb->ccb_h, periph->path,
1815 					      priority);
1816 			ccb_malloced = 1;
1817 		}
1818 
1819 		if (ccb == NULL) {
1820 			xpt_print(periph->path, "unable to allocate CCB\n");
1821 			error = ENOMEM;
1822 			break;
1823 		}
1824 
1825 		error = passsendccb(periph, ccb, inccb);
1826 
1827 		if (ccb_malloced)
1828 			xpt_free_ccb(ccb);
1829 		else
1830 			xpt_release_ccb(ccb);
1831 
1832 		break;
1833 	}
1834 	case CAMIOQUEUE:
1835 	{
1836 		struct pass_io_req *io_req;
1837 		union ccb **user_ccb, *ccb;
1838 		xpt_opcode fc;
1839 
1840 		if ((softc->flags & PASS_FLAG_ZONE_VALID) == 0) {
1841 			error = passcreatezone(periph);
1842 			if (error != 0)
1843 				goto bailout;
1844 		}
1845 
1846 		/*
1847 		 * We're going to do a blocking allocation for this I/O
1848 		 * request, so we have to drop the lock.
1849 		 */
1850 		cam_periph_unlock(periph);
1851 
1852 		io_req = uma_zalloc(softc->pass_zone, M_WAITOK | M_ZERO);
1853 		ccb = &io_req->ccb;
1854 		user_ccb = (union ccb **)addr;
1855 
1856 		/*
1857 		 * Unlike the CAMIOCOMMAND ioctl above, we only have a
1858 		 * pointer to the user's CCB, so we have to copy the whole
1859 		 * thing in to a buffer we have allocated (above) instead
1860 		 * of allowing the ioctl code to malloc a buffer and copy
1861 		 * it in.
1862 		 *
1863 		 * This is an advantage for this asynchronous interface,
1864 		 * since we don't want the memory to get freed while the
1865 		 * CCB is outstanding.
1866 		 */
1867 #if 0
1868 		xpt_print(periph->path, "Copying user CCB %p to "
1869 			  "kernel address %p\n", *user_ccb, ccb);
1870 #endif
1871 		error = copyin(*user_ccb, ccb, sizeof(*ccb));
1872 		if (error != 0) {
1873 			xpt_print(periph->path, "Copy of user CCB %p to "
1874 				  "kernel address %p failed with error %d\n",
1875 				  *user_ccb, ccb, error);
1876 			uma_zfree(softc->pass_zone, io_req);
1877 			cam_periph_lock(periph);
1878 			break;
1879 		}
1880 
1881 		/*
1882 		 * Some CCB types, like scan bus and scan lun can only go
1883 		 * through the transport layer device.
1884 		 */
1885 		if (ccb->ccb_h.func_code & XPT_FC_XPT_ONLY) {
1886 			xpt_print(periph->path, "CCB function code %#x is "
1887 			    "restricted to the XPT device\n",
1888 			    ccb->ccb_h.func_code);
1889 			uma_zfree(softc->pass_zone, io_req);
1890 			cam_periph_lock(periph);
1891 			error = ENODEV;
1892 			break;
1893 		}
1894 
1895 		/*
1896 		 * Save the user's CCB pointer as well as his linked list
1897 		 * pointers and peripheral private area so that we can
1898 		 * restore these later.
1899 		 */
1900 		io_req->user_ccb_ptr = *user_ccb;
1901 		io_req->user_periph_links = ccb->ccb_h.periph_links;
1902 		io_req->user_periph_priv = ccb->ccb_h.periph_priv;
1903 
1904 		/*
1905 		 * Now that we've saved the user's values, we can set our
1906 		 * own peripheral private entry.
1907 		 */
1908 		ccb->ccb_h.ccb_ioreq = io_req;
1909 
1910 		/* Compatibility for RL/priority-unaware code. */
1911 		priority = ccb->ccb_h.pinfo.priority;
1912 		if (priority <= CAM_PRIORITY_OOB)
1913 		    priority += CAM_PRIORITY_OOB + 1;
1914 
1915 		/*
1916 		 * Setup fields in the CCB like the path and the priority.
1917 		 * The path in particular cannot be done in userland, since
1918 		 * it is a pointer to a kernel data structure.
1919 		 */
1920 		xpt_setup_ccb_flags(&ccb->ccb_h, periph->path, priority,
1921 				    ccb->ccb_h.flags);
1922 
1923 		/*
1924 		 * Setup our done routine.  There is no way for the user to
1925 		 * have a valid pointer here.
1926 		 */
1927 		ccb->ccb_h.cbfcnp = passdone;
1928 
1929 		fc = ccb->ccb_h.func_code;
1930 		/*
1931 		 * If this function code has memory that can be mapped in
1932 		 * or out, we need to call passmemsetup().
1933 		 */
1934 		if ((fc == XPT_SCSI_IO) || (fc == XPT_ATA_IO)
1935 		 || (fc == XPT_SMP_IO) || (fc == XPT_DEV_MATCH)
1936 		 || (fc == XPT_DEV_ADVINFO)) {
1937 			error = passmemsetup(periph, io_req);
1938 			if (error != 0) {
1939 				uma_zfree(softc->pass_zone, io_req);
1940 				cam_periph_lock(periph);
1941 				break;
1942 			}
1943 		} else
1944 			io_req->mapinfo.num_bufs_used = 0;
1945 
1946 		cam_periph_lock(periph);
1947 
1948 		/*
1949 		 * Everything goes on the incoming queue initially.
1950 		 */
1951 		TAILQ_INSERT_TAIL(&softc->incoming_queue, io_req, links);
1952 
1953 		/*
1954 		 * If the CCB is queued, and is not a user CCB, then
1955 		 * we need to allocate a slot for it.  Call xpt_schedule()
1956 		 * so that our start routine will get called when a CCB is
1957 		 * available.
1958 		 */
1959 		if ((fc & XPT_FC_QUEUED)
1960 		 && ((fc & XPT_FC_USER_CCB) == 0)) {
1961 			xpt_schedule(periph, priority);
1962 			break;
1963 		}
1964 
1965 		/*
1966 		 * At this point, the CCB in question is either an
1967 		 * immediate CCB (like XPT_DEV_ADVINFO) or it is a user CCB
1968 		 * and therefore should be malloced, not allocated via a slot.
1969 		 * Remove the CCB from the incoming queue and add it to the
1970 		 * active queue.
1971 		 */
1972 		TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
1973 		TAILQ_INSERT_TAIL(&softc->active_queue, io_req, links);
1974 
1975 		xpt_action(ccb);
1976 
1977 		/*
1978 		 * If this is not a queued CCB (i.e. it is an immediate CCB),
1979 		 * then it is already done.  We need to put it on the done
1980 		 * queue for the user to fetch.
1981 		 */
1982 		if ((fc & XPT_FC_QUEUED) == 0) {
1983 			TAILQ_REMOVE(&softc->active_queue, io_req, links);
1984 			TAILQ_INSERT_TAIL(&softc->done_queue, io_req, links);
1985 		}
1986 		break;
1987 	}
1988 	case CAMIOGET:
1989 	{
1990 		union ccb **user_ccb;
1991 		struct pass_io_req *io_req;
1992 		int old_error;
1993 
1994 		user_ccb = (union ccb **)addr;
1995 		old_error = 0;
1996 
1997 		io_req = TAILQ_FIRST(&softc->done_queue);
1998 		if (io_req == NULL) {
1999 			error = ENOENT;
2000 			break;
2001 		}
2002 
2003 		/*
2004 		 * Remove the I/O from the done queue.
2005 		 */
2006 		TAILQ_REMOVE(&softc->done_queue, io_req, links);
2007 
2008 		/*
2009 		 * We have to drop the lock during the copyout because the
2010 		 * copyout can result in VM faults that require sleeping.
2011 		 */
2012 		cam_periph_unlock(periph);
2013 
2014 		/*
2015 		 * Do any needed copies (e.g. for reads) and revert the
2016 		 * pointers in the CCB back to the user's pointers.
2017 		 */
2018 		error = passmemdone(periph, io_req);
2019 
2020 		old_error = error;
2021 
2022 		io_req->ccb.ccb_h.periph_links = io_req->user_periph_links;
2023 		io_req->ccb.ccb_h.periph_priv = io_req->user_periph_priv;
2024 
2025 #if 0
2026 		xpt_print(periph->path, "Copying to user CCB %p from "
2027 			  "kernel address %p\n", *user_ccb, &io_req->ccb);
2028 #endif
2029 
2030 		error = copyout(&io_req->ccb, *user_ccb, sizeof(union ccb));
2031 		if (error != 0) {
2032 			xpt_print(periph->path, "Copy to user CCB %p from "
2033 				  "kernel address %p failed with error %d\n",
2034 				  *user_ccb, &io_req->ccb, error);
2035 		}
2036 
2037 		/*
2038 		 * Prefer the first error we got back, and make sure we
2039 		 * don't overwrite bad status with good.
2040 		 */
2041 		if (old_error != 0)
2042 			error = old_error;
2043 
2044 		cam_periph_lock(periph);
2045 
2046 		/*
2047 		 * At this point, if there was an error, we could potentially
2048 		 * re-queue the I/O and try again.  But why?  The error
2049 		 * would almost certainly happen again.  We might as well
2050 		 * not leak memory.
2051 		 */
2052 		uma_zfree(softc->pass_zone, io_req);
2053 		break;
2054 	}
2055 	default:
2056 		error = cam_periph_ioctl(periph, cmd, addr, passerror);
2057 		break;
2058 	}
2059 
2060 bailout:
2061 	cam_periph_unlock(periph);
2062 
2063 	return(error);
2064 }
2065 
2066 static int
2067 passpoll(struct cdev *dev, int poll_events, struct thread *td)
2068 {
2069 	struct cam_periph *periph;
2070 	struct pass_softc *softc;
2071 	int revents;
2072 
2073 	periph = (struct cam_periph *)dev->si_drv1;
2074 	softc = (struct pass_softc *)periph->softc;
2075 
2076 	revents = poll_events & (POLLOUT | POLLWRNORM);
2077 	if ((poll_events & (POLLIN | POLLRDNORM)) != 0) {
2078 		cam_periph_lock(periph);
2079 
2080 		if (!TAILQ_EMPTY(&softc->done_queue)) {
2081 			revents |= poll_events & (POLLIN | POLLRDNORM);
2082 		}
2083 		cam_periph_unlock(periph);
2084 		if (revents == 0)
2085 			selrecord(td, &softc->read_select);
2086 	}
2087 
2088 	return (revents);
2089 }
2090 
2091 static int
2092 passkqfilter(struct cdev *dev, struct knote *kn)
2093 {
2094 	struct cam_periph *periph;
2095 	struct pass_softc *softc;
2096 
2097 	periph = (struct cam_periph *)dev->si_drv1;
2098 	softc = (struct pass_softc *)periph->softc;
2099 
2100 	kn->kn_hook = (caddr_t)periph;
2101 	kn->kn_fop = &passread_filtops;
2102 	knlist_add(&softc->read_select.si_note, kn, 0);
2103 
2104 	return (0);
2105 }
2106 
2107 static void
2108 passreadfiltdetach(struct knote *kn)
2109 {
2110 	struct cam_periph *periph;
2111 	struct pass_softc *softc;
2112 
2113 	periph = (struct cam_periph *)kn->kn_hook;
2114 	softc = (struct pass_softc *)periph->softc;
2115 
2116 	knlist_remove(&softc->read_select.si_note, kn, 0);
2117 }
2118 
2119 static int
2120 passreadfilt(struct knote *kn, long hint)
2121 {
2122 	struct cam_periph *periph;
2123 	struct pass_softc *softc;
2124 	int retval;
2125 
2126 	periph = (struct cam_periph *)kn->kn_hook;
2127 	softc = (struct pass_softc *)periph->softc;
2128 
2129 	cam_periph_assert(periph, MA_OWNED);
2130 
2131 	if (TAILQ_EMPTY(&softc->done_queue))
2132 		retval = 0;
2133 	else
2134 		retval = 1;
2135 
2136 	return (retval);
2137 }
2138 
2139 /*
2140  * Generally, "ccb" should be the CCB supplied by the kernel.  "inccb"
2141  * should be the CCB that is copied in from the user.
2142  */
2143 static int
2144 passsendccb(struct cam_periph *periph, union ccb *ccb, union ccb *inccb)
2145 {
2146 	struct pass_softc *softc;
2147 	struct cam_periph_map_info mapinfo;
2148 	xpt_opcode fc;
2149 	int error;
2150 
2151 	softc = (struct pass_softc *)periph->softc;
2152 
2153 	/*
2154 	 * There are some fields in the CCB header that need to be
2155 	 * preserved, the rest we get from the user.
2156 	 */
2157 	xpt_merge_ccb(ccb, inccb);
2158 
2159 	/*
2160 	 */
2161 	ccb->ccb_h.cbfcnp = passdone;
2162 
2163 	/*
2164 	 * Let cam_periph_mapmem do a sanity check on the data pointer format.
2165 	 * Even if no data transfer is needed, it's a cheap check and it
2166 	 * simplifies the code.
2167 	 */
2168 	fc = ccb->ccb_h.func_code;
2169 	if ((fc == XPT_SCSI_IO) || (fc == XPT_ATA_IO) || (fc == XPT_SMP_IO)
2170 	 || (fc == XPT_DEV_MATCH) || (fc == XPT_DEV_ADVINFO)) {
2171 		bzero(&mapinfo, sizeof(mapinfo));
2172 
2173 		/*
2174 		 * cam_periph_mapmem calls into proc and vm functions that can
2175 		 * sleep as well as trigger I/O, so we can't hold the lock.
2176 		 * Dropping it here is reasonably safe.
2177 		 */
2178 		cam_periph_unlock(periph);
2179 		error = cam_periph_mapmem(ccb, &mapinfo, softc->maxio);
2180 		cam_periph_lock(periph);
2181 
2182 		/*
2183 		 * cam_periph_mapmem returned an error, we can't continue.
2184 		 * Return the error to the user.
2185 		 */
2186 		if (error)
2187 			return(error);
2188 	} else
2189 		/* Ensure that the unmap call later on is a no-op. */
2190 		mapinfo.num_bufs_used = 0;
2191 
2192 	/*
2193 	 * If the user wants us to perform any error recovery, then honor
2194 	 * that request.  Otherwise, it's up to the user to perform any
2195 	 * error recovery.
2196 	 */
2197 	cam_periph_runccb(ccb, passerror, /* cam_flags */ CAM_RETRY_SELTO,
2198 	    /* sense_flags */ ((ccb->ccb_h.flags & CAM_PASS_ERR_RECOVER) ?
2199 	     SF_RETRY_UA : SF_NO_RECOVERY) | SF_NO_PRINT,
2200 	    softc->device_stats);
2201 
2202 	cam_periph_unmapmem(ccb, &mapinfo);
2203 
2204 	ccb->ccb_h.cbfcnp = NULL;
2205 	ccb->ccb_h.periph_priv = inccb->ccb_h.periph_priv;
2206 	bcopy(ccb, inccb, sizeof(union ccb));
2207 
2208 	return(0);
2209 }
2210 
2211 static int
2212 passerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2213 {
2214 	struct cam_periph *periph;
2215 	struct pass_softc *softc;
2216 
2217 	periph = xpt_path_periph(ccb->ccb_h.path);
2218 	softc = (struct pass_softc *)periph->softc;
2219 
2220 	return(cam_periph_error(ccb, cam_flags, sense_flags,
2221 				 &softc->saved_ccb));
2222 }
2223