2 * Common functions for CAM "type" (peripheral) drivers.
4 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
6 * Copyright (c) 1997, 1998 Justin T. Gibbs.
7 * Copyright (c) 1997, 1998, 1999, 2000 Kenneth D. Merry.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
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>
43 #include <sys/mutex.h>
46 #include <sys/devicestat.h>
49 #include <sys/sysctl.h>
51 #include <vm/vm_extern.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>
61 #include <cam/scsi/scsi_all.h>
62 #include <cam/scsi/scsi_message.h>
63 #include <cam/scsi/scsi_pass.h>
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,
69 static u_int camperiphunit(struct periph_driver *p_drv,
70 path_id_t pathid, target_id_t target,
72 static void camperiphdone(struct cam_periph *periph,
74 static void camperiphfree(struct cam_periph *periph);
75 static int camperiphscsistatuserror(union ccb *ccb,
78 u_int32_t sense_flags,
80 u_int32_t *relsim_flags,
83 const char **action_string);
84 static int camperiphscsisenseerror(union ccb *ccb,
87 u_int32_t sense_flags,
89 u_int32_t *relsim_flags,
92 const char **action_string);
93 static void cam_periph_devctl_notify(union ccb *ccb);
95 static int nperiph_drivers;
96 static int initialized = 0;
97 struct periph_driver **periph_drivers;
99 static MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
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);
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");
113 periphdriver_register(void *data)
115 struct periph_driver *drv = (struct periph_driver *)data;
116 struct periph_driver **newdrivers, **old;
120 ndrivers = nperiph_drivers + 2;
121 newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
124 if (ndrivers != nperiph_drivers + 2) {
126 * Lost race against itself; go around.
129 free(newdrivers, M_CAMPERIPH);
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;
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) ||
150 periphdriver_unregister(void *data)
152 struct periph_driver *drv = (struct periph_driver *)data;
155 /* If driver marked as early or it is late now, deinitialize it. */
156 if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
158 if (drv->deinit == NULL) {
159 printf("CAM periph driver '%s' doesn't have deinit.\n",
163 error = drv->deinit();
169 for (n = 0; n < nperiph_drivers && periph_drivers[n] != drv; n++)
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;
182 periphdriver_init(int level)
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)();
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)
201 struct periph_driver **p_drv;
203 struct cam_periph *periph;
204 struct cam_periph *cur_periph;
206 target_id_t target_id;
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.
219 if ((periph = cam_periph_find(path, name)) != NULL) {
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);
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,
234 return (CAM_REQ_INVALID);
237 periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
241 return (CAM_RESRC_UNAVAIL);
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;
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. */
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)
266 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
267 if (strcmp((*p_drv)->driver_name, name) == 0)
270 if (*p_drv == NULL) {
271 printf("cam_periph_alloc: invalid periph name '%s'\n", name);
273 xpt_free_path(periph->path);
274 free(periph, M_CAMPERIPH);
275 return (CAM_REQ_INVALID);
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);
286 TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
287 (*p_drv)->generation++;
293 status = xpt_add_periph(periph);
294 if (status != CAM_REQ_CMP)
298 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
300 status = periph_ctor(periph, arg);
302 if (status == CAM_REQ_CMP)
306 switch (init_level) {
308 /* Initialized successfully */
311 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
312 xpt_remove_periph(periph);
316 TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
318 xpt_free_path(periph->path);
321 free(periph, M_CAMPERIPH);
324 /* No cleanup to perform. */
327 panic("%s: Unknown init level", __func__);
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.
338 cam_periph_find(struct cam_path *path, char *name)
340 struct periph_driver **p_drv;
341 struct cam_periph *periph;
344 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
346 if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
349 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
350 if (xpt_path_comp(periph->path, path) == 0) {
352 cam_periph_assert(periph, MA_OWNED);
366 * Find peripheral driver instances attached to the specified path.
369 cam_periph_list(struct cam_path *path, struct sbuf *sb)
371 struct sbuf local_sb;
372 struct periph_driver **p_drv;
373 struct cam_periph *periph;
379 sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
382 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
384 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
385 if (xpt_path_comp(periph->path, path) != 0)
388 if (sbuf_len(&local_sb) != 0)
389 sbuf_cat(&local_sb, ",");
391 sbuf_printf(&local_sb, "%s%d", periph->periph_name,
392 periph->unit_number);
394 if (sbuf_error(&local_sb) == ENOMEM) {
397 sbuf_delete(&local_sb);
404 sbuf_finish(&local_sb);
405 if (sbuf_len(sb) != 0)
407 sbuf_cat(sb, sbuf_data(&local_sb));
408 sbuf_delete(&local_sb);
413 cam_periph_acquire(struct cam_periph *periph)
422 if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
432 cam_periph_doacquire(struct cam_periph *periph)
436 KASSERT(periph->refcount >= 1,
437 ("cam_periph_doacquire() with refcount == %d", periph->refcount));
443 cam_periph_release_locked_buses(struct cam_periph *periph)
446 cam_periph_assert(periph, MA_OWNED);
447 KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
448 if (--periph->refcount == 0)
449 camperiphfree(periph);
453 cam_periph_release_locked(struct cam_periph *periph)
460 cam_periph_release_locked_buses(periph);
465 cam_periph_release(struct cam_periph *periph)
472 cam_periph_assert(periph, MA_NOTOWNED);
473 mtx = cam_periph_mtx(periph);
475 cam_periph_release_locked(periph);
480 * hold/unhold act as mutual exclusion for sections of the code that
481 * need to sleep and want to make sure that other sections that
482 * will interfere are held off. This only protects exclusive sections
486 cam_periph_hold(struct cam_periph *periph, int priority)
491 * Increment the reference count on the peripheral
492 * while we wait for our lock attempt to succeed
493 * to ensure the peripheral doesn't disappear out
494 * from user us while we sleep.
497 if (cam_periph_acquire(periph) != 0)
500 cam_periph_assert(periph, MA_OWNED);
501 while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
502 periph->flags |= CAM_PERIPH_LOCK_WANTED;
503 if ((error = cam_periph_sleep(periph, periph, priority,
504 "caplck", 0)) != 0) {
505 cam_periph_release_locked(periph);
508 if (periph->flags & CAM_PERIPH_INVALID) {
509 cam_periph_release_locked(periph);
514 periph->flags |= CAM_PERIPH_LOCKED;
519 cam_periph_unhold(struct cam_periph *periph)
522 cam_periph_assert(periph, MA_OWNED);
524 periph->flags &= ~CAM_PERIPH_LOCKED;
525 if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
526 periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
530 cam_periph_release_locked(periph);
534 * Look for the next unit number that is not currently in use for this
535 * peripheral type starting at "newunit". Also exclude unit numbers that
536 * are reserved by for future "hardwiring" unless we already know that this
537 * is a potential wired device. Only assume that the device is "wired" the
538 * first time through the loop since after that we'll be looking at unit
539 * numbers that did not match a wiring entry.
542 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
543 path_id_t pathid, target_id_t target, lun_id_t lun)
545 struct cam_periph *periph;
547 int i, val, dunit, r;
548 const char *dname, *strval;
550 periph_name = p_drv->driver_name;
553 for (periph = TAILQ_FIRST(&p_drv->units);
554 periph != NULL && periph->unit_number != newunit;
555 periph = TAILQ_NEXT(periph, unit_links))
558 if (periph != NULL && periph->unit_number == newunit) {
560 xpt_print(periph->path, "Duplicate Wired "
562 xpt_print(periph->path, "Second device (%s "
563 "device at scbus%d target %d lun %d) will "
564 "not be wired\n", periph_name, pathid,
574 * Don't match entries like "da 4" as a wired down
575 * device, but do match entries like "da 4 target 5"
576 * or even "da 4 scbus 1".
581 r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
584 /* if no "target" and no specific scbus, skip */
585 if (resource_int_value(dname, dunit, "target", &val) &&
586 (resource_string_value(dname, dunit, "at",&strval)||
587 strcmp(strval, "scbus") == 0))
589 if (newunit == dunit)
599 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
600 target_id_t target, lun_id_t lun)
603 int wired, i, val, dunit;
604 const char *dname, *strval;
605 char pathbuf[32], *periph_name;
607 periph_name = p_drv->driver_name;
608 snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
612 for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
614 if (resource_string_value(dname, dunit, "at", &strval) == 0) {
615 if (strcmp(strval, pathbuf) != 0)
619 if (resource_int_value(dname, dunit, "target", &val) == 0) {
624 if (resource_int_value(dname, dunit, "lun", &val) == 0) {
636 * Either start from 0 looking for the next unit or from
637 * the unit number given in the resource config. This way,
638 * if we have wildcard matches, we don't return the same
641 unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
647 cam_periph_invalidate(struct cam_periph *periph)
650 cam_periph_assert(periph, MA_OWNED);
652 * We only call this routine the first time a peripheral is
655 if ((periph->flags & CAM_PERIPH_INVALID) != 0)
658 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
659 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting) {
663 sbuf_new(&sb, buffer, 160, SBUF_FIXEDLEN);
664 xpt_denounce_periph_sbuf(periph, &sb);
668 periph->flags |= CAM_PERIPH_INVALID;
669 periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
670 if (periph->periph_oninval != NULL)
671 periph->periph_oninval(periph);
672 cam_periph_release_locked(periph);
676 camperiphfree(struct cam_periph *periph)
678 struct periph_driver **p_drv;
679 struct periph_driver *drv;
681 cam_periph_assert(periph, MA_OWNED);
682 KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
683 periph->periph_name, periph->unit_number));
684 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
685 if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
688 if (*p_drv == NULL) {
689 printf("camperiphfree: attempt to free non-existant periph\n");
693 * Cache a pointer to the periph_driver structure. If a
694 * periph_driver is added or removed from the array (see
695 * periphdriver_register()) while we drop the toplogy lock
696 * below, p_drv may change. This doesn't protect against this
697 * particular periph_driver going away. That will require full
698 * reference counting in the periph_driver infrastructure.
703 * We need to set this flag before dropping the topology lock, to
704 * let anyone who is traversing the list that this peripheral is
705 * about to be freed, and there will be no more reference count
708 periph->flags |= CAM_PERIPH_FREE;
711 * The peripheral destructor semantics dictate calling with only the
712 * SIM mutex held. Since it might sleep, it should not be called
713 * with the topology lock held.
718 * We need to call the peripheral destructor prior to removing the
719 * peripheral from the list. Otherwise, we risk running into a
720 * scenario where the peripheral unit number may get reused
721 * (because it has been removed from the list), but some resources
722 * used by the peripheral are still hanging around. In particular,
723 * the devfs nodes used by some peripherals like the pass(4) driver
724 * aren't fully cleaned up until the destructor is run. If the
725 * unit number is reused before the devfs instance is fully gone,
728 if (periph->periph_dtor != NULL)
729 periph->periph_dtor(periph);
732 * The peripheral list is protected by the topology lock.
736 TAILQ_REMOVE(&drv->units, periph, unit_links);
739 xpt_remove_periph(periph);
742 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting)
743 xpt_print(periph->path, "Periph destroyed\n");
745 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
747 if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
751 switch (periph->deferred_ac) {
752 case AC_FOUND_DEVICE:
753 ccb.ccb_h.func_code = XPT_GDEV_TYPE;
754 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
758 case AC_PATH_REGISTERED:
759 xpt_path_inq(&ccb.cpi, periph->path);
766 periph->deferred_callback(NULL, periph->deferred_ac,
769 xpt_free_path(periph->path);
770 free(periph, M_CAMPERIPH);
775 * Map user virtual pointers into kernel virtual address space, so we can
776 * access the memory. This is now a generic function that centralizes most
777 * of the sanity checks on the data flags, if any.
778 * This also only works for up to MAXPHYS memory. Since we use
779 * buffers to map stuff in and out, we're limited to the buffer size.
782 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo,
786 u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
787 u_int32_t lengths[CAM_PERIPH_MAXMAPS];
788 u_int32_t dirs[CAM_PERIPH_MAXMAPS];
790 bzero(mapinfo, sizeof(*mapinfo));
792 maxmap = DFLTPHYS; /* traditional default */
793 else if (maxmap > MAXPHYS)
794 maxmap = MAXPHYS; /* for safety */
795 switch(ccb->ccb_h.func_code) {
797 if (ccb->cdm.match_buf_len == 0) {
798 printf("cam_periph_mapmem: invalid match buffer "
802 if (ccb->cdm.pattern_buf_len > 0) {
803 data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
804 lengths[0] = ccb->cdm.pattern_buf_len;
805 dirs[0] = CAM_DIR_OUT;
806 data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
807 lengths[1] = ccb->cdm.match_buf_len;
808 dirs[1] = CAM_DIR_IN;
811 data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
812 lengths[0] = ccb->cdm.match_buf_len;
813 dirs[0] = CAM_DIR_IN;
817 * This request will not go to the hardware, no reason
818 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
823 case XPT_CONT_TARGET_IO:
824 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
826 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
828 data_ptrs[0] = &ccb->csio.data_ptr;
829 lengths[0] = ccb->csio.dxfer_len;
830 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
834 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
836 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
838 data_ptrs[0] = &ccb->ataio.data_ptr;
839 lengths[0] = ccb->ataio.dxfer_len;
840 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
844 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
846 /* Two mappings: one for cmd->data and one for cmd->data->data */
847 data_ptrs[0] = (unsigned char **)&ccb->mmcio.cmd.data;
848 lengths[0] = sizeof(struct mmc_data *);
849 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
850 data_ptrs[1] = (unsigned char **)&ccb->mmcio.cmd.data->data;
851 lengths[1] = ccb->mmcio.cmd.data->len;
852 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
856 data_ptrs[0] = &ccb->smpio.smp_request;
857 lengths[0] = ccb->smpio.smp_request_len;
858 dirs[0] = CAM_DIR_OUT;
859 data_ptrs[1] = &ccb->smpio.smp_response;
860 lengths[1] = ccb->smpio.smp_response_len;
861 dirs[1] = CAM_DIR_IN;
866 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
868 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
870 data_ptrs[0] = &ccb->nvmeio.data_ptr;
871 lengths[0] = ccb->nvmeio.dxfer_len;
872 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
875 case XPT_DEV_ADVINFO:
876 if (ccb->cdai.bufsiz == 0)
879 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
880 lengths[0] = ccb->cdai.bufsiz;
881 dirs[0] = CAM_DIR_IN;
885 * This request will not go to the hardware, no reason
886 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
892 break; /* NOTREACHED */
896 * Check the transfer length and permissions first, so we don't
897 * have to unmap any previously mapped buffers.
899 for (i = 0; i < numbufs; i++) {
902 * The userland data pointer passed in may not be page
903 * aligned. vmapbuf() truncates the address to a page
904 * boundary, so if the address isn't page aligned, we'll
905 * need enough space for the given transfer length, plus
906 * whatever extra space is necessary to make it to the page
910 (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)) > maxmap){
911 printf("cam_periph_mapmem: attempt to map %lu bytes, "
912 "which is greater than %lu\n",
914 (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK)),
921 * This keeps the kernel stack of current thread from getting
922 * swapped. In low-memory situations where the kernel stack might
923 * otherwise get swapped out, this holds it and allows the thread
924 * to make progress and release the kernel mapped pages sooner.
926 * XXX KDM should I use P_NOSWAP instead?
930 for (i = 0; i < numbufs; i++) {
932 /* Save the user's data address. */
933 mapinfo->orig[i] = *data_ptrs[i];
936 * For small buffers use malloc+copyin/copyout instead of
937 * mapping to KVA to avoid expensive TLB shootdowns. For
938 * small allocations malloc is backed by UMA, and so much
939 * cheaper on SMP systems.
941 if (lengths[i] <= periph_mapmem_thresh &&
942 ccb->ccb_h.func_code != XPT_MMC_IO) {
943 *data_ptrs[i] = malloc(lengths[i], M_CAMPERIPH,
945 if (dirs[i] != CAM_DIR_IN) {
946 if (copyin(mapinfo->orig[i], *data_ptrs[i],
948 free(*data_ptrs[i], M_CAMPERIPH);
949 *data_ptrs[i] = mapinfo->orig[i];
953 bzero(*data_ptrs[i], lengths[i]);
960 mapinfo->bp[i] = getpbuf(NULL);
962 /* put our pointer in the data slot */
963 mapinfo->bp[i]->b_data = *data_ptrs[i];
965 /* set the transfer length, we know it's < MAXPHYS */
966 mapinfo->bp[i]->b_bufsize = lengths[i];
968 /* set the direction */
969 mapinfo->bp[i]->b_iocmd = (dirs[i] == CAM_DIR_OUT) ?
970 BIO_WRITE : BIO_READ;
973 * Map the buffer into kernel memory.
975 * Note that useracc() alone is not a sufficient test.
976 * vmapbuf() can still fail due to a smaller file mapped
977 * into a larger area of VM, or if userland races against
978 * vmapbuf() after the useracc() check.
980 if (vmapbuf(mapinfo->bp[i], 1) < 0) {
981 relpbuf(mapinfo->bp[i], NULL);
985 /* set our pointer to the new mapped area */
986 *data_ptrs[i] = mapinfo->bp[i]->b_data;
990 * Now that we've gotten this far, change ownership to the kernel
991 * of the buffers so that we don't run afoul of returning to user
992 * space with locks (on the buffer) held.
994 for (i = 0; i < numbufs; i++) {
996 BUF_KERNPROC(mapinfo->bp[i]);
999 mapinfo->num_bufs_used = numbufs;
1003 for (i--; i >= 0; i--) {
1004 if (mapinfo->bp[i]) {
1005 vunmapbuf(mapinfo->bp[i]);
1006 relpbuf(mapinfo->bp[i], NULL);
1008 free(*data_ptrs[i], M_CAMPERIPH);
1009 *data_ptrs[i] = mapinfo->orig[i];
1016 * Unmap memory segments mapped into kernel virtual address space by
1017 * cam_periph_mapmem().
1020 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
1023 u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1024 u_int32_t lengths[CAM_PERIPH_MAXMAPS];
1025 u_int32_t dirs[CAM_PERIPH_MAXMAPS];
1027 if (mapinfo->num_bufs_used <= 0) {
1028 /* nothing to free and the process wasn't held. */
1032 switch (ccb->ccb_h.func_code) {
1034 if (ccb->cdm.pattern_buf_len > 0) {
1035 data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1036 lengths[0] = ccb->cdm.pattern_buf_len;
1037 dirs[0] = CAM_DIR_OUT;
1038 data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1039 lengths[1] = ccb->cdm.match_buf_len;
1040 dirs[1] = CAM_DIR_IN;
1043 data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1044 lengths[0] = ccb->cdm.match_buf_len;
1045 dirs[0] = CAM_DIR_IN;
1050 case XPT_CONT_TARGET_IO:
1051 data_ptrs[0] = &ccb->csio.data_ptr;
1052 lengths[0] = ccb->csio.dxfer_len;
1053 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1057 data_ptrs[0] = &ccb->ataio.data_ptr;
1058 lengths[0] = ccb->ataio.dxfer_len;
1059 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1063 data_ptrs[0] = (u_int8_t **)&ccb->mmcio.cmd.data;
1064 lengths[0] = sizeof(struct mmc_data *);
1065 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1066 data_ptrs[1] = (u_int8_t **)&ccb->mmcio.cmd.data->data;
1067 lengths[1] = ccb->mmcio.cmd.data->len;
1068 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
1072 data_ptrs[0] = &ccb->smpio.smp_request;
1073 lengths[0] = ccb->smpio.smp_request_len;
1074 dirs[0] = CAM_DIR_OUT;
1075 data_ptrs[1] = &ccb->smpio.smp_response;
1076 lengths[1] = ccb->smpio.smp_response_len;
1077 dirs[1] = CAM_DIR_IN;
1081 case XPT_NVME_ADMIN:
1082 data_ptrs[0] = &ccb->nvmeio.data_ptr;
1083 lengths[0] = ccb->nvmeio.dxfer_len;
1084 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1087 case XPT_DEV_ADVINFO:
1088 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1089 lengths[0] = ccb->cdai.bufsiz;
1090 dirs[0] = CAM_DIR_IN;
1094 /* allow ourselves to be swapped once again */
1097 break; /* NOTREACHED */
1100 for (i = 0; i < numbufs; i++) {
1101 if (mapinfo->bp[i]) {
1102 /* unmap the buffer */
1103 vunmapbuf(mapinfo->bp[i]);
1105 /* release the buffer */
1106 relpbuf(mapinfo->bp[i], NULL);
1108 if (dirs[i] != CAM_DIR_OUT) {
1109 copyout(*data_ptrs[i], mapinfo->orig[i],
1112 free(*data_ptrs[i], M_CAMPERIPH);
1115 /* Set the user's pointer back to the original value */
1116 *data_ptrs[i] = mapinfo->orig[i];
1119 /* allow ourselves to be swapped once again */
1124 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
1125 int (*error_routine)(union ccb *ccb,
1127 u_int32_t sense_flags))
1136 case CAMGETPASSTHRU:
1137 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1138 xpt_setup_ccb(&ccb->ccb_h,
1140 CAM_PRIORITY_NORMAL);
1141 ccb->ccb_h.func_code = XPT_GDEVLIST;
1144 * Basically, the point of this is that we go through
1145 * getting the list of devices, until we find a passthrough
1146 * device. In the current version of the CAM code, the
1147 * only way to determine what type of device we're dealing
1148 * with is by its name.
1150 while (found == 0) {
1151 ccb->cgdl.index = 0;
1152 ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1153 while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
1155 /* we want the next device in the list */
1157 if (strncmp(ccb->cgdl.periph_name,
1163 if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1165 ccb->cgdl.periph_name[0] = '\0';
1166 ccb->cgdl.unit_number = 0;
1171 /* copy the result back out */
1172 bcopy(ccb, addr, sizeof(union ccb));
1174 /* and release the ccb */
1175 xpt_release_ccb(ccb);
1186 cam_periph_done_panic(struct cam_periph *periph, union ccb *done_ccb)
1189 panic("%s: already done with ccb %p", __func__, done_ccb);
1193 cam_periph_done(struct cam_periph *periph, union ccb *done_ccb)
1196 /* Caller will release the CCB */
1197 xpt_path_assert(done_ccb->ccb_h.path, MA_OWNED);
1198 done_ccb->ccb_h.cbfcnp = cam_periph_done_panic;
1199 wakeup(&done_ccb->ccb_h.cbfcnp);
1203 cam_periph_ccbwait(union ccb *ccb)
1206 if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
1207 while (ccb->ccb_h.cbfcnp != cam_periph_done_panic)
1208 xpt_path_sleep(ccb->ccb_h.path, &ccb->ccb_h.cbfcnp,
1209 PRIBIO, "cbwait", 0);
1211 KASSERT(ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX &&
1212 (ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG,
1213 ("%s: proceeding with incomplete ccb: ccb=%p, func_code=%#x, "
1214 "status=%#x, index=%d", __func__, ccb, ccb->ccb_h.func_code,
1215 ccb->ccb_h.status, ccb->ccb_h.pinfo.index));
1219 * Dispatch a CCB and wait for it to complete. If the CCB has set a
1220 * callback function (ccb->ccb_h.cbfcnp), it will be overwritten and lost.
1223 cam_periph_runccb(union ccb *ccb,
1224 int (*error_routine)(union ccb *ccb,
1226 u_int32_t sense_flags),
1227 cam_flags camflags, u_int32_t sense_flags,
1230 struct bintime *starttime;
1231 struct bintime ltime;
1234 uint32_t timeout = 1;
1237 xpt_path_assert(ccb->ccb_h.path, MA_OWNED);
1238 KASSERT((ccb->ccb_h.flags & CAM_UNLOCKED) == 0,
1239 ("%s: ccb=%p, func_code=%#x, flags=%#x", __func__, ccb,
1240 ccb->ccb_h.func_code, ccb->ccb_h.flags));
1243 * If the user has supplied a stats structure, and if we understand
1244 * this particular type of ccb, record the transaction start.
1247 (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1248 ccb->ccb_h.func_code == XPT_ATA_IO ||
1249 ccb->ccb_h.func_code == XPT_NVME_IO)) {
1251 binuptime(starttime);
1252 devstat_start_transaction(ds, starttime);
1256 * We must poll the I/O while we're dumping. The scheduler is normally
1257 * stopped for dumping, except when we call doadump from ddb. While the
1258 * scheduler is running in this case, we still need to poll the I/O to
1259 * avoid sleeping waiting for the ccb to complete.
1261 * A panic triggered dump stops the scheduler, any callback from the
1262 * shutdown_post_sync event will run with the scheduler stopped, but
1263 * before we're officially dumping. To avoid hanging in adashutdown
1264 * initiated commands (or other similar situations), we have to test for
1265 * either SCHEDULER_STOPPED() here as well.
1267 * To avoid locking problems, dumping/polling callers must call
1268 * without a periph lock held.
1270 must_poll = dumping || SCHEDULER_STOPPED();
1271 ccb->ccb_h.cbfcnp = cam_periph_done;
1274 * If we're polling, then we need to ensure that we have ample resources
1275 * in the periph. cam_periph_error can reschedule the ccb by calling
1276 * xpt_action and returning ERESTART, so we have to effect the polling
1277 * in the do loop below.
1280 timeout = xpt_poll_setup(ccb);
1284 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1290 xpt_pollwait(ccb, timeout);
1291 timeout = ccb->ccb_h.timeout * 10;
1293 cam_periph_ccbwait(ccb);
1295 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1297 else if (error_routine != NULL) {
1298 ccb->ccb_h.cbfcnp = cam_periph_done;
1299 error = (*error_routine)(ccb, camflags, sense_flags);
1302 } while (error == ERESTART);
1305 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1306 cam_release_devq(ccb->ccb_h.path,
1307 /* relsim_flags */0,
1310 /* getcount_only */ FALSE);
1311 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1316 devstat_tag_type tag;
1319 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1320 bytes = ccb->csio.dxfer_len - ccb->csio.resid;
1321 tag = (devstat_tag_type)(ccb->csio.tag_action & 0x3);
1322 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1323 bytes = ccb->ataio.dxfer_len - ccb->ataio.resid;
1324 tag = (devstat_tag_type)0;
1325 } else if (ccb->ccb_h.func_code == XPT_NVME_IO) {
1326 bytes = ccb->nvmeio.dxfer_len; /* NB: resid no possible */
1327 tag = (devstat_tag_type)0;
1332 devstat_end_transaction(ds, bytes, tag,
1333 ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE) ?
1334 DEVSTAT_NO_DATA : (ccb->ccb_h.flags & CAM_DIR_OUT) ?
1335 DEVSTAT_WRITE : DEVSTAT_READ, NULL, starttime);
1342 cam_freeze_devq(struct cam_path *path)
1344 struct ccb_hdr ccb_h;
1346 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1347 xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1348 ccb_h.func_code = XPT_NOOP;
1349 ccb_h.flags = CAM_DEV_QFREEZE;
1350 xpt_action((union ccb *)&ccb_h);
1354 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1355 u_int32_t openings, u_int32_t arg,
1358 struct ccb_relsim crs;
1360 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1361 relsim_flags, openings, arg, getcount_only));
1362 xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1363 crs.ccb_h.func_code = XPT_REL_SIMQ;
1364 crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1365 crs.release_flags = relsim_flags;
1366 crs.openings = openings;
1367 crs.release_timeout = arg;
1368 xpt_action((union ccb *)&crs);
1369 return (crs.qfrozen_cnt);
1372 #define saved_ccb_ptr ppriv_ptr0
1374 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1376 union ccb *saved_ccb;
1378 struct scsi_start_stop_unit *scsi_cmd;
1379 int error = 0, error_code, sense_key, asc, ascq;
1381 scsi_cmd = (struct scsi_start_stop_unit *)
1382 &done_ccb->csio.cdb_io.cdb_bytes;
1383 status = done_ccb->ccb_h.status;
1385 if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1386 if (scsi_extract_sense_ccb(done_ccb,
1387 &error_code, &sense_key, &asc, &ascq)) {
1389 * If the error is "invalid field in CDB",
1390 * and the load/eject flag is set, turn the
1391 * flag off and try again. This is just in
1392 * case the drive in question barfs on the
1393 * load eject flag. The CAM code should set
1394 * the load/eject flag by default for
1397 if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1398 ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1399 (asc == 0x24) && (ascq == 0x00)) {
1400 scsi_cmd->how &= ~SSS_LOEJ;
1401 if (status & CAM_DEV_QFRZN) {
1402 cam_release_devq(done_ccb->ccb_h.path,
1404 done_ccb->ccb_h.status &=
1407 xpt_action(done_ccb);
1411 error = cam_periph_error(done_ccb, 0,
1412 SF_RETRY_UA | SF_NO_PRINT);
1413 if (error == ERESTART)
1415 if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1416 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1417 done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1421 * If we have successfully taken a device from the not
1422 * ready to ready state, re-scan the device and re-get
1423 * the inquiry information. Many devices (mostly disks)
1424 * don't properly report their inquiry information unless
1427 if (scsi_cmd->opcode == START_STOP_UNIT)
1428 xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1432 * After recovery action(s) completed, return to the original CCB.
1433 * If the recovery CCB has failed, considering its own possible
1434 * retries and recovery, assume we are back in state where we have
1435 * been originally, but without recovery hopes left. In such case,
1436 * after the final attempt below, we cancel any further retries,
1437 * blocking by that also any new recovery attempts for this CCB,
1438 * and the result will be the final one returned to the CCB owher.
1440 saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1441 bcopy(saved_ccb, done_ccb, sizeof(*done_ccb));
1442 xpt_free_ccb(saved_ccb);
1443 if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1444 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1446 done_ccb->ccb_h.retry_count = 0;
1447 xpt_action(done_ccb);
1450 /* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1451 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1455 * Generic Async Event handler. Peripheral drivers usually
1456 * filter out the events that require personal attention,
1457 * and leave the rest to this function.
1460 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1461 struct cam_path *path, void *arg)
1464 case AC_LOST_DEVICE:
1465 cam_periph_invalidate(periph);
1473 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1475 struct ccb_getdevstats cgds;
1477 xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1478 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1479 xpt_action((union ccb *)&cgds);
1480 cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1484 cam_periph_freeze_after_event(struct cam_periph *periph,
1485 struct timeval* event_time, u_int duration_ms)
1487 struct timeval delta;
1488 struct timeval duration_tv;
1490 if (!timevalisset(event_time))
1494 timevalsub(&delta, event_time);
1495 duration_tv.tv_sec = duration_ms / 1000;
1496 duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1497 if (timevalcmp(&delta, &duration_tv, <)) {
1498 timevalsub(&duration_tv, &delta);
1500 duration_ms = duration_tv.tv_sec * 1000;
1501 duration_ms += duration_tv.tv_usec / 1000;
1502 cam_freeze_devq(periph->path);
1503 cam_release_devq(periph->path,
1504 RELSIM_RELEASE_AFTER_TIMEOUT,
1506 /*timeout*/duration_ms,
1507 /*getcount_only*/0);
1513 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1514 cam_flags camflags, u_int32_t sense_flags,
1515 int *openings, u_int32_t *relsim_flags,
1516 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1518 struct cam_periph *periph;
1521 switch (ccb->csio.scsi_status) {
1522 case SCSI_STATUS_OK:
1523 case SCSI_STATUS_COND_MET:
1524 case SCSI_STATUS_INTERMED:
1525 case SCSI_STATUS_INTERMED_COND_MET:
1528 case SCSI_STATUS_CMD_TERMINATED:
1529 case SCSI_STATUS_CHECK_COND:
1530 error = camperiphscsisenseerror(ccb, orig_ccb,
1539 case SCSI_STATUS_QUEUE_FULL:
1542 struct ccb_getdevstats cgds;
1545 * First off, find out what the current
1546 * transaction counts are.
1548 xpt_setup_ccb(&cgds.ccb_h,
1550 CAM_PRIORITY_NORMAL);
1551 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1552 xpt_action((union ccb *)&cgds);
1555 * If we were the only transaction active, treat
1556 * the QUEUE FULL as if it were a BUSY condition.
1558 if (cgds.dev_active != 0) {
1562 * Reduce the number of openings to
1563 * be 1 less than the amount it took
1564 * to get a queue full bounded by the
1565 * minimum allowed tag count for this
1568 total_openings = cgds.dev_active + cgds.dev_openings;
1569 *openings = cgds.dev_active;
1570 if (*openings < cgds.mintags)
1571 *openings = cgds.mintags;
1572 if (*openings < total_openings)
1573 *relsim_flags = RELSIM_ADJUST_OPENINGS;
1576 * Some devices report queue full for
1577 * temporary resource shortages. For
1578 * this reason, we allow a minimum
1579 * tag count to be entered via a
1580 * quirk entry to prevent the queue
1581 * count on these devices from falling
1582 * to a pessimisticly low value. We
1583 * still wait for the next successful
1584 * completion, however, before queueing
1585 * more transactions to the device.
1587 *relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1591 *action &= ~SSQ_PRINT_SENSE;
1596 case SCSI_STATUS_BUSY:
1598 * Restart the queue after either another
1599 * command completes or a 1 second timeout.
1601 periph = xpt_path_periph(ccb->ccb_h.path);
1602 if (periph->flags & CAM_PERIPH_INVALID) {
1604 *action_string = "Periph was invalidated";
1605 } else if ((sense_flags & SF_RETRY_BUSY) != 0 ||
1606 ccb->ccb_h.retry_count > 0) {
1607 if ((sense_flags & SF_RETRY_BUSY) == 0)
1608 ccb->ccb_h.retry_count--;
1610 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1611 | RELSIM_RELEASE_AFTER_CMDCMPLT;
1615 *action_string = "Retries exhausted";
1618 case SCSI_STATUS_RESERV_CONFLICT:
1627 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1628 cam_flags camflags, u_int32_t sense_flags,
1629 int *openings, u_int32_t *relsim_flags,
1630 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1632 struct cam_periph *periph;
1633 union ccb *orig_ccb = ccb;
1634 int error, recoveryccb;
1636 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1637 if (ccb->ccb_h.func_code == XPT_SCSI_IO && ccb->csio.bio != NULL)
1638 biotrack(ccb->csio.bio, __func__);
1641 periph = xpt_path_periph(ccb->ccb_h.path);
1642 recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1643 if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1645 * If error recovery is already in progress, don't attempt
1646 * to process this error, but requeue it unconditionally
1647 * and attempt to process it once error recovery has
1648 * completed. This failed command is probably related to
1649 * the error that caused the currently active error recovery
1650 * action so our current recovery efforts should also
1651 * address this command. Be aware that the error recovery
1652 * code assumes that only one recovery action is in progress
1653 * on a particular peripheral instance at any given time
1654 * (e.g. only one saved CCB for error recovery) so it is
1655 * imperitive that we don't violate this assumption.
1658 *action &= ~SSQ_PRINT_SENSE;
1660 scsi_sense_action err_action;
1661 struct ccb_getdev cgd;
1664 * Grab the inquiry data for this device.
1666 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1667 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1668 xpt_action((union ccb *)&cgd);
1670 err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1672 error = err_action & SS_ERRMASK;
1675 * Do not autostart sequential access devices
1676 * to avoid unexpected tape loading.
1678 if ((err_action & SS_MASK) == SS_START &&
1679 SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1680 *action_string = "Will not autostart a "
1681 "sequential access device";
1682 goto sense_error_done;
1686 * Avoid recovery recursion if recovery action is the same.
1688 if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1689 if (((err_action & SS_MASK) == SS_START &&
1690 ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1691 ((err_action & SS_MASK) == SS_TUR &&
1692 (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1693 err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1694 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1700 * If the recovery action will consume a retry,
1701 * make sure we actually have retries available.
1703 if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1704 if (ccb->ccb_h.retry_count > 0 &&
1705 (periph->flags & CAM_PERIPH_INVALID) == 0)
1706 ccb->ccb_h.retry_count--;
1708 *action_string = "Retries exhausted";
1709 goto sense_error_done;
1713 if ((err_action & SS_MASK) >= SS_START) {
1715 * Do common portions of commands that
1716 * use recovery CCBs.
1718 orig_ccb = xpt_alloc_ccb_nowait();
1719 if (orig_ccb == NULL) {
1720 *action_string = "Can't allocate recovery CCB";
1721 goto sense_error_done;
1724 * Clear freeze flag for original request here, as
1725 * this freeze will be dropped as part of ERESTART.
1727 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1728 bcopy(ccb, orig_ccb, sizeof(*orig_ccb));
1731 switch (err_action & SS_MASK) {
1733 *action_string = "No recovery action needed";
1737 *action_string = "Retrying command (per sense data)";
1741 *action_string = "Unretryable error";
1748 * Send a start unit command to the device, and
1749 * then retry the command.
1751 *action_string = "Attempting to start unit";
1752 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1755 * Check for removable media and set
1756 * load/eject flag appropriately.
1758 if (SID_IS_REMOVABLE(&cgd.inq_data))
1763 scsi_start_stop(&ccb->csio,
1777 * Send a Test Unit Ready to the device.
1778 * If the 'many' flag is set, we send 120
1779 * test unit ready commands, one every half
1780 * second. Otherwise, we just send one TUR.
1781 * We only want to do this if the retry
1782 * count has not been exhausted.
1786 if ((err_action & SSQ_MANY) != 0) {
1787 *action_string = "Polling device for readiness";
1790 *action_string = "Testing device for readiness";
1793 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1794 scsi_test_unit_ready(&ccb->csio,
1802 * Accomplish our 500ms delay by deferring
1803 * the release of our device queue appropriately.
1805 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1810 panic("Unhandled error action %x", err_action);
1813 if ((err_action & SS_MASK) >= SS_START) {
1815 * Drop the priority, so that the recovery
1816 * CCB is the first to execute. Freeze the queue
1817 * after this command is sent so that we can
1818 * restore the old csio and have it queued in
1819 * the proper order before we release normal
1820 * transactions to the device.
1822 ccb->ccb_h.pinfo.priority--;
1823 ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1824 ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1830 *action = err_action;
1836 * Generic error handler. Peripheral drivers usually filter
1837 * out the errors that they handle in a unique manner, then
1838 * call this function.
1841 cam_periph_error(union ccb *ccb, cam_flags camflags,
1842 u_int32_t sense_flags)
1844 struct cam_path *newpath;
1845 union ccb *orig_ccb, *scan_ccb;
1846 struct cam_periph *periph;
1847 const char *action_string;
1849 int frozen, error, openings, devctl_err;
1850 u_int32_t action, relsim_flags, timeout;
1852 action = SSQ_PRINT_SENSE;
1853 periph = xpt_path_periph(ccb->ccb_h.path);
1854 action_string = NULL;
1855 status = ccb->ccb_h.status;
1856 frozen = (status & CAM_DEV_QFRZN) != 0;
1857 status &= CAM_STATUS_MASK;
1858 devctl_err = openings = relsim_flags = timeout = 0;
1861 /* Filter the errors that should be reported via devctl */
1862 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1863 case CAM_CMD_TIMEOUT:
1864 case CAM_REQ_ABORTED:
1865 case CAM_REQ_CMP_ERR:
1866 case CAM_REQ_TERMIO:
1867 case CAM_UNREC_HBA_ERROR:
1868 case CAM_DATA_RUN_ERR:
1869 case CAM_SCSI_STATUS_ERROR:
1870 case CAM_ATA_STATUS_ERROR:
1871 case CAM_SMP_STATUS_ERROR:
1881 action &= ~SSQ_PRINT_SENSE;
1883 case CAM_SCSI_STATUS_ERROR:
1884 error = camperiphscsistatuserror(ccb, &orig_ccb,
1885 camflags, sense_flags, &openings, &relsim_flags,
1886 &timeout, &action, &action_string);
1888 case CAM_AUTOSENSE_FAIL:
1889 error = EIO; /* we have to kill the command */
1893 case CAM_MSG_REJECT_REC:
1894 /* XXX Don't know that these are correct */
1897 case CAM_SEL_TIMEOUT:
1898 if ((camflags & CAM_RETRY_SELTO) != 0) {
1899 if (ccb->ccb_h.retry_count > 0 &&
1900 (periph->flags & CAM_PERIPH_INVALID) == 0) {
1901 ccb->ccb_h.retry_count--;
1905 * Wait a bit to give the device
1906 * time to recover before we try again.
1908 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1909 timeout = periph_selto_delay;
1912 action_string = "Retries exhausted";
1915 case CAM_DEV_NOT_THERE:
1919 case CAM_REQ_INVALID:
1920 case CAM_PATH_INVALID:
1922 case CAM_PROVIDE_FAIL:
1923 case CAM_REQ_TOO_BIG:
1924 case CAM_LUN_INVALID:
1925 case CAM_TID_INVALID:
1926 case CAM_FUNC_NOTAVAIL:
1929 case CAM_SCSI_BUS_RESET:
1932 * Commands that repeatedly timeout and cause these
1933 * kinds of error recovery actions, should return
1934 * CAM_CMD_TIMEOUT, which allows us to safely assume
1935 * that this command was an innocent bystander to
1936 * these events and should be unconditionally
1939 case CAM_REQUEUE_REQ:
1940 /* Unconditional requeue if device is still there */
1941 if (periph->flags & CAM_PERIPH_INVALID) {
1942 action_string = "Periph was invalidated";
1944 } else if (sense_flags & SF_NO_RETRY) {
1946 action_string = "Retry was blocked";
1949 action &= ~SSQ_PRINT_SENSE;
1952 case CAM_RESRC_UNAVAIL:
1953 /* Wait a bit for the resource shortage to abate. */
1954 timeout = periph_noresrc_delay;
1958 /* Wait a bit for the busy condition to abate. */
1959 timeout = periph_busy_delay;
1961 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1963 case CAM_ATA_STATUS_ERROR:
1964 case CAM_REQ_CMP_ERR:
1965 case CAM_CMD_TIMEOUT:
1966 case CAM_UNEXP_BUSFREE:
1967 case CAM_UNCOR_PARITY:
1968 case CAM_DATA_RUN_ERR:
1970 if (periph->flags & CAM_PERIPH_INVALID) {
1972 action_string = "Periph was invalidated";
1973 } else if (ccb->ccb_h.retry_count == 0) {
1975 action_string = "Retries exhausted";
1976 } else if (sense_flags & SF_NO_RETRY) {
1978 action_string = "Retry was blocked";
1980 ccb->ccb_h.retry_count--;
1986 if ((sense_flags & SF_PRINT_ALWAYS) ||
1987 CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
1988 action |= SSQ_PRINT_SENSE;
1989 else if (sense_flags & SF_NO_PRINT)
1990 action &= ~SSQ_PRINT_SENSE;
1991 if ((action & SSQ_PRINT_SENSE) != 0)
1992 cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1993 if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
1994 if (error != ERESTART) {
1995 if (action_string == NULL)
1996 action_string = "Unretryable error";
1997 xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
1998 error, action_string);
1999 } else if (action_string != NULL)
2000 xpt_print(ccb->ccb_h.path, "%s\n", action_string);
2002 xpt_print(ccb->ccb_h.path,
2003 "Retrying command, %d more tries remain\n",
2004 ccb->ccb_h.retry_count);
2008 if (devctl_err && (error != 0 || (action & SSQ_PRINT_SENSE) != 0))
2009 cam_periph_devctl_notify(orig_ccb);
2011 if ((action & SSQ_LOST) != 0) {
2015 * For a selection timeout, we consider all of the LUNs on
2016 * the target to be gone. If the status is CAM_DEV_NOT_THERE,
2017 * then we only get rid of the device(s) specified by the
2018 * path in the original CCB.
2020 if (status == CAM_SEL_TIMEOUT)
2021 lun_id = CAM_LUN_WILDCARD;
2023 lun_id = xpt_path_lun_id(ccb->ccb_h.path);
2025 /* Should we do more if we can't create the path?? */
2026 if (xpt_create_path(&newpath, periph,
2027 xpt_path_path_id(ccb->ccb_h.path),
2028 xpt_path_target_id(ccb->ccb_h.path),
2029 lun_id) == CAM_REQ_CMP) {
2032 * Let peripheral drivers know that this
2033 * device has gone away.
2035 xpt_async(AC_LOST_DEVICE, newpath, NULL);
2036 xpt_free_path(newpath);
2040 /* Broadcast UNIT ATTENTIONs to all periphs. */
2041 if ((action & SSQ_UA) != 0)
2042 xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
2044 /* Rescan target on "Reported LUNs data has changed" */
2045 if ((action & SSQ_RESCAN) != 0) {
2046 if (xpt_create_path(&newpath, NULL,
2047 xpt_path_path_id(ccb->ccb_h.path),
2048 xpt_path_target_id(ccb->ccb_h.path),
2049 CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
2051 scan_ccb = xpt_alloc_ccb_nowait();
2052 if (scan_ccb != NULL) {
2053 scan_ccb->ccb_h.path = newpath;
2054 scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
2055 scan_ccb->crcn.flags = 0;
2056 xpt_rescan(scan_ccb);
2059 "Can't allocate CCB to rescan target\n");
2060 xpt_free_path(newpath);
2065 /* Attempt a retry */
2066 if (error == ERESTART || error == 0) {
2068 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
2069 if (error == ERESTART)
2072 cam_release_devq(ccb->ccb_h.path,
2076 /*getcount_only*/0);
2082 #define CAM_PERIPH_DEVD_MSG_SIZE 256
2085 cam_periph_devctl_notify(union ccb *ccb)
2087 struct cam_periph *periph;
2088 struct ccb_getdev *cgd;
2090 int serr, sk, asc, ascq;
2093 sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT);
2097 sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN);
2099 periph = xpt_path_periph(ccb->ccb_h.path);
2100 sbuf_printf(&sb, "device=%s%d ", periph->periph_name,
2101 periph->unit_number);
2103 sbuf_printf(&sb, "serial=\"");
2104 if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) {
2105 xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path,
2106 CAM_PRIORITY_NORMAL);
2107 cgd->ccb_h.func_code = XPT_GDEV_TYPE;
2108 xpt_action((union ccb *)cgd);
2110 if (cgd->ccb_h.status == CAM_REQ_CMP)
2111 sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len);
2112 xpt_free_ccb((union ccb *)cgd);
2114 sbuf_printf(&sb, "\" ");
2115 sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status);
2117 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
2118 case CAM_CMD_TIMEOUT:
2119 sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout);
2122 case CAM_SCSI_STATUS_ERROR:
2123 sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status);
2124 if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq))
2125 sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ",
2126 serr, sk, asc, ascq);
2129 case CAM_ATA_STATUS_ERROR:
2130 sbuf_printf(&sb, "RES=\"");
2131 ata_res_sbuf(&ccb->ataio.res, &sb);
2132 sbuf_printf(&sb, "\" ");
2140 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2141 sbuf_printf(&sb, "CDB=\"");
2142 scsi_cdb_sbuf(scsiio_cdb_ptr(&ccb->csio), &sb);
2143 sbuf_printf(&sb, "\" ");
2144 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2145 sbuf_printf(&sb, "ACB=\"");
2146 ata_cmd_sbuf(&ccb->ataio.cmd, &sb);
2147 sbuf_printf(&sb, "\" ");
2150 if (sbuf_finish(&sb) == 0)
2151 devctl_notify("CAM", "periph", type, sbuf_data(&sb));
2153 free(sbmsg, M_CAMPERIPH);
2157 * Sysctl to force an invalidation of the drive right now. Can be
2158 * called with CTLFLAG_MPSAFE since we take periph lock.
2161 cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)
2163 struct cam_periph *periph;
2168 error = sysctl_handle_int(oidp, &value, 0, req);
2169 if (error != 0 || req->newptr == NULL || value != 1)
2172 cam_periph_lock(periph);
2173 cam_periph_invalidate(periph);
2174 cam_periph_unlock(periph);