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