Kill the command (don't rerun it) if we had an AUTOSENSE failure.
[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.28 2007/11/22 00:59:49 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                         break;
1231                 }
1232                 /* FALLTHROUGH */
1233         }
1234         case SCSI_STATUS_BUSY:
1235                 /*
1236                  * Restart the queue after either another
1237                  * command completes or a 1 second timeout.
1238                  */
1239                 if (ccb->ccb_h.retry_count > 0) {
1240                         ccb->ccb_h.retry_count--;
1241                         error = ERESTART;
1242                         *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1243                                       | RELSIM_RELEASE_AFTER_CMDCMPLT;
1244                         *timeout = 1000;
1245                 } else {
1246                         error = EIO;
1247                 }
1248                 break;
1249         case SCSI_STATUS_RESERV_CONFLICT:
1250                 error = EIO;
1251                 break;
1252         default:
1253                 error = EIO;
1254                 break;
1255         }
1256         return (error);
1257 }
1258
1259 static int
1260 camperiphscsisenseerror(union ccb *ccb, cam_flags camflags,
1261                         u_int32_t sense_flags, union ccb *save_ccb,
1262                        int *openings, u_int32_t *relsim_flags,
1263                        u_int32_t *timeout)
1264 {
1265         struct cam_periph *periph;
1266         int error;
1267
1268         periph = xpt_path_periph(ccb->ccb_h.path);
1269         if (periph->flags & CAM_PERIPH_RECOVERY_INPROG) {
1270
1271                 /*
1272                  * If error recovery is already in progress, don't attempt
1273                  * to process this error, but requeue it unconditionally
1274                  * and attempt to process it once error recovery has
1275                  * completed.  This failed command is probably related to
1276                  * the error that caused the currently active error recovery
1277                  * action so our  current recovery efforts should also
1278                  * address this command.  Be aware that the error recovery
1279                  * code assumes that only one recovery action is in progress
1280                  * on a particular peripheral instance at any given time
1281                  * (e.g. only one saved CCB for error recovery) so it is
1282                  * imperitive that we don't violate this assumption.
1283                  */
1284                 error = ERESTART;
1285         } else {
1286                 scsi_sense_action err_action;
1287                 struct ccb_getdev cgd;
1288                 const char *action_string;
1289                 union ccb* print_ccb;
1290
1291                 /* A description of the error recovery action performed */
1292                 action_string = NULL;
1293
1294                 /*
1295                  * The location of the orignal ccb
1296                  * for sense printing purposes.
1297                  */
1298                 print_ccb = ccb;
1299
1300                 /*
1301                  * Grab the inquiry data for this device.
1302                  */
1303                 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, /*priority*/ 1);
1304                 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1305                 xpt_action((union ccb *)&cgd);
1306
1307                 if ((ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0)
1308                         err_action = scsi_error_action(&ccb->csio,
1309                                                        &cgd.inq_data,
1310                                                        sense_flags);
1311                 else if ((ccb->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0)
1312                         err_action = SS_REQSENSE;
1313                 else
1314                         err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1315
1316                 error = err_action & SS_ERRMASK;
1317
1318                 /*
1319                  * If the recovery action will consume a retry,
1320                  * make sure we actually have retries available.
1321                  */
1322                 if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1323                         if (ccb->ccb_h.retry_count > 0)
1324                                 ccb->ccb_h.retry_count--;
1325                         else {
1326                                 action_string = "Retries Exhausted";
1327                                 goto sense_error_done;
1328                         }
1329                 }
1330
1331                 if ((err_action & SS_MASK) >= SS_START) {
1332                         /*
1333                          * Do common portions of commands that
1334                          * use recovery CCBs.
1335                          */
1336                         if (save_ccb == NULL) {
1337                                 action_string = "No recovery CCB supplied";
1338                                 goto sense_error_done;
1339                         }
1340                         bcopy(ccb, save_ccb, sizeof(*save_ccb));
1341                         print_ccb = save_ccb;
1342                         periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1343                 }
1344
1345                 switch (err_action & SS_MASK) {
1346                 case SS_NOP:
1347                         action_string = "No Recovery Action Needed";
1348                         error = 0;
1349                         break;
1350                 case SS_RETRY:
1351                         action_string = "Retrying Command";
1352                         error = ERESTART;
1353                         break;
1354                 case SS_FAIL:
1355                         action_string = "Unretryable error";
1356                         break;
1357                 case SS_START:
1358                 {
1359                         int le;
1360
1361                         /*
1362                          * Send a start unit command to the device, and
1363                          * then retry the command.
1364                          */
1365                         action_string = "Attempting to Start Unit";
1366
1367                         /*
1368                          * Check for removable media and set
1369                          * load/eject flag appropriately.
1370                          */
1371                         if (SID_IS_REMOVABLE(&cgd.inq_data))
1372                                 le = TRUE;
1373                         else
1374                                 le = FALSE;
1375
1376                         scsi_start_stop(&ccb->csio,
1377                                         /*retries*/1,
1378                                         camperiphdone,
1379                                         MSG_SIMPLE_Q_TAG,
1380                                         /*start*/TRUE,
1381                                         /*load/eject*/le,
1382                                         /*immediate*/FALSE,
1383                                         SSD_FULL_SIZE,
1384                                         /*timeout*/50000);
1385                         break;
1386                 }
1387                 case SS_TUR:
1388                 {
1389                         /*
1390                          * Send a Test Unit Ready to the device.
1391                          * If the 'many' flag is set, we send 120
1392                          * test unit ready commands, one every half
1393                          * second.  Otherwise, we just send one TUR.
1394                          * We only want to do this if the retry
1395                          * count has not been exhausted.
1396                          */
1397                         int retries;
1398
1399                         if ((err_action & SSQ_MANY) != 0) {
1400                                 action_string = "Polling device for readiness";
1401                                 retries = 120;
1402                         } else {
1403                                 action_string = "Testing device for readiness";
1404                                 retries = 1;
1405                         }
1406                         scsi_test_unit_ready(&ccb->csio,
1407                                              retries,
1408                                              camperiphdone,
1409                                              MSG_SIMPLE_Q_TAG,
1410                                              SSD_FULL_SIZE,
1411                                              /*timeout*/5000);
1412
1413                         /*
1414                          * Accomplish our 500ms delay by deferring
1415                          * the release of our device queue appropriately.
1416                          */
1417                         *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1418                         *timeout = 500;
1419                         break;
1420                 }
1421                 case SS_REQSENSE:
1422                 {
1423                         /*
1424                          * Send a Request Sense to the device.  We
1425                          * assume that we are in a contingent allegiance
1426                          * condition so we do not tag this request.
1427                          */
1428                         scsi_request_sense(&ccb->csio, /*retries*/1,
1429                                            camperiphdone,
1430                                            &save_ccb->csio.sense_data,
1431                                            sizeof(save_ccb->csio.sense_data),
1432                                            CAM_TAG_ACTION_NONE,
1433                                            /*sense_len*/SSD_FULL_SIZE,
1434                                            /*timeout*/5000);
1435                         break;
1436                 }
1437                 default:
1438                         panic("Unhandled error action %x\n", err_action);
1439                 }
1440
1441                 if ((err_action & SS_MASK) >= SS_START) {
1442                         /*
1443                          * Drop the priority to 0 so that the recovery
1444                          * CCB is the first to execute.  Freeze the queue
1445                          * after this command is sent so that we can
1446                          * restore the old csio and have it queued in
1447                          * the proper order before we release normal
1448                          * transactions to the device.
1449                          */
1450                         ccb->ccb_h.pinfo.priority = 0;
1451                         ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1452                         ccb->ccb_h.saved_ccb_ptr = save_ccb;
1453                         error = ERESTART;
1454                 }
1455
1456 sense_error_done:
1457                 if ((err_action & SSQ_PRINT_SENSE) != 0
1458                  && (ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0) {
1459 #if 0
1460                         scsi_sense_print(&print_ccb->csio);
1461 #endif
1462                         cam_error_print(print_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1463                         xpt_print_path(ccb->ccb_h.path);
1464                         kprintf("%s\n", action_string);
1465                 }
1466         }
1467         return (error);
1468 }
1469
1470 /*
1471  * Generic error handler.  Peripheral drivers usually filter
1472  * out the errors that they handle in a unique mannor, then
1473  * call this function.
1474  */
1475 int
1476 cam_periph_error(union ccb *ccb, cam_flags camflags,
1477                  u_int32_t sense_flags, union ccb *save_ccb)
1478 {
1479         const char *action_string;
1480         cam_status  status;
1481         int         frozen;
1482         int         error;
1483         int         openings;
1484         u_int32_t   relsim_flags;
1485         u_int32_t   timeout;
1486
1487         action_string = NULL;
1488         status = ccb->ccb_h.status;
1489         frozen = (status & CAM_DEV_QFRZN) != 0;
1490         status &= CAM_STATUS_MASK;
1491         openings = relsim_flags = 0;
1492
1493         switch (status) {
1494         case CAM_REQ_CMP:
1495                 error = 0;
1496                 break;
1497         case CAM_SCSI_STATUS_ERROR:
1498                 error = camperiphscsistatuserror(ccb,
1499                                                  camflags,
1500                                                  sense_flags,
1501                                                  save_ccb,
1502                                                  &openings,
1503                                                  &relsim_flags,
1504                                                  &timeout);
1505                 break;
1506         case CAM_AUTOSENSE_FAIL:
1507                 xpt_print_path(ccb->ccb_h.path);
1508                 kprintf("AutoSense Failed\n");
1509                 error = EIO;    /* we have to kill the command */
1510                 break;
1511         case CAM_REQ_CMP_ERR:
1512         case CAM_CMD_TIMEOUT:
1513         case CAM_UNEXP_BUSFREE:
1514         case CAM_UNCOR_PARITY:
1515         case CAM_DATA_RUN_ERR:
1516                 /* decrement the number of retries */
1517                 if (ccb->ccb_h.retry_count > 0) {
1518                         ccb->ccb_h.retry_count--;
1519                         error = ERESTART;
1520                 } else {
1521                         action_string = "Retries Exausted";
1522                         error = EIO;
1523                 }
1524                 break;
1525         case CAM_UA_ABORT:
1526         case CAM_UA_TERMIO:
1527         case CAM_MSG_REJECT_REC:
1528                 /* XXX Don't know that these are correct */
1529                 error = EIO;
1530                 break;
1531         case CAM_SEL_TIMEOUT:
1532         {
1533                 struct cam_path *newpath;
1534
1535                 if ((camflags & CAM_RETRY_SELTO) != 0) {
1536                         if (ccb->ccb_h.retry_count > 0) {
1537
1538                                 ccb->ccb_h.retry_count--;
1539                                 error = ERESTART;
1540
1541                                 /*
1542                                  * Wait a second to give the device
1543                                  * time to recover before we try again.
1544                                  */
1545                                 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1546                                 timeout = 1000;
1547                                 break;
1548                         }
1549                 }
1550                 error = ENXIO;
1551                 /* Should we do more if we can't create the path?? */
1552                 if (xpt_create_path(&newpath, xpt_path_periph(ccb->ccb_h.path),
1553                                     xpt_path_path_id(ccb->ccb_h.path),
1554                                     xpt_path_target_id(ccb->ccb_h.path),
1555                                     CAM_LUN_WILDCARD) != CAM_REQ_CMP) 
1556                         break;
1557
1558                 /*
1559                  * Let peripheral drivers know that this device has gone
1560                  * away.
1561                  */
1562                 xpt_async(AC_LOST_DEVICE, newpath, NULL);
1563                 xpt_free_path(newpath);
1564                 break;
1565         }
1566         case CAM_REQ_INVALID:
1567         case CAM_PATH_INVALID:
1568         case CAM_DEV_NOT_THERE:
1569         case CAM_NO_HBA:
1570         case CAM_PROVIDE_FAIL:
1571         case CAM_REQ_TOO_BIG:
1572                 error = EINVAL;
1573                 break;
1574         case CAM_SCSI_BUS_RESET:
1575         case CAM_BDR_SENT:
1576                 /*
1577                  * Commands that repeatedly timeout and cause these
1578                  * kinds of error recovery actions, should return
1579                  * CAM_CMD_TIMEOUT, which allows us to safely assume
1580                  * that this command was an innocent bystander to
1581                  * these events and should be unconditionally
1582                  * retried.
1583                  */
1584                 /* FALLTHROUGH */
1585         case CAM_REQUEUE_REQ:
1586                 /* Unconditional requeue */
1587                 error = ERESTART;
1588                 break;
1589         case CAM_RESRC_UNAVAIL:
1590         case CAM_BUSY:
1591                 /* timeout??? */
1592         default:
1593                 /* decrement the number of retries */
1594                 if (ccb->ccb_h.retry_count > 0) {
1595                         ccb->ccb_h.retry_count--;
1596                         error = ERESTART;
1597                 } else {
1598                         error = EIO;
1599                         action_string = "Retries Exhausted";
1600                 }
1601                 break;
1602         }
1603
1604         /* Attempt a retry */
1605         if (error == ERESTART || error == 0) {  
1606                 if (frozen != 0)
1607                         ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1608
1609                 if (error == ERESTART) {
1610                         action_string = "Retrying Command";
1611                         xpt_action(ccb);
1612                 }
1613                 
1614                 if (frozen != 0)
1615                         cam_release_devq(ccb->ccb_h.path,
1616                                          relsim_flags,
1617                                          openings,
1618                                          timeout,
1619                                          /*getcount_only*/0);
1620         }
1621
1622         /*
1623          * If we have an error and are booting verbosely, whine
1624          * *unless* this was a non-retryable selection timeout.
1625          */
1626         if (error != 0 && bootverbose &&
1627             !(status == CAM_SEL_TIMEOUT && (camflags & CAM_RETRY_SELTO) == 0)) {
1628
1629
1630                 if (action_string == NULL)
1631                         action_string = "Unretryable Error";
1632                 if (error != ERESTART) {
1633                         xpt_print_path(ccb->ccb_h.path);
1634                         kprintf("error %d\n", error);
1635                 }
1636                 xpt_print_path(ccb->ccb_h.path);
1637                 kprintf("%s\n", action_string);
1638         }
1639
1640         return (error);
1641 }