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