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