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