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>
42 #include <sys/devctl.h>
44 #include <sys/mutex.h>
47 #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) {
220 if ((periph->flags & CAM_PERIPH_INVALID) != 0
221 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
222 periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
223 periph->deferred_callback = ac_callback;
224 periph->deferred_ac = code;
225 return (CAM_REQ_INPROG);
227 printf("cam_periph_alloc: attempt to re-allocate "
228 "valid device %s%d rejected flags %#x "
229 "refcount %d\n", periph->periph_name,
230 periph->unit_number, periph->flags,
233 return (CAM_REQ_INVALID);
236 periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
240 return (CAM_RESRC_UNAVAIL);
244 sim = xpt_path_sim(path);
245 path_id = xpt_path_path_id(path);
246 target_id = xpt_path_target_id(path);
247 lun_id = xpt_path_lun_id(path);
248 periph->periph_start = periph_start;
249 periph->periph_dtor = periph_dtor;
250 periph->periph_oninval = periph_oninvalidate;
252 periph->periph_name = name;
253 periph->scheduled_priority = CAM_PRIORITY_NONE;
254 periph->immediate_priority = CAM_PRIORITY_NONE;
255 periph->refcount = 1; /* Dropped by invalidation. */
257 SLIST_INIT(&periph->ccb_list);
258 status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
259 if (status != CAM_REQ_CMP)
264 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
265 if (strcmp((*p_drv)->driver_name, name) == 0)
268 if (*p_drv == NULL) {
269 printf("cam_periph_alloc: invalid periph name '%s'\n", name);
271 xpt_free_path(periph->path);
272 free(periph, M_CAMPERIPH);
273 return (CAM_REQ_INVALID);
275 periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id);
276 cur_periph = TAILQ_FIRST(&(*p_drv)->units);
277 while (cur_periph != NULL
278 && cur_periph->unit_number < periph->unit_number)
279 cur_periph = TAILQ_NEXT(cur_periph, unit_links);
280 if (cur_periph != NULL) {
281 KASSERT(cur_periph->unit_number != periph->unit_number, ("duplicate units on periph list"));
282 TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
284 TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
285 (*p_drv)->generation++;
291 status = xpt_add_periph(periph);
292 if (status != CAM_REQ_CMP)
296 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
298 status = periph_ctor(periph, arg);
300 if (status == CAM_REQ_CMP)
304 switch (init_level) {
306 /* Initialized successfully */
309 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
310 xpt_remove_periph(periph);
314 TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
316 xpt_free_path(periph->path);
319 free(periph, M_CAMPERIPH);
322 /* No cleanup to perform. */
325 panic("%s: Unknown init level", __func__);
331 * Find a peripheral structure with the specified path, target, lun,
332 * and (optionally) type. If the name is NULL, this function will return
333 * the first peripheral driver that matches the specified path.
336 cam_periph_find(struct cam_path *path, char *name)
338 struct periph_driver **p_drv;
339 struct cam_periph *periph;
342 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
343 if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
346 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
347 if (xpt_path_comp(periph->path, path) == 0) {
349 cam_periph_assert(periph, MA_OWNED);
363 * Find peripheral driver instances attached to the specified path.
366 cam_periph_list(struct cam_path *path, struct sbuf *sb)
368 struct sbuf local_sb;
369 struct periph_driver **p_drv;
370 struct cam_periph *periph;
376 sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
379 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
380 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
381 if (xpt_path_comp(periph->path, path) != 0)
384 if (sbuf_len(&local_sb) != 0)
385 sbuf_cat(&local_sb, ",");
387 sbuf_printf(&local_sb, "%s%d", periph->periph_name,
388 periph->unit_number);
390 if (sbuf_error(&local_sb) == ENOMEM) {
393 sbuf_delete(&local_sb);
400 sbuf_finish(&local_sb);
401 if (sbuf_len(sb) != 0)
403 sbuf_cat(sb, sbuf_data(&local_sb));
404 sbuf_delete(&local_sb);
409 cam_periph_acquire(struct cam_periph *periph)
418 if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
428 cam_periph_doacquire(struct cam_periph *periph)
432 KASSERT(periph->refcount >= 1,
433 ("cam_periph_doacquire() with refcount == %d", periph->refcount));
439 cam_periph_release_locked_buses(struct cam_periph *periph)
442 cam_periph_assert(periph, MA_OWNED);
443 KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
444 if (--periph->refcount == 0)
445 camperiphfree(periph);
449 cam_periph_release_locked(struct cam_periph *periph)
456 cam_periph_release_locked_buses(periph);
461 cam_periph_release(struct cam_periph *periph)
468 cam_periph_assert(periph, MA_NOTOWNED);
469 mtx = cam_periph_mtx(periph);
471 cam_periph_release_locked(periph);
476 * hold/unhold act as mutual exclusion for sections of the code that
477 * need to sleep and want to make sure that other sections that
478 * will interfere are held off. This only protects exclusive sections
482 cam_periph_hold(struct cam_periph *periph, int priority)
487 * Increment the reference count on the peripheral
488 * while we wait for our lock attempt to succeed
489 * to ensure the peripheral doesn't disappear out
490 * from user us while we sleep.
493 if (cam_periph_acquire(periph) != 0)
496 cam_periph_assert(periph, MA_OWNED);
497 while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
498 periph->flags |= CAM_PERIPH_LOCK_WANTED;
499 if ((error = cam_periph_sleep(periph, periph, priority,
500 "caplck", 0)) != 0) {
501 cam_periph_release_locked(periph);
504 if (periph->flags & CAM_PERIPH_INVALID) {
505 cam_periph_release_locked(periph);
510 periph->flags |= CAM_PERIPH_LOCKED;
515 cam_periph_unhold(struct cam_periph *periph)
518 cam_periph_assert(periph, MA_OWNED);
520 periph->flags &= ~CAM_PERIPH_LOCKED;
521 if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
522 periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
526 cam_periph_release_locked(periph);
530 * Look for the next unit number that is not currently in use for this
531 * peripheral type starting at "newunit". Also exclude unit numbers that
532 * are reserved by for future "hardwiring" unless we already know that this
533 * is a potential wired device. Only assume that the device is "wired" the
534 * first time through the loop since after that we'll be looking at unit
535 * numbers that did not match a wiring entry.
538 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, int wired,
539 path_id_t pathid, target_id_t target, lun_id_t lun)
541 struct cam_periph *periph;
543 int i, val, dunit, r;
544 const char *dname, *strval;
546 periph_name = p_drv->driver_name;
548 for (periph = TAILQ_FIRST(&p_drv->units);
549 periph != NULL && periph->unit_number != newunit;
550 periph = TAILQ_NEXT(periph, unit_links))
553 if (periph != NULL && periph->unit_number == newunit) {
555 xpt_print(periph->path, "Duplicate Wired "
557 xpt_print(periph->path, "Second device (%s "
558 "device at scbus%d target %d lun %d) will "
559 "not be wired\n", periph_name, pathid,
569 * Don't match entries like "da 4" as a wired down
570 * device, but do match entries like "da 4 target 5"
571 * or even "da 4 scbus 1".
576 r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
579 /* if no "target" and no specific scbus, skip */
580 if (resource_int_value(dname, dunit, "target", &val) &&
581 (resource_string_value(dname, dunit, "at",&strval)||
582 strcmp(strval, "scbus") == 0))
584 if (newunit == dunit)
594 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
595 target_id_t target, lun_id_t lun)
598 int wired, i, val, dunit;
599 const char *dname, *strval;
600 char pathbuf[32], *periph_name;
602 periph_name = p_drv->driver_name;
603 snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
607 for (wired = 0; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
609 if (resource_string_value(dname, dunit, "at", &strval) == 0) {
610 if (strcmp(strval, pathbuf) != 0)
614 if (resource_int_value(dname, dunit, "target", &val) == 0) {
619 if (resource_int_value(dname, dunit, "lun", &val) == 0) {
631 * Either start from 0 looking for the next unit or from
632 * the unit number given in the resource config. This way,
633 * if we have wildcard matches, we don't return the same
636 unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
642 cam_periph_invalidate(struct cam_periph *periph)
645 cam_periph_assert(periph, MA_OWNED);
647 * We only tear down the device the first time a peripheral is
650 if ((periph->flags & CAM_PERIPH_INVALID) != 0)
653 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
654 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting) {
658 sbuf_new(&sb, buffer, 160, SBUF_FIXEDLEN);
659 xpt_denounce_periph_sbuf(periph, &sb);
663 periph->flags |= CAM_PERIPH_INVALID;
664 periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
665 if (periph->periph_oninval != NULL)
666 periph->periph_oninval(periph);
667 cam_periph_release_locked(periph);
671 camperiphfree(struct cam_periph *periph)
673 struct periph_driver **p_drv;
674 struct periph_driver *drv;
676 cam_periph_assert(periph, MA_OWNED);
677 KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
678 periph->periph_name, periph->unit_number));
679 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
680 if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
683 if (*p_drv == NULL) {
684 printf("camperiphfree: attempt to free non-existant periph\n");
688 * Cache a pointer to the periph_driver structure. If a
689 * periph_driver is added or removed from the array (see
690 * periphdriver_register()) while we drop the toplogy lock
691 * below, p_drv may change. This doesn't protect against this
692 * particular periph_driver going away. That will require full
693 * reference counting in the periph_driver infrastructure.
698 * We need to set this flag before dropping the topology lock, to
699 * let anyone who is traversing the list that this peripheral is
700 * about to be freed, and there will be no more reference count
703 periph->flags |= CAM_PERIPH_FREE;
706 * The peripheral destructor semantics dictate calling with only the
707 * SIM mutex held. Since it might sleep, it should not be called
708 * with the topology lock held.
713 * We need to call the peripheral destructor prior to removing the
714 * peripheral from the list. Otherwise, we risk running into a
715 * scenario where the peripheral unit number may get reused
716 * (because it has been removed from the list), but some resources
717 * used by the peripheral are still hanging around. In particular,
718 * the devfs nodes used by some peripherals like the pass(4) driver
719 * aren't fully cleaned up until the destructor is run. If the
720 * unit number is reused before the devfs instance is fully gone,
723 if (periph->periph_dtor != NULL)
724 periph->periph_dtor(periph);
727 * The peripheral list is protected by the topology lock. We have to
728 * remove the periph from the drv list before we call deferred_ac. The
729 * AC_FOUND_DEVICE callback won't create a new periph if it's still there.
733 TAILQ_REMOVE(&drv->units, periph, unit_links);
736 xpt_remove_periph(periph);
739 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting)
740 xpt_print(periph->path, "Periph destroyed\n");
742 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
744 if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
748 switch (periph->deferred_ac) {
749 case AC_FOUND_DEVICE:
750 ccb.ccb_h.func_code = XPT_GDEV_TYPE;
751 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
755 case AC_PATH_REGISTERED:
756 xpt_path_inq(&ccb.cpi, periph->path);
763 periph->deferred_callback(NULL, periph->deferred_ac,
766 xpt_free_path(periph->path);
767 free(periph, M_CAMPERIPH);
772 * Map user virtual pointers into kernel virtual address space, so we can
773 * access the memory. This is now a generic function that centralizes most
774 * of the sanity checks on the data flags, if any.
775 * This also only works for up to MAXPHYS memory. Since we use
776 * buffers to map stuff in and out, we're limited to the buffer size.
779 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo,
783 u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
784 u_int32_t lengths[CAM_PERIPH_MAXMAPS];
785 u_int32_t dirs[CAM_PERIPH_MAXMAPS];
786 bool misaligned[CAM_PERIPH_MAXMAPS];
788 bzero(mapinfo, sizeof(*mapinfo));
790 maxmap = DFLTPHYS; /* traditional default */
791 else if (maxmap > MAXPHYS)
792 maxmap = MAXPHYS; /* for safety */
793 switch(ccb->ccb_h.func_code) {
795 if (ccb->cdm.match_buf_len == 0) {
796 printf("cam_periph_mapmem: invalid match buffer "
800 if (ccb->cdm.pattern_buf_len > 0) {
801 data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
802 lengths[0] = ccb->cdm.pattern_buf_len;
803 dirs[0] = CAM_DIR_OUT;
804 data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
805 lengths[1] = ccb->cdm.match_buf_len;
806 dirs[1] = CAM_DIR_IN;
809 data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
810 lengths[0] = ccb->cdm.match_buf_len;
811 dirs[0] = CAM_DIR_IN;
815 * This request will not go to the hardware, no reason
816 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
821 case XPT_CONT_TARGET_IO:
822 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
824 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
826 data_ptrs[0] = &ccb->csio.data_ptr;
827 lengths[0] = ccb->csio.dxfer_len;
828 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
832 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
834 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
836 data_ptrs[0] = &ccb->ataio.data_ptr;
837 lengths[0] = ccb->ataio.dxfer_len;
838 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
842 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
844 /* Two mappings: one for cmd->data and one for cmd->data->data */
845 data_ptrs[0] = (unsigned char **)&ccb->mmcio.cmd.data;
846 lengths[0] = sizeof(struct mmc_data *);
847 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
848 data_ptrs[1] = (unsigned char **)&ccb->mmcio.cmd.data->data;
849 lengths[1] = ccb->mmcio.cmd.data->len;
850 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
854 data_ptrs[0] = &ccb->smpio.smp_request;
855 lengths[0] = ccb->smpio.smp_request_len;
856 dirs[0] = CAM_DIR_OUT;
857 data_ptrs[1] = &ccb->smpio.smp_response;
858 lengths[1] = ccb->smpio.smp_response_len;
859 dirs[1] = CAM_DIR_IN;
864 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
866 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
868 data_ptrs[0] = &ccb->nvmeio.data_ptr;
869 lengths[0] = ccb->nvmeio.dxfer_len;
870 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
873 case XPT_DEV_ADVINFO:
874 if (ccb->cdai.bufsiz == 0)
877 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
878 lengths[0] = ccb->cdai.bufsiz;
879 dirs[0] = CAM_DIR_IN;
883 * This request will not go to the hardware, no reason
884 * to be so strict. vmapbuf() is able to map up to MAXPHYS.
890 break; /* NOTREACHED */
894 * Check the transfer length and permissions first, so we don't
895 * have to unmap any previously mapped buffers.
897 for (i = 0; i < numbufs; i++) {
898 if (lengths[i] > maxmap) {
899 printf("cam_periph_mapmem: attempt to map %lu bytes, "
900 "which is greater than %lu\n",
901 (long)(lengths[i]), (u_long)maxmap);
906 * The userland data pointer passed in may not be page
907 * aligned. vmapbuf() truncates the address to a page
908 * boundary, so if the address isn't page aligned, we'll
909 * need enough space for the given transfer length, plus
910 * whatever extra space is necessary to make it to the page
913 misaligned[i] = (lengths[i] +
914 (((vm_offset_t)(*data_ptrs[i])) & PAGE_MASK) > MAXPHYS);
918 * This keeps the kernel stack of current thread from getting
919 * swapped. In low-memory situations where the kernel stack might
920 * otherwise get swapped out, this holds it and allows the thread
921 * to make progress and release the kernel mapped pages sooner.
923 * XXX KDM should I use P_NOSWAP instead?
927 for (i = 0; i < numbufs; i++) {
928 /* Save the user's data address. */
929 mapinfo->orig[i] = *data_ptrs[i];
932 * For small buffers use malloc+copyin/copyout instead of
933 * mapping to KVA to avoid expensive TLB shootdowns. For
934 * small allocations malloc is backed by UMA, and so much
935 * cheaper on SMP systems.
937 if ((lengths[i] <= periph_mapmem_thresh || misaligned[i]) &&
938 ccb->ccb_h.func_code != XPT_MMC_IO) {
939 *data_ptrs[i] = malloc(lengths[i], M_CAMPERIPH,
941 if (dirs[i] != CAM_DIR_IN) {
942 if (copyin(mapinfo->orig[i], *data_ptrs[i],
944 free(*data_ptrs[i], M_CAMPERIPH);
945 *data_ptrs[i] = mapinfo->orig[i];
949 bzero(*data_ptrs[i], lengths[i]);
956 mapinfo->bp[i] = uma_zalloc(pbuf_zone, M_WAITOK);
958 /* put our pointer in the data slot */
959 mapinfo->bp[i]->b_data = *data_ptrs[i];
961 /* set the transfer length, we know it's < MAXPHYS */
962 mapinfo->bp[i]->b_bufsize = lengths[i];
964 /* set the direction */
965 mapinfo->bp[i]->b_iocmd = (dirs[i] == CAM_DIR_OUT) ?
966 BIO_WRITE : BIO_READ;
968 /* Map the buffer into kernel memory. */
969 if (vmapbuf(mapinfo->bp[i], 1) < 0) {
970 uma_zfree(pbuf_zone, mapinfo->bp[i]);
974 /* set our pointer to the new mapped area */
975 *data_ptrs[i] = mapinfo->bp[i]->b_data;
979 * Now that we've gotten this far, change ownership to the kernel
980 * of the buffers so that we don't run afoul of returning to user
981 * space with locks (on the buffer) held.
983 for (i = 0; i < numbufs; i++) {
985 BUF_KERNPROC(mapinfo->bp[i]);
988 mapinfo->num_bufs_used = numbufs;
992 for (i--; i >= 0; i--) {
993 if (mapinfo->bp[i]) {
994 vunmapbuf(mapinfo->bp[i]);
995 uma_zfree(pbuf_zone, mapinfo->bp[i]);
997 free(*data_ptrs[i], M_CAMPERIPH);
998 *data_ptrs[i] = mapinfo->orig[i];
1005 * Unmap memory segments mapped into kernel virtual address space by
1006 * cam_periph_mapmem().
1009 cam_periph_unmapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo)
1012 u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
1013 u_int32_t lengths[CAM_PERIPH_MAXMAPS];
1014 u_int32_t dirs[CAM_PERIPH_MAXMAPS];
1016 if (mapinfo->num_bufs_used <= 0) {
1017 /* nothing to free and the process wasn't held. */
1021 switch (ccb->ccb_h.func_code) {
1023 if (ccb->cdm.pattern_buf_len > 0) {
1024 data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
1025 lengths[0] = ccb->cdm.pattern_buf_len;
1026 dirs[0] = CAM_DIR_OUT;
1027 data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
1028 lengths[1] = ccb->cdm.match_buf_len;
1029 dirs[1] = CAM_DIR_IN;
1032 data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
1033 lengths[0] = ccb->cdm.match_buf_len;
1034 dirs[0] = CAM_DIR_IN;
1039 case XPT_CONT_TARGET_IO:
1040 data_ptrs[0] = &ccb->csio.data_ptr;
1041 lengths[0] = ccb->csio.dxfer_len;
1042 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1046 data_ptrs[0] = &ccb->ataio.data_ptr;
1047 lengths[0] = ccb->ataio.dxfer_len;
1048 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1052 data_ptrs[0] = (u_int8_t **)&ccb->mmcio.cmd.data;
1053 lengths[0] = sizeof(struct mmc_data *);
1054 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1055 data_ptrs[1] = (u_int8_t **)&ccb->mmcio.cmd.data->data;
1056 lengths[1] = ccb->mmcio.cmd.data->len;
1057 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
1061 data_ptrs[0] = &ccb->smpio.smp_request;
1062 lengths[0] = ccb->smpio.smp_request_len;
1063 dirs[0] = CAM_DIR_OUT;
1064 data_ptrs[1] = &ccb->smpio.smp_response;
1065 lengths[1] = ccb->smpio.smp_response_len;
1066 dirs[1] = CAM_DIR_IN;
1070 case XPT_NVME_ADMIN:
1071 data_ptrs[0] = &ccb->nvmeio.data_ptr;
1072 lengths[0] = ccb->nvmeio.dxfer_len;
1073 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
1076 case XPT_DEV_ADVINFO:
1077 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
1078 lengths[0] = ccb->cdai.bufsiz;
1079 dirs[0] = CAM_DIR_IN;
1083 /* allow ourselves to be swapped once again */
1086 break; /* NOTREACHED */
1089 for (i = 0; i < numbufs; i++) {
1090 if (mapinfo->bp[i]) {
1091 /* unmap the buffer */
1092 vunmapbuf(mapinfo->bp[i]);
1094 /* release the buffer */
1095 uma_zfree(pbuf_zone, mapinfo->bp[i]);
1097 if (dirs[i] != CAM_DIR_OUT) {
1098 copyout(*data_ptrs[i], mapinfo->orig[i],
1101 free(*data_ptrs[i], M_CAMPERIPH);
1104 /* Set the user's pointer back to the original value */
1105 *data_ptrs[i] = mapinfo->orig[i];
1108 /* allow ourselves to be swapped once again */
1113 cam_periph_ioctl(struct cam_periph *periph, u_long cmd, caddr_t addr,
1114 int (*error_routine)(union ccb *ccb,
1116 u_int32_t sense_flags))
1125 case CAMGETPASSTHRU:
1126 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1127 xpt_setup_ccb(&ccb->ccb_h,
1129 CAM_PRIORITY_NORMAL);
1130 ccb->ccb_h.func_code = XPT_GDEVLIST;
1133 * Basically, the point of this is that we go through
1134 * getting the list of devices, until we find a passthrough
1135 * device. In the current version of the CAM code, the
1136 * only way to determine what type of device we're dealing
1137 * with is by its name.
1139 while (found == 0) {
1140 ccb->cgdl.index = 0;
1141 ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1142 while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
1143 /* we want the next device in the list */
1145 if (strncmp(ccb->cgdl.periph_name,
1151 if ((ccb->cgdl.status == CAM_GDEVLIST_LAST_DEVICE) &&
1153 ccb->cgdl.periph_name[0] = '\0';
1154 ccb->cgdl.unit_number = 0;
1159 /* copy the result back out */
1160 bcopy(ccb, addr, sizeof(union ccb));
1162 /* and release the ccb */
1163 xpt_release_ccb(ccb);
1174 cam_periph_done_panic(struct cam_periph *periph, union ccb *done_ccb)
1177 panic("%s: already done with ccb %p", __func__, done_ccb);
1181 cam_periph_done(struct cam_periph *periph, union ccb *done_ccb)
1184 /* Caller will release the CCB */
1185 xpt_path_assert(done_ccb->ccb_h.path, MA_OWNED);
1186 done_ccb->ccb_h.cbfcnp = cam_periph_done_panic;
1187 wakeup(&done_ccb->ccb_h.cbfcnp);
1191 cam_periph_ccbwait(union ccb *ccb)
1194 if ((ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
1195 while (ccb->ccb_h.cbfcnp != cam_periph_done_panic)
1196 xpt_path_sleep(ccb->ccb_h.path, &ccb->ccb_h.cbfcnp,
1197 PRIBIO, "cbwait", 0);
1199 KASSERT(ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX &&
1200 (ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG,
1201 ("%s: proceeding with incomplete ccb: ccb=%p, func_code=%#x, "
1202 "status=%#x, index=%d", __func__, ccb, ccb->ccb_h.func_code,
1203 ccb->ccb_h.status, ccb->ccb_h.pinfo.index));
1207 * Dispatch a CCB and wait for it to complete. If the CCB has set a
1208 * callback function (ccb->ccb_h.cbfcnp), it will be overwritten and lost.
1211 cam_periph_runccb(union ccb *ccb,
1212 int (*error_routine)(union ccb *ccb,
1214 u_int32_t sense_flags),
1215 cam_flags camflags, u_int32_t sense_flags,
1218 struct bintime *starttime;
1219 struct bintime ltime;
1222 uint32_t timeout = 1;
1225 xpt_path_assert(ccb->ccb_h.path, MA_OWNED);
1226 KASSERT((ccb->ccb_h.flags & CAM_UNLOCKED) == 0,
1227 ("%s: ccb=%p, func_code=%#x, flags=%#x", __func__, ccb,
1228 ccb->ccb_h.func_code, ccb->ccb_h.flags));
1231 * If the user has supplied a stats structure, and if we understand
1232 * this particular type of ccb, record the transaction start.
1235 (ccb->ccb_h.func_code == XPT_SCSI_IO ||
1236 ccb->ccb_h.func_code == XPT_ATA_IO ||
1237 ccb->ccb_h.func_code == XPT_NVME_IO)) {
1239 binuptime(starttime);
1240 devstat_start_transaction(ds, starttime);
1244 * We must poll the I/O while we're dumping. The scheduler is normally
1245 * stopped for dumping, except when we call doadump from ddb. While the
1246 * scheduler is running in this case, we still need to poll the I/O to
1247 * avoid sleeping waiting for the ccb to complete.
1249 * A panic triggered dump stops the scheduler, any callback from the
1250 * shutdown_post_sync event will run with the scheduler stopped, but
1251 * before we're officially dumping. To avoid hanging in adashutdown
1252 * initiated commands (or other similar situations), we have to test for
1253 * either SCHEDULER_STOPPED() here as well.
1255 * To avoid locking problems, dumping/polling callers must call
1256 * without a periph lock held.
1258 must_poll = dumping || SCHEDULER_STOPPED();
1259 ccb->ccb_h.cbfcnp = cam_periph_done;
1262 * If we're polling, then we need to ensure that we have ample resources
1263 * in the periph. cam_periph_error can reschedule the ccb by calling
1264 * xpt_action and returning ERESTART, so we have to effect the polling
1265 * in the do loop below.
1268 timeout = xpt_poll_setup(ccb);
1272 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1278 xpt_pollwait(ccb, timeout);
1279 timeout = ccb->ccb_h.timeout * 10;
1281 cam_periph_ccbwait(ccb);
1283 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1285 else if (error_routine != NULL) {
1286 ccb->ccb_h.cbfcnp = cam_periph_done;
1287 error = (*error_routine)(ccb, camflags, sense_flags);
1290 } while (error == ERESTART);
1293 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1294 cam_release_devq(ccb->ccb_h.path,
1295 /* relsim_flags */0,
1298 /* getcount_only */ FALSE);
1299 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1304 devstat_tag_type tag;
1307 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1308 bytes = ccb->csio.dxfer_len - ccb->csio.resid;
1309 tag = (devstat_tag_type)(ccb->csio.tag_action & 0x3);
1310 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1311 bytes = ccb->ataio.dxfer_len - ccb->ataio.resid;
1312 tag = (devstat_tag_type)0;
1313 } else if (ccb->ccb_h.func_code == XPT_NVME_IO) {
1314 bytes = ccb->nvmeio.dxfer_len; /* NB: resid no possible */
1315 tag = (devstat_tag_type)0;
1320 devstat_end_transaction(ds, bytes, tag,
1321 ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE) ?
1322 DEVSTAT_NO_DATA : (ccb->ccb_h.flags & CAM_DIR_OUT) ?
1323 DEVSTAT_WRITE : DEVSTAT_READ, NULL, starttime);
1330 cam_freeze_devq(struct cam_path *path)
1332 struct ccb_hdr ccb_h;
1334 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1335 xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1336 ccb_h.func_code = XPT_NOOP;
1337 ccb_h.flags = CAM_DEV_QFREEZE;
1338 xpt_action((union ccb *)&ccb_h);
1342 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1343 u_int32_t openings, u_int32_t arg,
1346 struct ccb_relsim crs;
1348 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1349 relsim_flags, openings, arg, getcount_only));
1350 xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1351 crs.ccb_h.func_code = XPT_REL_SIMQ;
1352 crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1353 crs.release_flags = relsim_flags;
1354 crs.openings = openings;
1355 crs.release_timeout = arg;
1356 xpt_action((union ccb *)&crs);
1357 return (crs.qfrozen_cnt);
1360 #define saved_ccb_ptr ppriv_ptr0
1362 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1364 union ccb *saved_ccb;
1366 struct scsi_start_stop_unit *scsi_cmd;
1367 int error = 0, error_code, sense_key, asc, ascq;
1369 scsi_cmd = (struct scsi_start_stop_unit *)
1370 &done_ccb->csio.cdb_io.cdb_bytes;
1371 status = done_ccb->ccb_h.status;
1373 if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1374 if (scsi_extract_sense_ccb(done_ccb,
1375 &error_code, &sense_key, &asc, &ascq)) {
1377 * If the error is "invalid field in CDB",
1378 * and the load/eject flag is set, turn the
1379 * flag off and try again. This is just in
1380 * case the drive in question barfs on the
1381 * load eject flag. The CAM code should set
1382 * the load/eject flag by default for
1385 if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1386 ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1387 (asc == 0x24) && (ascq == 0x00)) {
1388 scsi_cmd->how &= ~SSS_LOEJ;
1389 if (status & CAM_DEV_QFRZN) {
1390 cam_release_devq(done_ccb->ccb_h.path,
1392 done_ccb->ccb_h.status &=
1395 xpt_action(done_ccb);
1399 error = cam_periph_error(done_ccb, 0,
1400 SF_RETRY_UA | SF_NO_PRINT);
1401 if (error == ERESTART)
1403 if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1404 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1405 done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1409 * If we have successfully taken a device from the not
1410 * ready to ready state, re-scan the device and re-get
1411 * the inquiry information. Many devices (mostly disks)
1412 * don't properly report their inquiry information unless
1415 if (scsi_cmd->opcode == START_STOP_UNIT)
1416 xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1419 /* If we tried long wait and still failed, remember that. */
1420 if ((periph->flags & CAM_PERIPH_RECOVERY_WAIT) &&
1421 (done_ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY)) {
1422 periph->flags &= ~CAM_PERIPH_RECOVERY_WAIT;
1423 if (error != 0 && done_ccb->ccb_h.retry_count == 0)
1424 periph->flags |= CAM_PERIPH_RECOVERY_WAIT_FAILED;
1428 * After recovery action(s) completed, return to the original CCB.
1429 * If the recovery CCB has failed, considering its own possible
1430 * retries and recovery, assume we are back in state where we have
1431 * been originally, but without recovery hopes left. In such case,
1432 * after the final attempt below, we cancel any further retries,
1433 * blocking by that also any new recovery attempts for this CCB,
1434 * and the result will be the final one returned to the CCB owher.
1436 saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1437 bcopy(saved_ccb, done_ccb, sizeof(*done_ccb));
1438 xpt_free_ccb(saved_ccb);
1439 if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1440 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1442 done_ccb->ccb_h.retry_count = 0;
1443 xpt_action(done_ccb);
1446 /* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1447 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1451 * Generic Async Event handler. Peripheral drivers usually
1452 * filter out the events that require personal attention,
1453 * and leave the rest to this function.
1456 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1457 struct cam_path *path, void *arg)
1460 case AC_LOST_DEVICE:
1461 cam_periph_invalidate(periph);
1469 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1471 struct ccb_getdevstats cgds;
1473 xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1474 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1475 xpt_action((union ccb *)&cgds);
1476 cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1480 cam_periph_freeze_after_event(struct cam_periph *periph,
1481 struct timeval* event_time, u_int duration_ms)
1483 struct timeval delta;
1484 struct timeval duration_tv;
1486 if (!timevalisset(event_time))
1490 timevalsub(&delta, event_time);
1491 duration_tv.tv_sec = duration_ms / 1000;
1492 duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1493 if (timevalcmp(&delta, &duration_tv, <)) {
1494 timevalsub(&duration_tv, &delta);
1496 duration_ms = duration_tv.tv_sec * 1000;
1497 duration_ms += duration_tv.tv_usec / 1000;
1498 cam_freeze_devq(periph->path);
1499 cam_release_devq(periph->path,
1500 RELSIM_RELEASE_AFTER_TIMEOUT,
1502 /*timeout*/duration_ms,
1503 /*getcount_only*/0);
1509 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1510 cam_flags camflags, u_int32_t sense_flags,
1511 int *openings, u_int32_t *relsim_flags,
1512 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1514 struct cam_periph *periph;
1517 switch (ccb->csio.scsi_status) {
1518 case SCSI_STATUS_OK:
1519 case SCSI_STATUS_COND_MET:
1520 case SCSI_STATUS_INTERMED:
1521 case SCSI_STATUS_INTERMED_COND_MET:
1524 case SCSI_STATUS_CMD_TERMINATED:
1525 case SCSI_STATUS_CHECK_COND:
1526 error = camperiphscsisenseerror(ccb, orig_ccb,
1535 case SCSI_STATUS_QUEUE_FULL:
1538 struct ccb_getdevstats cgds;
1541 * First off, find out what the current
1542 * transaction counts are.
1544 xpt_setup_ccb(&cgds.ccb_h,
1546 CAM_PRIORITY_NORMAL);
1547 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1548 xpt_action((union ccb *)&cgds);
1551 * If we were the only transaction active, treat
1552 * the QUEUE FULL as if it were a BUSY condition.
1554 if (cgds.dev_active != 0) {
1558 * Reduce the number of openings to
1559 * be 1 less than the amount it took
1560 * to get a queue full bounded by the
1561 * minimum allowed tag count for this
1564 total_openings = cgds.dev_active + cgds.dev_openings;
1565 *openings = cgds.dev_active;
1566 if (*openings < cgds.mintags)
1567 *openings = cgds.mintags;
1568 if (*openings < total_openings)
1569 *relsim_flags = RELSIM_ADJUST_OPENINGS;
1572 * Some devices report queue full for
1573 * temporary resource shortages. For
1574 * this reason, we allow a minimum
1575 * tag count to be entered via a
1576 * quirk entry to prevent the queue
1577 * count on these devices from falling
1578 * to a pessimisticly low value. We
1579 * still wait for the next successful
1580 * completion, however, before queueing
1581 * more transactions to the device.
1583 *relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1587 *action &= ~SSQ_PRINT_SENSE;
1592 case SCSI_STATUS_BUSY:
1594 * Restart the queue after either another
1595 * command completes or a 1 second timeout.
1597 periph = xpt_path_periph(ccb->ccb_h.path);
1598 if (periph->flags & CAM_PERIPH_INVALID) {
1600 *action_string = "Periph was invalidated";
1601 } else if ((sense_flags & SF_RETRY_BUSY) != 0 ||
1602 ccb->ccb_h.retry_count > 0) {
1603 if ((sense_flags & SF_RETRY_BUSY) == 0)
1604 ccb->ccb_h.retry_count--;
1606 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1607 | RELSIM_RELEASE_AFTER_CMDCMPLT;
1611 *action_string = "Retries exhausted";
1614 case SCSI_STATUS_RESERV_CONFLICT:
1623 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1624 cam_flags camflags, u_int32_t sense_flags,
1625 int *openings, u_int32_t *relsim_flags,
1626 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1628 struct cam_periph *periph;
1629 union ccb *orig_ccb = ccb;
1630 int error, recoveryccb;
1632 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1633 if (ccb->ccb_h.func_code == XPT_SCSI_IO && ccb->csio.bio != NULL)
1634 biotrack(ccb->csio.bio, __func__);
1637 periph = xpt_path_periph(ccb->ccb_h.path);
1638 recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1639 if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1641 * If error recovery is already in progress, don't attempt
1642 * to process this error, but requeue it unconditionally
1643 * and attempt to process it once error recovery has
1644 * completed. This failed command is probably related to
1645 * the error that caused the currently active error recovery
1646 * action so our current recovery efforts should also
1647 * address this command. Be aware that the error recovery
1648 * code assumes that only one recovery action is in progress
1649 * on a particular peripheral instance at any given time
1650 * (e.g. only one saved CCB for error recovery) so it is
1651 * imperitive that we don't violate this assumption.
1654 *action &= ~SSQ_PRINT_SENSE;
1656 scsi_sense_action err_action;
1657 struct ccb_getdev cgd;
1660 * Grab the inquiry data for this device.
1662 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1663 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1664 xpt_action((union ccb *)&cgd);
1666 err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1668 error = err_action & SS_ERRMASK;
1671 * Do not autostart sequential access devices
1672 * to avoid unexpected tape loading.
1674 if ((err_action & SS_MASK) == SS_START &&
1675 SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1676 *action_string = "Will not autostart a "
1677 "sequential access device";
1678 goto sense_error_done;
1682 * Avoid recovery recursion if recovery action is the same.
1684 if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1685 if (((err_action & SS_MASK) == SS_START &&
1686 ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1687 ((err_action & SS_MASK) == SS_TUR &&
1688 (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1689 err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1690 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1696 * If the recovery action will consume a retry,
1697 * make sure we actually have retries available.
1699 if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1700 if (ccb->ccb_h.retry_count > 0 &&
1701 (periph->flags & CAM_PERIPH_INVALID) == 0)
1702 ccb->ccb_h.retry_count--;
1704 *action_string = "Retries exhausted";
1705 goto sense_error_done;
1709 if ((err_action & SS_MASK) >= SS_START) {
1711 * Do common portions of commands that
1712 * use recovery CCBs.
1714 orig_ccb = xpt_alloc_ccb_nowait();
1715 if (orig_ccb == NULL) {
1716 *action_string = "Can't allocate recovery CCB";
1717 goto sense_error_done;
1720 * Clear freeze flag for original request here, as
1721 * this freeze will be dropped as part of ERESTART.
1723 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1724 bcopy(ccb, orig_ccb, sizeof(*orig_ccb));
1727 switch (err_action & SS_MASK) {
1729 *action_string = "No recovery action needed";
1733 *action_string = "Retrying command (per sense data)";
1737 *action_string = "Unretryable error";
1744 * Send a start unit command to the device, and
1745 * then retry the command.
1747 *action_string = "Attempting to start unit";
1748 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1751 * Check for removable media and set
1752 * load/eject flag appropriately.
1754 if (SID_IS_REMOVABLE(&cgd.inq_data))
1759 scsi_start_stop(&ccb->csio,
1773 * Send a Test Unit Ready to the device.
1774 * If the 'many' flag is set, we send 120
1775 * test unit ready commands, one every half
1776 * second. Otherwise, we just send one TUR.
1777 * We only want to do this if the retry
1778 * count has not been exhausted.
1782 if ((err_action & SSQ_MANY) != 0 && (periph->flags &
1783 CAM_PERIPH_RECOVERY_WAIT_FAILED) == 0) {
1784 periph->flags |= CAM_PERIPH_RECOVERY_WAIT;
1785 *action_string = "Polling device for readiness";
1788 *action_string = "Testing device for readiness";
1791 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1792 scsi_test_unit_ready(&ccb->csio,
1800 * Accomplish our 500ms delay by deferring
1801 * the release of our device queue appropriately.
1803 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1808 panic("Unhandled error action %x", err_action);
1811 if ((err_action & SS_MASK) >= SS_START) {
1813 * Drop the priority, so that the recovery
1814 * CCB is the first to execute. Freeze the queue
1815 * after this command is sent so that we can
1816 * restore the old csio and have it queued in
1817 * the proper order before we release normal
1818 * transactions to the device.
1820 ccb->ccb_h.pinfo.priority--;
1821 ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1822 ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1828 *action = err_action;
1834 * Generic error handler. Peripheral drivers usually filter
1835 * out the errors that they handle in a unique manner, then
1836 * call this function.
1839 cam_periph_error(union ccb *ccb, cam_flags camflags,
1840 u_int32_t sense_flags)
1842 struct cam_path *newpath;
1843 union ccb *orig_ccb, *scan_ccb;
1844 struct cam_periph *periph;
1845 const char *action_string;
1847 int frozen, error, openings, devctl_err;
1848 u_int32_t action, relsim_flags, timeout;
1850 action = SSQ_PRINT_SENSE;
1851 periph = xpt_path_periph(ccb->ccb_h.path);
1852 action_string = NULL;
1853 status = ccb->ccb_h.status;
1854 frozen = (status & CAM_DEV_QFRZN) != 0;
1855 status &= CAM_STATUS_MASK;
1856 devctl_err = openings = relsim_flags = timeout = 0;
1859 /* Filter the errors that should be reported via devctl */
1860 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1861 case CAM_CMD_TIMEOUT:
1862 case CAM_REQ_ABORTED:
1863 case CAM_REQ_CMP_ERR:
1864 case CAM_REQ_TERMIO:
1865 case CAM_UNREC_HBA_ERROR:
1866 case CAM_DATA_RUN_ERR:
1867 case CAM_SCSI_STATUS_ERROR:
1868 case CAM_ATA_STATUS_ERROR:
1869 case CAM_SMP_STATUS_ERROR:
1879 action &= ~SSQ_PRINT_SENSE;
1881 case CAM_SCSI_STATUS_ERROR:
1882 error = camperiphscsistatuserror(ccb, &orig_ccb,
1883 camflags, sense_flags, &openings, &relsim_flags,
1884 &timeout, &action, &action_string);
1886 case CAM_AUTOSENSE_FAIL:
1887 error = EIO; /* we have to kill the command */
1891 case CAM_MSG_REJECT_REC:
1892 /* XXX Don't know that these are correct */
1895 case CAM_SEL_TIMEOUT:
1896 if ((camflags & CAM_RETRY_SELTO) != 0) {
1897 if (ccb->ccb_h.retry_count > 0 &&
1898 (periph->flags & CAM_PERIPH_INVALID) == 0) {
1899 ccb->ccb_h.retry_count--;
1903 * Wait a bit to give the device
1904 * time to recover before we try again.
1906 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1907 timeout = periph_selto_delay;
1910 action_string = "Retries exhausted";
1913 case CAM_DEV_NOT_THERE:
1917 case CAM_REQ_INVALID:
1918 case CAM_PATH_INVALID:
1920 case CAM_PROVIDE_FAIL:
1921 case CAM_REQ_TOO_BIG:
1922 case CAM_LUN_INVALID:
1923 case CAM_TID_INVALID:
1924 case CAM_FUNC_NOTAVAIL:
1927 case CAM_SCSI_BUS_RESET:
1930 * Commands that repeatedly timeout and cause these
1931 * kinds of error recovery actions, should return
1932 * CAM_CMD_TIMEOUT, which allows us to safely assume
1933 * that this command was an innocent bystander to
1934 * these events and should be unconditionally
1937 case CAM_REQUEUE_REQ:
1938 /* Unconditional requeue if device is still there */
1939 if (periph->flags & CAM_PERIPH_INVALID) {
1940 action_string = "Periph was invalidated";
1942 } else if (sense_flags & SF_NO_RETRY) {
1944 action_string = "Retry was blocked";
1947 action &= ~SSQ_PRINT_SENSE;
1950 case CAM_RESRC_UNAVAIL:
1951 /* Wait a bit for the resource shortage to abate. */
1952 timeout = periph_noresrc_delay;
1956 /* Wait a bit for the busy condition to abate. */
1957 timeout = periph_busy_delay;
1959 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1961 case CAM_ATA_STATUS_ERROR:
1962 case CAM_REQ_CMP_ERR:
1963 case CAM_CMD_TIMEOUT:
1964 case CAM_UNEXP_BUSFREE:
1965 case CAM_UNCOR_PARITY:
1966 case CAM_DATA_RUN_ERR:
1968 if (periph->flags & CAM_PERIPH_INVALID) {
1970 action_string = "Periph was invalidated";
1971 } else if (ccb->ccb_h.retry_count == 0) {
1973 action_string = "Retries exhausted";
1974 } else if (sense_flags & SF_NO_RETRY) {
1976 action_string = "Retry was blocked";
1978 ccb->ccb_h.retry_count--;
1984 if ((sense_flags & SF_PRINT_ALWAYS) ||
1985 CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
1986 action |= SSQ_PRINT_SENSE;
1987 else if (sense_flags & SF_NO_PRINT)
1988 action &= ~SSQ_PRINT_SENSE;
1989 if ((action & SSQ_PRINT_SENSE) != 0)
1990 cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
1991 if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
1992 if (error != ERESTART) {
1993 if (action_string == NULL)
1994 action_string = "Unretryable error";
1995 xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
1996 error, action_string);
1997 } else if (action_string != NULL)
1998 xpt_print(ccb->ccb_h.path, "%s\n", action_string);
2000 xpt_print(ccb->ccb_h.path,
2001 "Retrying command, %d more tries remain\n",
2002 ccb->ccb_h.retry_count);
2006 if (devctl_err && (error != 0 || (action & SSQ_PRINT_SENSE) != 0))
2007 cam_periph_devctl_notify(orig_ccb);
2009 if ((action & SSQ_LOST) != 0) {
2013 * For a selection timeout, we consider all of the LUNs on
2014 * the target to be gone. If the status is CAM_DEV_NOT_THERE,
2015 * then we only get rid of the device(s) specified by the
2016 * path in the original CCB.
2018 if (status == CAM_SEL_TIMEOUT)
2019 lun_id = CAM_LUN_WILDCARD;
2021 lun_id = xpt_path_lun_id(ccb->ccb_h.path);
2023 /* Should we do more if we can't create the path?? */
2024 if (xpt_create_path(&newpath, periph,
2025 xpt_path_path_id(ccb->ccb_h.path),
2026 xpt_path_target_id(ccb->ccb_h.path),
2027 lun_id) == CAM_REQ_CMP) {
2029 * Let peripheral drivers know that this
2030 * device has gone away.
2032 xpt_async(AC_LOST_DEVICE, newpath, NULL);
2033 xpt_free_path(newpath);
2037 /* Broadcast UNIT ATTENTIONs to all periphs. */
2038 if ((action & SSQ_UA) != 0)
2039 xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
2041 /* Rescan target on "Reported LUNs data has changed" */
2042 if ((action & SSQ_RESCAN) != 0) {
2043 if (xpt_create_path(&newpath, NULL,
2044 xpt_path_path_id(ccb->ccb_h.path),
2045 xpt_path_target_id(ccb->ccb_h.path),
2046 CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
2047 scan_ccb = xpt_alloc_ccb_nowait();
2048 if (scan_ccb != NULL) {
2049 scan_ccb->ccb_h.path = newpath;
2050 scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
2051 scan_ccb->crcn.flags = 0;
2052 xpt_rescan(scan_ccb);
2055 "Can't allocate CCB to rescan target\n");
2056 xpt_free_path(newpath);
2061 /* Attempt a retry */
2062 if (error == ERESTART || error == 0) {
2064 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
2065 if (error == ERESTART)
2068 cam_release_devq(ccb->ccb_h.path,
2072 /*getcount_only*/0);
2078 #define CAM_PERIPH_DEVD_MSG_SIZE 256
2081 cam_periph_devctl_notify(union ccb *ccb)
2083 struct cam_periph *periph;
2084 struct ccb_getdev *cgd;
2086 int serr, sk, asc, ascq;
2089 sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT);
2093 sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN);
2095 periph = xpt_path_periph(ccb->ccb_h.path);
2096 sbuf_printf(&sb, "device=%s%d ", periph->periph_name,
2097 periph->unit_number);
2099 sbuf_printf(&sb, "serial=\"");
2100 if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) {
2101 xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path,
2102 CAM_PRIORITY_NORMAL);
2103 cgd->ccb_h.func_code = XPT_GDEV_TYPE;
2104 xpt_action((union ccb *)cgd);
2106 if (cgd->ccb_h.status == CAM_REQ_CMP)
2107 sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len);
2108 xpt_free_ccb((union ccb *)cgd);
2110 sbuf_printf(&sb, "\" ");
2111 sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status);
2113 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
2114 case CAM_CMD_TIMEOUT:
2115 sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout);
2118 case CAM_SCSI_STATUS_ERROR:
2119 sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status);
2120 if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq))
2121 sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ",
2122 serr, sk, asc, ascq);
2125 case CAM_ATA_STATUS_ERROR:
2126 sbuf_printf(&sb, "RES=\"");
2127 ata_res_sbuf(&ccb->ataio.res, &sb);
2128 sbuf_printf(&sb, "\" ");
2136 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2137 sbuf_printf(&sb, "CDB=\"");
2138 scsi_cdb_sbuf(scsiio_cdb_ptr(&ccb->csio), &sb);
2139 sbuf_printf(&sb, "\" ");
2140 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2141 sbuf_printf(&sb, "ACB=\"");
2142 ata_cmd_sbuf(&ccb->ataio.cmd, &sb);
2143 sbuf_printf(&sb, "\" ");
2146 if (sbuf_finish(&sb) == 0)
2147 devctl_notify("CAM", "periph", type, sbuf_data(&sb));
2149 free(sbmsg, M_CAMPERIPH);
2153 * Sysctl to force an invalidation of the drive right now. Can be
2154 * called with CTLFLAG_MPSAFE since we take periph lock.
2157 cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)
2159 struct cam_periph *periph;
2164 error = sysctl_handle_int(oidp, &value, 0, req);
2165 if (error != 0 || req->newptr == NULL || value != 1)
2168 cam_periph_lock(periph);
2169 cam_periph_invalidate(periph);
2170 cam_periph_unlock(periph);