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