xref: /freebsd/sys/cam/cam_periph.c (revision 48e091f99d8736d1e02cbc3afd7a1cc19ce66d5c)
1 /*-
2  * Common functions for CAM "type" (peripheral) drivers.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5  *
6  * Copyright (c) 1997, 1998 Justin T. Gibbs.
7  * Copyright (c) 1997, 1998, 1999, 2000 Kenneth D. Merry.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification, immediately at the beginning of the file.
16  * 2. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/types.h>
38 #include <sys/malloc.h>
39 #include <sys/kernel.h>
40 #include <sys/bio.h>
41 #include <sys/conf.h>
42 #include <sys/lock.h>
43 #include <sys/mutex.h>
44 #include <sys/buf.h>
45 #include <sys/proc.h>
46 #include <sys/devicestat.h>
47 #include <sys/bus.h>
48 #include <sys/sbuf.h>
49 #include <sys/sysctl.h>
50 #include <vm/vm.h>
51 #include <vm/vm_extern.h>
52 
53 #include <cam/cam.h>
54 #include <cam/cam_ccb.h>
55 #include <cam/cam_queue.h>
56 #include <cam/cam_xpt_periph.h>
57 #include <cam/cam_periph.h>
58 #include <cam/cam_debug.h>
59 #include <cam/cam_sim.h>
60 
61 #include <cam/scsi/scsi_all.h>
62 #include <cam/scsi/scsi_message.h>
63 #include <cam/scsi/scsi_pass.h>
64 
65 static	u_int		camperiphnextunit(struct periph_driver *p_drv,
66 					  u_int newunit, int wired,
67 					  path_id_t pathid, target_id_t target,
68 					  lun_id_t lun);
69 static	u_int		camperiphunit(struct periph_driver *p_drv,
70 				      path_id_t pathid, target_id_t target,
71 				      lun_id_t lun);
72 static	void		camperiphdone(struct cam_periph *periph,
73 					union ccb *done_ccb);
74 static  void		camperiphfree(struct cam_periph *periph);
75 static int		camperiphscsistatuserror(union ccb *ccb,
76 					        union ccb **orig_ccb,
77 						 cam_flags camflags,
78 						 u_int32_t sense_flags,
79 						 int *openings,
80 						 u_int32_t *relsim_flags,
81 						 u_int32_t *timeout,
82 						 u_int32_t  *action,
83 						 const char **action_string);
84 static	int		camperiphscsisenseerror(union ccb *ccb,
85 					        union ccb **orig_ccb,
86 					        cam_flags camflags,
87 					        u_int32_t sense_flags,
88 					        int *openings,
89 					        u_int32_t *relsim_flags,
90 					        u_int32_t *timeout,
91 					        u_int32_t *action,
92 					        const char **action_string);
93 static void		cam_periph_devctl_notify(union ccb *ccb);
94 
95 static int nperiph_drivers;
96 static int initialized = 0;
97 struct periph_driver **periph_drivers;
98 
99 static MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
100 
101 static int periph_selto_delay = 1000;
102 TUNABLE_INT("kern.cam.periph_selto_delay", &periph_selto_delay);
103 static int periph_noresrc_delay = 500;
104 TUNABLE_INT("kern.cam.periph_noresrc_delay", &periph_noresrc_delay);
105 static int periph_busy_delay = 500;
106 TUNABLE_INT("kern.cam.periph_busy_delay", &periph_busy_delay);
107 
108 static u_int periph_mapmem_thresh = 65536;
109 SYSCTL_UINT(_kern_cam, OID_AUTO, mapmem_thresh, CTLFLAG_RWTUN,
110     &periph_mapmem_thresh, 0, "Threshold for user-space buffer mapping");
111 
112 void
113 periphdriver_register(void *data)
114 {
115 	struct periph_driver *drv = (struct periph_driver *)data;
116 	struct periph_driver **newdrivers, **old;
117 	int ndrivers;
118 
119 again:
120 	ndrivers = nperiph_drivers + 2;
121 	newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
122 			    M_WAITOK);
123 	xpt_lock_buses();
124 	if (ndrivers != nperiph_drivers + 2) {
125 		/*
126 		 * Lost race against itself; go around.
127 		 */
128 		xpt_unlock_buses();
129 		free(newdrivers, M_CAMPERIPH);
130 		goto again;
131 	}
132 	if (periph_drivers)
133 		bcopy(periph_drivers, newdrivers,
134 		      sizeof(*newdrivers) * nperiph_drivers);
135 	newdrivers[nperiph_drivers] = drv;
136 	newdrivers[nperiph_drivers + 1] = NULL;
137 	old = periph_drivers;
138 	periph_drivers = newdrivers;
139 	nperiph_drivers++;
140 	xpt_unlock_buses();
141 	if (old)
142 		free(old, M_CAMPERIPH);
143 	/* If driver marked as early or it is late now, initialize it. */
144 	if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
145 	    initialized > 1)
146 		(*drv->init)();
147 }
148 
149 int
150 periphdriver_unregister(void *data)
151 {
152 	struct periph_driver *drv = (struct periph_driver *)data;
153 	int error, n;
154 
155 	/* If driver marked as early or it is late now, deinitialize it. */
156 	if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
157 	    initialized > 1) {
158 		if (drv->deinit == NULL) {
159 			printf("CAM periph driver '%s' doesn't have deinit.\n",
160 			    drv->driver_name);
161 			return (EOPNOTSUPP);
162 		}
163 		error = drv->deinit();
164 		if (error != 0)
165 			return (error);
166 	}
167 
168 	xpt_lock_buses();
169 	for (n = 0; n < nperiph_drivers && periph_drivers[n] != drv; n++)
170 		;
171 	KASSERT(n < nperiph_drivers,
172 	    ("Periph driver '%s' was not registered", drv->driver_name));
173 	for (; n + 1 < nperiph_drivers; n++)
174 		periph_drivers[n] = periph_drivers[n + 1];
175 	periph_drivers[n + 1] = NULL;
176 	nperiph_drivers--;
177 	xpt_unlock_buses();
178 	return (0);
179 }
180 
181 void
182 periphdriver_init(int level)
183 {
184 	int	i, early;
185 
186 	initialized = max(initialized, level);
187 	for (i = 0; periph_drivers[i] != NULL; i++) {
188 		early = (periph_drivers[i]->flags & CAM_PERIPH_DRV_EARLY) ? 1 : 2;
189 		if (early == initialized)
190 			(*periph_drivers[i]->init)();
191 	}
192 }
193 
194 cam_status
195 cam_periph_alloc(periph_ctor_t *periph_ctor,
196 		 periph_oninv_t *periph_oninvalidate,
197 		 periph_dtor_t *periph_dtor, periph_start_t *periph_start,
198 		 char *name, cam_periph_type type, struct cam_path *path,
199 		 ac_callback_t *ac_callback, ac_code code, void *arg)
200 {
201 	struct		periph_driver **p_drv;
202 	struct		cam_sim *sim;
203 	struct		cam_periph *periph;
204 	struct		cam_periph *cur_periph;
205 	path_id_t	path_id;
206 	target_id_t	target_id;
207 	lun_id_t	lun_id;
208 	cam_status	status;
209 	u_int		init_level;
210 
211 	init_level = 0;
212 	/*
213 	 * Handle Hot-Plug scenarios.  If there is already a peripheral
214 	 * of our type assigned to this path, we are likely waiting for
215 	 * final close on an old, invalidated, peripheral.  If this is
216 	 * the case, queue up a deferred call to the peripheral's async
217 	 * handler.  If it looks like a mistaken re-allocation, complain.
218 	 */
219 	if ((periph = cam_periph_find(path, name)) != NULL) {
220 
221 		if ((periph->flags & CAM_PERIPH_INVALID) != 0
222 		 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
223 			periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
224 			periph->deferred_callback = ac_callback;
225 			periph->deferred_ac = code;
226 			return (CAM_REQ_INPROG);
227 		} else {
228 			printf("cam_periph_alloc: attempt to re-allocate "
229 			       "valid device %s%d rejected flags %#x "
230 			       "refcount %d\n", periph->periph_name,
231 			       periph->unit_number, periph->flags,
232 			       periph->refcount);
233 		}
234 		return (CAM_REQ_INVALID);
235 	}
236 
237 	periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
238 					     M_NOWAIT|M_ZERO);
239 
240 	if (periph == NULL)
241 		return (CAM_RESRC_UNAVAIL);
242 
243 	init_level++;
244 
245 
246 	sim = xpt_path_sim(path);
247 	path_id = xpt_path_path_id(path);
248 	target_id = xpt_path_target_id(path);
249 	lun_id = xpt_path_lun_id(path);
250 	periph->periph_start = periph_start;
251 	periph->periph_dtor = periph_dtor;
252 	periph->periph_oninval = periph_oninvalidate;
253 	periph->type = type;
254 	periph->periph_name = name;
255 	periph->scheduled_priority = CAM_PRIORITY_NONE;
256 	periph->immediate_priority = CAM_PRIORITY_NONE;
257 	periph->refcount = 1;		/* Dropped by invalidation. */
258 	periph->sim = sim;
259 	SLIST_INIT(&periph->ccb_list);
260 	status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
261 	if (status != CAM_REQ_CMP)
262 		goto failure;
263 	periph->path = path;
264 
265 	xpt_lock_buses();
266 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
267 		if (strcmp((*p_drv)->driver_name, name) == 0)
268 			break;
269 	}
270 	if (*p_drv == NULL) {
271 		printf("cam_periph_alloc: invalid periph name '%s'\n", name);
272 		xpt_unlock_buses();
273 		xpt_free_path(periph->path);
274 		free(periph, M_CAMPERIPH);
275 		return (CAM_REQ_INVALID);
276 	}
277 	periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id);
278 	cur_periph = TAILQ_FIRST(&(*p_drv)->units);
279 	while (cur_periph != NULL
280 	    && cur_periph->unit_number < periph->unit_number)
281 		cur_periph = TAILQ_NEXT(cur_periph, unit_links);
282 	if (cur_periph != NULL) {
283 		KASSERT(cur_periph->unit_number != periph->unit_number, ("duplicate units on periph list"));
284 		TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
285 	} else {
286 		TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
287 		(*p_drv)->generation++;
288 	}
289 	xpt_unlock_buses();
290 
291 	init_level++;
292 
293 	status = xpt_add_periph(periph);
294 	if (status != CAM_REQ_CMP)
295 		goto failure;
296 
297 	init_level++;
298 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
299 
300 	status = periph_ctor(periph, arg);
301 
302 	if (status == CAM_REQ_CMP)
303 		init_level++;
304 
305 failure:
306 	switch (init_level) {
307 	case 4:
308 		/* Initialized successfully */
309 		break;
310 	case 3:
311 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
312 		xpt_remove_periph(periph);
313 		/* FALLTHROUGH */
314 	case 2:
315 		xpt_lock_buses();
316 		TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
317 		xpt_unlock_buses();
318 		xpt_free_path(periph->path);
319 		/* FALLTHROUGH */
320 	case 1:
321 		free(periph, M_CAMPERIPH);
322 		/* FALLTHROUGH */
323 	case 0:
324 		/* No cleanup to perform. */
325 		break;
326 	default:
327 		panic("%s: Unknown init level", __func__);
328 	}
329 	return(status);
330 }
331 
332 /*
333  * Find a peripheral structure with the specified path, target, lun,
334  * and (optionally) type.  If the name is NULL, this function will return
335  * the first peripheral driver that matches the specified path.
336  */
337 struct cam_periph *
338 cam_periph_find(struct cam_path *path, char *name)
339 {
340 	struct periph_driver **p_drv;
341 	struct cam_periph *periph;
342 
343 	xpt_lock_buses();
344 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
345 
346 		if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
347 			continue;
348 
349 		TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
350 			if (xpt_path_comp(periph->path, path) == 0) {
351 				xpt_unlock_buses();
352 				cam_periph_assert(periph, MA_OWNED);
353 				return(periph);
354 			}
355 		}
356 		if (name != NULL) {
357 			xpt_unlock_buses();
358 			return(NULL);
359 		}
360 	}
361 	xpt_unlock_buses();
362 	return(NULL);
363 }
364 
365 /*
366  * Find peripheral driver instances attached to the specified path.
367  */
368 int
369 cam_periph_list(struct cam_path *path, struct sbuf *sb)
370 {
371 	struct sbuf local_sb;
372 	struct periph_driver **p_drv;
373 	struct cam_periph *periph;
374 	int count;
375 	int sbuf_alloc_len;
376 
377 	sbuf_alloc_len = 16;
378 retry:
379 	sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
380 	count = 0;
381 	xpt_lock_buses();
382 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
383 
384 		TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
385 			if (xpt_path_comp(periph->path, path) != 0)
386 				continue;
387 
388 			if (sbuf_len(&local_sb) != 0)
389 				sbuf_cat(&local_sb, ",");
390 
391 			sbuf_printf(&local_sb, "%s%d", periph->periph_name,
392 				    periph->unit_number);
393 
394 			if (sbuf_error(&local_sb) == ENOMEM) {
395 				sbuf_alloc_len *= 2;
396 				xpt_unlock_buses();
397 				sbuf_delete(&local_sb);
398 				goto retry;
399 			}
400 			count++;
401 		}
402 	}
403 	xpt_unlock_buses();
404 	sbuf_finish(&local_sb);
405 	sbuf_cpy(sb, sbuf_data(&local_sb));
406 	sbuf_delete(&local_sb);
407 	return (count);
408 }
409 
410 int
411 cam_periph_acquire(struct cam_periph *periph)
412 {
413 	int status;
414 
415 	if (periph == NULL)
416 		return (EINVAL);
417 
418 	status = ENOENT;
419 	xpt_lock_buses();
420 	if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
421 		periph->refcount++;
422 		status = 0;
423 	}
424 	xpt_unlock_buses();
425 
426 	return (status);
427 }
428 
429 void
430 cam_periph_doacquire(struct cam_periph *periph)
431 {
432 
433 	xpt_lock_buses();
434 	KASSERT(periph->refcount >= 1,
435 	    ("cam_periph_doacquire() with refcount == %d", periph->refcount));
436 	periph->refcount++;
437 	xpt_unlock_buses();
438 }
439 
440 void
441 cam_periph_release_locked_buses(struct cam_periph *periph)
442 {
443 
444 	cam_periph_assert(periph, MA_OWNED);
445 	KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
446 	if (--periph->refcount == 0)
447 		camperiphfree(periph);
448 }
449 
450 void
451 cam_periph_release_locked(struct cam_periph *periph)
452 {
453 
454 	if (periph == NULL)
455 		return;
456 
457 	xpt_lock_buses();
458 	cam_periph_release_locked_buses(periph);
459 	xpt_unlock_buses();
460 }
461 
462 void
463 cam_periph_release(struct cam_periph *periph)
464 {
465 	struct mtx *mtx;
466 
467 	if (periph == NULL)
468 		return;
469 
470 	cam_periph_assert(periph, MA_NOTOWNED);
471 	mtx = cam_periph_mtx(periph);
472 	mtx_lock(mtx);
473 	cam_periph_release_locked(periph);
474 	mtx_unlock(mtx);
475 }
476 
477 /*
478  * hold/unhold act as mutual exclusion for sections of the code that
479  * need to sleep and want to make sure that other sections that
480  * will interfere are held off. This only protects exclusive sections
481  * from each other.
482  */
483 int
484 cam_periph_hold(struct cam_periph *periph, int priority)
485 {
486 	int error;
487 
488 	/*
489 	 * Increment the reference count on the peripheral
490 	 * while we wait for our lock attempt to succeed
491 	 * to ensure the peripheral doesn't disappear out
492 	 * from user us while we sleep.
493 	 */
494 
495 	if (cam_periph_acquire(periph) != 0)
496 		return (ENXIO);
497 
498 	cam_periph_assert(periph, MA_OWNED);
499 	while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
500 		periph->flags |= CAM_PERIPH_LOCK_WANTED;
501 		if ((error = cam_periph_sleep(periph, periph, priority,
502 		    "caplck", 0)) != 0) {
503 			cam_periph_release_locked(periph);
504 			return (error);
505 		}
506 		if (periph->flags & CAM_PERIPH_INVALID) {
507 			cam_periph_release_locked(periph);
508 			return (ENXIO);
509 		}
510 	}
511 
512 	periph->flags |= CAM_PERIPH_LOCKED;
513 	return (0);
514 }
515 
516 void
517 cam_periph_unhold(struct cam_periph *periph)
518 {
519 
520 	cam_periph_assert(periph, MA_OWNED);
521 
522 	periph->flags &= ~CAM_PERIPH_LOCKED;
523 	if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
524 		periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
525 		wakeup(periph);
526 	}
527 
528 	cam_periph_release_locked(periph);
529 }
530 
531 /*
532  * Look for the next unit number that is not currently in use for this
533  * peripheral type starting at "newunit".  Also exclude unit numbers that
534  * are reserved by for future "hardwiring" unless we already know that this
535  * is a potential wired device.  Only assume that the device is "wired" the
536  * first time through the loop since after that we'll be looking at unit
537  * numbers that did not match a wiring entry.
538  */
539 static u_int
540 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
541 		  path_id_t pathid, target_id_t target, lun_id_t lun)
542 {
543 	struct	cam_periph *periph;
544 	char	*periph_name;
545 	int	i, val, dunit, r;
546 	const char *dname, *strval;
547 
548 	periph_name = p_drv->driver_name;
549 	for (;;newunit++) {
550 
551 		for (periph = TAILQ_FIRST(&p_drv->units);
552 		     periph != NULL && periph->unit_number != newunit;
553 		     periph = TAILQ_NEXT(periph, unit_links))
554 			;
555 
556 		if (periph != NULL && periph->unit_number == newunit) {
557 			if (wired != 0) {
558 				xpt_print(periph->path, "Duplicate Wired "
559 				    "Device entry!\n");
560 				xpt_print(periph->path, "Second device (%s "
561 				    "device at scbus%d target %d lun %d) will "
562 				    "not be wired\n", periph_name, pathid,
563 				    target, lun);
564 				wired = 0;
565 			}
566 			continue;
567 		}
568 		if (wired)
569 			break;
570 
571 		/*
572 		 * Don't match entries like "da 4" as a wired down
573 		 * device, but do match entries like "da 4 target 5"
574 		 * or even "da 4 scbus 1".
575 		 */
576 		i = 0;
577 		dname = periph_name;
578 		for (;;) {
579 			r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
580 			if (r != 0)
581 				break;
582 			/* if no "target" and no specific scbus, skip */
583 			if (resource_int_value(dname, dunit, "target", &val) &&
584 			    (resource_string_value(dname, dunit, "at",&strval)||
585 			     strcmp(strval, "scbus") == 0))
586 				continue;
587 			if (newunit == dunit)
588 				break;
589 		}
590 		if (r != 0)
591 			break;
592 	}
593 	return (newunit);
594 }
595 
596 static u_int
597 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
598 	      target_id_t target, lun_id_t lun)
599 {
600 	u_int	unit;
601 	int	wired, i, val, dunit;
602 	const char *dname, *strval;
603 	char	pathbuf[32], *periph_name;
604 
605 	periph_name = p_drv->driver_name;
606 	snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
607 	unit = 0;
608 	i = 0;
609 	dname = periph_name;
610 	for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
611 	     wired = 0) {
612 		if (resource_string_value(dname, dunit, "at", &strval) == 0) {
613 			if (strcmp(strval, pathbuf) != 0)
614 				continue;
615 			wired++;
616 		}
617 		if (resource_int_value(dname, dunit, "target", &val) == 0) {
618 			if (val != target)
619 				continue;
620 			wired++;
621 		}
622 		if (resource_int_value(dname, dunit, "lun", &val) == 0) {
623 			if (val != lun)
624 				continue;
625 			wired++;
626 		}
627 		if (wired != 0) {
628 			unit = dunit;
629 			break;
630 		}
631 	}
632 
633 	/*
634 	 * Either start from 0 looking for the next unit or from
635 	 * the unit number given in the resource config.  This way,
636 	 * if we have wildcard matches, we don't return the same
637 	 * unit number twice.
638 	 */
639 	unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
640 
641 	return (unit);
642 }
643 
644 void
645 cam_periph_invalidate(struct cam_periph *periph)
646 {
647 
648 	cam_periph_assert(periph, MA_OWNED);
649 	/*
650 	 * We only call this routine the first time a peripheral is
651 	 * invalidated.
652 	 */
653 	if ((periph->flags & CAM_PERIPH_INVALID) != 0)
654 		return;
655 
656 	CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
657 	if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting) {
658 		struct sbuf sb;
659 		char buffer[160];
660 
661 		sbuf_new(&sb, buffer, 160, SBUF_FIXEDLEN);
662 		xpt_denounce_periph_sbuf(periph, &sb);
663 		sbuf_finish(&sb);
664 		sbuf_putbuf(&sb);
665 	}
666 	periph->flags |= CAM_PERIPH_INVALID;
667 	periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
668 	if (periph->periph_oninval != NULL)
669 		periph->periph_oninval(periph);
670 	cam_periph_release_locked(periph);
671 }
672 
673 static void
674 camperiphfree(struct cam_periph *periph)
675 {
676 	struct periph_driver **p_drv;
677 	struct periph_driver *drv;
678 
679 	cam_periph_assert(periph, MA_OWNED);
680 	KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
681 	    periph->periph_name, periph->unit_number));
682 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
683 		if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
684 			break;
685 	}
686 	if (*p_drv == NULL) {
687 		printf("camperiphfree: attempt to free non-existant periph\n");
688 		return;
689 	}
690 	/*
691 	 * Cache a pointer to the periph_driver structure.  If a
692 	 * periph_driver is added or removed from the array (see
693 	 * periphdriver_register()) while we drop the toplogy lock
694 	 * below, p_drv may change.  This doesn't protect against this
695 	 * particular periph_driver going away.  That will require full
696 	 * reference counting in the periph_driver infrastructure.
697 	 */
698 	drv = *p_drv;
699 
700 	/*
701 	 * We need to set this flag before dropping the topology lock, to
702 	 * let anyone who is traversing the list that this peripheral is
703 	 * about to be freed, and there will be no more reference count
704 	 * checks.
705 	 */
706 	periph->flags |= CAM_PERIPH_FREE;
707 
708 	/*
709 	 * The peripheral destructor semantics dictate calling with only the
710 	 * SIM mutex held.  Since it might sleep, it should not be called
711 	 * with the topology lock held.
712 	 */
713 	xpt_unlock_buses();
714 
715 	/*
716 	 * We need to call the peripheral destructor prior to removing the
717 	 * peripheral from the list.  Otherwise, we risk running into a
718 	 * scenario where the peripheral unit number may get reused
719 	 * (because it has been removed from the list), but some resources
720 	 * used by the peripheral are still hanging around.  In particular,
721 	 * the devfs nodes used by some peripherals like the pass(4) driver
722 	 * aren't fully cleaned up until the destructor is run.  If the
723 	 * unit number is reused before the devfs instance is fully gone,
724 	 * devfs will panic.
725 	 */
726 	if (periph->periph_dtor != NULL)
727 		periph->periph_dtor(periph);
728 
729 	/*
730 	 * The peripheral list is protected by the topology lock.
731 	 */
732 	xpt_lock_buses();
733 
734 	TAILQ_REMOVE(&drv->units, periph, unit_links);
735 	drv->generation++;
736 
737 	xpt_remove_periph(periph);
738 
739 	xpt_unlock_buses();
740 	if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting)
741 		xpt_print(periph->path, "Periph destroyed\n");
742 	else
743 		CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
744 
745 	if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
746 		union ccb ccb;
747 		void *arg;
748 
749 		switch (periph->deferred_ac) {
750 		case AC_FOUND_DEVICE:
751 			ccb.ccb_h.func_code = XPT_GDEV_TYPE;
752 			xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
753 			xpt_action(&ccb);
754 			arg = &ccb;
755 			break;
756 		case AC_PATH_REGISTERED:
757 			xpt_path_inq(&ccb.cpi, periph->path);
758 			arg = &ccb;
759 			break;
760 		default:
761 			arg = NULL;
762 			break;
763 		}
764 		periph->deferred_callback(NULL, periph->deferred_ac,
765 					  periph->path, arg);
766 	}
767 	xpt_free_path(periph->path);
768 	free(periph, M_CAMPERIPH);
769 	xpt_lock_buses();
770 }
771 
772 /*
773  * Map user virtual pointers into kernel virtual address space, so we can
774  * access the memory.  This is now a generic function that centralizes most
775  * of the sanity checks on the data flags, if any.
776  * This also only works for up to MAXPHYS memory.  Since we use
777  * buffers to map stuff in and out, we're limited to the buffer size.
778  */
779 int
780 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo,
781     u_int maxmap)
782 {
783 	int numbufs, i;
784 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
785 	u_int32_t lengths[CAM_PERIPH_MAXMAPS];
786 	u_int32_t dirs[CAM_PERIPH_MAXMAPS];
787 
788 	bzero(mapinfo, sizeof(*mapinfo));
789 	if (maxmap == 0)
790 		maxmap = DFLTPHYS;	/* traditional default */
791 	else if (maxmap > MAXPHYS)
792 		maxmap = MAXPHYS;	/* for safety */
793 	switch(ccb->ccb_h.func_code) {
794 	case XPT_DEV_MATCH:
795 		if (ccb->cdm.match_buf_len == 0) {
796 			printf("cam_periph_mapmem: invalid match buffer "
797 			       "length 0\n");
798 			return(EINVAL);
799 		}
800 		if (ccb->cdm.pattern_buf_len > 0) {
801 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
802 			lengths[0] = ccb->cdm.pattern_buf_len;
803 			dirs[0] = CAM_DIR_OUT;
804 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
805 			lengths[1] = ccb->cdm.match_buf_len;
806 			dirs[1] = CAM_DIR_IN;
807 			numbufs = 2;
808 		} else {
809 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
810 			lengths[0] = ccb->cdm.match_buf_len;
811 			dirs[0] = CAM_DIR_IN;
812 			numbufs = 1;
813 		}
814 		/*
815 		 * This request will not go to the hardware, no reason
816 		 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
817 		 */
818 		maxmap = MAXPHYS;
819 		break;
820 	case XPT_SCSI_IO:
821 	case XPT_CONT_TARGET_IO:
822 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
823 			return(0);
824 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
825 			return (EINVAL);
826 		data_ptrs[0] = &ccb->csio.data_ptr;
827 		lengths[0] = ccb->csio.dxfer_len;
828 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
829 		numbufs = 1;
830 		break;
831 	case XPT_ATA_IO:
832 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
833 			return(0);
834 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
835 			return (EINVAL);
836 		data_ptrs[0] = &ccb->ataio.data_ptr;
837 		lengths[0] = ccb->ataio.dxfer_len;
838 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
839 		numbufs = 1;
840 		break;
841 	case XPT_MMC_IO:
842 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
843 			return(0);
844 		/* Two mappings: one for cmd->data and one for cmd->data->data */
845 		data_ptrs[0] = (unsigned char **)&ccb->mmcio.cmd.data;
846 		lengths[0] = sizeof(struct mmc_data *);
847 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
848 		data_ptrs[1] = (unsigned char **)&ccb->mmcio.cmd.data->data;
849 		lengths[1] = ccb->mmcio.cmd.data->len;
850 		dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
851 		numbufs = 2;
852 		break;
853 	case XPT_SMP_IO:
854 		data_ptrs[0] = &ccb->smpio.smp_request;
855 		lengths[0] = ccb->smpio.smp_request_len;
856 		dirs[0] = CAM_DIR_OUT;
857 		data_ptrs[1] = &ccb->smpio.smp_response;
858 		lengths[1] = ccb->smpio.smp_response_len;
859 		dirs[1] = CAM_DIR_IN;
860 		numbufs = 2;
861 		break;
862 	case XPT_NVME_IO:
863 	case XPT_NVME_ADMIN:
864 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
865 			return (0);
866 		if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
867 			return (EINVAL);
868 		data_ptrs[0] = &ccb->nvmeio.data_ptr;
869 		lengths[0] = ccb->nvmeio.dxfer_len;
870 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
871 		numbufs = 1;
872 		break;
873 	case XPT_DEV_ADVINFO:
874 		if (ccb->cdai.bufsiz == 0)
875 			return (0);
876 
877 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
878 		lengths[0] = ccb->cdai.bufsiz;
879 		dirs[0] = CAM_DIR_IN;
880 		numbufs = 1;
881 
882 		/*
883 		 * This request will not go to the hardware, no reason
884 		 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
885 		 */
886 		maxmap = MAXPHYS;
887 		break;
888 	default:
889 		return(EINVAL);
890 		break; /* NOTREACHED */
891 	}
892 
893 	/*
894 	 * Check the transfer length and permissions first, so we don't
895 	 * have to unmap any previously mapped buffers.
896 	 */
897 	for (i = 0; i < numbufs; i++) {
898 
899 		/*
900 		 * The userland data pointer passed in may not be page
901 		 * aligned.  vmapbuf() truncates the address to a page
902 		 * boundary, so if the address isn't page aligned, we'll
903 		 * need enough space for the given transfer length, plus
904 		 * whatever extra space is necessary to make it to the page
905 		 * boundary.
906 		 */
907 		if ((lengths[i] +
908 		    (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)) > maxmap){
909 			printf("cam_periph_mapmem: attempt to map %lu bytes, "
910 			       "which is greater than %lu\n",
911 			       (long)(lengths[i] +
912 			       (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)),
913 			       (u_long)maxmap);
914 			return(E2BIG);
915 		}
916 	}
917 
918 	/*
919 	 * This keeps the kernel stack of current thread from getting
920 	 * swapped.  In low-memory situations where the kernel stack might
921 	 * otherwise get swapped out, this holds it and allows the thread
922 	 * to make progress and release the kernel mapped pages sooner.
923 	 *
924 	 * XXX KDM should I use P_NOSWAP instead?
925 	 */
926 	PHOLD(curproc);
927 
928 	for (i = 0; i < numbufs; i++) {
929 
930 		/* Save the user's data address. */
931 		mapinfo->orig[i] = *data_ptrs[i];
932 
933 		/*
934 		 * For small buffers use malloc+copyin/copyout instead of
935 		 * mapping to KVA to avoid expensive TLB shootdowns.  For
936 		 * small allocations malloc is backed by UMA, and so much
937 		 * cheaper on SMP systems.
938 		 */
939 		if (lengths[i] <= periph_mapmem_thresh &&
940 		    ccb->ccb_h.func_code != XPT_MMC_IO) {
941 			*data_ptrs[i] = malloc(lengths[i], M_CAMPERIPH,
942 			    M_WAITOK);
943 			if (dirs[i] != CAM_DIR_IN) {
944 				if (copyin(mapinfo->orig[i], *data_ptrs[i],
945 				    lengths[i]) != 0) {
946 					free(*data_ptrs[i], M_CAMPERIPH);
947 					*data_ptrs[i] = mapinfo->orig[i];
948 					goto fail;
949 				}
950 			} else
951 				bzero(*data_ptrs[i], lengths[i]);
952 			continue;
953 		}
954 
955 		/*
956 		 * Get the buffer.
957 		 */
958 		mapinfo->bp[i] = uma_zalloc(pbuf_zone, M_WAITOK);
959 
960 		/* put our pointer in the data slot */
961 		mapinfo->bp[i]->b_data = *data_ptrs[i];
962 
963 		/* set the transfer length, we know it's < MAXPHYS */
964 		mapinfo->bp[i]->b_bufsize = lengths[i];
965 
966 		/* set the direction */
967 		mapinfo->bp[i]->b_iocmd = (dirs[i] == CAM_DIR_OUT) ?
968 		    BIO_WRITE : BIO_READ;
969 
970 		/*
971 		 * Map the buffer into kernel memory.
972 		 *
973 		 * Note that useracc() alone is not a  sufficient test.
974 		 * vmapbuf() can still fail due to a smaller file mapped
975 		 * into a larger area of VM, or if userland races against
976 		 * vmapbuf() after the useracc() check.
977 		 */
978 		if (vmapbuf(mapinfo->bp[i], 1) < 0) {
979 			uma_zfree(pbuf_zone, mapinfo->bp[i]);
980 			goto fail;
981 		}
982 
983 		/* set our pointer to the new mapped area */
984 		*data_ptrs[i] = mapinfo->bp[i]->b_data;
985 	}
986 
987 	/*
988 	 * Now that we've gotten this far, change ownership to the kernel
989 	 * of the buffers so that we don't run afoul of returning to user
990 	 * space with locks (on the buffer) held.
991 	 */
992 	for (i = 0; i < numbufs; i++) {
993 		if (mapinfo->bp[i])
994 			BUF_KERNPROC(mapinfo->bp[i]);
995 	}
996 
997 	mapinfo->num_bufs_used = numbufs;
998 	return(0);
999 
1000 fail:
1001 	for (i--; i >= 0; i--) {
1002 		if (mapinfo->bp[i]) {
1003 			vunmapbuf(mapinfo->bp[i]);
1004 			uma_zfree(pbuf_zone, mapinfo->bp[i]);
1005 		} else
1006 			free(*data_ptrs[i], M_CAMPERIPH);
1007 		*data_ptrs[i] = mapinfo->orig[i];
1008 	}
1009 	PRELE(curproc);
1010 	return(EACCES);
1011 }
1012 
1013 /*
1014  * Unmap memory segments mapped into kernel virtual address space by
1015  * cam_periph_mapmem().
1016  */
1017 void
1018 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
1019 {
1020 	int numbufs, i;
1021 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1022 	u_int32_t lengths[CAM_PERIPH_MAXMAPS];
1023 	u_int32_t dirs[CAM_PERIPH_MAXMAPS];
1024 
1025 	if (mapinfo->num_bufs_used <= 0) {
1026 		/* nothing to free and the process wasn't held. */
1027 		return;
1028 	}
1029 
1030 	switch (ccb->ccb_h.func_code) {
1031 	case XPT_DEV_MATCH:
1032 		if (ccb->cdm.pattern_buf_len > 0) {
1033 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1034 			lengths[0] = ccb->cdm.pattern_buf_len;
1035 			dirs[0] = CAM_DIR_OUT;
1036 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1037 			lengths[1] = ccb->cdm.match_buf_len;
1038 			dirs[1] = CAM_DIR_IN;
1039 			numbufs = 2;
1040 		} else {
1041 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1042 			lengths[0] = ccb->cdm.match_buf_len;
1043 			dirs[0] = CAM_DIR_IN;
1044 			numbufs = 1;
1045 		}
1046 		break;
1047 	case XPT_SCSI_IO:
1048 	case XPT_CONT_TARGET_IO:
1049 		data_ptrs[0] = &ccb->csio.data_ptr;
1050 		lengths[0] = ccb->csio.dxfer_len;
1051 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1052 		numbufs = 1;
1053 		break;
1054 	case XPT_ATA_IO:
1055 		data_ptrs[0] = &ccb->ataio.data_ptr;
1056 		lengths[0] = ccb->ataio.dxfer_len;
1057 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1058 		numbufs = 1;
1059 		break;
1060 	case XPT_MMC_IO:
1061 		data_ptrs[0] = (u_int8_t **)&ccb->mmcio.cmd.data;
1062 		lengths[0] = sizeof(struct mmc_data *);
1063 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1064 		data_ptrs[1] = (u_int8_t **)&ccb->mmcio.cmd.data->data;
1065 		lengths[1] = ccb->mmcio.cmd.data->len;
1066 		dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
1067 		numbufs = 2;
1068 		break;
1069 	case XPT_SMP_IO:
1070 		data_ptrs[0] = &ccb->smpio.smp_request;
1071 		lengths[0] = ccb->smpio.smp_request_len;
1072 		dirs[0] = CAM_DIR_OUT;
1073 		data_ptrs[1] = &ccb->smpio.smp_response;
1074 		lengths[1] = ccb->smpio.smp_response_len;
1075 		dirs[1] = CAM_DIR_IN;
1076 		numbufs = 2;
1077 		break;
1078 	case XPT_NVME_IO:
1079 	case XPT_NVME_ADMIN:
1080 		data_ptrs[0] = &ccb->nvmeio.data_ptr;
1081 		lengths[0] = ccb->nvmeio.dxfer_len;
1082 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1083 		numbufs = 1;
1084 		break;
1085 	case XPT_DEV_ADVINFO:
1086 		data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1087 		lengths[0] = ccb->cdai.bufsiz;
1088 		dirs[0] = CAM_DIR_IN;
1089 		numbufs = 1;
1090 		break;
1091 	default:
1092 		/* allow ourselves to be swapped once again */
1093 		PRELE(curproc);
1094 		return;
1095 		break; /* NOTREACHED */
1096 	}
1097 
1098 	for (i = 0; i < numbufs; i++) {
1099 		if (mapinfo->bp[i]) {
1100 			/* unmap the buffer */
1101 			vunmapbuf(mapinfo->bp[i]);
1102 
1103 			/* release the buffer */
1104 			uma_zfree(pbuf_zone, mapinfo->bp[i]);
1105 		} else {
1106 			if (dirs[i] != CAM_DIR_OUT) {
1107 				copyout(*data_ptrs[i], mapinfo->orig[i],
1108 				    lengths[i]);
1109 			}
1110 			free(*data_ptrs[i], M_CAMPERIPH);
1111 		}
1112 
1113 		/* Set the user's pointer back to the original value */
1114 		*data_ptrs[i] = mapinfo->orig[i];
1115 	}
1116 
1117 	/* allow ourselves to be swapped once again */
1118 	PRELE(curproc);
1119 }
1120 
1121 int
1122 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
1123 		 int (*error_routine)(union ccb *ccb,
1124 				      cam_flags camflags,
1125 				      u_int32_t sense_flags))
1126 {
1127 	union ccb 	     *ccb;
1128 	int 		     error;
1129 	int		     found;
1130 
1131 	error = found = 0;
1132 
1133 	switch(cmd){
1134 	case CAMGETPASSTHRU:
1135 		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1136 		xpt_setup_ccb(&ccb->ccb_h,
1137 			      ccb->ccb_h.path,
1138 			      CAM_PRIORITY_NORMAL);
1139 		ccb->ccb_h.func_code = XPT_GDEVLIST;
1140 
1141 		/*
1142 		 * Basically, the point of this is that we go through
1143 		 * getting the list of devices, until we find a passthrough
1144 		 * device.  In the current version of the CAM code, the
1145 		 * only way to determine what type of device we're dealing
1146 		 * with is by its name.
1147 		 */
1148 		while (found == 0) {
1149 			ccb->cgdl.index = 0;
1150 			ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1151 			while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
1152 
1153 				/* we want the next device in the list */
1154 				xpt_action(ccb);
1155 				if (strncmp(ccb->cgdl.periph_name,
1156 				    "pass", 4) == 0){
1157 					found = 1;
1158 					break;
1159 				}
1160 			}
1161 			if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1162 			    (found == 0)) {
1163 				ccb->cgdl.periph_name[0] = '\0';
1164 				ccb->cgdl.unit_number = 0;
1165 				break;
1166 			}
1167 		}
1168 
1169 		/* copy the result back out */
1170 		bcopy(ccb, addr, sizeof(union ccb));
1171 
1172 		/* and release the ccb */
1173 		xpt_release_ccb(ccb);
1174 
1175 		break;
1176 	default:
1177 		error = ENOTTY;
1178 		break;
1179 	}
1180 	return(error);
1181 }
1182 
1183 static void
1184 cam_periph_done_panic(struct cam_periph *periph, union ccb *done_ccb)
1185 {
1186 
1187 	panic("%s: already done with ccb %p", __func__, done_ccb);
1188 }
1189 
1190 static void
1191 cam_periph_done(struct cam_periph *periph, union ccb *done_ccb)
1192 {
1193 
1194 	/* Caller will release the CCB */
1195 	xpt_path_assert(done_ccb->ccb_h.path, MA_OWNED);
1196 	done_ccb->ccb_h.cbfcnp = cam_periph_done_panic;
1197 	wakeup(&done_ccb->ccb_h.cbfcnp);
1198 }
1199 
1200 static void
1201 cam_periph_ccbwait(union ccb *ccb)
1202 {
1203 
1204 	if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
1205 		while (ccb->ccb_h.cbfcnp != cam_periph_done_panic)
1206 			xpt_path_sleep(ccb->ccb_h.path, &ccb->ccb_h.cbfcnp,
1207 			    PRIBIO, "cbwait", 0);
1208 	}
1209 	KASSERT(ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX &&
1210 	    (ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG,
1211 	    ("%s: proceeding with incomplete ccb: ccb=%p, func_code=%#x, "
1212 	     "status=%#x, index=%d", __func__, ccb, ccb->ccb_h.func_code,
1213 	     ccb->ccb_h.status, ccb->ccb_h.pinfo.index));
1214 }
1215 
1216 /*
1217  * Dispatch a CCB and wait for it to complete.  If the CCB has set a
1218  * callback function (ccb->ccb_h.cbfcnp), it will be overwritten and lost.
1219  */
1220 int
1221 cam_periph_runccb(union ccb *ccb,
1222 		  int (*error_routine)(union ccb *ccb,
1223 				       cam_flags camflags,
1224 				       u_int32_t sense_flags),
1225 		  cam_flags camflags, u_int32_t sense_flags,
1226 		  struct devstat *ds)
1227 {
1228 	struct bintime *starttime;
1229 	struct bintime ltime;
1230 	int error;
1231 	bool must_poll;
1232 	uint32_t timeout = 1;
1233 
1234 	starttime = NULL;
1235 	xpt_path_assert(ccb->ccb_h.path, MA_OWNED);
1236 	KASSERT((ccb->ccb_h.flags & CAM_UNLOCKED) == 0,
1237 	    ("%s: ccb=%p, func_code=%#x, flags=%#x", __func__, ccb,
1238 	     ccb->ccb_h.func_code, ccb->ccb_h.flags));
1239 
1240 	/*
1241 	 * If the user has supplied a stats structure, and if we understand
1242 	 * this particular type of ccb, record the transaction start.
1243 	 */
1244 	if (ds != NULL &&
1245 	    (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1246 	    ccb->ccb_h.func_code == XPT_ATA_IO ||
1247 	    ccb->ccb_h.func_code == XPT_NVME_IO)) {
1248 		starttime = &ltime;
1249 		binuptime(starttime);
1250 		devstat_start_transaction(ds, starttime);
1251 	}
1252 
1253 	/*
1254 	 * We must poll the I/O while we're dumping. The scheduler is normally
1255 	 * stopped for dumping, except when we call doadump from ddb. While the
1256 	 * scheduler is running in this case, we still need to poll the I/O to
1257 	 * avoid sleeping waiting for the ccb to complete.
1258 	 *
1259 	 * A panic triggered dump stops the scheduler, any callback from the
1260 	 * shutdown_post_sync event will run with the scheduler stopped, but
1261 	 * before we're officially dumping. To avoid hanging in adashutdown
1262 	 * initiated commands (or other similar situations), we have to test for
1263 	 * either SCHEDULER_STOPPED() here as well.
1264 	 *
1265 	 * To avoid locking problems, dumping/polling callers must call
1266 	 * without a periph lock held.
1267 	 */
1268 	must_poll = dumping || SCHEDULER_STOPPED();
1269 	ccb->ccb_h.cbfcnp = cam_periph_done;
1270 
1271 	/*
1272 	 * If we're polling, then we need to ensure that we have ample resources
1273 	 * in the periph.  cam_periph_error can reschedule the ccb by calling
1274 	 * xpt_action and returning ERESTART, so we have to effect the polling
1275 	 * in the do loop below.
1276 	 */
1277 	if (must_poll) {
1278 		timeout = xpt_poll_setup(ccb);
1279 	}
1280 
1281 	if (timeout == 0) {
1282 		ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1283 		error = EBUSY;
1284 	} else {
1285 		xpt_action(ccb);
1286 		do {
1287 			if (must_poll) {
1288 				xpt_pollwait(ccb, timeout);
1289 				timeout = ccb->ccb_h.timeout * 10;
1290 			} else {
1291 				cam_periph_ccbwait(ccb);
1292 			}
1293 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1294 				error = 0;
1295 			else if (error_routine != NULL) {
1296 				ccb->ccb_h.cbfcnp = cam_periph_done;
1297 				error = (*error_routine)(ccb, camflags, sense_flags);
1298 			} else
1299 				error = 0;
1300 		} while (error == ERESTART);
1301 	}
1302 
1303 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1304 		cam_release_devq(ccb->ccb_h.path,
1305 				 /* relsim_flags */0,
1306 				 /* openings */0,
1307 				 /* timeout */0,
1308 				 /* getcount_only */ FALSE);
1309 		ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1310 	}
1311 
1312 	if (ds != NULL) {
1313 		uint32_t bytes;
1314 		devstat_tag_type tag;
1315 		bool valid = true;
1316 
1317 		if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1318 			bytes = ccb->csio.dxfer_len - ccb->csio.resid;
1319 			tag = (devstat_tag_type)(ccb->csio.tag_action & 0x3);
1320 		} else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1321 			bytes = ccb->ataio.dxfer_len - ccb->ataio.resid;
1322 			tag = (devstat_tag_type)0;
1323 		} else if (ccb->ccb_h.func_code == XPT_NVME_IO) {
1324 			bytes = ccb->nvmeio.dxfer_len; /* NB: resid no possible */
1325 			tag = (devstat_tag_type)0;
1326 		} else {
1327 			valid = false;
1328 		}
1329 		if (valid)
1330 			devstat_end_transaction(ds, bytes, tag,
1331 			    ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE) ?
1332 			    DEVSTAT_NO_DATA : (ccb->ccb_h.flags & CAM_DIR_OUT) ?
1333 			    DEVSTAT_WRITE : DEVSTAT_READ, NULL, starttime);
1334 	}
1335 
1336 	return(error);
1337 }
1338 
1339 void
1340 cam_freeze_devq(struct cam_path *path)
1341 {
1342 	struct ccb_hdr ccb_h;
1343 
1344 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1345 	xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1346 	ccb_h.func_code = XPT_NOOP;
1347 	ccb_h.flags = CAM_DEV_QFREEZE;
1348 	xpt_action((union ccb *)&ccb_h);
1349 }
1350 
1351 u_int32_t
1352 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1353 		 u_int32_t openings, u_int32_t arg,
1354 		 int getcount_only)
1355 {
1356 	struct ccb_relsim crs;
1357 
1358 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1359 	    relsim_flags, openings, arg, getcount_only));
1360 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1361 	crs.ccb_h.func_code = XPT_REL_SIMQ;
1362 	crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1363 	crs.release_flags = relsim_flags;
1364 	crs.openings = openings;
1365 	crs.release_timeout = arg;
1366 	xpt_action((union ccb *)&crs);
1367 	return (crs.qfrozen_cnt);
1368 }
1369 
1370 #define saved_ccb_ptr ppriv_ptr0
1371 static void
1372 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1373 {
1374 	union ccb      *saved_ccb;
1375 	cam_status	status;
1376 	struct scsi_start_stop_unit *scsi_cmd;
1377 	int		error = 0, error_code, sense_key, asc, ascq;
1378 
1379 	scsi_cmd = (struct scsi_start_stop_unit *)
1380 	    &done_ccb->csio.cdb_io.cdb_bytes;
1381 	status = done_ccb->ccb_h.status;
1382 
1383 	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1384 		if (scsi_extract_sense_ccb(done_ccb,
1385 		    &error_code, &sense_key, &asc, &ascq)) {
1386 			/*
1387 			 * If the error is "invalid field in CDB",
1388 			 * and the load/eject flag is set, turn the
1389 			 * flag off and try again.  This is just in
1390 			 * case the drive in question barfs on the
1391 			 * load eject flag.  The CAM code should set
1392 			 * the load/eject flag by default for
1393 			 * removable media.
1394 			 */
1395 			if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1396 			    ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1397 			     (asc == 0x24) && (ascq == 0x00)) {
1398 				scsi_cmd->how &= ~SSS_LOEJ;
1399 				if (status & CAM_DEV_QFRZN) {
1400 					cam_release_devq(done_ccb->ccb_h.path,
1401 					    0, 0, 0, 0);
1402 					done_ccb->ccb_h.status &=
1403 					    ~CAM_DEV_QFRZN;
1404 				}
1405 				xpt_action(done_ccb);
1406 				goto out;
1407 			}
1408 		}
1409 		error = cam_periph_error(done_ccb, 0,
1410 		    SF_RETRY_UA | SF_NO_PRINT);
1411 		if (error == ERESTART)
1412 			goto out;
1413 		if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1414 			cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1415 			done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1416 		}
1417 	} else {
1418 		/*
1419 		 * If we have successfully taken a device from the not
1420 		 * ready to ready state, re-scan the device and re-get
1421 		 * the inquiry information.  Many devices (mostly disks)
1422 		 * don't properly report their inquiry information unless
1423 		 * they are spun up.
1424 		 */
1425 		if (scsi_cmd->opcode == START_STOP_UNIT)
1426 			xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1427 	}
1428 
1429 	/*
1430 	 * After recovery action(s) completed, return to the original CCB.
1431 	 * If the recovery CCB has failed, considering its own possible
1432 	 * retries and recovery, assume we are back in state where we have
1433 	 * been originally, but without recovery hopes left.  In such case,
1434 	 * after the final attempt below, we cancel any further retries,
1435 	 * blocking by that also any new recovery attempts for this CCB,
1436 	 * and the result will be the final one returned to the CCB owher.
1437 	 */
1438 	saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1439 	bcopy(saved_ccb, done_ccb, sizeof(*done_ccb));
1440 	xpt_free_ccb(saved_ccb);
1441 	if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1442 		periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1443 	if (error != 0)
1444 		done_ccb->ccb_h.retry_count = 0;
1445 	xpt_action(done_ccb);
1446 
1447 out:
1448 	/* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1449 	cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1450 }
1451 
1452 /*
1453  * Generic Async Event handler.  Peripheral drivers usually
1454  * filter out the events that require personal attention,
1455  * and leave the rest to this function.
1456  */
1457 void
1458 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1459 		 struct cam_path *path, void *arg)
1460 {
1461 	switch (code) {
1462 	case AC_LOST_DEVICE:
1463 		cam_periph_invalidate(periph);
1464 		break;
1465 	default:
1466 		break;
1467 	}
1468 }
1469 
1470 void
1471 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1472 {
1473 	struct ccb_getdevstats cgds;
1474 
1475 	xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1476 	cgds.ccb_h.func_code = XPT_GDEV_STATS;
1477 	xpt_action((union ccb *)&cgds);
1478 	cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1479 }
1480 
1481 void
1482 cam_periph_freeze_after_event(struct cam_periph *periph,
1483 			      struct timeval* event_time, u_int duration_ms)
1484 {
1485 	struct timeval delta;
1486 	struct timeval duration_tv;
1487 
1488 	if (!timevalisset(event_time))
1489 		return;
1490 
1491 	microtime(&delta);
1492 	timevalsub(&delta, event_time);
1493 	duration_tv.tv_sec = duration_ms / 1000;
1494 	duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1495 	if (timevalcmp(&delta, &duration_tv, <)) {
1496 		timevalsub(&duration_tv, &delta);
1497 
1498 		duration_ms = duration_tv.tv_sec * 1000;
1499 		duration_ms += duration_tv.tv_usec / 1000;
1500 		cam_freeze_devq(periph->path);
1501 		cam_release_devq(periph->path,
1502 				RELSIM_RELEASE_AFTER_TIMEOUT,
1503 				/*reduction*/0,
1504 				/*timeout*/duration_ms,
1505 				/*getcount_only*/0);
1506 	}
1507 
1508 }
1509 
1510 static int
1511 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1512     cam_flags camflags, u_int32_t sense_flags,
1513     int *openings, u_int32_t *relsim_flags,
1514     u_int32_t *timeout, u_int32_t *action, const char **action_string)
1515 {
1516 	struct cam_periph *periph;
1517 	int error;
1518 
1519 	switch (ccb->csio.scsi_status) {
1520 	case SCSI_STATUS_OK:
1521 	case SCSI_STATUS_COND_MET:
1522 	case SCSI_STATUS_INTERMED:
1523 	case SCSI_STATUS_INTERMED_COND_MET:
1524 		error = 0;
1525 		break;
1526 	case SCSI_STATUS_CMD_TERMINATED:
1527 	case SCSI_STATUS_CHECK_COND:
1528 		error = camperiphscsisenseerror(ccb, orig_ccb,
1529 					        camflags,
1530 					        sense_flags,
1531 					        openings,
1532 					        relsim_flags,
1533 					        timeout,
1534 					        action,
1535 					        action_string);
1536 		break;
1537 	case SCSI_STATUS_QUEUE_FULL:
1538 	{
1539 		/* no decrement */
1540 		struct ccb_getdevstats cgds;
1541 
1542 		/*
1543 		 * First off, find out what the current
1544 		 * transaction counts are.
1545 		 */
1546 		xpt_setup_ccb(&cgds.ccb_h,
1547 			      ccb->ccb_h.path,
1548 			      CAM_PRIORITY_NORMAL);
1549 		cgds.ccb_h.func_code = XPT_GDEV_STATS;
1550 		xpt_action((union ccb *)&cgds);
1551 
1552 		/*
1553 		 * If we were the only transaction active, treat
1554 		 * the QUEUE FULL as if it were a BUSY condition.
1555 		 */
1556 		if (cgds.dev_active != 0) {
1557 			int total_openings;
1558 
1559 			/*
1560 		 	 * Reduce the number of openings to
1561 			 * be 1 less than the amount it took
1562 			 * to get a queue full bounded by the
1563 			 * minimum allowed tag count for this
1564 			 * device.
1565 		 	 */
1566 			total_openings = cgds.dev_active + cgds.dev_openings;
1567 			*openings = cgds.dev_active;
1568 			if (*openings < cgds.mintags)
1569 				*openings = cgds.mintags;
1570 			if (*openings < total_openings)
1571 				*relsim_flags = RELSIM_ADJUST_OPENINGS;
1572 			else {
1573 				/*
1574 				 * Some devices report queue full for
1575 				 * temporary resource shortages.  For
1576 				 * this reason, we allow a minimum
1577 				 * tag count to be entered via a
1578 				 * quirk entry to prevent the queue
1579 				 * count on these devices from falling
1580 				 * to a pessimisticly low value.  We
1581 				 * still wait for the next successful
1582 				 * completion, however, before queueing
1583 				 * more transactions to the device.
1584 				 */
1585 				*relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1586 			}
1587 			*timeout = 0;
1588 			error = ERESTART;
1589 			*action &= ~SSQ_PRINT_SENSE;
1590 			break;
1591 		}
1592 		/* FALLTHROUGH */
1593 	}
1594 	case SCSI_STATUS_BUSY:
1595 		/*
1596 		 * Restart the queue after either another
1597 		 * command completes or a 1 second timeout.
1598 		 */
1599 		periph = xpt_path_periph(ccb->ccb_h.path);
1600 		if (periph->flags & CAM_PERIPH_INVALID) {
1601 			error = EIO;
1602 			*action_string = "Periph was invalidated";
1603 		} else if ((sense_flags & SF_RETRY_BUSY) != 0 ||
1604 		    ccb->ccb_h.retry_count > 0) {
1605 			if ((sense_flags & SF_RETRY_BUSY) == 0)
1606 				ccb->ccb_h.retry_count--;
1607 			error = ERESTART;
1608 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1609 				      | RELSIM_RELEASE_AFTER_CMDCMPLT;
1610 			*timeout = 1000;
1611 		} else {
1612 			error = EIO;
1613 			*action_string = "Retries exhausted";
1614 		}
1615 		break;
1616 	case SCSI_STATUS_RESERV_CONFLICT:
1617 	default:
1618 		error = EIO;
1619 		break;
1620 	}
1621 	return (error);
1622 }
1623 
1624 static int
1625 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1626     cam_flags camflags, u_int32_t sense_flags,
1627     int *openings, u_int32_t *relsim_flags,
1628     u_int32_t *timeout, u_int32_t *action, const char **action_string)
1629 {
1630 	struct cam_periph *periph;
1631 	union ccb *orig_ccb = ccb;
1632 	int error, recoveryccb;
1633 
1634 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1635 	if (ccb->ccb_h.func_code == XPT_SCSI_IO && ccb->csio.bio != NULL)
1636 		biotrack(ccb->csio.bio, __func__);
1637 #endif
1638 
1639 	periph = xpt_path_periph(ccb->ccb_h.path);
1640 	recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1641 	if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1642 		/*
1643 		 * If error recovery is already in progress, don't attempt
1644 		 * to process this error, but requeue it unconditionally
1645 		 * and attempt to process it once error recovery has
1646 		 * completed.  This failed command is probably related to
1647 		 * the error that caused the currently active error recovery
1648 		 * action so our  current recovery efforts should also
1649 		 * address this command.  Be aware that the error recovery
1650 		 * code assumes that only one recovery action is in progress
1651 		 * on a particular peripheral instance at any given time
1652 		 * (e.g. only one saved CCB for error recovery) so it is
1653 		 * imperitive that we don't violate this assumption.
1654 		 */
1655 		error = ERESTART;
1656 		*action &= ~SSQ_PRINT_SENSE;
1657 	} else {
1658 		scsi_sense_action err_action;
1659 		struct ccb_getdev cgd;
1660 
1661 		/*
1662 		 * Grab the inquiry data for this device.
1663 		 */
1664 		xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1665 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1666 		xpt_action((union ccb *)&cgd);
1667 
1668 		err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1669 		    sense_flags);
1670 		error = err_action & SS_ERRMASK;
1671 
1672 		/*
1673 		 * Do not autostart sequential access devices
1674 		 * to avoid unexpected tape loading.
1675 		 */
1676 		if ((err_action & SS_MASK) == SS_START &&
1677 		    SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1678 			*action_string = "Will not autostart a "
1679 			    "sequential access device";
1680 			goto sense_error_done;
1681 		}
1682 
1683 		/*
1684 		 * Avoid recovery recursion if recovery action is the same.
1685 		 */
1686 		if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1687 			if (((err_action & SS_MASK) == SS_START &&
1688 			     ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1689 			    ((err_action & SS_MASK) == SS_TUR &&
1690 			     (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1691 				err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1692 				*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1693 				*timeout = 500;
1694 			}
1695 		}
1696 
1697 		/*
1698 		 * If the recovery action will consume a retry,
1699 		 * make sure we actually have retries available.
1700 		 */
1701 		if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1702 		 	if (ccb->ccb_h.retry_count > 0 &&
1703 			    (periph->flags & CAM_PERIPH_INVALID) == 0)
1704 		 		ccb->ccb_h.retry_count--;
1705 			else {
1706 				*action_string = "Retries exhausted";
1707 				goto sense_error_done;
1708 			}
1709 		}
1710 
1711 		if ((err_action & SS_MASK) >= SS_START) {
1712 			/*
1713 			 * Do common portions of commands that
1714 			 * use recovery CCBs.
1715 			 */
1716 			orig_ccb = xpt_alloc_ccb_nowait();
1717 			if (orig_ccb == NULL) {
1718 				*action_string = "Can't allocate recovery CCB";
1719 				goto sense_error_done;
1720 			}
1721 			/*
1722 			 * Clear freeze flag for original request here, as
1723 			 * this freeze will be dropped as part of ERESTART.
1724 			 */
1725 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1726 			bcopy(ccb, orig_ccb, sizeof(*orig_ccb));
1727 		}
1728 
1729 		switch (err_action & SS_MASK) {
1730 		case SS_NOP:
1731 			*action_string = "No recovery action needed";
1732 			error = 0;
1733 			break;
1734 		case SS_RETRY:
1735 			*action_string = "Retrying command (per sense data)";
1736 			error = ERESTART;
1737 			break;
1738 		case SS_FAIL:
1739 			*action_string = "Unretryable error";
1740 			break;
1741 		case SS_START:
1742 		{
1743 			int le;
1744 
1745 			/*
1746 			 * Send a start unit command to the device, and
1747 			 * then retry the command.
1748 			 */
1749 			*action_string = "Attempting to start unit";
1750 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1751 
1752 			/*
1753 			 * Check for removable media and set
1754 			 * load/eject flag appropriately.
1755 			 */
1756 			if (SID_IS_REMOVABLE(&cgd.inq_data))
1757 				le = TRUE;
1758 			else
1759 				le = FALSE;
1760 
1761 			scsi_start_stop(&ccb->csio,
1762 					/*retries*/1,
1763 					camperiphdone,
1764 					MSG_SIMPLE_Q_TAG,
1765 					/*start*/TRUE,
1766 					/*load/eject*/le,
1767 					/*immediate*/FALSE,
1768 					SSD_FULL_SIZE,
1769 					/*timeout*/50000);
1770 			break;
1771 		}
1772 		case SS_TUR:
1773 		{
1774 			/*
1775 			 * Send a Test Unit Ready to the device.
1776 			 * If the 'many' flag is set, we send 120
1777 			 * test unit ready commands, one every half
1778 			 * second.  Otherwise, we just send one TUR.
1779 			 * We only want to do this if the retry
1780 			 * count has not been exhausted.
1781 			 */
1782 			int retries;
1783 
1784 			if ((err_action & SSQ_MANY) != 0) {
1785 				*action_string = "Polling device for readiness";
1786 				retries = 120;
1787 			} else {
1788 				*action_string = "Testing device for readiness";
1789 				retries = 1;
1790 			}
1791 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1792 			scsi_test_unit_ready(&ccb->csio,
1793 					     retries,
1794 					     camperiphdone,
1795 					     MSG_SIMPLE_Q_TAG,
1796 					     SSD_FULL_SIZE,
1797 					     /*timeout*/5000);
1798 
1799 			/*
1800 			 * Accomplish our 500ms delay by deferring
1801 			 * the release of our device queue appropriately.
1802 			 */
1803 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1804 			*timeout = 500;
1805 			break;
1806 		}
1807 		default:
1808 			panic("Unhandled error action %x", err_action);
1809 		}
1810 
1811 		if ((err_action & SS_MASK) >= SS_START) {
1812 			/*
1813 			 * Drop the priority, so that the recovery
1814 			 * CCB is the first to execute.  Freeze the queue
1815 			 * after this command is sent so that we can
1816 			 * restore the old csio and have it queued in
1817 			 * the proper order before we release normal
1818 			 * transactions to the device.
1819 			 */
1820 			ccb->ccb_h.pinfo.priority--;
1821 			ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1822 			ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1823 			error = ERESTART;
1824 			*orig = orig_ccb;
1825 		}
1826 
1827 sense_error_done:
1828 		*action = err_action;
1829 	}
1830 	return (error);
1831 }
1832 
1833 /*
1834  * Generic error handler.  Peripheral drivers usually filter
1835  * out the errors that they handle in a unique manner, then
1836  * call this function.
1837  */
1838 int
1839 cam_periph_error(union ccb *ccb, cam_flags camflags,
1840 		 u_int32_t sense_flags)
1841 {
1842 	struct cam_path *newpath;
1843 	union ccb  *orig_ccb, *scan_ccb;
1844 	struct cam_periph *periph;
1845 	const char *action_string;
1846 	cam_status  status;
1847 	int	    frozen, error, openings, devctl_err;
1848 	u_int32_t   action, relsim_flags, timeout;
1849 
1850 	action = SSQ_PRINT_SENSE;
1851 	periph = xpt_path_periph(ccb->ccb_h.path);
1852 	action_string = NULL;
1853 	status = ccb->ccb_h.status;
1854 	frozen = (status & CAM_DEV_QFRZN) != 0;
1855 	status &= CAM_STATUS_MASK;
1856 	devctl_err = openings = relsim_flags = timeout = 0;
1857 	orig_ccb = ccb;
1858 
1859 	/* Filter the errors that should be reported via devctl */
1860 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1861 	case CAM_CMD_TIMEOUT:
1862 	case CAM_REQ_ABORTED:
1863 	case CAM_REQ_CMP_ERR:
1864 	case CAM_REQ_TERMIO:
1865 	case CAM_UNREC_HBA_ERROR:
1866 	case CAM_DATA_RUN_ERR:
1867 	case CAM_SCSI_STATUS_ERROR:
1868 	case CAM_ATA_STATUS_ERROR:
1869 	case CAM_SMP_STATUS_ERROR:
1870 		devctl_err++;
1871 		break;
1872 	default:
1873 		break;
1874 	}
1875 
1876 	switch (status) {
1877 	case CAM_REQ_CMP:
1878 		error = 0;
1879 		action &= ~SSQ_PRINT_SENSE;
1880 		break;
1881 	case CAM_SCSI_STATUS_ERROR:
1882 		error = camperiphscsistatuserror(ccb, &orig_ccb,
1883 		    camflags, sense_flags, &openings, &relsim_flags,
1884 		    &timeout, &action, &action_string);
1885 		break;
1886 	case CAM_AUTOSENSE_FAIL:
1887 		error = EIO;	/* we have to kill the command */
1888 		break;
1889 	case CAM_UA_ABORT:
1890 	case CAM_UA_TERMIO:
1891 	case CAM_MSG_REJECT_REC:
1892 		/* XXX Don't know that these are correct */
1893 		error = EIO;
1894 		break;
1895 	case CAM_SEL_TIMEOUT:
1896 		if ((camflags & CAM_RETRY_SELTO) != 0) {
1897 			if (ccb->ccb_h.retry_count > 0 &&
1898 			    (periph->flags & CAM_PERIPH_INVALID) == 0) {
1899 				ccb->ccb_h.retry_count--;
1900 				error = ERESTART;
1901 
1902 				/*
1903 				 * Wait a bit to give the device
1904 				 * time to recover before we try again.
1905 				 */
1906 				relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1907 				timeout = periph_selto_delay;
1908 				break;
1909 			}
1910 			action_string = "Retries exhausted";
1911 		}
1912 		/* FALLTHROUGH */
1913 	case CAM_DEV_NOT_THERE:
1914 		error = ENXIO;
1915 		action = SSQ_LOST;
1916 		break;
1917 	case CAM_REQ_INVALID:
1918 	case CAM_PATH_INVALID:
1919 	case CAM_NO_HBA:
1920 	case CAM_PROVIDE_FAIL:
1921 	case CAM_REQ_TOO_BIG:
1922 	case CAM_LUN_INVALID:
1923 	case CAM_TID_INVALID:
1924 	case CAM_FUNC_NOTAVAIL:
1925 		error = EINVAL;
1926 		break;
1927 	case CAM_SCSI_BUS_RESET:
1928 	case CAM_BDR_SENT:
1929 		/*
1930 		 * Commands that repeatedly timeout and cause these
1931 		 * kinds of error recovery actions, should return
1932 		 * CAM_CMD_TIMEOUT, which allows us to safely assume
1933 		 * that this command was an innocent bystander to
1934 		 * these events and should be unconditionally
1935 		 * retried.
1936 		 */
1937 	case CAM_REQUEUE_REQ:
1938 		/* Unconditional requeue if device is still there */
1939 		if (periph->flags & CAM_PERIPH_INVALID) {
1940 			action_string = "Periph was invalidated";
1941 			error = EIO;
1942 		} else if (sense_flags & SF_NO_RETRY) {
1943 			error = EIO;
1944 			action_string = "Retry was blocked";
1945 		} else {
1946 			error = ERESTART;
1947 			action &= ~SSQ_PRINT_SENSE;
1948 		}
1949 		break;
1950 	case CAM_RESRC_UNAVAIL:
1951 		/* Wait a bit for the resource shortage to abate. */
1952 		timeout = periph_noresrc_delay;
1953 		/* FALLTHROUGH */
1954 	case CAM_BUSY:
1955 		if (timeout == 0) {
1956 			/* Wait a bit for the busy condition to abate. */
1957 			timeout = periph_busy_delay;
1958 		}
1959 		relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1960 		/* FALLTHROUGH */
1961 	case CAM_ATA_STATUS_ERROR:
1962 	case CAM_REQ_CMP_ERR:
1963 	case CAM_CMD_TIMEOUT:
1964 	case CAM_UNEXP_BUSFREE:
1965 	case CAM_UNCOR_PARITY:
1966 	case CAM_DATA_RUN_ERR:
1967 	default:
1968 		if (periph->flags & CAM_PERIPH_INVALID) {
1969 			error = EIO;
1970 			action_string = "Periph was invalidated";
1971 		} else if (ccb->ccb_h.retry_count == 0) {
1972 			error = EIO;
1973 			action_string = "Retries exhausted";
1974 		} else if (sense_flags & SF_NO_RETRY) {
1975 			error = EIO;
1976 			action_string = "Retry was blocked";
1977 		} else {
1978 			ccb->ccb_h.retry_count--;
1979 			error = ERESTART;
1980 		}
1981 		break;
1982 	}
1983 
1984 	if ((sense_flags & SF_PRINT_ALWAYS) ||
1985 	    CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
1986 		action |= SSQ_PRINT_SENSE;
1987 	else if (sense_flags & SF_NO_PRINT)
1988 		action &= ~SSQ_PRINT_SENSE;
1989 	if ((action & SSQ_PRINT_SENSE) != 0)
1990 		cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1991 	if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
1992 		if (error != ERESTART) {
1993 			if (action_string == NULL)
1994 				action_string = "Unretryable error";
1995 			xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
1996 			    error, action_string);
1997 		} else if (action_string != NULL)
1998 			xpt_print(ccb->ccb_h.path, "%s\n", action_string);
1999 		else {
2000 			xpt_print(ccb->ccb_h.path,
2001 			    "Retrying command, %d more tries remain\n",
2002 			    ccb->ccb_h.retry_count);
2003 		}
2004 	}
2005 
2006 	if (devctl_err && (error != 0 || (action & SSQ_PRINT_SENSE) != 0))
2007 		cam_periph_devctl_notify(orig_ccb);
2008 
2009 	if ((action & SSQ_LOST) != 0) {
2010 		lun_id_t lun_id;
2011 
2012 		/*
2013 		 * For a selection timeout, we consider all of the LUNs on
2014 		 * the target to be gone.  If the status is CAM_DEV_NOT_THERE,
2015 		 * then we only get rid of the device(s) specified by the
2016 		 * path in the original CCB.
2017 		 */
2018 		if (status == CAM_SEL_TIMEOUT)
2019 			lun_id = CAM_LUN_WILDCARD;
2020 		else
2021 			lun_id = xpt_path_lun_id(ccb->ccb_h.path);
2022 
2023 		/* Should we do more if we can't create the path?? */
2024 		if (xpt_create_path(&newpath, periph,
2025 				    xpt_path_path_id(ccb->ccb_h.path),
2026 				    xpt_path_target_id(ccb->ccb_h.path),
2027 				    lun_id) == CAM_REQ_CMP) {
2028 
2029 			/*
2030 			 * Let peripheral drivers know that this
2031 			 * device has gone away.
2032 			 */
2033 			xpt_async(AC_LOST_DEVICE, newpath, NULL);
2034 			xpt_free_path(newpath);
2035 		}
2036 	}
2037 
2038 	/* Broadcast UNIT ATTENTIONs to all periphs. */
2039 	if ((action & SSQ_UA) != 0)
2040 		xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
2041 
2042 	/* Rescan target on "Reported LUNs data has changed" */
2043 	if ((action & SSQ_RESCAN) != 0) {
2044 		if (xpt_create_path(&newpath, NULL,
2045 				    xpt_path_path_id(ccb->ccb_h.path),
2046 				    xpt_path_target_id(ccb->ccb_h.path),
2047 				    CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
2048 
2049 			scan_ccb = xpt_alloc_ccb_nowait();
2050 			if (scan_ccb != NULL) {
2051 				scan_ccb->ccb_h.path = newpath;
2052 				scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
2053 				scan_ccb->crcn.flags = 0;
2054 				xpt_rescan(scan_ccb);
2055 			} else {
2056 				xpt_print(newpath,
2057 				    "Can't allocate CCB to rescan target\n");
2058 				xpt_free_path(newpath);
2059 			}
2060 		}
2061 	}
2062 
2063 	/* Attempt a retry */
2064 	if (error == ERESTART || error == 0) {
2065 		if (frozen != 0)
2066 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
2067 		if (error == ERESTART)
2068 			xpt_action(ccb);
2069 		if (frozen != 0)
2070 			cam_release_devq(ccb->ccb_h.path,
2071 					 relsim_flags,
2072 					 openings,
2073 					 timeout,
2074 					 /*getcount_only*/0);
2075 	}
2076 
2077 	return (error);
2078 }
2079 
2080 #define CAM_PERIPH_DEVD_MSG_SIZE	256
2081 
2082 static void
2083 cam_periph_devctl_notify(union ccb *ccb)
2084 {
2085 	struct cam_periph *periph;
2086 	struct ccb_getdev *cgd;
2087 	struct sbuf sb;
2088 	int serr, sk, asc, ascq;
2089 	char *sbmsg, *type;
2090 
2091 	sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT);
2092 	if (sbmsg == NULL)
2093 		return;
2094 
2095 	sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN);
2096 
2097 	periph = xpt_path_periph(ccb->ccb_h.path);
2098 	sbuf_printf(&sb, "device=%s%d ", periph->periph_name,
2099 	    periph->unit_number);
2100 
2101 	sbuf_printf(&sb, "serial=\"");
2102 	if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) {
2103 		xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path,
2104 		    CAM_PRIORITY_NORMAL);
2105 		cgd->ccb_h.func_code = XPT_GDEV_TYPE;
2106 		xpt_action((union ccb *)cgd);
2107 
2108 		if (cgd->ccb_h.status == CAM_REQ_CMP)
2109 			sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len);
2110 		xpt_free_ccb((union ccb *)cgd);
2111 	}
2112 	sbuf_printf(&sb, "\" ");
2113 	sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status);
2114 
2115 	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
2116 	case CAM_CMD_TIMEOUT:
2117 		sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout);
2118 		type = "timeout";
2119 		break;
2120 	case CAM_SCSI_STATUS_ERROR:
2121 		sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status);
2122 		if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq))
2123 			sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ",
2124 			    serr, sk, asc, ascq);
2125 		type = "error";
2126 		break;
2127 	case CAM_ATA_STATUS_ERROR:
2128 		sbuf_printf(&sb, "RES=\"");
2129 		ata_res_sbuf(&ccb->ataio.res, &sb);
2130 		sbuf_printf(&sb, "\" ");
2131 		type = "error";
2132 		break;
2133 	default:
2134 		type = "error";
2135 		break;
2136 	}
2137 
2138 	if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2139 		sbuf_printf(&sb, "CDB=\"");
2140 		scsi_cdb_sbuf(scsiio_cdb_ptr(&ccb->csio), &sb);
2141 		sbuf_printf(&sb, "\" ");
2142 	} else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2143 		sbuf_printf(&sb, "ACB=\"");
2144 		ata_cmd_sbuf(&ccb->ataio.cmd, &sb);
2145 		sbuf_printf(&sb, "\" ");
2146 	}
2147 
2148 	if (sbuf_finish(&sb) == 0)
2149 		devctl_notify("CAM", "periph", type, sbuf_data(&sb));
2150 	sbuf_delete(&sb);
2151 	free(sbmsg, M_CAMPERIPH);
2152 }
2153 
2154 /*
2155  * Sysctl to force an invalidation of the drive right now. Can be
2156  * called with CTLFLAG_MPSAFE since we take periph lock.
2157  */
2158 int
2159 cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)
2160 {
2161 	struct cam_periph *periph;
2162 	int error, value;
2163 
2164 	periph = arg1;
2165 	value = 0;
2166 	error = sysctl_handle_int(oidp, &value, 0, req);
2167 	if (error != 0 || req->newptr == NULL || value != 1)
2168 		return (error);
2169 
2170 	cam_periph_lock(periph);
2171 	cam_periph_invalidate(periph);
2172 	cam_periph_unlock(periph);
2173 
2174 	return (0);
2175 }
2176