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