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