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