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