2 * Common functions for CAM "type" (peripheral) drivers.
4 * SPDX-License-Identifier: BSD-2-Clause
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_compat.h>
56 #include <cam/cam_queue.h>
57 #include <cam/cam_xpt_periph.h>
58 #include <cam/cam_xpt_internal.h>
59 #include <cam/cam_periph.h>
60 #include <cam/cam_debug.h>
61 #include <cam/cam_sim.h>
63 #include <cam/scsi/scsi_all.h>
64 #include <cam/scsi/scsi_message.h>
65 #include <cam/scsi/scsi_pass.h>
67 static u_int camperiphnextunit(struct periph_driver *p_drv,
68 u_int newunit, bool wired,
69 path_id_t pathid, target_id_t target,
71 static u_int camperiphunit(struct periph_driver *p_drv,
72 path_id_t pathid, target_id_t target,
75 static void camperiphdone(struct cam_periph *periph,
77 static void camperiphfree(struct cam_periph *periph);
78 static int camperiphscsistatuserror(union ccb *ccb,
81 u_int32_t sense_flags,
83 u_int32_t *relsim_flags,
86 const char **action_string);
87 static int camperiphscsisenseerror(union ccb *ccb,
90 u_int32_t sense_flags,
92 u_int32_t *relsim_flags,
95 const char **action_string);
96 static void cam_periph_devctl_notify(union ccb *ccb);
98 static int nperiph_drivers;
99 static int initialized = 0;
100 struct periph_driver **periph_drivers;
102 static MALLOC_DEFINE(M_CAMPERIPH, "CAM periph", "CAM peripheral buffers");
104 static int periph_selto_delay = 1000;
105 TUNABLE_INT("kern.cam.periph_selto_delay", &periph_selto_delay);
106 static int periph_noresrc_delay = 500;
107 TUNABLE_INT("kern.cam.periph_noresrc_delay", &periph_noresrc_delay);
108 static int periph_busy_delay = 500;
109 TUNABLE_INT("kern.cam.periph_busy_delay", &periph_busy_delay);
111 static u_int periph_mapmem_thresh = 65536;
112 SYSCTL_UINT(_kern_cam, OID_AUTO, mapmem_thresh, CTLFLAG_RWTUN,
113 &periph_mapmem_thresh, 0, "Threshold for user-space buffer mapping");
116 periphdriver_register(void *data)
118 struct periph_driver *drv = (struct periph_driver *)data;
119 struct periph_driver **newdrivers, **old;
123 ndrivers = nperiph_drivers + 2;
124 newdrivers = malloc(sizeof(*newdrivers) * ndrivers, M_CAMPERIPH,
127 if (ndrivers != nperiph_drivers + 2) {
129 * Lost race against itself; go around.
132 free(newdrivers, M_CAMPERIPH);
136 bcopy(periph_drivers, newdrivers,
137 sizeof(*newdrivers) * nperiph_drivers);
138 newdrivers[nperiph_drivers] = drv;
139 newdrivers[nperiph_drivers + 1] = NULL;
140 old = periph_drivers;
141 periph_drivers = newdrivers;
145 free(old, M_CAMPERIPH);
146 /* If driver marked as early or it is late now, initialize it. */
147 if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
153 periphdriver_unregister(void *data)
155 struct periph_driver *drv = (struct periph_driver *)data;
158 /* If driver marked as early or it is late now, deinitialize it. */
159 if (((drv->flags & CAM_PERIPH_DRV_EARLY) != 0 && initialized > 0) ||
161 if (drv->deinit == NULL) {
162 printf("CAM periph driver '%s' doesn't have deinit.\n",
166 error = drv->deinit();
172 for (n = 0; n < nperiph_drivers && periph_drivers[n] != drv; n++)
174 KASSERT(n < nperiph_drivers,
175 ("Periph driver '%s' was not registered", drv->driver_name));
176 for (; n + 1 < nperiph_drivers; n++)
177 periph_drivers[n] = periph_drivers[n + 1];
178 periph_drivers[n + 1] = NULL;
185 periphdriver_init(int level)
189 initialized = max(initialized, level);
190 for (i = 0; periph_drivers[i] != NULL; i++) {
191 early = (periph_drivers[i]->flags & CAM_PERIPH_DRV_EARLY) ? 1 : 2;
192 if (early == initialized)
193 (*periph_drivers[i]->init)();
198 cam_periph_alloc(periph_ctor_t *periph_ctor,
199 periph_oninv_t *periph_oninvalidate,
200 periph_dtor_t *periph_dtor, periph_start_t *periph_start,
201 char *name, cam_periph_type type, struct cam_path *path,
202 ac_callback_t *ac_callback, ac_code code, void *arg)
204 struct periph_driver **p_drv;
206 struct cam_periph *periph;
207 struct cam_periph *cur_periph;
209 target_id_t target_id;
216 * Handle Hot-Plug scenarios. If there is already a peripheral
217 * of our type assigned to this path, we are likely waiting for
218 * final close on an old, invalidated, peripheral. If this is
219 * the case, queue up a deferred call to the peripheral's async
220 * handler. If it looks like a mistaken re-allocation, complain.
222 if ((periph = cam_periph_find(path, name)) != NULL) {
223 if ((periph->flags & CAM_PERIPH_INVALID) != 0
224 && (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) == 0) {
225 periph->flags |= CAM_PERIPH_NEW_DEV_FOUND;
226 periph->deferred_callback = ac_callback;
227 periph->deferred_ac = code;
228 return (CAM_REQ_INPROG);
230 printf("cam_periph_alloc: attempt to re-allocate "
231 "valid device %s%d rejected flags %#x "
232 "refcount %d\n", periph->periph_name,
233 periph->unit_number, periph->flags,
236 return (CAM_REQ_INVALID);
239 periph = (struct cam_periph *)malloc(sizeof(*periph), M_CAMPERIPH,
243 return (CAM_RESRC_UNAVAIL);
247 sim = xpt_path_sim(path);
248 path_id = xpt_path_path_id(path);
249 target_id = xpt_path_target_id(path);
250 lun_id = xpt_path_lun_id(path);
251 periph->periph_start = periph_start;
252 periph->periph_dtor = periph_dtor;
253 periph->periph_oninval = periph_oninvalidate;
255 periph->periph_name = name;
256 periph->scheduled_priority = CAM_PRIORITY_NONE;
257 periph->immediate_priority = CAM_PRIORITY_NONE;
258 periph->refcount = 1; /* Dropped by invalidation. */
260 SLIST_INIT(&periph->ccb_list);
261 status = xpt_create_path(&path, periph, path_id, target_id, lun_id);
262 if (status != CAM_REQ_CMP)
267 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
268 if (strcmp((*p_drv)->driver_name, name) == 0)
271 if (*p_drv == NULL) {
272 printf("cam_periph_alloc: invalid periph name '%s'\n", name);
274 xpt_free_path(periph->path);
275 free(periph, M_CAMPERIPH);
276 return (CAM_REQ_INVALID);
278 periph->unit_number = camperiphunit(*p_drv, path_id, target_id, lun_id,
279 path->device->serial_num);
280 cur_periph = TAILQ_FIRST(&(*p_drv)->units);
281 while (cur_periph != NULL
282 && cur_periph->unit_number < periph->unit_number)
283 cur_periph = TAILQ_NEXT(cur_periph, unit_links);
284 if (cur_periph != NULL) {
285 KASSERT(cur_periph->unit_number != periph->unit_number,
286 ("duplicate units on periph list"));
287 TAILQ_INSERT_BEFORE(cur_periph, periph, unit_links);
289 TAILQ_INSERT_TAIL(&(*p_drv)->units, periph, unit_links);
290 (*p_drv)->generation++;
296 status = xpt_add_periph(periph);
297 if (status != CAM_REQ_CMP)
301 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph created\n"));
303 status = periph_ctor(periph, arg);
305 if (status == CAM_REQ_CMP)
309 switch (init_level) {
311 /* Initialized successfully */
314 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
315 xpt_remove_periph(periph);
319 TAILQ_REMOVE(&(*p_drv)->units, periph, unit_links);
321 xpt_free_path(periph->path);
324 free(periph, M_CAMPERIPH);
327 /* No cleanup to perform. */
330 panic("%s: Unknown init level", __func__);
336 * Find a peripheral structure with the specified path, target, lun,
337 * and (optionally) type. If the name is NULL, this function will return
338 * the first peripheral driver that matches the specified path.
341 cam_periph_find(struct cam_path *path, char *name)
343 struct periph_driver **p_drv;
344 struct cam_periph *periph;
347 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
348 if (name != NULL && (strcmp((*p_drv)->driver_name, name) != 0))
351 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
352 if (xpt_path_comp(periph->path, path) == 0) {
354 cam_periph_assert(periph, MA_OWNED);
368 * Find peripheral driver instances attached to the specified path.
371 cam_periph_list(struct cam_path *path, struct sbuf *sb)
373 struct sbuf local_sb;
374 struct periph_driver **p_drv;
375 struct cam_periph *periph;
381 sbuf_new(&local_sb, NULL, sbuf_alloc_len, SBUF_FIXEDLEN);
384 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
385 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
386 if (xpt_path_comp(periph->path, path) != 0)
389 if (sbuf_len(&local_sb) != 0)
390 sbuf_cat(&local_sb, ",");
392 sbuf_printf(&local_sb, "%s%d", periph->periph_name,
393 periph->unit_number);
395 if (sbuf_error(&local_sb) == ENOMEM) {
398 sbuf_delete(&local_sb);
405 sbuf_finish(&local_sb);
406 if (sbuf_len(sb) != 0)
408 sbuf_cat(sb, sbuf_data(&local_sb));
409 sbuf_delete(&local_sb);
414 cam_periph_acquire(struct cam_periph *periph)
423 if ((periph->flags & CAM_PERIPH_INVALID) == 0) {
433 cam_periph_doacquire(struct cam_periph *periph)
437 KASSERT(periph->refcount >= 1,
438 ("cam_periph_doacquire() with refcount == %d", periph->refcount));
444 cam_periph_release_locked_buses(struct cam_periph *periph)
447 cam_periph_assert(periph, MA_OWNED);
448 KASSERT(periph->refcount >= 1, ("periph->refcount >= 1"));
449 if (--periph->refcount == 0)
450 camperiphfree(periph);
454 cam_periph_release_locked(struct cam_periph *periph)
461 cam_periph_release_locked_buses(periph);
466 cam_periph_release(struct cam_periph *periph)
473 cam_periph_assert(periph, MA_NOTOWNED);
474 mtx = cam_periph_mtx(periph);
476 cam_periph_release_locked(periph);
481 * hold/unhold act as mutual exclusion for sections of the code that
482 * need to sleep and want to make sure that other sections that
483 * will interfere are held off. This only protects exclusive sections
487 cam_periph_hold(struct cam_periph *periph, int priority)
492 * Increment the reference count on the peripheral
493 * while we wait for our lock attempt to succeed
494 * to ensure the peripheral doesn't disappear out
495 * from user us while we sleep.
498 if (cam_periph_acquire(periph) != 0)
501 cam_periph_assert(periph, MA_OWNED);
502 while ((periph->flags & CAM_PERIPH_LOCKED) != 0) {
503 periph->flags |= CAM_PERIPH_LOCK_WANTED;
504 if ((error = cam_periph_sleep(periph, periph, priority,
505 "caplck", 0)) != 0) {
506 cam_periph_release_locked(periph);
509 if (periph->flags & CAM_PERIPH_INVALID) {
510 cam_periph_release_locked(periph);
515 periph->flags |= CAM_PERIPH_LOCKED;
520 cam_periph_unhold(struct cam_periph *periph)
523 cam_periph_assert(periph, MA_OWNED);
525 periph->flags &= ~CAM_PERIPH_LOCKED;
526 if ((periph->flags & CAM_PERIPH_LOCK_WANTED) != 0) {
527 periph->flags &= ~CAM_PERIPH_LOCK_WANTED;
531 cam_periph_release_locked(periph);
535 cam_periph_hold_boot(struct cam_periph *periph)
538 root_mount_hold_token(periph->periph_name, &periph->periph_rootmount);
542 cam_periph_release_boot(struct cam_periph *periph)
545 root_mount_rel(&periph->periph_rootmount);
549 * Look for the next unit number that is not currently in use for this
550 * peripheral type starting at "newunit". Also exclude unit numbers that
551 * are reserved by for future "hardwiring" unless we already know that this
552 * is a potential wired device. Only assume that the device is "wired" the
553 * first time through the loop since after that we'll be looking at unit
554 * numbers that did not match a wiring entry.
557 camperiphnextunit(struct periph_driver *p_drv, u_int newunit, bool wired,
558 path_id_t pathid, target_id_t target, lun_id_t lun)
560 struct cam_periph *periph;
562 int i, val, dunit, r;
563 const char *dname, *strval;
565 periph_name = p_drv->driver_name;
567 for (periph = TAILQ_FIRST(&p_drv->units);
568 periph != NULL && periph->unit_number != newunit;
569 periph = TAILQ_NEXT(periph, unit_links))
572 if (periph != NULL && periph->unit_number == newunit) {
574 xpt_print(periph->path, "Duplicate Wired "
576 xpt_print(periph->path, "Second device (%s "
577 "device at scbus%d target %d lun %d) will "
578 "not be wired\n", periph_name, pathid,
588 * Don't allow the mere presence of any attributes of a device
589 * means that it is for a wired down entry. Instead, insist that
590 * one of the matching criteria from camperiphunit be present
596 r = resource_find_dev(&i, dname, &dunit, NULL, NULL);
600 if (newunit != dunit)
602 if (resource_string_value(dname, dunit, "sn", &strval) == 0 ||
603 resource_int_value(dname, dunit, "lun", &val) == 0 ||
604 resource_int_value(dname, dunit, "target", &val) == 0 ||
605 resource_string_value(dname, dunit, "at", &strval) == 0)
615 camperiphunit(struct periph_driver *p_drv, path_id_t pathid,
616 target_id_t target, lun_id_t lun, const char *sn)
621 const char *dname, *strval;
622 char pathbuf[32], *periph_name;
624 periph_name = p_drv->driver_name;
625 snprintf(pathbuf, sizeof(pathbuf), "scbus%d", pathid);
630 for (wired = false; resource_find_dev(&i, dname, &dunit, NULL, NULL) == 0;
632 if (resource_string_value(dname, dunit, "at", &strval) == 0) {
633 if (strcmp(strval, pathbuf) != 0)
637 if (resource_int_value(dname, dunit, "target", &val) == 0) {
642 if (resource_int_value(dname, dunit, "lun", &val) == 0) {
647 if (resource_string_value(dname, dunit, "sn", &strval) == 0) {
648 if (sn == NULL || strcmp(strval, sn) != 0)
659 * Either start from 0 looking for the next unit or from
660 * the unit number given in the resource config. This way,
661 * if we have wildcard matches, we don't return the same
664 unit = camperiphnextunit(p_drv, unit, wired, pathid, target, lun);
670 cam_periph_invalidate(struct cam_periph *periph)
673 cam_periph_assert(periph, MA_OWNED);
675 * We only tear down the device the first time a peripheral is
678 if ((periph->flags & CAM_PERIPH_INVALID) != 0)
681 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph invalidated\n"));
682 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting) {
686 sbuf_new(&sb, buffer, 160, SBUF_FIXEDLEN);
687 xpt_denounce_periph_sbuf(periph, &sb);
691 periph->flags |= CAM_PERIPH_INVALID;
692 periph->flags &= ~CAM_PERIPH_NEW_DEV_FOUND;
693 if (periph->periph_oninval != NULL)
694 periph->periph_oninval(periph);
695 cam_periph_release_locked(periph);
699 camperiphfree(struct cam_periph *periph)
701 struct periph_driver **p_drv;
702 struct periph_driver *drv;
704 cam_periph_assert(periph, MA_OWNED);
705 KASSERT(periph->periph_allocating == 0, ("%s%d: freed while allocating",
706 periph->periph_name, periph->unit_number));
707 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
708 if (strcmp((*p_drv)->driver_name, periph->periph_name) == 0)
711 if (*p_drv == NULL) {
712 printf("camperiphfree: attempt to free non-existant periph\n");
716 * Cache a pointer to the periph_driver structure. If a
717 * periph_driver is added or removed from the array (see
718 * periphdriver_register()) while we drop the toplogy lock
719 * below, p_drv may change. This doesn't protect against this
720 * particular periph_driver going away. That will require full
721 * reference counting in the periph_driver infrastructure.
726 * We need to set this flag before dropping the topology lock, to
727 * let anyone who is traversing the list that this peripheral is
728 * about to be freed, and there will be no more reference count
731 periph->flags |= CAM_PERIPH_FREE;
734 * The peripheral destructor semantics dictate calling with only the
735 * SIM mutex held. Since it might sleep, it should not be called
736 * with the topology lock held.
741 * We need to call the peripheral destructor prior to removing the
742 * peripheral from the list. Otherwise, we risk running into a
743 * scenario where the peripheral unit number may get reused
744 * (because it has been removed from the list), but some resources
745 * used by the peripheral are still hanging around. In particular,
746 * the devfs nodes used by some peripherals like the pass(4) driver
747 * aren't fully cleaned up until the destructor is run. If the
748 * unit number is reused before the devfs instance is fully gone,
751 if (periph->periph_dtor != NULL)
752 periph->periph_dtor(periph);
755 * The peripheral list is protected by the topology lock. We have to
756 * remove the periph from the drv list before we call deferred_ac. The
757 * AC_FOUND_DEVICE callback won't create a new periph if it's still there.
761 TAILQ_REMOVE(&drv->units, periph, unit_links);
764 xpt_remove_periph(periph);
767 if ((periph->flags & CAM_PERIPH_ANNOUNCED) && !rebooting)
768 xpt_print(periph->path, "Periph destroyed\n");
770 CAM_DEBUG(periph->path, CAM_DEBUG_INFO, ("Periph destroyed\n"));
772 if (periph->flags & CAM_PERIPH_NEW_DEV_FOUND) {
776 memset(&ccb, 0, sizeof(ccb));
777 switch (periph->deferred_ac) {
778 case AC_FOUND_DEVICE:
779 ccb.ccb_h.func_code = XPT_GDEV_TYPE;
780 xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
784 case AC_PATH_REGISTERED:
785 xpt_path_inq(&ccb.cpi, periph->path);
792 periph->deferred_callback(NULL, periph->deferred_ac,
795 xpt_free_path(periph->path);
796 free(periph, M_CAMPERIPH);
801 * Map user virtual pointers into kernel virtual address space, so we can
802 * access the memory. This is now a generic function that centralizes most
803 * of the sanity checks on the data flags, if any.
804 * This also only works for up to maxphys memory. Since we use
805 * buffers to map stuff in and out, we're limited to the buffer size.
808 cam_periph_mapmem(union ccb *ccb, struct cam_periph_map_info *mapinfo,
812 u_int8_t **data_ptrs[CAM_PERIPH_MAXMAPS];
813 u_int32_t lengths[CAM_PERIPH_MAXMAPS];
814 u_int32_t dirs[CAM_PERIPH_MAXMAPS];
816 bzero(mapinfo, sizeof(*mapinfo));
818 maxmap = DFLTPHYS; /* traditional default */
819 else if (maxmap > maxphys)
820 maxmap = maxphys; /* for safety */
821 switch(ccb->ccb_h.func_code) {
823 if (ccb->cdm.match_buf_len == 0) {
824 printf("cam_periph_mapmem: invalid match buffer "
828 if (ccb->cdm.pattern_buf_len > 0) {
829 data_ptrs[0] = (u_int8_t **)&ccb->cdm.patterns;
830 lengths[0] = ccb->cdm.pattern_buf_len;
831 dirs[0] = CAM_DIR_OUT;
832 data_ptrs[1] = (u_int8_t **)&ccb->cdm.matches;
833 lengths[1] = ccb->cdm.match_buf_len;
834 dirs[1] = CAM_DIR_IN;
837 data_ptrs[0] = (u_int8_t **)&ccb->cdm.matches;
838 lengths[0] = ccb->cdm.match_buf_len;
839 dirs[0] = CAM_DIR_IN;
843 * This request will not go to the hardware, no reason
844 * to be so strict. vmapbuf() is able to map up to maxphys.
849 case XPT_CONT_TARGET_IO:
850 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
852 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
854 data_ptrs[0] = &ccb->csio.data_ptr;
855 lengths[0] = ccb->csio.dxfer_len;
856 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
860 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
862 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
864 data_ptrs[0] = &ccb->ataio.data_ptr;
865 lengths[0] = ccb->ataio.dxfer_len;
866 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
870 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
872 /* Two mappings: one for cmd->data and one for cmd->data->data */
873 data_ptrs[0] = (unsigned char **)&ccb->mmcio.cmd.data;
874 lengths[0] = sizeof(struct mmc_data *);
875 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
876 data_ptrs[1] = (unsigned char **)&ccb->mmcio.cmd.data->data;
877 lengths[1] = ccb->mmcio.cmd.data->len;
878 dirs[1] = ccb->ccb_h.flags & CAM_DIR_MASK;
882 data_ptrs[0] = &ccb->smpio.smp_request;
883 lengths[0] = ccb->smpio.smp_request_len;
884 dirs[0] = CAM_DIR_OUT;
885 data_ptrs[1] = &ccb->smpio.smp_response;
886 lengths[1] = ccb->smpio.smp_response_len;
887 dirs[1] = CAM_DIR_IN;
892 if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE)
894 if ((ccb->ccb_h.flags & CAM_DATA_MASK) != CAM_DATA_VADDR)
896 data_ptrs[0] = &ccb->nvmeio.data_ptr;
897 lengths[0] = ccb->nvmeio.dxfer_len;
898 dirs[0] = ccb->ccb_h.flags & CAM_DIR_MASK;
901 case XPT_DEV_ADVINFO:
902 if (ccb->cdai.bufsiz == 0)
905 data_ptrs[0] = (uint8_t **)&ccb->cdai.buf;
906 lengths[0] = ccb->cdai.bufsiz;
907 dirs[0] = CAM_DIR_IN;
911 * This request will not go to the hardware, no reason
912 * to be so strict. vmapbuf() is able to map up to maxphys.
918 break; /* NOTREACHED */
922 * Check the transfer length and permissions first, so we don't
923 * have to unmap any previously mapped buffers.
925 for (i = 0; i < numbufs; i++) {
926 if (lengths[i] > maxmap) {
927 printf("cam_periph_mapmem: attempt to map %lu bytes, "
928 "which is greater than %lu\n",
929 (long)(lengths[i]), (u_long)maxmap);
935 * This keeps the kernel stack of current thread from getting
936 * swapped. In low-memory situations where the kernel stack might
937 * otherwise get swapped out, this holds it and allows the thread
938 * to make progress and release the kernel mapped pages sooner.
940 * XXX KDM should I use P_NOSWAP instead?
944 for (i = 0; i < numbufs; i++) {
945 /* Save the user's data address. */
946 mapinfo->orig[i] = *data_ptrs[i];
949 * For small buffers use malloc+copyin/copyout instead of
950 * mapping to KVA to avoid expensive TLB shootdowns. For
951 * small allocations malloc is backed by UMA, and so much
952 * cheaper on SMP systems.
954 if (lengths[i] <= periph_mapmem_thresh &&
955 ccb->ccb_h.func_code != XPT_MMC_IO) {
956 *data_ptrs[i] = malloc(lengths[i], M_CAMPERIPH,
958 if (dirs[i] != CAM_DIR_IN) {
959 if (copyin(mapinfo->orig[i], *data_ptrs[i],
961 free(*data_ptrs[i], M_CAMPERIPH);
962 *data_ptrs[i] = mapinfo->orig[i];
966 bzero(*data_ptrs[i], lengths[i]);
973 mapinfo->bp[i] = uma_zalloc(pbuf_zone, M_WAITOK);
975 /* set the direction */
976 mapinfo->bp[i]->b_iocmd = (dirs[i] == CAM_DIR_OUT) ?
977 BIO_WRITE : BIO_READ;
979 /* Map the buffer into kernel memory. */
980 if (vmapbuf(mapinfo->bp[i], *data_ptrs[i], lengths[i], 1) < 0) {
981 uma_zfree(pbuf_zone, mapinfo->bp[i]);
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 uma_zfree(pbuf_zone, mapinfo->bp[i]);
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 uma_zfree(pbuf_zone, mapinfo->bp[i]);
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_0x19:
1137 case CAMGETPASSTHRU:
1138 ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
1139 xpt_setup_ccb(&ccb->ccb_h,
1141 CAM_PRIORITY_NORMAL);
1142 ccb->ccb_h.func_code = XPT_GDEVLIST;
1145 * Basically, the point of this is that we go through
1146 * getting the list of devices, until we find a passthrough
1147 * device. In the current version of the CAM code, the
1148 * only way to determine what type of device we're dealing
1149 * with is by its name.
1151 while (found == 0) {
1152 ccb->cgdl.index = 0;
1153 ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
1154 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 dumping or SCHEDULER_STOPPED() here.
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 if (cam_sim_pollable(ccb->ccb_h.path->bus->sim))
1281 timeout = xpt_poll_setup(ccb);
1287 ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1293 xpt_pollwait(ccb, timeout);
1294 timeout = ccb->ccb_h.timeout * 10;
1296 cam_periph_ccbwait(ccb);
1298 if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1300 else if (error_routine != NULL) {
1301 ccb->ccb_h.cbfcnp = cam_periph_done;
1302 error = (*error_routine)(ccb, camflags, sense_flags);
1305 } while (error == ERESTART);
1308 if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1309 cam_release_devq(ccb->ccb_h.path,
1310 /* relsim_flags */0,
1313 /* getcount_only */ FALSE);
1314 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1319 devstat_tag_type tag;
1322 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
1323 bytes = ccb->csio.dxfer_len - ccb->csio.resid;
1324 tag = (devstat_tag_type)(ccb->csio.tag_action & 0x3);
1325 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
1326 bytes = ccb->ataio.dxfer_len - ccb->ataio.resid;
1327 tag = (devstat_tag_type)0;
1328 } else if (ccb->ccb_h.func_code == XPT_NVME_IO) {
1329 bytes = ccb->nvmeio.dxfer_len; /* NB: resid no possible */
1330 tag = (devstat_tag_type)0;
1335 devstat_end_transaction(ds, bytes, tag,
1336 ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_NONE) ?
1337 DEVSTAT_NO_DATA : (ccb->ccb_h.flags & CAM_DIR_OUT) ?
1338 DEVSTAT_WRITE : DEVSTAT_READ, NULL, starttime);
1345 cam_freeze_devq(struct cam_path *path)
1347 struct ccb_hdr ccb_h;
1349 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_freeze_devq\n"));
1350 memset(&ccb_h, 0, sizeof(ccb_h));
1351 xpt_setup_ccb(&ccb_h, path, /*priority*/1);
1352 ccb_h.func_code = XPT_NOOP;
1353 ccb_h.flags = CAM_DEV_QFREEZE;
1354 xpt_action((union ccb *)&ccb_h);
1358 cam_release_devq(struct cam_path *path, u_int32_t relsim_flags,
1359 u_int32_t openings, u_int32_t arg,
1362 struct ccb_relsim crs;
1364 CAM_DEBUG(path, CAM_DEBUG_TRACE, ("cam_release_devq(%u, %u, %u, %d)\n",
1365 relsim_flags, openings, arg, getcount_only));
1366 memset(&crs, 0, sizeof(crs));
1367 xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
1368 crs.ccb_h.func_code = XPT_REL_SIMQ;
1369 crs.ccb_h.flags = getcount_only ? CAM_DEV_QFREEZE : 0;
1370 crs.release_flags = relsim_flags;
1371 crs.openings = openings;
1372 crs.release_timeout = arg;
1373 xpt_action((union ccb *)&crs);
1374 return (crs.qfrozen_cnt);
1377 #define saved_ccb_ptr ppriv_ptr0
1379 camperiphdone(struct cam_periph *periph, union ccb *done_ccb)
1381 union ccb *saved_ccb;
1383 struct scsi_start_stop_unit *scsi_cmd;
1384 int error = 0, error_code, sense_key, asc, ascq;
1385 u_int16_t done_flags;
1387 scsi_cmd = (struct scsi_start_stop_unit *)
1388 &done_ccb->csio.cdb_io.cdb_bytes;
1389 status = done_ccb->ccb_h.status;
1391 if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1392 if (scsi_extract_sense_ccb(done_ccb,
1393 &error_code, &sense_key, &asc, &ascq)) {
1395 * If the error is "invalid field in CDB",
1396 * and the load/eject flag is set, turn the
1397 * flag off and try again. This is just in
1398 * case the drive in question barfs on the
1399 * load eject flag. The CAM code should set
1400 * the load/eject flag by default for
1403 if ((scsi_cmd->opcode == START_STOP_UNIT) &&
1404 ((scsi_cmd->how & SSS_LOEJ) != 0) &&
1405 (asc == 0x24) && (ascq == 0x00)) {
1406 scsi_cmd->how &= ~SSS_LOEJ;
1407 if (status & CAM_DEV_QFRZN) {
1408 cam_release_devq(done_ccb->ccb_h.path,
1410 done_ccb->ccb_h.status &=
1413 xpt_action(done_ccb);
1417 error = cam_periph_error(done_ccb, 0,
1418 SF_RETRY_UA | SF_NO_PRINT);
1419 if (error == ERESTART)
1421 if (done_ccb->ccb_h.status & CAM_DEV_QFRZN) {
1422 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1423 done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1427 * If we have successfully taken a device from the not
1428 * ready to ready state, re-scan the device and re-get
1429 * the inquiry information. Many devices (mostly disks)
1430 * don't properly report their inquiry information unless
1433 if (scsi_cmd->opcode == START_STOP_UNIT)
1434 xpt_async(AC_INQ_CHANGED, done_ccb->ccb_h.path, NULL);
1437 /* If we tried long wait and still failed, remember that. */
1438 if ((periph->flags & CAM_PERIPH_RECOVERY_WAIT) &&
1439 (done_ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY)) {
1440 periph->flags &= ~CAM_PERIPH_RECOVERY_WAIT;
1441 if (error != 0 && done_ccb->ccb_h.retry_count == 0)
1442 periph->flags |= CAM_PERIPH_RECOVERY_WAIT_FAILED;
1446 * After recovery action(s) completed, return to the original CCB.
1447 * If the recovery CCB has failed, considering its own possible
1448 * retries and recovery, assume we are back in state where we have
1449 * been originally, but without recovery hopes left. In such case,
1450 * after the final attempt below, we cancel any further retries,
1451 * blocking by that also any new recovery attempts for this CCB,
1452 * and the result will be the final one returned to the CCB owher.
1454 saved_ccb = (union ccb *)done_ccb->ccb_h.saved_ccb_ptr;
1455 KASSERT(saved_ccb->ccb_h.func_code == XPT_SCSI_IO,
1456 ("%s: saved_ccb func_code %#x != XPT_SCSI_IO",
1457 __func__, saved_ccb->ccb_h.func_code));
1458 KASSERT(done_ccb->ccb_h.func_code == XPT_SCSI_IO,
1459 ("%s: done_ccb func_code %#x != XPT_SCSI_IO",
1460 __func__, done_ccb->ccb_h.func_code));
1461 saved_ccb->ccb_h.periph_links = done_ccb->ccb_h.periph_links;
1462 done_flags = done_ccb->ccb_h.alloc_flags;
1463 bcopy(saved_ccb, done_ccb, sizeof(struct ccb_scsiio));
1464 done_ccb->ccb_h.alloc_flags = done_flags;
1465 xpt_free_ccb(saved_ccb);
1466 if (done_ccb->ccb_h.cbfcnp != camperiphdone)
1467 periph->flags &= ~CAM_PERIPH_RECOVERY_INPROG;
1469 done_ccb->ccb_h.retry_count = 0;
1470 xpt_action(done_ccb);
1473 /* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1474 cam_release_devq(done_ccb->ccb_h.path, 0, 0, 0, 0);
1478 * Generic Async Event handler. Peripheral drivers usually
1479 * filter out the events that require personal attention,
1480 * and leave the rest to this function.
1483 cam_periph_async(struct cam_periph *periph, u_int32_t code,
1484 struct cam_path *path, void *arg)
1487 case AC_LOST_DEVICE:
1488 cam_periph_invalidate(periph);
1496 cam_periph_bus_settle(struct cam_periph *periph, u_int bus_settle)
1498 struct ccb_getdevstats cgds;
1500 memset(&cgds, 0, sizeof(cgds));
1501 xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1502 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1503 xpt_action((union ccb *)&cgds);
1504 cam_periph_freeze_after_event(periph, &cgds.last_reset, bus_settle);
1508 cam_periph_freeze_after_event(struct cam_periph *periph,
1509 struct timeval* event_time, u_int duration_ms)
1511 struct timeval delta;
1512 struct timeval duration_tv;
1514 if (!timevalisset(event_time))
1518 timevalsub(&delta, event_time);
1519 duration_tv.tv_sec = duration_ms / 1000;
1520 duration_tv.tv_usec = (duration_ms % 1000) * 1000;
1521 if (timevalcmp(&delta, &duration_tv, <)) {
1522 timevalsub(&duration_tv, &delta);
1524 duration_ms = duration_tv.tv_sec * 1000;
1525 duration_ms += duration_tv.tv_usec / 1000;
1526 cam_freeze_devq(periph->path);
1527 cam_release_devq(periph->path,
1528 RELSIM_RELEASE_AFTER_TIMEOUT,
1530 /*timeout*/duration_ms,
1531 /*getcount_only*/0);
1537 camperiphscsistatuserror(union ccb *ccb, union ccb **orig_ccb,
1538 cam_flags camflags, u_int32_t sense_flags,
1539 int *openings, u_int32_t *relsim_flags,
1540 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1542 struct cam_periph *periph;
1545 switch (ccb->csio.scsi_status) {
1546 case SCSI_STATUS_OK:
1547 case SCSI_STATUS_COND_MET:
1548 case SCSI_STATUS_INTERMED:
1549 case SCSI_STATUS_INTERMED_COND_MET:
1552 case SCSI_STATUS_CMD_TERMINATED:
1553 case SCSI_STATUS_CHECK_COND:
1554 error = camperiphscsisenseerror(ccb, orig_ccb,
1563 case SCSI_STATUS_QUEUE_FULL:
1566 struct ccb_getdevstats cgds;
1569 * First off, find out what the current
1570 * transaction counts are.
1572 memset(&cgds, 0, sizeof(cgds));
1573 xpt_setup_ccb(&cgds.ccb_h,
1575 CAM_PRIORITY_NORMAL);
1576 cgds.ccb_h.func_code = XPT_GDEV_STATS;
1577 xpt_action((union ccb *)&cgds);
1580 * If we were the only transaction active, treat
1581 * the QUEUE FULL as if it were a BUSY condition.
1583 if (cgds.dev_active != 0) {
1587 * Reduce the number of openings to
1588 * be 1 less than the amount it took
1589 * to get a queue full bounded by the
1590 * minimum allowed tag count for this
1593 total_openings = cgds.dev_active + cgds.dev_openings;
1594 *openings = cgds.dev_active;
1595 if (*openings < cgds.mintags)
1596 *openings = cgds.mintags;
1597 if (*openings < total_openings)
1598 *relsim_flags = RELSIM_ADJUST_OPENINGS;
1601 * Some devices report queue full for
1602 * temporary resource shortages. For
1603 * this reason, we allow a minimum
1604 * tag count to be entered via a
1605 * quirk entry to prevent the queue
1606 * count on these devices from falling
1607 * to a pessimisticly low value. We
1608 * still wait for the next successful
1609 * completion, however, before queueing
1610 * more transactions to the device.
1612 *relsim_flags = RELSIM_RELEASE_AFTER_CMDCMPLT;
1616 *action &= ~SSQ_PRINT_SENSE;
1621 case SCSI_STATUS_BUSY:
1623 * Restart the queue after either another
1624 * command completes or a 1 second timeout.
1626 periph = xpt_path_periph(ccb->ccb_h.path);
1627 if (periph->flags & CAM_PERIPH_INVALID) {
1629 *action_string = "Periph was invalidated";
1630 } else if ((sense_flags & SF_RETRY_BUSY) != 0 ||
1631 ccb->ccb_h.retry_count > 0) {
1632 if ((sense_flags & SF_RETRY_BUSY) == 0)
1633 ccb->ccb_h.retry_count--;
1635 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT
1636 | RELSIM_RELEASE_AFTER_CMDCMPLT;
1640 *action_string = "Retries exhausted";
1643 case SCSI_STATUS_RESERV_CONFLICT:
1652 camperiphscsisenseerror(union ccb *ccb, union ccb **orig,
1653 cam_flags camflags, u_int32_t sense_flags,
1654 int *openings, u_int32_t *relsim_flags,
1655 u_int32_t *timeout, u_int32_t *action, const char **action_string)
1657 struct cam_periph *periph;
1658 union ccb *orig_ccb = ccb;
1659 int error, recoveryccb;
1662 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
1663 if (ccb->ccb_h.func_code == XPT_SCSI_IO && ccb->csio.bio != NULL)
1664 biotrack(ccb->csio.bio, __func__);
1667 periph = xpt_path_periph(ccb->ccb_h.path);
1668 recoveryccb = (ccb->ccb_h.cbfcnp == camperiphdone);
1669 if ((periph->flags & CAM_PERIPH_RECOVERY_INPROG) && !recoveryccb) {
1671 * If error recovery is already in progress, don't attempt
1672 * to process this error, but requeue it unconditionally
1673 * and attempt to process it once error recovery has
1674 * completed. This failed command is probably related to
1675 * the error that caused the currently active error recovery
1676 * action so our current recovery efforts should also
1677 * address this command. Be aware that the error recovery
1678 * code assumes that only one recovery action is in progress
1679 * on a particular peripheral instance at any given time
1680 * (e.g. only one saved CCB for error recovery) so it is
1681 * imperitive that we don't violate this assumption.
1684 *action &= ~SSQ_PRINT_SENSE;
1686 scsi_sense_action err_action;
1687 struct ccb_getdev cgd;
1690 * Grab the inquiry data for this device.
1692 memset(&cgd, 0, sizeof(cgd));
1693 xpt_setup_ccb(&cgd.ccb_h, ccb->ccb_h.path, CAM_PRIORITY_NORMAL);
1694 cgd.ccb_h.func_code = XPT_GDEV_TYPE;
1695 xpt_action((union ccb *)&cgd);
1697 err_action = scsi_error_action(&ccb->csio, &cgd.inq_data,
1699 error = err_action & SS_ERRMASK;
1702 * Do not autostart sequential access devices
1703 * to avoid unexpected tape loading.
1705 if ((err_action & SS_MASK) == SS_START &&
1706 SID_TYPE(&cgd.inq_data) == T_SEQUENTIAL) {
1707 *action_string = "Will not autostart a "
1708 "sequential access device";
1709 goto sense_error_done;
1713 * Avoid recovery recursion if recovery action is the same.
1715 if ((err_action & SS_MASK) >= SS_START && recoveryccb) {
1716 if (((err_action & SS_MASK) == SS_START &&
1717 ccb->csio.cdb_io.cdb_bytes[0] == START_STOP_UNIT) ||
1718 ((err_action & SS_MASK) == SS_TUR &&
1719 (ccb->csio.cdb_io.cdb_bytes[0] == TEST_UNIT_READY))) {
1720 err_action = SS_RETRY|SSQ_DECREMENT_COUNT|EIO;
1721 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1727 * If the recovery action will consume a retry,
1728 * make sure we actually have retries available.
1730 if ((err_action & SSQ_DECREMENT_COUNT) != 0) {
1731 if (ccb->ccb_h.retry_count > 0 &&
1732 (periph->flags & CAM_PERIPH_INVALID) == 0)
1733 ccb->ccb_h.retry_count--;
1735 *action_string = "Retries exhausted";
1736 goto sense_error_done;
1740 if ((err_action & SS_MASK) >= SS_START) {
1742 * Do common portions of commands that
1743 * use recovery CCBs.
1745 orig_ccb = xpt_alloc_ccb_nowait();
1746 if (orig_ccb == NULL) {
1747 *action_string = "Can't allocate recovery CCB";
1748 goto sense_error_done;
1751 * Clear freeze flag for original request here, as
1752 * this freeze will be dropped as part of ERESTART.
1754 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1756 KASSERT(ccb->ccb_h.func_code == XPT_SCSI_IO,
1757 ("%s: ccb func_code %#x != XPT_SCSI_IO",
1758 __func__, ccb->ccb_h.func_code));
1759 flags = orig_ccb->ccb_h.alloc_flags;
1760 bcopy(ccb, orig_ccb, sizeof(struct ccb_scsiio));
1761 orig_ccb->ccb_h.alloc_flags = flags;
1764 switch (err_action & SS_MASK) {
1766 *action_string = "No recovery action needed";
1770 *action_string = "Retrying command (per sense data)";
1774 *action_string = "Unretryable error";
1781 * Send a start unit command to the device, and
1782 * then retry the command.
1784 *action_string = "Attempting to start unit";
1785 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1788 * Check for removable media and set
1789 * load/eject flag appropriately.
1791 if (SID_IS_REMOVABLE(&cgd.inq_data))
1796 scsi_start_stop(&ccb->csio,
1810 * Send a Test Unit Ready to the device.
1811 * If the 'many' flag is set, we send 120
1812 * test unit ready commands, one every half
1813 * second. Otherwise, we just send one TUR.
1814 * We only want to do this if the retry
1815 * count has not been exhausted.
1819 if ((err_action & SSQ_MANY) != 0 && (periph->flags &
1820 CAM_PERIPH_RECOVERY_WAIT_FAILED) == 0) {
1821 periph->flags |= CAM_PERIPH_RECOVERY_WAIT;
1822 *action_string = "Polling device for readiness";
1825 *action_string = "Testing device for readiness";
1828 periph->flags |= CAM_PERIPH_RECOVERY_INPROG;
1829 scsi_test_unit_ready(&ccb->csio,
1837 * Accomplish our 500ms delay by deferring
1838 * the release of our device queue appropriately.
1840 *relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1845 panic("Unhandled error action %x", err_action);
1848 if ((err_action & SS_MASK) >= SS_START) {
1850 * Drop the priority, so that the recovery
1851 * CCB is the first to execute. Freeze the queue
1852 * after this command is sent so that we can
1853 * restore the old csio and have it queued in
1854 * the proper order before we release normal
1855 * transactions to the device.
1857 ccb->ccb_h.pinfo.priority--;
1858 ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1859 ccb->ccb_h.saved_ccb_ptr = orig_ccb;
1865 *action = err_action;
1871 * Generic error handler. Peripheral drivers usually filter
1872 * out the errors that they handle in a unique manner, then
1873 * call this function.
1876 cam_periph_error(union ccb *ccb, cam_flags camflags,
1877 u_int32_t sense_flags)
1879 struct cam_path *newpath;
1880 union ccb *orig_ccb, *scan_ccb;
1881 struct cam_periph *periph;
1882 const char *action_string;
1884 int frozen, error, openings, devctl_err;
1885 u_int32_t action, relsim_flags, timeout;
1887 action = SSQ_PRINT_SENSE;
1888 periph = xpt_path_periph(ccb->ccb_h.path);
1889 action_string = NULL;
1890 status = ccb->ccb_h.status;
1891 frozen = (status & CAM_DEV_QFRZN) != 0;
1892 status &= CAM_STATUS_MASK;
1893 devctl_err = openings = relsim_flags = timeout = 0;
1896 /* Filter the errors that should be reported via devctl */
1897 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
1898 case CAM_CMD_TIMEOUT:
1899 case CAM_REQ_ABORTED:
1900 case CAM_REQ_CMP_ERR:
1901 case CAM_REQ_TERMIO:
1902 case CAM_UNREC_HBA_ERROR:
1903 case CAM_DATA_RUN_ERR:
1904 case CAM_SCSI_STATUS_ERROR:
1905 case CAM_ATA_STATUS_ERROR:
1906 case CAM_SMP_STATUS_ERROR:
1916 action &= ~SSQ_PRINT_SENSE;
1918 case CAM_SCSI_STATUS_ERROR:
1919 error = camperiphscsistatuserror(ccb, &orig_ccb,
1920 camflags, sense_flags, &openings, &relsim_flags,
1921 &timeout, &action, &action_string);
1923 case CAM_AUTOSENSE_FAIL:
1924 error = EIO; /* we have to kill the command */
1928 case CAM_MSG_REJECT_REC:
1929 /* XXX Don't know that these are correct */
1932 case CAM_SEL_TIMEOUT:
1933 if ((camflags & CAM_RETRY_SELTO) != 0) {
1934 if (ccb->ccb_h.retry_count > 0 &&
1935 (periph->flags & CAM_PERIPH_INVALID) == 0) {
1936 ccb->ccb_h.retry_count--;
1940 * Wait a bit to give the device
1941 * time to recover before we try again.
1943 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1944 timeout = periph_selto_delay;
1947 action_string = "Retries exhausted";
1950 case CAM_DEV_NOT_THERE:
1954 case CAM_REQ_INVALID:
1955 case CAM_PATH_INVALID:
1957 case CAM_PROVIDE_FAIL:
1958 case CAM_REQ_TOO_BIG:
1959 case CAM_LUN_INVALID:
1960 case CAM_TID_INVALID:
1961 case CAM_FUNC_NOTAVAIL:
1964 case CAM_SCSI_BUS_RESET:
1967 * Commands that repeatedly timeout and cause these
1968 * kinds of error recovery actions, should return
1969 * CAM_CMD_TIMEOUT, which allows us to safely assume
1970 * that this command was an innocent bystander to
1971 * these events and should be unconditionally
1974 case CAM_REQUEUE_REQ:
1975 /* Unconditional requeue if device is still there */
1976 if (periph->flags & CAM_PERIPH_INVALID) {
1977 action_string = "Periph was invalidated";
1979 } else if (sense_flags & SF_NO_RETRY) {
1981 action_string = "Retry was blocked";
1984 action &= ~SSQ_PRINT_SENSE;
1987 case CAM_RESRC_UNAVAIL:
1988 /* Wait a bit for the resource shortage to abate. */
1989 timeout = periph_noresrc_delay;
1993 /* Wait a bit for the busy condition to abate. */
1994 timeout = periph_busy_delay;
1996 relsim_flags = RELSIM_RELEASE_AFTER_TIMEOUT;
1998 case CAM_ATA_STATUS_ERROR:
1999 case CAM_NVME_STATUS_ERROR:
2000 case CAM_SMP_STATUS_ERROR:
2001 case CAM_REQ_CMP_ERR:
2002 case CAM_CMD_TIMEOUT:
2003 case CAM_UNEXP_BUSFREE:
2004 case CAM_UNCOR_PARITY:
2005 case CAM_DATA_RUN_ERR:
2007 if (periph->flags & CAM_PERIPH_INVALID) {
2009 action_string = "Periph was invalidated";
2010 } else if (ccb->ccb_h.retry_count == 0) {
2012 action_string = "Retries exhausted";
2013 } else if (sense_flags & SF_NO_RETRY) {
2015 action_string = "Retry was blocked";
2017 ccb->ccb_h.retry_count--;
2023 if ((sense_flags & SF_PRINT_ALWAYS) ||
2024 CAM_DEBUGGED(ccb->ccb_h.path, CAM_DEBUG_INFO))
2025 action |= SSQ_PRINT_SENSE;
2026 else if (sense_flags & SF_NO_PRINT)
2027 action &= ~SSQ_PRINT_SENSE;
2028 if ((action & SSQ_PRINT_SENSE) != 0)
2029 cam_error_print(orig_ccb, CAM_ESF_ALL, CAM_EPF_ALL);
2030 if (error != 0 && (action & SSQ_PRINT_SENSE) != 0) {
2031 if (error != ERESTART) {
2032 if (action_string == NULL)
2033 action_string = "Unretryable error";
2034 xpt_print(ccb->ccb_h.path, "Error %d, %s\n",
2035 error, action_string);
2036 } else if (action_string != NULL)
2037 xpt_print(ccb->ccb_h.path, "%s\n", action_string);
2039 xpt_print(ccb->ccb_h.path,
2040 "Retrying command, %d more tries remain\n",
2041 ccb->ccb_h.retry_count);
2045 if (devctl_err && (error != 0 || (action & SSQ_PRINT_SENSE) != 0))
2046 cam_periph_devctl_notify(orig_ccb);
2048 if ((action & SSQ_LOST) != 0) {
2052 * For a selection timeout, we consider all of the LUNs on
2053 * the target to be gone. If the status is CAM_DEV_NOT_THERE,
2054 * then we only get rid of the device(s) specified by the
2055 * path in the original CCB.
2057 if (status == CAM_SEL_TIMEOUT)
2058 lun_id = CAM_LUN_WILDCARD;
2060 lun_id = xpt_path_lun_id(ccb->ccb_h.path);
2062 /* Should we do more if we can't create the path?? */
2063 if (xpt_create_path(&newpath, periph,
2064 xpt_path_path_id(ccb->ccb_h.path),
2065 xpt_path_target_id(ccb->ccb_h.path),
2066 lun_id) == CAM_REQ_CMP) {
2068 * Let peripheral drivers know that this
2069 * device has gone away.
2071 xpt_async(AC_LOST_DEVICE, newpath, NULL);
2072 xpt_free_path(newpath);
2076 /* Broadcast UNIT ATTENTIONs to all periphs. */
2077 if ((action & SSQ_UA) != 0)
2078 xpt_async(AC_UNIT_ATTENTION, orig_ccb->ccb_h.path, orig_ccb);
2080 /* Rescan target on "Reported LUNs data has changed" */
2081 if ((action & SSQ_RESCAN) != 0) {
2082 if (xpt_create_path(&newpath, NULL,
2083 xpt_path_path_id(ccb->ccb_h.path),
2084 xpt_path_target_id(ccb->ccb_h.path),
2085 CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
2086 scan_ccb = xpt_alloc_ccb_nowait();
2087 if (scan_ccb != NULL) {
2088 scan_ccb->ccb_h.path = newpath;
2089 scan_ccb->ccb_h.func_code = XPT_SCAN_TGT;
2090 scan_ccb->crcn.flags = 0;
2091 xpt_rescan(scan_ccb);
2094 "Can't allocate CCB to rescan target\n");
2095 xpt_free_path(newpath);
2100 /* Attempt a retry */
2101 if (error == ERESTART || error == 0) {
2103 ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
2104 if (error == ERESTART)
2107 cam_release_devq(ccb->ccb_h.path,
2111 /*getcount_only*/0);
2117 #define CAM_PERIPH_DEVD_MSG_SIZE 256
2120 cam_periph_devctl_notify(union ccb *ccb)
2122 struct cam_periph *periph;
2123 struct ccb_getdev *cgd;
2125 int serr, sk, asc, ascq;
2128 sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT);
2132 sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN);
2134 periph = xpt_path_periph(ccb->ccb_h.path);
2135 sbuf_printf(&sb, "device=%s%d ", periph->periph_name,
2136 periph->unit_number);
2138 sbuf_printf(&sb, "serial=\"");
2139 if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) {
2140 xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path,
2141 CAM_PRIORITY_NORMAL);
2142 cgd->ccb_h.func_code = XPT_GDEV_TYPE;
2143 xpt_action((union ccb *)cgd);
2145 if (cgd->ccb_h.status == CAM_REQ_CMP)
2146 sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len);
2147 xpt_free_ccb((union ccb *)cgd);
2149 sbuf_printf(&sb, "\" ");
2150 sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status);
2152 switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
2153 case CAM_CMD_TIMEOUT:
2154 sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout);
2157 case CAM_SCSI_STATUS_ERROR:
2158 sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status);
2159 if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq))
2160 sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ",
2161 serr, sk, asc, ascq);
2164 case CAM_ATA_STATUS_ERROR:
2165 sbuf_printf(&sb, "RES=\"");
2166 ata_res_sbuf(&ccb->ataio.res, &sb);
2167 sbuf_printf(&sb, "\" ");
2175 if (ccb->ccb_h.func_code == XPT_SCSI_IO) {
2176 sbuf_printf(&sb, "CDB=\"");
2177 scsi_cdb_sbuf(scsiio_cdb_ptr(&ccb->csio), &sb);
2178 sbuf_printf(&sb, "\" ");
2179 } else if (ccb->ccb_h.func_code == XPT_ATA_IO) {
2180 sbuf_printf(&sb, "ACB=\"");
2181 ata_cmd_sbuf(&ccb->ataio.cmd, &sb);
2182 sbuf_printf(&sb, "\" ");
2185 if (sbuf_finish(&sb) == 0)
2186 devctl_notify("CAM", "periph", type, sbuf_data(&sb));
2188 free(sbmsg, M_CAMPERIPH);
2192 * Sysctl to force an invalidation of the drive right now. Can be
2193 * called with CTLFLAG_MPSAFE since we take periph lock.
2196 cam_periph_invalidate_sysctl(SYSCTL_HANDLER_ARGS)
2198 struct cam_periph *periph;
2203 error = sysctl_handle_int(oidp, &value, 0, req);
2204 if (error != 0 || req->newptr == NULL || value != 1)
2207 cam_periph_lock(periph);
2208 cam_periph_invalidate(periph);
2209 cam_periph_unlock(periph);