xref: /freebsd/sys/cam/cam_periph.c (revision 3047fefe49f57a673de8df152c199de12ec2c6d3)
1 /*
2  * Common functions for CAM "type" (peripheral) drivers.
3  *
4  * Copyright (c) 1997, 1998 Justin T. Gibbs.
5  * Copyright (c) 1997, 1998, 1999, 2000 Kenneth D. Merry.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/types.h>
35 #include <sys/malloc.h>
36 #include <sys/linker_set.h>
37 #include <sys/bio.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/buf.h>
41 #include <sys/proc.h>
42 #include <sys/devicestat.h>
43 #include <sys/bus.h>
44 #include <vm/vm.h>
45 #include <vm/vm_extern.h>
46 
47 #include <cam/cam.h>
48 #include <cam/cam_ccb.h>
49 #include <cam/cam_xpt_periph.h>
50 #include <cam/cam_periph.h>
51 #include <cam/cam_debug.h>
52 
53 #include <cam/scsi/scsi_all.h>
54 #include <cam/scsi/scsi_message.h>
55 #include <cam/scsi/scsi_pass.h>
56 
57 static	u_int		camperiphnextunit(struct periph_driver *p_drv,
58 					  u_int newunit, int wired,
59 					  path_id_t pathid, target_id_t target,
60 					  lun_id_t lun);
61 static	u_int		camperiphunit(struct periph_driver *p_drv,
62 				      path_id_t pathid, target_id_t target,
63 				      lun_id_t lun);
64 static	void		camperiphdone(struct cam_periph *periph,
65 					union ccb *done_ccb);
66 static  void		camperiphfree(struct cam_periph *periph);
67 static int		camperiphscsistatuserror(union ccb *ccb,
68 						 cam_flags camflags,
69 						 u_int32_t sense_flags,
70 						 union ccb *save_ccb,
71 						 int *openings,
72 						 u_int32_t *relsim_flags,
73 						 u_int32_t *timeout);
74 static	int		camperiphscsisenseerror(union ccb *ccb,
75 					        cam_flags camflags,
76 					        u_int32_t sense_flags,
77 					        union ccb *save_ccb,
78 					        int *openings,
79 					        u_int32_t *relsim_flags,
80 					        u_int32_t *timeout);
81 
82 static int nperiph_drivers;
83 struct periph_driver **periph_drivers;
84 
85 void
86 periphdriver_register(void *data)
87 {
88 	struct periph_driver **newdrivers, **old;
89 	int ndrivers;
90 
91 	ndrivers = nperiph_drivers + 2;
92 	newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_TEMP, M_WAITOK);
93 	if (periph_drivers)
94 		bcopy(periph_drivers, newdrivers,
95 		      sizeof(*newdrivers) * nperiph_drivers);
96 	newdrivers[nperiph_drivers] = (struct periph_driver *)data;
97 	newdrivers[nperiph_drivers + 1] = NULL;
98 	old = periph_drivers;
99 	periph_drivers = newdrivers;
100 	if (old)
101 		free(old, M_TEMP);
102 	nperiph_drivers++;
103 }
104 
105 cam_status
106 cam_periph_alloc(periph_ctor_t *periph_ctor,
107 		 periph_oninv_t *periph_oninvalidate,
108 		 periph_dtor_t *periph_dtor, periph_start_t *periph_start,
109 		 char *name, cam_periph_type type, struct cam_path *path,
110 		 ac_callback_t *ac_callback, ac_code code, void *arg)
111 {
112 	struct		periph_driver **p_drv;
113 	struct		cam_periph *periph;
114 	struct		cam_periph *cur_periph;
115 	path_id_t	path_id;
116 	target_id_t	target_id;
117 	lun_id_t	lun_id;
118 	cam_status	status;
119 	u_int		init_level;
120 	int s;
121 
122 	init_level = 0;
123 	/*
124 	 * Handle Hot-Plug scenarios.  If there is already a peripheral
125 	 * of our type assigned to this path, we are likely waiting for
126 	 * final close on an old, invalidated, peripheral.  If this is
127 	 * the case, queue up a deferred call to the peripheral's async
128 	 * handler.  If it looks like a mistaken re-alloation, complain.
129 	 */
130 	if ((periph = cam_periph_find(path, name)) != NULL) {
131 
132 		if ((periph->flags & CAM_PERIPH_INVALID) != 0
133 		 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
134 			periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
135 			periph->deferred_callback = ac_callback;
136 			periph->deferred_ac = code;
137 			return (CAM_REQ_INPROG);
138 		} else {
139 			printf("cam_periph_alloc: attempt to re-allocate "
140 			       "valid device %s%d rejected\n",
141 			       periph->periph_name, periph->unit_number);
142 		}
143 		return (CAM_REQ_INVALID);
144 	}
145 
146 	periph = (struct cam_periph *)malloc(sizeof(*periph), M_DEVBUF,
147 					     M_NOWAIT);
148 
149 	if (periph == NULL)
150 		return (CAM_RESRC_UNAVAIL);
151 
152 	init_level++;
153 
154 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
155 		if (strcmp((*p_drv)->driver_name, name) == 0)
156 			break;
157 	}
158 
159 	path_id = xpt_path_path_id(path);
160 	target_id = xpt_path_target_id(path);
161 	lun_id = xpt_path_lun_id(path);
162 	bzero(periph, sizeof(*periph));
163 	cam_init_pinfo(&periph->pinfo);
164 	periph->periph_start = periph_start;
165 	periph->periph_dtor = periph_dtor;
166 	periph->periph_oninval = periph_oninvalidate;
167 	periph->type = type;
168 	periph->periph_name = name;
169 	periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id);
170 	periph->immediate_priority = CAM_PRIORITY_NONE;
171 	periph->refcount = 0;
172 	SLIST_INIT(&periph->ccb_list);
173 	status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
174 	if (status != CAM_REQ_CMP)
175 		goto failure;
176 
177 	periph->path = path;
178 	init_level++;
179 
180 	status = xpt_add_periph(periph);
181 
182 	if (status != CAM_REQ_CMP)
183 		goto failure;
184 
185 	s = splsoftcam();
186 	cur_periph = TAILQ_FIRST(&(*p_drv)->units);
187 	while (cur_periph != NULL
188 	    && cur_periph->unit_number < periph->unit_number)
189 		cur_periph = TAILQ_NEXT(cur_periph, unit_links);
190 
191 	if (cur_periph != NULL)
192 		TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
193 	else {
194 		TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
195 		(*p_drv)->generation++;
196 	}
197 
198 	splx(s);
199 
200 	init_level++;
201 
202 	status = periph_ctor(periph, arg);
203 
204 	if (status == CAM_REQ_CMP)
205 		init_level++;
206 
207 failure:
208 	switch (init_level) {
209 	case 4:
210 		/* Initialized successfully */
211 		break;
212 	case 3:
213 		s = splsoftcam();
214 		TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
215 		splx(s);
216 		xpt_remove_periph(periph);
217 	case 2:
218 		xpt_free_path(periph->path);
219 	case 1:
220 		free(periph, M_DEVBUF);
221 	case 0:
222 		/* No cleanup to perform. */
223 		break;
224 	default:
225 		panic("cam_periph_alloc: Unkown init level");
226 	}
227 	return(status);
228 }
229 
230 /*
231  * Find a peripheral structure with the specified path, target, lun,
232  * and (optionally) type.  If the name is NULL, this function will return
233  * the first peripheral driver that matches the specified path.
234  */
235 struct cam_periph *
236 cam_periph_find(struct cam_path *path, char *name)
237 {
238 	struct periph_driver **p_drv;
239 	struct cam_periph *periph;
240 	int s;
241 
242 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
243 
244 		if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
245 			continue;
246 
247 		s = splsoftcam();
248 		TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
249 			if (xpt_path_comp(periph->path, path) == 0) {
250 				splx(s);
251 				return(periph);
252 			}
253 		}
254 		splx(s);
255 		if (name != NULL)
256 			return(NULL);
257 	}
258 	return(NULL);
259 }
260 
261 cam_status
262 cam_periph_acquire(struct cam_periph *periph)
263 {
264 	int s;
265 
266 	if (periph == NULL)
267 		return(CAM_REQ_CMP_ERR);
268 
269 	s = splsoftcam();
270 	periph->refcount++;
271 	splx(s);
272 
273 	return(CAM_REQ_CMP);
274 }
275 
276 void
277 cam_periph_release(struct cam_periph *periph)
278 {
279 	int s;
280 
281 	if (periph == NULL)
282 		return;
283 
284 	s = splsoftcam();
285 	if ((--periph->refcount == 0)
286 	 && (periph->flags & CAM_PERIPH_INVALID)) {
287 		camperiphfree(periph);
288 	}
289 	splx(s);
290 
291 }
292 
293 /*
294  * Look for the next unit number that is not currently in use for this
295  * peripheral type starting at "newunit".  Also exclude unit numbers that
296  * are reserved by for future "hardwiring" unless we already know that this
297  * is a potential wired device.  Only assume that the device is "wired" the
298  * first time through the loop since after that we'll be looking at unit
299  * numbers that did not match a wiring entry.
300  */
301 static u_int
302 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
303 		  path_id_t pathid, target_id_t target, lun_id_t lun)
304 {
305 	struct	cam_periph *periph;
306 	char	*periph_name;
307 	int	s;
308 	int	i, val, dunit, r;
309 	const char *dname, *strval;
310 
311 	s = splsoftcam();
312 	periph_name = p_drv->driver_name;
313 	for (;;newunit++) {
314 
315 		for (periph = TAILQ_FIRST(&p_drv->units);
316 		     periph != NULL && periph->unit_number != newunit;
317 		     periph = TAILQ_NEXT(periph, unit_links))
318 			;
319 
320 		if (periph != NULL && periph->unit_number == newunit) {
321 			if (wired != 0) {
322 				xpt_print_path(periph->path);
323 				printf("Duplicate Wired Device entry!\n");
324 				xpt_print_path(periph->path);
325 				printf("Second device (%s device at scbus%d "
326 				       "target %d lun %d) will not be wired\n",
327 				       periph_name, pathid, target, lun);
328 				wired = 0;
329 			}
330 			continue;
331 		}
332 		if (wired)
333 			break;
334 
335 		/*
336 		 * Don't match entries like "da 4" as a wired down
337 		 * device, but do match entries like "da 4 target 5"
338 		 * or even "da 4 scbus 1".
339 		 */
340 		i = 0;
341 		dname = periph_name;
342 		for (;;) {
343 			r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
344 			if (r != 0)
345 				break;
346 			/* if no "target" and no specific scbus, skip */
347 			if (resource_int_value(dname, dunit, "target", &val) &&
348 			    (resource_string_value(dname, dunit, "at",&strval)||
349 			     strcmp(strval, "scbus") == 0))
350 				continue;
351 			if (newunit == dunit)
352 				break;
353 		}
354 		if (r != 0)
355 			break;
356 	}
357 	splx(s);
358 	return (newunit);
359 }
360 
361 static u_int
362 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
363 	      target_id_t target, lun_id_t lun)
364 {
365 	u_int	unit;
366 	int	wired, i, val, dunit;
367 	const char *dname, *strval;
368 	char	pathbuf[32], *periph_name;
369 
370 	periph_name = p_drv->driver_name;
371 	snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
372 	unit = 0;
373 	i = 0;
374 	dname = periph_name;
375 	for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
376 	     wired = 0) {
377 		if (resource_string_value(dname, dunit, "at", &strval) == 0) {
378 			if (strcmp(strval, pathbuf) != 0)
379 				continue;
380 			wired++;
381 		}
382 		if (resource_int_value(dname, dunit, "target", &val) == 0) {
383 			if (val != target)
384 				continue;
385 			wired++;
386 		}
387 		if (resource_int_value(dname, dunit, "lun", &val) == 0) {
388 			if (val != lun)
389 				continue;
390 			wired++;
391 		}
392 		if (wired != 0) {
393 			unit = dunit;
394 			break;
395 		}
396 	}
397 
398 	/*
399 	 * Either start from 0 looking for the next unit or from
400 	 * the unit number given in the resource config.  This way,
401 	 * if we have wildcard matches, we don't return the same
402 	 * unit number twice.
403 	 */
404 	unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
405 
406 	return (unit);
407 }
408 
409 void
410 cam_periph_invalidate(struct cam_periph *periph)
411 {
412 	int s;
413 
414 	s = splsoftcam();
415 	/*
416 	 * We only call this routine the first time a peripheral is
417 	 * invalidated.  The oninvalidate() routine is always called at
418 	 * splsoftcam().
419 	 */
420 	if (((periph->flags & CAM_PERIPH_INVALID) == 0)
421 	 && (periph->periph_oninval != NULL))
422 		periph->periph_oninval(periph);
423 
424 	periph->flags |= CAM_PERIPH_INVALID;
425 	periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
426 
427 	if (periph->refcount == 0)
428 		camperiphfree(periph);
429 	else if (periph->refcount < 0)
430 		printf("cam_invalidate_periph: refcount < 0!!\n");
431 	splx(s);
432 }
433 
434 static void
435 camperiphfree(struct cam_periph *periph)
436 {
437 	int s;
438 	struct periph_driver **p_drv;
439 
440 	for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
441 		if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
442 			break;
443 	}
444 
445 	if (periph->periph_dtor != NULL)
446 		periph->periph_dtor(periph);
447 
448 	s = splsoftcam();
449 	TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
450 	(*p_drv)->generation++;
451 	splx(s);
452 
453 	xpt_remove_periph(periph);
454 
455 	if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
456 		union ccb ccb;
457 		void *arg;
458 
459 		switch (periph->deferred_ac) {
460 		case AC_FOUND_DEVICE:
461 			ccb.ccb_h.func_code = XPT_GDEV_TYPE;
462 			xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/ 1);
463 			xpt_action(&ccb);
464 			arg = &ccb;
465 			break;
466 		case AC_PATH_REGISTERED:
467 			ccb.ccb_h.func_code = XPT_PATH_INQ;
468 			xpt_setup_ccb(&ccb.ccb_h, periph->path, /*priority*/ 1);
469 			xpt_action(&ccb);
470 			arg = &ccb;
471 			break;
472 		default:
473 			arg = NULL;
474 			break;
475 		}
476 		periph->deferred_callback(NULL, periph->deferred_ac,
477 					  periph->path, arg);
478 	}
479 	xpt_free_path(periph->path);
480 	free(periph, M_DEVBUF);
481 }
482 
483 /*
484  * Wait interruptibly for an exclusive lock.
485  */
486 int
487 cam_periph_lock(struct cam_periph *periph, int priority)
488 {
489 	int error;
490 
491 	/*
492 	 * Increment the reference count on the peripheral
493 	 * while we wait for our lock attempt to succeed
494 	 * to ensure the peripheral doesn't disappear out
495 	 * from under us while we sleep.
496 	 */
497 	if (cam_periph_acquire(periph) != CAM_REQ_CMP)
498 		return(ENXIO);
499 
500 	while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
501 		periph->flags |= CAM_PERIPH_LOCK_WANTED;
502 		if ((error = tsleep(periph, priority, "caplck", 0)) != 0) {
503 			cam_periph_release(periph);
504 			return error;
505 		}
506 	}
507 
508 	periph->flags |= CAM_PERIPH_LOCKED;
509 	return 0;
510 }
511 
512 /*
513  * Unlock and wake up any waiters.
514  */
515 void
516 cam_periph_unlock(struct cam_periph *periph)
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(periph);
525 }
526 
527 /*
528  * Map user virtual pointers into kernel virtual address space, so we can
529  * access the memory.  This won't work on physical pointers, for now it's
530  * up to the caller to check for that.  (XXX KDM -- should we do that here
531  * instead?)  This also only works for up to MAXPHYS memory.  Since we use
532  * buffers to map stuff in and out, we're limited to the buffer size.
533  */
534 int
535 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
536 {
537 	int numbufs, i;
538 	int flags[CAM_PERIPH_MAXMAPS];
539 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
540 	u_int32_t lengths[CAM_PERIPH_MAXMAPS];
541 	u_int32_t dirs[CAM_PERIPH_MAXMAPS];
542 
543 	switch(ccb->ccb_h.func_code) {
544 	case XPT_DEV_MATCH:
545 		if (ccb->cdm.match_buf_len == 0) {
546 			printf("cam_periph_mapmem: invalid match buffer "
547 			       "length 0\n");
548 			return(EINVAL);
549 		}
550 		if (ccb->cdm.pattern_buf_len > 0) {
551 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
552 			lengths[0] = ccb->cdm.pattern_buf_len;
553 			dirs[0] = CAM_DIR_OUT;
554 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
555 			lengths[1] = ccb->cdm.match_buf_len;
556 			dirs[1] = CAM_DIR_IN;
557 			numbufs = 2;
558 		} else {
559 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
560 			lengths[0] = ccb->cdm.match_buf_len;
561 			dirs[0] = CAM_DIR_IN;
562 			numbufs = 1;
563 		}
564 		break;
565 	case XPT_SCSI_IO:
566 	case XPT_CONT_TARGET_IO:
567 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
568 			return(0);
569 
570 		data_ptrs[0] = &ccb->csio.data_ptr;
571 		lengths[0] = ccb->csio.dxfer_len;
572 		dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
573 		numbufs = 1;
574 		break;
575 	default:
576 		return(EINVAL);
577 		break; /* NOTREACHED */
578 	}
579 
580 	/*
581 	 * Check the transfer length and permissions first, so we don't
582 	 * have to unmap any previously mapped buffers.
583 	 */
584 	for (i = 0; i < numbufs; i++) {
585 
586 		flags[i] = 0;
587 
588 		/*
589 		 * The userland data pointer passed in may not be page
590 		 * aligned.  vmapbuf() truncates the address to a page
591 		 * boundary, so if the address isn't page aligned, we'll
592 		 * need enough space for the given transfer length, plus
593 		 * whatever extra space is necessary to make it to the page
594 		 * boundary.
595 		 */
596 		if ((lengths[i] +
597 		    (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)) > DFLTPHYS){
598 			printf("cam_periph_mapmem: attempt to map %lu bytes, "
599 			       "which is greater than DFLTPHYS(%d)\n",
600 			       (long)(lengths[i] +
601 			       (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)),
602 			       DFLTPHYS);
603 			return(E2BIG);
604 		}
605 
606 		if (dirs[i] & CAM_DIR_OUT) {
607 			flags[i] = BIO_WRITE;
608 			if (!useracc(*data_ptrs[i], lengths[i],
609 				     VM_PROT_READ)) {
610 				printf("cam_periph_mapmem: error, "
611 					"address %p, length %lu isn't "
612 					"user accessible for READ\n",
613 					(void *)*data_ptrs[i],
614 					(u_long)lengths[i]);
615 				return(EACCES);
616 			}
617 		}
618 
619 		if (dirs[i] & CAM_DIR_IN) {
620 			flags[i] = BIO_READ;
621 			if (!useracc(*data_ptrs[i], lengths[i],
622 				     VM_PROT_WRITE)) {
623 				printf("cam_periph_mapmem: error, "
624 					"address %p, length %lu isn't "
625 					"user accessible for WRITE\n",
626 					(void *)*data_ptrs[i],
627 					(u_long)lengths[i]);
628 
629 				return(EACCES);
630 			}
631 		}
632 
633 	}
634 
635 	/* this keeps the current process from getting swapped */
636 	/*
637 	 * XXX KDM should I use P_NOSWAP instead?
638 	 */
639 	PHOLD(curproc);
640 
641 	for (i = 0; i < numbufs; i++) {
642 		/*
643 		 * Get the buffer.
644 		 */
645 		mapinfo->bp[i] = getpbuf(NULL);
646 
647 		/* save the buffer's data address */
648 		mapinfo->bp[i]->b_saveaddr = mapinfo->bp[i]->b_data;
649 
650 		/* put our pointer in the data slot */
651 		mapinfo->bp[i]->b_data = *data_ptrs[i];
652 
653 		/* set the transfer length, we know it's < DFLTPHYS */
654 		mapinfo->bp[i]->b_bufsize = lengths[i];
655 
656 		/* set the flags */
657 		mapinfo->bp[i]->b_flags = B_PHYS;
658 
659 		/* set the direction */
660 		mapinfo->bp[i]->b_iocmd = flags[i];
661 
662 		/* map the buffer into kernel memory */
663 		vmapbuf(mapinfo->bp[i]);
664 
665 		/* set our pointer to the new mapped area */
666 		*data_ptrs[i] = mapinfo->bp[i]->b_data;
667 
668 		mapinfo->num_bufs_used++;
669 	}
670 
671 	return(0);
672 }
673 
674 /*
675  * Unmap memory segments mapped into kernel virtual address space by
676  * cam_periph_mapmem().
677  */
678 void
679 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
680 {
681 	int numbufs, i;
682 	u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
683 
684 	if (mapinfo->num_bufs_used <= 0) {
685 		/* allow ourselves to be swapped once again */
686 		PRELE(curproc);
687 		return;
688 	}
689 
690 	switch (ccb->ccb_h.func_code) {
691 	case XPT_DEV_MATCH:
692 		numbufs = min(mapinfo->num_bufs_used, 2);
693 
694 		if (numbufs == 1) {
695 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
696 		} else {
697 			data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
698 			data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
699 		}
700 		break;
701 	case XPT_SCSI_IO:
702 	case XPT_CONT_TARGET_IO:
703 		data_ptrs[0] = &ccb->csio.data_ptr;
704 		numbufs = min(mapinfo->num_bufs_used, 1);
705 		break;
706 	default:
707 		/* allow ourselves to be swapped once again */
708 		PRELE(curproc);
709 		return;
710 		break; /* NOTREACHED */
711 	}
712 
713 	for (i = 0; i < numbufs; i++) {
714 		/* Set the user's pointer back to the original value */
715 		*data_ptrs[i] = mapinfo->bp[i]->b_saveaddr;
716 
717 		/* unmap the buffer */
718 		vunmapbuf(mapinfo->bp[i]);
719 
720 		/* clear the flags we set above */
721 		mapinfo->bp[i]->b_flags &= ~B_PHYS;
722 
723 		/* release the buffer */
724 		relpbuf(mapinfo->bp[i], NULL);
725 	}
726 
727 	/* allow ourselves to be swapped once again */
728 	PRELE(curproc);
729 }
730 
731 union ccb *
732 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
733 {
734 	struct ccb_hdr *ccb_h;
735 	int s;
736 
737 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdgetccb\n"));
738 
739 	s = splsoftcam();
740 
741 	while (SLIST_FIRST(&periph->ccb_list) == NULL) {
742 		if (periph->immediate_priority > priority)
743 			periph->immediate_priority = priority;
744 		xpt_schedule(periph, priority);
745 		if ((SLIST_FIRST(&periph->ccb_list) != NULL)
746 		 && (SLIST_FIRST(&periph->ccb_list)->pinfo.priority == priority))
747 			break;
748 		tsleep(&periph->ccb_list, PRIBIO, "cgticb", 0);
749 	}
750 
751 	ccb_h = SLIST_FIRST(&periph->ccb_list);
752 	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
753 	splx(s);
754 	return ((union ccb *)ccb_h);
755 }
756 
757 void
758 cam_periph_ccbwait(union ccb *ccb)
759 {
760 	int s;
761 
762 	s = splsoftcam();
763 	if ((ccb->ccb_h.pinfo.index != CAM_UNQUEUED_INDEX)
764 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG))
765 		tsleep(&ccb->ccb_h.cbfcnp, PRIBIO, "cbwait", 0);
766 
767 	splx(s);
768 }
769 
770 int
771 cam_periph_ioctl(struct cam_periph *periph, int cmd, caddr_t addr,
772 		 int (*error_routine)(union ccb *ccb,
773 				      cam_flags camflags,
774 				      u_int32_t sense_flags))
775 {
776 	union ccb 	     *ccb;
777 	int 		     error;
778 	int		     found;
779 
780 	error = found = 0;
781 
782 	switch(cmd){
783 	case CAMGETPASSTHRU:
784 		ccb = cam_periph_getccb(periph, /* priority */ 1);
785 		xpt_setup_ccb(&ccb->ccb_h,
786 			      ccb->ccb_h.path,
787 			      /*priority*/1);
788 		ccb->ccb_h.func_code = XPT_GDEVLIST;
789 
790 		/*
791 		 * Basically, the point of this is that we go through
792 		 * getting the list of devices, until we find a passthrough
793 		 * device.  In the current version of the CAM code, the
794 		 * only way to determine what type of device we're dealing
795 		 * with is by its name.
796 		 */
797 		while (found == 0) {
798 			ccb->cgdl.index = 0;
799 			ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
800 			while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
801 
802 				/* we want the next device in the list */
803 				xpt_action(ccb);
804 				if (strncmp(ccb->cgdl.periph_name,
805 				    "pass", 4) == 0){
806 					found = 1;
807 					break;
808 				}
809 			}
810 			if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
811 			    (found == 0)) {
812 				ccb->cgdl.periph_name[0] = '\0';
813 				ccb->cgdl.unit_number = 0;
814 				break;
815 			}
816 		}
817 
818 		/* copy the result back out */
819 		bcopy(ccb, addr, sizeof(union ccb));
820 
821 		/* and release the ccb */
822 		xpt_release_ccb(ccb);
823 
824 		break;
825 	default:
826 		error = ENOTTY;
827 		break;
828 	}
829 	return(error);
830 }
831 
832 int
833 cam_periph_runccb(union ccb *ccb,
834 		  int (*error_routine)(union ccb *ccb,
835 				       cam_flags camflags,
836 				       u_int32_t sense_flags),
837 		  cam_flags camflags, u_int32_t sense_flags,
838 		  struct devstat *ds)
839 {
840 	int error;
841 
842 	error = 0;
843 
844 	/*
845 	 * If the user has supplied a stats structure, and if we understand
846 	 * this particular type of ccb, record the transaction start.
847 	 */
848 	if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO))
849 		devstat_start_transaction(ds);
850 
851 	xpt_action(ccb);
852 
853 	do {
854 		cam_periph_ccbwait(ccb);
855 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
856 			error = 0;
857 		else if (error_routine != NULL)
858 			error = (*error_routine)(ccb, camflags, sense_flags);
859 		else
860 			error = 0;
861 
862 	} while (error == ERESTART);
863 
864 	if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
865 		cam_release_devq(ccb->ccb_h.path,
866 				 /* relsim_flags */0,
867 				 /* openings */0,
868 				 /* timeout */0,
869 				 /* getcount_only */ FALSE);
870 
871 	if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO))
872 		devstat_end_transaction(ds,
873 					ccb->csio.dxfer_len,
874 					ccb->csio.tag_action & 0xf,
875 					((ccb->ccb_h.flags & CAM_DIR_MASK) ==
876 					CAM_DIR_NONE) ?  DEVSTAT_NO_DATA :
877 					(ccb->ccb_h.flags & CAM_DIR_OUT) ?
878 					DEVSTAT_WRITE :
879 					DEVSTAT_READ);
880 
881 	return(error);
882 }
883 
884 void
885 cam_freeze_devq(struct cam_path *path)
886 {
887 	struct ccb_hdr ccb_h;
888 
889 	xpt_setup_ccb(&ccb_h, path, /*priority*/1);
890 	ccb_h.func_code = XPT_NOOP;
891 	ccb_h.flags = CAM_DEV_QFREEZE;
892 	xpt_action((union ccb *)&ccb_h);
893 }
894 
895 u_int32_t
896 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
897 		 u_int32_t openings, u_int32_t timeout,
898 		 int getcount_only)
899 {
900 	struct ccb_relsim crs;
901 
902 	xpt_setup_ccb(&crs.ccb_h, path,
903 		      /*priority*/1);
904 	crs.ccb_h.func_code = XPT_REL_SIMQ;
905 	crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
906 	crs.release_flags = relsim_flags;
907 	crs.openings = openings;
908 	crs.release_timeout = timeout;
909 	xpt_action((union ccb *)&crs);
910 	return (crs.qfrozen_cnt);
911 }
912 
913 #define saved_ccb_ptr ppriv_ptr0
914 static void
915 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
916 {
917 	union ccb      *saved_ccb;
918 	cam_status	status;
919 	int		frozen;
920 	int		sense;
921 	struct scsi_start_stop_unit *scsi_cmd;
922 	u_int32_t	relsim_flags, timeout;
923 	u_int32_t	qfrozen_cnt;
924 	int		xpt_done_ccb;
925 
926 	xpt_done_ccb = FALSE;
927 	status = done_ccb->ccb_h.status;
928 	frozen = (status & CAM_DEV_QFRZN) != 0;
929 	sense  = (status & CAM_AUTOSNS_VALID) != 0;
930 	status &= CAM_STATUS_MASK;
931 
932 	timeout = 0;
933 	relsim_flags = 0;
934 	saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
935 
936 	/*
937 	 * Unfreeze the queue once if it is already frozen..
938 	 */
939 	if (frozen != 0) {
940 		qfrozen_cnt = cam_release_devq(done_ccb->ccb_h.path,
941 					      /*relsim_flags*/0,
942 					      /*openings*/0,
943 					      /*timeout*/0,
944 					      /*getcount_only*/0);
945 	}
946 
947 	switch (status) {
948 	case CAM_REQ_CMP:
949 	{
950 		/*
951 		 * If we have successfully taken a device from the not
952 		 * ready to ready state, re-scan the device and re-get
953 		 * the inquiry information.  Many devices (mostly disks)
954 		 * don't properly report their inquiry information unless
955 		 * they are spun up.
956 		 *
957 		 * If we manually retrieved sense into a CCB and got
958 		 * something other than "NO SENSE" send the updated CCB
959 		 * back to the client via xpt_done() to be processed via
960 		 * the error recovery code again.
961 		 */
962 		if (done_ccb->ccb_h.func_code == XPT_SCSI_IO) {
963 			scsi_cmd = (struct scsi_start_stop_unit *)
964 					&done_ccb->csio.cdb_io.cdb_bytes;
965 
966 		 	if (scsi_cmd->opcode == START_STOP_UNIT)
967 				xpt_async(AC_INQ_CHANGED,
968 					  done_ccb->ccb_h.path, NULL);
969 			if (scsi_cmd->opcode == REQUEST_SENSE) {
970 				u_int sense_key;
971 
972 				sense_key = saved_ccb->csio.sense_data.flags;
973 				sense_key &= SSD_KEY;
974 				if (sense_key != SSD_KEY_NO_SENSE) {
975 					saved_ccb->ccb_h.flags |=
976 					    CAM_AUTOSNS_VALID;
977 					xpt_print_path(saved_ccb->ccb_h.path);
978 					printf("Recovered Sense\n");
979 #if 0
980 					scsi_sense_print(&saved_ccb->csio);
981 #endif
982 					cam_error_print(saved_ccb, CAM_ESF_ALL,
983 							CAM_EPF_ALL);
984 					xpt_done_ccb = TRUE;
985 				}
986 			}
987 		}
988 		bcopy(done_ccb->ccb_h.saved_ccb_ptr, done_ccb,
989 		      sizeof(union ccb));
990 
991 		periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
992 
993 		if (xpt_done_ccb == FALSE)
994 			xpt_action(done_ccb);
995 
996 		break;
997 	}
998 	case CAM_SCSI_STATUS_ERROR:
999 		scsi_cmd = (struct scsi_start_stop_unit *)
1000 				&done_ccb->csio.cdb_io.cdb_bytes;
1001 		if (sense != 0) {
1002 			struct scsi_sense_data *sense;
1003 			int    error_code, sense_key, asc, ascq;
1004 
1005 			sense = &done_ccb->csio.sense_data;
1006 			scsi_extract_sense(sense, &error_code,
1007 					   &sense_key, &asc, &ascq);
1008 
1009 			/*
1010 	 		 * If the error is "invalid field in CDB",
1011 			 * and the load/eject flag is set, turn the
1012 			 * flag off and try again.  This is just in
1013 			 * case the drive in question barfs on the
1014 			 * load eject flag.  The CAM code should set
1015 			 * the load/eject flag by default for
1016 			 * removable media.
1017 			 */
1018 
1019 			/* XXX KDM
1020 			 * Should we check to see what the specific
1021 			 * scsi status is??  Or does it not matter
1022 			 * since we already know that there was an
1023 			 * error, and we know what the specific
1024 			 * error code was, and we know what the
1025 			 * opcode is..
1026 			 */
1027 			if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1028 			    ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1029 			     (asc == 0x24) && (ascq == 0x00) &&
1030 			     (done_ccb->ccb_h.retry_count > 0)) {
1031 
1032 				scsi_cmd->how &= ~SSS_LOEJ;
1033 
1034 				xpt_action(done_ccb);
1035 
1036 			} else if (done_ccb->ccb_h.retry_count > 1) {
1037 				/*
1038 				 * In this case, the error recovery
1039 				 * command failed, but we've got
1040 				 * some retries left on it.  Give
1041 				 * it another try.
1042 				 */
1043 
1044 				/* set the timeout to .5 sec */
1045 				relsim_flags =
1046 					RELSIM_RELEASE_AFTER_TIMEOUT;
1047 				timeout = 500;
1048 
1049 				xpt_action(done_ccb);
1050 
1051 				break;
1052 
1053 			} else {
1054 				/*
1055 				 * Perform the final retry with the original
1056 				 * CCB so that final error processing is
1057 				 * performed by the owner of the CCB.
1058 				 */
1059 				bcopy(done_ccb->ccb_h.saved_ccb_ptr,
1060 				      done_ccb, sizeof(union ccb));
1061 
1062 				periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1063 
1064 				xpt_action(done_ccb);
1065 			}
1066 		} else {
1067 			/*
1068 			 * Eh??  The command failed, but we don't
1069 			 * have any sense.  What's up with that?
1070 			 * Fire the CCB again to return it to the
1071 			 * caller.
1072 			 */
1073 			bcopy(done_ccb->ccb_h.saved_ccb_ptr,
1074 			      done_ccb, sizeof(union ccb));
1075 
1076 			periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1077 
1078 			xpt_action(done_ccb);
1079 
1080 		}
1081 		break;
1082 	default:
1083 		bcopy(done_ccb->ccb_h.saved_ccb_ptr, done_ccb,
1084 		      sizeof(union ccb));
1085 
1086 		periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1087 
1088 		xpt_action(done_ccb);
1089 
1090 		break;
1091 	}
1092 
1093 	/* decrement the retry count */
1094 	/*
1095 	 * XXX This isn't appropriate in all cases.  Restructure,
1096 	 *     so that the retry count is only decremented on an
1097 	 *     actual retry.  Remeber that the orignal ccb had its
1098 	 *     retry count dropped before entering recovery, so
1099 	 *     doing it again is a bug.
1100 	 */
1101 	if (done_ccb->ccb_h.retry_count > 0)
1102 		done_ccb->ccb_h.retry_count--;
1103 
1104 	qfrozen_cnt = cam_release_devq(done_ccb->ccb_h.path,
1105 				      /*relsim_flags*/relsim_flags,
1106 				      /*openings*/0,
1107 				      /*timeout*/timeout,
1108 				      /*getcount_only*/0);
1109 	if (xpt_done_ccb == TRUE)
1110 		(*done_ccb->ccb_h.cbfcnp)(periph, done_ccb);
1111 }
1112 
1113 /*
1114  * Generic Async Event handler.  Peripheral drivers usually
1115  * filter out the events that require personal attention,
1116  * and leave the rest to this function.
1117  */
1118 void
1119 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1120 		 struct cam_path *path, void *arg)
1121 {
1122 	switch (code) {
1123 	case AC_LOST_DEVICE:
1124 		cam_periph_invalidate(periph);
1125 		break;
1126 	case AC_SENT_BDR:
1127 	case AC_BUS_RESET:
1128 	{
1129 		cam_periph_bus_settle(periph, scsi_delay);
1130 		break;
1131 	}
1132 	default:
1133 		break;
1134 	}
1135 }
1136 
1137 void
1138 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1139 {
1140 	struct ccb_getdevstats cgds;
1141 
1142 	xpt_setup_ccb(&cgds.ccb_h, periph->path, /*priority*/1);
1143 	cgds.ccb_h.func_code = XPT_GDEV_STATS;
1144 	xpt_action((union ccb *)&cgds);
1145 	cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1146 }
1147 
1148 void
1149 cam_periph_freeze_after_event(struct cam_periph *periph,
1150 			      struct timeval* event_time, u_int duration_ms)
1151 {
1152 	struct timeval delta;
1153 	struct timeval duration_tv;
1154 	int s;
1155 
1156 	s = splclock();
1157 	microtime(&delta);
1158 	splx(s);
1159 	timevalsub(&delta, event_time);
1160 	duration_tv.tv_sec = duration_ms / 1000;
1161 	duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1162 	if (timevalcmp(&delta, &duration_tv, <)) {
1163 		timevalsub(&duration_tv, &delta);
1164 
1165 		duration_ms = duration_tv.tv_sec * 1000;
1166 		duration_ms += duration_tv.tv_usec / 1000;
1167 		cam_freeze_devq(periph->path);
1168 		cam_release_devq(periph->path,
1169 				RELSIM_RELEASE_AFTER_TIMEOUT,
1170 				/*reduction*/0,
1171 				/*timeout*/duration_ms,
1172 				/*getcount_only*/0);
1173 	}
1174 
1175 }
1176 
1177 static int
1178 camperiphscsistatuserror(union ccb *ccb, cam_flags camflags,
1179 			 u_int32_t sense_flags, union ccb *save_ccb,
1180 			 int *openings, u_int32_t *relsim_flags,
1181 			 u_int32_t *timeout)
1182 {
1183 	int error;
1184 
1185 	switch (ccb->csio.scsi_status) {
1186 	case SCSI_STATUS_OK:
1187 	case SCSI_STATUS_COND_MET:
1188 	case SCSI_STATUS_INTERMED:
1189 	case SCSI_STATUS_INTERMED_COND_MET:
1190 		error = 0;
1191 		break;
1192 	case SCSI_STATUS_CMD_TERMINATED:
1193 	case SCSI_STATUS_CHECK_COND:
1194 		error = camperiphscsisenseerror(ccb,
1195 					        camflags,
1196 					        sense_flags,
1197 					        save_ccb,
1198 					        openings,
1199 					        relsim_flags,
1200 					        timeout);
1201 		break;
1202 	case SCSI_STATUS_QUEUE_FULL:
1203 	{
1204 		/* no decrement */
1205 		struct ccb_getdevstats cgds;
1206 
1207 		/*
1208 		 * First off, find out what the current
1209 		 * transaction counts are.
1210 		 */
1211 		xpt_setup_ccb(&cgds.ccb_h,
1212 			      ccb->ccb_h.path,
1213 			      /*priority*/1);
1214 		cgds.ccb_h.func_code = XPT_GDEV_STATS;
1215 		xpt_action((union ccb *)&cgds);
1216 
1217 		/*
1218 		 * If we were the only transaction active, treat
1219 		 * the QUEUE FULL as if it were a BUSY condition.
1220 		 */
1221 		if (cgds.dev_active != 0) {
1222 			int total_openings;
1223 
1224 			/*
1225 		 	 * Reduce the number of openings to
1226 			 * be 1 less than the amount it took
1227 			 * to get a queue full bounded by the
1228 			 * minimum allowed tag count for this
1229 			 * device.
1230 		 	 */
1231 			total_openings = cgds.dev_active + cgds.dev_openings;
1232 			*openings = cgds.dev_active;
1233 			if (*openings < cgds.mintags)
1234 				*openings = cgds.mintags;
1235 			if (*openings < total_openings)
1236 				*relsim_flags = RELSIM_ADJUST_OPENINGS;
1237 			else {
1238 				/*
1239 				 * Some devices report queue full for
1240 				 * temporary resource shortages.  For
1241 				 * this reason, we allow a minimum
1242 				 * tag count to be entered via a
1243 				 * quirk entry to prevent the queue
1244 				 * count on these devices from falling
1245 				 * to a pessimisticly low value.  We
1246 				 * still wait for the next successful
1247 				 * completion, however, before queueing
1248 				 * more transactions to the device.
1249 				 */
1250 				*relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1251 			}
1252 			*timeout = 0;
1253 			error = ERESTART;
1254 			if (bootverbose) {
1255 				xpt_print_path(ccb->ccb_h.path);
1256 				printf("Queue Full\n");
1257 			}
1258 			break;
1259 		}
1260 		/* FALLTHROUGH */
1261 	}
1262 	case SCSI_STATUS_BUSY:
1263 		/*
1264 		 * Restart the queue after either another
1265 		 * command completes or a 1 second timeout.
1266 		 */
1267 		if (bootverbose) {
1268 			xpt_print_path(ccb->ccb_h.path);
1269 			printf("Device Busy\n");
1270 		}
1271 	 	if (ccb->ccb_h.retry_count > 0) {
1272 	 		ccb->ccb_h.retry_count--;
1273 			error = ERESTART;
1274 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1275 				      | RELSIM_RELEASE_AFTER_CMDCMPLT;
1276 			*timeout = 1000;
1277 		} else {
1278 			error = EIO;
1279 		}
1280 		break;
1281 	case SCSI_STATUS_RESERV_CONFLICT:
1282 		xpt_print_path(ccb->ccb_h.path);
1283 		printf("Reservation Conflict\n");
1284 		error = EIO;
1285 		break;
1286 	default:
1287 		xpt_print_path(ccb->ccb_h.path);
1288 		printf("SCSI Status 0x%x\n", ccb->csio.scsi_status);
1289 		error = EIO;
1290 		break;
1291 	}
1292 	return (error);
1293 }
1294 
1295 static int
1296 camperiphscsisenseerror(union ccb *ccb, cam_flags camflags,
1297 			u_int32_t sense_flags, union ccb *save_ccb,
1298 		       int *openings, u_int32_t *relsim_flags,
1299 		       u_int32_t *timeout)
1300 {
1301 	struct cam_periph *periph;
1302 	int error;
1303 
1304 	periph = xpt_path_periph(ccb->ccb_h.path);
1305 	if (periph->flags & CAM_PERIPH_RECOVERY_INPROG) {
1306 
1307 		/*
1308 		 * If error recovery is already in progress, don't attempt
1309 		 * to process this error, but requeue it unconditionally
1310 		 * and attempt to process it once error recovery has
1311 		 * completed.  This failed command is probably related to
1312 		 * the error that caused the currently active error recovery
1313 		 * action so our  current recovery efforts should also
1314 		 * address this command.  Be aware that the error recovery
1315 		 * code assumes that only one recovery action is in progress
1316 		 * on a particular peripheral instance at any given time
1317 		 * (e.g. only one saved CCB for error recovery) so it is
1318 		 * imperitive that we don't violate this assumption.
1319 		 */
1320 		error = ERESTART;
1321 	} else {
1322 		scsi_sense_action err_action;
1323 		struct ccb_getdev cgd;
1324 		const char *action_string;
1325 		union ccb* print_ccb;
1326 
1327 		/* A description of the error recovery action performed */
1328 		action_string = NULL;
1329 
1330 		/*
1331 		 * The location of the orignal ccb
1332 		 * for sense printing purposes.
1333 		 */
1334 		print_ccb = ccb;
1335 
1336 		/*
1337 		 * Grab the inquiry data for this device.
1338 		 */
1339 		xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, /*priority*/ 1);
1340 		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1341 		xpt_action((union ccb *)&cgd);
1342 
1343 		if ((ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0)
1344 			err_action = scsi_error_action(&ccb->csio,
1345 						       &cgd.inq_data,
1346 						       sense_flags);
1347 		else if ((ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)
1348 			err_action = SS_REQSENSE;
1349 		else
1350 			err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1351 
1352 		error = err_action & SS_ERRMASK;
1353 
1354 		/*
1355 		 * If the recovery action will consume a retry,
1356 		 * make sure we actually have retries available.
1357 		 */
1358 		if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1359 		 	if (ccb->ccb_h.retry_count > 0)
1360 		 		ccb->ccb_h.retry_count--;
1361 			else {
1362 				action_string = "Retries Exhausted";
1363 				goto sense_error_done;
1364 			}
1365 		}
1366 
1367 		if ((err_action & SS_MASK) >= SS_START) {
1368 			/*
1369 			 * Do common portions of commands that
1370 			 * use recovery CCBs.
1371 			 */
1372 			if (save_ccb == NULL) {
1373 				action_string = "No recovery CCB supplied";
1374 				goto sense_error_done;
1375 			}
1376 			bcopy(ccb, save_ccb, sizeof(*save_ccb));
1377 			print_ccb = save_ccb;
1378 			periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1379 		}
1380 
1381 		switch (err_action & SS_MASK) {
1382 		case SS_NOP:
1383 			action_string = "No Recovery Action Needed";
1384 			error = 0;
1385 			break;
1386 		case SS_RETRY:
1387 			action_string = "Retrying Command (per Sense Data)";
1388 			error = ERESTART;
1389 			break;
1390 		case SS_FAIL:
1391 			action_string = "Unretryable error";
1392 			break;
1393 		case SS_START:
1394 		{
1395 			int le;
1396 
1397 			/*
1398 			 * Send a start unit command to the device, and
1399 			 * then retry the command.
1400 			 */
1401 			action_string = "Attempting to Start Unit";
1402 
1403 			/*
1404 			 * Check for removable media and set
1405 			 * load/eject flag appropriately.
1406 			 */
1407 			if (SID_IS_REMOVABLE(&cgd.inq_data))
1408 				le = TRUE;
1409 			else
1410 				le = FALSE;
1411 
1412 			scsi_start_stop(&ccb->csio,
1413 					/*retries*/1,
1414 					camperiphdone,
1415 					MSG_SIMPLE_Q_TAG,
1416 					/*start*/TRUE,
1417 					/*load/eject*/le,
1418 					/*immediate*/FALSE,
1419 					SSD_FULL_SIZE,
1420 					/*timeout*/50000);
1421 			break;
1422 		}
1423 		case SS_TUR:
1424 		{
1425 			/*
1426 			 * Send a Test Unit Ready to the device.
1427 			 * If the 'many' flag is set, we send 120
1428 			 * test unit ready commands, one every half
1429 			 * second.  Otherwise, we just send one TUR.
1430 			 * We only want to do this if the retry
1431 			 * count has not been exhausted.
1432 			 */
1433 			int retries;
1434 
1435 			if ((err_action & SSQ_MANY) != 0) {
1436 				action_string = "Polling device for readiness";
1437 				retries = 120;
1438 			} else {
1439 				action_string = "Testing device for readiness";
1440 				retries = 1;
1441 			}
1442 			scsi_test_unit_ready(&ccb->csio,
1443 					     retries,
1444 					     camperiphdone,
1445 					     MSG_SIMPLE_Q_TAG,
1446 					     SSD_FULL_SIZE,
1447 					     /*timeout*/5000);
1448 
1449 			/*
1450 			 * Accomplish our 500ms delay by deferring
1451 			 * the release of our device queue appropriately.
1452 			 */
1453 			*relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1454 			*timeout = 500;
1455 			break;
1456 		}
1457 		case SS_REQSENSE:
1458 		{
1459 			/*
1460 			 * Send a Request Sense to the device.  We
1461 			 * assume that we are in a contingent allegiance
1462 			 * condition so we do not tag this request.
1463 			 */
1464 			scsi_request_sense(&ccb->csio, /*retries*/1,
1465 					   camperiphdone,
1466 					   &save_ccb->csio.sense_data,
1467 					   sizeof(save_ccb->csio.sense_data),
1468 					   CAM_TAG_ACTION_NONE,
1469 					   /*sense_len*/SSD_FULL_SIZE,
1470 					   /*timeout*/5000);
1471 			break;
1472 		}
1473 		default:
1474 			panic("Unhandled error action %x\n", err_action);
1475 		}
1476 
1477 		if ((err_action & SS_MASK) >= SS_START) {
1478 			/*
1479 			 * Drop the priority to 0 so that the recovery
1480 			 * CCB is the first to execute.  Freeze the queue
1481 			 * after this command is sent so that we can
1482 			 * restore the old csio and have it queued in
1483 			 * the proper order before we release normal
1484 			 * transactions to the device.
1485 			 */
1486 			ccb->ccb_h.pinfo.priority = 0;
1487 			ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1488 			ccb->ccb_h.saved_ccb_ptr = save_ccb;
1489 			error = ERESTART;
1490 		}
1491 
1492 sense_error_done:
1493 		if ((err_action & SSQ_PRINT_SENSE) != 0
1494 		 && (ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0) {
1495 			cam_error_print(print_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1496 			xpt_print_path(ccb->ccb_h.path);
1497 			if (bootverbose)
1498 				scsi_sense_print(&print_ccb->csio);
1499 			printf("%s\n", action_string);
1500 		}
1501 	}
1502 	return (error);
1503 }
1504 
1505 /*
1506  * Generic error handler.  Peripheral drivers usually filter
1507  * out the errors that they handle in a unique mannor, then
1508  * call this function.
1509  */
1510 int
1511 cam_periph_error(union ccb *ccb, cam_flags camflags,
1512 		 u_int32_t sense_flags, union ccb *save_ccb)
1513 {
1514 	const char *action_string;
1515 	cam_status  status;
1516 	int	    frozen;
1517 	int	    error, printed = 0;
1518 	int         openings;
1519 	u_int32_t   relsim_flags;
1520 	u_int32_t   timeout;
1521 
1522 	action_string = NULL;
1523 	status = ccb->ccb_h.status;
1524 	frozen = (status & CAM_DEV_QFRZN) != 0;
1525 	status &= CAM_STATUS_MASK;
1526 	openings = relsim_flags = 0;
1527 
1528 	switch (status) {
1529 	case CAM_REQ_CMP:
1530 		error = 0;
1531 		break;
1532 	case CAM_SCSI_STATUS_ERROR:
1533 		error = camperiphscsistatuserror(ccb,
1534 						 camflags,
1535 						 sense_flags,
1536 						 save_ccb,
1537 						 &openings,
1538 						 &relsim_flags,
1539 						 &timeout);
1540 		break;
1541 	case CAM_AUTOSENSE_FAIL:
1542 		xpt_print_path(ccb->ccb_h.path);
1543 		printf("AutoSense Failed\n");
1544 		error = EIO;	/* we have to kill the command */
1545 		break;
1546 	case CAM_REQ_CMP_ERR:
1547 		if (bootverbose && printed == 0) {
1548 			xpt_print_path(ccb->ccb_h.path);
1549 			printf("Request completed with CAM_REQ_CMP_ERR\n");
1550 			printed++;
1551 		}
1552 	case CAM_CMD_TIMEOUT:
1553 		if (bootverbose && printed == 0) {
1554 			xpt_print_path(ccb->ccb_h.path);
1555 			printf("Command timed out\n");
1556 			printed++;
1557 		}
1558 	case CAM_UNEXP_BUSFREE:
1559 		if (bootverbose && printed == 0) {
1560 			xpt_print_path(ccb->ccb_h.path);
1561 			printf("Unexpected Bus Free\n");
1562 			printed++;
1563 		}
1564 	case CAM_UNCOR_PARITY:
1565 		if (bootverbose && printed == 0) {
1566 			xpt_print_path(ccb->ccb_h.path);
1567 			printf("Uncorrected Parity Error\n");
1568 			printed++;
1569 		}
1570 	case CAM_DATA_RUN_ERR:
1571 		if (bootverbose && printed == 0) {
1572 			xpt_print_path(ccb->ccb_h.path);
1573 			printf("Data Overrun\n");
1574 			printed++;
1575 		}
1576 		error = EIO;	/* we have to kill the command */
1577 		/* decrement the number of retries */
1578 		if (ccb->ccb_h.retry_count > 0) {
1579 			ccb->ccb_h.retry_count--;
1580 			error = ERESTART;
1581 		} else {
1582 			action_string = "Retries Exausted";
1583 			error = EIO;
1584 		}
1585 		break;
1586 	case CAM_UA_ABORT:
1587 	case CAM_UA_TERMIO:
1588 	case CAM_MSG_REJECT_REC:
1589 		/* XXX Don't know that these are correct */
1590 		error = EIO;
1591 		break;
1592 	case CAM_SEL_TIMEOUT:
1593 	{
1594 		struct cam_path *newpath;
1595 
1596 		if ((camflags & CAM_RETRY_SELTO) != 0) {
1597 			if (ccb->ccb_h.retry_count > 0) {
1598 
1599 				ccb->ccb_h.retry_count--;
1600 				error = ERESTART;
1601 				if (bootverbose && printed == 0) {
1602 					xpt_print_path(ccb->ccb_h.path);
1603 					printf("Selection Timeout\n");
1604 					printed++;
1605 				}
1606 
1607 				/*
1608 				 * Wait a second to give the device
1609 				 * time to recover before we try again.
1610 				 */
1611 				relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1612 				timeout = 1000;
1613 				break;
1614 			}
1615 		}
1616 		error = ENXIO;
1617 		/* Should we do more if we can't create the path?? */
1618 		if (xpt_create_path(&newpath, xpt_path_periph(ccb->ccb_h.path),
1619 				    xpt_path_path_id(ccb->ccb_h.path),
1620 				    xpt_path_target_id(ccb->ccb_h.path),
1621 				    CAM_LUN_WILDCARD) != CAM_REQ_CMP)
1622 			break;
1623 
1624 		/*
1625 		 * Let peripheral drivers know that this device has gone
1626 		 * away.
1627 		 */
1628 		xpt_async(AC_LOST_DEVICE, newpath, NULL);
1629 		xpt_free_path(newpath);
1630 		break;
1631 	}
1632 	case CAM_REQ_INVALID:
1633 	case CAM_PATH_INVALID:
1634 	case CAM_DEV_NOT_THERE:
1635 	case CAM_NO_HBA:
1636 	case CAM_PROVIDE_FAIL:
1637 	case CAM_REQ_TOO_BIG:
1638 		error = EINVAL;
1639 		break;
1640 	case CAM_SCSI_BUS_RESET:
1641 	case CAM_BDR_SENT:
1642 		/*
1643 		 * Commands that repeatedly timeout and cause these
1644 		 * kinds of error recovery actions, should return
1645 		 * CAM_CMD_TIMEOUT, which allows us to safely assume
1646 		 * that this command was an innocent bystander to
1647 		 * these events and should be unconditionally
1648 		 * retried.
1649 		 */
1650 		if (bootverbose && printed == 0) {
1651 			xpt_print_path(ccb->ccb_h.path);
1652 			if (status == CAM_BDR_SENT)
1653 				printf("Bus Device Reset sent\n");
1654 			else
1655 				printf("Bus Reset issued\n");
1656 			printed++;
1657 		}
1658 		/* FALLTHROUGH */
1659 	case CAM_REQUEUE_REQ:
1660 		/* Unconditional requeue */
1661 		error = ERESTART;
1662 		if (bootverbose && printed == 0) {
1663 			xpt_print_path(ccb->ccb_h.path);
1664 			printf("Request Requeued\n");
1665 			printed++;
1666 		}
1667 		break;
1668 	case CAM_RESRC_UNAVAIL:
1669 	case CAM_BUSY:
1670 		/* timeout??? */
1671 	default:
1672 		/* decrement the number of retries */
1673 		if (ccb->ccb_h.retry_count > 0) {
1674 			ccb->ccb_h.retry_count--;
1675 			error = ERESTART;
1676 			if (bootverbose && printed == 0) {
1677 				xpt_print_path(ccb->ccb_h.path);
1678 				printf("CAM Status 0x%x\n", status);
1679 				printed++;
1680 			}
1681 		} else {
1682 			error = EIO;
1683 			action_string = "Retries Exhausted";
1684 		}
1685 		break;
1686 	}
1687 
1688 	/* Attempt a retry */
1689 	if (error == ERESTART || error == 0) {
1690 		if (frozen != 0)
1691 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1692 
1693 		if (error == ERESTART) {
1694 			action_string = "Retrying Command";
1695 			xpt_action(ccb);
1696 		}
1697 
1698 		if (frozen != 0)
1699 			cam_release_devq(ccb->ccb_h.path,
1700 					 relsim_flags,
1701 					 openings,
1702 					 timeout,
1703 					 /*getcount_only*/0);
1704 	}
1705 
1706 	/*
1707 	 * If we have and error and are booting verbosely, whine
1708 	 * *unless* this was a non-retryable selection timeout.
1709 	 */
1710 	if (error != 0 && bootverbose &&
1711 	    !(status == CAM_SEL_TIMEOUT && (camflags & CAM_RETRY_SELTO) == 0)) {
1712 
1713 
1714 		if (action_string == NULL)
1715 			action_string = "Unretryable Error";
1716 		if (error != ERESTART) {
1717 			xpt_print_path(ccb->ccb_h.path);
1718 			printf("error %d\n", error);
1719 		}
1720 		xpt_print_path(ccb->ccb_h.path);
1721 		printf("%s\n", action_string);
1722 	}
1723 
1724 	return (error);
1725 }
1726