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