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