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