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