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