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