xref: /freebsd/sys/cam/scsi/scsi_pass.c (revision a476e3a5678de5ca7ad765315f28308410d4f09e)
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 	int    no_tags;
552 
553 	cgd = (struct ccb_getdev *)arg;
554 	if (cgd == NULL) {
555 		printf("%s: no getdev CCB, can't register device\n", __func__);
556 		return(CAM_REQ_CMP_ERR);
557 	}
558 
559 	softc = (struct pass_softc *)malloc(sizeof(*softc),
560 					    M_DEVBUF, M_NOWAIT);
561 
562 	if (softc == NULL) {
563 		printf("%s: Unable to probe new device. "
564 		       "Unable to allocate softc\n", __func__);
565 		return(CAM_REQ_CMP_ERR);
566 	}
567 
568 	bzero(softc, sizeof(*softc));
569 	softc->state = PASS_STATE_NORMAL;
570 	if (cgd->protocol == PROTO_SCSI || cgd->protocol == PROTO_ATAPI)
571 		softc->pd_type = SID_TYPE(&cgd->inq_data);
572 	else if (cgd->protocol == PROTO_SATAPM)
573 		softc->pd_type = T_ENCLOSURE;
574 	else
575 		softc->pd_type = T_DIRECT;
576 
577 	periph->softc = softc;
578 	softc->periph = periph;
579 	TAILQ_INIT(&softc->incoming_queue);
580 	TAILQ_INIT(&softc->active_queue);
581 	TAILQ_INIT(&softc->abandoned_queue);
582 	TAILQ_INIT(&softc->done_queue);
583 	snprintf(softc->zone_name, sizeof(softc->zone_name), "%s%d",
584 		 periph->periph_name, periph->unit_number);
585 	snprintf(softc->io_zone_name, sizeof(softc->io_zone_name), "%s%dIO",
586 		 periph->periph_name, periph->unit_number);
587 	softc->io_zone_size = MAXPHYS;
588 	knlist_init_mtx(&softc->read_select.si_note, cam_periph_mtx(periph));
589 
590 	bzero(&cpi, sizeof(cpi));
591 	xpt_setup_ccb(&cpi.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
592 	cpi.ccb_h.func_code = XPT_PATH_INQ;
593 	xpt_action((union ccb *)&cpi);
594 
595 	if (cpi.maxio == 0)
596 		softc->maxio = DFLTPHYS;	/* traditional default */
597 	else if (cpi.maxio > MAXPHYS)
598 		softc->maxio = MAXPHYS;		/* for safety */
599 	else
600 		softc->maxio = cpi.maxio;	/* real value */
601 
602 	if (cpi.hba_misc & PIM_UNMAPPED)
603 		softc->flags |= PASS_FLAG_UNMAPPED_CAPABLE;
604 
605 	/*
606 	 * We pass in 0 for a blocksize, since we don't
607 	 * know what the blocksize of this device is, if
608 	 * it even has a blocksize.
609 	 */
610 	cam_periph_unlock(periph);
611 	no_tags = (cgd->inq_data.flags & SID_CmdQue) == 0;
612 	softc->device_stats = devstat_new_entry("pass",
613 			  periph->unit_number, 0,
614 			  DEVSTAT_NO_BLOCKSIZE
615 			  | (no_tags ? DEVSTAT_NO_ORDERED_TAGS : 0),
616 			  softc->pd_type |
617 			  XPORT_DEVSTAT_TYPE(cpi.transport) |
618 			  DEVSTAT_TYPE_PASS,
619 			  DEVSTAT_PRIORITY_PASS);
620 
621 	/*
622 	 * Initialize the taskqueue handler for shutting down kqueue.
623 	 */
624 	TASK_INIT(&softc->shutdown_kqueue_task, /*priority*/ 0,
625 		  pass_shutdown_kqueue, periph);
626 
627 	/*
628 	 * Acquire a reference to the periph that we can release once we've
629 	 * cleaned up the kqueue.
630 	 */
631 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
632 		xpt_print(periph->path, "%s: lost periph during "
633 			  "registration!\n", __func__);
634 		cam_periph_lock(periph);
635 		return (CAM_REQ_CMP_ERR);
636 	}
637 
638 	/*
639 	 * Acquire a reference to the periph before we create the devfs
640 	 * instance for it.  We'll release this reference once the devfs
641 	 * instance has been freed.
642 	 */
643 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
644 		xpt_print(periph->path, "%s: lost periph during "
645 			  "registration!\n", __func__);
646 		cam_periph_lock(periph);
647 		return (CAM_REQ_CMP_ERR);
648 	}
649 
650 	/* Register the device */
651 	softc->dev = make_dev(&pass_cdevsw, periph->unit_number,
652 			      UID_ROOT, GID_OPERATOR, 0600, "%s%d",
653 			      periph->periph_name, periph->unit_number);
654 
655 	/*
656 	 * Hold a reference to the periph before we create the physical
657 	 * path alias so it can't go away.
658 	 */
659 	if (cam_periph_acquire(periph) != CAM_REQ_CMP) {
660 		xpt_print(periph->path, "%s: lost periph during "
661 			  "registration!\n", __func__);
662 		cam_periph_lock(periph);
663 		return (CAM_REQ_CMP_ERR);
664 	}
665 
666 	cam_periph_lock(periph);
667 	softc->dev->si_drv1 = periph;
668 
669 	TASK_INIT(&softc->add_physpath_task, /*priority*/0,
670 		  pass_add_physpath, periph);
671 
672 	/*
673 	 * See if physical path information is already available.
674 	 */
675 	taskqueue_enqueue(taskqueue_thread, &softc->add_physpath_task);
676 
677 	/*
678 	 * Add an async callback so that we get notified if
679 	 * this device goes away or its physical path
680 	 * (stored in the advanced info data of the EDT) has
681 	 * changed.
682 	 */
683 	xpt_register_async(AC_LOST_DEVICE | AC_ADVINFO_CHANGED,
684 			   passasync, periph, periph->path);
685 
686 	if (bootverbose)
687 		xpt_announce_periph(periph, NULL);
688 
689 	return(CAM_REQ_CMP);
690 }
691 
692 static int
693 passopen(struct cdev *dev, int flags, int fmt, struct thread *td)
694 {
695 	struct cam_periph *periph;
696 	struct pass_softc *softc;
697 	int error;
698 
699 	periph = (struct cam_periph *)dev->si_drv1;
700 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
701 		return (ENXIO);
702 
703 	cam_periph_lock(periph);
704 
705 	softc = (struct pass_softc *)periph->softc;
706 
707 	if (softc->flags & PASS_FLAG_INVALID) {
708 		cam_periph_release_locked(periph);
709 		cam_periph_unlock(periph);
710 		return(ENXIO);
711 	}
712 
713 	/*
714 	 * Don't allow access when we're running at a high securelevel.
715 	 */
716 	error = securelevel_gt(td->td_ucred, 1);
717 	if (error) {
718 		cam_periph_release_locked(periph);
719 		cam_periph_unlock(periph);
720 		return(error);
721 	}
722 
723 	/*
724 	 * Only allow read-write access.
725 	 */
726 	if (((flags & FWRITE) == 0) || ((flags & FREAD) == 0)) {
727 		cam_periph_release_locked(periph);
728 		cam_periph_unlock(periph);
729 		return(EPERM);
730 	}
731 
732 	/*
733 	 * We don't allow nonblocking access.
734 	 */
735 	if ((flags & O_NONBLOCK) != 0) {
736 		xpt_print(periph->path, "can't do nonblocking access\n");
737 		cam_periph_release_locked(periph);
738 		cam_periph_unlock(periph);
739 		return(EINVAL);
740 	}
741 
742 	softc->open_count++;
743 
744 	cam_periph_unlock(periph);
745 
746 	return (error);
747 }
748 
749 static int
750 passclose(struct cdev *dev, int flag, int fmt, struct thread *td)
751 {
752 	struct 	cam_periph *periph;
753 	struct  pass_softc *softc;
754 	struct mtx *mtx;
755 
756 	periph = (struct cam_periph *)dev->si_drv1;
757 	if (periph == NULL)
758 		return (ENXIO);
759 	mtx = cam_periph_mtx(periph);
760 	mtx_lock(mtx);
761 
762 	softc = periph->softc;
763 	softc->open_count--;
764 
765 	if (softc->open_count == 0) {
766 		struct pass_io_req *io_req, *io_req2;
767 		int need_unlock;
768 
769 		need_unlock = 0;
770 
771 		TAILQ_FOREACH_SAFE(io_req, &softc->done_queue, links, io_req2) {
772 			TAILQ_REMOVE(&softc->done_queue, io_req, links);
773 			passiocleanup(softc, io_req);
774 			uma_zfree(softc->pass_zone, io_req);
775 		}
776 
777 		TAILQ_FOREACH_SAFE(io_req, &softc->incoming_queue, links,
778 				   io_req2) {
779 			TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
780 			passiocleanup(softc, io_req);
781 			uma_zfree(softc->pass_zone, io_req);
782 		}
783 
784 		/*
785 		 * If there are any active I/Os, we need to forcibly acquire a
786 		 * reference to the peripheral so that we don't go away
787 		 * before they complete.  We'll release the reference when
788 		 * the abandoned queue is empty.
789 		 */
790 		io_req = TAILQ_FIRST(&softc->active_queue);
791 		if ((io_req != NULL)
792 		 && (softc->flags & PASS_FLAG_ABANDONED_REF_SET) == 0) {
793 			cam_periph_doacquire(periph);
794 			softc->flags |= PASS_FLAG_ABANDONED_REF_SET;
795 		}
796 
797 		/*
798 		 * Since the I/O in the active queue is not under our
799 		 * control, just set a flag so that we can clean it up when
800 		 * it completes and put it on the abandoned queue.  This
801 		 * will prevent our sending spurious completions in the
802 		 * event that the device is opened again before these I/Os
803 		 * complete.
804 		 */
805 		TAILQ_FOREACH_SAFE(io_req, &softc->active_queue, links,
806 				   io_req2) {
807 			TAILQ_REMOVE(&softc->active_queue, io_req, links);
808 			io_req->flags |= PASS_IO_ABANDONED;
809 			TAILQ_INSERT_TAIL(&softc->abandoned_queue, io_req,
810 					  links);
811 		}
812 	}
813 
814 	cam_periph_release_locked(periph);
815 
816 	/*
817 	 * We reference the lock directly here, instead of using
818 	 * cam_periph_unlock().  The reason is that the call to
819 	 * cam_periph_release_locked() above could result in the periph
820 	 * getting freed.  If that is the case, dereferencing the periph
821 	 * with a cam_periph_unlock() call would cause a page fault.
822 	 *
823 	 * cam_periph_release() avoids this problem using the same method,
824 	 * but we're manually acquiring and dropping the lock here to
825 	 * protect the open count and avoid another lock acquisition and
826 	 * release.
827 	 */
828 	mtx_unlock(mtx);
829 
830 	return (0);
831 }
832 
833 
834 static void
835 passstart(struct cam_periph *periph, union ccb *start_ccb)
836 {
837 	struct pass_softc *softc;
838 
839 	softc = (struct pass_softc *)periph->softc;
840 
841 	switch (softc->state) {
842 	case PASS_STATE_NORMAL: {
843 		struct pass_io_req *io_req;
844 
845 		/*
846 		 * Check for any queued I/O requests that require an
847 		 * allocated slot.
848 		 */
849 		io_req = TAILQ_FIRST(&softc->incoming_queue);
850 		if (io_req == NULL) {
851 			xpt_release_ccb(start_ccb);
852 			break;
853 		}
854 		TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
855 		TAILQ_INSERT_TAIL(&softc->active_queue, io_req, links);
856 		/*
857 		 * Merge the user's CCB into the allocated CCB.
858 		 */
859 		xpt_merge_ccb(start_ccb, &io_req->ccb);
860 		start_ccb->ccb_h.ccb_type = PASS_CCB_QUEUED_IO;
861 		start_ccb->ccb_h.ccb_ioreq = io_req;
862 		start_ccb->ccb_h.cbfcnp = passdone;
863 		io_req->alloced_ccb = start_ccb;
864 		binuptime(&io_req->start_time);
865 		devstat_start_transaction(softc->device_stats,
866 					  &io_req->start_time);
867 
868 		xpt_action(start_ccb);
869 
870 		/*
871 		 * If we have any more I/O waiting, schedule ourselves again.
872 		 */
873 		if (!TAILQ_EMPTY(&softc->incoming_queue))
874 			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
875 		break;
876 	}
877 	default:
878 		break;
879 	}
880 }
881 
882 static void
883 passdone(struct cam_periph *periph, union ccb *done_ccb)
884 {
885 	struct pass_softc *softc;
886 	struct ccb_scsiio *csio;
887 
888 	softc = (struct pass_softc *)periph->softc;
889 
890 	cam_periph_assert(periph, MA_OWNED);
891 
892 	csio = &done_ccb->csio;
893 	switch (csio->ccb_h.ccb_type) {
894 	case PASS_CCB_QUEUED_IO: {
895 		struct pass_io_req *io_req;
896 
897 		io_req = done_ccb->ccb_h.ccb_ioreq;
898 #if 0
899 		xpt_print(periph->path, "%s: called for user CCB %p\n",
900 			  __func__, io_req->user_ccb_ptr);
901 #endif
902 		if (((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)
903 		 && (done_ccb->ccb_h.flags & CAM_PASS_ERR_RECOVER)
904 		 && ((io_req->flags & PASS_IO_ABANDONED) == 0)) {
905 			int error;
906 
907 			error = passerror(done_ccb, CAM_RETRY_SELTO,
908 					  SF_RETRY_UA | SF_NO_PRINT);
909 
910 			if (error == ERESTART) {
911 				/*
912 				 * A retry was scheduled, so
913  				 * just return.
914 				 */
915 				return;
916 			}
917 		}
918 
919 		/*
920 		 * Copy the allocated CCB contents back to the malloced CCB
921 		 * so we can give status back to the user when he requests it.
922 		 */
923 		bcopy(done_ccb, &io_req->ccb, sizeof(*done_ccb));
924 
925 		/*
926 		 * Log data/transaction completion with devstat(9).
927 		 */
928 		switch (done_ccb->ccb_h.func_code) {
929 		case XPT_SCSI_IO:
930 			devstat_end_transaction(softc->device_stats,
931 			    done_ccb->csio.dxfer_len - done_ccb->csio.resid,
932 			    done_ccb->csio.tag_action & 0x3,
933 			    ((done_ccb->ccb_h.flags & CAM_DIR_MASK) ==
934 			    CAM_DIR_NONE) ? DEVSTAT_NO_DATA :
935 			    (done_ccb->ccb_h.flags & CAM_DIR_OUT) ?
936 			    DEVSTAT_WRITE : DEVSTAT_READ, NULL,
937 			    &io_req->start_time);
938 			break;
939 		case XPT_ATA_IO:
940 			devstat_end_transaction(softc->device_stats,
941 			    done_ccb->ataio.dxfer_len - done_ccb->ataio.resid,
942 			    done_ccb->ataio.tag_action & 0x3,
943 			    ((done_ccb->ccb_h.flags & CAM_DIR_MASK) ==
944 			    CAM_DIR_NONE) ? DEVSTAT_NO_DATA :
945 			    (done_ccb->ccb_h.flags & CAM_DIR_OUT) ?
946 			    DEVSTAT_WRITE : DEVSTAT_READ, NULL,
947 			    &io_req->start_time);
948 			break;
949 		case XPT_SMP_IO:
950 			/*
951 			 * XXX KDM this isn't quite right, but there isn't
952 			 * currently an easy way to represent a bidirectional
953 			 * transfer in devstat.  The only way to do it
954 			 * and have the byte counts come out right would
955 			 * mean that we would have to record two
956 			 * transactions, one for the request and one for the
957 			 * response.  For now, so that we report something,
958 			 * just treat the entire thing as a read.
959 			 */
960 			devstat_end_transaction(softc->device_stats,
961 			    done_ccb->smpio.smp_request_len +
962 			    done_ccb->smpio.smp_response_len,
963 			    DEVSTAT_TAG_SIMPLE, DEVSTAT_READ, NULL,
964 			    &io_req->start_time);
965 			break;
966 		default:
967 			devstat_end_transaction(softc->device_stats, 0,
968 			    DEVSTAT_TAG_NONE, DEVSTAT_NO_DATA, NULL,
969 			    &io_req->start_time);
970 			break;
971 		}
972 
973 		/*
974 		 * In the normal case, take the completed I/O off of the
975 		 * active queue and put it on the done queue.  Notitfy the
976 		 * user that we have a completed I/O.
977 		 */
978 		if ((io_req->flags & PASS_IO_ABANDONED) == 0) {
979 			TAILQ_REMOVE(&softc->active_queue, io_req, links);
980 			TAILQ_INSERT_TAIL(&softc->done_queue, io_req, links);
981 			selwakeuppri(&softc->read_select, PRIBIO);
982 			KNOTE_LOCKED(&softc->read_select.si_note, 0);
983 		} else {
984 			/*
985 			 * In the case of an abandoned I/O (final close
986 			 * without fetching the I/O), take it off of the
987 			 * abandoned queue and free it.
988 			 */
989 			TAILQ_REMOVE(&softc->abandoned_queue, io_req, links);
990 			passiocleanup(softc, io_req);
991 			uma_zfree(softc->pass_zone, io_req);
992 
993 			/*
994 			 * Release the done_ccb here, since we may wind up
995 			 * freeing the peripheral when we decrement the
996 			 * reference count below.
997 			 */
998 			xpt_release_ccb(done_ccb);
999 
1000 			/*
1001 			 * If the abandoned queue is empty, we can release
1002 			 * our reference to the periph since we won't have
1003 			 * any more completions coming.
1004 			 */
1005 			if ((TAILQ_EMPTY(&softc->abandoned_queue))
1006 			 && (softc->flags & PASS_FLAG_ABANDONED_REF_SET)) {
1007 				softc->flags &= ~PASS_FLAG_ABANDONED_REF_SET;
1008 				cam_periph_release_locked(periph);
1009 			}
1010 
1011 			/*
1012 			 * We have already released the CCB, so we can
1013 			 * return.
1014 			 */
1015 			return;
1016 		}
1017 		break;
1018 	}
1019 	}
1020 	xpt_release_ccb(done_ccb);
1021 }
1022 
1023 static int
1024 passcreatezone(struct cam_periph *periph)
1025 {
1026 	struct pass_softc *softc;
1027 	int error;
1028 
1029 	error = 0;
1030 	softc = (struct pass_softc *)periph->softc;
1031 
1032 	cam_periph_assert(periph, MA_OWNED);
1033 	KASSERT(((softc->flags & PASS_FLAG_ZONE_VALID) == 0),
1034 		("%s called when the pass(4) zone is valid!\n", __func__));
1035 	KASSERT((softc->pass_zone == NULL),
1036 		("%s called when the pass(4) zone is allocated!\n", __func__));
1037 
1038 	if ((softc->flags & PASS_FLAG_ZONE_INPROG) == 0) {
1039 
1040 		/*
1041 		 * We're the first context through, so we need to create
1042 		 * the pass(4) UMA zone for I/O requests.
1043 		 */
1044 		softc->flags |= PASS_FLAG_ZONE_INPROG;
1045 
1046 		/*
1047 		 * uma_zcreate() does a blocking (M_WAITOK) allocation,
1048 		 * so we cannot hold a mutex while we call it.
1049 		 */
1050 		cam_periph_unlock(periph);
1051 
1052 		softc->pass_zone = uma_zcreate(softc->zone_name,
1053 		    sizeof(struct pass_io_req), NULL, NULL, NULL, NULL,
1054 		    /*align*/ 0, /*flags*/ 0);
1055 
1056 		softc->pass_io_zone = uma_zcreate(softc->io_zone_name,
1057 		    softc->io_zone_size, NULL, NULL, NULL, NULL,
1058 		    /*align*/ 0, /*flags*/ 0);
1059 
1060 		cam_periph_lock(periph);
1061 
1062 		if ((softc->pass_zone == NULL)
1063 		 || (softc->pass_io_zone == NULL)) {
1064 			if (softc->pass_zone == NULL)
1065 				xpt_print(periph->path, "unable to allocate "
1066 				    "IO Req UMA zone\n");
1067 			else
1068 				xpt_print(periph->path, "unable to allocate "
1069 				    "IO UMA zone\n");
1070 			softc->flags &= ~PASS_FLAG_ZONE_INPROG;
1071 			goto bailout;
1072 		}
1073 
1074 		/*
1075 		 * Set the flags appropriately and notify any other waiters.
1076 		 */
1077 		softc->flags &= PASS_FLAG_ZONE_INPROG;
1078 		softc->flags |= PASS_FLAG_ZONE_VALID;
1079 		wakeup(&softc->pass_zone);
1080 	} else {
1081 		/*
1082 		 * In this case, the UMA zone has not yet been created, but
1083 		 * another context is in the process of creating it.  We
1084 		 * need to sleep until the creation is either done or has
1085 		 * failed.
1086 		 */
1087 		while ((softc->flags & PASS_FLAG_ZONE_INPROG)
1088 		    && ((softc->flags & PASS_FLAG_ZONE_VALID) == 0)) {
1089 			error = msleep(&softc->pass_zone,
1090 				       cam_periph_mtx(periph), PRIBIO,
1091 				       "paszon", 0);
1092 			if (error != 0)
1093 				goto bailout;
1094 		}
1095 		/*
1096 		 * If the zone creation failed, no luck for the user.
1097 		 */
1098 		if ((softc->flags & PASS_FLAG_ZONE_VALID) == 0){
1099 			error = ENOMEM;
1100 			goto bailout;
1101 		}
1102 	}
1103 bailout:
1104 	return (error);
1105 }
1106 
1107 static void
1108 passiocleanup(struct pass_softc *softc, struct pass_io_req *io_req)
1109 {
1110 	union ccb *ccb;
1111 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1112 	int i, numbufs;
1113 
1114 	ccb = &io_req->ccb;
1115 
1116 	switch (ccb->ccb_h.func_code) {
1117 	case XPT_DEV_MATCH:
1118 		numbufs = min(io_req->num_bufs, 2);
1119 
1120 		if (numbufs == 1) {
1121 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1122 		} else {
1123 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1124 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1125 		}
1126 		break;
1127 	case XPT_SCSI_IO:
1128 	case XPT_CONT_TARGET_IO:
1129 		data_ptrs[0] = &ccb->csio.data_ptr;
1130 		numbufs = min(io_req->num_bufs, 1);
1131 		break;
1132 	case XPT_ATA_IO:
1133 		data_ptrs[0] = &ccb->ataio.data_ptr;
1134 		numbufs = min(io_req->num_bufs, 1);
1135 		break;
1136 	case XPT_SMP_IO:
1137 		numbufs = min(io_req->num_bufs, 2);
1138 		data_ptrs[0] = &ccb->smpio.smp_request;
1139 		data_ptrs[1] = &ccb->smpio.smp_response;
1140 		break;
1141 	case XPT_DEV_ADVINFO:
1142 		numbufs = min(io_req->num_bufs, 1);
1143 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1144 		break;
1145 	default:
1146 		/* allow ourselves to be swapped once again */
1147 		return;
1148 		break; /* NOTREACHED */
1149 	}
1150 
1151 	if (io_req->flags & PASS_IO_USER_SEG_MALLOC) {
1152 		free(io_req->user_segptr, M_SCSIPASS);
1153 		io_req->user_segptr = NULL;
1154 	}
1155 
1156 	/*
1157 	 * We only want to free memory we malloced.
1158 	 */
1159 	if (io_req->data_flags == CAM_DATA_VADDR) {
1160 		for (i = 0; i < io_req->num_bufs; i++) {
1161 			if (io_req->kern_bufs[i] == NULL)
1162 				continue;
1163 
1164 			free(io_req->kern_bufs[i], M_SCSIPASS);
1165 			io_req->kern_bufs[i] = NULL;
1166 		}
1167 	} else if (io_req->data_flags == CAM_DATA_SG) {
1168 		for (i = 0; i < io_req->num_kern_segs; i++) {
1169 			if ((uint8_t *)(uintptr_t)
1170 			    io_req->kern_segptr[i].ds_addr == NULL)
1171 				continue;
1172 
1173 			uma_zfree(softc->pass_io_zone, (uint8_t *)(uintptr_t)
1174 			    io_req->kern_segptr[i].ds_addr);
1175 			io_req->kern_segptr[i].ds_addr = 0;
1176 		}
1177 	}
1178 
1179 	if (io_req->flags & PASS_IO_KERN_SEG_MALLOC) {
1180 		free(io_req->kern_segptr, M_SCSIPASS);
1181 		io_req->kern_segptr = NULL;
1182 	}
1183 
1184 	if (io_req->data_flags != CAM_DATA_PADDR) {
1185 		for (i = 0; i < numbufs; i++) {
1186 			/*
1187 			 * Restore the user's buffer pointers to their
1188 			 * previous values.
1189 			 */
1190 			if (io_req->user_bufs[i] != NULL)
1191 				*data_ptrs[i] = io_req->user_bufs[i];
1192 		}
1193 	}
1194 
1195 }
1196 
1197 static int
1198 passcopysglist(struct cam_periph *periph, struct pass_io_req *io_req,
1199 	       ccb_flags direction)
1200 {
1201 	bus_size_t kern_watermark, user_watermark, len_copied, len_to_copy;
1202 	bus_dma_segment_t *user_sglist, *kern_sglist;
1203 	int i, j, error;
1204 
1205 	error = 0;
1206 	kern_watermark = 0;
1207 	user_watermark = 0;
1208 	len_to_copy = 0;
1209 	len_copied = 0;
1210 	user_sglist = io_req->user_segptr;
1211 	kern_sglist = io_req->kern_segptr;
1212 
1213 	for (i = 0, j = 0; i < io_req->num_user_segs &&
1214 	     j < io_req->num_kern_segs;) {
1215 		uint8_t *user_ptr, *kern_ptr;
1216 
1217 		len_to_copy = min(user_sglist[i].ds_len -user_watermark,
1218 		    kern_sglist[j].ds_len - kern_watermark);
1219 
1220 		user_ptr = (uint8_t *)(uintptr_t)user_sglist[i].ds_addr;
1221 		user_ptr = user_ptr + user_watermark;
1222 		kern_ptr = (uint8_t *)(uintptr_t)kern_sglist[j].ds_addr;
1223 		kern_ptr = kern_ptr + kern_watermark;
1224 
1225 		user_watermark += len_to_copy;
1226 		kern_watermark += len_to_copy;
1227 
1228 		if (!useracc(user_ptr, len_to_copy,
1229 		    (direction == CAM_DIR_IN) ? VM_PROT_WRITE : VM_PROT_READ)) {
1230 			xpt_print(periph->path, "%s: unable to access user "
1231 				  "S/G list element %p len %zu\n", __func__,
1232 				  user_ptr, len_to_copy);
1233 			error = EFAULT;
1234 			goto bailout;
1235 		}
1236 
1237 		if (direction == CAM_DIR_IN) {
1238 			error = copyout(kern_ptr, user_ptr, len_to_copy);
1239 			if (error != 0) {
1240 				xpt_print(periph->path, "%s: copyout of %u "
1241 					  "bytes from %p to %p failed with "
1242 					  "error %d\n", __func__, len_to_copy,
1243 					  kern_ptr, user_ptr, error);
1244 				goto bailout;
1245 			}
1246 		} else {
1247 			error = copyin(user_ptr, kern_ptr, len_to_copy);
1248 			if (error != 0) {
1249 				xpt_print(periph->path, "%s: copyin of %u "
1250 					  "bytes from %p to %p failed with "
1251 					  "error %d\n", __func__, len_to_copy,
1252 					  user_ptr, kern_ptr, error);
1253 				goto bailout;
1254 			}
1255 		}
1256 
1257 		len_copied += len_to_copy;
1258 
1259 		if (user_sglist[i].ds_len == user_watermark) {
1260 			i++;
1261 			user_watermark = 0;
1262 		}
1263 
1264 		if (kern_sglist[j].ds_len == kern_watermark) {
1265 			j++;
1266 			kern_watermark = 0;
1267 		}
1268 	}
1269 
1270 bailout:
1271 
1272 	return (error);
1273 }
1274 
1275 static int
1276 passmemsetup(struct cam_periph *periph, struct pass_io_req *io_req)
1277 {
1278 	union ccb *ccb;
1279 	struct pass_softc *softc;
1280 	int numbufs, i;
1281 	uint8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1282 	uint32_t lengths[CAM_PERIPH_MAXMAPS];
1283 	uint32_t dirs[CAM_PERIPH_MAXMAPS];
1284 	uint32_t num_segs;
1285 	uint16_t *seg_cnt_ptr;
1286 	size_t maxmap;
1287 	int error;
1288 
1289 	cam_periph_assert(periph, MA_NOTOWNED);
1290 
1291 	softc = periph->softc;
1292 
1293 	error = 0;
1294 	ccb = &io_req->ccb;
1295 	maxmap = 0;
1296 	num_segs = 0;
1297 	seg_cnt_ptr = NULL;
1298 
1299 	switch(ccb->ccb_h.func_code) {
1300 	case XPT_DEV_MATCH:
1301 		if (ccb->cdm.match_buf_len == 0) {
1302 			printf("%s: invalid match buffer length 0\n", __func__);
1303 			return(EINVAL);
1304 		}
1305 		if (ccb->cdm.pattern_buf_len > 0) {
1306 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1307 			lengths[0] = ccb->cdm.pattern_buf_len;
1308 			dirs[0] = CAM_DIR_OUT;
1309 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1310 			lengths[1] = ccb->cdm.match_buf_len;
1311 			dirs[1] = CAM_DIR_IN;
1312 			numbufs = 2;
1313 		} else {
1314 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1315 			lengths[0] = ccb->cdm.match_buf_len;
1316 			dirs[0] = CAM_DIR_IN;
1317 			numbufs = 1;
1318 		}
1319 		io_req->data_flags = CAM_DATA_VADDR;
1320 		break;
1321 	case XPT_SCSI_IO:
1322 	case XPT_CONT_TARGET_IO:
1323 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
1324 			return(0);
1325 
1326 		/*
1327 		 * The user shouldn't be able to supply a bio.
1328 		 */
1329 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) == CAM_DATA_BIO)
1330 			return (EINVAL);
1331 
1332 		io_req->data_flags = ccb->ccb_h.flags & CAM_DATA_MASK;
1333 
1334 		data_ptrs[0] = &ccb->csio.data_ptr;
1335 		lengths[0] = ccb->csio.dxfer_len;
1336 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1337 		num_segs = ccb->csio.sglist_cnt;
1338 		seg_cnt_ptr = &ccb->csio.sglist_cnt;
1339 		numbufs = 1;
1340 		maxmap = softc->maxio;
1341 		break;
1342 	case XPT_ATA_IO:
1343 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
1344 			return(0);
1345 
1346 		/*
1347 		 * We only support a single virtual address for ATA I/O.
1348 		 */
1349 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
1350 			return (EINVAL);
1351 
1352 		io_req->data_flags = CAM_DATA_VADDR;
1353 
1354 		data_ptrs[0] = &ccb->ataio.data_ptr;
1355 		lengths[0] = ccb->ataio.dxfer_len;
1356 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1357 		numbufs = 1;
1358 		maxmap = softc->maxio;
1359 		break;
1360 	case XPT_SMP_IO:
1361 		io_req->data_flags = CAM_DATA_VADDR;
1362 
1363 		data_ptrs[0] = &ccb->smpio.smp_request;
1364 		lengths[0] = ccb->smpio.smp_request_len;
1365 		dirs[0] = CAM_DIR_OUT;
1366 		data_ptrs[1] = &ccb->smpio.smp_response;
1367 		lengths[1] = ccb->smpio.smp_response_len;
1368 		dirs[1] = CAM_DIR_IN;
1369 		numbufs = 2;
1370 		maxmap = softc->maxio;
1371 		break;
1372 	case XPT_DEV_ADVINFO:
1373 		if (ccb->cdai.bufsiz == 0)
1374 			return (0);
1375 
1376 		io_req->data_flags = CAM_DATA_VADDR;
1377 
1378 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1379 		lengths[0] = ccb->cdai.bufsiz;
1380 		dirs[0] = CAM_DIR_IN;
1381 		numbufs = 1;
1382 		break;
1383 	default:
1384 		return(EINVAL);
1385 		break; /* NOTREACHED */
1386 	}
1387 
1388 	io_req->num_bufs = numbufs;
1389 
1390 	/*
1391 	 * If there is a maximum, check to make sure that the user's
1392 	 * request fits within the limit.  In general, we should only have
1393 	 * a maximum length for requests that go to hardware.  Otherwise it
1394 	 * is whatever we're able to malloc.
1395 	 */
1396 	for (i = 0; i < numbufs; i++) {
1397 		io_req->user_bufs[i] = *data_ptrs[i];
1398 		io_req->dirs[i] = dirs[i];
1399 		io_req->lengths[i] = lengths[i];
1400 
1401 		if (maxmap == 0)
1402 			continue;
1403 
1404 		if (lengths[i] <= maxmap)
1405 			continue;
1406 
1407 		xpt_print(periph->path, "%s: data length %u > max allowed %u "
1408 			  "bytes\n", __func__, lengths[i], maxmap);
1409 		error = EINVAL;
1410 		goto bailout;
1411 	}
1412 
1413 	switch (io_req->data_flags) {
1414 	case CAM_DATA_VADDR:
1415 		/* Map or copy the buffer into kernel address space */
1416 		for (i = 0; i < numbufs; i++) {
1417 			uint8_t *tmp_buf;
1418 
1419 			/*
1420 			 * If for some reason no length is specified, we
1421 			 * don't need to allocate anything.
1422 			 */
1423 			if (io_req->lengths[i] == 0)
1424 				continue;
1425 
1426 			/*
1427 			 * Make sure that the user's buffer is accessible
1428 			 * to that process.
1429 			 */
1430 			if (!useracc(io_req->user_bufs[i], io_req->lengths[i],
1431 			    (io_req->dirs[i] == CAM_DIR_IN) ? VM_PROT_WRITE :
1432 			     VM_PROT_READ)) {
1433 				xpt_print(periph->path, "%s: user address %p "
1434 				    "length %u is not accessible\n", __func__,
1435 				    io_req->user_bufs[i], io_req->lengths[i]);
1436 				error = EFAULT;
1437 				goto bailout;
1438 			}
1439 
1440 			tmp_buf = malloc(lengths[i], M_SCSIPASS,
1441 					 M_WAITOK | M_ZERO);
1442 			io_req->kern_bufs[i] = tmp_buf;
1443 			*data_ptrs[i] = tmp_buf;
1444 
1445 #if 0
1446 			xpt_print(periph->path, "%s: malloced %p len %u, user "
1447 				  "buffer %p, operation: %s\n", __func__,
1448 				  tmp_buf, lengths[i], io_req->user_bufs[i],
1449 				  (dirs[i] == CAM_DIR_IN) ? "read" : "write");
1450 #endif
1451 			/*
1452 			 * We only need to copy in if the user is writing.
1453 			 */
1454 			if (dirs[i] != CAM_DIR_OUT)
1455 				continue;
1456 
1457 			error = copyin(io_req->user_bufs[i],
1458 				       io_req->kern_bufs[i], lengths[i]);
1459 			if (error != 0) {
1460 				xpt_print(periph->path, "%s: copy of user "
1461 					  "buffer from %p to %p failed with "
1462 					  "error %d\n", __func__,
1463 					  io_req->user_bufs[i],
1464 					  io_req->kern_bufs[i], error);
1465 				goto bailout;
1466 			}
1467 		}
1468 		break;
1469 	case CAM_DATA_PADDR:
1470 		/* Pass down the pointer as-is */
1471 		break;
1472 	case CAM_DATA_SG: {
1473 		size_t sg_length, size_to_go, alloc_size;
1474 		uint32_t num_segs_needed;
1475 
1476 		/*
1477 		 * Copy the user S/G list in, and then copy in the
1478 		 * individual segments.
1479 		 */
1480 		/*
1481 		 * We shouldn't see this, but check just in case.
1482 		 */
1483 		if (numbufs != 1) {
1484 			xpt_print(periph->path, "%s: cannot currently handle "
1485 				  "more than one S/G list per CCB\n", __func__);
1486 			error = EINVAL;
1487 			goto bailout;
1488 		}
1489 
1490 		/*
1491 		 * We have to have at least one segment.
1492 		 */
1493 		if (num_segs == 0) {
1494 			xpt_print(periph->path, "%s: CAM_DATA_SG flag set, "
1495 				  "but sglist_cnt=0!\n", __func__);
1496 			error = EINVAL;
1497 			goto bailout;
1498 		}
1499 
1500 		/*
1501 		 * Make sure the user specified the total length and didn't
1502 		 * just leave it to us to decode the S/G list.
1503 		 */
1504 		if (lengths[0] == 0) {
1505 			xpt_print(periph->path, "%s: no dxfer_len specified, "
1506 				  "but CAM_DATA_SG flag is set!\n", __func__);
1507 			error = EINVAL;
1508 			goto bailout;
1509 		}
1510 
1511 		/*
1512 		 * We allocate buffers in io_zone_size increments for an
1513 		 * S/G list.  This will generally be MAXPHYS.
1514 		 */
1515 		if (lengths[0] <= softc->io_zone_size)
1516 			num_segs_needed = 1;
1517 		else {
1518 			num_segs_needed = lengths[0] / softc->io_zone_size;
1519 			if ((lengths[0] % softc->io_zone_size) != 0)
1520 				num_segs_needed++;
1521 		}
1522 
1523 		/* Figure out the size of the S/G list */
1524 		sg_length = num_segs * sizeof(bus_dma_segment_t);
1525 		io_req->num_user_segs = num_segs;
1526 		io_req->num_kern_segs = num_segs_needed;
1527 
1528 		/* Save the user's S/G list pointer for later restoration */
1529 		io_req->user_bufs[0] = *data_ptrs[0];
1530 
1531 		/*
1532 		 * If we have enough segments allocated by default to handle
1533 		 * the length of the user's S/G list,
1534 		 */
1535 		if (num_segs > PASS_MAX_SEGS) {
1536 			io_req->user_segptr = malloc(sizeof(bus_dma_segment_t) *
1537 			    num_segs, M_SCSIPASS, M_WAITOK | M_ZERO);
1538 			io_req->flags |= PASS_IO_USER_SEG_MALLOC;
1539 		} else
1540 			io_req->user_segptr = io_req->user_segs;
1541 
1542 		if (!useracc(*data_ptrs[0], sg_length, VM_PROT_READ)) {
1543 			xpt_print(periph->path, "%s: unable to access user "
1544 				  "S/G list at %p\n", __func__, *data_ptrs[0]);
1545 			error = EFAULT;
1546 			goto bailout;
1547 		}
1548 
1549 		error = copyin(*data_ptrs[0], io_req->user_segptr, sg_length);
1550 		if (error != 0) {
1551 			xpt_print(periph->path, "%s: copy of user S/G list "
1552 				  "from %p to %p failed with error %d\n",
1553 				  __func__, *data_ptrs[0], io_req->user_segptr,
1554 				  error);
1555 			goto bailout;
1556 		}
1557 
1558 		if (num_segs_needed > PASS_MAX_SEGS) {
1559 			io_req->kern_segptr = malloc(sizeof(bus_dma_segment_t) *
1560 			    num_segs_needed, M_SCSIPASS, M_WAITOK | M_ZERO);
1561 			io_req->flags |= PASS_IO_KERN_SEG_MALLOC;
1562 		} else {
1563 			io_req->kern_segptr = io_req->kern_segs;
1564 		}
1565 
1566 		/*
1567 		 * Allocate the kernel S/G list.
1568 		 */
1569 		for (size_to_go = lengths[0], i = 0;
1570 		     size_to_go > 0 && i < num_segs_needed;
1571 		     i++, size_to_go -= alloc_size) {
1572 			uint8_t *kern_ptr;
1573 
1574 			alloc_size = min(size_to_go, softc->io_zone_size);
1575 			kern_ptr = uma_zalloc(softc->pass_io_zone, M_WAITOK);
1576 			io_req->kern_segptr[i].ds_addr =
1577 			    (bus_addr_t)(uintptr_t)kern_ptr;
1578 			io_req->kern_segptr[i].ds_len = alloc_size;
1579 		}
1580 		if (size_to_go > 0) {
1581 			printf("%s: size_to_go = %zu, software error!\n",
1582 			       __func__, size_to_go);
1583 			error = EINVAL;
1584 			goto bailout;
1585 		}
1586 
1587 		*data_ptrs[0] = (uint8_t *)io_req->kern_segptr;
1588 		*seg_cnt_ptr = io_req->num_kern_segs;
1589 
1590 		/*
1591 		 * We only need to copy data here if the user is writing.
1592 		 */
1593 		if (dirs[0] == CAM_DIR_OUT)
1594 			error = passcopysglist(periph, io_req, dirs[0]);
1595 		break;
1596 	}
1597 	case CAM_DATA_SG_PADDR: {
1598 		size_t sg_length;
1599 
1600 		/*
1601 		 * We shouldn't see this, but check just in case.
1602 		 */
1603 		if (numbufs != 1) {
1604 			printf("%s: cannot currently handle more than one "
1605 			       "S/G list per CCB\n", __func__);
1606 			error = EINVAL;
1607 			goto bailout;
1608 		}
1609 
1610 		/*
1611 		 * We have to have at least one segment.
1612 		 */
1613 		if (num_segs == 0) {
1614 			xpt_print(periph->path, "%s: CAM_DATA_SG_PADDR flag "
1615 				  "set, but sglist_cnt=0!\n", __func__);
1616 			error = EINVAL;
1617 			goto bailout;
1618 		}
1619 
1620 		/*
1621 		 * Make sure the user specified the total length and didn't
1622 		 * just leave it to us to decode the S/G list.
1623 		 */
1624 		if (lengths[0] == 0) {
1625 			xpt_print(periph->path, "%s: no dxfer_len specified, "
1626 				  "but CAM_DATA_SG flag is set!\n", __func__);
1627 			error = EINVAL;
1628 			goto bailout;
1629 		}
1630 
1631 		/* Figure out the size of the S/G list */
1632 		sg_length = num_segs * sizeof(bus_dma_segment_t);
1633 		io_req->num_user_segs = num_segs;
1634 		io_req->num_kern_segs = io_req->num_user_segs;
1635 
1636 		/* Save the user's S/G list pointer for later restoration */
1637 		io_req->user_bufs[0] = *data_ptrs[0];
1638 
1639 		if (num_segs > PASS_MAX_SEGS) {
1640 			io_req->user_segptr = malloc(sizeof(bus_dma_segment_t) *
1641 			    num_segs, M_SCSIPASS, M_WAITOK | M_ZERO);
1642 			io_req->flags |= PASS_IO_USER_SEG_MALLOC;
1643 		} else
1644 			io_req->user_segptr = io_req->user_segs;
1645 
1646 		io_req->kern_segptr = io_req->user_segptr;
1647 
1648 		error = copyin(*data_ptrs[0], io_req->user_segptr, sg_length);
1649 		if (error != 0) {
1650 			xpt_print(periph->path, "%s: copy of user S/G list "
1651 				  "from %p to %p failed with error %d\n",
1652 				  __func__, *data_ptrs[0], io_req->user_segptr,
1653 				  error);
1654 			goto bailout;
1655 		}
1656 		break;
1657 	}
1658 	default:
1659 	case CAM_DATA_BIO:
1660 		/*
1661 		 * A user shouldn't be attaching a bio to the CCB.  It
1662 		 * isn't a user-accessible structure.
1663 		 */
1664 		error = EINVAL;
1665 		break;
1666 	}
1667 
1668 bailout:
1669 	if (error != 0)
1670 		passiocleanup(softc, io_req);
1671 
1672 	return (error);
1673 }
1674 
1675 static int
1676 passmemdone(struct cam_periph *periph, struct pass_io_req *io_req)
1677 {
1678 	struct pass_softc *softc;
1679 	union ccb *ccb;
1680 	int error;
1681 	int i;
1682 
1683 	error = 0;
1684 	softc = (struct pass_softc *)periph->softc;
1685 	ccb = &io_req->ccb;
1686 
1687 	switch (io_req->data_flags) {
1688 	case CAM_DATA_VADDR:
1689 		/*
1690 		 * Copy back to the user buffer if this was a read.
1691 		 */
1692 		for (i = 0; i < io_req->num_bufs; i++) {
1693 			if (io_req->dirs[i] != CAM_DIR_IN)
1694 				continue;
1695 
1696 			error = copyout(io_req->kern_bufs[i],
1697 			    io_req->user_bufs[i], io_req->lengths[i]);
1698 			if (error != 0) {
1699 				xpt_print(periph->path, "Unable to copy %u "
1700 					  "bytes from %p to user address %p\n",
1701 					  io_req->lengths[i],
1702 					  io_req->kern_bufs[i],
1703 					  io_req->user_bufs[i]);
1704 				goto bailout;
1705 			}
1706 
1707 		}
1708 		break;
1709 	case CAM_DATA_PADDR:
1710 		/* Do nothing.  The pointer is a physical address already */
1711 		break;
1712 	case CAM_DATA_SG:
1713 		/*
1714 		 * Copy back to the user buffer if this was a read.
1715 		 * Restore the user's S/G list buffer pointer.
1716 		 */
1717 		if (io_req->dirs[0] == CAM_DIR_IN)
1718 			error = passcopysglist(periph, io_req, io_req->dirs[0]);
1719 		break;
1720 	case CAM_DATA_SG_PADDR:
1721 		/*
1722 		 * Restore the user's S/G list buffer pointer.  No need to
1723 		 * copy.
1724 		 */
1725 		break;
1726 	default:
1727 	case CAM_DATA_BIO:
1728 		error = EINVAL;
1729 		break;
1730 	}
1731 
1732 bailout:
1733 	/*
1734 	 * Reset the user's pointers to their original values and free
1735 	 * allocated memory.
1736 	 */
1737 	passiocleanup(softc, io_req);
1738 
1739 	return (error);
1740 }
1741 
1742 static int
1743 passioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1744 {
1745 	int error;
1746 
1747 	if ((error = passdoioctl(dev, cmd, addr, flag, td)) == ENOTTY) {
1748 		error = cam_compat_ioctl(dev, cmd, addr, flag, td, passdoioctl);
1749 	}
1750 	return (error);
1751 }
1752 
1753 static int
1754 passdoioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
1755 {
1756 	struct	cam_periph *periph;
1757 	struct	pass_softc *softc;
1758 	int	error;
1759 	uint32_t priority;
1760 
1761 	periph = (struct cam_periph *)dev->si_drv1;
1762 	if (periph == NULL)
1763 		return(ENXIO);
1764 
1765 	cam_periph_lock(periph);
1766 	softc = (struct pass_softc *)periph->softc;
1767 
1768 	error = 0;
1769 
1770 	switch (cmd) {
1771 
1772 	case CAMIOCOMMAND:
1773 	{
1774 		union ccb *inccb;
1775 		union ccb *ccb;
1776 		int ccb_malloced;
1777 
1778 		inccb = (union ccb *)addr;
1779 
1780 		/*
1781 		 * Some CCB types, like scan bus and scan lun can only go
1782 		 * through the transport layer device.
1783 		 */
1784 		if (inccb->ccb_h.func_code & XPT_FC_XPT_ONLY) {
1785 			xpt_print(periph->path, "CCB function code %#x is "
1786 			    "restricted to the XPT device\n",
1787 			    inccb->ccb_h.func_code);
1788 			error = ENODEV;
1789 			break;
1790 		}
1791 
1792 		/* Compatibility for RL/priority-unaware code. */
1793 		priority = inccb->ccb_h.pinfo.priority;
1794 		if (priority <= CAM_PRIORITY_OOB)
1795 		    priority += CAM_PRIORITY_OOB + 1;
1796 
1797 		/*
1798 		 * Non-immediate CCBs need a CCB from the per-device pool
1799 		 * of CCBs, which is scheduled by the transport layer.
1800 		 * Immediate CCBs and user-supplied CCBs should just be
1801 		 * malloced.
1802 		 */
1803 		if ((inccb->ccb_h.func_code & XPT_FC_QUEUED)
1804 		 && ((inccb->ccb_h.func_code & XPT_FC_USER_CCB) == 0)) {
1805 			ccb = cam_periph_getccb(periph, priority);
1806 			ccb_malloced = 0;
1807 		} else {
1808 			ccb = xpt_alloc_ccb_nowait();
1809 
1810 			if (ccb != NULL)
1811 				xpt_setup_ccb(&ccb->ccb_h, periph->path,
1812 					      priority);
1813 			ccb_malloced = 1;
1814 		}
1815 
1816 		if (ccb == NULL) {
1817 			xpt_print(periph->path, "unable to allocate CCB\n");
1818 			error = ENOMEM;
1819 			break;
1820 		}
1821 
1822 		error = passsendccb(periph, ccb, inccb);
1823 
1824 		if (ccb_malloced)
1825 			xpt_free_ccb(ccb);
1826 		else
1827 			xpt_release_ccb(ccb);
1828 
1829 		break;
1830 	}
1831 	case CAMIOQUEUE:
1832 	{
1833 		struct pass_io_req *io_req;
1834 		union ccb **user_ccb, *ccb;
1835 		xpt_opcode fc;
1836 
1837 		if ((softc->flags & PASS_FLAG_ZONE_VALID) == 0) {
1838 			error = passcreatezone(periph);
1839 			if (error != 0)
1840 				goto bailout;
1841 		}
1842 
1843 		/*
1844 		 * We're going to do a blocking allocation for this I/O
1845 		 * request, so we have to drop the lock.
1846 		 */
1847 		cam_periph_unlock(periph);
1848 
1849 		io_req = uma_zalloc(softc->pass_zone, M_WAITOK | M_ZERO);
1850 		ccb = &io_req->ccb;
1851 		user_ccb = (union ccb **)addr;
1852 
1853 		/*
1854 		 * Unlike the CAMIOCOMMAND ioctl above, we only have a
1855 		 * pointer to the user's CCB, so we have to copy the whole
1856 		 * thing in to a buffer we have allocated (above) instead
1857 		 * of allowing the ioctl code to malloc a buffer and copy
1858 		 * it in.
1859 		 *
1860 		 * This is an advantage for this asynchronous interface,
1861 		 * since we don't want the memory to get freed while the
1862 		 * CCB is outstanding.
1863 		 */
1864 #if 0
1865 		xpt_print(periph->path, "Copying user CCB %p to "
1866 			  "kernel address %p\n", *user_ccb, ccb);
1867 #endif
1868 		error = copyin(*user_ccb, ccb, sizeof(*ccb));
1869 		if (error != 0) {
1870 			xpt_print(periph->path, "Copy of user CCB %p to "
1871 				  "kernel address %p failed with error %d\n",
1872 				  *user_ccb, ccb, error);
1873 			uma_zfree(softc->pass_zone, io_req);
1874 			cam_periph_lock(periph);
1875 			break;
1876 		}
1877 
1878 		/*
1879 		 * Some CCB types, like scan bus and scan lun can only go
1880 		 * through the transport layer device.
1881 		 */
1882 		if (ccb->ccb_h.func_code & XPT_FC_XPT_ONLY) {
1883 			xpt_print(periph->path, "CCB function code %#x is "
1884 			    "restricted to the XPT device\n",
1885 			    ccb->ccb_h.func_code);
1886 			uma_zfree(softc->pass_zone, io_req);
1887 			cam_periph_lock(periph);
1888 			error = ENODEV;
1889 			break;
1890 		}
1891 
1892 		/*
1893 		 * Save the user's CCB pointer as well as his linked list
1894 		 * pointers and peripheral private area so that we can
1895 		 * restore these later.
1896 		 */
1897 		io_req->user_ccb_ptr = *user_ccb;
1898 		io_req->user_periph_links = ccb->ccb_h.periph_links;
1899 		io_req->user_periph_priv = ccb->ccb_h.periph_priv;
1900 
1901 		/*
1902 		 * Now that we've saved the user's values, we can set our
1903 		 * own peripheral private entry.
1904 		 */
1905 		ccb->ccb_h.ccb_ioreq = io_req;
1906 
1907 		/* Compatibility for RL/priority-unaware code. */
1908 		priority = ccb->ccb_h.pinfo.priority;
1909 		if (priority <= CAM_PRIORITY_OOB)
1910 		    priority += CAM_PRIORITY_OOB + 1;
1911 
1912 		/*
1913 		 * Setup fields in the CCB like the path and the priority.
1914 		 * The path in particular cannot be done in userland, since
1915 		 * it is a pointer to a kernel data structure.
1916 		 */
1917 		xpt_setup_ccb_flags(&ccb->ccb_h, periph->path, priority,
1918 				    ccb->ccb_h.flags);
1919 
1920 		/*
1921 		 * Setup our done routine.  There is no way for the user to
1922 		 * have a valid pointer here.
1923 		 */
1924 		ccb->ccb_h.cbfcnp = passdone;
1925 
1926 		fc = ccb->ccb_h.func_code;
1927 		/*
1928 		 * If this function code has memory that can be mapped in
1929 		 * or out, we need to call passmemsetup().
1930 		 */
1931 		if ((fc == XPT_SCSI_IO) || (fc == XPT_ATA_IO)
1932 		 || (fc == XPT_SMP_IO) || (fc == XPT_DEV_MATCH)
1933 		 || (fc == XPT_DEV_ADVINFO)) {
1934 			error = passmemsetup(periph, io_req);
1935 			if (error != 0) {
1936 				uma_zfree(softc->pass_zone, io_req);
1937 				cam_periph_lock(periph);
1938 				break;
1939 			}
1940 		} else
1941 			io_req->mapinfo.num_bufs_used = 0;
1942 
1943 		cam_periph_lock(periph);
1944 
1945 		/*
1946 		 * Everything goes on the incoming queue initially.
1947 		 */
1948 		TAILQ_INSERT_TAIL(&softc->incoming_queue, io_req, links);
1949 
1950 		/*
1951 		 * If the CCB is queued, and is not a user CCB, then
1952 		 * we need to allocate a slot for it.  Call xpt_schedule()
1953 		 * so that our start routine will get called when a CCB is
1954 		 * available.
1955 		 */
1956 		if ((fc & XPT_FC_QUEUED)
1957 		 && ((fc & XPT_FC_USER_CCB) == 0)) {
1958 			xpt_schedule(periph, priority);
1959 			break;
1960 		}
1961 
1962 		/*
1963 		 * At this point, the CCB in question is either an
1964 		 * immediate CCB (like XPT_DEV_ADVINFO) or it is a user CCB
1965 		 * and therefore should be malloced, not allocated via a slot.
1966 		 * Remove the CCB from the incoming queue and add it to the
1967 		 * active queue.
1968 		 */
1969 		TAILQ_REMOVE(&softc->incoming_queue, io_req, links);
1970 		TAILQ_INSERT_TAIL(&softc->active_queue, io_req, links);
1971 
1972 		xpt_action(ccb);
1973 
1974 		/*
1975 		 * If this is not a queued CCB (i.e. it is an immediate CCB),
1976 		 * then it is already done.  We need to put it on the done
1977 		 * queue for the user to fetch.
1978 		 */
1979 		if ((fc & XPT_FC_QUEUED) == 0) {
1980 			TAILQ_REMOVE(&softc->active_queue, io_req, links);
1981 			TAILQ_INSERT_TAIL(&softc->done_queue, io_req, links);
1982 		}
1983 		break;
1984 	}
1985 	case CAMIOGET:
1986 	{
1987 		union ccb **user_ccb;
1988 		struct pass_io_req *io_req;
1989 		int old_error;
1990 
1991 		user_ccb = (union ccb **)addr;
1992 		old_error = 0;
1993 
1994 		io_req = TAILQ_FIRST(&softc->done_queue);
1995 		if (io_req == NULL) {
1996 			error = ENOENT;
1997 			break;
1998 		}
1999 
2000 		/*
2001 		 * Remove the I/O from the done queue.
2002 		 */
2003 		TAILQ_REMOVE(&softc->done_queue, io_req, links);
2004 
2005 		/*
2006 		 * We have to drop the lock during the copyout because the
2007 		 * copyout can result in VM faults that require sleeping.
2008 		 */
2009 		cam_periph_unlock(periph);
2010 
2011 		/*
2012 		 * Do any needed copies (e.g. for reads) and revert the
2013 		 * pointers in the CCB back to the user's pointers.
2014 		 */
2015 		error = passmemdone(periph, io_req);
2016 
2017 		old_error = error;
2018 
2019 		io_req->ccb.ccb_h.periph_links = io_req->user_periph_links;
2020 		io_req->ccb.ccb_h.periph_priv = io_req->user_periph_priv;
2021 
2022 #if 0
2023 		xpt_print(periph->path, "Copying to user CCB %p from "
2024 			  "kernel address %p\n", *user_ccb, &io_req->ccb);
2025 #endif
2026 
2027 		error = copyout(&io_req->ccb, *user_ccb, sizeof(union ccb));
2028 		if (error != 0) {
2029 			xpt_print(periph->path, "Copy to user CCB %p from "
2030 				  "kernel address %p failed with error %d\n",
2031 				  *user_ccb, &io_req->ccb, error);
2032 		}
2033 
2034 		/*
2035 		 * Prefer the first error we got back, and make sure we
2036 		 * don't overwrite bad status with good.
2037 		 */
2038 		if (old_error != 0)
2039 			error = old_error;
2040 
2041 		cam_periph_lock(periph);
2042 
2043 		/*
2044 		 * At this point, if there was an error, we could potentially
2045 		 * re-queue the I/O and try again.  But why?  The error
2046 		 * would almost certainly happen again.  We might as well
2047 		 * not leak memory.
2048 		 */
2049 		uma_zfree(softc->pass_zone, io_req);
2050 		break;
2051 	}
2052 	default:
2053 		error = cam_periph_ioctl(periph, cmd, addr, passerror);
2054 		break;
2055 	}
2056 
2057 bailout:
2058 	cam_periph_unlock(periph);
2059 
2060 	return(error);
2061 }
2062 
2063 static int
2064 passpoll(struct cdev *dev, int poll_events, struct thread *td)
2065 {
2066 	struct cam_periph *periph;
2067 	struct pass_softc *softc;
2068 	int revents;
2069 
2070 	periph = (struct cam_periph *)dev->si_drv1;
2071 	if (periph == NULL)
2072 		return (ENXIO);
2073 
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 	if (periph == NULL)
2099 		return (ENXIO);
2100 
2101 	softc = (struct pass_softc *)periph->softc;
2102 
2103 	kn->kn_hook = (caddr_t)periph;
2104 	kn->kn_fop = &passread_filtops;
2105 	knlist_add(&softc->read_select.si_note, kn, 0);
2106 
2107 	return (0);
2108 }
2109 
2110 static void
2111 passreadfiltdetach(struct knote *kn)
2112 {
2113 	struct cam_periph *periph;
2114 	struct pass_softc *softc;
2115 
2116 	periph = (struct cam_periph *)kn->kn_hook;
2117 	softc = (struct pass_softc *)periph->softc;
2118 
2119 	knlist_remove(&softc->read_select.si_note, kn, 0);
2120 }
2121 
2122 static int
2123 passreadfilt(struct knote *kn, long hint)
2124 {
2125 	struct cam_periph *periph;
2126 	struct pass_softc *softc;
2127 	int retval;
2128 
2129 	periph = (struct cam_periph *)kn->kn_hook;
2130 	softc = (struct pass_softc *)periph->softc;
2131 
2132 	cam_periph_assert(periph, MA_OWNED);
2133 
2134 	if (TAILQ_EMPTY(&softc->done_queue))
2135 		retval = 0;
2136 	else
2137 		retval = 1;
2138 
2139 	return (retval);
2140 }
2141 
2142 /*
2143  * Generally, "ccb" should be the CCB supplied by the kernel.  "inccb"
2144  * should be the CCB that is copied in from the user.
2145  */
2146 static int
2147 passsendccb(struct cam_periph *periph, union ccb *ccb, union ccb *inccb)
2148 {
2149 	struct pass_softc *softc;
2150 	struct cam_periph_map_info mapinfo;
2151 	xpt_opcode fc;
2152 	int error;
2153 
2154 	softc = (struct pass_softc *)periph->softc;
2155 
2156 	/*
2157 	 * There are some fields in the CCB header that need to be
2158 	 * preserved, the rest we get from the user.
2159 	 */
2160 	xpt_merge_ccb(ccb, inccb);
2161 
2162 	/*
2163 	 */
2164 	ccb->ccb_h.cbfcnp = passdone;
2165 
2166 	/*
2167 	 * Let cam_periph_mapmem do a sanity check on the data pointer format.
2168 	 * Even if no data transfer is needed, it's a cheap check and it
2169 	 * simplifies the code.
2170 	 */
2171 	fc = ccb->ccb_h.func_code;
2172 	if ((fc == XPT_SCSI_IO) || (fc == XPT_ATA_IO) || (fc == XPT_SMP_IO)
2173 	 || (fc == XPT_DEV_MATCH) || (fc == XPT_DEV_ADVINFO)) {
2174 		bzero(&mapinfo, sizeof(mapinfo));
2175 
2176 		/*
2177 		 * cam_periph_mapmem calls into proc and vm functions that can
2178 		 * sleep as well as trigger I/O, so we can't hold the lock.
2179 		 * Dropping it here is reasonably safe.
2180 		 */
2181 		cam_periph_unlock(periph);
2182 		error = cam_periph_mapmem(ccb, &mapinfo, softc->maxio);
2183 		cam_periph_lock(periph);
2184 
2185 		/*
2186 		 * cam_periph_mapmem returned an error, we can't continue.
2187 		 * Return the error to the user.
2188 		 */
2189 		if (error)
2190 			return(error);
2191 	} else
2192 		/* Ensure that the unmap call later on is a no-op. */
2193 		mapinfo.num_bufs_used = 0;
2194 
2195 	/*
2196 	 * If the user wants us to perform any error recovery, then honor
2197 	 * that request.  Otherwise, it's up to the user to perform any
2198 	 * error recovery.
2199 	 */
2200 	cam_periph_runccb(ccb, passerror, /* cam_flags */ CAM_RETRY_SELTO,
2201 	    /* sense_flags */ ((ccb->ccb_h.flags & CAM_PASS_ERR_RECOVER) ?
2202 	     SF_RETRY_UA : SF_NO_RECOVERY) | SF_NO_PRINT,
2203 	    softc->device_stats);
2204 
2205 	cam_periph_unmapmem(ccb, &mapinfo);
2206 
2207 	ccb->ccb_h.cbfcnp = NULL;
2208 	ccb->ccb_h.periph_priv = inccb->ccb_h.periph_priv;
2209 	bcopy(ccb, inccb, sizeof(union ccb));
2210 
2211 	return(0);
2212 }
2213 
2214 static int
2215 passerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
2216 {
2217 	struct cam_periph *periph;
2218 	struct pass_softc *softc;
2219 
2220 	periph = xpt_path_periph(ccb->ccb_h.path);
2221 	softc = (struct pass_softc *)periph->softc;
2222 
2223 	return(cam_periph_error(ccb, cam_flags, sense_flags,
2224 				 &softc->saved_ccb));
2225 }
2226