xref: /freebsd/sys/cam/cam_periph.c (revision 8d20be1e22095c27faf8fe8b2f0d089739cc742e)
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 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
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/bio.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/buf.h>
42 #include <sys/proc.h>
43 #include <sys/devicestat.h>
44 #include <sys/bus.h>
45 #include <sys/sbuf.h>
46 #include <vm/vm.h>
47 #include <vm/vm_extern.h>
48 
49 #include <cam/cam.h>
50 #include <cam/cam_ccb.h>
51 #include <cam/cam_queue.h>
52 #include <cam/cam_xpt_periph.h>
53 #include <cam/cam_periph.h>
54 #include <cam/cam_debug.h>
55 #include <cam/cam_sim.h>
56 
57 #include <cam/scsi/scsi_all.h>
58 #include <cam/scsi/scsi_message.h>
59 #include <cam/scsi/scsi_pass.h>
60 
61 static	u_int		camperiphnextunit(struct periph_driver *p_drv,
62 					  u_int newunit, int wired,
63 					  path_id_t pathid, target_id_t target,
64 					  lun_id_t lun);
65 static	u_int		camperiphunit(struct periph_driver *p_drv,
66 				      path_id_t pathid, target_id_t target,
67 				      lun_id_t lun);
68 static	void		camperiphdone(struct cam_periph *periph,
69 					union ccb *done_ccb);
70 static  void		camperiphfree(struct cam_periph *periph);
71 static int		camperiphscsistatuserror(union ccb *ccb,
72 					        union ccb **orig_ccb,
73 						 cam_flags camflags,
74 						 u_int32_t sense_flags,
75 						 int *openings,
76 						 u_int32_t *relsim_flags,
77 						 u_int32_t *timeout,
78 						 u_int32_t  *action,
79 						 const char **action_string);
80 static	int		camperiphscsisenseerror(union ccb *ccb,
81 					        union ccb **orig_ccb,
82 					        cam_flags camflags,
83 					        u_int32_t sense_flags,
84 					        int *openings,
85 					        u_int32_t *relsim_flags,
86 					        u_int32_t *timeout,
87 					        u_int32_t *action,
88 					        const char **action_string);
89 
90 static int nperiph_drivers;
91 static int initialized = 0;
92 struct periph_driver **periph_drivers;
93 
94 static MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
95 
96 static int periph_selto_delay = 1000;
97 TUNABLE_INT("kern.cam.periph_selto_delay", &periph_selto_delay);
98 static int periph_noresrc_delay = 500;
99 TUNABLE_INT("kern.cam.periph_noresrc_delay", &periph_noresrc_delay);
100 static int periph_busy_delay = 500;
101 TUNABLE_INT("kern.cam.periph_busy_delay", &periph_busy_delay);
102 
103 
104 void
105 periphdriver_register(void *data)
106 {
107 	struct periph_driver *drv = (struct periph_driver *)data;
108 	struct periph_driver **newdrivers, **old;
109 	int ndrivers;
110 
111 	ndrivers = nperiph_drivers + 2;
112 	newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
113 			    M_WAITOK);
114 	if (periph_drivers)
115 		bcopy(periph_drivers, newdrivers,
116 		      sizeof(*newdrivers) * nperiph_drivers);
117 	newdrivers[nperiph_drivers] = drv;
118 	newdrivers[nperiph_drivers + 1] = NULL;
119 	old = periph_drivers;
120 	periph_drivers = newdrivers;
121 	if (old)
122 		free(old, M_CAMPERIPH);
123 	nperiph_drivers++;
124 	/* If driver marked as early or it is late now, initialize it. */
125 	if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
126 	    initialized > 1)
127 		(*drv->init)();
128 }
129 
130 void
131 periphdriver_init(int level)
132 {
133 	int	i, early;
134 
135 	initialized = max(initialized, level);
136 	for (i = 0; periph_drivers[i] != NULL; i++) {
137 		early = (periph_drivers[i]->flags & CAM_PERIPH_DRV_EARLY) ? 1 : 2;
138 		if (early == initialized)
139 			(*periph_drivers[i]->init)();
140 	}
141 }
142 
143 cam_status
144 cam_periph_alloc(periph_ctor_t *periph_ctor,
145 		 periph_oninv_t *periph_oninvalidate,
146 		 periph_dtor_t *periph_dtor, periph_start_t *periph_start,
147 		 char *name, cam_periph_type type, struct cam_path *path,
148 		 ac_callback_t *ac_callback, ac_code code, void *arg)
149 {
150 	struct		periph_driver **p_drv;
151 	struct		cam_sim *sim;
152 	struct		cam_periph *periph;
153 	struct		cam_periph *cur_periph;
154 	path_id_t	path_id;
155 	target_id_t	target_id;
156 	lun_id_t	lun_id;
157 	cam_status	status;
158 	u_int		init_level;
159 
160 	init_level = 0;
161 	/*
162 	 * Handle Hot-Plug scenarios.  If there is already a peripheral
163 	 * of our type assigned to this path, we are likely waiting for
164 	 * final close on an old, invalidated, peripheral.  If this is
165 	 * the case, queue up a deferred call to the peripheral's async
166 	 * handler.  If it looks like a mistaken re-allocation, complain.
167 	 */
168 	if ((periph = cam_periph_find(path, name)) != NULL) {
169 
170 		if ((periph->flags & CAM_PERIPH_INVALID) != 0
171 		 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
172 			periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
173 			periph->deferred_callback = ac_callback;
174 			periph->deferred_ac = code;
175 			return (CAM_REQ_INPROG);
176 		} else {
177 			printf("cam_periph_alloc: attempt to re-allocate "
178 			       "valid device %s%d rejected flags %#x "
179 			       "refcount %d\n", periph->periph_name,
180 			       periph->unit_number, periph->flags,
181 			       periph->refcount);
182 		}
183 		return (CAM_REQ_INVALID);
184 	}
185 
186 	periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
187 					     M_NOWAIT|M_ZERO);
188 
189 	if (periph == NULL)
190 		return (CAM_RESRC_UNAVAIL);
191 
192 	init_level++;
193 
194 
195 	sim = xpt_path_sim(path);
196 	path_id = xpt_path_path_id(path);
197 	target_id = xpt_path_target_id(path);
198 	lun_id = xpt_path_lun_id(path);
199 	periph->periph_start = periph_start;
200 	periph->periph_dtor = periph_dtor;
201 	periph->periph_oninval = periph_oninvalidate;
202 	periph->type = type;
203 	periph->periph_name = name;
204 	periph->scheduled_priority = CAM_PRIORITY_NONE;
205 	periph->immediate_priority = CAM_PRIORITY_NONE;
206 	periph->refcount = 1;		/* Dropped by invalidation. */
207 	periph->sim = sim;
208 	SLIST_INIT(&periph->ccb_list);
209 	status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
210 	if (status != CAM_REQ_CMP)
211 		goto failure;
212 	periph->path = path;
213 
214 	xpt_lock_buses();
215 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
216 		if (strcmp((*p_drv)->driver_name, name) == 0)
217 			break;
218 	}
219 	if (*p_drv == NULL) {
220 		printf("cam_periph_alloc: invalid periph name '%s'\n", name);
221 		xpt_unlock_buses();
222 		xpt_free_path(periph->path);
223 		free(periph, M_CAMPERIPH);
224 		return (CAM_REQ_INVALID);
225 	}
226 	periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id);
227 	cur_periph = TAILQ_FIRST(&(*p_drv)->units);
228 	while (cur_periph != NULL
229 	    && cur_periph->unit_number < periph->unit_number)
230 		cur_periph = TAILQ_NEXT(cur_periph, unit_links);
231 	if (cur_periph != NULL) {
232 		KASSERT(cur_periph->unit_number != periph->unit_number, ("duplicate units on periph list"));
233 		TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
234 	} else {
235 		TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
236 		(*p_drv)->generation++;
237 	}
238 	xpt_unlock_buses();
239 
240 	init_level++;
241 
242 	status = xpt_add_periph(periph);
243 	if (status != CAM_REQ_CMP)
244 		goto failure;
245 
246 	init_level++;
247 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
248 
249 	status = periph_ctor(periph, arg);
250 
251 	if (status == CAM_REQ_CMP)
252 		init_level++;
253 
254 failure:
255 	switch (init_level) {
256 	case 4:
257 		/* Initialized successfully */
258 		break;
259 	case 3:
260 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
261 		xpt_remove_periph(periph);
262 		/* FALLTHROUGH */
263 	case 2:
264 		xpt_lock_buses();
265 		TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
266 		xpt_unlock_buses();
267 		xpt_free_path(periph->path);
268 		/* FALLTHROUGH */
269 	case 1:
270 		free(periph, M_CAMPERIPH);
271 		/* FALLTHROUGH */
272 	case 0:
273 		/* No cleanup to perform. */
274 		break;
275 	default:
276 		panic("%s: Unknown init level", __func__);
277 	}
278 	return(status);
279 }
280 
281 /*
282  * Find a peripheral structure with the specified path, target, lun,
283  * and (optionally) type.  If the name is NULL, this function will return
284  * the first peripheral driver that matches the specified path.
285  */
286 struct cam_periph *
287 cam_periph_find(struct cam_path *path, char *name)
288 {
289 	struct periph_driver **p_drv;
290 	struct cam_periph *periph;
291 
292 	xpt_lock_buses();
293 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
294 
295 		if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
296 			continue;
297 
298 		TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
299 			if (xpt_path_comp(periph->path, path) == 0) {
300 				xpt_unlock_buses();
301 				cam_periph_assert(periph, MA_OWNED);
302 				return(periph);
303 			}
304 		}
305 		if (name != NULL) {
306 			xpt_unlock_buses();
307 			return(NULL);
308 		}
309 	}
310 	xpt_unlock_buses();
311 	return(NULL);
312 }
313 
314 /*
315  * Find peripheral driver instances attached to the specified path.
316  */
317 int
318 cam_periph_list(struct cam_path *path, struct sbuf *sb)
319 {
320 	struct sbuf local_sb;
321 	struct periph_driver **p_drv;
322 	struct cam_periph *periph;
323 	int count;
324 	int sbuf_alloc_len;
325 
326 	sbuf_alloc_len = 16;
327 retry:
328 	sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
329 	count = 0;
330 	xpt_lock_buses();
331 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
332 
333 		TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
334 			if (xpt_path_comp(periph->path, path) != 0)
335 				continue;
336 
337 			if (sbuf_len(&local_sb) != 0)
338 				sbuf_cat(&local_sb, ",");
339 
340 			sbuf_printf(&local_sb, "%s%d", periph->periph_name,
341 				    periph->unit_number);
342 
343 			if (sbuf_error(&local_sb) == ENOMEM) {
344 				sbuf_alloc_len *= 2;
345 				xpt_unlock_buses();
346 				sbuf_delete(&local_sb);
347 				goto retry;
348 			}
349 			count++;
350 		}
351 	}
352 	xpt_unlock_buses();
353 	sbuf_finish(&local_sb);
354 	sbuf_cpy(sb, sbuf_data(&local_sb));
355 	sbuf_delete(&local_sb);
356 	return (count);
357 }
358 
359 cam_status
360 cam_periph_acquire(struct cam_periph *periph)
361 {
362 	cam_status status;
363 
364 	status = CAM_REQ_CMP_ERR;
365 	if (periph == NULL)
366 		return (status);
367 
368 	xpt_lock_buses();
369 	if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
370 		periph->refcount++;
371 		status = CAM_REQ_CMP;
372 	}
373 	xpt_unlock_buses();
374 
375 	return (status);
376 }
377 
378 void
379 cam_periph_release_locked_buses(struct cam_periph *periph)
380 {
381 
382 	cam_periph_assert(periph, MA_OWNED);
383 	KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
384 	if (--periph->refcount == 0)
385 		camperiphfree(periph);
386 }
387 
388 void
389 cam_periph_release_locked(struct cam_periph *periph)
390 {
391 
392 	if (periph == NULL)
393 		return;
394 
395 	xpt_lock_buses();
396 	cam_periph_release_locked_buses(periph);
397 	xpt_unlock_buses();
398 }
399 
400 void
401 cam_periph_release(struct cam_periph *periph)
402 {
403 	struct mtx *mtx;
404 
405 	if (periph == NULL)
406 		return;
407 
408 	cam_periph_assert(periph, MA_NOTOWNED);
409 	mtx = cam_periph_mtx(periph);
410 	mtx_lock(mtx);
411 	cam_periph_release_locked(periph);
412 	mtx_unlock(mtx);
413 }
414 
415 int
416 cam_periph_hold(struct cam_periph *periph, int priority)
417 {
418 	int error;
419 
420 	/*
421 	 * Increment the reference count on the peripheral
422 	 * while we wait for our lock attempt to succeed
423 	 * to ensure the peripheral doesn't disappear out
424 	 * from user us while we sleep.
425 	 */
426 
427 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
428 		return (ENXIO);
429 
430 	cam_periph_assert(periph, MA_OWNED);
431 	while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
432 		periph->flags |= CAM_PERIPH_LOCK_WANTED;
433 		if ((error = cam_periph_sleep(periph, periph, priority,
434 		    "caplck", 0)) != 0) {
435 			cam_periph_release_locked(periph);
436 			return (error);
437 		}
438 		if (periph->flags & CAM_PERIPH_INVALID) {
439 			cam_periph_release_locked(periph);
440 			return (ENXIO);
441 		}
442 	}
443 
444 	periph->flags |= CAM_PERIPH_LOCKED;
445 	return (0);
446 }
447 
448 void
449 cam_periph_unhold(struct cam_periph *periph)
450 {
451 
452 	cam_periph_assert(periph, MA_OWNED);
453 
454 	periph->flags &= ~CAM_PERIPH_LOCKED;
455 	if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
456 		periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
457 		wakeup(periph);
458 	}
459 
460 	cam_periph_release_locked(periph);
461 }
462 
463 /*
464  * Look for the next unit number that is not currently in use for this
465  * peripheral type starting at "newunit".  Also exclude unit numbers that
466  * are reserved by for future "hardwiring" unless we already know that this
467  * is a potential wired device.  Only assume that the device is "wired" the
468  * first time through the loop since after that we'll be looking at unit
469  * numbers that did not match a wiring entry.
470  */
471 static u_int
472 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
473 		  path_id_t pathid, target_id_t target, lun_id_t lun)
474 {
475 	struct	cam_periph *periph;
476 	char	*periph_name;
477 	int	i, val, dunit, r;
478 	const char *dname, *strval;
479 
480 	periph_name = p_drv->driver_name;
481 	for (;;newunit++) {
482 
483 		for (periph = TAILQ_FIRST(&p_drv->units);
484 		     periph != NULL && periph->unit_number != newunit;
485 		     periph = TAILQ_NEXT(periph, unit_links))
486 			;
487 
488 		if (periph != NULL && periph->unit_number == newunit) {
489 			if (wired != 0) {
490 				xpt_print(periph->path, "Duplicate Wired "
491 				    "Device entry!\n");
492 				xpt_print(periph->path, "Second device (%s "
493 				    "device at scbus%d target %d lun %d) will "
494 				    "not be wired\n", periph_name, pathid,
495 				    target, lun);
496 				wired = 0;
497 			}
498 			continue;
499 		}
500 		if (wired)
501 			break;
502 
503 		/*
504 		 * Don't match entries like "da 4" as a wired down
505 		 * device, but do match entries like "da 4 target 5"
506 		 * or even "da 4 scbus 1".
507 		 */
508 		i = 0;
509 		dname = periph_name;
510 		for (;;) {
511 			r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
512 			if (r != 0)
513 				break;
514 			/* if no "target" and no specific scbus, skip */
515 			if (resource_int_value(dname, dunit, "target", &val) &&
516 			    (resource_string_value(dname, dunit, "at",&strval)||
517 			     strcmp(strval, "scbus") == 0))
518 				continue;
519 			if (newunit == dunit)
520 				break;
521 		}
522 		if (r != 0)
523 			break;
524 	}
525 	return (newunit);
526 }
527 
528 static u_int
529 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
530 	      target_id_t target, lun_id_t lun)
531 {
532 	u_int	unit;
533 	int	wired, i, val, dunit;
534 	const char *dname, *strval;
535 	char	pathbuf[32], *periph_name;
536 
537 	periph_name = p_drv->driver_name;
538 	snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
539 	unit = 0;
540 	i = 0;
541 	dname = periph_name;
542 	for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
543 	     wired = 0) {
544 		if (resource_string_value(dname, dunit, "at", &strval) == 0) {
545 			if (strcmp(strval, pathbuf) != 0)
546 				continue;
547 			wired++;
548 		}
549 		if (resource_int_value(dname, dunit, "target", &val) == 0) {
550 			if (val != target)
551 				continue;
552 			wired++;
553 		}
554 		if (resource_int_value(dname, dunit, "lun", &val) == 0) {
555 			if (val != lun)
556 				continue;
557 			wired++;
558 		}
559 		if (wired != 0) {
560 			unit = dunit;
561 			break;
562 		}
563 	}
564 
565 	/*
566 	 * Either start from 0 looking for the next unit or from
567 	 * the unit number given in the resource config.  This way,
568 	 * if we have wildcard matches, we don't return the same
569 	 * unit number twice.
570 	 */
571 	unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
572 
573 	return (unit);
574 }
575 
576 void
577 cam_periph_invalidate(struct cam_periph *periph)
578 {
579 
580 	cam_periph_assert(periph, MA_OWNED);
581 	/*
582 	 * We only call this routine the first time a peripheral is
583 	 * invalidated.
584 	 */
585 	if ((periph->flags & CAM_PERIPH_INVALID) != 0)
586 		return;
587 
588 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
589 	if (periph->flags & CAM_PERIPH_ANNOUNCED)
590 		xpt_denounce_periph(periph);
591 	periph->flags |= CAM_PERIPH_INVALID;
592 	periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
593 	if (periph->periph_oninval != NULL)
594 		periph->periph_oninval(periph);
595 	cam_periph_release_locked(periph);
596 }
597 
598 static void
599 camperiphfree(struct cam_periph *periph)
600 {
601 	struct periph_driver **p_drv;
602 
603 	cam_periph_assert(periph, MA_OWNED);
604 	KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
605 	    periph->periph_name, periph->unit_number));
606 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
607 		if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
608 			break;
609 	}
610 	if (*p_drv == NULL) {
611 		printf("camperiphfree: attempt to free non-existant periph\n");
612 		return;
613 	}
614 
615 	/*
616 	 * We need to set this flag before dropping the topology lock, to
617 	 * let anyone who is traversing the list that this peripheral is
618 	 * about to be freed, and there will be no more reference count
619 	 * checks.
620 	 */
621 	periph->flags |= CAM_PERIPH_FREE;
622 
623 	/*
624 	 * The peripheral destructor semantics dictate calling with only the
625 	 * SIM mutex held.  Since it might sleep, it should not be called
626 	 * with the topology lock held.
627 	 */
628 	xpt_unlock_buses();
629 
630 	/*
631 	 * We need to call the peripheral destructor prior to removing the
632 	 * peripheral from the list.  Otherwise, we risk running into a
633 	 * scenario where the peripheral unit number may get reused
634 	 * (because it has been removed from the list), but some resources
635 	 * used by the peripheral are still hanging around.  In particular,
636 	 * the devfs nodes used by some peripherals like the pass(4) driver
637 	 * aren't fully cleaned up until the destructor is run.  If the
638 	 * unit number is reused before the devfs instance is fully gone,
639 	 * devfs will panic.
640 	 */
641 	if (periph->periph_dtor != NULL)
642 		periph->periph_dtor(periph);
643 
644 	/*
645 	 * The peripheral list is protected by the topology lock.
646 	 */
647 	xpt_lock_buses();
648 
649 	TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
650 	(*p_drv)->generation++;
651 
652 	xpt_remove_periph(periph);
653 
654 	xpt_unlock_buses();
655 	if (periph->flags & CAM_PERIPH_ANNOUNCED) {
656 		xpt_print(periph->path, "Periph destroyed\n");
657 	} else
658 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
659 
660 	if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
661 		union ccb ccb;
662 		void *arg;
663 
664 		switch (periph->deferred_ac) {
665 		case AC_FOUND_DEVICE:
666 			ccb.ccb_h.func_code = XPT_GDEV_TYPE;
667 			xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
668 			xpt_action(&ccb);
669 			arg = &ccb;
670 			break;
671 		case AC_PATH_REGISTERED:
672 			ccb.ccb_h.func_code = XPT_PATH_INQ;
673 			xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
674 			xpt_action(&ccb);
675 			arg = &ccb;
676 			break;
677 		default:
678 			arg = NULL;
679 			break;
680 		}
681 		periph->deferred_callback(NULL, periph->deferred_ac,
682 					  periph->path, arg);
683 	}
684 	xpt_free_path(periph->path);
685 	free(periph, M_CAMPERIPH);
686 	xpt_lock_buses();
687 }
688 
689 /*
690  * Map user virtual pointers into kernel virtual address space, so we can
691  * access the memory.  This is now a generic function that centralizes most
692  * of the sanity checks on the data flags, if any.
693  * This also only works for up to MAXPHYS memory.  Since we use
694  * buffers to map stuff in and out, we're limited to the buffer size.
695  */
696 int
697 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
698 {
699 	int numbufs, i, j;
700 	int flags[CAM_PERIPH_MAXMAPS];
701 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
702 	u_int32_t lengths[CAM_PERIPH_MAXMAPS];
703 	u_int32_t dirs[CAM_PERIPH_MAXMAPS];
704 	/* Some controllers may not be able to handle more data. */
705 	size_t maxmap = DFLTPHYS;
706 
707 	switch(ccb->ccb_h.func_code) {
708 	case XPT_DEV_MATCH:
709 		if (ccb->cdm.match_buf_len == 0) {
710 			printf("cam_periph_mapmem: invalid match buffer "
711 			       "length 0\n");
712 			return(EINVAL);
713 		}
714 		if (ccb->cdm.pattern_buf_len > 0) {
715 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
716 			lengths[0] = ccb->cdm.pattern_buf_len;
717 			dirs[0] = CAM_DIR_OUT;
718 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
719 			lengths[1] = ccb->cdm.match_buf_len;
720 			dirs[1] = CAM_DIR_IN;
721 			numbufs = 2;
722 		} else {
723 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
724 			lengths[0] = ccb->cdm.match_buf_len;
725 			dirs[0] = CAM_DIR_IN;
726 			numbufs = 1;
727 		}
728 		/*
729 		 * This request will not go to the hardware, no reason
730 		 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
731 		 */
732 		maxmap = MAXPHYS;
733 		break;
734 	case XPT_SCSI_IO:
735 	case XPT_CONT_TARGET_IO:
736 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
737 			return(0);
738 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
739 			return (EINVAL);
740 		data_ptrs[0] = &ccb->csio.data_ptr;
741 		lengths[0] = ccb->csio.dxfer_len;
742 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
743 		numbufs = 1;
744 		break;
745 	case XPT_ATA_IO:
746 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
747 			return(0);
748 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
749 			return (EINVAL);
750 		data_ptrs[0] = &ccb->ataio.data_ptr;
751 		lengths[0] = ccb->ataio.dxfer_len;
752 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
753 		numbufs = 1;
754 		break;
755 	case XPT_SMP_IO:
756 		data_ptrs[0] = &ccb->smpio.smp_request;
757 		lengths[0] = ccb->smpio.smp_request_len;
758 		dirs[0] = CAM_DIR_OUT;
759 		data_ptrs[1] = &ccb->smpio.smp_response;
760 		lengths[1] = ccb->smpio.smp_response_len;
761 		dirs[1] = CAM_DIR_IN;
762 		numbufs = 2;
763 		break;
764 	case XPT_DEV_ADVINFO:
765 		if (ccb->cdai.bufsiz == 0)
766 			return (0);
767 
768 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
769 		lengths[0] = ccb->cdai.bufsiz;
770 		dirs[0] = CAM_DIR_IN;
771 		numbufs = 1;
772 
773 		/*
774 		 * This request will not go to the hardware, no reason
775 		 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
776 		 */
777 		maxmap = MAXPHYS;
778 		break;
779 	default:
780 		return(EINVAL);
781 		break; /* NOTREACHED */
782 	}
783 
784 	/*
785 	 * Check the transfer length and permissions first, so we don't
786 	 * have to unmap any previously mapped buffers.
787 	 */
788 	for (i = 0; i < numbufs; i++) {
789 
790 		flags[i] = 0;
791 
792 		/*
793 		 * The userland data pointer passed in may not be page
794 		 * aligned.  vmapbuf() truncates the address to a page
795 		 * boundary, so if the address isn't page aligned, we'll
796 		 * need enough space for the given transfer length, plus
797 		 * whatever extra space is necessary to make it to the page
798 		 * boundary.
799 		 */
800 		if ((lengths[i] +
801 		    (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)) > maxmap){
802 			printf("cam_periph_mapmem: attempt to map %lu bytes, "
803 			       "which is greater than %lu\n",
804 			       (long)(lengths[i] +
805 			       (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)),
806 			       (u_long)maxmap);
807 			return(E2BIG);
808 		}
809 
810 		if (dirs[i] & CAM_DIR_OUT) {
811 			flags[i] = BIO_WRITE;
812 		}
813 
814 		if (dirs[i] & CAM_DIR_IN) {
815 			flags[i] = BIO_READ;
816 		}
817 
818 	}
819 
820 	/*
821 	 * This keeps the the kernel stack of current thread from getting
822 	 * swapped.  In low-memory situations where the kernel stack might
823 	 * otherwise get swapped out, this holds it and allows the thread
824 	 * to make progress and release the kernel mapped pages sooner.
825 	 *
826 	 * XXX KDM should I use P_NOSWAP instead?
827 	 */
828 	PHOLD(curproc);
829 
830 	for (i = 0; i < numbufs; i++) {
831 		/*
832 		 * Get the buffer.
833 		 */
834 		mapinfo->bp[i] = getpbuf(NULL);
835 
836 		/* save the buffer's data address */
837 		mapinfo->bp[i]->b_saveaddr = mapinfo->bp[i]->b_data;
838 
839 		/* put our pointer in the data slot */
840 		mapinfo->bp[i]->b_data = *data_ptrs[i];
841 
842 		/* set the transfer length, we know it's < MAXPHYS */
843 		mapinfo->bp[i]->b_bufsize = lengths[i];
844 
845 		/* set the direction */
846 		mapinfo->bp[i]->b_iocmd = flags[i];
847 
848 		/*
849 		 * Map the buffer into kernel memory.
850 		 *
851 		 * Note that useracc() alone is not a  sufficient test.
852 		 * vmapbuf() can still fail due to a smaller file mapped
853 		 * into a larger area of VM, or if userland races against
854 		 * vmapbuf() after the useracc() check.
855 		 */
856 		if (vmapbuf(mapinfo->bp[i], 1) < 0) {
857 			for (j = 0; j < i; ++j) {
858 				*data_ptrs[j] = mapinfo->bp[j]->b_saveaddr;
859 				vunmapbuf(mapinfo->bp[j]);
860 				relpbuf(mapinfo->bp[j], NULL);
861 			}
862 			relpbuf(mapinfo->bp[i], NULL);
863 			PRELE(curproc);
864 			return(EACCES);
865 		}
866 
867 		/* set our pointer to the new mapped area */
868 		*data_ptrs[i] = mapinfo->bp[i]->b_data;
869 
870 		mapinfo->num_bufs_used++;
871 	}
872 
873 	/*
874 	 * Now that we've gotten this far, change ownership to the kernel
875 	 * of the buffers so that we don't run afoul of returning to user
876 	 * space with locks (on the buffer) held.
877 	 */
878 	for (i = 0; i < numbufs; i++) {
879 		BUF_KERNPROC(mapinfo->bp[i]);
880 	}
881 
882 
883 	return(0);
884 }
885 
886 /*
887  * Unmap memory segments mapped into kernel virtual address space by
888  * cam_periph_mapmem().
889  */
890 void
891 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
892 {
893 	int numbufs, i;
894 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
895 
896 	if (mapinfo->num_bufs_used <= 0) {
897 		/* nothing to free and the process wasn't held. */
898 		return;
899 	}
900 
901 	switch (ccb->ccb_h.func_code) {
902 	case XPT_DEV_MATCH:
903 		numbufs = min(mapinfo->num_bufs_used, 2);
904 
905 		if (numbufs == 1) {
906 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
907 		} else {
908 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
909 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
910 		}
911 		break;
912 	case XPT_SCSI_IO:
913 	case XPT_CONT_TARGET_IO:
914 		data_ptrs[0] = &ccb->csio.data_ptr;
915 		numbufs = min(mapinfo->num_bufs_used, 1);
916 		break;
917 	case XPT_ATA_IO:
918 		data_ptrs[0] = &ccb->ataio.data_ptr;
919 		numbufs = min(mapinfo->num_bufs_used, 1);
920 		break;
921 	case XPT_SMP_IO:
922 		numbufs = min(mapinfo->num_bufs_used, 2);
923 		data_ptrs[0] = &ccb->smpio.smp_request;
924 		data_ptrs[1] = &ccb->smpio.smp_response;
925 		break;
926 	case XPT_DEV_ADVINFO:
927 		numbufs = min(mapinfo->num_bufs_used, 1);
928 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
929 		break;
930 	default:
931 		/* allow ourselves to be swapped once again */
932 		PRELE(curproc);
933 		return;
934 		break; /* NOTREACHED */
935 	}
936 
937 	for (i = 0; i < numbufs; i++) {
938 		/* Set the user's pointer back to the original value */
939 		*data_ptrs[i] = mapinfo->bp[i]->b_saveaddr;
940 
941 		/* unmap the buffer */
942 		vunmapbuf(mapinfo->bp[i]);
943 
944 		/* release the buffer */
945 		relpbuf(mapinfo->bp[i], NULL);
946 	}
947 
948 	/* allow ourselves to be swapped once again */
949 	PRELE(curproc);
950 }
951 
952 void
953 cam_periph_ccbwait(union ccb *ccb)
954 {
955 
956 	if ((ccb->ccb_h.pinfo.index != CAM_UNQUEUED_INDEX)
957 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG))
958 		xpt_path_sleep(ccb->ccb_h.path, &ccb->ccb_h.cbfcnp, PRIBIO,
959 		    "cbwait", 0);
960 }
961 
962 int
963 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
964 		 int (*error_routine)(union ccb *ccb,
965 				      cam_flags camflags,
966 				      u_int32_t sense_flags))
967 {
968 	union ccb 	     *ccb;
969 	int 		     error;
970 	int		     found;
971 
972 	error = found = 0;
973 
974 	switch(cmd){
975 	case CAMGETPASSTHRU:
976 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
977 		xpt_setup_ccb(&ccb->ccb_h,
978 			      ccb->ccb_h.path,
979 			      CAM_PRIORITY_NORMAL);
980 		ccb->ccb_h.func_code = XPT_GDEVLIST;
981 
982 		/*
983 		 * Basically, the point of this is that we go through
984 		 * getting the list of devices, until we find a passthrough
985 		 * device.  In the current version of the CAM code, the
986 		 * only way to determine what type of device we're dealing
987 		 * with is by its name.
988 		 */
989 		while (found == 0) {
990 			ccb->cgdl.index = 0;
991 			ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
992 			while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
993 
994 				/* we want the next device in the list */
995 				xpt_action(ccb);
996 				if (strncmp(ccb->cgdl.periph_name,
997 				    "pass", 4) == 0){
998 					found = 1;
999 					break;
1000 				}
1001 			}
1002 			if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1003 			    (found == 0)) {
1004 				ccb->cgdl.periph_name[0] = '\0';
1005 				ccb->cgdl.unit_number = 0;
1006 				break;
1007 			}
1008 		}
1009 
1010 		/* copy the result back out */
1011 		bcopy(ccb, addr, sizeof(union ccb));
1012 
1013 		/* and release the ccb */
1014 		xpt_release_ccb(ccb);
1015 
1016 		break;
1017 	default:
1018 		error = ENOTTY;
1019 		break;
1020 	}
1021 	return(error);
1022 }
1023 
1024 static void
1025 cam_periph_done(struct cam_periph *periph, union ccb *done_ccb)
1026 {
1027 
1028 	/* Caller will release the CCB */
1029 	wakeup(&done_ccb->ccb_h.cbfcnp);
1030 }
1031 
1032 int
1033 cam_periph_runccb(union ccb *ccb,
1034 		  int (*error_routine)(union ccb *ccb,
1035 				       cam_flags camflags,
1036 				       u_int32_t sense_flags),
1037 		  cam_flags camflags, u_int32_t sense_flags,
1038 		  struct devstat *ds)
1039 {
1040 	int error;
1041 
1042 	xpt_path_assert(ccb->ccb_h.path, MA_OWNED);
1043 
1044 	/*
1045 	 * If the user has supplied a stats structure, and if we understand
1046 	 * this particular type of ccb, record the transaction start.
1047 	 */
1048 	if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1049 	    ccb->ccb_h.func_code == XPT_ATA_IO))
1050 		devstat_start_transaction(ds, NULL);
1051 
1052 	ccb->ccb_h.cbfcnp = cam_periph_done;
1053 	xpt_action(ccb);
1054 
1055 	do {
1056 		cam_periph_ccbwait(ccb);
1057 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1058 			error = 0;
1059 		else if (error_routine != NULL)
1060 			error = (*error_routine)(ccb, camflags, sense_flags);
1061 		else
1062 			error = 0;
1063 
1064 	} while (error == ERESTART);
1065 
1066 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1067 		cam_release_devq(ccb->ccb_h.path,
1068 				 /* relsim_flags */0,
1069 				 /* openings */0,
1070 				 /* timeout */0,
1071 				 /* getcount_only */ FALSE);
1072 		ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1073 	}
1074 
1075 	if (ds != NULL) {
1076 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1077 			devstat_end_transaction(ds,
1078 					ccb->csio.dxfer_len,
1079 					ccb->csio.tag_action & 0x3,
1080 					((ccb->ccb_h.flags & CAM_DIR_MASK) ==
1081 					CAM_DIR_NONE) ?  DEVSTAT_NO_DATA :
1082 					(ccb->ccb_h.flags & CAM_DIR_OUT) ?
1083 					DEVSTAT_WRITE :
1084 					DEVSTAT_READ, NULL, NULL);
1085 		} else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1086 			devstat_end_transaction(ds,
1087 					ccb->ataio.dxfer_len,
1088 					ccb->ataio.tag_action & 0x3,
1089 					((ccb->ccb_h.flags & CAM_DIR_MASK) ==
1090 					CAM_DIR_NONE) ?  DEVSTAT_NO_DATA :
1091 					(ccb->ccb_h.flags & CAM_DIR_OUT) ?
1092 					DEVSTAT_WRITE :
1093 					DEVSTAT_READ, NULL, NULL);
1094 		}
1095 	}
1096 
1097 	return(error);
1098 }
1099 
1100 void
1101 cam_freeze_devq(struct cam_path *path)
1102 {
1103 	struct ccb_hdr ccb_h;
1104 
1105 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1106 	xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1107 	ccb_h.func_code = XPT_NOOP;
1108 	ccb_h.flags = CAM_DEV_QFREEZE;
1109 	xpt_action((union ccb *)&ccb_h);
1110 }
1111 
1112 u_int32_t
1113 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1114 		 u_int32_t openings, u_int32_t arg,
1115 		 int getcount_only)
1116 {
1117 	struct ccb_relsim crs;
1118 
1119 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1120 	    relsim_flags, openings, arg, getcount_only));
1121 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1122 	crs.ccb_h.func_code = XPT_REL_SIMQ;
1123 	crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1124 	crs.release_flags = relsim_flags;
1125 	crs.openings = openings;
1126 	crs.release_timeout = arg;
1127 	xpt_action((union ccb *)&crs);
1128 	return (crs.qfrozen_cnt);
1129 }
1130 
1131 #define saved_ccb_ptr ppriv_ptr0
1132 static void
1133 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1134 {
1135 	union ccb      *saved_ccb;
1136 	cam_status	status;
1137 	struct scsi_start_stop_unit *scsi_cmd;
1138 	int    error_code, sense_key, asc, ascq;
1139 
1140 	scsi_cmd = (struct scsi_start_stop_unit *)
1141 	    &done_ccb->csio.cdb_io.cdb_bytes;
1142 	status = done_ccb->ccb_h.status;
1143 
1144 	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1145 		if (scsi_extract_sense_ccb(done_ccb,
1146 		    &error_code, &sense_key, &asc, &ascq)) {
1147 			/*
1148 			 * If the error is "invalid field in CDB",
1149 			 * and the load/eject flag is set, turn the
1150 			 * flag off and try again.  This is just in
1151 			 * case the drive in question barfs on the
1152 			 * load eject flag.  The CAM code should set
1153 			 * the load/eject flag by default for
1154 			 * removable media.
1155 			 */
1156 			if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1157 			    ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1158 			     (asc == 0x24) && (ascq == 0x00)) {
1159 				scsi_cmd->how &= ~SSS_LOEJ;
1160 				if (status & CAM_DEV_QFRZN) {
1161 					cam_release_devq(done_ccb->ccb_h.path,
1162 					    0, 0, 0, 0);
1163 					done_ccb->ccb_h.status &=
1164 					    ~CAM_DEV_QFRZN;
1165 				}
1166 				xpt_action(done_ccb);
1167 				goto out;
1168 			}
1169 		}
1170 		if (cam_periph_error(done_ccb,
1171 		    0, SF_RETRY_UA | SF_NO_PRINT, NULL) == ERESTART)
1172 			goto out;
1173 		if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1174 			cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1175 			done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1176 		}
1177 	} else {
1178 		/*
1179 		 * If we have successfully taken a device from the not
1180 		 * ready to ready state, re-scan the device and re-get
1181 		 * the inquiry information.  Many devices (mostly disks)
1182 		 * don't properly report their inquiry information unless
1183 		 * they are spun up.
1184 		 */
1185 		if (scsi_cmd->opcode == START_STOP_UNIT)
1186 			xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1187 	}
1188 
1189 	/*
1190 	 * Perform the final retry with the original CCB so that final
1191 	 * error processing is performed by the owner of the CCB.
1192 	 */
1193 	saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1194 	bcopy(saved_ccb, done_ccb, sizeof(*done_ccb));
1195 	xpt_free_ccb(saved_ccb);
1196 	if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1197 		periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1198 	xpt_action(done_ccb);
1199 
1200 out:
1201 	/* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1202 	cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1203 }
1204 
1205 /*
1206  * Generic Async Event handler.  Peripheral drivers usually
1207  * filter out the events that require personal attention,
1208  * and leave the rest to this function.
1209  */
1210 void
1211 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1212 		 struct cam_path *path, void *arg)
1213 {
1214 	switch (code) {
1215 	case AC_LOST_DEVICE:
1216 		cam_periph_invalidate(periph);
1217 		break;
1218 	default:
1219 		break;
1220 	}
1221 }
1222 
1223 void
1224 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1225 {
1226 	struct ccb_getdevstats cgds;
1227 
1228 	xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1229 	cgds.ccb_h.func_code = XPT_GDEV_STATS;
1230 	xpt_action((union ccb *)&cgds);
1231 	cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1232 }
1233 
1234 void
1235 cam_periph_freeze_after_event(struct cam_periph *periph,
1236 			      struct timeval* event_time, u_int duration_ms)
1237 {
1238 	struct timeval delta;
1239 	struct timeval duration_tv;
1240 
1241 	if (!timevalisset(event_time))
1242 		return;
1243 
1244 	microtime(&delta);
1245 	timevalsub(&delta, event_time);
1246 	duration_tv.tv_sec = duration_ms / 1000;
1247 	duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1248 	if (timevalcmp(&delta, &duration_tv, <)) {
1249 		timevalsub(&duration_tv, &delta);
1250 
1251 		duration_ms = duration_tv.tv_sec * 1000;
1252 		duration_ms += duration_tv.tv_usec / 1000;
1253 		cam_freeze_devq(periph->path);
1254 		cam_release_devq(periph->path,
1255 				RELSIM_RELEASE_AFTER_TIMEOUT,
1256 				/*reduction*/0,
1257 				/*timeout*/duration_ms,
1258 				/*getcount_only*/0);
1259 	}
1260 
1261 }
1262 
1263 static int
1264 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1265     cam_flags camflags, u_int32_t sense_flags,
1266     int *openings, u_int32_t *relsim_flags,
1267     u_int32_t *timeout, u_int32_t *action, const char **action_string)
1268 {
1269 	int error;
1270 
1271 	switch (ccb->csio.scsi_status) {
1272 	case SCSI_STATUS_OK:
1273 	case SCSI_STATUS_COND_MET:
1274 	case SCSI_STATUS_INTERMED:
1275 	case SCSI_STATUS_INTERMED_COND_MET:
1276 		error = 0;
1277 		break;
1278 	case SCSI_STATUS_CMD_TERMINATED:
1279 	case SCSI_STATUS_CHECK_COND:
1280 		error = camperiphscsisenseerror(ccb, orig_ccb,
1281 					        camflags,
1282 					        sense_flags,
1283 					        openings,
1284 					        relsim_flags,
1285 					        timeout,
1286 					        action,
1287 					        action_string);
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 			      CAM_PRIORITY_NORMAL);
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 			*action &= ~SSQ_PRINT_SENSE;
1342 			break;
1343 		}
1344 		/* FALLTHROUGH */
1345 	}
1346 	case SCSI_STATUS_BUSY:
1347 		/*
1348 		 * Restart the queue after either another
1349 		 * command completes or a 1 second timeout.
1350 		 */
1351 	 	if (ccb->ccb_h.retry_count > 0) {
1352 	 		ccb->ccb_h.retry_count--;
1353 			error = ERESTART;
1354 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1355 				      | RELSIM_RELEASE_AFTER_CMDCMPLT;
1356 			*timeout = 1000;
1357 		} else {
1358 			error = EIO;
1359 		}
1360 		break;
1361 	case SCSI_STATUS_RESERV_CONFLICT:
1362 	default:
1363 		error = EIO;
1364 		break;
1365 	}
1366 	return (error);
1367 }
1368 
1369 static int
1370 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1371     cam_flags camflags, u_int32_t sense_flags,
1372     int *openings, u_int32_t *relsim_flags,
1373     u_int32_t *timeout, u_int32_t *action, const char **action_string)
1374 {
1375 	struct cam_periph *periph;
1376 	union ccb *orig_ccb = ccb;
1377 	int error, recoveryccb;
1378 
1379 	periph = xpt_path_periph(ccb->ccb_h.path);
1380 	recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1381 	if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1382 		/*
1383 		 * If error recovery is already in progress, don't attempt
1384 		 * to process this error, but requeue it unconditionally
1385 		 * and attempt to process it once error recovery has
1386 		 * completed.  This failed command is probably related to
1387 		 * the error that caused the currently active error recovery
1388 		 * action so our  current recovery efforts should also
1389 		 * address this command.  Be aware that the error recovery
1390 		 * code assumes that only one recovery action is in progress
1391 		 * on a particular peripheral instance at any given time
1392 		 * (e.g. only one saved CCB for error recovery) so it is
1393 		 * imperitive that we don't violate this assumption.
1394 		 */
1395 		error = ERESTART;
1396 		*action &= ~SSQ_PRINT_SENSE;
1397 	} else {
1398 		scsi_sense_action err_action;
1399 		struct ccb_getdev cgd;
1400 
1401 		/*
1402 		 * Grab the inquiry data for this device.
1403 		 */
1404 		xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1405 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1406 		xpt_action((union ccb *)&cgd);
1407 
1408 		err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1409 		    sense_flags);
1410 		error = err_action & SS_ERRMASK;
1411 
1412 		/*
1413 		 * Do not autostart sequential access devices
1414 		 * to avoid unexpected tape loading.
1415 		 */
1416 		if ((err_action & SS_MASK) == SS_START &&
1417 		    SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1418 			*action_string = "Will not autostart a "
1419 			    "sequential access device";
1420 			goto sense_error_done;
1421 		}
1422 
1423 		/*
1424 		 * Avoid recovery recursion if recovery action is the same.
1425 		 */
1426 		if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1427 			if (((err_action & SS_MASK) == SS_START &&
1428 			     ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1429 			    ((err_action & SS_MASK) == SS_TUR &&
1430 			     (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1431 				err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1432 				*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1433 				*timeout = 500;
1434 			}
1435 		}
1436 
1437 		/*
1438 		 * If the recovery action will consume a retry,
1439 		 * make sure we actually have retries available.
1440 		 */
1441 		if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1442 		 	if (ccb->ccb_h.retry_count > 0 &&
1443 			    (periph->flags & CAM_PERIPH_INVALID) == 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 			orig_ccb = xpt_alloc_ccb_nowait();
1457 			if (orig_ccb == NULL) {
1458 				*action_string = "Can't allocate recovery CCB";
1459 				goto sense_error_done;
1460 			}
1461 			/*
1462 			 * Clear freeze flag for original request here, as
1463 			 * this freeze will be dropped as part of ERESTART.
1464 			 */
1465 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1466 			bcopy(ccb, orig_ccb, sizeof(*orig_ccb));
1467 		}
1468 
1469 		switch (err_action & SS_MASK) {
1470 		case SS_NOP:
1471 			*action_string = "No recovery action needed";
1472 			error = 0;
1473 			break;
1474 		case SS_RETRY:
1475 			*action_string = "Retrying command (per sense data)";
1476 			error = ERESTART;
1477 			break;
1478 		case SS_FAIL:
1479 			*action_string = "Unretryable error";
1480 			break;
1481 		case SS_START:
1482 		{
1483 			int le;
1484 
1485 			/*
1486 			 * Send a start unit command to the device, and
1487 			 * then retry the command.
1488 			 */
1489 			*action_string = "Attempting to start unit";
1490 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1491 
1492 			/*
1493 			 * Check for removable media and set
1494 			 * load/eject flag appropriately.
1495 			 */
1496 			if (SID_IS_REMOVABLE(&cgd.inq_data))
1497 				le = TRUE;
1498 			else
1499 				le = FALSE;
1500 
1501 			scsi_start_stop(&ccb->csio,
1502 					/*retries*/1,
1503 					camperiphdone,
1504 					MSG_SIMPLE_Q_TAG,
1505 					/*start*/TRUE,
1506 					/*load/eject*/le,
1507 					/*immediate*/FALSE,
1508 					SSD_FULL_SIZE,
1509 					/*timeout*/50000);
1510 			break;
1511 		}
1512 		case SS_TUR:
1513 		{
1514 			/*
1515 			 * Send a Test Unit Ready to the device.
1516 			 * If the 'many' flag is set, we send 120
1517 			 * test unit ready commands, one every half
1518 			 * second.  Otherwise, we just send one TUR.
1519 			 * We only want to do this if the retry
1520 			 * count has not been exhausted.
1521 			 */
1522 			int retries;
1523 
1524 			if ((err_action & SSQ_MANY) != 0) {
1525 				*action_string = "Polling device for readiness";
1526 				retries = 120;
1527 			} else {
1528 				*action_string = "Testing device for readiness";
1529 				retries = 1;
1530 			}
1531 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1532 			scsi_test_unit_ready(&ccb->csio,
1533 					     retries,
1534 					     camperiphdone,
1535 					     MSG_SIMPLE_Q_TAG,
1536 					     SSD_FULL_SIZE,
1537 					     /*timeout*/5000);
1538 
1539 			/*
1540 			 * Accomplish our 500ms delay by deferring
1541 			 * the release of our device queue appropriately.
1542 			 */
1543 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1544 			*timeout = 500;
1545 			break;
1546 		}
1547 		default:
1548 			panic("Unhandled error action %x", err_action);
1549 		}
1550 
1551 		if ((err_action & SS_MASK) >= SS_START) {
1552 			/*
1553 			 * Drop the priority, so that the recovery
1554 			 * CCB is the first to execute.  Freeze the queue
1555 			 * after this command is sent so that we can
1556 			 * restore the old csio and have it queued in
1557 			 * the proper order before we release normal
1558 			 * transactions to the device.
1559 			 */
1560 			ccb->ccb_h.pinfo.priority--;
1561 			ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1562 			ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1563 			error = ERESTART;
1564 			*orig = orig_ccb;
1565 		}
1566 
1567 sense_error_done:
1568 		*action = err_action;
1569 	}
1570 	return (error);
1571 }
1572 
1573 /*
1574  * Generic error handler.  Peripheral drivers usually filter
1575  * out the errors that they handle in a unique mannor, then
1576  * call this function.
1577  */
1578 int
1579 cam_periph_error(union ccb *ccb, cam_flags camflags,
1580 		 u_int32_t sense_flags, union ccb *save_ccb)
1581 {
1582 	struct cam_path *newpath;
1583 	union ccb  *orig_ccb, *scan_ccb;
1584 	struct cam_periph *periph;
1585 	const char *action_string;
1586 	cam_status  status;
1587 	int	    frozen, error, openings;
1588 	u_int32_t   action, relsim_flags, timeout;
1589 
1590 	action = SSQ_PRINT_SENSE;
1591 	periph = xpt_path_periph(ccb->ccb_h.path);
1592 	action_string = NULL;
1593 	status = ccb->ccb_h.status;
1594 	frozen = (status & CAM_DEV_QFRZN) != 0;
1595 	status &= CAM_STATUS_MASK;
1596 	openings = relsim_flags = timeout = 0;
1597 	orig_ccb = ccb;
1598 
1599 	switch (status) {
1600 	case CAM_REQ_CMP:
1601 		error = 0;
1602 		action &= ~SSQ_PRINT_SENSE;
1603 		break;
1604 	case CAM_SCSI_STATUS_ERROR:
1605 		error = camperiphscsistatuserror(ccb, &orig_ccb,
1606 		    camflags, sense_flags, &openings, &relsim_flags,
1607 		    &timeout, &action, &action_string);
1608 		break;
1609 	case CAM_AUTOSENSE_FAIL:
1610 		error = EIO;	/* we have to kill the command */
1611 		break;
1612 	case CAM_UA_ABORT:
1613 	case CAM_UA_TERMIO:
1614 	case CAM_MSG_REJECT_REC:
1615 		/* XXX Don't know that these are correct */
1616 		error = EIO;
1617 		break;
1618 	case CAM_SEL_TIMEOUT:
1619 		if ((camflags & CAM_RETRY_SELTO) != 0) {
1620 			if (ccb->ccb_h.retry_count > 0 &&
1621 			    (periph->flags & CAM_PERIPH_INVALID) == 0) {
1622 				ccb->ccb_h.retry_count--;
1623 				error = ERESTART;
1624 
1625 				/*
1626 				 * Wait a bit to give the device
1627 				 * time to recover before we try again.
1628 				 */
1629 				relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1630 				timeout = periph_selto_delay;
1631 				break;
1632 			}
1633 			action_string = "Retries exhausted";
1634 		}
1635 		/* FALLTHROUGH */
1636 	case CAM_DEV_NOT_THERE:
1637 		error = ENXIO;
1638 		action = SSQ_LOST;
1639 		break;
1640 	case CAM_REQ_INVALID:
1641 	case CAM_PATH_INVALID:
1642 	case CAM_NO_HBA:
1643 	case CAM_PROVIDE_FAIL:
1644 	case CAM_REQ_TOO_BIG:
1645 	case CAM_LUN_INVALID:
1646 	case CAM_TID_INVALID:
1647 		error = EINVAL;
1648 		break;
1649 	case CAM_SCSI_BUS_RESET:
1650 	case CAM_BDR_SENT:
1651 		/*
1652 		 * Commands that repeatedly timeout and cause these
1653 		 * kinds of error recovery actions, should return
1654 		 * CAM_CMD_TIMEOUT, which allows us to safely assume
1655 		 * that this command was an innocent bystander to
1656 		 * these events and should be unconditionally
1657 		 * retried.
1658 		 */
1659 	case CAM_REQUEUE_REQ:
1660 		/* Unconditional requeue if device is still there */
1661 		if (periph->flags & CAM_PERIPH_INVALID) {
1662 			action_string = "Periph was invalidated";
1663 			error = EIO;
1664 		} else if (sense_flags & SF_NO_RETRY) {
1665 			error = EIO;
1666 			action_string = "Retry was blocked";
1667 		} else {
1668 			error = ERESTART;
1669 			action &= ~SSQ_PRINT_SENSE;
1670 		}
1671 		break;
1672 	case CAM_RESRC_UNAVAIL:
1673 		/* Wait a bit for the resource shortage to abate. */
1674 		timeout = periph_noresrc_delay;
1675 		/* FALLTHROUGH */
1676 	case CAM_BUSY:
1677 		if (timeout == 0) {
1678 			/* Wait a bit for the busy condition to abate. */
1679 			timeout = periph_busy_delay;
1680 		}
1681 		relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1682 		/* FALLTHROUGH */
1683 	case CAM_ATA_STATUS_ERROR:
1684 	case CAM_REQ_CMP_ERR:
1685 	case CAM_CMD_TIMEOUT:
1686 	case CAM_UNEXP_BUSFREE:
1687 	case CAM_UNCOR_PARITY:
1688 	case CAM_DATA_RUN_ERR:
1689 	default:
1690 		if (periph->flags & CAM_PERIPH_INVALID) {
1691 			error = EIO;
1692 			action_string = "Periph was invalidated";
1693 		} else if (ccb->ccb_h.retry_count == 0) {
1694 			error = EIO;
1695 			action_string = "Retries exhausted";
1696 		} else if (sense_flags & SF_NO_RETRY) {
1697 			error = EIO;
1698 			action_string = "Retry was blocked";
1699 		} else {
1700 			ccb->ccb_h.retry_count--;
1701 			error = ERESTART;
1702 		}
1703 		break;
1704 	}
1705 
1706 	if ((sense_flags & SF_PRINT_ALWAYS) ||
1707 	    CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
1708 		action |= SSQ_PRINT_SENSE;
1709 	else if (sense_flags & SF_NO_PRINT)
1710 		action &= ~SSQ_PRINT_SENSE;
1711 	if ((action & SSQ_PRINT_SENSE) != 0)
1712 		cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1713 	if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
1714 		if (error != ERESTART) {
1715 			if (action_string == NULL)
1716 				action_string = "Unretryable error";
1717 			xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
1718 			    error, action_string);
1719 		} else if (action_string != NULL)
1720 			xpt_print(ccb->ccb_h.path, "%s\n", action_string);
1721 		else
1722 			xpt_print(ccb->ccb_h.path, "Retrying command\n");
1723 	}
1724 
1725 	if ((action & SSQ_LOST) != 0) {
1726 		lun_id_t lun_id;
1727 
1728 		/*
1729 		 * For a selection timeout, we consider all of the LUNs on
1730 		 * the target to be gone.  If the status is CAM_DEV_NOT_THERE,
1731 		 * then we only get rid of the device(s) specified by the
1732 		 * path in the original CCB.
1733 		 */
1734 		if (status == CAM_SEL_TIMEOUT)
1735 			lun_id = CAM_LUN_WILDCARD;
1736 		else
1737 			lun_id = xpt_path_lun_id(ccb->ccb_h.path);
1738 
1739 		/* Should we do more if we can't create the path?? */
1740 		if (xpt_create_path(&newpath, periph,
1741 				    xpt_path_path_id(ccb->ccb_h.path),
1742 				    xpt_path_target_id(ccb->ccb_h.path),
1743 				    lun_id) == CAM_REQ_CMP) {
1744 
1745 			/*
1746 			 * Let peripheral drivers know that this
1747 			 * device has gone away.
1748 			 */
1749 			xpt_async(AC_LOST_DEVICE, newpath, NULL);
1750 			xpt_free_path(newpath);
1751 		}
1752 	}
1753 
1754 	/* Broadcast UNIT ATTENTIONs to all periphs. */
1755 	if ((action & SSQ_UA) != 0)
1756 		xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
1757 
1758 	/* Rescan target on "Reported LUNs data has changed" */
1759 	if ((action & SSQ_RESCAN) != 0) {
1760 		if (xpt_create_path(&newpath, NULL,
1761 				    xpt_path_path_id(ccb->ccb_h.path),
1762 				    xpt_path_target_id(ccb->ccb_h.path),
1763 				    CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
1764 
1765 			scan_ccb = xpt_alloc_ccb_nowait();
1766 			if (scan_ccb != NULL) {
1767 				scan_ccb->ccb_h.path = newpath;
1768 				scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
1769 				scan_ccb->crcn.flags = 0;
1770 				xpt_rescan(scan_ccb);
1771 			} else {
1772 				xpt_print(newpath,
1773 				    "Can't allocate CCB to rescan target\n");
1774 				xpt_free_path(newpath);
1775 			}
1776 		}
1777 	}
1778 
1779 	/* Attempt a retry */
1780 	if (error == ERESTART || error == 0) {
1781 		if (frozen != 0)
1782 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1783 		if (error == ERESTART)
1784 			xpt_action(ccb);
1785 		if (frozen != 0)
1786 			cam_release_devq(ccb->ccb_h.path,
1787 					 relsim_flags,
1788 					 openings,
1789 					 timeout,
1790 					 /*getcount_only*/0);
1791 	}
1792 
1793 	return (error);
1794 }
1795