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