xref: /dragonfly/sys/bus/cam/cam_periph.c (revision a78dfe84)
1 /*
2  * Common functions for CAM "type" (peripheral) drivers.
3  *
4  * Copyright (c) 1997, 1998 Justin T. Gibbs.
5  * Copyright (c) 1997, 1998, 1999, 2000 Kenneth D. Merry.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD: src/sys/cam/cam_periph.c,v 1.70 2008/02/12 11:07:33 raj Exp $
30  * $DragonFly: src/sys/bus/cam/cam_periph.c,v 1.41 2008/07/18 00:07:21 dillon Exp $
31  */
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/types.h>
36 #include <sys/malloc.h>
37 #include <sys/kernel.h>
38 #include <sys/lock.h>
39 #include <sys/buf.h>
40 #include <sys/proc.h>
41 #include <sys/devicestat.h>
42 #include <sys/bus.h>
43 #include <vm/vm.h>
44 #include <vm/vm_extern.h>
45 
46 #include <sys/thread2.h>
47 
48 #include "cam.h"
49 #include "cam_ccb.h"
50 #include "cam_xpt_periph.h"
51 #include "cam_periph.h"
52 #include "cam_debug.h"
53 #include "cam_sim.h"
54 
55 #include <bus/cam/scsi/scsi_all.h>
56 #include <bus/cam/scsi/scsi_message.h>
57 #include <bus/cam/scsi/scsi_pass.h>
58 
59 static	u_int		camperiphnextunit(struct periph_driver *p_drv,
60 					  u_int newunit, int wired,
61 					  path_id_t pathid, target_id_t target,
62 					  lun_id_t lun);
63 static	u_int		camperiphunit(struct periph_driver *p_drv,
64 				      struct cam_sim *sim, path_id_t pathid,
65 				      target_id_t target, lun_id_t lun);
66 static	void		camperiphdone(struct cam_periph *periph,
67 					union ccb *done_ccb);
68 static  void		camperiphfree(struct cam_periph *periph);
69 static int		camperiphscsistatuserror(union ccb *ccb,
70 						 cam_flags camflags,
71 						 u_int32_t sense_flags,
72 						 union ccb *save_ccb,
73 						 int *openings,
74 						 u_int32_t *relsim_flags,
75 						 u_int32_t *timeout);
76 static	int		camperiphscsisenseerror(union ccb *ccb,
77 					        cam_flags camflags,
78 					        u_int32_t sense_flags,
79 					        union ccb *save_ccb,
80 					        int *openings,
81 					        u_int32_t *relsim_flags,
82 					        u_int32_t *timeout);
83 static void cam_periph_unmapbufs(struct cam_periph_map_info *mapinfo,
84 				 u_int8_t ***data_ptrs, int numbufs);
85 
86 static int nperiph_drivers;
87 struct periph_driver **periph_drivers;
88 
89 MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
90 
91 static int periph_selto_delay = 1000;
92 TUNABLE_INT("kern.cam.periph_selto_delay", &periph_selto_delay);
93 static int periph_noresrc_delay = 500;
94 TUNABLE_INT("kern.cam.periph_noresrc_delay", &periph_noresrc_delay);
95 static int periph_busy_delay = 500;
96 TUNABLE_INT("kern.cam.periph_busy_delay", &periph_busy_delay);
97 
98 
99 void
100 periphdriver_register(void *data)
101 {
102 	struct periph_driver **newdrivers, **old;
103 	int ndrivers;
104 
105 	ndrivers = nperiph_drivers + 2;
106 	newdrivers = kmalloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
107 			     M_WAITOK);
108 	if (periph_drivers)
109 		bcopy(periph_drivers, newdrivers,
110 		      sizeof(*newdrivers) * nperiph_drivers);
111 	newdrivers[nperiph_drivers] = (struct periph_driver *)data;
112 	newdrivers[nperiph_drivers + 1] = NULL;
113 	old = periph_drivers;
114 	periph_drivers = newdrivers;
115 	if (old)
116 		kfree(old, M_CAMPERIPH);
117 	nperiph_drivers++;
118 }
119 
120 cam_status
121 cam_periph_alloc(periph_ctor_t *periph_ctor,
122 		 periph_oninv_t *periph_oninvalidate,
123 		 periph_dtor_t *periph_dtor, periph_start_t *periph_start,
124 		 char *name, cam_periph_type type, struct cam_path *path,
125 		 ac_callback_t *ac_callback, ac_code code, void *arg)
126 {
127 	struct		periph_driver **p_drv;
128 	struct		cam_sim *sim;
129 	struct		cam_periph *periph;
130 	struct		cam_periph *cur_periph;
131 	path_id_t	path_id;
132 	target_id_t	target_id;
133 	lun_id_t	lun_id;
134 	cam_status	status;
135 	u_int		init_level;
136 
137 	init_level = 0;
138 	/*
139 	 * Handle Hot-Plug scenarios.  If there is already a peripheral
140 	 * of our type assigned to this path, we are likely waiting for
141 	 * final close on an old, invalidated, peripheral.  If this is
142 	 * the case, queue up a deferred call to the peripheral's async
143 	 * handler.  If it looks like a mistaken re-allocation, complain.
144 	 */
145 	if ((periph = cam_periph_find(path, name)) != NULL) {
146 
147 		if ((periph->flags & CAM_PERIPH_INVALID) != 0
148 		 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
149 			periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
150 			periph->deferred_callback = ac_callback;
151 			periph->deferred_ac = code;
152 			return (CAM_REQ_INPROG);
153 		} else {
154 			kprintf("cam_periph_alloc: attempt to re-allocate "
155 			       "valid device %s%d rejected\n",
156 			       periph->periph_name, periph->unit_number);
157 		}
158 		return (CAM_REQ_INVALID);
159 	}
160 
161 	periph = kmalloc(sizeof(*periph), M_CAMPERIPH, M_INTWAIT | M_ZERO);
162 
163 	init_level++;	/* 1 */
164 
165 	xpt_lock_buses();
166 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
167 		if (strcmp((*p_drv)->driver_name, name) == 0)
168 			break;
169 	}
170 	xpt_unlock_buses();
171 
172 	sim = xpt_path_sim(path);
173 	CAM_SIM_LOCK(sim);
174 	path_id = xpt_path_path_id(path);
175 	target_id = xpt_path_target_id(path);
176 	lun_id = xpt_path_lun_id(path);
177 	cam_init_pinfo(&periph->pinfo);
178 	periph->periph_start = periph_start;
179 	periph->periph_dtor = periph_dtor;
180 	periph->periph_oninval = periph_oninvalidate;
181 	periph->type = type;
182 	periph->periph_name = name;
183 	periph->unit_number = camperiphunit(*p_drv, sim, path_id,
184 					    target_id, lun_id);
185 	periph->immediate_priority = CAM_PRIORITY_NONE;
186 	periph->refcount = 0;
187 	periph->sim = sim;
188 	SLIST_INIT(&periph->ccb_list);
189 	status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
190 	if (status != CAM_REQ_CMP)
191 		goto failure;
192 
193 	init_level++;	/* 2 */
194 
195 	periph->path = path;
196 	status = xpt_add_periph(periph);
197 
198 	if (status != CAM_REQ_CMP)
199 		goto failure;
200 
201 	cur_periph = TAILQ_FIRST(&(*p_drv)->units);
202 	while (cur_periph != NULL
203 	    && cur_periph->unit_number < periph->unit_number)
204 		cur_periph = TAILQ_NEXT(cur_periph, unit_links);
205 
206 	if (cur_periph != NULL)
207 		TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
208 	else {
209 		TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
210 		(*p_drv)->generation++;
211 	}
212 
213 	init_level++;
214 
215 	status = periph_ctor(periph, arg);
216 
217 	if (status == CAM_REQ_CMP)
218 		init_level++;
219 
220 failure:
221 	switch (init_level) {
222 	case 4:
223 		/* Initialized successfully */
224 		CAM_SIM_UNLOCK(sim);
225 		break;
226 	case 3:
227 		TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
228 		xpt_remove_periph(periph);
229 		/* FALLTHROUGH */
230 	case 2:
231 		periph->path = NULL;
232 		/* FALLTHROUGH */
233 	case 1:
234 		CAM_SIM_UNLOCK(sim);	/* sim was retrieved from path */
235 		xpt_free_path(path);
236 		kfree(periph, M_CAMPERIPH);
237 		/* FALLTHROUGH */
238 	case 0:
239 		/* No cleanup to perform. */
240 		break;
241 	default:
242 		panic("cam_periph_alloc: Unknown init level");
243 	}
244 	return(status);
245 }
246 
247 /*
248  * Find a peripheral structure with the specified path, target, lun,
249  * and (optionally) type.  If the name is NULL, this function will return
250  * the first peripheral driver that matches the specified path.
251  */
252 struct cam_periph *
253 cam_periph_find(struct cam_path *path, char *name)
254 {
255 	struct periph_driver **p_drv;
256 	struct cam_periph *periph;
257 
258 	xpt_lock_buses();
259 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
260 		if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
261 			continue;
262 
263 		TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
264 			if (xpt_path_comp(periph->path, path) == 0) {
265 				xpt_unlock_buses();
266 				return(periph);
267 			}
268 		}
269 		if (name != NULL) {
270 			xpt_unlock_buses();
271 			return(NULL);
272 		}
273 	}
274 	xpt_unlock_buses();
275 	return(NULL);
276 }
277 
278 cam_status
279 cam_periph_acquire(struct cam_periph *periph)
280 {
281 	if (periph == NULL)
282 		return(CAM_REQ_CMP_ERR);
283 
284 	xpt_lock_buses();
285 	periph->refcount++;
286 	xpt_unlock_buses();
287 
288 	return(CAM_REQ_CMP);
289 }
290 
291 /*
292  * Release the peripheral.  The XPT is not locked and the SIM may or may
293  * not be locked on entry.
294  *
295  * The last release on a peripheral marked invalid frees it.  In this
296  * case we must be sure to hold both the XPT lock and the SIM lock,
297  * requiring a bit of fancy footwork if the SIM lock already happens
298  * to be held.
299  */
300 void
301 cam_periph_release(struct cam_periph *periph)
302 {
303 	struct cam_sim *sim;
304 	int doun;
305 
306 	while (periph) {
307 		/*
308 		 * First try the critical path case
309 		 */
310 		sim = periph->sim;
311 		xpt_lock_buses();
312 		if ((periph->flags & CAM_PERIPH_INVALID) == 0 ||
313 		    periph->refcount != 1) {
314 			--periph->refcount;
315 			xpt_unlock_buses();
316 			break;
317 		}
318 
319 		/*
320 		 * Otherwise we also need to free the peripheral and must
321 		 * acquire the sim lock and xpt lock in the correct order
322 		 * to do so.
323 		 *
324 		 * The condition must be re-checked after the locks have
325 		 * been reacquired.
326 		 */
327 		xpt_unlock_buses();
328 		doun = CAM_SIM_COND_LOCK(sim);
329 		xpt_lock_buses();
330 		--periph->refcount;
331 		if ((periph->flags & CAM_PERIPH_INVALID) &&
332 		    periph->refcount == 0) {
333 			camperiphfree(periph);
334 		}
335 		xpt_unlock_buses();
336 		CAM_SIM_COND_UNLOCK(sim, doun);
337 		break;
338 	}
339 }
340 
341 int
342 cam_periph_hold(struct cam_periph *periph, int flags)
343 {
344 	int error;
345 
346 	sim_lock_assert_owned(periph->sim->lock);
347 
348 	/*
349 	 * Increment the reference count on the peripheral
350 	 * while we wait for our lock attempt to succeed
351 	 * to ensure the peripheral doesn't disappear out
352 	 * from user us while we sleep.
353 	 */
354 
355 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
356 		return (ENXIO);
357 
358 	while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
359 		periph->flags |= CAM_PERIPH_LOCK_WANTED;
360 		if ((error = sim_lock_sleep(periph, flags, "caplck", 0,
361 					    periph->sim->lock)) != 0) {
362 			cam_periph_release(periph);
363 			return (error);
364 		}
365 	}
366 
367 	periph->flags |= CAM_PERIPH_LOCKED;
368 	return (0);
369 }
370 
371 void
372 cam_periph_unhold(struct cam_periph *periph, int unlock)
373 {
374 	struct cam_sim *sim;
375 
376 	sim_lock_assert_owned(periph->sim->lock);
377 	periph->flags &= ~CAM_PERIPH_LOCKED;
378 	if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
379 		periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
380 		wakeup(periph);
381 	}
382 	if (unlock) {
383 		sim = periph->sim;
384 		cam_periph_release(periph);
385 		/* periph may be garbage now */
386 		CAM_SIM_UNLOCK(sim);
387 	} else {
388 		cam_periph_release(periph);
389 	}
390 }
391 
392 /*
393  * Look for the next unit number that is not currently in use for this
394  * peripheral type starting at "newunit".  Also exclude unit numbers that
395  * are reserved by for future "hardwiring" unless we already know that this
396  * is a potential wired device.  Only assume that the device is "wired" the
397  * first time through the loop since after that we'll be looking at unit
398  * numbers that did not match a wiring entry.
399  */
400 static u_int
401 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
402 		  path_id_t pathid, target_id_t target, lun_id_t lun)
403 {
404 	struct	cam_periph *periph;
405 	char	*periph_name;
406 	int	i, val, dunit;
407 	const char *dname, *strval;
408 
409 	periph_name = p_drv->driver_name;
410 	for (;;newunit++) {
411 
412 		for (periph = TAILQ_FIRST(&p_drv->units);
413 		     periph != NULL && periph->unit_number != newunit;
414 		     periph = TAILQ_NEXT(periph, unit_links))
415 			;
416 
417 		if (periph != NULL && periph->unit_number == newunit) {
418 			if (wired != 0) {
419 				xpt_print(periph->path, "Duplicate Wired "
420 				    "Device entry!\n");
421 				xpt_print(periph->path, "Second device (%s "
422 				    "device at scbus%d target %d lun %d) will "
423 				    "not be wired\n", periph_name, pathid,
424 				    target, lun);
425 				wired = 0;
426 			}
427 			continue;
428 		}
429 		if (wired)
430 			break;
431 
432 		/*
433 		 * Don't match entries like "da 4" as a wired down
434 		 * device, but do match entries like "da 4 target 5"
435 		 * or even "da 4 scbus 1".
436 		 */
437 		i = -1;
438 		while ((i = resource_locate(i, periph_name)) != -1) {
439 			dname = resource_query_name(i);
440 			dunit = resource_query_unit(i);
441 			/* if no "target" and no specific scbus, skip */
442 			if (resource_int_value(dname, dunit, "target", &val) &&
443 			    (resource_string_value(dname, dunit, "at",&strval)||
444 			     strcmp(strval, "scbus") == 0))
445 				continue;
446 			if (newunit == dunit)
447 				break;
448 		}
449 		if (i == -1)
450 			break;
451 	}
452 	return (newunit);
453 }
454 
455 static u_int
456 camperiphunit(struct periph_driver *p_drv,
457 	      struct cam_sim *sim, path_id_t pathid,
458 	      target_id_t target, lun_id_t lun)
459 {
460 	u_int	unit;
461 	int	hit, i, val, dunit;
462 	const char *dname, *strval;
463 	char	pathbuf[32], *periph_name;
464 
465 	unit = 0;
466 
467 	periph_name = p_drv->driver_name;
468 	ksnprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
469 	i = -1;
470 	for (hit = 0; (i = resource_locate(i, periph_name)) != -1; hit = 0) {
471 		dname = resource_query_name(i);
472 		dunit = resource_query_unit(i);
473 		if (resource_string_value(dname, dunit, "at", &strval) == 0) {
474 			if (strcmp(strval, pathbuf) != 0)
475 				continue;
476 			hit++;
477 		}
478 		if (resource_int_value(dname, dunit, "target", &val) == 0) {
479 			if (val != target)
480 				continue;
481 			hit++;
482 		}
483 		if (resource_int_value(dname, dunit, "lun", &val) == 0) {
484 			if (val != lun)
485 				continue;
486 			hit++;
487 		}
488 		if (hit != 0) {
489 			unit = dunit;
490 			break;
491 		}
492 	}
493 
494 	/*
495 	 * If no wired units are in the kernel config do an auto unit
496 	 * start selection.  We want usb mass storage out of the way
497 	 * so it doesn't steal low numbered da%d slots from ahci, sili,
498 	 * or other scsi attachments.
499 	 */
500 	if (hit == 0 && sim) {
501 		if (strncmp(sim->sim_name, "umass", 4) == 0 && unit < 8)
502 			unit = 8;
503 	}
504 
505 	/*
506 	 * Either start from 0 looking for the next unit or from
507 	 * the unit number given in the resource config.  This way,
508 	 * if we have wildcard matches, we don't return the same
509 	 * unit number twice.
510 	 */
511 	unit = camperiphnextunit(p_drv, unit, /*wired*/hit, pathid,
512 				 target, lun);
513 
514 	return (unit);
515 }
516 
517 void
518 cam_periph_invalidate(struct cam_periph *periph)
519 {
520 	/*
521 	 * We only call this routine the first time a peripheral is
522 	 * invalidated.
523 	 */
524 	if (((periph->flags & CAM_PERIPH_INVALID) == 0)
525 	 && (periph->periph_oninval != NULL))
526 		periph->periph_oninval(periph);
527 
528 	periph->flags |= CAM_PERIPH_INVALID;
529 	periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
530 
531 	xpt_lock_buses();
532 	if (periph->refcount == 0)
533 		camperiphfree(periph);
534 	else if (periph->refcount < 0)
535 		kprintf("cam_invalidate_periph: refcount < 0!!\n");
536 	xpt_unlock_buses();
537 }
538 
539 static void
540 camperiphfree(struct cam_periph *periph)
541 {
542 	struct periph_driver **p_drv;
543 
544 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
545 		if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
546 			break;
547 	}
548 
549 	if (*p_drv == NULL) {
550 		kprintf("camperiphfree: attempt to free non-existent periph\n");
551 		return;
552 	}
553 
554 	TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
555 	(*p_drv)->generation++;
556 	xpt_unlock_buses();
557 
558 	if (periph->periph_dtor != NULL)
559 		periph->periph_dtor(periph);
560 	xpt_remove_periph(periph);
561 
562 	if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
563 		union ccb ccb;
564 		void *arg;
565 
566 		switch (periph->deferred_ac) {
567 		case AC_FOUND_DEVICE:
568 			ccb.ccb_h.func_code = XPT_GDEV_TYPE;
569 			xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/ 1);
570 			xpt_action(&ccb);
571 			arg = &ccb;
572 			break;
573 		case AC_PATH_REGISTERED:
574 			ccb.ccb_h.func_code = XPT_PATH_INQ;
575 			xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/ 1);
576 			xpt_action(&ccb);
577 			arg = &ccb;
578 			break;
579 		default:
580 			arg = NULL;
581 			break;
582 		}
583 		periph->deferred_callback(NULL, periph->deferred_ac,
584 					  periph->path, arg);
585 	}
586 	xpt_free_path(periph->path);
587 	kfree(periph, M_CAMPERIPH);
588 	xpt_lock_buses();
589 }
590 
591 /*
592  * We don't map user pointers into KVM, instead we use pbufs.
593  *
594  * This won't work on physical pointers(?OLD), for now it's
595  * up to the caller to check for that.  (XXX KDM -- should we do that here
596  * instead?)  This also only works for up to MAXPHYS memory.  Since we use
597  * buffers to map stuff in and out, we're limited to the buffer size.
598  */
599 int
600 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
601 {
602 	buf_cmd_t cmd[CAM_PERIPH_MAXMAPS];
603 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
604 	u_int32_t lengths[CAM_PERIPH_MAXMAPS];
605 	int numbufs;
606 	int error;
607 	int i;
608 	struct buf *bp;
609 
610 	switch(ccb->ccb_h.func_code) {
611 	case XPT_DEV_MATCH:
612 		if (ccb->cdm.match_buf_len == 0) {
613 			kprintf("cam_periph_mapmem: invalid match buffer "
614 			       "length 0\n");
615 			return(EINVAL);
616 		}
617 		if (ccb->cdm.pattern_buf_len > 0) {
618 			data_ptrs[0] = (void *)&ccb->cdm.patterns;
619 			lengths[0] = ccb->cdm.pattern_buf_len;
620 			mapinfo->dirs[0] = CAM_DIR_OUT;
621 			data_ptrs[1] = (void *)&ccb->cdm.matches;
622 			lengths[1] = ccb->cdm.match_buf_len;
623 			mapinfo->dirs[1] = CAM_DIR_IN;
624 			numbufs = 2;
625 		} else {
626 			data_ptrs[0] = (void *)&ccb->cdm.matches;
627 			lengths[0] = ccb->cdm.match_buf_len;
628 			mapinfo->dirs[0] = CAM_DIR_IN;
629 			numbufs = 1;
630 		}
631 		break;
632 	case XPT_SCSI_IO:
633 	case XPT_CONT_TARGET_IO:
634 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
635 			return(0);
636 
637 		data_ptrs[0] = &ccb->csio.data_ptr;
638 		lengths[0] = ccb->csio.dxfer_len;
639 		mapinfo->dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
640 		numbufs = 1;
641 		break;
642 	default:
643 		return(EINVAL);
644 		break; /* NOTREACHED */
645 	}
646 
647 	/*
648 	 * Check the transfer length and permissions first, so we don't
649 	 * have to unmap any previously mapped buffers.
650 	 */
651 	for (i = 0; i < numbufs; i++) {
652 		/*
653 		 * Its kinda bogus, we need a R+W command.  For now the
654 		 * buffer needs some sort of command.  Use BUF_CMD_WRITE
655 		 * to indicate a write and BUF_CMD_READ to indicate R+W.
656 		 */
657 		cmd[i] = BUF_CMD_WRITE;
658 
659 		if (lengths[i] > MAXPHYS) {
660 			kprintf("cam_periph_mapmem: attempt to map %lu bytes, "
661 			       "which is greater than MAXPHYS(%d)\n",
662 			       (long)(lengths[i] +
663 			       (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)),
664 			       MAXPHYS);
665 			return(E2BIG);
666 		}
667 
668 		if (mapinfo->dirs[i] & CAM_DIR_OUT) {
669 			if (!useracc(*data_ptrs[i], lengths[i],
670 				     VM_PROT_READ)) {
671 				kprintf("cam_periph_mapmem: error, "
672 					"address %p, length %lu isn't "
673 					"user accessible for READ\n",
674 					(void *)*data_ptrs[i],
675 					(u_long)lengths[i]);
676 				return(EACCES);
677 			}
678 		}
679 
680 		if (mapinfo->dirs[i] & CAM_DIR_IN) {
681 			cmd[i] = BUF_CMD_READ;
682 			if (!useracc(*data_ptrs[i], lengths[i],
683 				     VM_PROT_WRITE)) {
684 				kprintf("cam_periph_mapmem: error, "
685 					"address %p, length %lu isn't "
686 					"user accessible for WRITE\n",
687 					(void *)*data_ptrs[i],
688 					(u_long)lengths[i]);
689 
690 				return(EACCES);
691 			}
692 		}
693 
694 	}
695 
696 	for (i = 0; i < numbufs; i++) {
697 		/*
698 		 * Get the buffer.
699 		 */
700 		bp = getpbuf_kva(NULL);
701 
702 		/* save the original user pointer */
703 		mapinfo->saved_ptrs[i] = *data_ptrs[i];
704 
705 		/* set the flags */
706 		bp->b_cmd = cmd[i];
707 
708 		/*
709 		 * Always bounce the I/O through kernel memory.
710 		 */
711 		bp->b_data = bp->b_kvabase;
712 		bp->b_bcount = lengths[i];
713 		vm_hold_load_pages(bp, (vm_offset_t)bp->b_data,
714 				   (vm_offset_t)bp->b_data + bp->b_bcount);
715 		if (mapinfo->dirs[i] & CAM_DIR_OUT) {
716 			error = copyin(*data_ptrs[i], bp->b_data, bp->b_bcount);
717 			if (error) {
718 				vm_hold_free_pages(bp,
719 						   (vm_offset_t)bp->b_data,
720 						   (vm_offset_t)bp->b_data +
721 						    bp->b_bcount);
722 			}
723 		} else {
724 			error = 0;
725 		}
726 		if (error) {
727 			relpbuf(bp, NULL);
728 			cam_periph_unmapbufs(mapinfo, data_ptrs, i);
729 			mapinfo->num_bufs_used -= i;
730 			return(error);
731 		}
732 
733 		/* set our pointer to the new mapped area */
734 		*data_ptrs[i] = bp->b_data;
735 
736 		mapinfo->bp[i] = bp;
737 		mapinfo->num_bufs_used++;
738 	}
739 
740 	return(0);
741 }
742 
743 /*
744  * Unmap memory segments mapped into kernel virtual address space by
745  * cam_periph_mapmem().
746  */
747 void
748 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
749 {
750 	int numbufs;
751 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
752 
753 	if (mapinfo->num_bufs_used <= 0) {
754 		/* allow ourselves to be swapped once again */
755 		return;
756 	}
757 
758 	switch (ccb->ccb_h.func_code) {
759 	case XPT_DEV_MATCH:
760 		numbufs = min(mapinfo->num_bufs_used, 2);
761 
762 		if (numbufs == 1) {
763 			data_ptrs[0] = (void *)&ccb->cdm.matches;
764 		} else {
765 			data_ptrs[0] = (void *)&ccb->cdm.patterns;
766 			data_ptrs[1] = (void *)&ccb->cdm.matches;
767 		}
768 		break;
769 	case XPT_SCSI_IO:
770 	case XPT_CONT_TARGET_IO:
771 		data_ptrs[0] = &ccb->csio.data_ptr;
772 		numbufs = min(mapinfo->num_bufs_used, 1);
773 		break;
774 	default:
775 		/* allow ourselves to be swapped once again */
776 		return;
777 		break; /* NOTREACHED */
778 	}
779 	cam_periph_unmapbufs(mapinfo, data_ptrs, numbufs);
780 }
781 
782 static void
783 cam_periph_unmapbufs(struct cam_periph_map_info *mapinfo,
784 		     u_int8_t ***data_ptrs, int numbufs)
785 {
786 	struct buf *bp;
787 	int i;
788 
789 	for (i = 0; i < numbufs; i++) {
790 		bp = mapinfo->bp[i];
791 
792 		/* Set the user's pointer back to the original value */
793 		*data_ptrs[i] = mapinfo->saved_ptrs[i];
794 
795 		if (mapinfo->dirs[i] & CAM_DIR_IN) {
796 			/* XXX return error */
797 			copyout(bp->b_data, *data_ptrs[i], bp->b_bcount);
798 		}
799 		vm_hold_free_pages(bp, (vm_offset_t)bp->b_data,
800 				   (vm_offset_t)bp->b_data + bp->b_bcount);
801 		relpbuf(bp, NULL);
802 		mapinfo->bp[i] = NULL;
803 	}
804 }
805 
806 union ccb *
807 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
808 {
809 	struct ccb_hdr *ccb_h;
810 
811 	sim_lock_assert_owned(periph->sim->lock);
812 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdgetccb\n"));
813 
814 	while (SLIST_FIRST(&periph->ccb_list) == NULL) {
815 		if (periph->immediate_priority > priority)
816 			periph->immediate_priority = priority;
817 		xpt_schedule(periph, priority);
818 		if ((SLIST_FIRST(&periph->ccb_list) != NULL)
819 		 && (SLIST_FIRST(&periph->ccb_list)->pinfo.priority == priority))
820 			break;
821 		sim_lock_sleep(&periph->ccb_list, 0, "cgticb", 0,
822 			       periph->sim->lock);
823 	}
824 
825 	ccb_h = SLIST_FIRST(&periph->ccb_list);
826 	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
827 	return ((union ccb *)ccb_h);
828 }
829 
830 void
831 cam_periph_ccbwait(union ccb *ccb)
832 {
833 	struct cam_sim *sim;
834 
835 	sim = xpt_path_sim(ccb->ccb_h.path);
836 	while ((ccb->ccb_h.pinfo.index != CAM_UNQUEUED_INDEX)
837 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG)) {
838 		sim_lock_sleep(&ccb->ccb_h.cbfcnp, 0, "cbwait", 0, sim->lock);
839 	}
840 }
841 
842 int
843 cam_periph_ioctl(struct cam_periph *periph, int cmd, caddr_t addr,
844 		 int (*error_routine)(union ccb *ccb,
845 				      cam_flags camflags,
846 				      u_int32_t sense_flags))
847 {
848 	union ccb 	     *ccb;
849 	int 		     error;
850 	int		     found;
851 
852 	error = found = 0;
853 
854 	switch(cmd){
855 	case CAMGETPASSTHRU:
856 		ccb = cam_periph_getccb(periph, /* priority */ 1);
857 		xpt_setup_ccb(&ccb->ccb_h,
858 			      ccb->ccb_h.path,
859 			      /*priority*/1);
860 		ccb->ccb_h.func_code = XPT_GDEVLIST;
861 
862 		/*
863 		 * Basically, the point of this is that we go through
864 		 * getting the list of devices, until we find a passthrough
865 		 * device.  In the current version of the CAM code, the
866 		 * only way to determine what type of device we're dealing
867 		 * with is by its name.
868 		 */
869 		while (found == 0) {
870 			ccb->cgdl.index = 0;
871 			ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
872 			while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
873 
874 				/* we want the next device in the list */
875 				xpt_action(ccb);
876 				if (strncmp(ccb->cgdl.periph_name,
877 				    "pass", 4) == 0){
878 					found = 1;
879 					break;
880 				}
881 			}
882 			if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
883 			    (found == 0)) {
884 				ccb->cgdl.periph_name[0] = '\0';
885 				ccb->cgdl.unit_number = 0;
886 				break;
887 			}
888 		}
889 
890 		/* copy the result back out */
891 		bcopy(ccb, addr, sizeof(union ccb));
892 
893 		/* and release the ccb */
894 		xpt_release_ccb(ccb);
895 
896 		break;
897 	default:
898 		error = ENOTTY;
899 		break;
900 	}
901 	return(error);
902 }
903 
904 int
905 cam_periph_runccb(union ccb *ccb,
906 		  int (*error_routine)(union ccb *ccb,
907 				       cam_flags camflags,
908 				       u_int32_t sense_flags),
909 		  cam_flags camflags, u_int32_t sense_flags,
910 		  struct devstat *ds)
911 {
912 	struct cam_sim *sim;
913 	int error;
914 
915 	error = 0;
916 	sim = xpt_path_sim(ccb->ccb_h.path);
917 	sim_lock_assert_owned(sim->lock);
918 
919 	/*
920 	 * If the user has supplied a stats structure, and if we understand
921 	 * this particular type of ccb, record the transaction start.
922 	 */
923 	if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO))
924 		devstat_start_transaction(ds);
925 
926 	xpt_action(ccb);
927 
928 	do {
929 		cam_periph_ccbwait(ccb);
930 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
931 			error = 0;
932 		else if (error_routine != NULL)
933 			error = (*error_routine)(ccb, camflags, sense_flags);
934 		else
935 			error = 0;
936 
937 	} while (error == ERESTART);
938 
939 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
940 		cam_release_devq(ccb->ccb_h.path,
941 				 /* relsim_flags */0,
942 				 /* openings */0,
943 				 /* timeout */0,
944 				 /* getcount_only */ FALSE);
945 
946 	if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO))
947 		devstat_end_transaction(ds,
948 					ccb->csio.dxfer_len,
949 					ccb->csio.tag_action & 0xf,
950 					((ccb->ccb_h.flags & CAM_DIR_MASK) ==
951 					CAM_DIR_NONE) ?  DEVSTAT_NO_DATA :
952 					(ccb->ccb_h.flags & CAM_DIR_OUT) ?
953 					DEVSTAT_WRITE :
954 					DEVSTAT_READ);
955 
956 	return(error);
957 }
958 
959 void
960 cam_freeze_devq(struct cam_path *path)
961 {
962 	struct ccb_hdr ccb_h;
963 
964 	xpt_setup_ccb(&ccb_h, path, /*priority*/1);
965 	ccb_h.func_code = XPT_NOOP;
966 	ccb_h.flags = CAM_DEV_QFREEZE;
967 	xpt_action((union ccb *)&ccb_h);
968 }
969 
970 u_int32_t
971 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
972 		 u_int32_t openings, u_int32_t timeout,
973 		 int getcount_only)
974 {
975 	struct ccb_relsim crs;
976 
977 	xpt_setup_ccb(&crs.ccb_h, path,
978 		      /*priority*/1);
979 	crs.ccb_h.func_code = XPT_REL_SIMQ;
980 	crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
981 	crs.release_flags = relsim_flags;
982 	crs.openings = openings;
983 	crs.release_timeout = timeout;
984 	xpt_action((union ccb *)&crs);
985 	return (crs.qfrozen_cnt);
986 }
987 
988 #define saved_ccb_ptr ppriv_ptr0
989 static void
990 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
991 {
992 	union ccb      *saved_ccb;
993 	cam_status	status;
994 	int		frozen;
995 	int		sense;
996 	struct scsi_start_stop_unit *scsi_cmd;
997 	u_int32_t	relsim_flags, timeout;
998 	u_int32_t	qfrozen_cnt;
999 	int		xpt_done_ccb;
1000 
1001 	xpt_done_ccb = FALSE;
1002 	status = done_ccb->ccb_h.status;
1003 	frozen = (status & CAM_DEV_QFRZN) != 0;
1004 	sense  = (status & CAM_AUTOSNS_VALID) != 0;
1005 	status &= CAM_STATUS_MASK;
1006 
1007 	timeout = 0;
1008 	relsim_flags = 0;
1009 	saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1010 
1011 	/*
1012 	 * Unfreeze the queue once if it is already frozen..
1013 	 */
1014 	if (frozen != 0) {
1015 		qfrozen_cnt = cam_release_devq(done_ccb->ccb_h.path,
1016 					      /*relsim_flags*/0,
1017 					      /*openings*/0,
1018 					      /*timeout*/0,
1019 					      /*getcount_only*/0);
1020 	}
1021 
1022 	switch (status) {
1023 	case CAM_REQ_CMP:
1024 	{
1025 		/*
1026 		 * If we have successfully taken a device from the not
1027 		 * ready to ready state, re-scan the device and re-get
1028 		 * the inquiry information.  Many devices (mostly disks)
1029 		 * don't properly report their inquiry information unless
1030 		 * they are spun up.
1031 		 *
1032 		 * If we manually retrieved sense into a CCB and got
1033 		 * something other than "NO SENSE" send the updated CCB
1034 		 * back to the client via xpt_done() to be processed via
1035 		 * the error recovery code again.
1036 		 */
1037 		if (done_ccb->ccb_h.func_code == XPT_SCSI_IO) {
1038 			scsi_cmd = (struct scsi_start_stop_unit *)
1039 					&done_ccb->csio.cdb_io.cdb_bytes;
1040 
1041 		 	if (scsi_cmd->opcode == START_STOP_UNIT)
1042 				xpt_async(AC_INQ_CHANGED,
1043 					  done_ccb->ccb_h.path, NULL);
1044 			if (scsi_cmd->opcode == REQUEST_SENSE) {
1045 				u_int sense_key;
1046 
1047 				sense_key = saved_ccb->csio.sense_data.flags;
1048 				sense_key &= SSD_KEY;
1049 				if (sense_key != SSD_KEY_NO_SENSE) {
1050 					saved_ccb->ccb_h.status |=
1051 					    CAM_AUTOSNS_VALID;
1052 #if 0
1053 					xpt_print(saved_ccb->ccb_h.path,
1054 					    "Recovered Sense\n");
1055 					scsi_sense_print(&saved_ccb->csio);
1056 					cam_error_print(saved_ccb, CAM_ESF_ALL,
1057 							CAM_EPF_ALL);
1058 #endif
1059 					xpt_done_ccb = TRUE;
1060 				}
1061 			}
1062 		}
1063 		bcopy(done_ccb->ccb_h.saved_ccb_ptr, done_ccb,
1064 		      sizeof(union ccb));
1065 
1066 		periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1067 
1068 		if (xpt_done_ccb == FALSE)
1069 			xpt_action(done_ccb);
1070 
1071 		break;
1072 	}
1073 	case CAM_SCSI_STATUS_ERROR:
1074 		scsi_cmd = (struct scsi_start_stop_unit *)
1075 				&done_ccb->csio.cdb_io.cdb_bytes;
1076 		if (sense != 0) {
1077 			struct ccb_getdev cgd;
1078 			struct scsi_sense_data *sense;
1079 			int    error_code, sense_key, asc, ascq;
1080 			scsi_sense_action err_action;
1081 
1082 			sense = &done_ccb->csio.sense_data;
1083 			scsi_extract_sense(sense, &error_code,
1084 					   &sense_key, &asc, &ascq);
1085 
1086 			/*
1087 			 * Grab the inquiry data for this device.
1088 			 */
1089 			xpt_setup_ccb(&cgd.ccb_h, done_ccb->ccb_h.path,
1090 				      /*priority*/ 1);
1091 			cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1092 			xpt_action((union ccb *)&cgd);
1093 			err_action = scsi_error_action(&done_ccb->csio,
1094 						       &cgd.inq_data, 0);
1095 
1096 			/*
1097 	 		 * If the error is "invalid field in CDB",
1098 			 * and the load/eject flag is set, turn the
1099 			 * flag off and try again.  This is just in
1100 			 * case the drive in question barfs on the
1101 			 * load eject flag.  The CAM code should set
1102 			 * the load/eject flag by default for
1103 			 * removable media.
1104 			 */
1105 
1106 			/* XXX KDM
1107 			 * Should we check to see what the specific
1108 			 * scsi status is??  Or does it not matter
1109 			 * since we already know that there was an
1110 			 * error, and we know what the specific
1111 			 * error code was, and we know what the
1112 			 * opcode is..
1113 			 */
1114 			if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1115 			    ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1116 			     (asc == 0x24) && (ascq == 0x00) &&
1117 			     (done_ccb->ccb_h.retry_count > 0)) {
1118 
1119 				scsi_cmd->how &= ~SSS_LOEJ;
1120 
1121 				xpt_action(done_ccb);
1122 
1123 			} else if ((done_ccb->ccb_h.retry_count > 1)
1124 				&& ((err_action & SS_MASK) != SS_FAIL)) {
1125 
1126 				/*
1127 				 * In this case, the error recovery
1128 				 * command failed, but we've got
1129 				 * some retries left on it.  Give
1130 				 * it another try unless this is an
1131 				 * unretryable error.
1132 				 */
1133 
1134 				/* set the timeout to .5 sec */
1135 				relsim_flags =
1136 					RELSIM_RELEASE_AFTER_TIMEOUT;
1137 				timeout = 500;
1138 
1139 				xpt_action(done_ccb);
1140 
1141 				break;
1142 
1143 			} else {
1144 				/*
1145 				 * Perform the final retry with the original
1146 				 * CCB so that final error processing is
1147 				 * performed by the owner of the CCB.
1148 				 */
1149 				bcopy(done_ccb->ccb_h.saved_ccb_ptr,
1150 				      done_ccb, sizeof(union ccb));
1151 
1152 				periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1153 
1154 				xpt_action(done_ccb);
1155 			}
1156 		} else {
1157 			/*
1158 			 * Eh??  The command failed, but we don't
1159 			 * have any sense.  What's up with that?
1160 			 * Fire the CCB again to return it to the
1161 			 * caller.
1162 			 */
1163 			bcopy(done_ccb->ccb_h.saved_ccb_ptr,
1164 			      done_ccb, sizeof(union ccb));
1165 
1166 			periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1167 
1168 			xpt_action(done_ccb);
1169 
1170 		}
1171 		break;
1172 	default:
1173 		bcopy(done_ccb->ccb_h.saved_ccb_ptr, done_ccb,
1174 		      sizeof(union ccb));
1175 
1176 		periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1177 
1178 		xpt_action(done_ccb);
1179 
1180 		break;
1181 	}
1182 
1183 	/* decrement the retry count */
1184 	/*
1185 	 * XXX This isn't appropriate in all cases.  Restructure,
1186 	 *     so that the retry count is only decremented on an
1187 	 *     actual retry.  Remeber that the orignal ccb had its
1188 	 *     retry count dropped before entering recovery, so
1189 	 *     doing it again is a bug.
1190 	 */
1191 	if (done_ccb->ccb_h.retry_count > 0)
1192 		done_ccb->ccb_h.retry_count--;
1193 
1194 	qfrozen_cnt = cam_release_devq(done_ccb->ccb_h.path,
1195 				      /*relsim_flags*/relsim_flags,
1196 				      /*openings*/0,
1197 				      /*timeout*/timeout,
1198 				      /*getcount_only*/0);
1199 	if (xpt_done_ccb == TRUE)
1200 		(*done_ccb->ccb_h.cbfcnp)(periph, done_ccb);
1201 }
1202 
1203 /*
1204  * Generic Async Event handler.  Peripheral drivers usually
1205  * filter out the events that require personal attention,
1206  * and leave the rest to this function.
1207  */
1208 void
1209 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1210 		 struct cam_path *path, void *arg)
1211 {
1212 	switch (code) {
1213 	case AC_LOST_DEVICE:
1214 		cam_periph_invalidate(periph);
1215 		break;
1216 	case AC_SENT_BDR:
1217 	case AC_BUS_RESET:
1218 	{
1219 		cam_periph_bus_settle(periph, scsi_delay);
1220 		break;
1221 	}
1222 	default:
1223 		break;
1224 	}
1225 }
1226 
1227 void
1228 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1229 {
1230 	struct ccb_getdevstats cgds;
1231 
1232 	xpt_setup_ccb(&cgds.ccb_h, periph->path, /*priority*/1);
1233 	cgds.ccb_h.func_code = XPT_GDEV_STATS;
1234 	xpt_action((union ccb *)&cgds);
1235 	cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1236 }
1237 
1238 void
1239 cam_periph_freeze_after_event(struct cam_periph *periph,
1240 			      struct timeval* event_time, u_int duration_ms)
1241 {
1242 	struct timeval delta;
1243 	struct timeval duration_tv;
1244 
1245 	microuptime(&delta);
1246 	timevalsub(&delta, event_time);
1247 	duration_tv.tv_sec = duration_ms / 1000;
1248 	duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1249 	if (timevalcmp(&delta, &duration_tv, <)) {
1250 		timevalsub(&duration_tv, &delta);
1251 
1252 		duration_ms = duration_tv.tv_sec * 1000;
1253 		duration_ms += duration_tv.tv_usec / 1000;
1254 		cam_freeze_devq(periph->path);
1255 		cam_release_devq(periph->path,
1256 				RELSIM_RELEASE_AFTER_TIMEOUT,
1257 				/*reduction*/0,
1258 				/*timeout*/duration_ms,
1259 				/*getcount_only*/0);
1260 	}
1261 
1262 }
1263 
1264 static int
1265 camperiphscsistatuserror(union ccb *ccb, cam_flags camflags,
1266 			 u_int32_t sense_flags, union ccb *save_ccb,
1267 			 int *openings, u_int32_t *relsim_flags,
1268 			 u_int32_t *timeout)
1269 {
1270 	int error;
1271 
1272 	switch (ccb->csio.scsi_status) {
1273 	case SCSI_STATUS_OK:
1274 	case SCSI_STATUS_COND_MET:
1275 	case SCSI_STATUS_INTERMED:
1276 	case SCSI_STATUS_INTERMED_COND_MET:
1277 		error = 0;
1278 		break;
1279 	case SCSI_STATUS_CMD_TERMINATED:
1280 	case SCSI_STATUS_CHECK_COND:
1281 		error = camperiphscsisenseerror(ccb,
1282 					        camflags,
1283 					        sense_flags,
1284 					        save_ccb,
1285 					        openings,
1286 					        relsim_flags,
1287 					        timeout);
1288 		break;
1289 	case SCSI_STATUS_QUEUE_FULL:
1290 	{
1291 		/* no decrement */
1292 		struct ccb_getdevstats cgds;
1293 
1294 		/*
1295 		 * First off, find out what the current
1296 		 * transaction counts are.
1297 		 */
1298 		xpt_setup_ccb(&cgds.ccb_h,
1299 			      ccb->ccb_h.path,
1300 			      /*priority*/1);
1301 		cgds.ccb_h.func_code = XPT_GDEV_STATS;
1302 		xpt_action((union ccb *)&cgds);
1303 
1304 		/*
1305 		 * If we were the only transaction active, treat
1306 		 * the QUEUE FULL as if it were a BUSY condition.
1307 		 */
1308 		if (cgds.dev_active != 0) {
1309 			int total_openings;
1310 
1311 			/*
1312 			 * Reduce the number of openings to
1313 			 * be 1 less than the amount it took
1314 			 * to get a queue full bounded by the
1315 			 * minimum allowed tag count for this
1316 			 * device.
1317 			 */
1318 			total_openings = cgds.dev_active + cgds.dev_openings;
1319 			*openings = cgds.dev_active;
1320 			if (*openings < cgds.mintags)
1321 				*openings = cgds.mintags;
1322 			if (*openings < total_openings)
1323 				*relsim_flags = RELSIM_ADJUST_OPENINGS;
1324 			else {
1325 				/*
1326 				 * Some devices report queue full for
1327 				 * temporary resource shortages.  For
1328 				 * this reason, we allow a minimum
1329 				 * tag count to be entered via a
1330 				 * quirk entry to prevent the queue
1331 				 * count on these devices from falling
1332 				 * to a pessimisticly low value.  We
1333 				 * still wait for the next successful
1334 				 * completion, however, before queueing
1335 				 * more transactions to the device.
1336 				 */
1337 				*relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1338 			}
1339 			*timeout = 0;
1340 			error = ERESTART;
1341 			if (bootverbose) {
1342 				xpt_print(ccb->ccb_h.path, "Queue Full\n");
1343 			}
1344 			break;
1345 		}
1346 		/* FALLTHROUGH */
1347 	}
1348 	case SCSI_STATUS_BUSY:
1349 		/*
1350 		 * Restart the queue after either another
1351 		 * command completes or a 1 second timeout.
1352 		 */
1353 		if (bootverbose) {
1354 			xpt_print(ccb->ccb_h.path, "Device Busy\n");
1355 		}
1356 		if (ccb->ccb_h.retry_count > 0) {
1357 			ccb->ccb_h.retry_count--;
1358 			error = ERESTART;
1359 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1360 				      | RELSIM_RELEASE_AFTER_CMDCMPLT;
1361 			*timeout = 1000;
1362 		} else {
1363 			error = EIO;
1364 		}
1365 		break;
1366 	case SCSI_STATUS_RESERV_CONFLICT:
1367 		xpt_print(ccb->ccb_h.path, "Reservation Conflict\n");
1368 		error = EIO;
1369 		break;
1370 	default:
1371 		xpt_print(ccb->ccb_h.path, "SCSI Status 0x%x\n",
1372 		    ccb->csio.scsi_status);
1373 		error = EIO;
1374 		break;
1375 	}
1376 	return (error);
1377 }
1378 
1379 static int
1380 camperiphscsisenseerror(union ccb *ccb, cam_flags camflags,
1381 			u_int32_t sense_flags, union ccb *save_ccb,
1382 		       int *openings, u_int32_t *relsim_flags,
1383 		       u_int32_t *timeout)
1384 {
1385 	struct cam_periph *periph;
1386 	int error;
1387 
1388 	periph = xpt_path_periph(ccb->ccb_h.path);
1389 	if (periph->flags & CAM_PERIPH_RECOVERY_INPROG) {
1390 
1391 		/*
1392 		 * If error recovery is already in progress, don't attempt
1393 		 * to process this error, but requeue it unconditionally
1394 		 * and attempt to process it once error recovery has
1395 		 * completed.  This failed command is probably related to
1396 		 * the error that caused the currently active error recovery
1397 		 * action so our  current recovery efforts should also
1398 		 * address this command.  Be aware that the error recovery
1399 		 * code assumes that only one recovery action is in progress
1400 		 * on a particular peripheral instance at any given time
1401 		 * (e.g. only one saved CCB for error recovery) so it is
1402 		 * imperitive that we don't violate this assumption.
1403 		 */
1404 		error = ERESTART;
1405 	} else {
1406 		scsi_sense_action err_action;
1407 		struct ccb_getdev cgd;
1408 		const char *action_string;
1409 		union ccb* print_ccb;
1410 
1411 		/* A description of the error recovery action performed */
1412 		action_string = NULL;
1413 
1414 		/*
1415 		 * The location of the orignal ccb
1416 		 * for sense printing purposes.
1417 		 */
1418 		print_ccb = ccb;
1419 
1420 		/*
1421 		 * Grab the inquiry data for this device.
1422 		 */
1423 		xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, /*priority*/ 1);
1424 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1425 		xpt_action((union ccb *)&cgd);
1426 
1427 		if ((ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0)
1428 			err_action = scsi_error_action(&ccb->csio,
1429 						       &cgd.inq_data,
1430 						       sense_flags);
1431 		else if ((ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)
1432 			err_action = SS_REQSENSE;
1433 		else
1434 			err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1435 
1436 		error = err_action & SS_ERRMASK;
1437 
1438 		/*
1439 		 * If the recovery action will consume a retry,
1440 		 * make sure we actually have retries available.
1441 		 */
1442 		if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1443 			if (ccb->ccb_h.retry_count > 0)
1444 				ccb->ccb_h.retry_count--;
1445 			else {
1446 				action_string = "Retries Exhausted";
1447 				goto sense_error_done;
1448 			}
1449 		}
1450 
1451 		if ((err_action & SS_MASK) >= SS_START) {
1452 			/*
1453 			 * Do common portions of commands that
1454 			 * use recovery CCBs.
1455 			 */
1456 			if (save_ccb == NULL) {
1457 				action_string = "No recovery CCB supplied";
1458 				goto sense_error_done;
1459 			}
1460 			bcopy(ccb, save_ccb, sizeof(*save_ccb));
1461 			print_ccb = save_ccb;
1462 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1463 		}
1464 
1465 		switch (err_action & SS_MASK) {
1466 		case SS_NOP:
1467 			action_string = "No Recovery Action Needed";
1468 			error = 0;
1469 			break;
1470 		case SS_RETRY:
1471 			action_string = "Retrying Command (per Sense Data)";
1472 			error = ERESTART;
1473 			break;
1474 		case SS_FAIL:
1475 			action_string = "Unretryable error";
1476 			break;
1477 		case SS_START:
1478 		{
1479 			int le;
1480 
1481 			/*
1482 			 * Send a start unit command to the device, and
1483 			 * then retry the command.
1484 			 */
1485 			action_string = "Attempting to Start Unit";
1486 
1487 			/*
1488 			 * Check for removable media and set
1489 			 * load/eject flag appropriately.
1490 			 */
1491 			if (SID_IS_REMOVABLE(&cgd.inq_data))
1492 				le = TRUE;
1493 			else
1494 				le = FALSE;
1495 
1496 			scsi_start_stop(&ccb->csio,
1497 					/*retries*/1,
1498 					camperiphdone,
1499 					MSG_SIMPLE_Q_TAG,
1500 					/*start*/TRUE,
1501 					/*load/eject*/le,
1502 					/*immediate*/FALSE,
1503 					SSD_FULL_SIZE,
1504 					/*timeout*/50000);
1505 			break;
1506 		}
1507 		case SS_TUR:
1508 		{
1509 			/*
1510 			 * Send a Test Unit Ready to the device.
1511 			 * If the 'many' flag is set, we send 120
1512 			 * test unit ready commands, one every half
1513 			 * second.  Otherwise, we just send one TUR.
1514 			 * We only want to do this if the retry
1515 			 * count has not been exhausted.
1516 			 */
1517 			int retries;
1518 
1519 			if ((err_action & SSQ_MANY) != 0) {
1520 				action_string = "Polling device for readiness";
1521 				retries = 120;
1522 			} else {
1523 				action_string = "Testing device for readiness";
1524 				retries = 1;
1525 			}
1526 			scsi_test_unit_ready(&ccb->csio,
1527 					     retries,
1528 					     camperiphdone,
1529 					     MSG_SIMPLE_Q_TAG,
1530 					     SSD_FULL_SIZE,
1531 					     /*timeout*/5000);
1532 
1533 			/*
1534 			 * Accomplish our 500ms delay by deferring
1535 			 * the release of our device queue appropriately.
1536 			 */
1537 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1538 			*timeout = 500;
1539 			break;
1540 		}
1541 		case SS_REQSENSE:
1542 		{
1543 			/*
1544 			 * Send a Request Sense to the device.  We
1545 			 * assume that we are in a contingent allegiance
1546 			 * condition so we do not tag this request.
1547 			 */
1548 			scsi_request_sense(&ccb->csio, /*retries*/1,
1549 					   camperiphdone,
1550 					   &save_ccb->csio.sense_data,
1551 					   sizeof(save_ccb->csio.sense_data),
1552 					   CAM_TAG_ACTION_NONE,
1553 					   /*sense_len*/SSD_FULL_SIZE,
1554 					   /*timeout*/5000);
1555 			break;
1556 		}
1557 		default:
1558 			panic("Unhandled error action %x", err_action);
1559 		}
1560 
1561 		if ((err_action & SS_MASK) >= SS_START) {
1562 			/*
1563 			 * Drop the priority to 0 so that the recovery
1564 			 * CCB is the first to execute.  Freeze the queue
1565 			 * after this command is sent so that we can
1566 			 * restore the old csio and have it queued in
1567 			 * the proper order before we release normal
1568 			 * transactions to the device.
1569 			 */
1570 			ccb->ccb_h.pinfo.priority = 0;
1571 			ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1572 			ccb->ccb_h.saved_ccb_ptr = save_ccb;
1573 			error = ERESTART;
1574 		}
1575 
1576 sense_error_done:
1577 		if ((err_action & SSQ_PRINT_SENSE) != 0
1578 		 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0) {
1579 			cam_error_print(print_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1580 			xpt_print_path(ccb->ccb_h.path);
1581 			if (bootverbose)
1582 				scsi_sense_print(&print_ccb->csio);
1583 			kprintf("%s\n", action_string);
1584 		}
1585 	}
1586 	return (error);
1587 }
1588 
1589 /*
1590  * Generic error handler.  Peripheral drivers usually filter
1591  * out the errors that they handle in a unique mannor, then
1592  * call this function.
1593  */
1594 int
1595 cam_periph_error(union ccb *ccb, cam_flags camflags,
1596 		 u_int32_t sense_flags, union ccb *save_ccb)
1597 {
1598 	const char *action_string;
1599 	cam_status  status;
1600 	int	    frozen;
1601 	int	    error, printed = 0;
1602 	int         openings;
1603 	u_int32_t   relsim_flags;
1604 	u_int32_t   timeout = 0;
1605 
1606 	action_string = NULL;
1607 	status = ccb->ccb_h.status;
1608 	frozen = (status & CAM_DEV_QFRZN) != 0;
1609 	status &= CAM_STATUS_MASK;
1610 	openings = relsim_flags = 0;
1611 
1612 	switch (status) {
1613 	case CAM_REQ_CMP:
1614 		error = 0;
1615 		break;
1616 	case CAM_SCSI_STATUS_ERROR:
1617 		error = camperiphscsistatuserror(ccb,
1618 						 camflags,
1619 						 sense_flags,
1620 						 save_ccb,
1621 						 &openings,
1622 						 &relsim_flags,
1623 						 &timeout);
1624 		break;
1625 	case CAM_AUTOSENSE_FAIL:
1626 		xpt_print(ccb->ccb_h.path, "AutoSense Failed\n");
1627 		error = EIO;	/* we have to kill the command */
1628 		break;
1629 	case CAM_REQ_CMP_ERR:
1630 		if (bootverbose && printed == 0) {
1631 			xpt_print(ccb->ccb_h.path,
1632 			    "Request completed with CAM_REQ_CMP_ERR\n");
1633 			printed++;
1634 		}
1635 		/* FALLTHROUGH */
1636 	case CAM_CMD_TIMEOUT:
1637 		if (bootverbose && printed == 0) {
1638 			xpt_print(ccb->ccb_h.path, "Command timed out\n");
1639 			printed++;
1640 		}
1641 		/* FALLTHROUGH */
1642 	case CAM_UNEXP_BUSFREE:
1643 		if (bootverbose && printed == 0) {
1644 			xpt_print(ccb->ccb_h.path, "Unexpected Bus Free\n");
1645 			printed++;
1646 		}
1647 		/* FALLTHROUGH */
1648 	case CAM_UNCOR_PARITY:
1649 		if (bootverbose && printed == 0) {
1650 			xpt_print(ccb->ccb_h.path,
1651 			    "Uncorrected Parity Error\n");
1652 			printed++;
1653 		}
1654 		/* FALLTHROUGH */
1655 	case CAM_DATA_RUN_ERR:
1656 		if (bootverbose && printed == 0) {
1657 			xpt_print(ccb->ccb_h.path, "Data Overrun\n");
1658 			printed++;
1659 		}
1660 		error = EIO;	/* we have to kill the command */
1661 		/* decrement the number of retries */
1662 		if (ccb->ccb_h.retry_count > 0) {
1663 			ccb->ccb_h.retry_count--;
1664 			error = ERESTART;
1665 		} else {
1666 			action_string = "Retries Exhausted";
1667 			error = EIO;
1668 		}
1669 		break;
1670 	case CAM_UA_ABORT:
1671 	case CAM_UA_TERMIO:
1672 	case CAM_MSG_REJECT_REC:
1673 		/* XXX Don't know that these are correct */
1674 		error = EIO;
1675 		break;
1676 	case CAM_SEL_TIMEOUT:
1677 	{
1678 		struct cam_path *newpath;
1679 
1680 		if ((camflags & CAM_RETRY_SELTO) != 0) {
1681 			if (ccb->ccb_h.retry_count > 0) {
1682 
1683 				ccb->ccb_h.retry_count--;
1684 				error = ERESTART;
1685 				if (bootverbose && printed == 0) {
1686 					xpt_print(ccb->ccb_h.path,
1687 					    "Selection Timeout\n");
1688 					printed++;
1689 				}
1690 
1691 				/*
1692 				 * Wait a bit to give the device
1693 				 * time to recover before we try again.
1694 				 */
1695 				relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1696 				timeout = periph_selto_delay;
1697 				break;
1698 			}
1699 		}
1700 		error = ENXIO;
1701 		/* Should we do more if we can't create the path?? */
1702 		if (xpt_create_path(&newpath, xpt_path_periph(ccb->ccb_h.path),
1703 				    xpt_path_path_id(ccb->ccb_h.path),
1704 				    xpt_path_target_id(ccb->ccb_h.path),
1705 				    CAM_LUN_WILDCARD) != CAM_REQ_CMP)
1706 			break;
1707 
1708 		/*
1709 		 * Let peripheral drivers know that this device has gone
1710 		 * away.
1711 		 */
1712 		xpt_async(AC_LOST_DEVICE, newpath, NULL);
1713 		xpt_free_path(newpath);
1714 		break;
1715 	}
1716 	case CAM_REQ_INVALID:
1717 	case CAM_PATH_INVALID:
1718 	case CAM_DEV_NOT_THERE:
1719 	case CAM_NO_HBA:
1720 	case CAM_PROVIDE_FAIL:
1721 	case CAM_REQ_TOO_BIG:
1722 	case CAM_LUN_INVALID:
1723 	case CAM_TID_INVALID:
1724 		error = EINVAL;
1725 		break;
1726 	case CAM_SCSI_BUS_RESET:
1727 	case CAM_BDR_SENT:
1728 		/*
1729 		 * Commands that repeatedly timeout and cause these
1730 		 * kinds of error recovery actions, should return
1731 		 * CAM_CMD_TIMEOUT, which allows us to safely assume
1732 		 * that this command was an innocent bystander to
1733 		 * these events and should be unconditionally
1734 		 * retried.
1735 		 */
1736 		if (bootverbose && printed == 0) {
1737 			xpt_print_path(ccb->ccb_h.path);
1738 			if (status == CAM_BDR_SENT)
1739 				kprintf("Bus Device Reset sent\n");
1740 			else
1741 				kprintf("Bus Reset issued\n");
1742 			printed++;
1743 		}
1744 		/* FALLTHROUGH */
1745 	case CAM_REQUEUE_REQ:
1746 		/* Unconditional requeue */
1747 		error = ERESTART;
1748 		if (bootverbose && printed == 0) {
1749 			xpt_print(ccb->ccb_h.path, "Request Requeued\n");
1750 			printed++;
1751 		}
1752 		break;
1753 	case CAM_RESRC_UNAVAIL:
1754 		/* Wait a bit for the resource shortage to abate. */
1755 		timeout = periph_noresrc_delay;
1756 		/* FALLTHROUGH */
1757 	case CAM_BUSY:
1758 		if (timeout == 0) {
1759 			/* Wait a bit for the busy condition to abate. */
1760 			timeout = periph_busy_delay;
1761 		}
1762 		relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1763 		/* FALLTHROUGH */
1764 	default:
1765 		/* decrement the number of retries */
1766 		if (ccb->ccb_h.retry_count > 0) {
1767 			ccb->ccb_h.retry_count--;
1768 			error = ERESTART;
1769 			if (bootverbose && printed == 0) {
1770 				xpt_print(ccb->ccb_h.path, "CAM Status 0x%x\n",
1771 				    status);
1772 				printed++;
1773 			}
1774 		} else {
1775 			error = EIO;
1776 			action_string = "Retries Exhausted";
1777 		}
1778 		break;
1779 	}
1780 
1781 	/* Attempt a retry */
1782 	if (error == ERESTART || error == 0) {
1783 		if (frozen != 0)
1784 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1785 
1786 		if (error == ERESTART) {
1787 			action_string = "Retrying Command";
1788 			xpt_action(ccb);
1789 		}
1790 
1791 		if (frozen != 0)
1792 			cam_release_devq(ccb->ccb_h.path,
1793 					 relsim_flags,
1794 					 openings,
1795 					 timeout,
1796 					 /*getcount_only*/0);
1797 	}
1798 
1799 	/*
1800 	 * If we have an error and are booting verbosely, whine
1801 	 * *unless* this was a non-retryable selection timeout.
1802 	 */
1803 	if (error != 0 && bootverbose && (sense_flags & SF_NO_PRINT) == 0 &&
1804 	    !(status == CAM_SEL_TIMEOUT && (camflags & CAM_RETRY_SELTO) == 0)) {
1805 
1806 
1807 		if (action_string == NULL)
1808 			action_string = "Unretryable Error";
1809 		if (error != ERESTART) {
1810 			xpt_print(ccb->ccb_h.path, "error %d\n", error);
1811 		}
1812 		xpt_print(ccb->ccb_h.path, "%s\n", action_string);
1813 	}
1814 
1815 	return (error);
1816 }
1817