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