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