This commit represents a major revamping of the clock interrupt and timebase
[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.7 2004/01/30 05:42:09 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
1075         microuptime(&delta);
1076         timevalsub(&delta, event_time);
1077         duration_tv.tv_sec = duration_ms / 1000;
1078         duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1079         if (timevalcmp(&delta, &duration_tv, <)) {
1080                 timevalsub(&duration_tv, &delta);
1081
1082                 duration_ms = duration_tv.tv_sec * 1000;
1083                 duration_ms += duration_tv.tv_usec / 1000;
1084                 cam_freeze_devq(periph->path); 
1085                 cam_release_devq(periph->path,
1086                                 RELSIM_RELEASE_AFTER_TIMEOUT,
1087                                 /*reduction*/0,
1088                                 /*timeout*/duration_ms,
1089                                 /*getcount_only*/0);
1090         }
1091
1092 }
1093
1094 /*
1095  * Generic error handler.  Peripheral drivers usually filter
1096  * out the errors that they handle in a unique mannor, then
1097  * call this function.
1098  */
1099 int
1100 cam_periph_error(union ccb *ccb, cam_flags camflags,
1101                  u_int32_t sense_flags, union ccb *save_ccb)
1102 {
1103         cam_status status;
1104         int        frozen;
1105         int        sense;
1106         int        error;
1107         int        openings;
1108         int        retry;
1109         u_int32_t  relsim_flags;
1110         u_int32_t  timeout;
1111         
1112         status = ccb->ccb_h.status;
1113         frozen = (status & CAM_DEV_QFRZN) != 0;
1114         sense  = (status & CAM_AUTOSNS_VALID) != 0;
1115         status &= CAM_STATUS_MASK;
1116         relsim_flags = 0;
1117
1118         switch (status) {
1119         case CAM_REQ_CMP:
1120                 /* decrement the number of retries */
1121                 retry = ccb->ccb_h.retry_count > 0;
1122                 if (retry)
1123                         ccb->ccb_h.retry_count--;
1124                 error = 0;
1125                 break;
1126         case CAM_AUTOSENSE_FAIL:
1127         case CAM_SCSI_STATUS_ERROR:
1128
1129                 switch (ccb->csio.scsi_status) {
1130                 case SCSI_STATUS_OK:
1131                 case SCSI_STATUS_COND_MET:
1132                 case SCSI_STATUS_INTERMED:
1133                 case SCSI_STATUS_INTERMED_COND_MET:
1134                         error = 0;
1135                         break;
1136                 case SCSI_STATUS_CMD_TERMINATED:
1137                 case SCSI_STATUS_CHECK_COND:
1138                         if (sense != 0) {
1139                                 struct scsi_sense_data *sense;
1140                                 int    error_code, sense_key, asc, ascq;
1141                                 struct cam_periph *periph;
1142                                 scsi_sense_action err_action;
1143                                 struct ccb_getdev cgd;
1144
1145                                 sense = &ccb->csio.sense_data;
1146                                 scsi_extract_sense(sense, &error_code,
1147                                                    &sense_key, &asc, &ascq);
1148                                 periph = xpt_path_periph(ccb->ccb_h.path);
1149
1150                                 /*
1151                                  * Grab the inquiry data for this device.
1152                                  */
1153                                 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path,
1154                                               /*priority*/ 1);
1155                                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1156                                 xpt_action((union ccb *)&cgd);
1157
1158                                 err_action = scsi_error_action(asc, ascq, 
1159                                                                &cgd.inq_data);
1160
1161                                 /*
1162                                  * Send a Test Unit Ready to the device.
1163                                  * If the 'many' flag is set, we send 120
1164                                  * test unit ready commands, one every half 
1165                                  * second.  Otherwise, we just send one TUR.
1166                                  * We only want to do this if the retry 
1167                                  * count has not been exhausted.
1168                                  */
1169                                 if (((err_action & SS_MASK) == SS_TUR)
1170                                  && save_ccb != NULL 
1171                                  && ccb->ccb_h.retry_count > 0) {
1172
1173                                         /*
1174                                          * Since error recovery is already
1175                                          * in progress, don't attempt to
1176                                          * process this error.  It is probably
1177                                          * related to the error that caused
1178                                          * the currently active error recovery
1179                                          * action.  Also, we only have
1180                                          * space for one saved CCB, so if we
1181                                          * had two concurrent error recovery
1182                                          * actions, we would end up
1183                                          * over-writing one error recovery
1184                                          * CCB with another one.
1185                                          */
1186                                         if (periph->flags &
1187                                             CAM_PERIPH_RECOVERY_INPROG) {
1188                                                 error = ERESTART;
1189                                                 break;
1190                                         }
1191
1192                                         periph->flags |=
1193                                                 CAM_PERIPH_RECOVERY_INPROG;
1194
1195                                         /* decrement the number of retries */
1196                                         if ((err_action & 
1197                                              SSQ_DECREMENT_COUNT) != 0) {
1198                                                 retry = 1;
1199                                                 ccb->ccb_h.retry_count--;
1200                                         }
1201
1202                                         bcopy(ccb, save_ccb, sizeof(*save_ccb));
1203
1204                                         /*
1205                                          * We retry this one every half
1206                                          * second for a minute.  If the
1207                                          * device hasn't become ready in a
1208                                          * minute's time, it's unlikely to
1209                                          * ever become ready.  If the table
1210                                          * doesn't specify SSQ_MANY, we can
1211                                          * only try this once.  Oh well.
1212                                          */
1213                                         if ((err_action & SSQ_MANY) != 0)
1214                                                 scsi_test_unit_ready(&ccb->csio,
1215                                                                /*retries*/120,
1216                                                                camperiphdone,
1217                                                                MSG_SIMPLE_Q_TAG,
1218                                                                SSD_FULL_SIZE,
1219                                                                /*timeout*/5000);
1220                                         else
1221                                                 scsi_test_unit_ready(&ccb->csio,
1222                                                                /*retries*/1,
1223                                                                camperiphdone,
1224                                                                MSG_SIMPLE_Q_TAG,
1225                                                                SSD_FULL_SIZE,
1226                                                                /*timeout*/5000);
1227
1228                                         /* release the queue after .5 sec.  */
1229                                         relsim_flags = 
1230                                                 RELSIM_RELEASE_AFTER_TIMEOUT;
1231                                         timeout = 500;
1232                                         /*
1233                                          * Drop the priority to 0 so that 
1234                                          * we are the first to execute.  Also 
1235                                          * freeze the queue after this command 
1236                                          * is sent so that we can restore the 
1237                                          * old csio and have it queued in the 
1238                                          * proper order before we let normal 
1239                                          * transactions go to the drive.
1240                                          */
1241                                         ccb->ccb_h.pinfo.priority = 0;
1242                                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1243
1244                                         /*
1245                                          * Save a pointer to the original
1246                                          * CCB in the new CCB.
1247                                          */
1248                                         ccb->ccb_h.saved_ccb_ptr = save_ccb;
1249
1250                                         error = ERESTART;
1251                                 }
1252                                 /*
1253                                  * Send a start unit command to the device,
1254                                  * and then retry the command.  We only 
1255                                  * want to do this if the retry count has 
1256                                  * not been exhausted.  If the user 
1257                                  * specified 0 retries, then we follow 
1258                                  * their request and do not retry.
1259                                  */
1260                                 else if (((err_action & SS_MASK) == SS_START)
1261                                       && save_ccb != NULL 
1262                                       && ccb->ccb_h.retry_count > 0) {
1263                                         int le;
1264
1265                                         /*
1266                                          * Only one error recovery action
1267                                          * at a time.  See above.
1268                                          */
1269                                         if (periph->flags &
1270                                             CAM_PERIPH_RECOVERY_INPROG) {
1271                                                 error = ERESTART;
1272                                                 break;
1273                                         }
1274
1275                                         periph->flags |=
1276                                                 CAM_PERIPH_RECOVERY_INPROG;
1277
1278                                         /* decrement the number of retries */
1279                                         retry = 1;
1280                                         ccb->ccb_h.retry_count--;
1281
1282                                         /*
1283                                          * Check for removable media and
1284                                          * set load/eject flag
1285                                          * appropriately.
1286                                          */
1287                                         if (SID_IS_REMOVABLE(&cgd.inq_data))
1288                                                 le = TRUE;
1289                                         else
1290                                                 le = FALSE;
1291
1292                                         /*
1293                                          * Attempt to start the drive up.
1294                                          *
1295                                          * Save the current ccb so it can 
1296                                          * be restored and retried once the 
1297                                          * drive is started up.
1298                                          */
1299                                         bcopy(ccb, save_ccb, sizeof(*save_ccb));
1300
1301                                         scsi_start_stop(&ccb->csio,
1302                                                         /*retries*/1,
1303                                                         camperiphdone,
1304                                                         MSG_SIMPLE_Q_TAG,
1305                                                         /*start*/TRUE,
1306                                                         /*load/eject*/le,
1307                                                         /*immediate*/FALSE,
1308                                                         SSD_FULL_SIZE,
1309                                                         /*timeout*/50000);
1310                                         /*
1311                                          * Drop the priority to 0 so that 
1312                                          * we are the first to execute.  Also 
1313                                          * freeze the queue after this command 
1314                                          * is sent so that we can restore the 
1315                                          * old csio and have it queued in the 
1316                                          * proper order before we let normal 
1317                                          * transactions go to the drive.
1318                                          */
1319                                         ccb->ccb_h.pinfo.priority = 0;
1320                                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1321
1322                                         /*
1323                                          * Save a pointer to the original
1324                                          * CCB in the new CCB.
1325                                          */
1326                                         ccb->ccb_h.saved_ccb_ptr = save_ccb;
1327
1328                                         error = ERESTART;
1329                                 } else if ((sense_flags & SF_RETRY_UA) != 0) {
1330                                         /*
1331                                          * XXX KDM this is a *horrible*
1332                                          * hack.  
1333                                          */
1334                                         error = scsi_interpret_sense(ccb,
1335                                                                   sense_flags,
1336                                                                   &relsim_flags,
1337                                                                   &openings,
1338                                                                   &timeout,
1339                                                                   err_action);
1340                                 } 
1341
1342                                 /*
1343                                  * Theoretically, this code should send a
1344                                  * test unit ready to the given device, and 
1345                                  * if it returns and error, send a start 
1346                                  * unit command.  Since we don't yet have
1347                                  * the capability to do two-command error
1348                                  * recovery, just send a start unit.
1349                                  * XXX KDM fix this!
1350                                  */
1351                                 else if (((err_action & SS_MASK) == SS_TURSTART)
1352                                       && save_ccb != NULL
1353                                       && ccb->ccb_h.retry_count > 0) {
1354                                         int le;
1355
1356                                         /*
1357                                          * Only one error recovery action
1358                                          * at a time.  See above.
1359                                          */
1360                                         if (periph->flags &
1361                                             CAM_PERIPH_RECOVERY_INPROG) {
1362                                                 error = ERESTART;
1363                                                 break;
1364                                         }
1365
1366                                         periph->flags |=
1367                                                 CAM_PERIPH_RECOVERY_INPROG;
1368
1369                                         /* decrement the number of retries */
1370                                         retry = 1;
1371                                         ccb->ccb_h.retry_count--;
1372
1373                                         /*
1374                                          * Check for removable media and
1375                                          * set load/eject flag
1376                                          * appropriately.
1377                                          */
1378                                         if (SID_IS_REMOVABLE(&cgd.inq_data))
1379                                                 le = TRUE;
1380                                         else
1381                                                 le = FALSE;
1382
1383                                         /*
1384                                          * Attempt to start the drive up.
1385                                          *
1386                                          * Save the current ccb so it can 
1387                                          * be restored and retried once the 
1388                                          * drive is started up.
1389                                          */
1390                                         bcopy(ccb, save_ccb, sizeof(*save_ccb));
1391
1392                                         scsi_start_stop(&ccb->csio,
1393                                                         /*retries*/1,
1394                                                         camperiphdone,
1395                                                         MSG_SIMPLE_Q_TAG,
1396                                                         /*start*/TRUE,
1397                                                         /*load/eject*/le,
1398                                                         /*immediate*/FALSE,
1399                                                         SSD_FULL_SIZE,
1400                                                         /*timeout*/50000);
1401
1402                                         /* release the queue after .5 sec.  */
1403                                         relsim_flags = 
1404                                                 RELSIM_RELEASE_AFTER_TIMEOUT;
1405                                         timeout = 500;
1406                                         /*
1407                                          * Drop the priority to 0 so that 
1408                                          * we are the first to execute.  Also 
1409                                          * freeze the queue after this command 
1410                                          * is sent so that we can restore the 
1411                                          * old csio and have it queued in the 
1412                                          * proper order before we let normal 
1413                                          * transactions go to the drive.
1414                                          */
1415                                         ccb->ccb_h.pinfo.priority = 0;
1416                                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1417
1418                                         /*
1419                                          * Save a pointer to the original
1420                                          * CCB in the new CCB.
1421                                          */
1422                                         ccb->ccb_h.saved_ccb_ptr = save_ccb;
1423
1424                                         error = ERESTART;
1425                                 } else {
1426                                         error = scsi_interpret_sense(ccb,
1427                                                                   sense_flags,
1428                                                                   &relsim_flags,
1429                                                                   &openings,
1430                                                                   &timeout,
1431                                                                   err_action);
1432                                 }
1433                         } else if (ccb->csio.scsi_status == 
1434                                    SCSI_STATUS_CHECK_COND
1435                                 && status != CAM_AUTOSENSE_FAIL) {
1436                                 /* no point in decrementing the retry count */
1437                                 panic("cam_periph_error: scsi status of "
1438                                       "CHECK COND returned but no sense "
1439                                       "information is availible.  "
1440                                       "Controller should have returned "
1441                                       "CAM_AUTOSENSE_FAILED");
1442                                 /* NOTREACHED */
1443                                 error = EIO;
1444                         } else if (ccb->ccb_h.retry_count == 0) {
1445                                 /*
1446                                  * XXX KDM shouldn't there be a better
1447                                  * argument to return??
1448                                  */
1449                                 error = EIO;
1450                         } else {
1451                                 /* decrement the number of retries */
1452                                 retry = ccb->ccb_h.retry_count > 0;
1453                                 if (retry)
1454                                         ccb->ccb_h.retry_count--;
1455                                 /*
1456                                  * If it was aborted with no
1457                                  * clue as to the reason, just
1458                                  * retry it again.
1459                                  */
1460                                 error = ERESTART;
1461                         }
1462                         break;
1463                 case SCSI_STATUS_QUEUE_FULL:
1464                 {
1465                         /* no decrement */
1466                         struct ccb_getdevstats cgds;
1467
1468                         /*
1469                          * First off, find out what the current
1470                          * transaction counts are.
1471                          */
1472                         xpt_setup_ccb(&cgds.ccb_h,
1473                                       ccb->ccb_h.path,
1474                                       /*priority*/1);
1475                         cgds.ccb_h.func_code = XPT_GDEV_STATS;
1476                         xpt_action((union ccb *)&cgds);
1477
1478                         /*
1479                          * If we were the only transaction active, treat
1480                          * the QUEUE FULL as if it were a BUSY condition.
1481                          */
1482                         if (cgds.dev_active != 0) {
1483                                 int total_openings;
1484
1485                                 /*
1486                                  * Reduce the number of openings to
1487                                  * be 1 less than the amount it took
1488                                  * to get a queue full bounded by the
1489                                  * minimum allowed tag count for this
1490                                  * device.
1491                                  */
1492                                 total_openings =
1493                                     cgds.dev_active+cgds.dev_openings;
1494                                 openings = cgds.dev_active;
1495                                 if (openings < cgds.mintags)
1496                                         openings = cgds.mintags;
1497                                 if (openings < total_openings)
1498                                         relsim_flags = RELSIM_ADJUST_OPENINGS;
1499                                 else {
1500                                         /*
1501                                          * Some devices report queue full for
1502                                          * temporary resource shortages.  For
1503                                          * this reason, we allow a minimum
1504                                          * tag count to be entered via a
1505                                          * quirk entry to prevent the queue
1506                                          * count on these devices from falling
1507                                          * to a pessimisticly low value.  We
1508                                          * still wait for the next successful
1509                                          * completion, however, before queueing
1510                                          * more transactions to the device.
1511                                          */
1512                                         relsim_flags =
1513                                             RELSIM_RELEASE_AFTER_CMDCMPLT;
1514                                 }
1515                                 timeout = 0;
1516                                 error = ERESTART;
1517                                 break;
1518                         }
1519                         /* FALLTHROUGH */
1520                 }
1521                 case SCSI_STATUS_BUSY:
1522                         /*
1523                          * Restart the queue after either another
1524                          * command completes or a 1 second timeout.
1525                          * If we have any retries left, that is.
1526                          */
1527                         retry = ccb->ccb_h.retry_count > 0;
1528                         if (retry) {
1529                                 ccb->ccb_h.retry_count--;
1530                                 error = ERESTART;
1531                                 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1532                                              | RELSIM_RELEASE_AFTER_CMDCMPLT;
1533                                 timeout = 1000;
1534                         } else {
1535                                 error = EIO;
1536                         }
1537                         break;
1538                 case SCSI_STATUS_RESERV_CONFLICT:
1539                         error = EIO;
1540                         break;
1541                 default:
1542                         error = EIO;
1543                         break;
1544                 }
1545                 break;
1546         case CAM_REQ_CMP_ERR:
1547         case CAM_CMD_TIMEOUT:
1548         case CAM_UNEXP_BUSFREE:
1549         case CAM_UNCOR_PARITY:
1550         case CAM_DATA_RUN_ERR:
1551                 /* decrement the number of retries */
1552                 retry = ccb->ccb_h.retry_count > 0;
1553                 if (retry) {
1554                         ccb->ccb_h.retry_count--;
1555                         error = ERESTART;
1556                 } else {
1557                         error = EIO;
1558                 }
1559                 break;
1560         case CAM_UA_ABORT:
1561         case CAM_UA_TERMIO:
1562         case CAM_MSG_REJECT_REC:
1563                 /* XXX Don't know that these are correct */
1564                 error = EIO;
1565                 break;
1566         case CAM_SEL_TIMEOUT:
1567         {
1568                 /*
1569                  * XXX
1570                  * A single selection timeout should not be enough
1571                  * to invalidate a device.  We should retry for multiple
1572                  * seconds assuming this isn't a probe.  We'll probably
1573                  * need a special flag for that.
1574                  */
1575 #if 0
1576                 struct cam_path *newpath;
1577
1578                 /* Should we do more if we can't create the path?? */
1579                 if (xpt_create_path(&newpath, xpt_path_periph(ccb->ccb_h.path),
1580                                     xpt_path_path_id(ccb->ccb_h.path),
1581                                     xpt_path_target_id(ccb->ccb_h.path),
1582                                     CAM_LUN_WILDCARD) != CAM_REQ_CMP) 
1583                         break;
1584                 /*
1585                  * Let peripheral drivers know that this device has gone
1586                  * away.
1587                  */
1588                 xpt_async(AC_LOST_DEVICE, newpath, NULL);
1589                 xpt_free_path(newpath);
1590 #endif
1591                 if ((sense_flags & SF_RETRY_SELTO) != 0) {
1592                         retry = ccb->ccb_h.retry_count > 0;
1593                         if (retry) {
1594                                 ccb->ccb_h.retry_count--;
1595                                 error = ERESTART;
1596                                 /*
1597                                  * Wait half a second to give the device
1598                                  * time to recover before we try again.
1599                                  */
1600                                 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1601                                 timeout = 500;
1602                         } else {
1603                                 error = ENXIO;
1604                         }
1605                 } else {
1606                         error = ENXIO;
1607                 }
1608                 break;
1609         }
1610         case CAM_REQ_INVALID:
1611         case CAM_PATH_INVALID:
1612         case CAM_DEV_NOT_THERE:
1613         case CAM_NO_HBA:
1614         case CAM_PROVIDE_FAIL:
1615         case CAM_REQ_TOO_BIG:           
1616                 error = EINVAL;
1617                 break;
1618         case CAM_SCSI_BUS_RESET:
1619         case CAM_BDR_SENT:              
1620         case CAM_REQUEUE_REQ:
1621                 /* Unconditional requeue, dammit */
1622                 error = ERESTART;
1623                 break;
1624         case CAM_RESRC_UNAVAIL:
1625         case CAM_BUSY:
1626                 /* timeout??? */
1627         default:
1628                 /* decrement the number of retries */
1629                 retry = ccb->ccb_h.retry_count > 0;
1630                 if (retry) {
1631                         ccb->ccb_h.retry_count--;
1632                         error = ERESTART;
1633                 } else {
1634                         /* Check the sense codes */
1635                         error = EIO;
1636                 }
1637                 break;
1638         }
1639
1640         /* Attempt a retry */
1641         if (error == ERESTART || error == 0) {  
1642                 if (frozen != 0)
1643                         ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1644
1645                 if (error == ERESTART)
1646                         xpt_action(ccb);
1647                 
1648                 if (frozen != 0) {
1649                         cam_release_devq(ccb->ccb_h.path,
1650                                          relsim_flags,
1651                                          openings,
1652                                          timeout,
1653                                          /*getcount_only*/0);
1654                 }
1655         }
1656
1657
1658         return (error);
1659 }