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