2ed4aafae315dc91edf7a615d7f33e47e39c31d8
[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.20 2007/05/13 22:25:41 swildner 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                         kprintf("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 = kmalloc(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                 kfree(periph, M_DEVBUF);
179         case 0:
180                 /* No cleanup to perform. */
181                 break;
182         default:
183                 panic("cam_periph_alloc: Unknown 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                                 kprintf("Duplicate Wired Device entry!\n");
275                                 xpt_print_path(periph->path);
276                                 kprintf("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         ksnprintf(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                 kprintf("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                 kprintf("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         kfree(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                         kprintf("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                         kprintf("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                                 kprintf("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                                 kprintf("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 original user pointer */
591                 mapinfo->saved_ptrs[i] = *data_ptrs[i];
592
593                 /* set the flags */
594                 mapinfo->bp[i]->b_cmd = cmd[i];
595
596                 /* map the user buffer into kernel memory */
597                 if (vmapbuf(mapinfo->bp[i], *data_ptrs[i], lengths[i]) < 0) {
598                         kprintf("cam_periph_mapmem: error, "
599                                 "address %p, length %lu isn't "
600                                 "user accessible any more\n",
601                                 (void *)*data_ptrs[i],
602                                 (u_long)lengths[i]);
603                         for (j = 0; j < i; ++j) {
604                                 *data_ptrs[j] = mapinfo->saved_ptrs[j];
605                                 vunmapbuf(mapinfo->bp[j]);
606                                 relpbuf(mapinfo->bp[j], NULL);
607                         }
608                         mapinfo->num_bufs_used -= i;
609                         return(EACCES);
610                 }
611
612                 /* set our pointer to the new mapped area */
613                 *data_ptrs[i] = mapinfo->bp[i]->b_data;
614
615                 mapinfo->num_bufs_used++;
616         }
617
618         return(0);
619 }
620
621 /*
622  * Unmap memory segments mapped into kernel virtual address space by
623  * cam_periph_mapmem().
624  */
625 void
626 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
627 {
628         int numbufs, i;
629         u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
630
631         if (mapinfo->num_bufs_used <= 0) {
632                 /* allow ourselves to be swapped once again */
633                 return;
634         }
635
636         switch (ccb->ccb_h.func_code) {
637         case XPT_DEV_MATCH:
638                 numbufs = min(mapinfo->num_bufs_used, 2);
639
640                 if (numbufs == 1) {
641                         data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
642                 } else {
643                         data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
644                         data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
645                 }
646                 break;
647         case XPT_SCSI_IO:
648         case XPT_CONT_TARGET_IO:
649                 data_ptrs[0] = &ccb->csio.data_ptr;
650                 numbufs = min(mapinfo->num_bufs_used, 1);
651                 break;
652         default:
653                 /* allow ourselves to be swapped once again */
654                 return;
655                 break; /* NOTREACHED */ 
656         }
657
658         for (i = 0; i < numbufs; i++) {
659                 /* Set the user's pointer back to the original value */
660                 *data_ptrs[i] = mapinfo->saved_ptrs[i];
661
662                 /* unmap the buffer */
663                 vunmapbuf(mapinfo->bp[i]);
664
665                 /* release the buffer */
666                 relpbuf(mapinfo->bp[i], NULL);
667         }
668
669         /* allow ourselves to be swapped once again */
670 }
671
672 union ccb *
673 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
674 {
675         struct ccb_hdr *ccb_h;
676
677         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("entering cdgetccb\n"));
678
679         crit_enter();
680         
681         while (periph->ccb_list.slh_first == NULL) {
682                 if (periph->immediate_priority > priority)
683                         periph->immediate_priority = priority;
684                 xpt_schedule(periph, priority);
685                 if ((periph->ccb_list.slh_first != NULL)
686                  && (periph->ccb_list.slh_first->pinfo.priority == priority))
687                         break;
688                 tsleep(&periph->ccb_list, 0, "cgticb", 0);
689         }
690
691         ccb_h = periph->ccb_list.slh_first;
692         SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
693         crit_exit();
694         return ((union ccb *)ccb_h);
695 }
696
697 void
698 cam_periph_ccbwait(union ccb *ccb)
699 {
700         crit_enter();
701         if ((ccb->ccb_h.pinfo.index != CAM_UNQUEUED_INDEX)
702          || ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG))
703                 tsleep(&ccb->ccb_h.cbfcnp, 0, "cbwait", 0);
704         crit_exit();
705 }
706
707 int
708 cam_periph_ioctl(struct cam_periph *periph, int cmd, caddr_t addr,
709                  int (*error_routine)(union ccb *ccb, 
710                                       cam_flags camflags,
711                                       u_int32_t sense_flags))
712 {
713         union ccb            *ccb;
714         int                  error;
715         int                  found;
716
717         error = found = 0;
718
719         switch(cmd){
720         case CAMGETPASSTHRU:
721                 ccb = cam_periph_getccb(periph, /* priority */ 1);
722                 xpt_setup_ccb(&ccb->ccb_h,
723                               ccb->ccb_h.path,
724                               /*priority*/1);
725                 ccb->ccb_h.func_code = XPT_GDEVLIST;
726
727                 /*
728                  * Basically, the point of this is that we go through
729                  * getting the list of devices, until we find a passthrough
730                  * device.  In the current version of the CAM code, the
731                  * only way to determine what type of device we're dealing
732                  * with is by its name.
733                  */
734                 while (found == 0) {
735                         ccb->cgdl.index = 0;
736                         ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
737                         while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
738
739                                 /* we want the next device in the list */
740                                 xpt_action(ccb);
741                                 if (strncmp(ccb->cgdl.periph_name, 
742                                     "pass", 4) == 0){
743                                         found = 1;
744                                         break;
745                                 }
746                         }
747                         if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
748                             (found == 0)) {
749                                 ccb->cgdl.periph_name[0] = '\0';
750                                 ccb->cgdl.unit_number = 0;
751                                 break;
752                         }
753                 }
754
755                 /* copy the result back out */  
756                 bcopy(ccb, addr, sizeof(union ccb));
757
758                 /* and release the ccb */
759                 xpt_release_ccb(ccb);
760
761                 break;
762         default:
763                 error = ENOTTY;
764                 break;
765         }
766         return(error);
767 }
768
769 int
770 cam_periph_runccb(union ccb *ccb,
771                   int (*error_routine)(union ccb *ccb,
772                                        cam_flags camflags,
773                                        u_int32_t sense_flags),
774                   cam_flags camflags, u_int32_t sense_flags,
775                   struct devstat *ds)
776 {
777         int error;
778  
779         error = 0;
780         
781         /*
782          * If the user has supplied a stats structure, and if we understand
783          * this particular type of ccb, record the transaction start.
784          */
785         if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO))
786                 devstat_start_transaction(ds);
787
788         xpt_action(ccb);
789  
790         do {
791                 cam_periph_ccbwait(ccb);
792                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
793                         error = 0;
794                 else if (error_routine != NULL)
795                         error = (*error_routine)(ccb, camflags, sense_flags);
796                 else
797                         error = 0;
798
799         } while (error == ERESTART);
800           
801         if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) 
802                 cam_release_devq(ccb->ccb_h.path,
803                                  /* relsim_flags */0,
804                                  /* openings */0,
805                                  /* timeout */0,
806                                  /* getcount_only */ FALSE);
807
808         if ((ds != NULL) && (ccb->ccb_h.func_code == XPT_SCSI_IO))
809                 devstat_end_transaction(ds,
810                                         ccb->csio.dxfer_len,
811                                         ccb->csio.tag_action & 0xf,
812                                         ((ccb->ccb_h.flags & CAM_DIR_MASK) ==
813                                         CAM_DIR_NONE) ?  DEVSTAT_NO_DATA : 
814                                         (ccb->ccb_h.flags & CAM_DIR_OUT) ?
815                                         DEVSTAT_WRITE : 
816                                         DEVSTAT_READ);
817
818         return(error);
819 }
820
821 void
822 cam_freeze_devq(struct cam_path *path)
823 {
824         struct ccb_hdr ccb_h;
825
826         xpt_setup_ccb(&ccb_h, path, /*priority*/1);
827         ccb_h.func_code = XPT_NOOP;
828         ccb_h.flags = CAM_DEV_QFREEZE;
829         xpt_action((union ccb *)&ccb_h);
830 }
831
832 u_int32_t
833 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
834                  u_int32_t openings, u_int32_t timeout,
835                  int getcount_only)
836 {
837         struct ccb_relsim crs;
838
839         xpt_setup_ccb(&crs.ccb_h, path,
840                       /*priority*/1);
841         crs.ccb_h.func_code = XPT_REL_SIMQ;
842         crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
843         crs.release_flags = relsim_flags;
844         crs.openings = openings;
845         crs.release_timeout = timeout;
846         xpt_action((union ccb *)&crs);
847         return (crs.qfrozen_cnt);
848 }
849
850 #define saved_ccb_ptr ppriv_ptr0
851 static void
852 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
853 {
854         cam_status      status;
855         int             frozen;
856         int             sense;
857         struct scsi_start_stop_unit *scsi_cmd;
858         u_int32_t       relsim_flags, timeout;
859         u_int32_t       qfrozen_cnt;
860
861         status = done_ccb->ccb_h.status;
862         frozen = (status & CAM_DEV_QFRZN) != 0;
863         sense  = (status & CAM_AUTOSNS_VALID) != 0;
864         status &= CAM_STATUS_MASK;
865
866         timeout = 0;
867         relsim_flags = 0;
868
869         /* 
870          * Unfreeze the queue once if it is already frozen..
871          */
872         if (frozen != 0) {
873                 qfrozen_cnt = cam_release_devq(done_ccb->ccb_h.path,
874                                               /*relsim_flags*/0,
875                                               /*openings*/0,
876                                               /*timeout*/0,
877                                               /*getcount_only*/0);
878         }
879
880         switch (status) {
881
882         case CAM_REQ_CMP:
883
884                 /*
885                  * If we have successfully taken a device from the not
886                  * ready to ready state, re-scan the device and re-get the
887                  * inquiry information.  Many devices (mostly disks) don't
888                  * properly report their inquiry information unless they
889                  * are spun up.
890                  */
891                 if (done_ccb->ccb_h.func_code == XPT_SCSI_IO) {
892                         scsi_cmd = (struct scsi_start_stop_unit *)
893                                         &done_ccb->csio.cdb_io.cdb_bytes;
894
895                         if (scsi_cmd->opcode == START_STOP_UNIT)
896                                 xpt_async(AC_INQ_CHANGED,
897                                           done_ccb->ccb_h.path, NULL);
898                 }
899                 bcopy(done_ccb->ccb_h.saved_ccb_ptr, done_ccb,
900                       sizeof(union ccb));
901
902                 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
903
904                 xpt_action(done_ccb);
905
906                 break;
907         case CAM_SCSI_STATUS_ERROR:
908                 scsi_cmd = (struct scsi_start_stop_unit *)
909                                 &done_ccb->csio.cdb_io.cdb_bytes;
910                 if (sense != 0) {
911                         struct scsi_sense_data *sense;
912                         int    error_code, sense_key, asc, ascq;        
913
914                         sense = &done_ccb->csio.sense_data;
915                         scsi_extract_sense(sense, &error_code, 
916                                            &sense_key, &asc, &ascq);
917
918                         /*
919                          * If the error is "invalid field in CDB", 
920                          * and the load/eject flag is set, turn the 
921                          * flag off and try again.  This is just in 
922                          * case the drive in question barfs on the 
923                          * load eject flag.  The CAM code should set 
924                          * the load/eject flag by default for 
925                          * removable media.
926                          */
927
928                         /* XXX KDM 
929                          * Should we check to see what the specific
930                          * scsi status is??  Or does it not matter
931                          * since we already know that there was an
932                          * error, and we know what the specific
933                          * error code was, and we know what the
934                          * opcode is..
935                          */
936                         if ((scsi_cmd->opcode == START_STOP_UNIT) &&
937                             ((scsi_cmd->how & SSS_LOEJ) != 0) &&
938                              (asc == 0x24) && (ascq == 0x00) &&
939                              (done_ccb->ccb_h.retry_count > 0)) {
940
941                                 scsi_cmd->how &= ~SSS_LOEJ;
942
943                                 xpt_action(done_ccb);
944
945                         } else if (done_ccb->ccb_h.retry_count > 0) {
946                                 /*
947                                  * In this case, the error recovery
948                                  * command failed, but we've got 
949                                  * some retries left on it.  Give
950                                  * it another try.
951                                  */
952
953                                 /* set the timeout to .5 sec */
954                                 relsim_flags =
955                                         RELSIM_RELEASE_AFTER_TIMEOUT;
956                                 timeout = 500;
957
958                                 xpt_action(done_ccb);
959
960                                 break;
961
962                         } else {
963                                 /* 
964                                  * Copy the original CCB back and
965                                  * send it back to the caller.
966                                  */
967                                 bcopy(done_ccb->ccb_h.saved_ccb_ptr,            
968                                       done_ccb, sizeof(union ccb));
969
970                                 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
971
972                                 xpt_action(done_ccb);
973                         }
974                 } else {
975                         /*
976                          * Eh??  The command failed, but we don't
977                          * have any sense.  What's up with that?
978                          * Fire the CCB again to return it to the
979                          * caller.
980                          */
981                         bcopy(done_ccb->ccb_h.saved_ccb_ptr,
982                               done_ccb, sizeof(union ccb));
983
984                         periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
985
986                         xpt_action(done_ccb);
987
988                 }
989                 break;
990         default:
991                 bcopy(done_ccb->ccb_h.saved_ccb_ptr, done_ccb,
992                       sizeof(union ccb));
993
994                 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
995
996                 xpt_action(done_ccb);
997
998                 break;
999         }
1000
1001         /* decrement the retry count */
1002         if (done_ccb->ccb_h.retry_count > 0)
1003                 done_ccb->ccb_h.retry_count--;
1004
1005         qfrozen_cnt = cam_release_devq(done_ccb->ccb_h.path,
1006                                       /*relsim_flags*/relsim_flags,
1007                                       /*openings*/0,
1008                                       /*timeout*/timeout,
1009                                       /*getcount_only*/0);
1010 }
1011
1012 /*
1013  * Generic Async Event handler.  Peripheral drivers usually
1014  * filter out the events that require personal attention,
1015  * and leave the rest to this function.
1016  */
1017 void
1018 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1019                  struct cam_path *path, void *arg)
1020 {
1021         switch (code) {
1022         case AC_LOST_DEVICE:
1023                 cam_periph_invalidate(periph);
1024                 break; 
1025         case AC_SENT_BDR:
1026         case AC_BUS_RESET:
1027         {
1028                 cam_periph_bus_settle(periph, SCSI_DELAY);
1029                 break;
1030         }
1031         default:
1032                 break;
1033         }
1034 }
1035
1036 void
1037 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1038 {
1039         struct ccb_getdevstats cgds;
1040
1041         xpt_setup_ccb(&cgds.ccb_h, periph->path, /*priority*/1);
1042         cgds.ccb_h.func_code = XPT_GDEV_STATS;
1043         xpt_action((union ccb *)&cgds);
1044         cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1045 }
1046
1047 void
1048 cam_periph_freeze_after_event(struct cam_periph *periph,
1049                               struct timeval* event_time, u_int duration_ms)
1050 {
1051         struct timeval delta;
1052         struct timeval duration_tv;
1053
1054         microuptime(&delta);
1055         timevalsub(&delta, event_time);
1056         duration_tv.tv_sec = duration_ms / 1000;
1057         duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1058         if (timevalcmp(&delta, &duration_tv, <)) {
1059                 timevalsub(&duration_tv, &delta);
1060
1061                 duration_ms = duration_tv.tv_sec * 1000;
1062                 duration_ms += duration_tv.tv_usec / 1000;
1063                 cam_freeze_devq(periph->path); 
1064                 cam_release_devq(periph->path,
1065                                 RELSIM_RELEASE_AFTER_TIMEOUT,
1066                                 /*reduction*/0,
1067                                 /*timeout*/duration_ms,
1068                                 /*getcount_only*/0);
1069         }
1070
1071 }
1072
1073 /*
1074  * Generic error handler.  Peripheral drivers usually filter
1075  * out the errors that they handle in a unique mannor, then
1076  * call this function.
1077  */
1078 int
1079 cam_periph_error(union ccb *ccb, cam_flags camflags,
1080                  u_int32_t sense_flags, union ccb *save_ccb)
1081 {
1082         cam_status status;
1083         int        frozen;
1084         int        sense;
1085         int        error;
1086         int        openings;
1087         int        retry;
1088         u_int32_t  relsim_flags;
1089         u_int32_t  timeout;
1090         
1091         status = ccb->ccb_h.status;
1092         frozen = (status & CAM_DEV_QFRZN) != 0;
1093         sense  = (status & CAM_AUTOSNS_VALID) != 0;
1094         status &= CAM_STATUS_MASK;
1095         relsim_flags = 0;
1096
1097         switch (status) {
1098         case CAM_REQ_CMP:
1099                 /* decrement the number of retries */
1100                 retry = ccb->ccb_h.retry_count > 0;
1101                 if (retry)
1102                         ccb->ccb_h.retry_count--;
1103                 error = 0;
1104                 break;
1105         case CAM_AUTOSENSE_FAIL:
1106         case CAM_SCSI_STATUS_ERROR:
1107
1108                 switch (ccb->csio.scsi_status) {
1109                 case SCSI_STATUS_OK:
1110                 case SCSI_STATUS_COND_MET:
1111                 case SCSI_STATUS_INTERMED:
1112                 case SCSI_STATUS_INTERMED_COND_MET:
1113                         error = 0;
1114                         break;
1115                 case SCSI_STATUS_CMD_TERMINATED:
1116                 case SCSI_STATUS_CHECK_COND:
1117                         if (sense != 0) {
1118                                 struct scsi_sense_data *sense;
1119                                 int    error_code, sense_key, asc, ascq;
1120                                 struct cam_periph *periph;
1121                                 scsi_sense_action err_action;
1122                                 struct ccb_getdev cgd;
1123
1124                                 sense = &ccb->csio.sense_data;
1125                                 scsi_extract_sense(sense, &error_code,
1126                                                    &sense_key, &asc, &ascq);
1127                                 periph = xpt_path_periph(ccb->ccb_h.path);
1128
1129                                 /*
1130                                  * Grab the inquiry data for this device.
1131                                  */
1132                                 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path,
1133                                               /*priority*/ 1);
1134                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1135                                 xpt_action((union ccb *)&cgd);
1136
1137                                 err_action = scsi_error_action(asc, ascq, 
1138                                                                &cgd.inq_data);
1139
1140                                 /*
1141                                  * Send a Test Unit Ready to the device.
1142                                  * If the 'many' flag is set, we send 120
1143                                  * test unit ready commands, one every half 
1144                                  * second.  Otherwise, we just send one TUR.
1145                                  * We only want to do this if the retry 
1146                                  * count has not been exhausted.
1147                                  */
1148                                 if (((err_action & SS_MASK) == SS_TUR)
1149                                  && save_ccb != NULL 
1150                                  && ccb->ccb_h.retry_count > 0) {
1151
1152                                         /*
1153                                          * Since error recovery is already
1154                                          * in progress, don't attempt to
1155                                          * process this error.  It is probably
1156                                          * related to the error that caused
1157                                          * the currently active error recovery
1158                                          * action.  Also, we only have
1159                                          * space for one saved CCB, so if we
1160                                          * had two concurrent error recovery
1161                                          * actions, we would end up
1162                                          * over-writing one error recovery
1163                                          * CCB with another one.
1164                                          */
1165                                         if (periph->flags &
1166                                             CAM_PERIPH_RECOVERY_INPROG) {
1167                                                 error = ERESTART;
1168                                                 break;
1169                                         }
1170
1171                                         periph->flags |=
1172                                                 CAM_PERIPH_RECOVERY_INPROG;
1173
1174                                         /* decrement the number of retries */
1175                                         if ((err_action & 
1176                                              SSQ_DECREMENT_COUNT) != 0) {
1177                                                 retry = 1;
1178                                                 ccb->ccb_h.retry_count--;
1179                                         }
1180
1181                                         bcopy(ccb, save_ccb, sizeof(*save_ccb));
1182
1183                                         /*
1184                                          * We retry this one every half
1185                                          * second for a minute.  If the
1186                                          * device hasn't become ready in a
1187                                          * minute's time, it's unlikely to
1188                                          * ever become ready.  If the table
1189                                          * doesn't specify SSQ_MANY, we can
1190                                          * only try this once.  Oh well.
1191                                          */
1192                                         if ((err_action & SSQ_MANY) != 0)
1193                                                 scsi_test_unit_ready(&ccb->csio,
1194                                                                /*retries*/120,
1195                                                                camperiphdone,
1196                                                                MSG_SIMPLE_Q_TAG,
1197                                                                SSD_FULL_SIZE,
1198                                                                /*timeout*/5000);
1199                                         else
1200                                                 scsi_test_unit_ready(&ccb->csio,
1201                                                                /*retries*/1,
1202                                                                camperiphdone,
1203                                                                MSG_SIMPLE_Q_TAG,
1204                                                                SSD_FULL_SIZE,
1205                                                                /*timeout*/5000);
1206
1207                                         /* release the queue after .5 sec.  */
1208                                         relsim_flags = 
1209                                                 RELSIM_RELEASE_AFTER_TIMEOUT;
1210                                         timeout = 500;
1211                                         /*
1212                                          * Drop the priority to 0 so that 
1213                                          * we are the first to execute.  Also 
1214                                          * freeze the queue after this command 
1215                                          * is sent so that we can restore the 
1216                                          * old csio and have it queued in the 
1217                                          * proper order before we let normal 
1218                                          * transactions go to the drive.
1219                                          */
1220                                         ccb->ccb_h.pinfo.priority = 0;
1221                                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1222
1223                                         /*
1224                                          * Save a pointer to the original
1225                                          * CCB in the new CCB.
1226                                          */
1227                                         ccb->ccb_h.saved_ccb_ptr = save_ccb;
1228
1229                                         error = ERESTART;
1230                                 }
1231                                 /*
1232                                  * Send a start unit command to the device,
1233                                  * and then retry the command.  We only 
1234                                  * want to do this if the retry count has 
1235                                  * not been exhausted.  If the user 
1236                                  * specified 0 retries, then we follow 
1237                                  * their request and do not retry.
1238                                  */
1239                                 else if (((err_action & SS_MASK) == SS_START)
1240                                       && save_ccb != NULL 
1241                                       && ccb->ccb_h.retry_count > 0) {
1242                                         int le;
1243
1244                                         /*
1245                                          * Only one error recovery action
1246                                          * at a time.  See above.
1247                                          */
1248                                         if (periph->flags &
1249                                             CAM_PERIPH_RECOVERY_INPROG) {
1250                                                 error = ERESTART;
1251                                                 break;
1252                                         }
1253
1254                                         periph->flags |=
1255                                                 CAM_PERIPH_RECOVERY_INPROG;
1256
1257                                         /* decrement the number of retries */
1258                                         retry = 1;
1259                                         ccb->ccb_h.retry_count--;
1260
1261                                         /*
1262                                          * Check for removable media and
1263                                          * set load/eject flag
1264                                          * appropriately.
1265                                          */
1266                                         if (SID_IS_REMOVABLE(&cgd.inq_data))
1267                                                 le = TRUE;
1268                                         else
1269                                                 le = FALSE;
1270
1271                                         /*
1272                                          * Attempt to start the drive up.
1273                                          *
1274                                          * Save the current ccb so it can 
1275                                          * be restored and retried once the 
1276                                          * drive is started up.
1277                                          */
1278                                         bcopy(ccb, save_ccb, sizeof(*save_ccb));
1279
1280                                         scsi_start_stop(&ccb->csio,
1281                                                         /*retries*/1,
1282                                                         camperiphdone,
1283                                                         MSG_SIMPLE_Q_TAG,
1284                                                         /*start*/TRUE,
1285                                                         /*load/eject*/le,
1286                                                         /*immediate*/FALSE,
1287                                                         SSD_FULL_SIZE,
1288                                                         /*timeout*/50000);
1289                                         /*
1290                                          * Drop the priority to 0 so that 
1291                                          * we are the first to execute.  Also 
1292                                          * freeze the queue after this command 
1293                                          * is sent so that we can restore the 
1294                                          * old csio and have it queued in the 
1295                                          * proper order before we let normal 
1296                                          * transactions go to the drive.
1297                                          */
1298                                         ccb->ccb_h.pinfo.priority = 0;
1299                                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1300
1301                                         /*
1302                                          * Save a pointer to the original
1303                                          * CCB in the new CCB.
1304                                          */
1305                                         ccb->ccb_h.saved_ccb_ptr = save_ccb;
1306
1307                                         error = ERESTART;
1308                                 } else if ((sense_flags & SF_RETRY_UA) != 0) {
1309                                         /*
1310                                          * XXX KDM this is a *horrible*
1311                                          * hack.  
1312                                          */
1313                                         error = scsi_interpret_sense(ccb,
1314                                                                   sense_flags,
1315                                                                   &relsim_flags,
1316                                                                   &openings,
1317                                                                   &timeout,
1318                                                                   err_action);
1319                                 } 
1320
1321                                 /*
1322                                  * Theoretically, this code should send a
1323                                  * test unit ready to the given device, and 
1324                                  * if it returns and error, send a start 
1325                                  * unit command.  Since we don't yet have
1326                                  * the capability to do two-command error
1327                                  * recovery, just send a start unit.
1328                                  * XXX KDM fix this!
1329                                  */
1330                                 else if (((err_action & SS_MASK) == SS_TURSTART)
1331                                       && save_ccb != NULL
1332                                       && ccb->ccb_h.retry_count > 0) {
1333                                         int le;
1334
1335                                         /*
1336                                          * Only one error recovery action
1337                                          * at a time.  See above.
1338                                          */
1339                                         if (periph->flags &
1340                                             CAM_PERIPH_RECOVERY_INPROG) {
1341                                                 error = ERESTART;
1342                                                 break;
1343                                         }
1344
1345                                         periph->flags |=
1346                                                 CAM_PERIPH_RECOVERY_INPROG;
1347
1348                                         /* decrement the number of retries */
1349                                         retry = 1;
1350                                         ccb->ccb_h.retry_count--;
1351
1352                                         /*
1353                                          * Check for removable media and
1354                                          * set load/eject flag
1355                                          * appropriately.
1356                                          */
1357                                         if (SID_IS_REMOVABLE(&cgd.inq_data))
1358                                                 le = TRUE;
1359                                         else
1360                                                 le = FALSE;
1361
1362                                         /*
1363                                          * Attempt to start the drive up.
1364                                          *
1365                                          * Save the current ccb so it can 
1366                                          * be restored and retried once the 
1367                                          * drive is started up.
1368                                          */
1369                                         bcopy(ccb, save_ccb, sizeof(*save_ccb));
1370
1371                                         scsi_start_stop(&ccb->csio,
1372                                                         /*retries*/1,
1373                                                         camperiphdone,
1374                                                         MSG_SIMPLE_Q_TAG,
1375                                                         /*start*/TRUE,
1376                                                         /*load/eject*/le,
1377                                                         /*immediate*/FALSE,
1378                                                         SSD_FULL_SIZE,
1379                                                         /*timeout*/50000);
1380
1381                                         /* release the queue after .5 sec.  */
1382                                         relsim_flags = 
1383                                                 RELSIM_RELEASE_AFTER_TIMEOUT;
1384                                         timeout = 500;
1385                                         /*
1386                                          * Drop the priority to 0 so that 
1387                                          * we are the first to execute.  Also 
1388                                          * freeze the queue after this command 
1389                                          * is sent so that we can restore the 
1390                                          * old csio and have it queued in the 
1391                                          * proper order before we let normal 
1392                                          * transactions go to the drive.
1393                                          */
1394                                         ccb->ccb_h.pinfo.priority = 0;
1395                                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1396
1397                                         /*
1398                                          * Save a pointer to the original
1399                                          * CCB in the new CCB.
1400                                          */
1401                                         ccb->ccb_h.saved_ccb_ptr = save_ccb;
1402
1403                                         error = ERESTART;
1404                                 } else {
1405                                         error = scsi_interpret_sense(ccb,
1406                                                                   sense_flags,
1407                                                                   &relsim_flags,
1408                                                                   &openings,
1409                                                                   &timeout,
1410                                                                   err_action);
1411                                 }
1412                         } else if (ccb->csio.scsi_status == 
1413                                    SCSI_STATUS_CHECK_COND
1414                                 && status != CAM_AUTOSENSE_FAIL) {
1415                                 /* no point in decrementing the retry count */
1416                                 panic("cam_periph_error: scsi status of "
1417                                       "CHECK COND returned but no sense "
1418                                       "information is available.  "
1419                                       "Controller should have returned "
1420                                       "CAM_AUTOSENSE_FAILED");
1421                                 /* NOTREACHED */
1422                                 error = EIO;
1423                         } else if (ccb->ccb_h.retry_count == 0) {
1424                                 /*
1425                                  * XXX KDM shouldn't there be a better
1426                                  * argument to return??
1427                                  */
1428                                 error = EIO;
1429                         } else {
1430                                 /* decrement the number of retries */
1431                                 retry = ccb->ccb_h.retry_count > 0;
1432                                 if (retry)
1433                                         ccb->ccb_h.retry_count--;
1434                                 /*
1435                                  * If it was aborted with no
1436                                  * clue as to the reason, just
1437                                  * retry it again.
1438                                  */
1439                                 error = ERESTART;
1440                         }
1441                         break;
1442                 case SCSI_STATUS_QUEUE_FULL:
1443                 {
1444                         /* no decrement */
1445                         struct ccb_getdevstats cgds;
1446
1447                         /*
1448                          * First off, find out what the current
1449                          * transaction counts are.
1450                          */
1451                         xpt_setup_ccb(&cgds.ccb_h,
1452                                       ccb->ccb_h.path,
1453                                       /*priority*/1);
1454                         cgds.ccb_h.func_code = XPT_GDEV_STATS;
1455                         xpt_action((union ccb *)&cgds);
1456
1457                         /*
1458                          * If we were the only transaction active, treat
1459                          * the QUEUE FULL as if it were a BUSY condition.
1460                          */
1461                         if (cgds.dev_active != 0) {
1462                                 int total_openings;
1463
1464                                 /*
1465                                  * Reduce the number of openings to
1466                                  * be 1 less than the amount it took
1467                                  * to get a queue full bounded by the
1468                                  * minimum allowed tag count for this
1469                                  * device.
1470                                  */
1471                                 total_openings =
1472                                     cgds.dev_active+cgds.dev_openings;
1473                                 openings = cgds.dev_active;
1474                                 if (openings < cgds.mintags)
1475                                         openings = cgds.mintags;
1476                                 if (openings < total_openings)
1477                                         relsim_flags = RELSIM_ADJUST_OPENINGS;
1478                                 else {
1479                                         /*
1480                                          * Some devices report queue full for
1481                                          * temporary resource shortages.  For
1482                                          * this reason, we allow a minimum
1483                                          * tag count to be entered via a
1484                                          * quirk entry to prevent the queue
1485                                          * count on these devices from falling
1486                                          * to a pessimisticly low value.  We
1487                                          * still wait for the next successful
1488                                          * completion, however, before queueing
1489                                          * more transactions to the device.
1490                                          */
1491                                         relsim_flags =
1492                                             RELSIM_RELEASE_AFTER_CMDCMPLT;
1493                                 }
1494                                 timeout = 0;
1495                                 error = ERESTART;
1496                                 break;
1497                         }
1498                         /* FALLTHROUGH */
1499                 }
1500                 case SCSI_STATUS_BUSY:
1501                         /*
1502                          * Restart the queue after either another
1503                          * command completes or a 1 second timeout.
1504                          * If we have any retries left, that is.
1505                          */
1506                         retry = ccb->ccb_h.retry_count > 0;
1507                         if (retry) {
1508                                 ccb->ccb_h.retry_count--;
1509                                 error = ERESTART;
1510                                 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1511                                              | RELSIM_RELEASE_AFTER_CMDCMPLT;
1512                                 timeout = 1000;
1513                         } else {
1514                                 error = EIO;
1515                         }
1516                         break;
1517                 case SCSI_STATUS_RESERV_CONFLICT:
1518                         error = EIO;
1519                         break;
1520                 default:
1521                         error = EIO;
1522                         break;
1523                 }
1524                 break;
1525         case CAM_REQ_CMP_ERR:
1526         case CAM_CMD_TIMEOUT:
1527         case CAM_UNEXP_BUSFREE:
1528         case CAM_UNCOR_PARITY:
1529         case CAM_DATA_RUN_ERR:
1530                 /* decrement the number of retries */
1531                 retry = ccb->ccb_h.retry_count > 0;
1532                 if (retry) {
1533                         ccb->ccb_h.retry_count--;
1534                         error = ERESTART;
1535                 } else {
1536                         error = EIO;
1537                 }
1538                 break;
1539         case CAM_UA_ABORT:
1540         case CAM_UA_TERMIO:
1541         case CAM_MSG_REJECT_REC:
1542                 /* XXX Don't know that these are correct */
1543                 error = EIO;
1544                 break;
1545         case CAM_SEL_TIMEOUT:
1546         {
1547                 /*
1548                  * XXX
1549                  * A single selection timeout should not be enough
1550                  * to invalidate a device.  We should retry for multiple
1551                  * seconds assuming this isn't a probe.  We'll probably
1552                  * need a special flag for that.
1553                  */
1554 #if 0
1555                 struct cam_path *newpath;
1556
1557                 /* Should we do more if we can't create the path?? */
1558                 if (xpt_create_path(&newpath, xpt_path_periph(ccb->ccb_h.path),
1559                                     xpt_path_path_id(ccb->ccb_h.path),
1560                                     xpt_path_target_id(ccb->ccb_h.path),
1561                                     CAM_LUN_WILDCARD) != CAM_REQ_CMP) 
1562                         break;
1563                 /*
1564                  * Let peripheral drivers know that this device has gone
1565                  * away.
1566                  */
1567                 xpt_async(AC_LOST_DEVICE, newpath, NULL);
1568                 xpt_free_path(newpath);
1569 #endif
1570                 if ((sense_flags & SF_RETRY_SELTO) != 0) {
1571                         retry = ccb->ccb_h.retry_count > 0;
1572                         if (retry) {
1573                                 ccb->ccb_h.retry_count--;
1574                                 error = ERESTART;
1575                                 /*
1576                                  * Wait half a second to give the device
1577                                  * time to recover before we try again.
1578                                  */
1579                                 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1580                                 timeout = 500;
1581                         } else {
1582                                 error = ENXIO;
1583                         }
1584                 } else {
1585                         error = ENXIO;
1586                 }
1587                 break;
1588         }
1589         case CAM_REQ_INVALID:
1590         case CAM_PATH_INVALID:
1591         case CAM_DEV_NOT_THERE:
1592         case CAM_NO_HBA:
1593         case CAM_PROVIDE_FAIL:
1594         case CAM_REQ_TOO_BIG:           
1595                 error = EINVAL;
1596                 break;
1597         case CAM_SCSI_BUS_RESET:
1598         case CAM_BDR_SENT:              
1599         case CAM_REQUEUE_REQ:
1600                 /* Unconditional requeue, dammit */
1601                 error = ERESTART;
1602                 break;
1603         case CAM_RESRC_UNAVAIL:
1604         case CAM_BUSY:
1605                 /* timeout??? */
1606         default:
1607                 /* decrement the number of retries */
1608                 retry = ccb->ccb_h.retry_count > 0;
1609                 if (retry) {
1610                         ccb->ccb_h.retry_count--;
1611                         error = ERESTART;
1612                 } else {
1613                         /* Check the sense codes */
1614                         error = EIO;
1615                 }
1616                 break;
1617         }
1618
1619         /* Attempt a retry */
1620         if (error == ERESTART || error == 0) {  
1621                 if (frozen != 0)
1622                         ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1623
1624                 if (error == ERESTART)
1625                         xpt_action(ccb);
1626                 
1627                 if (frozen != 0) {
1628                         cam_release_devq(ccb->ccb_h.path,
1629                                          relsim_flags,
1630                                          openings,
1631                                          timeout,
1632                                          /*getcount_only*/0);
1633                 }
1634         }
1635
1636
1637         return (error);
1638 }