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