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