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