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