xref: /freebsd/sys/cam/cam_periph.c (revision d184218c18d067f8fd47203f54ab02a7b2ed9b11)
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 						 int *print,
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 					        int *print,
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 	cam_init_pinfo(&periph->pinfo);
200 	periph->periph_start = periph_start;
201 	periph->periph_dtor = periph_dtor;
202 	periph->periph_oninval = periph_oninvalidate;
203 	periph->type = type;
204 	periph->periph_name = name;
205 	periph->immediate_priority = CAM_PRIORITY_NONE;
206 	periph->refcount = 0;
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, /*topology_lock_held*/ 0);
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 				mtx_assert(periph->sim->mtx, 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 	mtx_assert(periph->sim->mtx, MA_OWNED);
383 	KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
384 	if (--periph->refcount == 0
385 	    && (periph->flags & CAM_PERIPH_INVALID)) {
386 		camperiphfree(periph);
387 	}
388 }
389 
390 void
391 cam_periph_release_locked(struct cam_periph *periph)
392 {
393 
394 	if (periph == NULL)
395 		return;
396 
397 	xpt_lock_buses();
398 	cam_periph_release_locked_buses(periph);
399 	xpt_unlock_buses();
400 }
401 
402 void
403 cam_periph_release(struct cam_periph *periph)
404 {
405 	struct cam_sim *sim;
406 
407 	if (periph == NULL)
408 		return;
409 
410 	sim = periph->sim;
411 	mtx_assert(sim->mtx, MA_NOTOWNED);
412 	mtx_lock(sim->mtx);
413 	cam_periph_release_locked(periph);
414 	mtx_unlock(sim->mtx);
415 }
416 
417 int
418 cam_periph_hold(struct cam_periph *periph, int priority)
419 {
420 	int error;
421 
422 	/*
423 	 * Increment the reference count on the peripheral
424 	 * while we wait for our lock attempt to succeed
425 	 * to ensure the peripheral doesn't disappear out
426 	 * from user us while we sleep.
427 	 */
428 
429 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
430 		return (ENXIO);
431 
432 	mtx_assert(periph->sim->mtx, MA_OWNED);
433 	while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
434 		periph->flags |= CAM_PERIPH_LOCK_WANTED;
435 		if ((error = mtx_sleep(periph, periph->sim->mtx, priority,
436 		    "caplck", 0)) != 0) {
437 			cam_periph_release_locked(periph);
438 			return (error);
439 		}
440 		if (periph->flags & CAM_PERIPH_INVALID) {
441 			cam_periph_release_locked(periph);
442 			return (ENXIO);
443 		}
444 	}
445 
446 	periph->flags |= CAM_PERIPH_LOCKED;
447 	return (0);
448 }
449 
450 void
451 cam_periph_unhold(struct cam_periph *periph)
452 {
453 
454 	mtx_assert(periph->sim->mtx, MA_OWNED);
455 
456 	periph->flags &= ~CAM_PERIPH_LOCKED;
457 	if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
458 		periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
459 		wakeup(periph);
460 	}
461 
462 	cam_periph_release_locked(periph);
463 }
464 
465 /*
466  * Look for the next unit number that is not currently in use for this
467  * peripheral type starting at "newunit".  Also exclude unit numbers that
468  * are reserved by for future "hardwiring" unless we already know that this
469  * is a potential wired device.  Only assume that the device is "wired" the
470  * first time through the loop since after that we'll be looking at unit
471  * numbers that did not match a wiring entry.
472  */
473 static u_int
474 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
475 		  path_id_t pathid, target_id_t target, lun_id_t lun)
476 {
477 	struct	cam_periph *periph;
478 	char	*periph_name;
479 	int	i, val, dunit, r;
480 	const char *dname, *strval;
481 
482 	periph_name = p_drv->driver_name;
483 	for (;;newunit++) {
484 
485 		for (periph = TAILQ_FIRST(&p_drv->units);
486 		     periph != NULL && periph->unit_number != newunit;
487 		     periph = TAILQ_NEXT(periph, unit_links))
488 			;
489 
490 		if (periph != NULL && periph->unit_number == newunit) {
491 			if (wired != 0) {
492 				xpt_print(periph->path, "Duplicate Wired "
493 				    "Device entry!\n");
494 				xpt_print(periph->path, "Second device (%s "
495 				    "device at scbus%d target %d lun %d) will "
496 				    "not be wired\n", periph_name, pathid,
497 				    target, lun);
498 				wired = 0;
499 			}
500 			continue;
501 		}
502 		if (wired)
503 			break;
504 
505 		/*
506 		 * Don't match entries like "da 4" as a wired down
507 		 * device, but do match entries like "da 4 target 5"
508 		 * or even "da 4 scbus 1".
509 		 */
510 		i = 0;
511 		dname = periph_name;
512 		for (;;) {
513 			r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
514 			if (r != 0)
515 				break;
516 			/* if no "target" and no specific scbus, skip */
517 			if (resource_int_value(dname, dunit, "target", &val) &&
518 			    (resource_string_value(dname, dunit, "at",&strval)||
519 			     strcmp(strval, "scbus") == 0))
520 				continue;
521 			if (newunit == dunit)
522 				break;
523 		}
524 		if (r != 0)
525 			break;
526 	}
527 	return (newunit);
528 }
529 
530 static u_int
531 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
532 	      target_id_t target, lun_id_t lun)
533 {
534 	u_int	unit;
535 	int	wired, i, val, dunit;
536 	const char *dname, *strval;
537 	char	pathbuf[32], *periph_name;
538 
539 	periph_name = p_drv->driver_name;
540 	snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
541 	unit = 0;
542 	i = 0;
543 	dname = periph_name;
544 	for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
545 	     wired = 0) {
546 		if (resource_string_value(dname, dunit, "at", &strval) == 0) {
547 			if (strcmp(strval, pathbuf) != 0)
548 				continue;
549 			wired++;
550 		}
551 		if (resource_int_value(dname, dunit, "target", &val) == 0) {
552 			if (val != target)
553 				continue;
554 			wired++;
555 		}
556 		if (resource_int_value(dname, dunit, "lun", &val) == 0) {
557 			if (val != lun)
558 				continue;
559 			wired++;
560 		}
561 		if (wired != 0) {
562 			unit = dunit;
563 			break;
564 		}
565 	}
566 
567 	/*
568 	 * Either start from 0 looking for the next unit or from
569 	 * the unit number given in the resource config.  This way,
570 	 * if we have wildcard matches, we don't return the same
571 	 * unit number twice.
572 	 */
573 	unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
574 
575 	return (unit);
576 }
577 
578 void
579 cam_periph_invalidate(struct cam_periph *periph)
580 {
581 
582 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
583 	mtx_assert(periph->sim->mtx, MA_OWNED);
584 	/*
585 	 * We only call this routine the first time a peripheral is
586 	 * invalidated.
587 	 */
588 	if (((periph->flags & CAM_PERIPH_INVALID) == 0)
589 	 && (periph->periph_oninval != NULL))
590 		periph->periph_oninval(periph);
591 
592 	periph->flags |= CAM_PERIPH_INVALID;
593 	periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
594 
595 	xpt_lock_buses();
596 	if (periph->refcount == 0)
597 		camperiphfree(periph);
598 	xpt_unlock_buses();
599 }
600 
601 static void
602 camperiphfree(struct cam_periph *periph)
603 {
604 	struct periph_driver **p_drv;
605 
606 	mtx_assert(periph->sim->mtx, MA_OWNED);
607 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
608 		if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
609 			break;
610 	}
611 	if (*p_drv == NULL) {
612 		printf("camperiphfree: attempt to free non-existant periph\n");
613 		return;
614 	}
615 
616 	/*
617 	 * We need to set this flag before dropping the topology lock, to
618 	 * let anyone who is traversing the list that this peripheral is
619 	 * about to be freed, and there will be no more reference count
620 	 * checks.
621 	 */
622 	periph->flags |= CAM_PERIPH_FREE;
623 
624 	/*
625 	 * The peripheral destructor semantics dictate calling with only the
626 	 * SIM mutex held.  Since it might sleep, it should not be called
627 	 * with the topology lock held.
628 	 */
629 	xpt_unlock_buses();
630 
631 	/*
632 	 * We need to call the peripheral destructor prior to removing the
633 	 * peripheral from the list.  Otherwise, we risk running into a
634 	 * scenario where the peripheral unit number may get reused
635 	 * (because it has been removed from the list), but some resources
636 	 * used by the peripheral are still hanging around.  In particular,
637 	 * the devfs nodes used by some peripherals like the pass(4) driver
638 	 * aren't fully cleaned up until the destructor is run.  If the
639 	 * unit number is reused before the devfs instance is fully gone,
640 	 * devfs will panic.
641 	 */
642 	if (periph->periph_dtor != NULL)
643 		periph->periph_dtor(periph);
644 
645 	/*
646 	 * The peripheral list is protected by the topology lock.
647 	 */
648 	xpt_lock_buses();
649 
650 	TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
651 	(*p_drv)->generation++;
652 
653 	xpt_remove_periph(periph, /*topology_lock_held*/ 1);
654 
655 	xpt_unlock_buses();
656 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
657 
658 	if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
659 		union ccb ccb;
660 		void *arg;
661 
662 		switch (periph->deferred_ac) {
663 		case AC_FOUND_DEVICE:
664 			ccb.ccb_h.func_code = XPT_GDEV_TYPE;
665 			xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
666 			xpt_action(&ccb);
667 			arg = &ccb;
668 			break;
669 		case AC_PATH_REGISTERED:
670 			ccb.ccb_h.func_code = XPT_PATH_INQ;
671 			xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
672 			xpt_action(&ccb);
673 			arg = &ccb;
674 			break;
675 		default:
676 			arg = NULL;
677 			break;
678 		}
679 		periph->deferred_callback(NULL, periph->deferred_ac,
680 					  periph->path, arg);
681 	}
682 	xpt_free_path(periph->path);
683 	free(periph, M_CAMPERIPH);
684 	xpt_lock_buses();
685 }
686 
687 /*
688  * Map user virtual pointers into kernel virtual address space, so we can
689  * access the memory.  This won't work on physical pointers, for now it's
690  * up to the caller to check for that.  (XXX KDM -- should we do that here
691  * instead?)  This also only works for up to MAXPHYS memory.  Since we use
692  * buffers to map stuff in and out, we're limited to the buffer size.
693  */
694 int
695 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
696 {
697 	int numbufs, i, j;
698 	int flags[CAM_PERIPH_MAXMAPS];
699 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
700 	u_int32_t lengths[CAM_PERIPH_MAXMAPS];
701 	u_int32_t dirs[CAM_PERIPH_MAXMAPS];
702 	/* Some controllers may not be able to handle more data. */
703 	size_t maxmap = DFLTPHYS;
704 
705 	switch(ccb->ccb_h.func_code) {
706 	case XPT_DEV_MATCH:
707 		if (ccb->cdm.match_buf_len == 0) {
708 			printf("cam_periph_mapmem: invalid match buffer "
709 			       "length 0\n");
710 			return(EINVAL);
711 		}
712 		if (ccb->cdm.pattern_buf_len > 0) {
713 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
714 			lengths[0] = ccb->cdm.pattern_buf_len;
715 			dirs[0] = CAM_DIR_OUT;
716 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
717 			lengths[1] = ccb->cdm.match_buf_len;
718 			dirs[1] = CAM_DIR_IN;
719 			numbufs = 2;
720 		} else {
721 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
722 			lengths[0] = ccb->cdm.match_buf_len;
723 			dirs[0] = CAM_DIR_IN;
724 			numbufs = 1;
725 		}
726 		/*
727 		 * This request will not go to the hardware, no reason
728 		 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
729 		 */
730 		maxmap = MAXPHYS;
731 		break;
732 	case XPT_SCSI_IO:
733 	case XPT_CONT_TARGET_IO:
734 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
735 			return(0);
736 		KASSERT((ccb->ccb_h.flags & CAM_DATA_MASK) == CAM_DATA_VADDR,
737 		    ("not VADDR for SCSI_IO %p %x\n", ccb, ccb->ccb_h.flags));
738 
739 		data_ptrs[0] = &ccb->csio.data_ptr;
740 		lengths[0] = ccb->csio.dxfer_len;
741 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
742 		numbufs = 1;
743 		break;
744 	case XPT_ATA_IO:
745 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
746 			return(0);
747 		KASSERT((ccb->ccb_h.flags & CAM_DATA_MASK) == CAM_DATA_VADDR,
748 		    ("not VADDR for ATA_IO %p %x\n", ccb, ccb->ccb_h.flags));
749 
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 	/* this keeps the current process from getting swapped */
821 	/*
822 	 * XXX KDM should I use P_NOSWAP instead?
823 	 */
824 	PHOLD(curproc);
825 
826 	for (i = 0; i < numbufs; i++) {
827 		/*
828 		 * Get the buffer.
829 		 */
830 		mapinfo->bp[i] = getpbuf(NULL);
831 
832 		/* save the buffer's data address */
833 		mapinfo->bp[i]->b_saveaddr = mapinfo->bp[i]->b_data;
834 
835 		/* put our pointer in the data slot */
836 		mapinfo->bp[i]->b_data = *data_ptrs[i];
837 
838 		/* set the transfer length, we know it's < MAXPHYS */
839 		mapinfo->bp[i]->b_bufsize = lengths[i];
840 
841 		/* set the direction */
842 		mapinfo->bp[i]->b_iocmd = flags[i];
843 
844 		/*
845 		 * Map the buffer into kernel memory.
846 		 *
847 		 * Note that useracc() alone is not a  sufficient test.
848 		 * vmapbuf() can still fail due to a smaller file mapped
849 		 * into a larger area of VM, or if userland races against
850 		 * vmapbuf() after the useracc() check.
851 		 */
852 		if (vmapbuf(mapinfo->bp[i], 1) < 0) {
853 			for (j = 0; j < i; ++j) {
854 				*data_ptrs[j] = mapinfo->bp[j]->b_saveaddr;
855 				vunmapbuf(mapinfo->bp[j]);
856 				relpbuf(mapinfo->bp[j], NULL);
857 			}
858 			relpbuf(mapinfo->bp[i], NULL);
859 			PRELE(curproc);
860 			return(EACCES);
861 		}
862 
863 		/* set our pointer to the new mapped area */
864 		*data_ptrs[i] = mapinfo->bp[i]->b_data;
865 
866 		mapinfo->num_bufs_used++;
867 	}
868 
869 	/*
870 	 * Now that we've gotten this far, change ownership to the kernel
871 	 * of the buffers so that we don't run afoul of returning to user
872 	 * space with locks (on the buffer) held.
873 	 */
874 	for (i = 0; i < numbufs; i++) {
875 		BUF_KERNPROC(mapinfo->bp[i]);
876 	}
877 
878 
879 	return(0);
880 }
881 
882 /*
883  * Unmap memory segments mapped into kernel virtual address space by
884  * cam_periph_mapmem().
885  */
886 void
887 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
888 {
889 	int numbufs, i;
890 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
891 
892 	if (mapinfo->num_bufs_used <= 0) {
893 		/* allow ourselves to be swapped once again */
894 		PRELE(curproc);
895 		return;
896 	}
897 
898 	switch (ccb->ccb_h.func_code) {
899 	case XPT_DEV_MATCH:
900 		numbufs = min(mapinfo->num_bufs_used, 2);
901 
902 		if (numbufs == 1) {
903 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
904 		} else {
905 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
906 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
907 		}
908 		break;
909 	case XPT_SCSI_IO:
910 	case XPT_CONT_TARGET_IO:
911 		data_ptrs[0] = &ccb->csio.data_ptr;
912 		numbufs = min(mapinfo->num_bufs_used, 1);
913 		break;
914 	case XPT_ATA_IO:
915 		data_ptrs[0] = &ccb->ataio.data_ptr;
916 		numbufs = min(mapinfo->num_bufs_used, 1);
917 		break;
918 	case XPT_SMP_IO:
919 		numbufs = min(mapinfo->num_bufs_used, 2);
920 		data_ptrs[0] = &ccb->smpio.smp_request;
921 		data_ptrs[1] = &ccb->smpio.smp_response;
922 		break;
923 	case XPT_DEV_ADVINFO:
924 		numbufs = min(mapinfo->num_bufs_used, 1);
925 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
926 		break;
927 	default:
928 		/* allow ourselves to be swapped once again */
929 		PRELE(curproc);
930 		return;
931 		break; /* NOTREACHED */
932 	}
933 
934 	for (i = 0; i < numbufs; i++) {
935 		/* Set the user's pointer back to the original value */
936 		*data_ptrs[i] = mapinfo->bp[i]->b_saveaddr;
937 
938 		/* unmap the buffer */
939 		vunmapbuf(mapinfo->bp[i]);
940 
941 		/* release the buffer */
942 		relpbuf(mapinfo->bp[i], NULL);
943 	}
944 
945 	/* allow ourselves to be swapped once again */
946 	PRELE(curproc);
947 }
948 
949 union ccb *
950 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
951 {
952 	struct ccb_hdr *ccb_h;
953 
954 	mtx_assert(periph->sim->mtx, MA_OWNED);
955 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdgetccb\n"));
956 
957 	while (SLIST_FIRST(&periph->ccb_list) == NULL) {
958 		if (periph->immediate_priority > priority)
959 			periph->immediate_priority = priority;
960 		xpt_schedule(periph, priority);
961 		if ((SLIST_FIRST(&periph->ccb_list) != NULL)
962 		 && (SLIST_FIRST(&periph->ccb_list)->pinfo.priority == priority))
963 			break;
964 		mtx_assert(periph->sim->mtx, MA_OWNED);
965 		mtx_sleep(&periph->ccb_list, periph->sim->mtx, PRIBIO, "cgticb",
966 		    0);
967 	}
968 
969 	ccb_h = SLIST_FIRST(&periph->ccb_list);
970 	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
971 	return ((union ccb *)ccb_h);
972 }
973 
974 void
975 cam_periph_ccbwait(union ccb *ccb)
976 {
977 	struct cam_sim *sim;
978 
979 	sim = xpt_path_sim(ccb->ccb_h.path);
980 	if ((ccb->ccb_h.pinfo.index != CAM_UNQUEUED_INDEX)
981 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG))
982 		mtx_sleep(&ccb->ccb_h.cbfcnp, sim->mtx, PRIBIO, "cbwait", 0);
983 }
984 
985 int
986 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
987 		 int (*error_routine)(union ccb *ccb,
988 				      cam_flags camflags,
989 				      u_int32_t sense_flags))
990 {
991 	union ccb 	     *ccb;
992 	int 		     error;
993 	int		     found;
994 
995 	error = found = 0;
996 
997 	switch(cmd){
998 	case CAMGETPASSTHRU:
999 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1000 		xpt_setup_ccb(&ccb->ccb_h,
1001 			      ccb->ccb_h.path,
1002 			      CAM_PRIORITY_NORMAL);
1003 		ccb->ccb_h.func_code = XPT_GDEVLIST;
1004 
1005 		/*
1006 		 * Basically, the point of this is that we go through
1007 		 * getting the list of devices, until we find a passthrough
1008 		 * device.  In the current version of the CAM code, the
1009 		 * only way to determine what type of device we're dealing
1010 		 * with is by its name.
1011 		 */
1012 		while (found == 0) {
1013 			ccb->cgdl.index = 0;
1014 			ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1015 			while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
1016 
1017 				/* we want the next device in the list */
1018 				xpt_action(ccb);
1019 				if (strncmp(ccb->cgdl.periph_name,
1020 				    "pass", 4) == 0){
1021 					found = 1;
1022 					break;
1023 				}
1024 			}
1025 			if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1026 			    (found == 0)) {
1027 				ccb->cgdl.periph_name[0] = '\0';
1028 				ccb->cgdl.unit_number = 0;
1029 				break;
1030 			}
1031 		}
1032 
1033 		/* copy the result back out */
1034 		bcopy(ccb, addr, sizeof(union ccb));
1035 
1036 		/* and release the ccb */
1037 		xpt_release_ccb(ccb);
1038 
1039 		break;
1040 	default:
1041 		error = ENOTTY;
1042 		break;
1043 	}
1044 	return(error);
1045 }
1046 
1047 int
1048 cam_periph_runccb(union ccb *ccb,
1049 		  int (*error_routine)(union ccb *ccb,
1050 				       cam_flags camflags,
1051 				       u_int32_t sense_flags),
1052 		  cam_flags camflags, u_int32_t sense_flags,
1053 		  struct devstat *ds)
1054 {
1055 	struct cam_sim *sim;
1056 	int error;
1057 
1058 	error = 0;
1059 	sim = xpt_path_sim(ccb->ccb_h.path);
1060 	mtx_assert(sim->mtx, MA_OWNED);
1061 
1062 	/*
1063 	 * If the user has supplied a stats structure, and if we understand
1064 	 * this particular type of ccb, record the transaction start.
1065 	 */
1066 	if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1067 	    ccb->ccb_h.func_code == XPT_ATA_IO))
1068 		devstat_start_transaction(ds, NULL);
1069 
1070 	xpt_action(ccb);
1071 
1072 	do {
1073 		cam_periph_ccbwait(ccb);
1074 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1075 			error = 0;
1076 		else if (error_routine != NULL)
1077 			error = (*error_routine)(ccb, camflags, sense_flags);
1078 		else
1079 			error = 0;
1080 
1081 	} while (error == ERESTART);
1082 
1083 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1084 		cam_release_devq(ccb->ccb_h.path,
1085 				 /* relsim_flags */0,
1086 				 /* openings */0,
1087 				 /* timeout */0,
1088 				 /* getcount_only */ FALSE);
1089 		ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1090 	}
1091 
1092 	if (ds != NULL) {
1093 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1094 			devstat_end_transaction(ds,
1095 					ccb->csio.dxfer_len,
1096 					ccb->csio.tag_action & 0x3,
1097 					((ccb->ccb_h.flags & CAM_DIR_MASK) ==
1098 					CAM_DIR_NONE) ?  DEVSTAT_NO_DATA :
1099 					(ccb->ccb_h.flags & CAM_DIR_OUT) ?
1100 					DEVSTAT_WRITE :
1101 					DEVSTAT_READ, NULL, NULL);
1102 		} else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1103 			devstat_end_transaction(ds,
1104 					ccb->ataio.dxfer_len,
1105 					ccb->ataio.tag_action & 0x3,
1106 					((ccb->ccb_h.flags & CAM_DIR_MASK) ==
1107 					CAM_DIR_NONE) ?  DEVSTAT_NO_DATA :
1108 					(ccb->ccb_h.flags & CAM_DIR_OUT) ?
1109 					DEVSTAT_WRITE :
1110 					DEVSTAT_READ, NULL, NULL);
1111 		}
1112 	}
1113 
1114 	return(error);
1115 }
1116 
1117 void
1118 cam_freeze_devq(struct cam_path *path)
1119 {
1120 
1121 	cam_freeze_devq_arg(path, 0, 0);
1122 }
1123 
1124 void
1125 cam_freeze_devq_arg(struct cam_path *path, uint32_t flags, uint32_t arg)
1126 {
1127 	struct ccb_relsim crs;
1128 
1129 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NONE);
1130 	crs.ccb_h.func_code = XPT_FREEZE_QUEUE;
1131 	crs.release_flags = flags;
1132 	crs.openings = arg;
1133 	crs.release_timeout = arg;
1134 	xpt_action((union ccb *)&crs);
1135 }
1136 
1137 u_int32_t
1138 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1139 		 u_int32_t openings, u_int32_t arg,
1140 		 int getcount_only)
1141 {
1142 	struct ccb_relsim crs;
1143 
1144 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1145 	crs.ccb_h.func_code = XPT_REL_SIMQ;
1146 	crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1147 	crs.release_flags = relsim_flags;
1148 	crs.openings = openings;
1149 	crs.release_timeout = arg;
1150 	xpt_action((union ccb *)&crs);
1151 	return (crs.qfrozen_cnt);
1152 }
1153 
1154 #define saved_ccb_ptr ppriv_ptr0
1155 static void
1156 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1157 {
1158 	union ccb      *saved_ccb;
1159 	cam_status	status;
1160 	struct scsi_start_stop_unit *scsi_cmd;
1161 	int    error_code, sense_key, asc, ascq;
1162 
1163 	scsi_cmd = (struct scsi_start_stop_unit *)
1164 	    &done_ccb->csio.cdb_io.cdb_bytes;
1165 	status = done_ccb->ccb_h.status;
1166 
1167 	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1168 		if (scsi_extract_sense_ccb(done_ccb,
1169 		    &error_code, &sense_key, &asc, &ascq)) {
1170 			/*
1171 			 * If the error is "invalid field in CDB",
1172 			 * and the load/eject flag is set, turn the
1173 			 * flag off and try again.  This is just in
1174 			 * case the drive in question barfs on the
1175 			 * load eject flag.  The CAM code should set
1176 			 * the load/eject flag by default for
1177 			 * removable media.
1178 			 */
1179 			if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1180 			    ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1181 			     (asc == 0x24) && (ascq == 0x00)) {
1182 				scsi_cmd->how &= ~SSS_LOEJ;
1183 				if (status & CAM_DEV_QFRZN) {
1184 					cam_release_devq(done_ccb->ccb_h.path,
1185 					    0, 0, 0, 0);
1186 					done_ccb->ccb_h.status &=
1187 					    ~CAM_DEV_QFRZN;
1188 				}
1189 				xpt_action(done_ccb);
1190 				goto out;
1191 			}
1192 		}
1193 		if (cam_periph_error(done_ccb,
1194 		    0, SF_RETRY_UA | SF_NO_PRINT, NULL) == ERESTART)
1195 			goto out;
1196 		if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1197 			cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1198 			done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1199 		}
1200 	} else {
1201 		/*
1202 		 * If we have successfully taken a device from the not
1203 		 * ready to ready state, re-scan the device and re-get
1204 		 * the inquiry information.  Many devices (mostly disks)
1205 		 * don't properly report their inquiry information unless
1206 		 * they are spun up.
1207 		 */
1208 		if (scsi_cmd->opcode == START_STOP_UNIT)
1209 			xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1210 	}
1211 
1212 	/*
1213 	 * Perform the final retry with the original CCB so that final
1214 	 * error processing is performed by the owner of the CCB.
1215 	 */
1216 	saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1217 	bcopy(saved_ccb, done_ccb, sizeof(*done_ccb));
1218 	xpt_free_ccb(saved_ccb);
1219 	if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1220 		periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1221 	xpt_action(done_ccb);
1222 
1223 out:
1224 	/* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1225 	cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1226 }
1227 
1228 /*
1229  * Generic Async Event handler.  Peripheral drivers usually
1230  * filter out the events that require personal attention,
1231  * and leave the rest to this function.
1232  */
1233 void
1234 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1235 		 struct cam_path *path, void *arg)
1236 {
1237 	switch (code) {
1238 	case AC_LOST_DEVICE:
1239 		cam_periph_invalidate(periph);
1240 		break;
1241 	default:
1242 		break;
1243 	}
1244 }
1245 
1246 void
1247 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1248 {
1249 	struct ccb_getdevstats cgds;
1250 
1251 	xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1252 	cgds.ccb_h.func_code = XPT_GDEV_STATS;
1253 	xpt_action((union ccb *)&cgds);
1254 	cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1255 }
1256 
1257 void
1258 cam_periph_freeze_after_event(struct cam_periph *periph,
1259 			      struct timeval* event_time, u_int duration_ms)
1260 {
1261 	struct timeval delta;
1262 	struct timeval duration_tv;
1263 
1264 	if (!timevalisset(event_time))
1265 		return;
1266 
1267 	microtime(&delta);
1268 	timevalsub(&delta, event_time);
1269 	duration_tv.tv_sec = duration_ms / 1000;
1270 	duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1271 	if (timevalcmp(&delta, &duration_tv, <)) {
1272 		timevalsub(&duration_tv, &delta);
1273 
1274 		duration_ms = duration_tv.tv_sec * 1000;
1275 		duration_ms += duration_tv.tv_usec / 1000;
1276 		cam_freeze_devq(periph->path);
1277 		cam_release_devq(periph->path,
1278 				RELSIM_RELEASE_AFTER_TIMEOUT,
1279 				/*reduction*/0,
1280 				/*timeout*/duration_ms,
1281 				/*getcount_only*/0);
1282 	}
1283 
1284 }
1285 
1286 static int
1287 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1288     cam_flags camflags, u_int32_t sense_flags,
1289     int *openings, u_int32_t *relsim_flags,
1290     u_int32_t *timeout, int *print, const char **action_string)
1291 {
1292 	int error;
1293 
1294 	switch (ccb->csio.scsi_status) {
1295 	case SCSI_STATUS_OK:
1296 	case SCSI_STATUS_COND_MET:
1297 	case SCSI_STATUS_INTERMED:
1298 	case SCSI_STATUS_INTERMED_COND_MET:
1299 		error = 0;
1300 		break;
1301 	case SCSI_STATUS_CMD_TERMINATED:
1302 	case SCSI_STATUS_CHECK_COND:
1303 		error = camperiphscsisenseerror(ccb, orig_ccb,
1304 					        camflags,
1305 					        sense_flags,
1306 					        openings,
1307 					        relsim_flags,
1308 					        timeout,
1309 					        print,
1310 					        action_string);
1311 		break;
1312 	case SCSI_STATUS_QUEUE_FULL:
1313 	{
1314 		/* no decrement */
1315 		struct ccb_getdevstats cgds;
1316 
1317 		/*
1318 		 * First off, find out what the current
1319 		 * transaction counts are.
1320 		 */
1321 		xpt_setup_ccb(&cgds.ccb_h,
1322 			      ccb->ccb_h.path,
1323 			      CAM_PRIORITY_NORMAL);
1324 		cgds.ccb_h.func_code = XPT_GDEV_STATS;
1325 		xpt_action((union ccb *)&cgds);
1326 
1327 		/*
1328 		 * If we were the only transaction active, treat
1329 		 * the QUEUE FULL as if it were a BUSY condition.
1330 		 */
1331 		if (cgds.dev_active != 0) {
1332 			int total_openings;
1333 
1334 			/*
1335 		 	 * Reduce the number of openings to
1336 			 * be 1 less than the amount it took
1337 			 * to get a queue full bounded by the
1338 			 * minimum allowed tag count for this
1339 			 * device.
1340 		 	 */
1341 			total_openings = cgds.dev_active + cgds.dev_openings;
1342 			*openings = cgds.dev_active;
1343 			if (*openings < cgds.mintags)
1344 				*openings = cgds.mintags;
1345 			if (*openings < total_openings)
1346 				*relsim_flags = RELSIM_ADJUST_OPENINGS;
1347 			else {
1348 				/*
1349 				 * Some devices report queue full for
1350 				 * temporary resource shortages.  For
1351 				 * this reason, we allow a minimum
1352 				 * tag count to be entered via a
1353 				 * quirk entry to prevent the queue
1354 				 * count on these devices from falling
1355 				 * to a pessimisticly low value.  We
1356 				 * still wait for the next successful
1357 				 * completion, however, before queueing
1358 				 * more transactions to the device.
1359 				 */
1360 				*relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1361 			}
1362 			*timeout = 0;
1363 			error = ERESTART;
1364 			*print = 0;
1365 			break;
1366 		}
1367 		/* FALLTHROUGH */
1368 	}
1369 	case SCSI_STATUS_BUSY:
1370 		/*
1371 		 * Restart the queue after either another
1372 		 * command completes or a 1 second timeout.
1373 		 */
1374 	 	if (ccb->ccb_h.retry_count > 0) {
1375 	 		ccb->ccb_h.retry_count--;
1376 			error = ERESTART;
1377 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1378 				      | RELSIM_RELEASE_AFTER_CMDCMPLT;
1379 			*timeout = 1000;
1380 		} else {
1381 			error = EIO;
1382 		}
1383 		break;
1384 	case SCSI_STATUS_RESERV_CONFLICT:
1385 	default:
1386 		error = EIO;
1387 		break;
1388 	}
1389 	return (error);
1390 }
1391 
1392 static int
1393 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1394     cam_flags camflags, u_int32_t sense_flags,
1395     int *openings, u_int32_t *relsim_flags,
1396     u_int32_t *timeout, int *print, const char **action_string)
1397 {
1398 	struct cam_periph *periph;
1399 	union ccb *orig_ccb = ccb;
1400 	int error, recoveryccb;
1401 
1402 	periph = xpt_path_periph(ccb->ccb_h.path);
1403 	recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1404 	if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1405 		/*
1406 		 * If error recovery is already in progress, don't attempt
1407 		 * to process this error, but requeue it unconditionally
1408 		 * and attempt to process it once error recovery has
1409 		 * completed.  This failed command is probably related to
1410 		 * the error that caused the currently active error recovery
1411 		 * action so our  current recovery efforts should also
1412 		 * address this command.  Be aware that the error recovery
1413 		 * code assumes that only one recovery action is in progress
1414 		 * on a particular peripheral instance at any given time
1415 		 * (e.g. only one saved CCB for error recovery) so it is
1416 		 * imperitive that we don't violate this assumption.
1417 		 */
1418 		error = ERESTART;
1419 		*print = 0;
1420 	} else {
1421 		scsi_sense_action err_action;
1422 		struct ccb_getdev cgd;
1423 
1424 		/*
1425 		 * Grab the inquiry data for this device.
1426 		 */
1427 		xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1428 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1429 		xpt_action((union ccb *)&cgd);
1430 
1431 		err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1432 		    sense_flags);
1433 		error = err_action & SS_ERRMASK;
1434 
1435 		/*
1436 		 * Do not autostart sequential access devices
1437 		 * to avoid unexpected tape loading.
1438 		 */
1439 		if ((err_action & SS_MASK) == SS_START &&
1440 		    SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1441 			*action_string = "Will not autostart a "
1442 			    "sequential access device";
1443 			goto sense_error_done;
1444 		}
1445 
1446 		/*
1447 		 * Avoid recovery recursion if recovery action is the same.
1448 		 */
1449 		if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1450 			if (((err_action & SS_MASK) == SS_START &&
1451 			     ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1452 			    ((err_action & SS_MASK) == SS_TUR &&
1453 			     (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1454 				err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1455 				*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1456 				*timeout = 500;
1457 			}
1458 		}
1459 
1460 		/*
1461 		 * If the recovery action will consume a retry,
1462 		 * make sure we actually have retries available.
1463 		 */
1464 		if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1465 		 	if (ccb->ccb_h.retry_count > 0 &&
1466 			    (periph->flags & CAM_PERIPH_INVALID) == 0)
1467 		 		ccb->ccb_h.retry_count--;
1468 			else {
1469 				*action_string = "Retries exhausted";
1470 				goto sense_error_done;
1471 			}
1472 		}
1473 
1474 		if ((err_action & SS_MASK) >= SS_START) {
1475 			/*
1476 			 * Do common portions of commands that
1477 			 * use recovery CCBs.
1478 			 */
1479 			orig_ccb = xpt_alloc_ccb_nowait();
1480 			if (orig_ccb == NULL) {
1481 				*action_string = "Can't allocate recovery CCB";
1482 				goto sense_error_done;
1483 			}
1484 			/*
1485 			 * Clear freeze flag for original request here, as
1486 			 * this freeze will be dropped as part of ERESTART.
1487 			 */
1488 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1489 			bcopy(ccb, orig_ccb, sizeof(*orig_ccb));
1490 		}
1491 
1492 		switch (err_action & SS_MASK) {
1493 		case SS_NOP:
1494 			*action_string = "No recovery action needed";
1495 			error = 0;
1496 			break;
1497 		case SS_RETRY:
1498 			*action_string = "Retrying command (per sense data)";
1499 			error = ERESTART;
1500 			break;
1501 		case SS_FAIL:
1502 			*action_string = "Unretryable error";
1503 			break;
1504 		case SS_START:
1505 		{
1506 			int le;
1507 
1508 			/*
1509 			 * Send a start unit command to the device, and
1510 			 * then retry the command.
1511 			 */
1512 			*action_string = "Attempting to start unit";
1513 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1514 
1515 			/*
1516 			 * Check for removable media and set
1517 			 * load/eject flag appropriately.
1518 			 */
1519 			if (SID_IS_REMOVABLE(&cgd.inq_data))
1520 				le = TRUE;
1521 			else
1522 				le = FALSE;
1523 
1524 			scsi_start_stop(&ccb->csio,
1525 					/*retries*/1,
1526 					camperiphdone,
1527 					MSG_SIMPLE_Q_TAG,
1528 					/*start*/TRUE,
1529 					/*load/eject*/le,
1530 					/*immediate*/FALSE,
1531 					SSD_FULL_SIZE,
1532 					/*timeout*/50000);
1533 			break;
1534 		}
1535 		case SS_TUR:
1536 		{
1537 			/*
1538 			 * Send a Test Unit Ready to the device.
1539 			 * If the 'many' flag is set, we send 120
1540 			 * test unit ready commands, one every half
1541 			 * second.  Otherwise, we just send one TUR.
1542 			 * We only want to do this if the retry
1543 			 * count has not been exhausted.
1544 			 */
1545 			int retries;
1546 
1547 			if ((err_action & SSQ_MANY) != 0) {
1548 				*action_string = "Polling device for readiness";
1549 				retries = 120;
1550 			} else {
1551 				*action_string = "Testing device for readiness";
1552 				retries = 1;
1553 			}
1554 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1555 			scsi_test_unit_ready(&ccb->csio,
1556 					     retries,
1557 					     camperiphdone,
1558 					     MSG_SIMPLE_Q_TAG,
1559 					     SSD_FULL_SIZE,
1560 					     /*timeout*/5000);
1561 
1562 			/*
1563 			 * Accomplish our 500ms delay by deferring
1564 			 * the release of our device queue appropriately.
1565 			 */
1566 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1567 			*timeout = 500;
1568 			break;
1569 		}
1570 		default:
1571 			panic("Unhandled error action %x", err_action);
1572 		}
1573 
1574 		if ((err_action & SS_MASK) >= SS_START) {
1575 			/*
1576 			 * Drop the priority, so that the recovery
1577 			 * CCB is the first to execute.  Freeze the queue
1578 			 * after this command is sent so that we can
1579 			 * restore the old csio and have it queued in
1580 			 * the proper order before we release normal
1581 			 * transactions to the device.
1582 			 */
1583 			ccb->ccb_h.pinfo.priority--;
1584 			ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1585 			ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1586 			error = ERESTART;
1587 			*orig = orig_ccb;
1588 		}
1589 
1590 sense_error_done:
1591 		*print = ((err_action & SSQ_PRINT_SENSE) != 0);
1592 	}
1593 	return (error);
1594 }
1595 
1596 /*
1597  * Generic error handler.  Peripheral drivers usually filter
1598  * out the errors that they handle in a unique mannor, then
1599  * call this function.
1600  */
1601 int
1602 cam_periph_error(union ccb *ccb, cam_flags camflags,
1603 		 u_int32_t sense_flags, union ccb *save_ccb)
1604 {
1605 	union ccb  *orig_ccb;
1606 	struct cam_periph *periph;
1607 	const char *action_string;
1608 	cam_status  status;
1609 	int	    frozen, error, openings, print, lost_device;
1610 	int	    error_code, sense_key, asc, ascq;
1611 	u_int32_t   relsim_flags, timeout;
1612 
1613 	print = 1;
1614 	periph = xpt_path_periph(ccb->ccb_h.path);
1615 	action_string = NULL;
1616 	status = ccb->ccb_h.status;
1617 	frozen = (status & CAM_DEV_QFRZN) != 0;
1618 	status &= CAM_STATUS_MASK;
1619 	openings = relsim_flags = timeout = lost_device = 0;
1620 	orig_ccb = ccb;
1621 
1622 	switch (status) {
1623 	case CAM_REQ_CMP:
1624 		error = 0;
1625 		print = 0;
1626 		break;
1627 	case CAM_SCSI_STATUS_ERROR:
1628 		error = camperiphscsistatuserror(ccb, &orig_ccb,
1629 		    camflags, sense_flags, &openings, &relsim_flags,
1630 		    &timeout, &print, &action_string);
1631 		break;
1632 	case CAM_AUTOSENSE_FAIL:
1633 		error = EIO;	/* we have to kill the command */
1634 		break;
1635 	case CAM_UA_ABORT:
1636 	case CAM_UA_TERMIO:
1637 	case CAM_MSG_REJECT_REC:
1638 		/* XXX Don't know that these are correct */
1639 		error = EIO;
1640 		break;
1641 	case CAM_SEL_TIMEOUT:
1642 		if ((camflags & CAM_RETRY_SELTO) != 0) {
1643 			if (ccb->ccb_h.retry_count > 0 &&
1644 			    (periph->flags & CAM_PERIPH_INVALID) == 0) {
1645 				ccb->ccb_h.retry_count--;
1646 				error = ERESTART;
1647 
1648 				/*
1649 				 * Wait a bit to give the device
1650 				 * time to recover before we try again.
1651 				 */
1652 				relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1653 				timeout = periph_selto_delay;
1654 				break;
1655 			}
1656 			action_string = "Retries exhausted";
1657 		}
1658 		/* FALLTHROUGH */
1659 	case CAM_DEV_NOT_THERE:
1660 		error = ENXIO;
1661 		print = 0;
1662 		lost_device = 1;
1663 		break;
1664 	case CAM_REQ_INVALID:
1665 	case CAM_PATH_INVALID:
1666 	case CAM_NO_HBA:
1667 	case CAM_PROVIDE_FAIL:
1668 	case CAM_REQ_TOO_BIG:
1669 	case CAM_LUN_INVALID:
1670 	case CAM_TID_INVALID:
1671 		error = EINVAL;
1672 		break;
1673 	case CAM_SCSI_BUS_RESET:
1674 	case CAM_BDR_SENT:
1675 		/*
1676 		 * Commands that repeatedly timeout and cause these
1677 		 * kinds of error recovery actions, should return
1678 		 * CAM_CMD_TIMEOUT, which allows us to safely assume
1679 		 * that this command was an innocent bystander to
1680 		 * these events and should be unconditionally
1681 		 * retried.
1682 		 */
1683 	case CAM_REQUEUE_REQ:
1684 		/* Unconditional requeue if device is still there */
1685 		if (periph->flags & CAM_PERIPH_INVALID) {
1686 			action_string = "Periph was invalidated";
1687 			error = EIO;
1688 		} else if (sense_flags & SF_NO_RETRY) {
1689 			error = EIO;
1690 			action_string = "Retry was blocked";
1691 		} else {
1692 			error = ERESTART;
1693 			print = 0;
1694 		}
1695 		break;
1696 	case CAM_RESRC_UNAVAIL:
1697 		/* Wait a bit for the resource shortage to abate. */
1698 		timeout = periph_noresrc_delay;
1699 		/* FALLTHROUGH */
1700 	case CAM_BUSY:
1701 		if (timeout == 0) {
1702 			/* Wait a bit for the busy condition to abate. */
1703 			timeout = periph_busy_delay;
1704 		}
1705 		relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1706 		/* FALLTHROUGH */
1707 	case CAM_ATA_STATUS_ERROR:
1708 	case CAM_REQ_CMP_ERR:
1709 	case CAM_CMD_TIMEOUT:
1710 	case CAM_UNEXP_BUSFREE:
1711 	case CAM_UNCOR_PARITY:
1712 	case CAM_DATA_RUN_ERR:
1713 	default:
1714 		if (periph->flags & CAM_PERIPH_INVALID) {
1715 			error = EIO;
1716 			action_string = "Periph was invalidated";
1717 		} else if (ccb->ccb_h.retry_count == 0) {
1718 			error = EIO;
1719 			action_string = "Retries exhausted";
1720 		} else if (sense_flags & SF_NO_RETRY) {
1721 			error = EIO;
1722 			action_string = "Retry was blocked";
1723 		} else {
1724 			ccb->ccb_h.retry_count--;
1725 			error = ERESTART;
1726 		}
1727 		break;
1728 	}
1729 
1730 	if ((sense_flags & SF_PRINT_ALWAYS) ||
1731 	    CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
1732 		print = 1;
1733 	else if (sense_flags & SF_NO_PRINT)
1734 		print = 0;
1735 	if (print)
1736 		cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1737 	if (error != 0 && print) {
1738 		if (error != ERESTART) {
1739 			if (action_string == NULL)
1740 				action_string = "Unretryable error";
1741 			xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
1742 			    error, action_string);
1743 		} else if (action_string != NULL)
1744 			xpt_print(ccb->ccb_h.path, "%s\n", action_string);
1745 		else
1746 			xpt_print(ccb->ccb_h.path, "Retrying command\n");
1747 	}
1748 
1749 	if (lost_device) {
1750 		struct cam_path *newpath;
1751 		lun_id_t lun_id;
1752 
1753 		/*
1754 		 * For a selection timeout, we consider all of the LUNs on
1755 		 * the target to be gone.  If the status is CAM_DEV_NOT_THERE,
1756 		 * then we only get rid of the device(s) specified by the
1757 		 * path in the original CCB.
1758 		 */
1759 		if (status == CAM_DEV_NOT_THERE)
1760 			lun_id = xpt_path_lun_id(ccb->ccb_h.path);
1761 		else
1762 			lun_id = CAM_LUN_WILDCARD;
1763 
1764 		/* Should we do more if we can't create the path?? */
1765 		if (xpt_create_path(&newpath, periph,
1766 				    xpt_path_path_id(ccb->ccb_h.path),
1767 				    xpt_path_target_id(ccb->ccb_h.path),
1768 				    lun_id) == CAM_REQ_CMP) {
1769 
1770 			/*
1771 			 * Let peripheral drivers know that this
1772 			 * device has gone away.
1773 			 */
1774 			xpt_async(AC_LOST_DEVICE, newpath, NULL);
1775 			xpt_free_path(newpath);
1776 		}
1777 
1778 	/* Broadcast UNIT ATTENTIONs to all periphs. */
1779 	} else if (scsi_extract_sense_ccb(ccb,
1780 	    &error_code, &sense_key, &asc, &ascq) &&
1781 	    sense_key == SSD_KEY_UNIT_ATTENTION) {
1782 		xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
1783 	}
1784 
1785 	/* Attempt a retry */
1786 	if (error == ERESTART || error == 0) {
1787 		if (frozen != 0)
1788 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1789 		if (error == ERESTART)
1790 			xpt_action(ccb);
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 	return (error);
1800 }
1801