]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cam/cam_xpt.c
Make `camcontrol modepage` support block descriptors.
[FreeBSD/FreeBSD.git] / sys / cam / cam_xpt.c
1 /*-
2  * Implementation of the Common Access Method Transport (XPT) layer.
3  *
4  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5  *
6  * Copyright (c) 1997, 1998, 1999 Justin T. Gibbs.
7  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification, immediately at the beginning of the file.
16  * 2. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #include "opt_printf.h"
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include <sys/param.h>
38 #include <sys/bio.h>
39 #include <sys/bus.h>
40 #include <sys/systm.h>
41 #include <sys/types.h>
42 #include <sys/malloc.h>
43 #include <sys/kernel.h>
44 #include <sys/time.h>
45 #include <sys/conf.h>
46 #include <sys/fcntl.h>
47 #include <sys/proc.h>
48 #include <sys/sbuf.h>
49 #include <sys/smp.h>
50 #include <sys/taskqueue.h>
51
52 #include <sys/lock.h>
53 #include <sys/mutex.h>
54 #include <sys/sysctl.h>
55 #include <sys/kthread.h>
56
57 #include <cam/cam.h>
58 #include <cam/cam_ccb.h>
59 #include <cam/cam_iosched.h>
60 #include <cam/cam_periph.h>
61 #include <cam/cam_queue.h>
62 #include <cam/cam_sim.h>
63 #include <cam/cam_xpt.h>
64 #include <cam/cam_xpt_sim.h>
65 #include <cam/cam_xpt_periph.h>
66 #include <cam/cam_xpt_internal.h>
67 #include <cam/cam_debug.h>
68 #include <cam/cam_compat.h>
69
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_message.h>
72 #include <cam/scsi/scsi_pass.h>
73
74 #include <machine/md_var.h>     /* geometry translation */
75 #include <machine/stdarg.h>     /* for xpt_print below */
76
77 #include "opt_cam.h"
78
79 /* Wild guess based on not wanting to grow the stack too much */
80 #define XPT_PRINT_MAXLEN        512
81 #ifdef PRINTF_BUFR_SIZE
82 #define XPT_PRINT_LEN   PRINTF_BUFR_SIZE
83 #else
84 #define XPT_PRINT_LEN   128
85 #endif
86 _Static_assert(XPT_PRINT_LEN <= XPT_PRINT_MAXLEN, "XPT_PRINT_LEN is too large");
87
88 /*
89  * This is the maximum number of high powered commands (e.g. start unit)
90  * that can be outstanding at a particular time.
91  */
92 #ifndef CAM_MAX_HIGHPOWER
93 #define CAM_MAX_HIGHPOWER  4
94 #endif
95
96 /* Datastructures internal to the xpt layer */
97 MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
98 MALLOC_DEFINE(M_CAMDEV, "CAM DEV", "CAM devices");
99 MALLOC_DEFINE(M_CAMCCB, "CAM CCB", "CAM CCBs");
100 MALLOC_DEFINE(M_CAMPATH, "CAM path", "CAM paths");
101
102 /* Object for defering XPT actions to a taskqueue */
103 struct xpt_task {
104         struct task     task;
105         void            *data1;
106         uintptr_t       data2;
107 };
108
109 struct xpt_softc {
110         uint32_t                xpt_generation;
111
112         /* number of high powered commands that can go through right now */
113         struct mtx              xpt_highpower_lock;
114         STAILQ_HEAD(highpowerlist, cam_ed)      highpowerq;
115         int                     num_highpower;
116
117         /* queue for handling async rescan requests. */
118         TAILQ_HEAD(, ccb_hdr) ccb_scanq;
119         int buses_to_config;
120         int buses_config_done;
121         int announce_nosbuf;
122
123         /*
124          * Registered buses
125          *
126          * N.B., "busses" is an archaic spelling of "buses".  In new code
127          * "buses" is preferred.
128          */
129         TAILQ_HEAD(,cam_eb)     xpt_busses;
130         u_int                   bus_generation;
131
132         struct intr_config_hook xpt_config_hook;
133
134         int                     boot_delay;
135         struct callout          boot_callout;
136
137         struct mtx              xpt_topo_lock;
138         struct mtx              xpt_lock;
139         struct taskqueue        *xpt_taskq;
140 };
141
142 typedef enum {
143         DM_RET_COPY             = 0x01,
144         DM_RET_FLAG_MASK        = 0x0f,
145         DM_RET_NONE             = 0x00,
146         DM_RET_STOP             = 0x10,
147         DM_RET_DESCEND          = 0x20,
148         DM_RET_ERROR            = 0x30,
149         DM_RET_ACTION_MASK      = 0xf0
150 } dev_match_ret;
151
152 typedef enum {
153         XPT_DEPTH_BUS,
154         XPT_DEPTH_TARGET,
155         XPT_DEPTH_DEVICE,
156         XPT_DEPTH_PERIPH
157 } xpt_traverse_depth;
158
159 struct xpt_traverse_config {
160         xpt_traverse_depth      depth;
161         void                    *tr_func;
162         void                    *tr_arg;
163 };
164
165 typedef int     xpt_busfunc_t (struct cam_eb *bus, void *arg);
166 typedef int     xpt_targetfunc_t (struct cam_et *target, void *arg);
167 typedef int     xpt_devicefunc_t (struct cam_ed *device, void *arg);
168 typedef int     xpt_periphfunc_t (struct cam_periph *periph, void *arg);
169 typedef int     xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
170
171 /* Transport layer configuration information */
172 static struct xpt_softc xsoftc;
173
174 MTX_SYSINIT(xpt_topo_init, &xsoftc.xpt_topo_lock, "XPT topology lock", MTX_DEF);
175
176 SYSCTL_INT(_kern_cam, OID_AUTO, boot_delay, CTLFLAG_RDTUN,
177            &xsoftc.boot_delay, 0, "Bus registration wait time");
178 SYSCTL_UINT(_kern_cam, OID_AUTO, xpt_generation, CTLFLAG_RD,
179             &xsoftc.xpt_generation, 0, "CAM peripheral generation count");
180 SYSCTL_INT(_kern_cam, OID_AUTO, announce_nosbuf, CTLFLAG_RWTUN,
181             &xsoftc.announce_nosbuf, 0, "Don't use sbuf for announcements");
182
183 struct cam_doneq {
184         struct mtx_padalign     cam_doneq_mtx;
185         STAILQ_HEAD(, ccb_hdr)  cam_doneq;
186         int                     cam_doneq_sleep;
187 };
188
189 static struct cam_doneq cam_doneqs[MAXCPU];
190 static int cam_num_doneqs;
191 static struct proc *cam_proc;
192
193 SYSCTL_INT(_kern_cam, OID_AUTO, num_doneqs, CTLFLAG_RDTUN,
194            &cam_num_doneqs, 0, "Number of completion queues/threads");
195
196 struct cam_periph *xpt_periph;
197
198 static periph_init_t xpt_periph_init;
199
200 static struct periph_driver xpt_driver =
201 {
202         xpt_periph_init, "xpt",
203         TAILQ_HEAD_INITIALIZER(xpt_driver.units), /* generation */ 0,
204         CAM_PERIPH_DRV_EARLY
205 };
206
207 PERIPHDRIVER_DECLARE(xpt, xpt_driver);
208
209 static d_open_t xptopen;
210 static d_close_t xptclose;
211 static d_ioctl_t xptioctl;
212 static d_ioctl_t xptdoioctl;
213
214 static struct cdevsw xpt_cdevsw = {
215         .d_version =    D_VERSION,
216         .d_flags =      0,
217         .d_open =       xptopen,
218         .d_close =      xptclose,
219         .d_ioctl =      xptioctl,
220         .d_name =       "xpt",
221 };
222
223 /* Storage for debugging datastructures */
224 struct cam_path *cam_dpath;
225 u_int32_t cam_dflags = CAM_DEBUG_FLAGS;
226 SYSCTL_UINT(_kern_cam, OID_AUTO, dflags, CTLFLAG_RWTUN,
227         &cam_dflags, 0, "Enabled debug flags");
228 u_int32_t cam_debug_delay = CAM_DEBUG_DELAY;
229 SYSCTL_UINT(_kern_cam, OID_AUTO, debug_delay, CTLFLAG_RWTUN,
230         &cam_debug_delay, 0, "Delay in us after each debug message");
231
232 /* Our boot-time initialization hook */
233 static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);
234
235 static moduledata_t cam_moduledata = {
236         "cam",
237         cam_module_event_handler,
238         NULL
239 };
240
241 static int      xpt_init(void *);
242
243 DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
244 MODULE_VERSION(cam, 1);
245
246
247 static void             xpt_async_bcast(struct async_list *async_head,
248                                         u_int32_t async_code,
249                                         struct cam_path *path,
250                                         void *async_arg);
251 static path_id_t xptnextfreepathid(void);
252 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
253 static union ccb *xpt_get_ccb(struct cam_periph *periph);
254 static union ccb *xpt_get_ccb_nowait(struct cam_periph *periph);
255 static void      xpt_run_allocq(struct cam_periph *periph, int sleep);
256 static void      xpt_run_allocq_task(void *context, int pending);
257 static void      xpt_run_devq(struct cam_devq *devq);
258 static timeout_t xpt_release_devq_timeout;
259 static void      xpt_release_simq_timeout(void *arg) __unused;
260 static void      xpt_acquire_bus(struct cam_eb *bus);
261 static void      xpt_release_bus(struct cam_eb *bus);
262 static uint32_t  xpt_freeze_devq_device(struct cam_ed *dev, u_int count);
263 static int       xpt_release_devq_device(struct cam_ed *dev, u_int count,
264                     int run_queue);
265 static struct cam_et*
266                  xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
267 static void      xpt_acquire_target(struct cam_et *target);
268 static void      xpt_release_target(struct cam_et *target);
269 static struct cam_eb*
270                  xpt_find_bus(path_id_t path_id);
271 static struct cam_et*
272                  xpt_find_target(struct cam_eb *bus, target_id_t target_id);
273 static struct cam_ed*
274                  xpt_find_device(struct cam_et *target, lun_id_t lun_id);
275 static void      xpt_config(void *arg);
276 static int       xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
277                                  u_int32_t new_priority);
278 static xpt_devicefunc_t xptpassannouncefunc;
279 static void      xptaction(struct cam_sim *sim, union ccb *work_ccb);
280 static void      xptpoll(struct cam_sim *sim);
281 static void      camisr_runqueue(void);
282 static void      xpt_done_process(struct ccb_hdr *ccb_h);
283 static void      xpt_done_td(void *);
284 static dev_match_ret    xptbusmatch(struct dev_match_pattern *patterns,
285                                     u_int num_patterns, struct cam_eb *bus);
286 static dev_match_ret    xptdevicematch(struct dev_match_pattern *patterns,
287                                        u_int num_patterns,
288                                        struct cam_ed *device);
289 static dev_match_ret    xptperiphmatch(struct dev_match_pattern *patterns,
290                                        u_int num_patterns,
291                                        struct cam_periph *periph);
292 static xpt_busfunc_t    xptedtbusfunc;
293 static xpt_targetfunc_t xptedttargetfunc;
294 static xpt_devicefunc_t xptedtdevicefunc;
295 static xpt_periphfunc_t xptedtperiphfunc;
296 static xpt_pdrvfunc_t   xptplistpdrvfunc;
297 static xpt_periphfunc_t xptplistperiphfunc;
298 static int              xptedtmatch(struct ccb_dev_match *cdm);
299 static int              xptperiphlistmatch(struct ccb_dev_match *cdm);
300 static int              xptbustraverse(struct cam_eb *start_bus,
301                                        xpt_busfunc_t *tr_func, void *arg);
302 static int              xpttargettraverse(struct cam_eb *bus,
303                                           struct cam_et *start_target,
304                                           xpt_targetfunc_t *tr_func, void *arg);
305 static int              xptdevicetraverse(struct cam_et *target,
306                                           struct cam_ed *start_device,
307                                           xpt_devicefunc_t *tr_func, void *arg);
308 static int              xptperiphtraverse(struct cam_ed *device,
309                                           struct cam_periph *start_periph,
310                                           xpt_periphfunc_t *tr_func, void *arg);
311 static int              xptpdrvtraverse(struct periph_driver **start_pdrv,
312                                         xpt_pdrvfunc_t *tr_func, void *arg);
313 static int              xptpdperiphtraverse(struct periph_driver **pdrv,
314                                             struct cam_periph *start_periph,
315                                             xpt_periphfunc_t *tr_func,
316                                             void *arg);
317 static xpt_busfunc_t    xptdefbusfunc;
318 static xpt_targetfunc_t xptdeftargetfunc;
319 static xpt_devicefunc_t xptdefdevicefunc;
320 static xpt_periphfunc_t xptdefperiphfunc;
321 static void             xpt_finishconfig_task(void *context, int pending);
322 static void             xpt_dev_async_default(u_int32_t async_code,
323                                               struct cam_eb *bus,
324                                               struct cam_et *target,
325                                               struct cam_ed *device,
326                                               void *async_arg);
327 static struct cam_ed *  xpt_alloc_device_default(struct cam_eb *bus,
328                                                  struct cam_et *target,
329                                                  lun_id_t lun_id);
330 static xpt_devicefunc_t xptsetasyncfunc;
331 static xpt_busfunc_t    xptsetasyncbusfunc;
332 static cam_status       xptregister(struct cam_periph *periph,
333                                     void *arg);
334 static __inline int device_is_queued(struct cam_ed *device);
335
336 static __inline int
337 xpt_schedule_devq(struct cam_devq *devq, struct cam_ed *dev)
338 {
339         int     retval;
340
341         mtx_assert(&devq->send_mtx, MA_OWNED);
342         if ((dev->ccbq.queue.entries > 0) &&
343             (dev->ccbq.dev_openings > 0) &&
344             (dev->ccbq.queue.qfrozen_cnt == 0)) {
345                 /*
346                  * The priority of a device waiting for controller
347                  * resources is that of the highest priority CCB
348                  * enqueued.
349                  */
350                 retval =
351                     xpt_schedule_dev(&devq->send_queue,
352                                      &dev->devq_entry,
353                                      CAMQ_GET_PRIO(&dev->ccbq.queue));
354         } else {
355                 retval = 0;
356         }
357         return (retval);
358 }
359
360 static __inline int
361 device_is_queued(struct cam_ed *device)
362 {
363         return (device->devq_entry.index != CAM_UNQUEUED_INDEX);
364 }
365
366 static void
367 xpt_periph_init()
368 {
369         make_dev(&xpt_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
370 }
371
372 static int
373 xptopen(struct cdev *dev, int flags, int fmt, struct thread *td)
374 {
375
376         /*
377          * Only allow read-write access.
378          */
379         if (((flags & FWRITE) == 0) || ((flags & FREAD) == 0))
380                 return(EPERM);
381
382         /*
383          * We don't allow nonblocking access.
384          */
385         if ((flags & O_NONBLOCK) != 0) {
386                 printf("%s: can't do nonblocking access\n", devtoname(dev));
387                 return(ENODEV);
388         }
389
390         return(0);
391 }
392
393 static int
394 xptclose(struct cdev *dev, int flag, int fmt, struct thread *td)
395 {
396
397         return(0);
398 }
399
400 /*
401  * Don't automatically grab the xpt softc lock here even though this is going
402  * through the xpt device.  The xpt device is really just a back door for
403  * accessing other devices and SIMs, so the right thing to do is to grab
404  * the appropriate SIM lock once the bus/SIM is located.
405  */
406 static int
407 xptioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
408 {
409         int error;
410
411         if ((error = xptdoioctl(dev, cmd, addr, flag, td)) == ENOTTY) {
412                 error = cam_compat_ioctl(dev, cmd, addr, flag, td, xptdoioctl);
413         }
414         return (error);
415 }
416
417 static int
418 xptdoioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
419 {
420         int error;
421
422         error = 0;
423
424         switch(cmd) {
425         /*
426          * For the transport layer CAMIOCOMMAND ioctl, we really only want
427          * to accept CCB types that don't quite make sense to send through a
428          * passthrough driver. XPT_PATH_INQ is an exception to this, as stated
429          * in the CAM spec.
430          */
431         case CAMIOCOMMAND: {
432                 union ccb *ccb;
433                 union ccb *inccb;
434                 struct cam_eb *bus;
435
436                 inccb = (union ccb *)addr;
437 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
438                 if (inccb->ccb_h.func_code == XPT_SCSI_IO)
439                         inccb->csio.bio = NULL;
440 #endif
441
442                 if (inccb->ccb_h.flags & CAM_UNLOCKED)
443                         return (EINVAL);
444
445                 bus = xpt_find_bus(inccb->ccb_h.path_id);
446                 if (bus == NULL)
447                         return (EINVAL);
448
449                 switch (inccb->ccb_h.func_code) {
450                 case XPT_SCAN_BUS:
451                 case XPT_RESET_BUS:
452                         if (inccb->ccb_h.target_id != CAM_TARGET_WILDCARD ||
453                             inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
454                                 xpt_release_bus(bus);
455                                 return (EINVAL);
456                         }
457                         break;
458                 case XPT_SCAN_TGT:
459                         if (inccb->ccb_h.target_id == CAM_TARGET_WILDCARD ||
460                             inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
461                                 xpt_release_bus(bus);
462                                 return (EINVAL);
463                         }
464                         break;
465                 default:
466                         break;
467                 }
468
469                 switch(inccb->ccb_h.func_code) {
470                 case XPT_SCAN_BUS:
471                 case XPT_RESET_BUS:
472                 case XPT_PATH_INQ:
473                 case XPT_ENG_INQ:
474                 case XPT_SCAN_LUN:
475                 case XPT_SCAN_TGT:
476
477                         ccb = xpt_alloc_ccb();
478
479                         /*
480                          * Create a path using the bus, target, and lun the
481                          * user passed in.
482                          */
483                         if (xpt_create_path(&ccb->ccb_h.path, NULL,
484                                             inccb->ccb_h.path_id,
485                                             inccb->ccb_h.target_id,
486                                             inccb->ccb_h.target_lun) !=
487                                             CAM_REQ_CMP){
488                                 error = EINVAL;
489                                 xpt_free_ccb(ccb);
490                                 break;
491                         }
492                         /* Ensure all of our fields are correct */
493                         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
494                                       inccb->ccb_h.pinfo.priority);
495                         xpt_merge_ccb(ccb, inccb);
496                         xpt_path_lock(ccb->ccb_h.path);
497                         cam_periph_runccb(ccb, NULL, 0, 0, NULL);
498                         xpt_path_unlock(ccb->ccb_h.path);
499                         bcopy(ccb, inccb, sizeof(union ccb));
500                         xpt_free_path(ccb->ccb_h.path);
501                         xpt_free_ccb(ccb);
502                         break;
503
504                 case XPT_DEBUG: {
505                         union ccb ccb;
506
507                         /*
508                          * This is an immediate CCB, so it's okay to
509                          * allocate it on the stack.
510                          */
511
512                         /*
513                          * Create a path using the bus, target, and lun the
514                          * user passed in.
515                          */
516                         if (xpt_create_path(&ccb.ccb_h.path, NULL,
517                                             inccb->ccb_h.path_id,
518                                             inccb->ccb_h.target_id,
519                                             inccb->ccb_h.target_lun) !=
520                                             CAM_REQ_CMP){
521                                 error = EINVAL;
522                                 break;
523                         }
524                         /* Ensure all of our fields are correct */
525                         xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
526                                       inccb->ccb_h.pinfo.priority);
527                         xpt_merge_ccb(&ccb, inccb);
528                         xpt_action(&ccb);
529                         bcopy(&ccb, inccb, sizeof(union ccb));
530                         xpt_free_path(ccb.ccb_h.path);
531                         break;
532
533                 }
534                 case XPT_DEV_MATCH: {
535                         struct cam_periph_map_info mapinfo;
536                         struct cam_path *old_path;
537
538                         /*
539                          * We can't deal with physical addresses for this
540                          * type of transaction.
541                          */
542                         if ((inccb->ccb_h.flags & CAM_DATA_MASK) !=
543                             CAM_DATA_VADDR) {
544                                 error = EINVAL;
545                                 break;
546                         }
547
548                         /*
549                          * Save this in case the caller had it set to
550                          * something in particular.
551                          */
552                         old_path = inccb->ccb_h.path;
553
554                         /*
555                          * We really don't need a path for the matching
556                          * code.  The path is needed because of the
557                          * debugging statements in xpt_action().  They
558                          * assume that the CCB has a valid path.
559                          */
560                         inccb->ccb_h.path = xpt_periph->path;
561
562                         bzero(&mapinfo, sizeof(mapinfo));
563
564                         /*
565                          * Map the pattern and match buffers into kernel
566                          * virtual address space.
567                          */
568                         error = cam_periph_mapmem(inccb, &mapinfo, MAXPHYS);
569
570                         if (error) {
571                                 inccb->ccb_h.path = old_path;
572                                 break;
573                         }
574
575                         /*
576                          * This is an immediate CCB, we can send it on directly.
577                          */
578                         xpt_action(inccb);
579
580                         /*
581                          * Map the buffers back into user space.
582                          */
583                         cam_periph_unmapmem(inccb, &mapinfo);
584
585                         inccb->ccb_h.path = old_path;
586
587                         error = 0;
588                         break;
589                 }
590                 default:
591                         error = ENOTSUP;
592                         break;
593                 }
594                 xpt_release_bus(bus);
595                 break;
596         }
597         /*
598          * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
599          * with the periphal driver name and unit name filled in.  The other
600          * fields don't really matter as input.  The passthrough driver name
601          * ("pass"), and unit number are passed back in the ccb.  The current
602          * device generation number, and the index into the device peripheral
603          * driver list, and the status are also passed back.  Note that
604          * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
605          * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
606          * (or rather should be) impossible for the device peripheral driver
607          * list to change since we look at the whole thing in one pass, and
608          * we do it with lock protection.
609          *
610          */
611         case CAMGETPASSTHRU: {
612                 union ccb *ccb;
613                 struct cam_periph *periph;
614                 struct periph_driver **p_drv;
615                 char   *name;
616                 u_int unit;
617                 int base_periph_found;
618
619                 ccb = (union ccb *)addr;
620                 unit = ccb->cgdl.unit_number;
621                 name = ccb->cgdl.periph_name;
622                 base_periph_found = 0;
623 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
624                 if (ccb->ccb_h.func_code == XPT_SCSI_IO)
625                         ccb->csio.bio = NULL;
626 #endif
627
628                 /*
629                  * Sanity check -- make sure we don't get a null peripheral
630                  * driver name.
631                  */
632                 if (*ccb->cgdl.periph_name == '\0') {
633                         error = EINVAL;
634                         break;
635                 }
636
637                 /* Keep the list from changing while we traverse it */
638                 xpt_lock_buses();
639
640                 /* first find our driver in the list of drivers */
641                 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++)
642                         if (strcmp((*p_drv)->driver_name, name) == 0)
643                                 break;
644
645                 if (*p_drv == NULL) {
646                         xpt_unlock_buses();
647                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
648                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
649                         *ccb->cgdl.periph_name = '\0';
650                         ccb->cgdl.unit_number = 0;
651                         error = ENOENT;
652                         break;
653                 }
654
655                 /*
656                  * Run through every peripheral instance of this driver
657                  * and check to see whether it matches the unit passed
658                  * in by the user.  If it does, get out of the loops and
659                  * find the passthrough driver associated with that
660                  * peripheral driver.
661                  */
662                 for (periph = TAILQ_FIRST(&(*p_drv)->units); periph != NULL;
663                      periph = TAILQ_NEXT(periph, unit_links)) {
664
665                         if (periph->unit_number == unit)
666                                 break;
667                 }
668                 /*
669                  * If we found the peripheral driver that the user passed
670                  * in, go through all of the peripheral drivers for that
671                  * particular device and look for a passthrough driver.
672                  */
673                 if (periph != NULL) {
674                         struct cam_ed *device;
675                         int i;
676
677                         base_periph_found = 1;
678                         device = periph->path->device;
679                         for (i = 0, periph = SLIST_FIRST(&device->periphs);
680                              periph != NULL;
681                              periph = SLIST_NEXT(periph, periph_links), i++) {
682                                 /*
683                                  * Check to see whether we have a
684                                  * passthrough device or not.
685                                  */
686                                 if (strcmp(periph->periph_name, "pass") == 0) {
687                                         /*
688                                          * Fill in the getdevlist fields.
689                                          */
690                                         strlcpy(ccb->cgdl.periph_name,
691                                                periph->periph_name,
692                                                sizeof(ccb->cgdl.periph_name));
693                                         ccb->cgdl.unit_number =
694                                                 periph->unit_number;
695                                         if (SLIST_NEXT(periph, periph_links))
696                                                 ccb->cgdl.status =
697                                                         CAM_GDEVLIST_MORE_DEVS;
698                                         else
699                                                 ccb->cgdl.status =
700                                                        CAM_GDEVLIST_LAST_DEVICE;
701                                         ccb->cgdl.generation =
702                                                 device->generation;
703                                         ccb->cgdl.index = i;
704                                         /*
705                                          * Fill in some CCB header fields
706                                          * that the user may want.
707                                          */
708                                         ccb->ccb_h.path_id =
709                                                 periph->path->bus->path_id;
710                                         ccb->ccb_h.target_id =
711                                                 periph->path->target->target_id;
712                                         ccb->ccb_h.target_lun =
713                                                 periph->path->device->lun_id;
714                                         ccb->ccb_h.status = CAM_REQ_CMP;
715                                         break;
716                                 }
717                         }
718                 }
719
720                 /*
721                  * If the periph is null here, one of two things has
722                  * happened.  The first possibility is that we couldn't
723                  * find the unit number of the particular peripheral driver
724                  * that the user is asking about.  e.g. the user asks for
725                  * the passthrough driver for "da11".  We find the list of
726                  * "da" peripherals all right, but there is no unit 11.
727                  * The other possibility is that we went through the list
728                  * of peripheral drivers attached to the device structure,
729                  * but didn't find one with the name "pass".  Either way,
730                  * we return ENOENT, since we couldn't find something.
731                  */
732                 if (periph == NULL) {
733                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
734                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
735                         *ccb->cgdl.periph_name = '\0';
736                         ccb->cgdl.unit_number = 0;
737                         error = ENOENT;
738                         /*
739                          * It is unfortunate that this is even necessary,
740                          * but there are many, many clueless users out there.
741                          * If this is true, the user is looking for the
742                          * passthrough driver, but doesn't have one in his
743                          * kernel.
744                          */
745                         if (base_periph_found == 1) {
746                                 printf("xptioctl: pass driver is not in the "
747                                        "kernel\n");
748                                 printf("xptioctl: put \"device pass\" in "
749                                        "your kernel config file\n");
750                         }
751                 }
752                 xpt_unlock_buses();
753                 break;
754                 }
755         default:
756                 error = ENOTTY;
757                 break;
758         }
759
760         return(error);
761 }
762
763 static int
764 cam_module_event_handler(module_t mod, int what, void *arg)
765 {
766         int error;
767
768         switch (what) {
769         case MOD_LOAD:
770                 if ((error = xpt_init(NULL)) != 0)
771                         return (error);
772                 break;
773         case MOD_UNLOAD:
774                 return EBUSY;
775         default:
776                 return EOPNOTSUPP;
777         }
778
779         return 0;
780 }
781
782 static struct xpt_proto *
783 xpt_proto_find(cam_proto proto)
784 {
785         struct xpt_proto **pp;
786
787         SET_FOREACH(pp, cam_xpt_proto_set) {
788                 if ((*pp)->proto == proto)
789                         return *pp;
790         }
791
792         return NULL;
793 }
794
795 static void
796 xpt_rescan_done(struct cam_periph *periph, union ccb *done_ccb)
797 {
798
799         if (done_ccb->ccb_h.ppriv_ptr1 == NULL) {
800                 xpt_free_path(done_ccb->ccb_h.path);
801                 xpt_free_ccb(done_ccb);
802         } else {
803                 done_ccb->ccb_h.cbfcnp = done_ccb->ccb_h.ppriv_ptr1;
804                 (*done_ccb->ccb_h.cbfcnp)(periph, done_ccb);
805         }
806         xpt_release_boot();
807 }
808
809 /* thread to handle bus rescans */
810 static void
811 xpt_scanner_thread(void *dummy)
812 {
813         union ccb       *ccb;
814         struct cam_path  path;
815
816         xpt_lock_buses();
817         for (;;) {
818                 if (TAILQ_EMPTY(&xsoftc.ccb_scanq))
819                         msleep(&xsoftc.ccb_scanq, &xsoftc.xpt_topo_lock, PRIBIO,
820                                "-", 0);
821                 if ((ccb = (union ccb *)TAILQ_FIRST(&xsoftc.ccb_scanq)) != NULL) {
822                         TAILQ_REMOVE(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
823                         xpt_unlock_buses();
824
825                         /*
826                          * Since lock can be dropped inside and path freed
827                          * by completion callback even before return here,
828                          * take our own path copy for reference.
829                          */
830                         xpt_copy_path(&path, ccb->ccb_h.path);
831                         xpt_path_lock(&path);
832                         xpt_action(ccb);
833                         xpt_path_unlock(&path);
834                         xpt_release_path(&path);
835
836                         xpt_lock_buses();
837                 }
838         }
839 }
840
841 void
842 xpt_rescan(union ccb *ccb)
843 {
844         struct ccb_hdr *hdr;
845
846         /* Prepare request */
847         if (ccb->ccb_h.path->target->target_id == CAM_TARGET_WILDCARD &&
848             ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
849                 ccb->ccb_h.func_code = XPT_SCAN_BUS;
850         else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
851             ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
852                 ccb->ccb_h.func_code = XPT_SCAN_TGT;
853         else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
854             ccb->ccb_h.path->device->lun_id != CAM_LUN_WILDCARD)
855                 ccb->ccb_h.func_code = XPT_SCAN_LUN;
856         else {
857                 xpt_print(ccb->ccb_h.path, "illegal scan path\n");
858                 xpt_free_path(ccb->ccb_h.path);
859                 xpt_free_ccb(ccb);
860                 return;
861         }
862         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
863             ("xpt_rescan: func %#x %s\n", ccb->ccb_h.func_code,
864                 xpt_action_name(ccb->ccb_h.func_code)));
865
866         ccb->ccb_h.ppriv_ptr1 = ccb->ccb_h.cbfcnp;
867         ccb->ccb_h.cbfcnp = xpt_rescan_done;
868         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path, CAM_PRIORITY_XPT);
869         /* Don't make duplicate entries for the same paths. */
870         xpt_lock_buses();
871         if (ccb->ccb_h.ppriv_ptr1 == NULL) {
872                 TAILQ_FOREACH(hdr, &xsoftc.ccb_scanq, sim_links.tqe) {
873                         if (xpt_path_comp(hdr->path, ccb->ccb_h.path) == 0) {
874                                 wakeup(&xsoftc.ccb_scanq);
875                                 xpt_unlock_buses();
876                                 xpt_print(ccb->ccb_h.path, "rescan already queued\n");
877                                 xpt_free_path(ccb->ccb_h.path);
878                                 xpt_free_ccb(ccb);
879                                 return;
880                         }
881                 }
882         }
883         TAILQ_INSERT_TAIL(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
884         xsoftc.buses_to_config++;
885         wakeup(&xsoftc.ccb_scanq);
886         xpt_unlock_buses();
887 }
888
889 /* Functions accessed by the peripheral drivers */
890 static int
891 xpt_init(void *dummy)
892 {
893         struct cam_sim *xpt_sim;
894         struct cam_path *path;
895         struct cam_devq *devq;
896         cam_status status;
897         int error, i;
898
899         TAILQ_INIT(&xsoftc.xpt_busses);
900         TAILQ_INIT(&xsoftc.ccb_scanq);
901         STAILQ_INIT(&xsoftc.highpowerq);
902         xsoftc.num_highpower = CAM_MAX_HIGHPOWER;
903
904         mtx_init(&xsoftc.xpt_lock, "XPT lock", NULL, MTX_DEF);
905         mtx_init(&xsoftc.xpt_highpower_lock, "XPT highpower lock", NULL, MTX_DEF);
906         xsoftc.xpt_taskq = taskqueue_create("CAM XPT task", M_WAITOK,
907             taskqueue_thread_enqueue, /*context*/&xsoftc.xpt_taskq);
908
909 #ifdef CAM_BOOT_DELAY
910         /*
911          * Override this value at compile time to assist our users
912          * who don't use loader to boot a kernel.
913          */
914         xsoftc.boot_delay = CAM_BOOT_DELAY;
915 #endif
916         /*
917          * The xpt layer is, itself, the equivalent of a SIM.
918          * Allow 16 ccbs in the ccb pool for it.  This should
919          * give decent parallelism when we probe buses and
920          * perform other XPT functions.
921          */
922         devq = cam_simq_alloc(16);
923         xpt_sim = cam_sim_alloc(xptaction,
924                                 xptpoll,
925                                 "xpt",
926                                 /*softc*/NULL,
927                                 /*unit*/0,
928                                 /*mtx*/&xsoftc.xpt_lock,
929                                 /*max_dev_transactions*/0,
930                                 /*max_tagged_dev_transactions*/0,
931                                 devq);
932         if (xpt_sim == NULL)
933                 return (ENOMEM);
934
935         mtx_lock(&xsoftc.xpt_lock);
936         if ((status = xpt_bus_register(xpt_sim, NULL, 0)) != CAM_SUCCESS) {
937                 mtx_unlock(&xsoftc.xpt_lock);
938                 printf("xpt_init: xpt_bus_register failed with status %#x,"
939                        " failing attach\n", status);
940                 return (EINVAL);
941         }
942         mtx_unlock(&xsoftc.xpt_lock);
943
944         /*
945          * Looking at the XPT from the SIM layer, the XPT is
946          * the equivalent of a peripheral driver.  Allocate
947          * a peripheral driver entry for us.
948          */
949         if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
950                                       CAM_TARGET_WILDCARD,
951                                       CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
952                 printf("xpt_init: xpt_create_path failed with status %#x,"
953                        " failing attach\n", status);
954                 return (EINVAL);
955         }
956         xpt_path_lock(path);
957         cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
958                          path, NULL, 0, xpt_sim);
959         xpt_path_unlock(path);
960         xpt_free_path(path);
961
962         if (cam_num_doneqs < 1)
963                 cam_num_doneqs = 1 + mp_ncpus / 6;
964         else if (cam_num_doneqs > MAXCPU)
965                 cam_num_doneqs = MAXCPU;
966         for (i = 0; i < cam_num_doneqs; i++) {
967                 mtx_init(&cam_doneqs[i].cam_doneq_mtx, "CAM doneq", NULL,
968                     MTX_DEF);
969                 STAILQ_INIT(&cam_doneqs[i].cam_doneq);
970                 error = kproc_kthread_add(xpt_done_td, &cam_doneqs[i],
971                     &cam_proc, NULL, 0, 0, "cam", "doneq%d", i);
972                 if (error != 0) {
973                         cam_num_doneqs = i;
974                         break;
975                 }
976         }
977         if (cam_num_doneqs < 1) {
978                 printf("xpt_init: Cannot init completion queues "
979                        "- failing attach\n");
980                 return (ENOMEM);
981         }
982         /*
983          * Register a callback for when interrupts are enabled.
984          */
985         xsoftc.xpt_config_hook.ich_func = xpt_config;
986         if (config_intrhook_establish(&xsoftc.xpt_config_hook) != 0) {
987                 printf("xpt_init: config_intrhook_establish failed "
988                        "- failing attach\n");
989         }
990
991         return (0);
992 }
993
994 static cam_status
995 xptregister(struct cam_periph *periph, void *arg)
996 {
997         struct cam_sim *xpt_sim;
998
999         if (periph == NULL) {
1000                 printf("xptregister: periph was NULL!!\n");
1001                 return(CAM_REQ_CMP_ERR);
1002         }
1003
1004         xpt_sim = (struct cam_sim *)arg;
1005         xpt_sim->softc = periph;
1006         xpt_periph = periph;
1007         periph->softc = NULL;
1008
1009         return(CAM_REQ_CMP);
1010 }
1011
1012 int32_t
1013 xpt_add_periph(struct cam_periph *periph)
1014 {
1015         struct cam_ed *device;
1016         int32_t  status;
1017
1018         TASK_INIT(&periph->periph_run_task, 0, xpt_run_allocq_task, periph);
1019         device = periph->path->device;
1020         status = CAM_REQ_CMP;
1021         if (device != NULL) {
1022                 mtx_lock(&device->target->bus->eb_mtx);
1023                 device->generation++;
1024                 SLIST_INSERT_HEAD(&device->periphs, periph, periph_links);
1025                 mtx_unlock(&device->target->bus->eb_mtx);
1026                 atomic_add_32(&xsoftc.xpt_generation, 1);
1027         }
1028
1029         return (status);
1030 }
1031
1032 void
1033 xpt_remove_periph(struct cam_periph *periph)
1034 {
1035         struct cam_ed *device;
1036
1037         device = periph->path->device;
1038         if (device != NULL) {
1039                 mtx_lock(&device->target->bus->eb_mtx);
1040                 device->generation++;
1041                 SLIST_REMOVE(&device->periphs, periph, cam_periph, periph_links);
1042                 mtx_unlock(&device->target->bus->eb_mtx);
1043                 atomic_add_32(&xsoftc.xpt_generation, 1);
1044         }
1045 }
1046
1047
1048 void
1049 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1050 {
1051         struct  cam_path *path = periph->path;
1052         struct  xpt_proto *proto;
1053
1054         cam_periph_assert(periph, MA_OWNED);
1055         periph->flags |= CAM_PERIPH_ANNOUNCED;
1056
1057         printf("%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1058                periph->periph_name, periph->unit_number,
1059                path->bus->sim->sim_name,
1060                path->bus->sim->unit_number,
1061                path->bus->sim->bus_id,
1062                path->bus->path_id,
1063                path->target->target_id,
1064                (uintmax_t)path->device->lun_id);
1065         printf("%s%d: ", periph->periph_name, periph->unit_number);
1066         proto = xpt_proto_find(path->device->protocol);
1067         if (proto)
1068                 proto->ops->announce(path->device);
1069         else
1070                 printf("%s%d: Unknown protocol device %d\n",
1071                     periph->periph_name, periph->unit_number,
1072                     path->device->protocol);
1073         if (path->device->serial_num_len > 0) {
1074                 /* Don't wrap the screen  - print only the first 60 chars */
1075                 printf("%s%d: Serial Number %.60s\n", periph->periph_name,
1076                        periph->unit_number, path->device->serial_num);
1077         }
1078         /* Announce transport details. */
1079         path->bus->xport->ops->announce(periph);
1080         /* Announce command queueing. */
1081         if (path->device->inq_flags & SID_CmdQue
1082          || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1083                 printf("%s%d: Command Queueing enabled\n",
1084                        periph->periph_name, periph->unit_number);
1085         }
1086         /* Announce caller's details if they've passed in. */
1087         if (announce_string != NULL)
1088                 printf("%s%d: %s\n", periph->periph_name,
1089                        periph->unit_number, announce_string);
1090 }
1091
1092 void
1093 xpt_announce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb,
1094     char *announce_string)
1095 {
1096         struct  cam_path *path = periph->path;
1097         struct  xpt_proto *proto;
1098
1099         cam_periph_assert(periph, MA_OWNED);
1100         periph->flags |= CAM_PERIPH_ANNOUNCED;
1101
1102         /* Fall back to the non-sbuf method if necessary */
1103         if (xsoftc.announce_nosbuf != 0) {
1104                 xpt_announce_periph(periph, announce_string);
1105                 return;
1106         }
1107         proto = xpt_proto_find(path->device->protocol);
1108         if (((proto != NULL) && (proto->ops->announce_sbuf == NULL)) ||
1109             (path->bus->xport->ops->announce_sbuf == NULL)) {
1110                 xpt_announce_periph(periph, announce_string);
1111                 return;
1112         }
1113
1114         sbuf_printf(sb, "%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1115             periph->periph_name, periph->unit_number,
1116             path->bus->sim->sim_name,
1117             path->bus->sim->unit_number,
1118             path->bus->sim->bus_id,
1119             path->bus->path_id,
1120             path->target->target_id,
1121             (uintmax_t)path->device->lun_id);
1122         sbuf_printf(sb, "%s%d: ", periph->periph_name, periph->unit_number);
1123
1124         if (proto)
1125                 proto->ops->announce_sbuf(path->device, sb);
1126         else
1127                 sbuf_printf(sb, "%s%d: Unknown protocol device %d\n",
1128                     periph->periph_name, periph->unit_number,
1129                     path->device->protocol);
1130         if (path->device->serial_num_len > 0) {
1131                 /* Don't wrap the screen  - print only the first 60 chars */
1132                 sbuf_printf(sb, "%s%d: Serial Number %.60s\n",
1133                     periph->periph_name, periph->unit_number,
1134                     path->device->serial_num);
1135         }
1136         /* Announce transport details. */
1137         path->bus->xport->ops->announce_sbuf(periph, sb);
1138         /* Announce command queueing. */
1139         if (path->device->inq_flags & SID_CmdQue
1140          || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1141                 sbuf_printf(sb, "%s%d: Command Queueing enabled\n",
1142                     periph->periph_name, periph->unit_number);
1143         }
1144         /* Announce caller's details if they've passed in. */
1145         if (announce_string != NULL)
1146                 sbuf_printf(sb, "%s%d: %s\n", periph->periph_name,
1147                     periph->unit_number, announce_string);
1148 }
1149
1150 void
1151 xpt_announce_quirks(struct cam_periph *periph, int quirks, char *bit_string)
1152 {
1153         if (quirks != 0) {
1154                 printf("%s%d: quirks=0x%b\n", periph->periph_name,
1155                     periph->unit_number, quirks, bit_string);
1156         }
1157 }
1158
1159 void
1160 xpt_announce_quirks_sbuf(struct cam_periph *periph, struct sbuf *sb,
1161                          int quirks, char *bit_string)
1162 {
1163         if (xsoftc.announce_nosbuf != 0) {
1164                 xpt_announce_quirks(periph, quirks, bit_string);
1165                 return;
1166         }
1167
1168         if (quirks != 0) {
1169                 sbuf_printf(sb, "%s%d: quirks=0x%b\n", periph->periph_name,
1170                     periph->unit_number, quirks, bit_string);
1171         }
1172 }
1173
1174 void
1175 xpt_denounce_periph(struct cam_periph *periph)
1176 {
1177         struct  cam_path *path = periph->path;
1178         struct  xpt_proto *proto;
1179
1180         cam_periph_assert(periph, MA_OWNED);
1181         printf("%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1182                periph->periph_name, periph->unit_number,
1183                path->bus->sim->sim_name,
1184                path->bus->sim->unit_number,
1185                path->bus->sim->bus_id,
1186                path->bus->path_id,
1187                path->target->target_id,
1188                (uintmax_t)path->device->lun_id);
1189         printf("%s%d: ", periph->periph_name, periph->unit_number);
1190         proto = xpt_proto_find(path->device->protocol);
1191         if (proto)
1192                 proto->ops->denounce(path->device);
1193         else
1194                 printf("%s%d: Unknown protocol device %d\n",
1195                     periph->periph_name, periph->unit_number,
1196                     path->device->protocol);
1197         if (path->device->serial_num_len > 0)
1198                 printf(" s/n %.60s", path->device->serial_num);
1199         printf(" detached\n");
1200 }
1201
1202 void
1203 xpt_denounce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb)
1204 {
1205         struct cam_path *path = periph->path;
1206         struct xpt_proto *proto;
1207
1208         cam_periph_assert(periph, MA_OWNED);
1209
1210         /* Fall back to the non-sbuf method if necessary */
1211         if (xsoftc.announce_nosbuf != 0) {
1212                 xpt_denounce_periph(periph);
1213                 return;
1214         }
1215         proto = xpt_proto_find(path->device->protocol);
1216         if ((proto != NULL) && (proto->ops->denounce_sbuf == NULL)) {
1217                 xpt_denounce_periph(periph);
1218                 return;
1219         }
1220
1221         sbuf_printf(sb, "%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1222             periph->periph_name, periph->unit_number,
1223             path->bus->sim->sim_name,
1224             path->bus->sim->unit_number,
1225             path->bus->sim->bus_id,
1226             path->bus->path_id,
1227             path->target->target_id,
1228             (uintmax_t)path->device->lun_id);
1229         sbuf_printf(sb, "%s%d: ", periph->periph_name, periph->unit_number);
1230
1231         if (proto)
1232                 proto->ops->denounce_sbuf(path->device, sb);
1233         else
1234                 sbuf_printf(sb, "%s%d: Unknown protocol device %d\n",
1235                     periph->periph_name, periph->unit_number,
1236                     path->device->protocol);
1237         if (path->device->serial_num_len > 0)
1238                 sbuf_printf(sb, " s/n %.60s", path->device->serial_num);
1239         sbuf_printf(sb, " detached\n");
1240 }
1241
1242 int
1243 xpt_getattr(char *buf, size_t len, const char *attr, struct cam_path *path)
1244 {
1245         int ret = -1, l, o;
1246         struct ccb_dev_advinfo cdai;
1247         struct scsi_vpd_device_id *did;
1248         struct scsi_vpd_id_descriptor *idd;
1249
1250         xpt_path_assert(path, MA_OWNED);
1251
1252         memset(&cdai, 0, sizeof(cdai));
1253         xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
1254         cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1255         cdai.flags = CDAI_FLAG_NONE;
1256         cdai.bufsiz = len;
1257         cdai.buf = buf;
1258
1259         if (!strcmp(attr, "GEOM::ident"))
1260                 cdai.buftype = CDAI_TYPE_SERIAL_NUM;
1261         else if (!strcmp(attr, "GEOM::physpath"))
1262                 cdai.buftype = CDAI_TYPE_PHYS_PATH;
1263         else if (strcmp(attr, "GEOM::lunid") == 0 ||
1264                  strcmp(attr, "GEOM::lunname") == 0) {
1265                 cdai.buftype = CDAI_TYPE_SCSI_DEVID;
1266                 cdai.bufsiz = CAM_SCSI_DEVID_MAXLEN;
1267                 cdai.buf = malloc(cdai.bufsiz, M_CAMXPT, M_NOWAIT);
1268                 if (cdai.buf == NULL) {
1269                         ret = ENOMEM;
1270                         goto out;
1271                 }
1272         } else
1273                 goto out;
1274
1275         xpt_action((union ccb *)&cdai); /* can only be synchronous */
1276         if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1277                 cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1278         if (cdai.provsiz == 0)
1279                 goto out;
1280         switch(cdai.buftype) {
1281         case CDAI_TYPE_SCSI_DEVID:
1282                 did = (struct scsi_vpd_device_id *)cdai.buf;
1283                 if (strcmp(attr, "GEOM::lunid") == 0) {
1284                         idd = scsi_get_devid(did, cdai.provsiz,
1285                             scsi_devid_is_lun_naa);
1286                         if (idd == NULL)
1287                                 idd = scsi_get_devid(did, cdai.provsiz,
1288                                     scsi_devid_is_lun_eui64);
1289                         if (idd == NULL)
1290                                 idd = scsi_get_devid(did, cdai.provsiz,
1291                                     scsi_devid_is_lun_uuid);
1292                         if (idd == NULL)
1293                                 idd = scsi_get_devid(did, cdai.provsiz,
1294                                     scsi_devid_is_lun_md5);
1295                 } else
1296                         idd = NULL;
1297
1298                 if (idd == NULL)
1299                         idd = scsi_get_devid(did, cdai.provsiz,
1300                             scsi_devid_is_lun_t10);
1301                 if (idd == NULL)
1302                         idd = scsi_get_devid(did, cdai.provsiz,
1303                             scsi_devid_is_lun_name);
1304                 if (idd == NULL)
1305                         break;
1306
1307                 ret = 0;
1308                 if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) ==
1309                     SVPD_ID_CODESET_ASCII) {
1310                         if (idd->length < len) {
1311                                 for (l = 0; l < idd->length; l++)
1312                                         buf[l] = idd->identifier[l] ?
1313                                             idd->identifier[l] : ' ';
1314                                 buf[l] = 0;
1315                         } else
1316                                 ret = EFAULT;
1317                         break;
1318                 }
1319                 if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) ==
1320                     SVPD_ID_CODESET_UTF8) {
1321                         l = strnlen(idd->identifier, idd->length);
1322                         if (l < len) {
1323                                 bcopy(idd->identifier, buf, l);
1324                                 buf[l] = 0;
1325                         } else
1326                                 ret = EFAULT;
1327                         break;
1328                 }
1329                 if ((idd->id_type & SVPD_ID_TYPE_MASK) ==
1330                     SVPD_ID_TYPE_UUID && idd->identifier[0] == 0x10) {
1331                         if ((idd->length - 2) * 2 + 4 >= len) {
1332                                 ret = EFAULT;
1333                                 break;
1334                         }
1335                         for (l = 2, o = 0; l < idd->length; l++) {
1336                                 if (l == 6 || l == 8 || l == 10 || l == 12)
1337                                     o += sprintf(buf + o, "-");
1338                                 o += sprintf(buf + o, "%02x",
1339                                     idd->identifier[l]);
1340                         }
1341                         break;
1342                 }
1343                 if (idd->length * 2 < len) {
1344                         for (l = 0; l < idd->length; l++)
1345                                 sprintf(buf + l * 2, "%02x",
1346                                     idd->identifier[l]);
1347                 } else
1348                                 ret = EFAULT;
1349                 break;
1350         default:
1351                 if (cdai.provsiz < len) {
1352                         cdai.buf[cdai.provsiz] = 0;
1353                         ret = 0;
1354                 } else
1355                         ret = EFAULT;
1356                 break;
1357         }
1358
1359 out:
1360         if ((char *)cdai.buf != buf)
1361                 free(cdai.buf, M_CAMXPT);
1362         return ret;
1363 }
1364
1365 static dev_match_ret
1366 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1367             struct cam_eb *bus)
1368 {
1369         dev_match_ret retval;
1370         u_int i;
1371
1372         retval = DM_RET_NONE;
1373
1374         /*
1375          * If we aren't given something to match against, that's an error.
1376          */
1377         if (bus == NULL)
1378                 return(DM_RET_ERROR);
1379
1380         /*
1381          * If there are no match entries, then this bus matches no
1382          * matter what.
1383          */
1384         if ((patterns == NULL) || (num_patterns == 0))
1385                 return(DM_RET_DESCEND | DM_RET_COPY);
1386
1387         for (i = 0; i < num_patterns; i++) {
1388                 struct bus_match_pattern *cur_pattern;
1389
1390                 /*
1391                  * If the pattern in question isn't for a bus node, we
1392                  * aren't interested.  However, we do indicate to the
1393                  * calling routine that we should continue descending the
1394                  * tree, since the user wants to match against lower-level
1395                  * EDT elements.
1396                  */
1397                 if (patterns[i].type != DEV_MATCH_BUS) {
1398                         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1399                                 retval |= DM_RET_DESCEND;
1400                         continue;
1401                 }
1402
1403                 cur_pattern = &patterns[i].pattern.bus_pattern;
1404
1405                 /*
1406                  * If they want to match any bus node, we give them any
1407                  * device node.
1408                  */
1409                 if (cur_pattern->flags == BUS_MATCH_ANY) {
1410                         /* set the copy flag */
1411                         retval |= DM_RET_COPY;
1412
1413                         /*
1414                          * If we've already decided on an action, go ahead
1415                          * and return.
1416                          */
1417                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1418                                 return(retval);
1419                 }
1420
1421                 /*
1422                  * Not sure why someone would do this...
1423                  */
1424                 if (cur_pattern->flags == BUS_MATCH_NONE)
1425                         continue;
1426
1427                 if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1428                  && (cur_pattern->path_id != bus->path_id))
1429                         continue;
1430
1431                 if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1432                  && (cur_pattern->bus_id != bus->sim->bus_id))
1433                         continue;
1434
1435                 if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1436                  && (cur_pattern->unit_number != bus->sim->unit_number))
1437                         continue;
1438
1439                 if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1440                  && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1441                              DEV_IDLEN) != 0))
1442                         continue;
1443
1444                 /*
1445                  * If we get to this point, the user definitely wants
1446                  * information on this bus.  So tell the caller to copy the
1447                  * data out.
1448                  */
1449                 retval |= DM_RET_COPY;
1450
1451                 /*
1452                  * If the return action has been set to descend, then we
1453                  * know that we've already seen a non-bus matching
1454                  * expression, therefore we need to further descend the tree.
1455                  * This won't change by continuing around the loop, so we
1456                  * go ahead and return.  If we haven't seen a non-bus
1457                  * matching expression, we keep going around the loop until
1458                  * we exhaust the matching expressions.  We'll set the stop
1459                  * flag once we fall out of the loop.
1460                  */
1461                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1462                         return(retval);
1463         }
1464
1465         /*
1466          * If the return action hasn't been set to descend yet, that means
1467          * we haven't seen anything other than bus matching patterns.  So
1468          * tell the caller to stop descending the tree -- the user doesn't
1469          * want to match against lower level tree elements.
1470          */
1471         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1472                 retval |= DM_RET_STOP;
1473
1474         return(retval);
1475 }
1476
1477 static dev_match_ret
1478 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1479                struct cam_ed *device)
1480 {
1481         dev_match_ret retval;
1482         u_int i;
1483
1484         retval = DM_RET_NONE;
1485
1486         /*
1487          * If we aren't given something to match against, that's an error.
1488          */
1489         if (device == NULL)
1490                 return(DM_RET_ERROR);
1491
1492         /*
1493          * If there are no match entries, then this device matches no
1494          * matter what.
1495          */
1496         if ((patterns == NULL) || (num_patterns == 0))
1497                 return(DM_RET_DESCEND | DM_RET_COPY);
1498
1499         for (i = 0; i < num_patterns; i++) {
1500                 struct device_match_pattern *cur_pattern;
1501                 struct scsi_vpd_device_id *device_id_page;
1502
1503                 /*
1504                  * If the pattern in question isn't for a device node, we
1505                  * aren't interested.
1506                  */
1507                 if (patterns[i].type != DEV_MATCH_DEVICE) {
1508                         if ((patterns[i].type == DEV_MATCH_PERIPH)
1509                          && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1510                                 retval |= DM_RET_DESCEND;
1511                         continue;
1512                 }
1513
1514                 cur_pattern = &patterns[i].pattern.device_pattern;
1515
1516                 /* Error out if mutually exclusive options are specified. */
1517                 if ((cur_pattern->flags & (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1518                  == (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1519                         return(DM_RET_ERROR);
1520
1521                 /*
1522                  * If they want to match any device node, we give them any
1523                  * device node.
1524                  */
1525                 if (cur_pattern->flags == DEV_MATCH_ANY)
1526                         goto copy_dev_node;
1527
1528                 /*
1529                  * Not sure why someone would do this...
1530                  */
1531                 if (cur_pattern->flags == DEV_MATCH_NONE)
1532                         continue;
1533
1534                 if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1535                  && (cur_pattern->path_id != device->target->bus->path_id))
1536                         continue;
1537
1538                 if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1539                  && (cur_pattern->target_id != device->target->target_id))
1540                         continue;
1541
1542                 if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1543                  && (cur_pattern->target_lun != device->lun_id))
1544                         continue;
1545
1546                 if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1547                  && (cam_quirkmatch((caddr_t)&device->inq_data,
1548                                     (caddr_t)&cur_pattern->data.inq_pat,
1549                                     1, sizeof(cur_pattern->data.inq_pat),
1550                                     scsi_static_inquiry_match) == NULL))
1551                         continue;
1552
1553                 device_id_page = (struct scsi_vpd_device_id *)device->device_id;
1554                 if (((cur_pattern->flags & DEV_MATCH_DEVID) != 0)
1555                  && (device->device_id_len < SVPD_DEVICE_ID_HDR_LEN
1556                   || scsi_devid_match((uint8_t *)device_id_page->desc_list,
1557                                       device->device_id_len
1558                                     - SVPD_DEVICE_ID_HDR_LEN,
1559                                       cur_pattern->data.devid_pat.id,
1560                                       cur_pattern->data.devid_pat.id_len) != 0))
1561                         continue;
1562
1563 copy_dev_node:
1564                 /*
1565                  * If we get to this point, the user definitely wants
1566                  * information on this device.  So tell the caller to copy
1567                  * the data out.
1568                  */
1569                 retval |= DM_RET_COPY;
1570
1571                 /*
1572                  * If the return action has been set to descend, then we
1573                  * know that we've already seen a peripheral matching
1574                  * expression, therefore we need to further descend the tree.
1575                  * This won't change by continuing around the loop, so we
1576                  * go ahead and return.  If we haven't seen a peripheral
1577                  * matching expression, we keep going around the loop until
1578                  * we exhaust the matching expressions.  We'll set the stop
1579                  * flag once we fall out of the loop.
1580                  */
1581                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1582                         return(retval);
1583         }
1584
1585         /*
1586          * If the return action hasn't been set to descend yet, that means
1587          * we haven't seen any peripheral matching patterns.  So tell the
1588          * caller to stop descending the tree -- the user doesn't want to
1589          * match against lower level tree elements.
1590          */
1591         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1592                 retval |= DM_RET_STOP;
1593
1594         return(retval);
1595 }
1596
1597 /*
1598  * Match a single peripheral against any number of match patterns.
1599  */
1600 static dev_match_ret
1601 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1602                struct cam_periph *periph)
1603 {
1604         dev_match_ret retval;
1605         u_int i;
1606
1607         /*
1608          * If we aren't given something to match against, that's an error.
1609          */
1610         if (periph == NULL)
1611                 return(DM_RET_ERROR);
1612
1613         /*
1614          * If there are no match entries, then this peripheral matches no
1615          * matter what.
1616          */
1617         if ((patterns == NULL) || (num_patterns == 0))
1618                 return(DM_RET_STOP | DM_RET_COPY);
1619
1620         /*
1621          * There aren't any nodes below a peripheral node, so there's no
1622          * reason to descend the tree any further.
1623          */
1624         retval = DM_RET_STOP;
1625
1626         for (i = 0; i < num_patterns; i++) {
1627                 struct periph_match_pattern *cur_pattern;
1628
1629                 /*
1630                  * If the pattern in question isn't for a peripheral, we
1631                  * aren't interested.
1632                  */
1633                 if (patterns[i].type != DEV_MATCH_PERIPH)
1634                         continue;
1635
1636                 cur_pattern = &patterns[i].pattern.periph_pattern;
1637
1638                 /*
1639                  * If they want to match on anything, then we will do so.
1640                  */
1641                 if (cur_pattern->flags == PERIPH_MATCH_ANY) {
1642                         /* set the copy flag */
1643                         retval |= DM_RET_COPY;
1644
1645                         /*
1646                          * We've already set the return action to stop,
1647                          * since there are no nodes below peripherals in
1648                          * the tree.
1649                          */
1650                         return(retval);
1651                 }
1652
1653                 /*
1654                  * Not sure why someone would do this...
1655                  */
1656                 if (cur_pattern->flags == PERIPH_MATCH_NONE)
1657                         continue;
1658
1659                 if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1660                  && (cur_pattern->path_id != periph->path->bus->path_id))
1661                         continue;
1662
1663                 /*
1664                  * For the target and lun id's, we have to make sure the
1665                  * target and lun pointers aren't NULL.  The xpt peripheral
1666                  * has a wildcard target and device.
1667                  */
1668                 if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1669                  && ((periph->path->target == NULL)
1670                  ||(cur_pattern->target_id != periph->path->target->target_id)))
1671                         continue;
1672
1673                 if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1674                  && ((periph->path->device == NULL)
1675                  || (cur_pattern->target_lun != periph->path->device->lun_id)))
1676                         continue;
1677
1678                 if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1679                  && (cur_pattern->unit_number != periph->unit_number))
1680                         continue;
1681
1682                 if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
1683                  && (strncmp(cur_pattern->periph_name, periph->periph_name,
1684                              DEV_IDLEN) != 0))
1685                         continue;
1686
1687                 /*
1688                  * If we get to this point, the user definitely wants
1689                  * information on this peripheral.  So tell the caller to
1690                  * copy the data out.
1691                  */
1692                 retval |= DM_RET_COPY;
1693
1694                 /*
1695                  * The return action has already been set to stop, since
1696                  * peripherals don't have any nodes below them in the EDT.
1697                  */
1698                 return(retval);
1699         }
1700
1701         /*
1702          * If we get to this point, the peripheral that was passed in
1703          * doesn't match any of the patterns.
1704          */
1705         return(retval);
1706 }
1707
1708 static int
1709 xptedtbusfunc(struct cam_eb *bus, void *arg)
1710 {
1711         struct ccb_dev_match *cdm;
1712         struct cam_et *target;
1713         dev_match_ret retval;
1714
1715         cdm = (struct ccb_dev_match *)arg;
1716
1717         /*
1718          * If our position is for something deeper in the tree, that means
1719          * that we've already seen this node.  So, we keep going down.
1720          */
1721         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1722          && (cdm->pos.cookie.bus == bus)
1723          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1724          && (cdm->pos.cookie.target != NULL))
1725                 retval = DM_RET_DESCEND;
1726         else
1727                 retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
1728
1729         /*
1730          * If we got an error, bail out of the search.
1731          */
1732         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1733                 cdm->status = CAM_DEV_MATCH_ERROR;
1734                 return(0);
1735         }
1736
1737         /*
1738          * If the copy flag is set, copy this bus out.
1739          */
1740         if (retval & DM_RET_COPY) {
1741                 int spaceleft, j;
1742
1743                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1744                         sizeof(struct dev_match_result));
1745
1746                 /*
1747                  * If we don't have enough space to put in another
1748                  * match result, save our position and tell the
1749                  * user there are more devices to check.
1750                  */
1751                 if (spaceleft < sizeof(struct dev_match_result)) {
1752                         bzero(&cdm->pos, sizeof(cdm->pos));
1753                         cdm->pos.position_type =
1754                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
1755
1756                         cdm->pos.cookie.bus = bus;
1757                         cdm->pos.generations[CAM_BUS_GENERATION]=
1758                                 xsoftc.bus_generation;
1759                         cdm->status = CAM_DEV_MATCH_MORE;
1760                         return(0);
1761                 }
1762                 j = cdm->num_matches;
1763                 cdm->num_matches++;
1764                 cdm->matches[j].type = DEV_MATCH_BUS;
1765                 cdm->matches[j].result.bus_result.path_id = bus->path_id;
1766                 cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
1767                 cdm->matches[j].result.bus_result.unit_number =
1768                         bus->sim->unit_number;
1769                 strlcpy(cdm->matches[j].result.bus_result.dev_name,
1770                         bus->sim->sim_name,
1771                         sizeof(cdm->matches[j].result.bus_result.dev_name));
1772         }
1773
1774         /*
1775          * If the user is only interested in buses, there's no
1776          * reason to descend to the next level in the tree.
1777          */
1778         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1779                 return(1);
1780
1781         /*
1782          * If there is a target generation recorded, check it to
1783          * make sure the target list hasn't changed.
1784          */
1785         mtx_lock(&bus->eb_mtx);
1786         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1787          && (cdm->pos.cookie.bus == bus)
1788          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1789          && (cdm->pos.cookie.target != NULL)) {
1790                 if ((cdm->pos.generations[CAM_TARGET_GENERATION] !=
1791                     bus->generation)) {
1792                         mtx_unlock(&bus->eb_mtx);
1793                         cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1794                         return (0);
1795                 }
1796                 target = (struct cam_et *)cdm->pos.cookie.target;
1797                 target->refcount++;
1798         } else
1799                 target = NULL;
1800         mtx_unlock(&bus->eb_mtx);
1801
1802         return (xpttargettraverse(bus, target, xptedttargetfunc, arg));
1803 }
1804
1805 static int
1806 xptedttargetfunc(struct cam_et *target, void *arg)
1807 {
1808         struct ccb_dev_match *cdm;
1809         struct cam_eb *bus;
1810         struct cam_ed *device;
1811
1812         cdm = (struct ccb_dev_match *)arg;
1813         bus = target->bus;
1814
1815         /*
1816          * If there is a device list generation recorded, check it to
1817          * make sure the device list hasn't changed.
1818          */
1819         mtx_lock(&bus->eb_mtx);
1820         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1821          && (cdm->pos.cookie.bus == bus)
1822          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1823          && (cdm->pos.cookie.target == target)
1824          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1825          && (cdm->pos.cookie.device != NULL)) {
1826                 if (cdm->pos.generations[CAM_DEV_GENERATION] !=
1827                     target->generation) {
1828                         mtx_unlock(&bus->eb_mtx);
1829                         cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1830                         return(0);
1831                 }
1832                 device = (struct cam_ed *)cdm->pos.cookie.device;
1833                 device->refcount++;
1834         } else
1835                 device = NULL;
1836         mtx_unlock(&bus->eb_mtx);
1837
1838         return (xptdevicetraverse(target, device, xptedtdevicefunc, arg));
1839 }
1840
1841 static int
1842 xptedtdevicefunc(struct cam_ed *device, void *arg)
1843 {
1844         struct cam_eb *bus;
1845         struct cam_periph *periph;
1846         struct ccb_dev_match *cdm;
1847         dev_match_ret retval;
1848
1849         cdm = (struct ccb_dev_match *)arg;
1850         bus = device->target->bus;
1851
1852         /*
1853          * If our position is for something deeper in the tree, that means
1854          * that we've already seen this node.  So, we keep going down.
1855          */
1856         if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1857          && (cdm->pos.cookie.device == device)
1858          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1859          && (cdm->pos.cookie.periph != NULL))
1860                 retval = DM_RET_DESCEND;
1861         else
1862                 retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
1863                                         device);
1864
1865         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1866                 cdm->status = CAM_DEV_MATCH_ERROR;
1867                 return(0);
1868         }
1869
1870         /*
1871          * If the copy flag is set, copy this device out.
1872          */
1873         if (retval & DM_RET_COPY) {
1874                 int spaceleft, j;
1875
1876                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1877                         sizeof(struct dev_match_result));
1878
1879                 /*
1880                  * If we don't have enough space to put in another
1881                  * match result, save our position and tell the
1882                  * user there are more devices to check.
1883                  */
1884                 if (spaceleft < sizeof(struct dev_match_result)) {
1885                         bzero(&cdm->pos, sizeof(cdm->pos));
1886                         cdm->pos.position_type =
1887                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1888                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
1889
1890                         cdm->pos.cookie.bus = device->target->bus;
1891                         cdm->pos.generations[CAM_BUS_GENERATION]=
1892                                 xsoftc.bus_generation;
1893                         cdm->pos.cookie.target = device->target;
1894                         cdm->pos.generations[CAM_TARGET_GENERATION] =
1895                                 device->target->bus->generation;
1896                         cdm->pos.cookie.device = device;
1897                         cdm->pos.generations[CAM_DEV_GENERATION] =
1898                                 device->target->generation;
1899                         cdm->status = CAM_DEV_MATCH_MORE;
1900                         return(0);
1901                 }
1902                 j = cdm->num_matches;
1903                 cdm->num_matches++;
1904                 cdm->matches[j].type = DEV_MATCH_DEVICE;
1905                 cdm->matches[j].result.device_result.path_id =
1906                         device->target->bus->path_id;
1907                 cdm->matches[j].result.device_result.target_id =
1908                         device->target->target_id;
1909                 cdm->matches[j].result.device_result.target_lun =
1910                         device->lun_id;
1911                 cdm->matches[j].result.device_result.protocol =
1912                         device->protocol;
1913                 bcopy(&device->inq_data,
1914                       &cdm->matches[j].result.device_result.inq_data,
1915                       sizeof(struct scsi_inquiry_data));
1916                 bcopy(&device->ident_data,
1917                       &cdm->matches[j].result.device_result.ident_data,
1918                       sizeof(struct ata_params));
1919
1920                 /* Let the user know whether this device is unconfigured */
1921                 if (device->flags & CAM_DEV_UNCONFIGURED)
1922                         cdm->matches[j].result.device_result.flags =
1923                                 DEV_RESULT_UNCONFIGURED;
1924                 else
1925                         cdm->matches[j].result.device_result.flags =
1926                                 DEV_RESULT_NOFLAG;
1927         }
1928
1929         /*
1930          * If the user isn't interested in peripherals, don't descend
1931          * the tree any further.
1932          */
1933         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1934                 return(1);
1935
1936         /*
1937          * If there is a peripheral list generation recorded, make sure
1938          * it hasn't changed.
1939          */
1940         xpt_lock_buses();
1941         mtx_lock(&bus->eb_mtx);
1942         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1943          && (cdm->pos.cookie.bus == bus)
1944          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1945          && (cdm->pos.cookie.target == device->target)
1946          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1947          && (cdm->pos.cookie.device == device)
1948          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1949          && (cdm->pos.cookie.periph != NULL)) {
1950                 if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1951                     device->generation) {
1952                         mtx_unlock(&bus->eb_mtx);
1953                         xpt_unlock_buses();
1954                         cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1955                         return(0);
1956                 }
1957                 periph = (struct cam_periph *)cdm->pos.cookie.periph;
1958                 periph->refcount++;
1959         } else
1960                 periph = NULL;
1961         mtx_unlock(&bus->eb_mtx);
1962         xpt_unlock_buses();
1963
1964         return (xptperiphtraverse(device, periph, xptedtperiphfunc, arg));
1965 }
1966
1967 static int
1968 xptedtperiphfunc(struct cam_periph *periph, void *arg)
1969 {
1970         struct ccb_dev_match *cdm;
1971         dev_match_ret retval;
1972
1973         cdm = (struct ccb_dev_match *)arg;
1974
1975         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1976
1977         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1978                 cdm->status = CAM_DEV_MATCH_ERROR;
1979                 return(0);
1980         }
1981
1982         /*
1983          * If the copy flag is set, copy this peripheral out.
1984          */
1985         if (retval & DM_RET_COPY) {
1986                 int spaceleft, j;
1987                 size_t l;
1988
1989                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
1990                         sizeof(struct dev_match_result));
1991
1992                 /*
1993                  * If we don't have enough space to put in another
1994                  * match result, save our position and tell the
1995                  * user there are more devices to check.
1996                  */
1997                 if (spaceleft < sizeof(struct dev_match_result)) {
1998                         bzero(&cdm->pos, sizeof(cdm->pos));
1999                         cdm->pos.position_type =
2000                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2001                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
2002                                 CAM_DEV_POS_PERIPH;
2003
2004                         cdm->pos.cookie.bus = periph->path->bus;
2005                         cdm->pos.generations[CAM_BUS_GENERATION]=
2006                                 xsoftc.bus_generation;
2007                         cdm->pos.cookie.target = periph->path->target;
2008                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2009                                 periph->path->bus->generation;
2010                         cdm->pos.cookie.device = periph->path->device;
2011                         cdm->pos.generations[CAM_DEV_GENERATION] =
2012                                 periph->path->target->generation;
2013                         cdm->pos.cookie.periph = periph;
2014                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2015                                 periph->path->device->generation;
2016                         cdm->status = CAM_DEV_MATCH_MORE;
2017                         return(0);
2018                 }
2019
2020                 j = cdm->num_matches;
2021                 cdm->num_matches++;
2022                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2023                 cdm->matches[j].result.periph_result.path_id =
2024                         periph->path->bus->path_id;
2025                 cdm->matches[j].result.periph_result.target_id =
2026                         periph->path->target->target_id;
2027                 cdm->matches[j].result.periph_result.target_lun =
2028                         periph->path->device->lun_id;
2029                 cdm->matches[j].result.periph_result.unit_number =
2030                         periph->unit_number;
2031                 l = sizeof(cdm->matches[j].result.periph_result.periph_name);
2032                 strlcpy(cdm->matches[j].result.periph_result.periph_name,
2033                         periph->periph_name, l);
2034         }
2035
2036         return(1);
2037 }
2038
2039 static int
2040 xptedtmatch(struct ccb_dev_match *cdm)
2041 {
2042         struct cam_eb *bus;
2043         int ret;
2044
2045         cdm->num_matches = 0;
2046
2047         /*
2048          * Check the bus list generation.  If it has changed, the user
2049          * needs to reset everything and start over.
2050          */
2051         xpt_lock_buses();
2052         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2053          && (cdm->pos.cookie.bus != NULL)) {
2054                 if (cdm->pos.generations[CAM_BUS_GENERATION] !=
2055                     xsoftc.bus_generation) {
2056                         xpt_unlock_buses();
2057                         cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2058                         return(0);
2059                 }
2060                 bus = (struct cam_eb *)cdm->pos.cookie.bus;
2061                 bus->refcount++;
2062         } else
2063                 bus = NULL;
2064         xpt_unlock_buses();
2065
2066         ret = xptbustraverse(bus, xptedtbusfunc, cdm);
2067
2068         /*
2069          * If we get back 0, that means that we had to stop before fully
2070          * traversing the EDT.  It also means that one of the subroutines
2071          * has set the status field to the proper value.  If we get back 1,
2072          * we've fully traversed the EDT and copied out any matching entries.
2073          */
2074         if (ret == 1)
2075                 cdm->status = CAM_DEV_MATCH_LAST;
2076
2077         return(ret);
2078 }
2079
2080 static int
2081 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
2082 {
2083         struct cam_periph *periph;
2084         struct ccb_dev_match *cdm;
2085
2086         cdm = (struct ccb_dev_match *)arg;
2087
2088         xpt_lock_buses();
2089         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2090          && (cdm->pos.cookie.pdrv == pdrv)
2091          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2092          && (cdm->pos.cookie.periph != NULL)) {
2093                 if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2094                     (*pdrv)->generation) {
2095                         xpt_unlock_buses();
2096                         cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2097                         return(0);
2098                 }
2099                 periph = (struct cam_periph *)cdm->pos.cookie.periph;
2100                 periph->refcount++;
2101         } else
2102                 periph = NULL;
2103         xpt_unlock_buses();
2104
2105         return (xptpdperiphtraverse(pdrv, periph, xptplistperiphfunc, arg));
2106 }
2107
2108 static int
2109 xptplistperiphfunc(struct cam_periph *periph, void *arg)
2110 {
2111         struct ccb_dev_match *cdm;
2112         dev_match_ret retval;
2113
2114         cdm = (struct ccb_dev_match *)arg;
2115
2116         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2117
2118         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2119                 cdm->status = CAM_DEV_MATCH_ERROR;
2120                 return(0);
2121         }
2122
2123         /*
2124          * If the copy flag is set, copy this peripheral out.
2125          */
2126         if (retval & DM_RET_COPY) {
2127                 int spaceleft, j;
2128                 size_t l;
2129
2130                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2131                         sizeof(struct dev_match_result));
2132
2133                 /*
2134                  * If we don't have enough space to put in another
2135                  * match result, save our position and tell the
2136                  * user there are more devices to check.
2137                  */
2138                 if (spaceleft < sizeof(struct dev_match_result)) {
2139                         struct periph_driver **pdrv;
2140
2141                         pdrv = NULL;
2142                         bzero(&cdm->pos, sizeof(cdm->pos));
2143                         cdm->pos.position_type =
2144                                 CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2145                                 CAM_DEV_POS_PERIPH;
2146
2147                         /*
2148                          * This may look a bit non-sensical, but it is
2149                          * actually quite logical.  There are very few
2150                          * peripheral drivers, and bloating every peripheral
2151                          * structure with a pointer back to its parent
2152                          * peripheral driver linker set entry would cost
2153                          * more in the long run than doing this quick lookup.
2154                          */
2155                         for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
2156                                 if (strcmp((*pdrv)->driver_name,
2157                                     periph->periph_name) == 0)
2158                                         break;
2159                         }
2160
2161                         if (*pdrv == NULL) {
2162                                 cdm->status = CAM_DEV_MATCH_ERROR;
2163                                 return(0);
2164                         }
2165
2166                         cdm->pos.cookie.pdrv = pdrv;
2167                         /*
2168                          * The periph generation slot does double duty, as
2169                          * does the periph pointer slot.  They are used for
2170                          * both edt and pdrv lookups and positioning.
2171                          */
2172                         cdm->pos.cookie.periph = periph;
2173                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2174                                 (*pdrv)->generation;
2175                         cdm->status = CAM_DEV_MATCH_MORE;
2176                         return(0);
2177                 }
2178
2179                 j = cdm->num_matches;
2180                 cdm->num_matches++;
2181                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2182                 cdm->matches[j].result.periph_result.path_id =
2183                         periph->path->bus->path_id;
2184
2185                 /*
2186                  * The transport layer peripheral doesn't have a target or
2187                  * lun.
2188                  */
2189                 if (periph->path->target)
2190                         cdm->matches[j].result.periph_result.target_id =
2191                                 periph->path->target->target_id;
2192                 else
2193                         cdm->matches[j].result.periph_result.target_id =
2194                                 CAM_TARGET_WILDCARD;
2195
2196                 if (periph->path->device)
2197                         cdm->matches[j].result.periph_result.target_lun =
2198                                 periph->path->device->lun_id;
2199                 else
2200                         cdm->matches[j].result.periph_result.target_lun =
2201                                 CAM_LUN_WILDCARD;
2202
2203                 cdm->matches[j].result.periph_result.unit_number =
2204                         periph->unit_number;
2205                 l = sizeof(cdm->matches[j].result.periph_result.periph_name);
2206                 strlcpy(cdm->matches[j].result.periph_result.periph_name,
2207                         periph->periph_name, l);
2208         }
2209
2210         return(1);
2211 }
2212
2213 static int
2214 xptperiphlistmatch(struct ccb_dev_match *cdm)
2215 {
2216         int ret;
2217
2218         cdm->num_matches = 0;
2219
2220         /*
2221          * At this point in the edt traversal function, we check the bus
2222          * list generation to make sure that no buses have been added or
2223          * removed since the user last sent a XPT_DEV_MATCH ccb through.
2224          * For the peripheral driver list traversal function, however, we
2225          * don't have to worry about new peripheral driver types coming or
2226          * going; they're in a linker set, and therefore can't change
2227          * without a recompile.
2228          */
2229
2230         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2231          && (cdm->pos.cookie.pdrv != NULL))
2232                 ret = xptpdrvtraverse(
2233                                 (struct periph_driver **)cdm->pos.cookie.pdrv,
2234                                 xptplistpdrvfunc, cdm);
2235         else
2236                 ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2237
2238         /*
2239          * If we get back 0, that means that we had to stop before fully
2240          * traversing the peripheral driver tree.  It also means that one of
2241          * the subroutines has set the status field to the proper value.  If
2242          * we get back 1, we've fully traversed the EDT and copied out any
2243          * matching entries.
2244          */
2245         if (ret == 1)
2246                 cdm->status = CAM_DEV_MATCH_LAST;
2247
2248         return(ret);
2249 }
2250
2251 static int
2252 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2253 {
2254         struct cam_eb *bus, *next_bus;
2255         int retval;
2256
2257         retval = 1;
2258         if (start_bus)
2259                 bus = start_bus;
2260         else {
2261                 xpt_lock_buses();
2262                 bus = TAILQ_FIRST(&xsoftc.xpt_busses);
2263                 if (bus == NULL) {
2264                         xpt_unlock_buses();
2265                         return (retval);
2266                 }
2267                 bus->refcount++;
2268                 xpt_unlock_buses();
2269         }
2270         for (; bus != NULL; bus = next_bus) {
2271                 retval = tr_func(bus, arg);
2272                 if (retval == 0) {
2273                         xpt_release_bus(bus);
2274                         break;
2275                 }
2276                 xpt_lock_buses();
2277                 next_bus = TAILQ_NEXT(bus, links);
2278                 if (next_bus)
2279                         next_bus->refcount++;
2280                 xpt_unlock_buses();
2281                 xpt_release_bus(bus);
2282         }
2283         return(retval);
2284 }
2285
2286 static int
2287 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2288                   xpt_targetfunc_t *tr_func, void *arg)
2289 {
2290         struct cam_et *target, *next_target;
2291         int retval;
2292
2293         retval = 1;
2294         if (start_target)
2295                 target = start_target;
2296         else {
2297                 mtx_lock(&bus->eb_mtx);
2298                 target = TAILQ_FIRST(&bus->et_entries);
2299                 if (target == NULL) {
2300                         mtx_unlock(&bus->eb_mtx);
2301                         return (retval);
2302                 }
2303                 target->refcount++;
2304                 mtx_unlock(&bus->eb_mtx);
2305         }
2306         for (; target != NULL; target = next_target) {
2307                 retval = tr_func(target, arg);
2308                 if (retval == 0) {
2309                         xpt_release_target(target);
2310                         break;
2311                 }
2312                 mtx_lock(&bus->eb_mtx);
2313                 next_target = TAILQ_NEXT(target, links);
2314                 if (next_target)
2315                         next_target->refcount++;
2316                 mtx_unlock(&bus->eb_mtx);
2317                 xpt_release_target(target);
2318         }
2319         return(retval);
2320 }
2321
2322 static int
2323 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2324                   xpt_devicefunc_t *tr_func, void *arg)
2325 {
2326         struct cam_eb *bus;
2327         struct cam_ed *device, *next_device;
2328         int retval;
2329
2330         retval = 1;
2331         bus = target->bus;
2332         if (start_device)
2333                 device = start_device;
2334         else {
2335                 mtx_lock(&bus->eb_mtx);
2336                 device = TAILQ_FIRST(&target->ed_entries);
2337                 if (device == NULL) {
2338                         mtx_unlock(&bus->eb_mtx);
2339                         return (retval);
2340                 }
2341                 device->refcount++;
2342                 mtx_unlock(&bus->eb_mtx);
2343         }
2344         for (; device != NULL; device = next_device) {
2345                 mtx_lock(&device->device_mtx);
2346                 retval = tr_func(device, arg);
2347                 mtx_unlock(&device->device_mtx);
2348                 if (retval == 0) {
2349                         xpt_release_device(device);
2350                         break;
2351                 }
2352                 mtx_lock(&bus->eb_mtx);
2353                 next_device = TAILQ_NEXT(device, links);
2354                 if (next_device)
2355                         next_device->refcount++;
2356                 mtx_unlock(&bus->eb_mtx);
2357                 xpt_release_device(device);
2358         }
2359         return(retval);
2360 }
2361
2362 static int
2363 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2364                   xpt_periphfunc_t *tr_func, void *arg)
2365 {
2366         struct cam_eb *bus;
2367         struct cam_periph *periph, *next_periph;
2368         int retval;
2369
2370         retval = 1;
2371
2372         bus = device->target->bus;
2373         if (start_periph)
2374                 periph = start_periph;
2375         else {
2376                 xpt_lock_buses();
2377                 mtx_lock(&bus->eb_mtx);
2378                 periph = SLIST_FIRST(&device->periphs);
2379                 while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2380                         periph = SLIST_NEXT(periph, periph_links);
2381                 if (periph == NULL) {
2382                         mtx_unlock(&bus->eb_mtx);
2383                         xpt_unlock_buses();
2384                         return (retval);
2385                 }
2386                 periph->refcount++;
2387                 mtx_unlock(&bus->eb_mtx);
2388                 xpt_unlock_buses();
2389         }
2390         for (; periph != NULL; periph = next_periph) {
2391                 retval = tr_func(periph, arg);
2392                 if (retval == 0) {
2393                         cam_periph_release_locked(periph);
2394                         break;
2395                 }
2396                 xpt_lock_buses();
2397                 mtx_lock(&bus->eb_mtx);
2398                 next_periph = SLIST_NEXT(periph, periph_links);
2399                 while (next_periph != NULL &&
2400                     (next_periph->flags & CAM_PERIPH_FREE) != 0)
2401                         next_periph = SLIST_NEXT(next_periph, periph_links);
2402                 if (next_periph)
2403                         next_periph->refcount++;
2404                 mtx_unlock(&bus->eb_mtx);
2405                 xpt_unlock_buses();
2406                 cam_periph_release_locked(periph);
2407         }
2408         return(retval);
2409 }
2410
2411 static int
2412 xptpdrvtraverse(struct periph_driver **start_pdrv,
2413                 xpt_pdrvfunc_t *tr_func, void *arg)
2414 {
2415         struct periph_driver **pdrv;
2416         int retval;
2417
2418         retval = 1;
2419
2420         /*
2421          * We don't traverse the peripheral driver list like we do the
2422          * other lists, because it is a linker set, and therefore cannot be
2423          * changed during runtime.  If the peripheral driver list is ever
2424          * re-done to be something other than a linker set (i.e. it can
2425          * change while the system is running), the list traversal should
2426          * be modified to work like the other traversal functions.
2427          */
2428         for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2429              *pdrv != NULL; pdrv++) {
2430                 retval = tr_func(pdrv, arg);
2431
2432                 if (retval == 0)
2433                         return(retval);
2434         }
2435
2436         return(retval);
2437 }
2438
2439 static int
2440 xptpdperiphtraverse(struct periph_driver **pdrv,
2441                     struct cam_periph *start_periph,
2442                     xpt_periphfunc_t *tr_func, void *arg)
2443 {
2444         struct cam_periph *periph, *next_periph;
2445         int retval;
2446
2447         retval = 1;
2448
2449         if (start_periph)
2450                 periph = start_periph;
2451         else {
2452                 xpt_lock_buses();
2453                 periph = TAILQ_FIRST(&(*pdrv)->units);
2454                 while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2455                         periph = TAILQ_NEXT(periph, unit_links);
2456                 if (periph == NULL) {
2457                         xpt_unlock_buses();
2458                         return (retval);
2459                 }
2460                 periph->refcount++;
2461                 xpt_unlock_buses();
2462         }
2463         for (; periph != NULL; periph = next_periph) {
2464                 cam_periph_lock(periph);
2465                 retval = tr_func(periph, arg);
2466                 cam_periph_unlock(periph);
2467                 if (retval == 0) {
2468                         cam_periph_release(periph);
2469                         break;
2470                 }
2471                 xpt_lock_buses();
2472                 next_periph = TAILQ_NEXT(periph, unit_links);
2473                 while (next_periph != NULL &&
2474                     (next_periph->flags & CAM_PERIPH_FREE) != 0)
2475                         next_periph = TAILQ_NEXT(next_periph, unit_links);
2476                 if (next_periph)
2477                         next_periph->refcount++;
2478                 xpt_unlock_buses();
2479                 cam_periph_release(periph);
2480         }
2481         return(retval);
2482 }
2483
2484 static int
2485 xptdefbusfunc(struct cam_eb *bus, void *arg)
2486 {
2487         struct xpt_traverse_config *tr_config;
2488
2489         tr_config = (struct xpt_traverse_config *)arg;
2490
2491         if (tr_config->depth == XPT_DEPTH_BUS) {
2492                 xpt_busfunc_t *tr_func;
2493
2494                 tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2495
2496                 return(tr_func(bus, tr_config->tr_arg));
2497         } else
2498                 return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2499 }
2500
2501 static int
2502 xptdeftargetfunc(struct cam_et *target, void *arg)
2503 {
2504         struct xpt_traverse_config *tr_config;
2505
2506         tr_config = (struct xpt_traverse_config *)arg;
2507
2508         if (tr_config->depth == XPT_DEPTH_TARGET) {
2509                 xpt_targetfunc_t *tr_func;
2510
2511                 tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2512
2513                 return(tr_func(target, tr_config->tr_arg));
2514         } else
2515                 return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2516 }
2517
2518 static int
2519 xptdefdevicefunc(struct cam_ed *device, void *arg)
2520 {
2521         struct xpt_traverse_config *tr_config;
2522
2523         tr_config = (struct xpt_traverse_config *)arg;
2524
2525         if (tr_config->depth == XPT_DEPTH_DEVICE) {
2526                 xpt_devicefunc_t *tr_func;
2527
2528                 tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2529
2530                 return(tr_func(device, tr_config->tr_arg));
2531         } else
2532                 return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2533 }
2534
2535 static int
2536 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2537 {
2538         struct xpt_traverse_config *tr_config;
2539         xpt_periphfunc_t *tr_func;
2540
2541         tr_config = (struct xpt_traverse_config *)arg;
2542
2543         tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2544
2545         /*
2546          * Unlike the other default functions, we don't check for depth
2547          * here.  The peripheral driver level is the last level in the EDT,
2548          * so if we're here, we should execute the function in question.
2549          */
2550         return(tr_func(periph, tr_config->tr_arg));
2551 }
2552
2553 /*
2554  * Execute the given function for every bus in the EDT.
2555  */
2556 static int
2557 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2558 {
2559         struct xpt_traverse_config tr_config;
2560
2561         tr_config.depth = XPT_DEPTH_BUS;
2562         tr_config.tr_func = tr_func;
2563         tr_config.tr_arg = arg;
2564
2565         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2566 }
2567
2568 /*
2569  * Execute the given function for every device in the EDT.
2570  */
2571 static int
2572 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2573 {
2574         struct xpt_traverse_config tr_config;
2575
2576         tr_config.depth = XPT_DEPTH_DEVICE;
2577         tr_config.tr_func = tr_func;
2578         tr_config.tr_arg = arg;
2579
2580         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2581 }
2582
2583 static int
2584 xptsetasyncfunc(struct cam_ed *device, void *arg)
2585 {
2586         struct cam_path path;
2587         struct ccb_getdev cgd;
2588         struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2589
2590         /*
2591          * Don't report unconfigured devices (Wildcard devs,
2592          * devices only for target mode, device instances
2593          * that have been invalidated but are waiting for
2594          * their last reference count to be released).
2595          */
2596         if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2597                 return (1);
2598
2599         xpt_compile_path(&path,
2600                          NULL,
2601                          device->target->bus->path_id,
2602                          device->target->target_id,
2603                          device->lun_id);
2604         xpt_setup_ccb(&cgd.ccb_h, &path, CAM_PRIORITY_NORMAL);
2605         cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2606         xpt_action((union ccb *)&cgd);
2607         csa->callback(csa->callback_arg,
2608                             AC_FOUND_DEVICE,
2609                             &path, &cgd);
2610         xpt_release_path(&path);
2611
2612         return(1);
2613 }
2614
2615 static int
2616 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2617 {
2618         struct cam_path path;
2619         struct ccb_pathinq cpi;
2620         struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2621
2622         xpt_compile_path(&path, /*periph*/NULL,
2623                          bus->path_id,
2624                          CAM_TARGET_WILDCARD,
2625                          CAM_LUN_WILDCARD);
2626         xpt_path_lock(&path);
2627         xpt_path_inq(&cpi, &path);
2628         csa->callback(csa->callback_arg,
2629                             AC_PATH_REGISTERED,
2630                             &path, &cpi);
2631         xpt_path_unlock(&path);
2632         xpt_release_path(&path);
2633
2634         return(1);
2635 }
2636
2637 void
2638 xpt_action(union ccb *start_ccb)
2639 {
2640
2641         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE,
2642             ("xpt_action: func %#x %s\n", start_ccb->ccb_h.func_code,
2643                 xpt_action_name(start_ccb->ccb_h.func_code)));
2644
2645         start_ccb->ccb_h.status = CAM_REQ_INPROG;
2646         (*(start_ccb->ccb_h.path->bus->xport->ops->action))(start_ccb);
2647 }
2648
2649 void
2650 xpt_action_default(union ccb *start_ccb)
2651 {
2652         struct cam_path *path;
2653         struct cam_sim *sim;
2654         struct mtx *mtx;
2655
2656         path = start_ccb->ccb_h.path;
2657         CAM_DEBUG(path, CAM_DEBUG_TRACE,
2658             ("xpt_action_default: func %#x %s\n", start_ccb->ccb_h.func_code,
2659                 xpt_action_name(start_ccb->ccb_h.func_code)));
2660
2661         switch (start_ccb->ccb_h.func_code) {
2662         case XPT_SCSI_IO:
2663         {
2664                 struct cam_ed *device;
2665
2666                 /*
2667                  * For the sake of compatibility with SCSI-1
2668                  * devices that may not understand the identify
2669                  * message, we include lun information in the
2670                  * second byte of all commands.  SCSI-1 specifies
2671                  * that luns are a 3 bit value and reserves only 3
2672                  * bits for lun information in the CDB.  Later
2673                  * revisions of the SCSI spec allow for more than 8
2674                  * luns, but have deprecated lun information in the
2675                  * CDB.  So, if the lun won't fit, we must omit.
2676                  *
2677                  * Also be aware that during initial probing for devices,
2678                  * the inquiry information is unknown but initialized to 0.
2679                  * This means that this code will be exercised while probing
2680                  * devices with an ANSI revision greater than 2.
2681                  */
2682                 device = path->device;
2683                 if (device->protocol_version <= SCSI_REV_2
2684                  && start_ccb->ccb_h.target_lun < 8
2685                  && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2686
2687                         start_ccb->csio.cdb_io.cdb_bytes[1] |=
2688                             start_ccb->ccb_h.target_lun << 5;
2689                 }
2690                 start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2691         }
2692         /* FALLTHROUGH */
2693         case XPT_TARGET_IO:
2694         case XPT_CONT_TARGET_IO:
2695                 start_ccb->csio.sense_resid = 0;
2696                 start_ccb->csio.resid = 0;
2697                 /* FALLTHROUGH */
2698         case XPT_ATA_IO:
2699                 if (start_ccb->ccb_h.func_code == XPT_ATA_IO)
2700                         start_ccb->ataio.resid = 0;
2701                 /* FALLTHROUGH */
2702         case XPT_NVME_IO:
2703                 /* FALLTHROUGH */
2704         case XPT_NVME_ADMIN:
2705                 /* FALLTHROUGH */
2706         case XPT_MMC_IO:
2707                 /* XXX just like nmve_io? */
2708         case XPT_RESET_DEV:
2709         case XPT_ENG_EXEC:
2710         case XPT_SMP_IO:
2711         {
2712                 struct cam_devq *devq;
2713
2714                 devq = path->bus->sim->devq;
2715                 mtx_lock(&devq->send_mtx);
2716                 cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2717                 if (xpt_schedule_devq(devq, path->device) != 0)
2718                         xpt_run_devq(devq);
2719                 mtx_unlock(&devq->send_mtx);
2720                 break;
2721         }
2722         case XPT_CALC_GEOMETRY:
2723                 /* Filter out garbage */
2724                 if (start_ccb->ccg.block_size == 0
2725                  || start_ccb->ccg.volume_size == 0) {
2726                         start_ccb->ccg.cylinders = 0;
2727                         start_ccb->ccg.heads = 0;
2728                         start_ccb->ccg.secs_per_track = 0;
2729                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2730                         break;
2731                 }
2732 #if defined(__sparc64__)
2733                 /*
2734                  * For sparc64, we may need adjust the geometry of large
2735                  * disks in order to fit the limitations of the 16-bit
2736                  * fields of the VTOC8 disk label.
2737                  */
2738                 if (scsi_da_bios_params(&start_ccb->ccg) != 0) {
2739                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2740                         break;
2741                 }
2742 #endif
2743                 goto call_sim;
2744         case XPT_ABORT:
2745         {
2746                 union ccb* abort_ccb;
2747
2748                 abort_ccb = start_ccb->cab.abort_ccb;
2749                 if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2750                         struct cam_ed *device;
2751                         struct cam_devq *devq;
2752
2753                         device = abort_ccb->ccb_h.path->device;
2754                         devq = device->sim->devq;
2755
2756                         mtx_lock(&devq->send_mtx);
2757                         if (abort_ccb->ccb_h.pinfo.index > 0) {
2758                                 cam_ccbq_remove_ccb(&device->ccbq, abort_ccb);
2759                                 abort_ccb->ccb_h.status =
2760                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2761                                 xpt_freeze_devq_device(device, 1);
2762                                 mtx_unlock(&devq->send_mtx);
2763                                 xpt_done(abort_ccb);
2764                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2765                                 break;
2766                         }
2767                         mtx_unlock(&devq->send_mtx);
2768
2769                         if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2770                          && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2771                                 /*
2772                                  * We've caught this ccb en route to
2773                                  * the SIM.  Flag it for abort and the
2774                                  * SIM will do so just before starting
2775                                  * real work on the CCB.
2776                                  */
2777                                 abort_ccb->ccb_h.status =
2778                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2779                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2780                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2781                                 break;
2782                         }
2783                 }
2784                 if (XPT_FC_IS_QUEUED(abort_ccb)
2785                  && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2786                         /*
2787                          * It's already completed but waiting
2788                          * for our SWI to get to it.
2789                          */
2790                         start_ccb->ccb_h.status = CAM_UA_ABORT;
2791                         break;
2792                 }
2793                 /*
2794                  * If we weren't able to take care of the abort request
2795                  * in the XPT, pass the request down to the SIM for processing.
2796                  */
2797         }
2798         /* FALLTHROUGH */
2799         case XPT_ACCEPT_TARGET_IO:
2800         case XPT_EN_LUN:
2801         case XPT_IMMED_NOTIFY:
2802         case XPT_NOTIFY_ACK:
2803         case XPT_RESET_BUS:
2804         case XPT_IMMEDIATE_NOTIFY:
2805         case XPT_NOTIFY_ACKNOWLEDGE:
2806         case XPT_GET_SIM_KNOB_OLD:
2807         case XPT_GET_SIM_KNOB:
2808         case XPT_SET_SIM_KNOB:
2809         case XPT_GET_TRAN_SETTINGS:
2810         case XPT_SET_TRAN_SETTINGS:
2811         case XPT_PATH_INQ:
2812 call_sim:
2813                 sim = path->bus->sim;
2814                 mtx = sim->mtx;
2815                 if (mtx && !mtx_owned(mtx))
2816                         mtx_lock(mtx);
2817                 else
2818                         mtx = NULL;
2819
2820                 CAM_DEBUG(path, CAM_DEBUG_TRACE,
2821                     ("Calling sim->sim_action(): func=%#x\n", start_ccb->ccb_h.func_code));
2822                 (*(sim->sim_action))(sim, start_ccb);
2823                 CAM_DEBUG(path, CAM_DEBUG_TRACE,
2824                     ("sim->sim_action returned: status=%#x\n", start_ccb->ccb_h.status));
2825                 if (mtx)
2826                         mtx_unlock(mtx);
2827                 break;
2828         case XPT_PATH_STATS:
2829                 start_ccb->cpis.last_reset = path->bus->last_reset;
2830                 start_ccb->ccb_h.status = CAM_REQ_CMP;
2831                 break;
2832         case XPT_GDEV_TYPE:
2833         {
2834                 struct cam_ed *dev;
2835
2836                 dev = path->device;
2837                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2838                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2839                 } else {
2840                         struct ccb_getdev *cgd;
2841
2842                         cgd = &start_ccb->cgd;
2843                         cgd->protocol = dev->protocol;
2844                         cgd->inq_data = dev->inq_data;
2845                         cgd->ident_data = dev->ident_data;
2846                         cgd->inq_flags = dev->inq_flags;
2847                         cgd->ccb_h.status = CAM_REQ_CMP;
2848                         cgd->serial_num_len = dev->serial_num_len;
2849                         if ((dev->serial_num_len > 0)
2850                          && (dev->serial_num != NULL))
2851                                 bcopy(dev->serial_num, cgd->serial_num,
2852                                       dev->serial_num_len);
2853                 }
2854                 break;
2855         }
2856         case XPT_GDEV_STATS:
2857         {
2858                 struct ccb_getdevstats *cgds = &start_ccb->cgds;
2859                 struct cam_ed *dev = path->device;
2860                 struct cam_eb *bus = path->bus;
2861                 struct cam_et *tar = path->target;
2862                 struct cam_devq *devq = bus->sim->devq;
2863
2864                 mtx_lock(&devq->send_mtx);
2865                 cgds->dev_openings = dev->ccbq.dev_openings;
2866                 cgds->dev_active = dev->ccbq.dev_active;
2867                 cgds->allocated = dev->ccbq.allocated;
2868                 cgds->queued = cam_ccbq_pending_ccb_count(&dev->ccbq);
2869                 cgds->held = cgds->allocated - cgds->dev_active - cgds->queued;
2870                 cgds->last_reset = tar->last_reset;
2871                 cgds->maxtags = dev->maxtags;
2872                 cgds->mintags = dev->mintags;
2873                 if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2874                         cgds->last_reset = bus->last_reset;
2875                 mtx_unlock(&devq->send_mtx);
2876                 cgds->ccb_h.status = CAM_REQ_CMP;
2877                 break;
2878         }
2879         case XPT_GDEVLIST:
2880         {
2881                 struct cam_periph       *nperiph;
2882                 struct periph_list      *periph_head;
2883                 struct ccb_getdevlist   *cgdl;
2884                 u_int                   i;
2885                 struct cam_ed           *device;
2886                 int                     found;
2887
2888
2889                 found = 0;
2890
2891                 /*
2892                  * Don't want anyone mucking with our data.
2893                  */
2894                 device = path->device;
2895                 periph_head = &device->periphs;
2896                 cgdl = &start_ccb->cgdl;
2897
2898                 /*
2899                  * Check and see if the list has changed since the user
2900                  * last requested a list member.  If so, tell them that the
2901                  * list has changed, and therefore they need to start over
2902                  * from the beginning.
2903                  */
2904                 if ((cgdl->index != 0) &&
2905                     (cgdl->generation != device->generation)) {
2906                         cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2907                         break;
2908                 }
2909
2910                 /*
2911                  * Traverse the list of peripherals and attempt to find
2912                  * the requested peripheral.
2913                  */
2914                 for (nperiph = SLIST_FIRST(periph_head), i = 0;
2915                      (nperiph != NULL) && (i <= cgdl->index);
2916                      nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
2917                         if (i == cgdl->index) {
2918                                 strlcpy(cgdl->periph_name,
2919                                         nperiph->periph_name,
2920                                         sizeof(cgdl->periph_name));
2921                                 cgdl->unit_number = nperiph->unit_number;
2922                                 found = 1;
2923                         }
2924                 }
2925                 if (found == 0) {
2926                         cgdl->status = CAM_GDEVLIST_ERROR;
2927                         break;
2928                 }
2929
2930                 if (nperiph == NULL)
2931                         cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
2932                 else
2933                         cgdl->status = CAM_GDEVLIST_MORE_DEVS;
2934
2935                 cgdl->index++;
2936                 cgdl->generation = device->generation;
2937
2938                 cgdl->ccb_h.status = CAM_REQ_CMP;
2939                 break;
2940         }
2941         case XPT_DEV_MATCH:
2942         {
2943                 dev_pos_type position_type;
2944                 struct ccb_dev_match *cdm;
2945
2946                 cdm = &start_ccb->cdm;
2947
2948                 /*
2949                  * There are two ways of getting at information in the EDT.
2950                  * The first way is via the primary EDT tree.  It starts
2951                  * with a list of buses, then a list of targets on a bus,
2952                  * then devices/luns on a target, and then peripherals on a
2953                  * device/lun.  The "other" way is by the peripheral driver
2954                  * lists.  The peripheral driver lists are organized by
2955                  * peripheral driver.  (obviously)  So it makes sense to
2956                  * use the peripheral driver list if the user is looking
2957                  * for something like "da1", or all "da" devices.  If the
2958                  * user is looking for something on a particular bus/target
2959                  * or lun, it's generally better to go through the EDT tree.
2960                  */
2961
2962                 if (cdm->pos.position_type != CAM_DEV_POS_NONE)
2963                         position_type = cdm->pos.position_type;
2964                 else {
2965                         u_int i;
2966
2967                         position_type = CAM_DEV_POS_NONE;
2968
2969                         for (i = 0; i < cdm->num_patterns; i++) {
2970                                 if ((cdm->patterns[i].type == DEV_MATCH_BUS)
2971                                  ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
2972                                         position_type = CAM_DEV_POS_EDT;
2973                                         break;
2974                                 }
2975                         }
2976
2977                         if (cdm->num_patterns == 0)
2978                                 position_type = CAM_DEV_POS_EDT;
2979                         else if (position_type == CAM_DEV_POS_NONE)
2980                                 position_type = CAM_DEV_POS_PDRV;
2981                 }
2982
2983                 switch(position_type & CAM_DEV_POS_TYPEMASK) {
2984                 case CAM_DEV_POS_EDT:
2985                         xptedtmatch(cdm);
2986                         break;
2987                 case CAM_DEV_POS_PDRV:
2988                         xptperiphlistmatch(cdm);
2989                         break;
2990                 default:
2991                         cdm->status = CAM_DEV_MATCH_ERROR;
2992                         break;
2993                 }
2994
2995                 if (cdm->status == CAM_DEV_MATCH_ERROR)
2996                         start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2997                 else
2998                         start_ccb->ccb_h.status = CAM_REQ_CMP;
2999
3000                 break;
3001         }
3002         case XPT_SASYNC_CB:
3003         {
3004                 struct ccb_setasync *csa;
3005                 struct async_node *cur_entry;
3006                 struct async_list *async_head;
3007                 u_int32_t added;
3008
3009                 csa = &start_ccb->csa;
3010                 added = csa->event_enable;
3011                 async_head = &path->device->asyncs;
3012
3013                 /*
3014                  * If there is already an entry for us, simply
3015                  * update it.
3016                  */
3017                 cur_entry = SLIST_FIRST(async_head);
3018                 while (cur_entry != NULL) {
3019                         if ((cur_entry->callback_arg == csa->callback_arg)
3020                          && (cur_entry->callback == csa->callback))
3021                                 break;
3022                         cur_entry = SLIST_NEXT(cur_entry, links);
3023                 }
3024
3025                 if (cur_entry != NULL) {
3026                         /*
3027                          * If the request has no flags set,
3028                          * remove the entry.
3029                          */
3030                         added &= ~cur_entry->event_enable;
3031                         if (csa->event_enable == 0) {
3032                                 SLIST_REMOVE(async_head, cur_entry,
3033                                              async_node, links);
3034                                 xpt_release_device(path->device);
3035                                 free(cur_entry, M_CAMXPT);
3036                         } else {
3037                                 cur_entry->event_enable = csa->event_enable;
3038                         }
3039                         csa->event_enable = added;
3040                 } else {
3041                         cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
3042                                            M_NOWAIT);
3043                         if (cur_entry == NULL) {
3044                                 csa->ccb_h.status = CAM_RESRC_UNAVAIL;
3045                                 break;
3046                         }
3047                         cur_entry->event_enable = csa->event_enable;
3048                         cur_entry->event_lock = (path->bus->sim->mtx &&
3049                             mtx_owned(path->bus->sim->mtx)) ? 1 : 0;
3050                         cur_entry->callback_arg = csa->callback_arg;
3051                         cur_entry->callback = csa->callback;
3052                         SLIST_INSERT_HEAD(async_head, cur_entry, links);
3053                         xpt_acquire_device(path->device);
3054                 }
3055                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3056                 break;
3057         }
3058         case XPT_REL_SIMQ:
3059         {
3060                 struct ccb_relsim *crs;
3061                 struct cam_ed *dev;
3062
3063                 crs = &start_ccb->crs;
3064                 dev = path->device;
3065                 if (dev == NULL) {
3066
3067                         crs->ccb_h.status = CAM_DEV_NOT_THERE;
3068                         break;
3069                 }
3070
3071                 if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
3072
3073                         /* Don't ever go below one opening */
3074                         if (crs->openings > 0) {
3075                                 xpt_dev_ccbq_resize(path, crs->openings);
3076                                 if (bootverbose) {
3077                                         xpt_print(path,
3078                                             "number of openings is now %d\n",
3079                                             crs->openings);
3080                                 }
3081                         }
3082                 }
3083
3084                 mtx_lock(&dev->sim->devq->send_mtx);
3085                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
3086
3087                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
3088
3089                                 /*
3090                                  * Just extend the old timeout and decrement
3091                                  * the freeze count so that a single timeout
3092                                  * is sufficient for releasing the queue.
3093                                  */
3094                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3095                                 callout_stop(&dev->callout);
3096                         } else {
3097
3098                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3099                         }
3100
3101                         callout_reset_sbt(&dev->callout,
3102                             SBT_1MS * crs->release_timeout, 0,
3103                             xpt_release_devq_timeout, dev, 0);
3104
3105                         dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
3106
3107                 }
3108
3109                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
3110
3111                         if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
3112                                 /*
3113                                  * Decrement the freeze count so that a single
3114                                  * completion is still sufficient to unfreeze
3115                                  * the queue.
3116                                  */
3117                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3118                         } else {
3119
3120                                 dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3121                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3122                         }
3123                 }
3124
3125                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3126
3127                         if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3128                          || (dev->ccbq.dev_active == 0)) {
3129
3130                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3131                         } else {
3132
3133                                 dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3134                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3135                         }
3136                 }
3137                 mtx_unlock(&dev->sim->devq->send_mtx);
3138
3139                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0)
3140                         xpt_release_devq(path, /*count*/1, /*run_queue*/TRUE);
3141                 start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt;
3142                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3143                 break;
3144         }
3145         case XPT_DEBUG: {
3146                 struct cam_path *oldpath;
3147
3148                 /* Check that all request bits are supported. */
3149                 if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
3150                         start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3151                         break;
3152                 }
3153
3154                 cam_dflags = CAM_DEBUG_NONE;
3155                 if (cam_dpath != NULL) {
3156                         oldpath = cam_dpath;
3157                         cam_dpath = NULL;
3158                         xpt_free_path(oldpath);
3159                 }
3160                 if (start_ccb->cdbg.flags != CAM_DEBUG_NONE) {
3161                         if (xpt_create_path(&cam_dpath, NULL,
3162                                             start_ccb->ccb_h.path_id,
3163                                             start_ccb->ccb_h.target_id,
3164                                             start_ccb->ccb_h.target_lun) !=
3165                                             CAM_REQ_CMP) {
3166                                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3167                         } else {
3168                                 cam_dflags = start_ccb->cdbg.flags;
3169                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3170                                 xpt_print(cam_dpath, "debugging flags now %x\n",
3171                                     cam_dflags);
3172                         }
3173                 } else
3174                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3175                 break;
3176         }
3177         case XPT_NOOP:
3178                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3179                         xpt_freeze_devq(path, 1);
3180                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3181                 break;
3182         case XPT_REPROBE_LUN:
3183                 xpt_async(AC_INQ_CHANGED, path, NULL);
3184                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3185                 xpt_done(start_ccb);
3186                 break;
3187         default:
3188         case XPT_SDEV_TYPE:
3189         case XPT_TERM_IO:
3190         case XPT_ENG_INQ:
3191                 /* XXX Implement */
3192                 xpt_print(start_ccb->ccb_h.path,
3193                     "%s: CCB type %#x %s not supported\n", __func__,
3194                     start_ccb->ccb_h.func_code,
3195                     xpt_action_name(start_ccb->ccb_h.func_code));
3196                 start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3197                 if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
3198                         xpt_done(start_ccb);
3199                 }
3200                 break;
3201         }
3202         CAM_DEBUG(path, CAM_DEBUG_TRACE,
3203             ("xpt_action_default: func= %#x %s status %#x\n",
3204                 start_ccb->ccb_h.func_code,
3205                 xpt_action_name(start_ccb->ccb_h.func_code),
3206                 start_ccb->ccb_h.status));
3207 }
3208
3209 /*
3210  * Call the sim poll routine to allow the sim to complete
3211  * any inflight requests, then call camisr_runqueue to
3212  * complete any CCB that the polling completed.
3213  */
3214 void
3215 xpt_sim_poll(struct cam_sim *sim)
3216 {
3217         struct mtx *mtx;
3218
3219         mtx = sim->mtx;
3220         if (mtx)
3221                 mtx_lock(mtx);
3222         (*(sim->sim_poll))(sim);
3223         if (mtx)
3224                 mtx_unlock(mtx);
3225         camisr_runqueue();
3226 }
3227
3228 uint32_t
3229 xpt_poll_setup(union ccb *start_ccb)
3230 {
3231         u_int32_t timeout;
3232         struct    cam_sim *sim;
3233         struct    cam_devq *devq;
3234         struct    cam_ed *dev;
3235
3236         timeout = start_ccb->ccb_h.timeout * 10;
3237         sim = start_ccb->ccb_h.path->bus->sim;
3238         devq = sim->devq;
3239         dev = start_ccb->ccb_h.path->device;
3240
3241         /*
3242          * Steal an opening so that no other queued requests
3243          * can get it before us while we simulate interrupts.
3244          */
3245         mtx_lock(&devq->send_mtx);
3246         dev->ccbq.dev_openings--;
3247         while((devq->send_openings <= 0 || dev->ccbq.dev_openings < 0) &&
3248             (--timeout > 0)) {
3249                 mtx_unlock(&devq->send_mtx);
3250                 DELAY(100);
3251                 xpt_sim_poll(sim);
3252                 mtx_lock(&devq->send_mtx);
3253         }
3254         dev->ccbq.dev_openings++;
3255         mtx_unlock(&devq->send_mtx);
3256
3257         return (timeout);
3258 }
3259
3260 void
3261 xpt_pollwait(union ccb *start_ccb, uint32_t timeout)
3262 {
3263
3264         while (--timeout > 0) {
3265                 xpt_sim_poll(start_ccb->ccb_h.path->bus->sim);
3266                 if ((start_ccb->ccb_h.status & CAM_STATUS_MASK)
3267                     != CAM_REQ_INPROG)
3268                         break;
3269                 DELAY(100);
3270         }
3271
3272         if (timeout == 0) {
3273                 /*
3274                  * XXX Is it worth adding a sim_timeout entry
3275                  * point so we can attempt recovery?  If
3276                  * this is only used for dumps, I don't think
3277                  * it is.
3278                  */
3279                 start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3280         }
3281 }
3282
3283 void
3284 xpt_polled_action(union ccb *start_ccb)
3285 {
3286         uint32_t        timeout;
3287         struct cam_ed   *dev;
3288
3289         timeout = start_ccb->ccb_h.timeout * 10;
3290         dev = start_ccb->ccb_h.path->device;
3291
3292         mtx_unlock(&dev->device_mtx);
3293
3294         timeout = xpt_poll_setup(start_ccb);
3295         if (timeout > 0) {
3296                 xpt_action(start_ccb);
3297                 xpt_pollwait(start_ccb, timeout);
3298         } else {
3299                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3300         }
3301
3302         mtx_lock(&dev->device_mtx);
3303 }
3304
3305 /*
3306  * Schedule a peripheral driver to receive a ccb when its
3307  * target device has space for more transactions.
3308  */
3309 void
3310 xpt_schedule(struct cam_periph *periph, u_int32_t new_priority)
3311 {
3312
3313         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3314         cam_periph_assert(periph, MA_OWNED);
3315         if (new_priority < periph->scheduled_priority) {
3316                 periph->scheduled_priority = new_priority;
3317                 xpt_run_allocq(periph, 0);
3318         }
3319 }
3320
3321
3322 /*
3323  * Schedule a device to run on a given queue.
3324  * If the device was inserted as a new entry on the queue,
3325  * return 1 meaning the device queue should be run. If we
3326  * were already queued, implying someone else has already
3327  * started the queue, return 0 so the caller doesn't attempt
3328  * to run the queue.
3329  */
3330 static int
3331 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3332                  u_int32_t new_priority)
3333 {
3334         int retval;
3335         u_int32_t old_priority;
3336
3337         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3338
3339
3340         old_priority = pinfo->priority;
3341
3342         /*
3343          * Are we already queued?
3344          */
3345         if (pinfo->index != CAM_UNQUEUED_INDEX) {
3346                 /* Simply reorder based on new priority */
3347                 if (new_priority < old_priority) {
3348                         camq_change_priority(queue, pinfo->index,
3349                                              new_priority);
3350                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3351                                         ("changed priority to %d\n",
3352                                          new_priority));
3353                         retval = 1;
3354                 } else
3355                         retval = 0;
3356         } else {
3357                 /* New entry on the queue */
3358                 if (new_priority < old_priority)
3359                         pinfo->priority = new_priority;
3360
3361                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3362                                 ("Inserting onto queue\n"));
3363                 pinfo->generation = ++queue->generation;
3364                 camq_insert(queue, pinfo);
3365                 retval = 1;
3366         }
3367         return (retval);
3368 }
3369
3370 static void
3371 xpt_run_allocq_task(void *context, int pending)
3372 {
3373         struct cam_periph *periph = context;
3374
3375         cam_periph_lock(periph);
3376         periph->flags &= ~CAM_PERIPH_RUN_TASK;
3377         xpt_run_allocq(periph, 1);
3378         cam_periph_unlock(periph);
3379         cam_periph_release(periph);
3380 }
3381
3382 static void
3383 xpt_run_allocq(struct cam_periph *periph, int sleep)
3384 {
3385         struct cam_ed   *device;
3386         union ccb       *ccb;
3387         uint32_t         prio;
3388
3389         cam_periph_assert(periph, MA_OWNED);
3390         if (periph->periph_allocating)
3391                 return;
3392         cam_periph_doacquire(periph);
3393         periph->periph_allocating = 1;
3394         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_allocq(%p)\n", periph));
3395         device = periph->path->device;
3396         ccb = NULL;
3397 restart:
3398         while ((prio = min(periph->scheduled_priority,
3399             periph->immediate_priority)) != CAM_PRIORITY_NONE &&
3400             (periph->periph_allocated - (ccb != NULL ? 1 : 0) <
3401              device->ccbq.total_openings || prio <= CAM_PRIORITY_OOB)) {
3402
3403                 if (ccb == NULL &&
3404                     (ccb = xpt_get_ccb_nowait(periph)) == NULL) {
3405                         if (sleep) {
3406                                 ccb = xpt_get_ccb(periph);
3407                                 goto restart;
3408                         }
3409                         if (periph->flags & CAM_PERIPH_RUN_TASK)
3410                                 break;
3411                         cam_periph_doacquire(periph);
3412                         periph->flags |= CAM_PERIPH_RUN_TASK;
3413                         taskqueue_enqueue(xsoftc.xpt_taskq,
3414                             &periph->periph_run_task);
3415                         break;
3416                 }
3417                 xpt_setup_ccb(&ccb->ccb_h, periph->path, prio);
3418                 if (prio == periph->immediate_priority) {
3419                         periph->immediate_priority = CAM_PRIORITY_NONE;
3420                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3421                                         ("waking cam_periph_getccb()\n"));
3422                         SLIST_INSERT_HEAD(&periph->ccb_list, &ccb->ccb_h,
3423                                           periph_links.sle);
3424                         wakeup(&periph->ccb_list);
3425                 } else {
3426                         periph->scheduled_priority = CAM_PRIORITY_NONE;
3427                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3428                                         ("calling periph_start()\n"));
3429                         periph->periph_start(periph, ccb);
3430                 }
3431                 ccb = NULL;
3432         }
3433         if (ccb != NULL)
3434                 xpt_release_ccb(ccb);
3435         periph->periph_allocating = 0;
3436         cam_periph_release_locked(periph);
3437 }
3438
3439 static void
3440 xpt_run_devq(struct cam_devq *devq)
3441 {
3442         struct mtx *mtx;
3443
3444         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_devq\n"));
3445
3446         devq->send_queue.qfrozen_cnt++;
3447         while ((devq->send_queue.entries > 0)
3448             && (devq->send_openings > 0)
3449             && (devq->send_queue.qfrozen_cnt <= 1)) {
3450                 struct  cam_ed *device;
3451                 union ccb *work_ccb;
3452                 struct  cam_sim *sim;
3453                 struct xpt_proto *proto;
3454
3455                 device = (struct cam_ed *)camq_remove(&devq->send_queue,
3456                                                            CAMQ_HEAD);
3457                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3458                                 ("running device %p\n", device));
3459
3460                 work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3461                 if (work_ccb == NULL) {
3462                         printf("device on run queue with no ccbs???\n");
3463                         continue;
3464                 }
3465
3466                 if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3467
3468                         mtx_lock(&xsoftc.xpt_highpower_lock);
3469                         if (xsoftc.num_highpower <= 0) {
3470                                 /*
3471                                  * We got a high power command, but we
3472                                  * don't have any available slots.  Freeze
3473                                  * the device queue until we have a slot
3474                                  * available.
3475                                  */
3476                                 xpt_freeze_devq_device(device, 1);
3477                                 STAILQ_INSERT_TAIL(&xsoftc.highpowerq, device,
3478                                                    highpowerq_entry);
3479
3480                                 mtx_unlock(&xsoftc.xpt_highpower_lock);
3481                                 continue;
3482                         } else {
3483                                 /*
3484                                  * Consume a high power slot while
3485                                  * this ccb runs.
3486                                  */
3487                                 xsoftc.num_highpower--;
3488                         }
3489                         mtx_unlock(&xsoftc.xpt_highpower_lock);
3490                 }
3491                 cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3492                 cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3493                 devq->send_openings--;
3494                 devq->send_active++;
3495                 xpt_schedule_devq(devq, device);
3496                 mtx_unlock(&devq->send_mtx);
3497
3498                 if ((work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0) {
3499                         /*
3500                          * The client wants to freeze the queue
3501                          * after this CCB is sent.
3502                          */
3503                         xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3504                 }
3505
3506                 /* In Target mode, the peripheral driver knows best... */
3507                 if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3508                         if ((device->inq_flags & SID_CmdQue) != 0
3509                          && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3510                                 work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3511                         else
3512                                 /*
3513                                  * Clear this in case of a retried CCB that
3514                                  * failed due to a rejected tag.
3515                                  */
3516                                 work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3517                 }
3518
3519                 KASSERT(device == work_ccb->ccb_h.path->device,
3520                     ("device (%p) / path->device (%p) mismatch",
3521                         device, work_ccb->ccb_h.path->device));
3522                 proto = xpt_proto_find(device->protocol);
3523                 if (proto && proto->ops->debug_out)
3524                         proto->ops->debug_out(work_ccb);
3525
3526                 /*
3527                  * Device queues can be shared among multiple SIM instances
3528                  * that reside on different buses.  Use the SIM from the
3529                  * queued device, rather than the one from the calling bus.
3530                  */
3531                 sim = device->sim;
3532                 mtx = sim->mtx;
3533                 if (mtx && !mtx_owned(mtx))
3534                         mtx_lock(mtx);
3535                 else
3536                         mtx = NULL;
3537                 work_ccb->ccb_h.qos.periph_data = cam_iosched_now();
3538                 (*(sim->sim_action))(sim, work_ccb);
3539                 if (mtx)
3540                         mtx_unlock(mtx);
3541                 mtx_lock(&devq->send_mtx);
3542         }
3543         devq->send_queue.qfrozen_cnt--;
3544 }
3545
3546 /*
3547  * This function merges stuff from the slave ccb into the master ccb, while
3548  * keeping important fields in the master ccb constant.
3549  */
3550 void
3551 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3552 {
3553
3554         /*
3555          * Pull fields that are valid for peripheral drivers to set
3556          * into the master CCB along with the CCB "payload".
3557          */
3558         master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3559         master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3560         master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3561         master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3562         bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3563               sizeof(union ccb) - sizeof(struct ccb_hdr));
3564 }
3565
3566 void
3567 xpt_setup_ccb_flags(struct ccb_hdr *ccb_h, struct cam_path *path,
3568                     u_int32_t priority, u_int32_t flags)
3569 {
3570
3571         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3572         ccb_h->pinfo.priority = priority;
3573         ccb_h->path = path;
3574         ccb_h->path_id = path->bus->path_id;
3575         if (path->target)
3576                 ccb_h->target_id = path->target->target_id;
3577         else
3578                 ccb_h->target_id = CAM_TARGET_WILDCARD;
3579         if (path->device) {
3580                 ccb_h->target_lun = path->device->lun_id;
3581                 ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3582         } else {
3583                 ccb_h->target_lun = CAM_TARGET_WILDCARD;
3584         }
3585         ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3586         ccb_h->flags = flags;
3587         ccb_h->xflags = 0;
3588 }
3589
3590 void
3591 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3592 {
3593         xpt_setup_ccb_flags(ccb_h, path, priority, /*flags*/ 0);
3594 }
3595
3596 /* Path manipulation functions */
3597 cam_status
3598 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3599                 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3600 {
3601         struct     cam_path *path;
3602         cam_status status;
3603
3604         path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3605
3606         if (path == NULL) {
3607                 status = CAM_RESRC_UNAVAIL;
3608                 return(status);
3609         }
3610         status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3611         if (status != CAM_REQ_CMP) {
3612                 free(path, M_CAMPATH);
3613                 path = NULL;
3614         }
3615         *new_path_ptr = path;
3616         return (status);
3617 }
3618
3619 cam_status
3620 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3621                          struct cam_periph *periph, path_id_t path_id,
3622                          target_id_t target_id, lun_id_t lun_id)
3623 {
3624
3625         return (xpt_create_path(new_path_ptr, periph, path_id, target_id,
3626             lun_id));
3627 }
3628
3629 cam_status
3630 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3631                  path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3632 {
3633         struct       cam_eb *bus;
3634         struct       cam_et *target;
3635         struct       cam_ed *device;
3636         cam_status   status;
3637
3638         status = CAM_REQ_CMP;   /* Completed without error */
3639         target = NULL;          /* Wildcarded */
3640         device = NULL;          /* Wildcarded */
3641
3642         /*
3643          * We will potentially modify the EDT, so block interrupts
3644          * that may attempt to create cam paths.
3645          */
3646         bus = xpt_find_bus(path_id);
3647         if (bus == NULL) {
3648                 status = CAM_PATH_INVALID;
3649         } else {
3650                 xpt_lock_buses();
3651                 mtx_lock(&bus->eb_mtx);
3652                 target = xpt_find_target(bus, target_id);
3653                 if (target == NULL) {
3654                         /* Create one */
3655                         struct cam_et *new_target;
3656
3657                         new_target = xpt_alloc_target(bus, target_id);
3658                         if (new_target == NULL) {
3659                                 status = CAM_RESRC_UNAVAIL;
3660                         } else {
3661                                 target = new_target;
3662                         }
3663                 }
3664                 xpt_unlock_buses();
3665                 if (target != NULL) {
3666                         device = xpt_find_device(target, lun_id);
3667                         if (device == NULL) {
3668                                 /* Create one */
3669                                 struct cam_ed *new_device;
3670
3671                                 new_device =
3672                                     (*(bus->xport->ops->alloc_device))(bus,
3673                                                                        target,
3674                                                                        lun_id);
3675                                 if (new_device == NULL) {
3676                                         status = CAM_RESRC_UNAVAIL;
3677                                 } else {
3678                                         device = new_device;
3679                                 }
3680                         }
3681                 }
3682                 mtx_unlock(&bus->eb_mtx);
3683         }
3684
3685         /*
3686          * Only touch the user's data if we are successful.
3687          */
3688         if (status == CAM_REQ_CMP) {
3689                 new_path->periph = perph;
3690                 new_path->bus = bus;
3691                 new_path->target = target;
3692                 new_path->device = device;
3693                 CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3694         } else {
3695                 if (device != NULL)
3696                         xpt_release_device(device);
3697                 if (target != NULL)
3698                         xpt_release_target(target);
3699                 if (bus != NULL)
3700                         xpt_release_bus(bus);
3701         }
3702         return (status);
3703 }
3704
3705 cam_status
3706 xpt_clone_path(struct cam_path **new_path_ptr, struct cam_path *path)
3707 {
3708         struct     cam_path *new_path;
3709
3710         new_path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3711         if (new_path == NULL)
3712                 return(CAM_RESRC_UNAVAIL);
3713         xpt_copy_path(new_path, path);
3714         *new_path_ptr = new_path;
3715         return (CAM_REQ_CMP);
3716 }
3717
3718 void
3719 xpt_copy_path(struct cam_path *new_path, struct cam_path *path)
3720 {
3721
3722         *new_path = *path;
3723         if (path->bus != NULL)
3724                 xpt_acquire_bus(path->bus);
3725         if (path->target != NULL)
3726                 xpt_acquire_target(path->target);
3727         if (path->device != NULL)
3728                 xpt_acquire_device(path->device);
3729 }
3730
3731 void
3732 xpt_release_path(struct cam_path *path)
3733 {
3734         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3735         if (path->device != NULL) {
3736                 xpt_release_device(path->device);
3737                 path->device = NULL;
3738         }
3739         if (path->target != NULL) {
3740                 xpt_release_target(path->target);
3741                 path->target = NULL;
3742         }
3743         if (path->bus != NULL) {
3744                 xpt_release_bus(path->bus);
3745                 path->bus = NULL;
3746         }
3747 }
3748
3749 void
3750 xpt_free_path(struct cam_path *path)
3751 {
3752
3753         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3754         xpt_release_path(path);
3755         free(path, M_CAMPATH);
3756 }
3757
3758 void
3759 xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
3760     uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
3761 {
3762
3763         xpt_lock_buses();
3764         if (bus_ref) {
3765                 if (path->bus)
3766                         *bus_ref = path->bus->refcount;
3767                 else
3768                         *bus_ref = 0;
3769         }
3770         if (periph_ref) {
3771                 if (path->periph)
3772                         *periph_ref = path->periph->refcount;
3773                 else
3774                         *periph_ref = 0;
3775         }
3776         xpt_unlock_buses();
3777         if (target_ref) {
3778                 if (path->target)
3779                         *target_ref = path->target->refcount;
3780                 else
3781                         *target_ref = 0;
3782         }
3783         if (device_ref) {
3784                 if (path->device)
3785                         *device_ref = path->device->refcount;
3786                 else
3787                         *device_ref = 0;
3788         }
3789 }
3790
3791 /*
3792  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3793  * in path1, 2 for match with wildcards in path2.
3794  */
3795 int
3796 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3797 {
3798         int retval = 0;
3799
3800         if (path1->bus != path2->bus) {
3801                 if (path1->bus->path_id == CAM_BUS_WILDCARD)
3802                         retval = 1;
3803                 else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3804                         retval = 2;
3805                 else
3806                         return (-1);
3807         }
3808         if (path1->target != path2->target) {
3809                 if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3810                         if (retval == 0)
3811                                 retval = 1;
3812                 } else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3813                         retval = 2;
3814                 else
3815                         return (-1);
3816         }
3817         if (path1->device != path2->device) {
3818                 if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3819                         if (retval == 0)
3820                                 retval = 1;
3821                 } else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3822                         retval = 2;
3823                 else
3824                         return (-1);
3825         }
3826         return (retval);
3827 }
3828
3829 int
3830 xpt_path_comp_dev(struct cam_path *path, struct cam_ed *dev)
3831 {
3832         int retval = 0;
3833
3834         if (path->bus != dev->target->bus) {
3835                 if (path->bus->path_id == CAM_BUS_WILDCARD)
3836                         retval = 1;
3837                 else if (dev->target->bus->path_id == CAM_BUS_WILDCARD)
3838                         retval = 2;
3839                 else
3840                         return (-1);
3841         }
3842         if (path->target != dev->target) {
3843                 if (path->target->target_id == CAM_TARGET_WILDCARD) {
3844                         if (retval == 0)
3845                                 retval = 1;
3846                 } else if (dev->target->target_id == CAM_TARGET_WILDCARD)
3847                         retval = 2;
3848                 else
3849                         return (-1);
3850         }
3851         if (path->device != dev) {
3852                 if (path->device->lun_id == CAM_LUN_WILDCARD) {
3853                         if (retval == 0)
3854                                 retval = 1;
3855                 } else if (dev->lun_id == CAM_LUN_WILDCARD)
3856                         retval = 2;
3857                 else
3858                         return (-1);
3859         }
3860         return (retval);
3861 }
3862
3863 void
3864 xpt_print_path(struct cam_path *path)
3865 {
3866         struct sbuf sb;
3867         char buffer[XPT_PRINT_LEN];
3868
3869         sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3870         xpt_path_sbuf(path, &sb);
3871         sbuf_finish(&sb);
3872         printf("%s", sbuf_data(&sb));
3873         sbuf_delete(&sb);
3874 }
3875
3876 void
3877 xpt_print_device(struct cam_ed *device)
3878 {
3879
3880         if (device == NULL)
3881                 printf("(nopath): ");
3882         else {
3883                 printf("(noperiph:%s%d:%d:%d:%jx): ", device->sim->sim_name,
3884                        device->sim->unit_number,
3885                        device->sim->bus_id,
3886                        device->target->target_id,
3887                        (uintmax_t)device->lun_id);
3888         }
3889 }
3890
3891 void
3892 xpt_print(struct cam_path *path, const char *fmt, ...)
3893 {
3894         va_list ap;
3895         struct sbuf sb;
3896         char buffer[XPT_PRINT_LEN];
3897
3898         sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3899
3900         xpt_path_sbuf(path, &sb);
3901         va_start(ap, fmt);
3902         sbuf_vprintf(&sb, fmt, ap);
3903         va_end(ap);
3904
3905         sbuf_finish(&sb);
3906         printf("%s", sbuf_data(&sb));
3907         sbuf_delete(&sb);
3908 }
3909
3910 int
3911 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
3912 {
3913         struct sbuf sb;
3914         int len;
3915
3916         sbuf_new(&sb, str, str_len, 0);
3917         len = xpt_path_sbuf(path, &sb);
3918         sbuf_finish(&sb);
3919         return (len);
3920 }
3921
3922 int
3923 xpt_path_sbuf(struct cam_path *path, struct sbuf *sb)
3924 {
3925
3926         if (path == NULL)
3927                 sbuf_printf(sb, "(nopath): ");
3928         else {
3929                 if (path->periph != NULL)
3930                         sbuf_printf(sb, "(%s%d:", path->periph->periph_name,
3931                                     path->periph->unit_number);
3932                 else
3933                         sbuf_printf(sb, "(noperiph:");
3934
3935                 if (path->bus != NULL)
3936                         sbuf_printf(sb, "%s%d:%d:", path->bus->sim->sim_name,
3937                                     path->bus->sim->unit_number,
3938                                     path->bus->sim->bus_id);
3939                 else
3940                         sbuf_printf(sb, "nobus:");
3941
3942                 if (path->target != NULL)
3943                         sbuf_printf(sb, "%d:", path->target->target_id);
3944                 else
3945                         sbuf_printf(sb, "X:");
3946
3947                 if (path->device != NULL)
3948                         sbuf_printf(sb, "%jx): ",
3949                             (uintmax_t)path->device->lun_id);
3950                 else
3951                         sbuf_printf(sb, "X): ");
3952         }
3953
3954         return(sbuf_len(sb));
3955 }
3956
3957 path_id_t
3958 xpt_path_path_id(struct cam_path *path)
3959 {
3960         return(path->bus->path_id);
3961 }
3962
3963 target_id_t
3964 xpt_path_target_id(struct cam_path *path)
3965 {
3966         if (path->target != NULL)
3967                 return (path->target->target_id);
3968         else
3969                 return (CAM_TARGET_WILDCARD);
3970 }
3971
3972 lun_id_t
3973 xpt_path_lun_id(struct cam_path *path)
3974 {
3975         if (path->device != NULL)
3976                 return (path->device->lun_id);
3977         else
3978                 return (CAM_LUN_WILDCARD);
3979 }
3980
3981 struct cam_sim *
3982 xpt_path_sim(struct cam_path *path)
3983 {
3984
3985         return (path->bus->sim);
3986 }
3987
3988 struct cam_periph*
3989 xpt_path_periph(struct cam_path *path)
3990 {
3991
3992         return (path->periph);
3993 }
3994
3995 /*
3996  * Release a CAM control block for the caller.  Remit the cost of the structure
3997  * to the device referenced by the path.  If the this device had no 'credits'
3998  * and peripheral drivers have registered async callbacks for this notification
3999  * call them now.
4000  */
4001 void
4002 xpt_release_ccb(union ccb *free_ccb)
4003 {
4004         struct   cam_ed *device;
4005         struct   cam_periph *periph;
4006
4007         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
4008         xpt_path_assert(free_ccb->ccb_h.path, MA_OWNED);
4009         device = free_ccb->ccb_h.path->device;
4010         periph = free_ccb->ccb_h.path->periph;
4011
4012         xpt_free_ccb(free_ccb);
4013         periph->periph_allocated--;
4014         cam_ccbq_release_opening(&device->ccbq);
4015         xpt_run_allocq(periph, 0);
4016 }
4017
4018 /* Functions accessed by SIM drivers */
4019
4020 static struct xpt_xport_ops xport_default_ops = {
4021         .alloc_device = xpt_alloc_device_default,
4022         .action = xpt_action_default,
4023         .async = xpt_dev_async_default,
4024 };
4025 static struct xpt_xport xport_default = {
4026         .xport = XPORT_UNKNOWN,
4027         .name = "unknown",
4028         .ops = &xport_default_ops,
4029 };
4030
4031 CAM_XPT_XPORT(xport_default);
4032
4033 /*
4034  * A sim structure, listing the SIM entry points and instance
4035  * identification info is passed to xpt_bus_register to hook the SIM
4036  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
4037  * for this new bus and places it in the array of buses and assigns
4038  * it a path_id.  The path_id may be influenced by "hard wiring"
4039  * information specified by the user.  Once interrupt services are
4040  * available, the bus will be probed.
4041  */
4042 int32_t
4043 xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
4044 {
4045         struct cam_eb *new_bus;
4046         struct cam_eb *old_bus;
4047         struct ccb_pathinq cpi;
4048         struct cam_path *path;
4049         cam_status status;
4050
4051         sim->bus_id = bus;
4052         new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
4053                                           M_CAMXPT, M_NOWAIT|M_ZERO);
4054         if (new_bus == NULL) {
4055                 /* Couldn't satisfy request */
4056                 return (CAM_RESRC_UNAVAIL);
4057         }
4058
4059         mtx_init(&new_bus->eb_mtx, "CAM bus lock", NULL, MTX_DEF);
4060         TAILQ_INIT(&new_bus->et_entries);
4061         cam_sim_hold(sim);
4062         new_bus->sim = sim;
4063         timevalclear(&new_bus->last_reset);
4064         new_bus->flags = 0;
4065         new_bus->refcount = 1;  /* Held until a bus_deregister event */
4066         new_bus->generation = 0;
4067
4068         xpt_lock_buses();
4069         sim->path_id = new_bus->path_id =
4070             xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
4071         old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4072         while (old_bus != NULL
4073             && old_bus->path_id < new_bus->path_id)
4074                 old_bus = TAILQ_NEXT(old_bus, links);
4075         if (old_bus != NULL)
4076                 TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
4077         else
4078                 TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
4079         xsoftc.bus_generation++;
4080         xpt_unlock_buses();
4081
4082         /*
4083          * Set a default transport so that a PATH_INQ can be issued to
4084          * the SIM.  This will then allow for probing and attaching of
4085          * a more appropriate transport.
4086          */
4087         new_bus->xport = &xport_default;
4088
4089         status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
4090                                   CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4091         if (status != CAM_REQ_CMP) {
4092                 xpt_release_bus(new_bus);
4093                 return (CAM_RESRC_UNAVAIL);
4094         }
4095
4096         xpt_path_inq(&cpi, path);
4097
4098         if (cpi.ccb_h.status == CAM_REQ_CMP) {
4099                 struct xpt_xport **xpt;
4100
4101                 SET_FOREACH(xpt, cam_xpt_xport_set) {
4102                         if ((*xpt)->xport == cpi.transport) {
4103                                 new_bus->xport = *xpt;
4104                                 break;
4105                         }
4106                 }
4107                 if (new_bus->xport == NULL) {
4108                         xpt_print(path,
4109                             "No transport found for %d\n", cpi.transport);
4110                         xpt_release_bus(new_bus);
4111                         free(path, M_CAMXPT);
4112                         return (CAM_RESRC_UNAVAIL);
4113                 }
4114         }
4115
4116         /* Notify interested parties */
4117         if (sim->path_id != CAM_XPT_PATH_ID) {
4118
4119                 xpt_async(AC_PATH_REGISTERED, path, &cpi);
4120                 if ((cpi.hba_misc & PIM_NOSCAN) == 0) {
4121                         union   ccb *scan_ccb;
4122
4123                         /* Initiate bus rescan. */
4124                         scan_ccb = xpt_alloc_ccb_nowait();
4125                         if (scan_ccb != NULL) {
4126                                 scan_ccb->ccb_h.path = path;
4127                                 scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
4128                                 scan_ccb->crcn.flags = 0;
4129                                 xpt_rescan(scan_ccb);
4130                         } else {
4131                                 xpt_print(path,
4132                                           "Can't allocate CCB to scan bus\n");
4133                                 xpt_free_path(path);
4134                         }
4135                 } else
4136                         xpt_free_path(path);
4137         } else
4138                 xpt_free_path(path);
4139         return (CAM_SUCCESS);
4140 }
4141
4142 int32_t
4143 xpt_bus_deregister(path_id_t pathid)
4144 {
4145         struct cam_path bus_path;
4146         cam_status status;
4147
4148         status = xpt_compile_path(&bus_path, NULL, pathid,
4149                                   CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4150         if (status != CAM_REQ_CMP)
4151                 return (status);
4152
4153         xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4154         xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4155
4156         /* Release the reference count held while registered. */
4157         xpt_release_bus(bus_path.bus);
4158         xpt_release_path(&bus_path);
4159
4160         return (CAM_REQ_CMP);
4161 }
4162
4163 static path_id_t
4164 xptnextfreepathid(void)
4165 {
4166         struct cam_eb *bus;
4167         path_id_t pathid;
4168         const char *strval;
4169
4170         mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4171         pathid = 0;
4172         bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4173 retry:
4174         /* Find an unoccupied pathid */
4175         while (bus != NULL && bus->path_id <= pathid) {
4176                 if (bus->path_id == pathid)
4177                         pathid++;
4178                 bus = TAILQ_NEXT(bus, links);
4179         }
4180
4181         /*
4182          * Ensure that this pathid is not reserved for
4183          * a bus that may be registered in the future.
4184          */
4185         if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4186                 ++pathid;
4187                 /* Start the search over */
4188                 goto retry;
4189         }
4190         return (pathid);
4191 }
4192
4193 static path_id_t
4194 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4195 {
4196         path_id_t pathid;
4197         int i, dunit, val;
4198         char buf[32];
4199         const char *dname;
4200
4201         pathid = CAM_XPT_PATH_ID;
4202         snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4203         if (strcmp(buf, "xpt0") == 0 && sim_bus == 0)
4204                 return (pathid);
4205         i = 0;
4206         while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
4207                 if (strcmp(dname, "scbus")) {
4208                         /* Avoid a bit of foot shooting. */
4209                         continue;
4210                 }
4211                 if (dunit < 0)          /* unwired?! */
4212                         continue;
4213                 if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4214                         if (sim_bus == val) {
4215                                 pathid = dunit;
4216                                 break;
4217                         }
4218                 } else if (sim_bus == 0) {
4219                         /* Unspecified matches bus 0 */
4220                         pathid = dunit;
4221                         break;
4222                 } else {
4223                         printf("Ambiguous scbus configuration for %s%d "
4224                                "bus %d, cannot wire down.  The kernel "
4225                                "config entry for scbus%d should "
4226                                "specify a controller bus.\n"
4227                                "Scbus will be assigned dynamically.\n",
4228                                sim_name, sim_unit, sim_bus, dunit);
4229                         break;
4230                 }
4231         }
4232
4233         if (pathid == CAM_XPT_PATH_ID)
4234                 pathid = xptnextfreepathid();
4235         return (pathid);
4236 }
4237
4238 static const char *
4239 xpt_async_string(u_int32_t async_code)
4240 {
4241
4242         switch (async_code) {
4243         case AC_BUS_RESET: return ("AC_BUS_RESET");
4244         case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
4245         case AC_SCSI_AEN: return ("AC_SCSI_AEN");
4246         case AC_SENT_BDR: return ("AC_SENT_BDR");
4247         case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
4248         case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
4249         case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
4250         case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
4251         case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
4252         case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
4253         case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
4254         case AC_CONTRACT: return ("AC_CONTRACT");
4255         case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
4256         case AC_UNIT_ATTENTION: return ("AC_UNIT_ATTENTION");
4257         }
4258         return ("AC_UNKNOWN");
4259 }
4260
4261 static int
4262 xpt_async_size(u_int32_t async_code)
4263 {
4264
4265         switch (async_code) {
4266         case AC_BUS_RESET: return (0);
4267         case AC_UNSOL_RESEL: return (0);
4268         case AC_SCSI_AEN: return (0);
4269         case AC_SENT_BDR: return (0);
4270         case AC_PATH_REGISTERED: return (sizeof(struct ccb_pathinq));
4271         case AC_PATH_DEREGISTERED: return (0);
4272         case AC_FOUND_DEVICE: return (sizeof(struct ccb_getdev));
4273         case AC_LOST_DEVICE: return (0);
4274         case AC_TRANSFER_NEG: return (sizeof(struct ccb_trans_settings));
4275         case AC_INQ_CHANGED: return (0);
4276         case AC_GETDEV_CHANGED: return (0);
4277         case AC_CONTRACT: return (sizeof(struct ac_contract));
4278         case AC_ADVINFO_CHANGED: return (-1);
4279         case AC_UNIT_ATTENTION: return (sizeof(struct ccb_scsiio));
4280         }
4281         return (0);
4282 }
4283
4284 static int
4285 xpt_async_process_dev(struct cam_ed *device, void *arg)
4286 {
4287         union ccb *ccb = arg;
4288         struct cam_path *path = ccb->ccb_h.path;
4289         void *async_arg = ccb->casync.async_arg_ptr;
4290         u_int32_t async_code = ccb->casync.async_code;
4291         int relock;
4292
4293         if (path->device != device
4294          && path->device->lun_id != CAM_LUN_WILDCARD
4295          && device->lun_id != CAM_LUN_WILDCARD)
4296                 return (1);
4297
4298         /*
4299          * The async callback could free the device.
4300          * If it is a broadcast async, it doesn't hold
4301          * device reference, so take our own reference.
4302          */
4303         xpt_acquire_device(device);
4304
4305         /*
4306          * If async for specific device is to be delivered to
4307          * the wildcard client, take the specific device lock.
4308          * XXX: We may need a way for client to specify it.
4309          */
4310         if ((device->lun_id == CAM_LUN_WILDCARD &&
4311              path->device->lun_id != CAM_LUN_WILDCARD) ||
4312             (device->target->target_id == CAM_TARGET_WILDCARD &&
4313              path->target->target_id != CAM_TARGET_WILDCARD) ||
4314             (device->target->bus->path_id == CAM_BUS_WILDCARD &&
4315              path->target->bus->path_id != CAM_BUS_WILDCARD)) {
4316                 mtx_unlock(&device->device_mtx);
4317                 xpt_path_lock(path);
4318                 relock = 1;
4319         } else
4320                 relock = 0;
4321
4322         (*(device->target->bus->xport->ops->async))(async_code,
4323             device->target->bus, device->target, device, async_arg);
4324         xpt_async_bcast(&device->asyncs, async_code, path, async_arg);
4325
4326         if (relock) {
4327                 xpt_path_unlock(path);
4328                 mtx_lock(&device->device_mtx);
4329         }
4330         xpt_release_device(device);
4331         return (1);
4332 }
4333
4334 static int
4335 xpt_async_process_tgt(struct cam_et *target, void *arg)
4336 {
4337         union ccb *ccb = arg;
4338         struct cam_path *path = ccb->ccb_h.path;
4339
4340         if (path->target != target
4341          && path->target->target_id != CAM_TARGET_WILDCARD
4342          && target->target_id != CAM_TARGET_WILDCARD)
4343                 return (1);
4344
4345         if (ccb->casync.async_code == AC_SENT_BDR) {
4346                 /* Update our notion of when the last reset occurred */
4347                 microtime(&target->last_reset);
4348         }
4349
4350         return (xptdevicetraverse(target, NULL, xpt_async_process_dev, ccb));
4351 }
4352
4353 static void
4354 xpt_async_process(struct cam_periph *periph, union ccb *ccb)
4355 {
4356         struct cam_eb *bus;
4357         struct cam_path *path;
4358         void *async_arg;
4359         u_int32_t async_code;
4360
4361         path = ccb->ccb_h.path;
4362         async_code = ccb->casync.async_code;
4363         async_arg = ccb->casync.async_arg_ptr;
4364         CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
4365             ("xpt_async(%s)\n", xpt_async_string(async_code)));
4366         bus = path->bus;
4367
4368         if (async_code == AC_BUS_RESET) {
4369                 /* Update our notion of when the last reset occurred */
4370                 microtime(&bus->last_reset);
4371         }
4372
4373         xpttargettraverse(bus, NULL, xpt_async_process_tgt, ccb);
4374
4375         /*
4376          * If this wasn't a fully wildcarded async, tell all
4377          * clients that want all async events.
4378          */
4379         if (bus != xpt_periph->path->bus) {
4380                 xpt_path_lock(xpt_periph->path);
4381                 xpt_async_process_dev(xpt_periph->path->device, ccb);
4382                 xpt_path_unlock(xpt_periph->path);
4383         }
4384
4385         if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4386                 xpt_release_devq(path, 1, TRUE);
4387         else
4388                 xpt_release_simq(path->bus->sim, TRUE);
4389         if (ccb->casync.async_arg_size > 0)
4390                 free(async_arg, M_CAMXPT);
4391         xpt_free_path(path);
4392         xpt_free_ccb(ccb);
4393 }
4394
4395 static void
4396 xpt_async_bcast(struct async_list *async_head,
4397                 u_int32_t async_code,
4398                 struct cam_path *path, void *async_arg)
4399 {
4400         struct async_node *cur_entry;
4401         struct mtx *mtx;
4402
4403         cur_entry = SLIST_FIRST(async_head);
4404         while (cur_entry != NULL) {
4405                 struct async_node *next_entry;
4406                 /*
4407                  * Grab the next list entry before we call the current
4408                  * entry's callback.  This is because the callback function
4409                  * can delete its async callback entry.
4410                  */
4411                 next_entry = SLIST_NEXT(cur_entry, links);
4412                 if ((cur_entry->event_enable & async_code) != 0) {
4413                         mtx = cur_entry->event_lock ?
4414                             path->device->sim->mtx : NULL;
4415                         if (mtx)
4416                                 mtx_lock(mtx);
4417                         cur_entry->callback(cur_entry->callback_arg,
4418                                             async_code, path,
4419                                             async_arg);
4420                         if (mtx)
4421                                 mtx_unlock(mtx);
4422                 }
4423                 cur_entry = next_entry;
4424         }
4425 }
4426
4427 void
4428 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4429 {
4430         union ccb *ccb;
4431         int size;
4432
4433         ccb = xpt_alloc_ccb_nowait();
4434         if (ccb == NULL) {
4435                 xpt_print(path, "Can't allocate CCB to send %s\n",
4436                     xpt_async_string(async_code));
4437                 return;
4438         }
4439
4440         if (xpt_clone_path(&ccb->ccb_h.path, path) != CAM_REQ_CMP) {
4441                 xpt_print(path, "Can't allocate path to send %s\n",
4442                     xpt_async_string(async_code));
4443                 xpt_free_ccb(ccb);
4444                 return;
4445         }
4446         ccb->ccb_h.path->periph = NULL;
4447         ccb->ccb_h.func_code = XPT_ASYNC;
4448         ccb->ccb_h.cbfcnp = xpt_async_process;
4449         ccb->ccb_h.flags |= CAM_UNLOCKED;
4450         ccb->casync.async_code = async_code;
4451         ccb->casync.async_arg_size = 0;
4452         size = xpt_async_size(async_code);
4453         CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
4454             ("xpt_async: func %#x %s aync_code %d %s\n",
4455                 ccb->ccb_h.func_code,
4456                 xpt_action_name(ccb->ccb_h.func_code),
4457                 async_code,
4458                 xpt_async_string(async_code)));
4459         if (size > 0 && async_arg != NULL) {
4460                 ccb->casync.async_arg_ptr = malloc(size, M_CAMXPT, M_NOWAIT);
4461                 if (ccb->casync.async_arg_ptr == NULL) {
4462                         xpt_print(path, "Can't allocate argument to send %s\n",
4463                             xpt_async_string(async_code));
4464                         xpt_free_path(ccb->ccb_h.path);
4465                         xpt_free_ccb(ccb);
4466                         return;
4467                 }
4468                 memcpy(ccb->casync.async_arg_ptr, async_arg, size);
4469                 ccb->casync.async_arg_size = size;
4470         } else if (size < 0) {
4471                 ccb->casync.async_arg_ptr = async_arg;
4472                 ccb->casync.async_arg_size = size;
4473         }
4474         if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4475                 xpt_freeze_devq(path, 1);
4476         else
4477                 xpt_freeze_simq(path->bus->sim, 1);
4478         xpt_done(ccb);
4479 }
4480
4481 static void
4482 xpt_dev_async_default(u_int32_t async_code, struct cam_eb *bus,
4483                       struct cam_et *target, struct cam_ed *device,
4484                       void *async_arg)
4485 {
4486
4487         /*
4488          * We only need to handle events for real devices.
4489          */
4490         if (target->target_id == CAM_TARGET_WILDCARD
4491          || device->lun_id == CAM_LUN_WILDCARD)
4492                 return;
4493
4494         printf("%s called\n", __func__);
4495 }
4496
4497 static uint32_t
4498 xpt_freeze_devq_device(struct cam_ed *dev, u_int count)
4499 {
4500         struct cam_devq *devq;
4501         uint32_t freeze;
4502
4503         devq = dev->sim->devq;
4504         mtx_assert(&devq->send_mtx, MA_OWNED);
4505         CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4506             ("xpt_freeze_devq_device(%d) %u->%u\n", count,
4507             dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt + count));
4508         freeze = (dev->ccbq.queue.qfrozen_cnt += count);
4509         /* Remove frozen device from sendq. */
4510         if (device_is_queued(dev))
4511                 camq_remove(&devq->send_queue, dev->devq_entry.index);
4512         return (freeze);
4513 }
4514
4515 u_int32_t
4516 xpt_freeze_devq(struct cam_path *path, u_int count)
4517 {
4518         struct cam_ed   *dev = path->device;
4519         struct cam_devq *devq;
4520         uint32_t         freeze;
4521
4522         devq = dev->sim->devq;
4523         mtx_lock(&devq->send_mtx);
4524         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_freeze_devq(%d)\n", count));
4525         freeze = xpt_freeze_devq_device(dev, count);
4526         mtx_unlock(&devq->send_mtx);
4527         return (freeze);
4528 }
4529
4530 u_int32_t
4531 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4532 {
4533         struct cam_devq *devq;
4534         uint32_t         freeze;
4535
4536         devq = sim->devq;
4537         mtx_lock(&devq->send_mtx);
4538         freeze = (devq->send_queue.qfrozen_cnt += count);
4539         mtx_unlock(&devq->send_mtx);
4540         return (freeze);
4541 }
4542
4543 static void
4544 xpt_release_devq_timeout(void *arg)
4545 {
4546         struct cam_ed *dev;
4547         struct cam_devq *devq;
4548
4549         dev = (struct cam_ed *)arg;
4550         CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE, ("xpt_release_devq_timeout\n"));
4551         devq = dev->sim->devq;
4552         mtx_assert(&devq->send_mtx, MA_OWNED);
4553         if (xpt_release_devq_device(dev, /*count*/1, /*run_queue*/TRUE))
4554                 xpt_run_devq(devq);
4555 }
4556
4557 void
4558 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4559 {
4560         struct cam_ed *dev;
4561         struct cam_devq *devq;
4562
4563         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_devq(%d, %d)\n",
4564             count, run_queue));
4565         dev = path->device;
4566         devq = dev->sim->devq;
4567         mtx_lock(&devq->send_mtx);
4568         if (xpt_release_devq_device(dev, count, run_queue))
4569                 xpt_run_devq(dev->sim->devq);
4570         mtx_unlock(&devq->send_mtx);
4571 }
4572
4573 static int
4574 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4575 {
4576
4577         mtx_assert(&dev->sim->devq->send_mtx, MA_OWNED);
4578         CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4579             ("xpt_release_devq_device(%d, %d) %u->%u\n", count, run_queue,
4580             dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt - count));
4581         if (count > dev->ccbq.queue.qfrozen_cnt) {
4582 #ifdef INVARIANTS
4583                 printf("xpt_release_devq(): requested %u > present %u\n",
4584                     count, dev->ccbq.queue.qfrozen_cnt);
4585 #endif
4586                 count = dev->ccbq.queue.qfrozen_cnt;
4587         }
4588         dev->ccbq.queue.qfrozen_cnt -= count;
4589         if (dev->ccbq.queue.qfrozen_cnt == 0) {
4590                 /*
4591                  * No longer need to wait for a successful
4592                  * command completion.
4593                  */
4594                 dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4595                 /*
4596                  * Remove any timeouts that might be scheduled
4597                  * to release this queue.
4598                  */
4599                 if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4600                         callout_stop(&dev->callout);
4601                         dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4602                 }
4603                 /*
4604                  * Now that we are unfrozen schedule the
4605                  * device so any pending transactions are
4606                  * run.
4607                  */
4608                 xpt_schedule_devq(dev->sim->devq, dev);
4609         } else
4610                 run_queue = 0;
4611         return (run_queue);
4612 }
4613
4614 void
4615 xpt_release_simq(struct cam_sim *sim, int run_queue)
4616 {
4617         struct cam_devq *devq;
4618
4619         devq = sim->devq;
4620         mtx_lock(&devq->send_mtx);
4621         if (devq->send_queue.qfrozen_cnt <= 0) {
4622 #ifdef INVARIANTS
4623                 printf("xpt_release_simq: requested 1 > present %u\n",
4624                     devq->send_queue.qfrozen_cnt);
4625 #endif
4626         } else
4627                 devq->send_queue.qfrozen_cnt--;
4628         if (devq->send_queue.qfrozen_cnt == 0) {
4629                 /*
4630                  * If there is a timeout scheduled to release this
4631                  * sim queue, remove it.  The queue frozen count is
4632                  * already at 0.
4633                  */
4634                 if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4635                         callout_stop(&sim->callout);
4636                         sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4637                 }
4638                 if (run_queue) {
4639                         /*
4640                          * Now that we are unfrozen run the send queue.
4641                          */
4642                         xpt_run_devq(sim->devq);
4643                 }
4644         }
4645         mtx_unlock(&devq->send_mtx);
4646 }
4647
4648 /*
4649  * XXX Appears to be unused.
4650  */
4651 static void
4652 xpt_release_simq_timeout(void *arg)
4653 {
4654         struct cam_sim *sim;
4655
4656         sim = (struct cam_sim *)arg;
4657         xpt_release_simq(sim, /* run_queue */ TRUE);
4658 }
4659
4660 void
4661 xpt_done(union ccb *done_ccb)
4662 {
4663         struct cam_doneq *queue;
4664         int     run, hash;
4665
4666 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4667         if (done_ccb->ccb_h.func_code == XPT_SCSI_IO &&
4668             done_ccb->csio.bio != NULL)
4669                 biotrack(done_ccb->csio.bio, __func__);
4670 #endif
4671
4672         CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4673             ("xpt_done: func= %#x %s status %#x\n",
4674                 done_ccb->ccb_h.func_code,
4675                 xpt_action_name(done_ccb->ccb_h.func_code),
4676                 done_ccb->ccb_h.status));
4677         if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4678                 return;
4679
4680         /* Store the time the ccb was in the sim */
4681         done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
4682         hash = (done_ccb->ccb_h.path_id + done_ccb->ccb_h.target_id +
4683             done_ccb->ccb_h.target_lun) % cam_num_doneqs;
4684         queue = &cam_doneqs[hash];
4685         mtx_lock(&queue->cam_doneq_mtx);
4686         run = (queue->cam_doneq_sleep && STAILQ_EMPTY(&queue->cam_doneq));
4687         STAILQ_INSERT_TAIL(&queue->cam_doneq, &done_ccb->ccb_h, sim_links.stqe);
4688         done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4689         mtx_unlock(&queue->cam_doneq_mtx);
4690         if (run)
4691                 wakeup(&queue->cam_doneq);
4692 }
4693
4694 void
4695 xpt_done_direct(union ccb *done_ccb)
4696 {
4697
4698         CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4699             ("xpt_done_direct: status %#x\n", done_ccb->ccb_h.status));
4700         if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4701                 return;
4702
4703         /* Store the time the ccb was in the sim */
4704         done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
4705         xpt_done_process(&done_ccb->ccb_h);
4706 }
4707
4708 union ccb *
4709 xpt_alloc_ccb()
4710 {
4711         union ccb *new_ccb;
4712
4713         new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4714         return (new_ccb);
4715 }
4716
4717 union ccb *
4718 xpt_alloc_ccb_nowait()
4719 {
4720         union ccb *new_ccb;
4721
4722         new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4723         return (new_ccb);
4724 }
4725
4726 void
4727 xpt_free_ccb(union ccb *free_ccb)
4728 {
4729         free(free_ccb, M_CAMCCB);
4730 }
4731
4732
4733
4734 /* Private XPT functions */
4735
4736 /*
4737  * Get a CAM control block for the caller. Charge the structure to the device
4738  * referenced by the path.  If we don't have sufficient resources to allocate
4739  * more ccbs, we return NULL.
4740  */
4741 static union ccb *
4742 xpt_get_ccb_nowait(struct cam_periph *periph)
4743 {
4744         union ccb *new_ccb;
4745
4746         new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4747         if (new_ccb == NULL)
4748                 return (NULL);
4749         periph->periph_allocated++;
4750         cam_ccbq_take_opening(&periph->path->device->ccbq);
4751         return (new_ccb);
4752 }
4753
4754 static union ccb *
4755 xpt_get_ccb(struct cam_periph *periph)
4756 {
4757         union ccb *new_ccb;
4758
4759         cam_periph_unlock(periph);
4760         new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4761         cam_periph_lock(periph);
4762         periph->periph_allocated++;
4763         cam_ccbq_take_opening(&periph->path->device->ccbq);
4764         return (new_ccb);
4765 }
4766
4767 union ccb *
4768 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
4769 {
4770         struct ccb_hdr *ccb_h;
4771
4772         CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("cam_periph_getccb\n"));
4773         cam_periph_assert(periph, MA_OWNED);
4774         while ((ccb_h = SLIST_FIRST(&periph->ccb_list)) == NULL ||
4775             ccb_h->pinfo.priority != priority) {
4776                 if (priority < periph->immediate_priority) {
4777                         periph->immediate_priority = priority;
4778                         xpt_run_allocq(periph, 0);
4779                 } else
4780                         cam_periph_sleep(periph, &periph->ccb_list, PRIBIO,
4781                             "cgticb", 0);
4782         }
4783         SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
4784         return ((union ccb *)ccb_h);
4785 }
4786
4787 static void
4788 xpt_acquire_bus(struct cam_eb *bus)
4789 {
4790
4791         xpt_lock_buses();
4792         bus->refcount++;
4793         xpt_unlock_buses();
4794 }
4795
4796 static void
4797 xpt_release_bus(struct cam_eb *bus)
4798 {
4799
4800         xpt_lock_buses();
4801         KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
4802         if (--bus->refcount > 0) {
4803                 xpt_unlock_buses();
4804                 return;
4805         }
4806         TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4807         xsoftc.bus_generation++;
4808         xpt_unlock_buses();
4809         KASSERT(TAILQ_EMPTY(&bus->et_entries),
4810             ("destroying bus, but target list is not empty"));
4811         cam_sim_release(bus->sim);
4812         mtx_destroy(&bus->eb_mtx);
4813         free(bus, M_CAMXPT);
4814 }
4815
4816 static struct cam_et *
4817 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4818 {
4819         struct cam_et *cur_target, *target;
4820
4821         mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4822         mtx_assert(&bus->eb_mtx, MA_OWNED);
4823         target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
4824                                          M_NOWAIT|M_ZERO);
4825         if (target == NULL)
4826                 return (NULL);
4827
4828         TAILQ_INIT(&target->ed_entries);
4829         target->bus = bus;
4830         target->target_id = target_id;
4831         target->refcount = 1;
4832         target->generation = 0;
4833         target->luns = NULL;
4834         mtx_init(&target->luns_mtx, "CAM LUNs lock", NULL, MTX_DEF);
4835         timevalclear(&target->last_reset);
4836         /*
4837          * Hold a reference to our parent bus so it
4838          * will not go away before we do.
4839          */
4840         bus->refcount++;
4841
4842         /* Insertion sort into our bus's target list */
4843         cur_target = TAILQ_FIRST(&bus->et_entries);
4844         while (cur_target != NULL && cur_target->target_id < target_id)
4845                 cur_target = TAILQ_NEXT(cur_target, links);
4846         if (cur_target != NULL) {
4847                 TAILQ_INSERT_BEFORE(cur_target, target, links);
4848         } else {
4849                 TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4850         }
4851         bus->generation++;
4852         return (target);
4853 }
4854
4855 static void
4856 xpt_acquire_target(struct cam_et *target)
4857 {
4858         struct cam_eb *bus = target->bus;
4859
4860         mtx_lock(&bus->eb_mtx);
4861         target->refcount++;
4862         mtx_unlock(&bus->eb_mtx);
4863 }
4864
4865 static void
4866 xpt_release_target(struct cam_et *target)
4867 {
4868         struct cam_eb *bus = target->bus;
4869
4870         mtx_lock(&bus->eb_mtx);
4871         if (--target->refcount > 0) {
4872                 mtx_unlock(&bus->eb_mtx);
4873                 return;
4874         }
4875         TAILQ_REMOVE(&bus->et_entries, target, links);
4876         bus->generation++;
4877         mtx_unlock(&bus->eb_mtx);
4878         KASSERT(TAILQ_EMPTY(&target->ed_entries),
4879             ("destroying target, but device list is not empty"));
4880         xpt_release_bus(bus);
4881         mtx_destroy(&target->luns_mtx);
4882         if (target->luns)
4883                 free(target->luns, M_CAMXPT);
4884         free(target, M_CAMXPT);
4885 }
4886
4887 static struct cam_ed *
4888 xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
4889                          lun_id_t lun_id)
4890 {
4891         struct cam_ed *device;
4892
4893         device = xpt_alloc_device(bus, target, lun_id);
4894         if (device == NULL)
4895                 return (NULL);
4896
4897         device->mintags = 1;
4898         device->maxtags = 1;
4899         return (device);
4900 }
4901
4902 static void
4903 xpt_destroy_device(void *context, int pending)
4904 {
4905         struct cam_ed   *device = context;
4906
4907         mtx_lock(&device->device_mtx);
4908         mtx_destroy(&device->device_mtx);
4909         free(device, M_CAMDEV);
4910 }
4911
4912 struct cam_ed *
4913 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4914 {
4915         struct cam_ed   *cur_device, *device;
4916         struct cam_devq *devq;
4917         cam_status status;
4918
4919         mtx_assert(&bus->eb_mtx, MA_OWNED);
4920         /* Make space for us in the device queue on our bus */
4921         devq = bus->sim->devq;
4922         mtx_lock(&devq->send_mtx);
4923         status = cam_devq_resize(devq, devq->send_queue.array_size + 1);
4924         mtx_unlock(&devq->send_mtx);
4925         if (status != CAM_REQ_CMP)
4926                 return (NULL);
4927
4928         device = (struct cam_ed *)malloc(sizeof(*device),
4929                                          M_CAMDEV, M_NOWAIT|M_ZERO);
4930         if (device == NULL)
4931                 return (NULL);
4932
4933         cam_init_pinfo(&device->devq_entry);
4934         device->target = target;
4935         device->lun_id = lun_id;
4936         device->sim = bus->sim;
4937         if (cam_ccbq_init(&device->ccbq,
4938                           bus->sim->max_dev_openings) != 0) {
4939                 free(device, M_CAMDEV);
4940                 return (NULL);
4941         }
4942         SLIST_INIT(&device->asyncs);
4943         SLIST_INIT(&device->periphs);
4944         device->generation = 0;
4945         device->flags = CAM_DEV_UNCONFIGURED;
4946         device->tag_delay_count = 0;
4947         device->tag_saved_openings = 0;
4948         device->refcount = 1;
4949         mtx_init(&device->device_mtx, "CAM device lock", NULL, MTX_DEF);
4950         callout_init_mtx(&device->callout, &devq->send_mtx, 0);
4951         TASK_INIT(&device->device_destroy_task, 0, xpt_destroy_device, device);
4952         /*
4953          * Hold a reference to our parent bus so it
4954          * will not go away before we do.
4955          */
4956         target->refcount++;
4957
4958         cur_device = TAILQ_FIRST(&target->ed_entries);
4959         while (cur_device != NULL && cur_device->lun_id < lun_id)
4960                 cur_device = TAILQ_NEXT(cur_device, links);
4961         if (cur_device != NULL)
4962                 TAILQ_INSERT_BEFORE(cur_device, device, links);
4963         else
4964                 TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4965         target->generation++;
4966         return (device);
4967 }
4968
4969 void
4970 xpt_acquire_device(struct cam_ed *device)
4971 {
4972         struct cam_eb *bus = device->target->bus;
4973
4974         mtx_lock(&bus->eb_mtx);
4975         device->refcount++;
4976         mtx_unlock(&bus->eb_mtx);
4977 }
4978
4979 void
4980 xpt_release_device(struct cam_ed *device)
4981 {
4982         struct cam_eb *bus = device->target->bus;
4983         struct cam_devq *devq;
4984
4985         mtx_lock(&bus->eb_mtx);
4986         if (--device->refcount > 0) {
4987                 mtx_unlock(&bus->eb_mtx);
4988                 return;
4989         }
4990
4991         TAILQ_REMOVE(&device->target->ed_entries, device,links);
4992         device->target->generation++;
4993         mtx_unlock(&bus->eb_mtx);
4994
4995         /* Release our slot in the devq */
4996         devq = bus->sim->devq;
4997         mtx_lock(&devq->send_mtx);
4998         cam_devq_resize(devq, devq->send_queue.array_size - 1);
4999         mtx_unlock(&devq->send_mtx);
5000
5001         KASSERT(SLIST_EMPTY(&device->periphs),
5002             ("destroying device, but periphs list is not empty"));
5003         KASSERT(device->devq_entry.index == CAM_UNQUEUED_INDEX,
5004             ("destroying device while still queued for ccbs"));
5005
5006         if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
5007                 callout_stop(&device->callout);
5008
5009         xpt_release_target(device->target);
5010
5011         cam_ccbq_fini(&device->ccbq);
5012         /*
5013          * Free allocated memory.  free(9) does nothing if the
5014          * supplied pointer is NULL, so it is safe to call without
5015          * checking.
5016          */
5017         free(device->supported_vpds, M_CAMXPT);
5018         free(device->device_id, M_CAMXPT);
5019         free(device->ext_inq, M_CAMXPT);
5020         free(device->physpath, M_CAMXPT);
5021         free(device->rcap_buf, M_CAMXPT);
5022         free(device->serial_num, M_CAMXPT);
5023         free(device->nvme_data, M_CAMXPT);
5024         free(device->nvme_cdata, M_CAMXPT);
5025         taskqueue_enqueue(xsoftc.xpt_taskq, &device->device_destroy_task);
5026 }
5027
5028 u_int32_t
5029 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
5030 {
5031         int     result;
5032         struct  cam_ed *dev;
5033
5034         dev = path->device;
5035         mtx_lock(&dev->sim->devq->send_mtx);
5036         result = cam_ccbq_resize(&dev->ccbq, newopenings);
5037         mtx_unlock(&dev->sim->devq->send_mtx);
5038         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5039          || (dev->inq_flags & SID_CmdQue) != 0)
5040                 dev->tag_saved_openings = newopenings;
5041         return (result);
5042 }
5043
5044 static struct cam_eb *
5045 xpt_find_bus(path_id_t path_id)
5046 {
5047         struct cam_eb *bus;
5048
5049         xpt_lock_buses();
5050         for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
5051              bus != NULL;
5052              bus = TAILQ_NEXT(bus, links)) {
5053                 if (bus->path_id == path_id) {
5054                         bus->refcount++;
5055                         break;
5056                 }
5057         }
5058         xpt_unlock_buses();
5059         return (bus);
5060 }
5061
5062 static struct cam_et *
5063 xpt_find_target(struct cam_eb *bus, target_id_t target_id)
5064 {
5065         struct cam_et *target;
5066
5067         mtx_assert(&bus->eb_mtx, MA_OWNED);
5068         for (target = TAILQ_FIRST(&bus->et_entries);
5069              target != NULL;
5070              target = TAILQ_NEXT(target, links)) {
5071                 if (target->target_id == target_id) {
5072                         target->refcount++;
5073                         break;
5074                 }
5075         }
5076         return (target);
5077 }
5078
5079 static struct cam_ed *
5080 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
5081 {
5082         struct cam_ed *device;
5083
5084         mtx_assert(&target->bus->eb_mtx, MA_OWNED);
5085         for (device = TAILQ_FIRST(&target->ed_entries);
5086              device != NULL;
5087              device = TAILQ_NEXT(device, links)) {
5088                 if (device->lun_id == lun_id) {
5089                         device->refcount++;
5090                         break;
5091                 }
5092         }
5093         return (device);
5094 }
5095
5096 void
5097 xpt_start_tags(struct cam_path *path)
5098 {
5099         struct ccb_relsim crs;
5100         struct cam_ed *device;
5101         struct cam_sim *sim;
5102         int    newopenings;
5103
5104         device = path->device;
5105         sim = path->bus->sim;
5106         device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
5107         xpt_freeze_devq(path, /*count*/1);
5108         device->inq_flags |= SID_CmdQue;
5109         if (device->tag_saved_openings != 0)
5110                 newopenings = device->tag_saved_openings;
5111         else
5112                 newopenings = min(device->maxtags,
5113                                   sim->max_tagged_dev_openings);
5114         xpt_dev_ccbq_resize(path, newopenings);
5115         xpt_async(AC_GETDEV_CHANGED, path, NULL);
5116         xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
5117         crs.ccb_h.func_code = XPT_REL_SIMQ;
5118         crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
5119         crs.openings
5120             = crs.release_timeout
5121             = crs.qfrozen_cnt
5122             = 0;
5123         xpt_action((union ccb *)&crs);
5124 }
5125
5126 void
5127 xpt_stop_tags(struct cam_path *path)
5128 {
5129         struct ccb_relsim crs;
5130         struct cam_ed *device;
5131         struct cam_sim *sim;
5132
5133         device = path->device;
5134         sim = path->bus->sim;
5135         device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
5136         device->tag_delay_count = 0;
5137         xpt_freeze_devq(path, /*count*/1);
5138         device->inq_flags &= ~SID_CmdQue;
5139         xpt_dev_ccbq_resize(path, sim->max_dev_openings);
5140         xpt_async(AC_GETDEV_CHANGED, path, NULL);
5141         xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
5142         crs.ccb_h.func_code = XPT_REL_SIMQ;
5143         crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
5144         crs.openings
5145             = crs.release_timeout
5146             = crs.qfrozen_cnt
5147             = 0;
5148         xpt_action((union ccb *)&crs);
5149 }
5150
5151 static void
5152 xpt_boot_delay(void *arg)
5153 {
5154
5155         xpt_release_boot();
5156 }
5157
5158 static void
5159 xpt_config(void *arg)
5160 {
5161         /*
5162          * Now that interrupts are enabled, go find our devices
5163          */
5164         if (taskqueue_start_threads(&xsoftc.xpt_taskq, 1, PRIBIO, "CAM taskq"))
5165                 printf("xpt_config: failed to create taskqueue thread.\n");
5166
5167         /* Setup debugging path */
5168         if (cam_dflags != CAM_DEBUG_NONE) {
5169                 if (xpt_create_path(&cam_dpath, NULL,
5170                                     CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
5171                                     CAM_DEBUG_LUN) != CAM_REQ_CMP) {
5172                         printf("xpt_config: xpt_create_path() failed for debug"
5173                                " target %d:%d:%d, debugging disabled\n",
5174                                CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
5175                         cam_dflags = CAM_DEBUG_NONE;
5176                 }
5177         } else
5178                 cam_dpath = NULL;
5179
5180         periphdriver_init(1);
5181         xpt_hold_boot();
5182         callout_init(&xsoftc.boot_callout, 1);
5183         callout_reset_sbt(&xsoftc.boot_callout, SBT_1MS * xsoftc.boot_delay, 0,
5184             xpt_boot_delay, NULL, 0);
5185         /* Fire up rescan thread. */
5186         if (kproc_kthread_add(xpt_scanner_thread, NULL, &cam_proc, NULL, 0, 0,
5187             "cam", "scanner")) {
5188                 printf("xpt_config: failed to create rescan thread.\n");
5189         }
5190 }
5191
5192 void
5193 xpt_hold_boot(void)
5194 {
5195         xpt_lock_buses();
5196         xsoftc.buses_to_config++;
5197         xpt_unlock_buses();
5198 }
5199
5200 void
5201 xpt_release_boot(void)
5202 {
5203         xpt_lock_buses();
5204         xsoftc.buses_to_config--;
5205         if (xsoftc.buses_to_config == 0 && xsoftc.buses_config_done == 0) {
5206                 struct  xpt_task *task;
5207
5208                 xsoftc.buses_config_done = 1;
5209                 xpt_unlock_buses();
5210                 /* Call manually because we don't have any buses */
5211                 task = malloc(sizeof(struct xpt_task), M_CAMXPT, M_NOWAIT);
5212                 if (task != NULL) {
5213                         TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
5214                         taskqueue_enqueue(taskqueue_thread, &task->task);
5215                 }
5216         } else
5217                 xpt_unlock_buses();
5218 }
5219
5220 /*
5221  * If the given device only has one peripheral attached to it, and if that
5222  * peripheral is the passthrough driver, announce it.  This insures that the
5223  * user sees some sort of announcement for every peripheral in their system.
5224  */
5225 static int
5226 xptpassannouncefunc(struct cam_ed *device, void *arg)
5227 {
5228         struct cam_periph *periph;
5229         int i;
5230
5231         for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
5232              periph = SLIST_NEXT(periph, periph_links), i++);
5233
5234         periph = SLIST_FIRST(&device->periphs);
5235         if ((i == 1)
5236          && (strncmp(periph->periph_name, "pass", 4) == 0))
5237                 xpt_announce_periph(periph, NULL);
5238
5239         return(1);
5240 }
5241
5242 static void
5243 xpt_finishconfig_task(void *context, int pending)
5244 {
5245
5246         periphdriver_init(2);
5247         /*
5248          * Check for devices with no "standard" peripheral driver
5249          * attached.  For any devices like that, announce the
5250          * passthrough driver so the user will see something.
5251          */
5252         if (!bootverbose)
5253                 xpt_for_all_devices(xptpassannouncefunc, NULL);
5254
5255         /* Release our hook so that the boot can continue. */
5256         config_intrhook_disestablish(&xsoftc.xpt_config_hook);
5257
5258         free(context, M_CAMXPT);
5259 }
5260
5261 cam_status
5262 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
5263                    struct cam_path *path)
5264 {
5265         struct ccb_setasync csa;
5266         cam_status status;
5267         int xptpath = 0;
5268
5269         if (path == NULL) {
5270                 status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
5271                                          CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
5272                 if (status != CAM_REQ_CMP)
5273                         return (status);
5274                 xpt_path_lock(path);
5275                 xptpath = 1;
5276         }
5277
5278         xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
5279         csa.ccb_h.func_code = XPT_SASYNC_CB;
5280         csa.event_enable = event;
5281         csa.callback = cbfunc;
5282         csa.callback_arg = cbarg;
5283         xpt_action((union ccb *)&csa);
5284         status = csa.ccb_h.status;
5285
5286         CAM_DEBUG(csa.ccb_h.path, CAM_DEBUG_TRACE,
5287             ("xpt_register_async: func %p\n", cbfunc));
5288
5289         if (xptpath) {
5290                 xpt_path_unlock(path);
5291                 xpt_free_path(path);
5292         }
5293
5294         if ((status == CAM_REQ_CMP) &&
5295             (csa.event_enable & AC_FOUND_DEVICE)) {
5296                 /*
5297                  * Get this peripheral up to date with all
5298                  * the currently existing devices.
5299                  */
5300                 xpt_for_all_devices(xptsetasyncfunc, &csa);
5301         }
5302         if ((status == CAM_REQ_CMP) &&
5303             (csa.event_enable & AC_PATH_REGISTERED)) {
5304                 /*
5305                  * Get this peripheral up to date with all
5306                  * the currently existing buses.
5307                  */
5308                 xpt_for_all_busses(xptsetasyncbusfunc, &csa);
5309         }
5310
5311         return (status);
5312 }
5313
5314 static void
5315 xptaction(struct cam_sim *sim, union ccb *work_ccb)
5316 {
5317         CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
5318
5319         switch (work_ccb->ccb_h.func_code) {
5320         /* Common cases first */
5321         case XPT_PATH_INQ:              /* Path routing inquiry */
5322         {
5323                 struct ccb_pathinq *cpi;
5324
5325                 cpi = &work_ccb->cpi;
5326                 cpi->version_num = 1; /* XXX??? */
5327                 cpi->hba_inquiry = 0;
5328                 cpi->target_sprt = 0;
5329                 cpi->hba_misc = 0;
5330                 cpi->hba_eng_cnt = 0;
5331                 cpi->max_target = 0;
5332                 cpi->max_lun = 0;
5333                 cpi->initiator_id = 0;
5334                 strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
5335                 strlcpy(cpi->hba_vid, "", HBA_IDLEN);
5336                 strlcpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
5337                 cpi->unit_number = sim->unit_number;
5338                 cpi->bus_id = sim->bus_id;
5339                 cpi->base_transfer_speed = 0;
5340                 cpi->protocol = PROTO_UNSPECIFIED;
5341                 cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
5342                 cpi->transport = XPORT_UNSPECIFIED;
5343                 cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
5344                 cpi->ccb_h.status = CAM_REQ_CMP;
5345                 xpt_done(work_ccb);
5346                 break;
5347         }
5348         default:
5349                 work_ccb->ccb_h.status = CAM_REQ_INVALID;
5350                 xpt_done(work_ccb);
5351                 break;
5352         }
5353 }
5354
5355 /*
5356  * The xpt as a "controller" has no interrupt sources, so polling
5357  * is a no-op.
5358  */
5359 static void
5360 xptpoll(struct cam_sim *sim)
5361 {
5362 }
5363
5364 void
5365 xpt_lock_buses(void)
5366 {
5367         mtx_lock(&xsoftc.xpt_topo_lock);
5368 }
5369
5370 void
5371 xpt_unlock_buses(void)
5372 {
5373         mtx_unlock(&xsoftc.xpt_topo_lock);
5374 }
5375
5376 struct mtx *
5377 xpt_path_mtx(struct cam_path *path)
5378 {
5379
5380         return (&path->device->device_mtx);
5381 }
5382
5383 static void
5384 xpt_done_process(struct ccb_hdr *ccb_h)
5385 {
5386         struct cam_sim *sim = NULL;
5387         struct cam_devq *devq = NULL;
5388         struct mtx *mtx = NULL;
5389
5390 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
5391         struct ccb_scsiio *csio;
5392
5393         if (ccb_h->func_code == XPT_SCSI_IO) {
5394                 csio = &((union ccb *)ccb_h)->csio;
5395                 if (csio->bio != NULL)
5396                         biotrack(csio->bio, __func__);
5397         }
5398 #endif
5399
5400         if (ccb_h->flags & CAM_HIGH_POWER) {
5401                 struct highpowerlist    *hphead;
5402                 struct cam_ed           *device;
5403
5404                 mtx_lock(&xsoftc.xpt_highpower_lock);
5405                 hphead = &xsoftc.highpowerq;
5406
5407                 device = STAILQ_FIRST(hphead);
5408
5409                 /*
5410                  * Increment the count since this command is done.
5411                  */
5412                 xsoftc.num_highpower++;
5413
5414                 /*
5415                  * Any high powered commands queued up?
5416                  */
5417                 if (device != NULL) {
5418
5419                         STAILQ_REMOVE_HEAD(hphead, highpowerq_entry);
5420                         mtx_unlock(&xsoftc.xpt_highpower_lock);
5421
5422                         mtx_lock(&device->sim->devq->send_mtx);
5423                         xpt_release_devq_device(device,
5424                                          /*count*/1, /*runqueue*/TRUE);
5425                         mtx_unlock(&device->sim->devq->send_mtx);
5426                 } else
5427                         mtx_unlock(&xsoftc.xpt_highpower_lock);
5428         }
5429
5430         /*
5431          * Insulate against a race where the periph is destroyed but CCBs are
5432          * still not all processed. This shouldn't happen, but allows us better
5433          * bug diagnostic when it does.
5434          */
5435         if (ccb_h->path->bus)
5436                 sim = ccb_h->path->bus->sim;
5437
5438         if (ccb_h->status & CAM_RELEASE_SIMQ) {
5439                 KASSERT(sim, ("sim missing for CAM_RELEASE_SIMQ request"));
5440                 xpt_release_simq(sim, /*run_queue*/FALSE);
5441                 ccb_h->status &= ~CAM_RELEASE_SIMQ;
5442         }
5443
5444         if ((ccb_h->flags & CAM_DEV_QFRZDIS)
5445          && (ccb_h->status & CAM_DEV_QFRZN)) {
5446                 xpt_release_devq(ccb_h->path, /*count*/1, /*run_queue*/TRUE);
5447                 ccb_h->status &= ~CAM_DEV_QFRZN;
5448         }
5449
5450         if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
5451                 struct cam_ed *dev = ccb_h->path->device;
5452
5453                 if (sim)
5454                         devq = sim->devq;
5455                 KASSERT(devq, ("Periph disappeared with request pending."));
5456
5457                 mtx_lock(&devq->send_mtx);
5458                 devq->send_active--;
5459                 devq->send_openings++;
5460                 cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
5461
5462                 if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
5463                   && (dev->ccbq.dev_active == 0))) {
5464                         dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
5465                         xpt_release_devq_device(dev, /*count*/1,
5466                                          /*run_queue*/FALSE);
5467                 }
5468
5469                 if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
5470                   && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
5471                         dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
5472                         xpt_release_devq_device(dev, /*count*/1,
5473                                          /*run_queue*/FALSE);
5474                 }
5475
5476                 if (!device_is_queued(dev))
5477                         (void)xpt_schedule_devq(devq, dev);
5478                 xpt_run_devq(devq);
5479                 mtx_unlock(&devq->send_mtx);
5480
5481                 if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0) {
5482                         mtx = xpt_path_mtx(ccb_h->path);
5483                         mtx_lock(mtx);
5484
5485                         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5486                          && (--dev->tag_delay_count == 0))
5487                                 xpt_start_tags(ccb_h->path);
5488                 }
5489         }
5490
5491         if ((ccb_h->flags & CAM_UNLOCKED) == 0) {
5492                 if (mtx == NULL) {
5493                         mtx = xpt_path_mtx(ccb_h->path);
5494                         mtx_lock(mtx);
5495                 }
5496         } else {
5497                 if (mtx != NULL) {
5498                         mtx_unlock(mtx);
5499                         mtx = NULL;
5500                 }
5501         }
5502
5503         /* Call the peripheral driver's callback */
5504         ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
5505         (*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
5506         if (mtx != NULL)
5507                 mtx_unlock(mtx);
5508 }
5509
5510 void
5511 xpt_done_td(void *arg)
5512 {
5513         struct cam_doneq *queue = arg;
5514         struct ccb_hdr *ccb_h;
5515         STAILQ_HEAD(, ccb_hdr)  doneq;
5516
5517         STAILQ_INIT(&doneq);
5518         mtx_lock(&queue->cam_doneq_mtx);
5519         while (1) {
5520                 while (STAILQ_EMPTY(&queue->cam_doneq)) {
5521                         queue->cam_doneq_sleep = 1;
5522                         msleep(&queue->cam_doneq, &queue->cam_doneq_mtx,
5523                             PRIBIO, "-", 0);
5524                         queue->cam_doneq_sleep = 0;
5525                 }
5526                 STAILQ_CONCAT(&doneq, &queue->cam_doneq);
5527                 mtx_unlock(&queue->cam_doneq_mtx);
5528
5529                 THREAD_NO_SLEEPING();
5530                 while ((ccb_h = STAILQ_FIRST(&doneq)) != NULL) {
5531                         STAILQ_REMOVE_HEAD(&doneq, sim_links.stqe);
5532                         xpt_done_process(ccb_h);
5533                 }
5534                 THREAD_SLEEPING_OK();
5535
5536                 mtx_lock(&queue->cam_doneq_mtx);
5537         }
5538 }
5539
5540 static void
5541 camisr_runqueue(void)
5542 {
5543         struct  ccb_hdr *ccb_h;
5544         struct cam_doneq *queue;
5545         int i;
5546
5547         /* Process global queues. */
5548         for (i = 0; i < cam_num_doneqs; i++) {
5549                 queue = &cam_doneqs[i];
5550                 mtx_lock(&queue->cam_doneq_mtx);
5551                 while ((ccb_h = STAILQ_FIRST(&queue->cam_doneq)) != NULL) {
5552                         STAILQ_REMOVE_HEAD(&queue->cam_doneq, sim_links.stqe);
5553                         mtx_unlock(&queue->cam_doneq_mtx);
5554                         xpt_done_process(ccb_h);
5555                         mtx_lock(&queue->cam_doneq_mtx);
5556                 }
5557                 mtx_unlock(&queue->cam_doneq_mtx);
5558         }
5559 }
5560
5561 struct kv 
5562 {
5563         uint32_t v;
5564         const char *name;
5565 };
5566
5567 static struct kv map[] = {
5568         { XPT_NOOP, "XPT_NOOP" },
5569         { XPT_SCSI_IO, "XPT_SCSI_IO" },
5570         { XPT_GDEV_TYPE, "XPT_GDEV_TYPE" },
5571         { XPT_GDEVLIST, "XPT_GDEVLIST" },
5572         { XPT_PATH_INQ, "XPT_PATH_INQ" },
5573         { XPT_REL_SIMQ, "XPT_REL_SIMQ" },
5574         { XPT_SASYNC_CB, "XPT_SASYNC_CB" },
5575         { XPT_SDEV_TYPE, "XPT_SDEV_TYPE" },
5576         { XPT_SCAN_BUS, "XPT_SCAN_BUS" },
5577         { XPT_DEV_MATCH, "XPT_DEV_MATCH" },
5578         { XPT_DEBUG, "XPT_DEBUG" },
5579         { XPT_PATH_STATS, "XPT_PATH_STATS" },
5580         { XPT_GDEV_STATS, "XPT_GDEV_STATS" },
5581         { XPT_DEV_ADVINFO, "XPT_DEV_ADVINFO" },
5582         { XPT_ASYNC, "XPT_ASYNC" },
5583         { XPT_ABORT, "XPT_ABORT" },
5584         { XPT_RESET_BUS, "XPT_RESET_BUS" },
5585         { XPT_RESET_DEV, "XPT_RESET_DEV" },
5586         { XPT_TERM_IO, "XPT_TERM_IO" },
5587         { XPT_SCAN_LUN, "XPT_SCAN_LUN" },
5588         { XPT_GET_TRAN_SETTINGS, "XPT_GET_TRAN_SETTINGS" },
5589         { XPT_SET_TRAN_SETTINGS, "XPT_SET_TRAN_SETTINGS" },
5590         { XPT_CALC_GEOMETRY, "XPT_CALC_GEOMETRY" },
5591         { XPT_ATA_IO, "XPT_ATA_IO" },
5592         { XPT_GET_SIM_KNOB, "XPT_GET_SIM_KNOB" },
5593         { XPT_SET_SIM_KNOB, "XPT_SET_SIM_KNOB" },
5594         { XPT_NVME_IO, "XPT_NVME_IO" },
5595         { XPT_MMC_IO, "XPT_MMC_IO" },
5596         { XPT_SMP_IO, "XPT_SMP_IO" },
5597         { XPT_SCAN_TGT, "XPT_SCAN_TGT" },
5598         { XPT_NVME_ADMIN, "XPT_NVME_ADMIN" },
5599         { XPT_ENG_INQ, "XPT_ENG_INQ" },
5600         { XPT_ENG_EXEC, "XPT_ENG_EXEC" },
5601         { XPT_EN_LUN, "XPT_EN_LUN" },
5602         { XPT_TARGET_IO, "XPT_TARGET_IO" },
5603         { XPT_ACCEPT_TARGET_IO, "XPT_ACCEPT_TARGET_IO" },
5604         { XPT_CONT_TARGET_IO, "XPT_CONT_TARGET_IO" },
5605         { XPT_IMMED_NOTIFY, "XPT_IMMED_NOTIFY" },
5606         { XPT_NOTIFY_ACK, "XPT_NOTIFY_ACK" },
5607         { XPT_IMMEDIATE_NOTIFY, "XPT_IMMEDIATE_NOTIFY" },
5608         { XPT_NOTIFY_ACKNOWLEDGE, "XPT_NOTIFY_ACKNOWLEDGE" },
5609         { 0, 0 }
5610 };
5611
5612 const char *
5613 xpt_action_name(uint32_t action) 
5614 {
5615         static char buffer[32]; /* Only for unknown messages -- racy */
5616         struct kv *walker = map;
5617
5618         while (walker->name != NULL) {
5619                 if (walker->v == action)
5620                         return (walker->name);
5621                 walker++;
5622         }
5623
5624         snprintf(buffer, sizeof(buffer), "%#x", action);
5625         return (buffer);
5626 }