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