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