Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / bus / 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  * $FreeBSD: src/sys/cam/cam_xpt.c,v 1.80.2.18 2002/12/09 17:31:55 gibbs Exp $
30  * $DragonFly: src/sys/bus/cam/cam_xpt.c,v 1.68 2008/08/23 17:13:31 pavalos Exp $
31  */
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/types.h>
35 #include <sys/malloc.h>
36 #include <sys/kernel.h>
37 #include <sys/time.h>
38 #include <sys/conf.h>
39 #include <sys/device.h>
40 #include <sys/fcntl.h>
41 #include <sys/md5.h>
42 #include <sys/devicestat.h>
43 #include <sys/interrupt.h>
44 #include <sys/sbuf.h>
45 #include <sys/taskqueue.h>
46 #include <sys/bus.h>
47 #include <sys/thread.h>
48 #include <sys/lock.h>
49 #include <sys/spinlock.h>
50 #include <sys/thread2.h>
51 #include <sys/spinlock2.h>
52
53 #include <machine/clock.h>
54 #include <machine/stdarg.h>
55
56 #include "cam.h"
57 #include "cam_ccb.h"
58 #include "cam_periph.h"
59 #include "cam_sim.h"
60 #include "cam_xpt.h"
61 #include "cam_xpt_sim.h"
62 #include "cam_xpt_periph.h"
63 #include "cam_debug.h"
64
65 #include "scsi/scsi_all.h"
66 #include "scsi/scsi_message.h"
67 #include "scsi/scsi_pass.h"
68 #include <sys/kthread.h>
69 #include "opt_cam.h"
70
71 /* Datastructures internal to the xpt layer */
72 MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
73
74 /* Object for defering XPT actions to a taskqueue */
75 struct xpt_task {
76         struct task     task;
77         void            *data1;
78         uintptr_t       data2;
79 };
80
81 /*
82  * Definition of an async handler callback block.  These are used to add
83  * SIMs and peripherals to the async callback lists.
84  */
85 struct async_node {
86         SLIST_ENTRY(async_node) links;
87         u_int32_t       event_enable;   /* Async Event enables */
88         void            (*callback)(void *arg, u_int32_t code,
89                                     struct cam_path *path, void *args);
90         void            *callback_arg;
91 };
92
93 SLIST_HEAD(async_list, async_node);
94 SLIST_HEAD(periph_list, cam_periph);
95
96 /*
97  * This is the maximum number of high powered commands (e.g. start unit)
98  * that can be outstanding at a particular time.
99  */
100 #ifndef CAM_MAX_HIGHPOWER
101 #define CAM_MAX_HIGHPOWER  4
102 #endif
103
104 /*
105  * Structure for queueing a device in a run queue.
106  * There is one run queue for allocating new ccbs,
107  * and another for sending ccbs to the controller.
108  */
109 struct cam_ed_qinfo {
110         cam_pinfo pinfo;
111         struct    cam_ed *device;
112 };
113
114 /*
115  * The CAM EDT (Existing Device Table) contains the device information for
116  * all devices for all busses in the system.  The table contains a
117  * cam_ed structure for each device on the bus.
118  */
119 struct cam_ed {
120         TAILQ_ENTRY(cam_ed) links;
121         struct  cam_ed_qinfo alloc_ccb_entry;
122         struct  cam_ed_qinfo send_ccb_entry;
123         struct  cam_et   *target;
124         struct  cam_sim  *sim;
125         lun_id_t         lun_id;
126         struct  camq drvq;              /*
127                                          * Queue of type drivers wanting to do
128                                          * work on this device.
129                                          */
130         struct  cam_ccbq ccbq;          /* Queue of pending ccbs */
131         struct  async_list asyncs;      /* Async callback info for this B/T/L */
132         struct  periph_list periphs;    /* All attached devices */
133         u_int   generation;             /* Generation number */
134         struct  cam_periph *owner;      /* Peripheral driver's ownership tag */
135         struct  xpt_quirk_entry *quirk; /* Oddities about this device */
136                                         /* Storage for the inquiry data */
137         cam_proto        protocol;
138         u_int            protocol_version;
139         cam_xport        transport;
140         u_int            transport_version;
141         struct           scsi_inquiry_data inq_data;
142         u_int8_t         inq_flags;     /*
143                                          * Current settings for inquiry flags.
144                                          * This allows us to override settings
145                                          * like disconnection and tagged
146                                          * queuing for a device.
147                                          */
148         u_int8_t         queue_flags;   /* Queue flags from the control page */
149         u_int8_t         serial_num_len;
150         u_int8_t        *serial_num;
151         u_int32_t        qfrozen_cnt;
152         u_int32_t        flags;
153 #define CAM_DEV_UNCONFIGURED            0x01
154 #define CAM_DEV_REL_TIMEOUT_PENDING     0x02
155 #define CAM_DEV_REL_ON_COMPLETE         0x04
156 #define CAM_DEV_REL_ON_QUEUE_EMPTY      0x08
157 #define CAM_DEV_RESIZE_QUEUE_NEEDED     0x10
158 #define CAM_DEV_TAG_AFTER_COUNT         0x20
159 #define CAM_DEV_INQUIRY_DATA_VALID      0x40
160 #define CAM_DEV_IN_DV                   0x80
161 #define CAM_DEV_DV_HIT_BOTTOM           0x100
162         u_int32_t        tag_delay_count;
163 #define CAM_TAG_DELAY_COUNT             5
164         u_int32_t        tag_saved_openings;
165         u_int32_t        refcount;
166         struct callout   callout;
167 };
168
169 /*
170  * Each target is represented by an ET (Existing Target).  These
171  * entries are created when a target is successfully probed with an
172  * identify, and removed when a device fails to respond after a number
173  * of retries, or a bus rescan finds the device missing.
174  */
175 struct cam_et {
176         TAILQ_HEAD(, cam_ed) ed_entries;
177         TAILQ_ENTRY(cam_et) links;
178         struct  cam_eb  *bus;
179         target_id_t     target_id;
180         u_int32_t       refcount;
181         u_int           generation;
182         struct          timeval last_reset;     /* uptime of last reset */
183 };
184
185 /*
186  * Each bus is represented by an EB (Existing Bus).  These entries
187  * are created by calls to xpt_bus_register and deleted by calls to
188  * xpt_bus_deregister.
189  */
190 struct cam_eb {
191         TAILQ_HEAD(, cam_et) et_entries;
192         TAILQ_ENTRY(cam_eb)  links;
193         path_id_t            path_id;
194         struct cam_sim       *sim;
195         struct timeval       last_reset;        /* uptime of last reset */
196         u_int32_t            flags;
197 #define CAM_EB_RUNQ_SCHEDULED   0x01
198         u_int32_t            refcount;
199         u_int                generation;
200 };
201
202 struct cam_path {
203         struct cam_periph *periph;
204         struct cam_eb     *bus;
205         struct cam_et     *target;
206         struct cam_ed     *device;
207 };
208
209 struct xpt_quirk_entry {
210         struct scsi_inquiry_pattern inq_pat;
211         u_int8_t quirks;
212 #define CAM_QUIRK_NOLUNS        0x01
213 #define CAM_QUIRK_NOSERIAL      0x02
214 #define CAM_QUIRK_HILUNS        0x04
215 #define CAM_QUIRK_NOHILUNS      0x08
216         u_int mintags;
217         u_int maxtags;
218 };
219
220 static int cam_srch_hi = 0;
221 TUNABLE_INT("kern.cam.cam_srch_hi", &cam_srch_hi);
222 static int sysctl_cam_search_luns(SYSCTL_HANDLER_ARGS);
223 SYSCTL_PROC(_kern_cam, OID_AUTO, cam_srch_hi, CTLTYPE_INT|CTLFLAG_RW, 0, 0,
224     sysctl_cam_search_luns, "I",
225     "allow search above LUN 7 for SCSI3 and greater devices");
226
227 #define CAM_SCSI2_MAXLUN        8
228 /*
229  * If we're not quirked to search <= the first 8 luns
230  * and we are either quirked to search above lun 8,
231  * or we're > SCSI-2 and we've enabled hilun searching,
232  * or we're > SCSI-2 and the last lun was a success,
233  * we can look for luns above lun 8.
234  */
235 #define CAN_SRCH_HI_SPARSE(dv)                          \
236   (((dv->quirk->quirks & CAM_QUIRK_NOHILUNS) == 0)      \
237   && ((dv->quirk->quirks & CAM_QUIRK_HILUNS)            \
238   || (SID_ANSI_REV(&dv->inq_data) > SCSI_REV_2 && cam_srch_hi)))
239
240 #define CAN_SRCH_HI_DENSE(dv)                           \
241   (((dv->quirk->quirks & CAM_QUIRK_NOHILUNS) == 0)      \
242   && ((dv->quirk->quirks & CAM_QUIRK_HILUNS)            \
243   || (SID_ANSI_REV(&dv->inq_data) > SCSI_REV_2)))
244
245 typedef enum {
246         XPT_FLAG_OPEN           = 0x01
247 } xpt_flags;
248
249 struct xpt_softc {
250         xpt_flags               flags;
251         u_int32_t               xpt_generation;
252
253         /* number of high powered commands that can go through right now */
254         STAILQ_HEAD(highpowerlist, ccb_hdr)     highpowerq;
255         int                     num_highpower;
256
257         /* queue for handling async rescan requests. */
258         TAILQ_HEAD(, ccb_hdr)   ccb_scanq;
259         int                     ccb_scanq_running;
260
261         /* Registered busses */
262         TAILQ_HEAD(,cam_eb)     xpt_busses;
263         u_int                   bus_generation;
264
265         struct intr_config_hook *xpt_config_hook;
266
267         struct lock             xpt_topo_lock;
268         struct lock             xpt_lock;
269 };
270
271 static const char quantum[] = "QUANTUM";
272 static const char sony[] = "SONY";
273 static const char west_digital[] = "WDIGTL";
274 static const char samsung[] = "SAMSUNG";
275 static const char seagate[] = "SEAGATE";
276 static const char microp[] = "MICROP";
277
278 static struct xpt_quirk_entry xpt_quirk_table[] =
279 {
280         {
281                 /* Reports QUEUE FULL for temporary resource shortages */
282                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP39100*", "*" },
283                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
284         },
285         {
286                 /* Reports QUEUE FULL for temporary resource shortages */
287                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP34550*", "*" },
288                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
289         },
290         {
291                 /* Reports QUEUE FULL for temporary resource shortages */
292                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP32275*", "*" },
293                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
294         },
295         {
296                 /* Broken tagged queuing drive */
297                 { T_DIRECT, SIP_MEDIA_FIXED, microp, "4421-07*", "*" },
298                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
299         },
300         {
301                 /* Broken tagged queuing drive */
302                 { T_DIRECT, SIP_MEDIA_FIXED, "HP", "C372*", "*" },
303                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
304         },
305         {
306                 /* Broken tagged queuing drive */
307                 { T_DIRECT, SIP_MEDIA_FIXED, microp, "3391*", "x43h" },
308                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
309         },
310         {
311                 /*
312                  * Unfortunately, the Quantum Atlas III has the same
313                  * problem as the Atlas II drives above.
314                  * Reported by: "Johan Granlund" <johan@granlund.nu>
315                  *
316                  * For future reference, the drive with the problem was:
317                  * QUANTUM QM39100TD-SW N1B0
318                  *
319                  * It's possible that Quantum will fix the problem in later
320                  * firmware revisions.  If that happens, the quirk entry
321                  * will need to be made specific to the firmware revisions
322                  * with the problem.
323                  *
324                  */
325                 /* Reports QUEUE FULL for temporary resource shortages */
326                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM39100*", "*" },
327                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
328         },
329         {
330                 /*
331                  * 18 Gig Atlas III, same problem as the 9G version.
332                  * Reported by: Andre Albsmeier
333                  *              <andre.albsmeier@mchp.siemens.de>
334                  *
335                  * For future reference, the drive with the problem was:
336                  * QUANTUM QM318000TD-S N491
337                  */
338                 /* Reports QUEUE FULL for temporary resource shortages */
339                 { T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM318000*", "*" },
340                 /*quirks*/0, /*mintags*/24, /*maxtags*/32
341         },
342         {
343                 /*
344                  * Broken tagged queuing drive
345                  * Reported by: Bret Ford <bford@uop.cs.uop.edu>
346                  *         and: Martin Renters <martin@tdc.on.ca>
347                  */
348                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST410800*", "71*" },
349                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
350         },
351                 /*
352                  * The Seagate Medalist Pro drives have very poor write
353                  * performance with anything more than 2 tags.
354                  *
355                  * Reported by:  Paul van der Zwan <paulz@trantor.xs4all.nl>
356                  * Drive:  <SEAGATE ST36530N 1444>
357                  *
358                  * Reported by:  Jeremy Lea <reg@shale.csir.co.za>
359                  * Drive:  <SEAGATE ST34520W 1281>
360                  *
361                  * No one has actually reported that the 9G version
362                  * (ST39140*) of the Medalist Pro has the same problem, but
363                  * we're assuming that it does because the 4G and 6.5G
364                  * versions of the drive are broken.
365                  */
366         {
367                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST34520*", "*"},
368                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
369         },
370         {
371                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST36530*", "*"},
372                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
373         },
374         {
375                 { T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST39140*", "*"},
376                 /*quirks*/0, /*mintags*/2, /*maxtags*/2
377         },
378         {
379                 /*
380                  * Slow when tagged queueing is enabled.  Write performance
381                  * steadily drops off with more and more concurrent
382                  * transactions.  Best sequential write performance with
383                  * tagged queueing turned off and write caching turned on.
384                  *
385                  * PR:  kern/10398
386                  * Submitted by:  Hideaki Okada <hokada@isl.melco.co.jp>
387                  * Drive:  DCAS-34330 w/ "S65A" firmware.
388                  *
389                  * The drive with the problem had the "S65A" firmware
390                  * revision, and has also been reported (by Stephen J.
391                  * Roznowski <sjr@home.net>) for a drive with the "S61A"
392                  * firmware revision.
393                  *
394                  * Although no one has reported problems with the 2 gig
395                  * version of the DCAS drive, the assumption is that it
396                  * has the same problems as the 4 gig version.  Therefore
397                  * this quirk entries disables tagged queueing for all
398                  * DCAS drives.
399                  */
400                 { T_DIRECT, SIP_MEDIA_FIXED, "IBM", "DCAS*", "*" },
401                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
402         },
403         {
404                 /* Broken tagged queuing drive */
405                 { T_DIRECT, SIP_MEDIA_REMOVABLE, "iomega", "jaz*", "*" },
406                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
407         },
408         {
409                 /* Broken tagged queuing drive */
410                 { T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CFP2107*", "*" },
411                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
412         },
413         {
414                 /* This does not support other than LUN 0 */
415                 { T_DIRECT, SIP_MEDIA_FIXED, "VMware*", "*", "*" },
416                 CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
417         },
418         {
419                 /*
420                  * Broken tagged queuing drive.
421                  * Submitted by:
422                  * NAKAJI Hiroyuki <nakaji@zeisei.dpri.kyoto-u.ac.jp>
423                  * in PR kern/9535
424                  */
425                 { T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN34324U*", "*" },
426                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
427         },
428         {
429                 /*
430                  * Slow when tagged queueing is enabled. (1.5MB/sec versus
431                  * 8MB/sec.)
432                  * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
433                  * Best performance with these drives is achieved with
434                  * tagged queueing turned off, and write caching turned on.
435                  */
436                 { T_DIRECT, SIP_MEDIA_FIXED, west_digital, "WDE*", "*" },
437                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
438         },
439         {
440                 /*
441                  * Slow when tagged queueing is enabled. (1.5MB/sec versus
442                  * 8MB/sec.)
443                  * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
444                  * Best performance with these drives is achieved with
445                  * tagged queueing turned off, and write caching turned on.
446                  */
447                 { T_DIRECT, SIP_MEDIA_FIXED, west_digital, "ENTERPRISE", "*" },
448                 /*quirks*/0, /*mintags*/0, /*maxtags*/0
449         },
450         {
451                 /*
452                  * Doesn't handle queue full condition correctly,
453                  * so we need to limit maxtags to what the device
454                  * can handle instead of determining this automatically.
455                  */
456                 { T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN321010S*", "*" },
457                 /*quirks*/0, /*mintags*/2, /*maxtags*/32
458         },
459         {
460                 /* Really only one LUN */
461                 { T_ENCLOSURE, SIP_MEDIA_FIXED, "SUN", "SENA", "*" },
462                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
463         },
464         {
465                 /* I can't believe we need a quirk for DPT volumes. */
466                 { T_ANY, SIP_MEDIA_FIXED|SIP_MEDIA_REMOVABLE, "DPT", "*", "*" },
467                 CAM_QUIRK_NOLUNS,
468                 /*mintags*/0, /*maxtags*/255
469         },
470         {
471                 /*
472                  * Many Sony CDROM drives don't like multi-LUN probing.
473                  */
474                 { T_CDROM, SIP_MEDIA_REMOVABLE, sony, "CD-ROM CDU*", "*" },
475                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
476         },
477         {
478                 /*
479                  * This drive doesn't like multiple LUN probing.
480                  * Submitted by:  Parag Patel <parag@cgt.com>
481                  */
482                 { T_WORM, SIP_MEDIA_REMOVABLE, sony, "CD-R   CDU9*", "*" },
483                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
484         },
485         {
486                 { T_WORM, SIP_MEDIA_REMOVABLE, "YAMAHA", "CDR100*", "*" },
487                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
488         },
489         {
490                 /*
491                  * The 8200 doesn't like multi-lun probing, and probably
492                  * don't like serial number requests either.
493                  */
494                 {
495                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
496                         "EXB-8200*", "*"
497                 },
498                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
499         },
500         {
501                 /*
502                  * Let's try the same as above, but for a drive that says
503                  * it's an IPL-6860 but is actually an EXB 8200.
504                  */
505                 {
506                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
507                         "IPL-6860*", "*"
508                 },
509                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
510         },
511         {
512                 /*
513                  * These Hitachi drives don't like multi-lun probing.
514                  * The PR submitter has a DK319H, but says that the Linux
515                  * kernel has a similar work-around for the DK312 and DK314,
516                  * so all DK31* drives are quirked here.
517                  * PR:            misc/18793
518                  * Submitted by:  Paul Haddad <paul@pth.com>
519                  */
520                 { T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK31*", "*" },
521                 CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
522         },
523         {
524                 /*
525                  * The Hitachi CJ series with J8A8 firmware apparantly has
526                  * problems with tagged commands.
527                  * PR: 23536
528                  * Reported by: amagai@nue.org
529                  */
530                 { T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK32CJ*", "J8A8" },
531                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
532         },
533         {
534                 /*
535                  * These are the large storage arrays.
536                  * Submitted by:  William Carrel <william.carrel@infospace.com>
537                  */
538                 { T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "OPEN*", "*" },
539                 CAM_QUIRK_HILUNS, 2, 1024
540         },
541         {
542                 /*
543                  * This old revision of the TDC3600 is also SCSI-1, and
544                  * hangs upon serial number probing.
545                  */
546                 {
547                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
548                         " TDC 3600", "U07:"
549                 },
550                 CAM_QUIRK_NOSERIAL, /*mintags*/0, /*maxtags*/0
551         },
552         {
553                 /*
554                  * Would repond to all LUNs if asked for.
555                  */
556                 {
557                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "CALIPER",
558                         "CP150", "*"
559                 },
560                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
561         },
562         {
563                 /*
564                  * Would repond to all LUNs if asked for.
565                  */
566                 {
567                         T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
568                         "96X2*", "*"
569                 },
570                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
571         },
572         {
573                 /* Submitted by: Matthew Dodd <winter@jurai.net> */
574                 { T_PROCESSOR, SIP_MEDIA_FIXED, "Cabletrn", "EA41*", "*" },
575                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
576         },
577         {
578                 /* Submitted by: Matthew Dodd <winter@jurai.net> */
579                 { T_PROCESSOR, SIP_MEDIA_FIXED, "CABLETRN", "EA41*", "*" },
580                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
581         },
582         {
583                 /* TeraSolutions special settings for TRC-22 RAID */
584                 { T_DIRECT, SIP_MEDIA_FIXED, "TERASOLU", "TRC-22", "*" },
585                   /*quirks*/0, /*mintags*/55, /*maxtags*/255
586         },
587         {
588                 /* Veritas Storage Appliance */
589                 { T_DIRECT, SIP_MEDIA_FIXED, "VERITAS", "*", "*" },
590                   CAM_QUIRK_HILUNS, /*mintags*/2, /*maxtags*/1024
591         },
592         {
593                 /*
594                  * Would respond to all LUNs.  Device type and removable
595                  * flag are jumper-selectable.
596                  */
597                 { T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED, "MaxOptix",
598                   "Tahiti 1", "*"
599                 },
600                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
601         },
602         {
603                 /* EasyRAID E5A aka. areca ARC-6010 */
604                 { T_DIRECT, SIP_MEDIA_FIXED, "easyRAID", "*", "*" },
605                   CAM_QUIRK_NOHILUNS, /*mintags*/2, /*maxtags*/255
606         },
607         {
608                 { T_ENCLOSURE, SIP_MEDIA_FIXED, "DP", "BACKPLANE", "*" },
609                 CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
610         },
611         {
612                 /* Default tagged queuing parameters for all devices */
613                 {
614                   T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
615                   /*vendor*/"*", /*product*/"*", /*revision*/"*"
616                 },
617                 /*quirks*/0, /*mintags*/2, /*maxtags*/255
618         },
619 };
620
621 static const int xpt_quirk_table_size =
622         sizeof(xpt_quirk_table) / sizeof(*xpt_quirk_table);
623
624 typedef enum {
625         DM_RET_COPY             = 0x01,
626         DM_RET_FLAG_MASK        = 0x0f,
627         DM_RET_NONE             = 0x00,
628         DM_RET_STOP             = 0x10,
629         DM_RET_DESCEND          = 0x20,
630         DM_RET_ERROR            = 0x30,
631         DM_RET_ACTION_MASK      = 0xf0
632 } dev_match_ret;
633
634 typedef enum {
635         XPT_DEPTH_BUS,
636         XPT_DEPTH_TARGET,
637         XPT_DEPTH_DEVICE,
638         XPT_DEPTH_PERIPH
639 } xpt_traverse_depth;
640
641 struct xpt_traverse_config {
642         xpt_traverse_depth      depth;
643         void                    *tr_func;
644         void                    *tr_arg;
645 };
646
647 typedef int     xpt_busfunc_t (struct cam_eb *bus, void *arg);
648 typedef int     xpt_targetfunc_t (struct cam_et *target, void *arg);
649 typedef int     xpt_devicefunc_t (struct cam_ed *device, void *arg);
650 typedef int     xpt_periphfunc_t (struct cam_periph *periph, void *arg);
651 typedef int     xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
652
653 /* Transport layer configuration information */
654 static struct xpt_softc xsoftc;
655
656 /* Queues for our software interrupt handler */
657 typedef TAILQ_HEAD(cam_isrq, ccb_hdr) cam_isrq_t;
658 typedef TAILQ_HEAD(cam_simq, cam_sim) cam_simq_t;
659 static cam_simq_t cam_simq;
660 static struct spinlock cam_simq_spin;
661
662 struct cam_periph *xpt_periph;
663
664 static periph_init_t xpt_periph_init;
665
666 static periph_init_t probe_periph_init;
667
668 static struct periph_driver xpt_driver =
669 {
670         xpt_periph_init, "xpt",
671         TAILQ_HEAD_INITIALIZER(xpt_driver.units)
672 };
673
674 static struct periph_driver probe_driver =
675 {
676         probe_periph_init, "probe",
677         TAILQ_HEAD_INITIALIZER(probe_driver.units)
678 };
679
680 PERIPHDRIVER_DECLARE(xpt, xpt_driver);
681 PERIPHDRIVER_DECLARE(probe, probe_driver);
682
683 #define XPT_CDEV_MAJOR 104
684
685 static d_open_t xptopen;
686 static d_close_t xptclose;
687 static d_ioctl_t xptioctl;
688
689 static struct dev_ops xpt_ops = {
690         { "xpt", XPT_CDEV_MAJOR, 0 },
691         .d_open = xptopen,
692         .d_close = xptclose,
693         .d_ioctl = xptioctl
694 };
695
696 static void dead_sim_action(struct cam_sim *sim, union ccb *ccb);
697 static void dead_sim_poll(struct cam_sim *sim);
698
699 /* Dummy SIM that is used when the real one has gone. */
700 static struct cam_sim cam_dead_sim;
701 static struct lock    cam_dead_lock;
702
703 /* Storage for debugging datastructures */
704 #ifdef  CAMDEBUG
705 struct cam_path *cam_dpath;
706 u_int32_t cam_dflags;
707 u_int32_t cam_debug_delay;
708 #endif
709
710 #if defined(CAM_DEBUG_FLAGS) && !defined(CAMDEBUG)
711 #error "You must have options CAMDEBUG to use options CAM_DEBUG_FLAGS"
712 #endif
713
714 /*
715  * In order to enable the CAM_DEBUG_* options, the user must have CAMDEBUG
716  * enabled.  Also, the user must have either none, or all of CAM_DEBUG_BUS,
717  * CAM_DEBUG_TARGET, and CAM_DEBUG_LUN specified.
718  */
719 #if defined(CAM_DEBUG_BUS) || defined(CAM_DEBUG_TARGET) \
720     || defined(CAM_DEBUG_LUN)
721 #ifdef CAMDEBUG
722 #if !defined(CAM_DEBUG_BUS) || !defined(CAM_DEBUG_TARGET) \
723     || !defined(CAM_DEBUG_LUN)
724 #error "You must define all or none of CAM_DEBUG_BUS, CAM_DEBUG_TARGET \
725         and CAM_DEBUG_LUN"
726 #endif /* !CAM_DEBUG_BUS || !CAM_DEBUG_TARGET || !CAM_DEBUG_LUN */
727 #else /* !CAMDEBUG */
728 #error "You must use options CAMDEBUG if you use the CAM_DEBUG_* options"
729 #endif /* CAMDEBUG */
730 #endif /* CAM_DEBUG_BUS || CAM_DEBUG_TARGET || CAM_DEBUG_LUN */
731
732 /* Our boot-time initialization hook */
733 static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);
734
735 static moduledata_t cam_moduledata = {
736         "cam",
737         cam_module_event_handler,
738         NULL
739 };
740
741 static int      xpt_init(void *);
742
743 DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
744 MODULE_VERSION(cam, 1);
745
746
747 static cam_status       xpt_compile_path(struct cam_path *new_path,
748                                          struct cam_periph *perph,
749                                          path_id_t path_id,
750                                          target_id_t target_id,
751                                          lun_id_t lun_id);
752
753 static void             xpt_release_path(struct cam_path *path);
754
755 static void             xpt_async_bcast(struct async_list *async_head,
756                                         u_int32_t async_code,
757                                         struct cam_path *path,
758                                         void *async_arg);
759 static void             xpt_dev_async(u_int32_t async_code,
760                                       struct cam_eb *bus,
761                                       struct cam_et *target,
762                                       struct cam_ed *device,
763                                       void *async_arg);
764 static path_id_t xptnextfreepathid(void);
765 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
766 static union ccb *xpt_get_ccb(struct cam_ed *device);
767 static int       xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
768                                   u_int32_t new_priority);
769 static void      xpt_run_dev_allocq(struct cam_eb *bus);
770 static void      xpt_run_dev_sendq(struct cam_eb *bus);
771 static timeout_t xpt_release_devq_timeout;
772 static void      xpt_release_bus(struct cam_eb *bus);
773 static void      xpt_release_devq_device(struct cam_ed *dev, u_int count,
774                                          int run_queue);
775 static struct cam_et*
776                  xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
777 static void      xpt_release_target(struct cam_eb *bus, struct cam_et *target);
778 static struct cam_ed*
779                  xpt_alloc_device(struct cam_eb *bus, struct cam_et *target,
780                                   lun_id_t lun_id);
781 static void      xpt_release_device(struct cam_eb *bus, struct cam_et *target,
782                                     struct cam_ed *device);
783 static u_int32_t xpt_dev_ccbq_resize(struct cam_path *path, int newopenings);
784 static struct cam_eb*
785                  xpt_find_bus(path_id_t path_id);
786 static struct cam_et*
787                  xpt_find_target(struct cam_eb *bus, target_id_t target_id);
788 static struct cam_ed*
789                  xpt_find_device(struct cam_et *target, lun_id_t lun_id);
790 static void      xpt_scan_bus(struct cam_periph *periph, union ccb *ccb);
791 static void      xpt_scan_lun(struct cam_periph *periph,
792                               struct cam_path *path, cam_flags flags,
793                               union ccb *ccb);
794 static void      xptscandone(struct cam_periph *periph, union ccb *done_ccb);
795 static xpt_busfunc_t    xptconfigbuscountfunc;
796 static xpt_busfunc_t    xptconfigfunc;
797 static void      xpt_config(void *arg);
798 static xpt_devicefunc_t xptpassannouncefunc;
799 static void      xpt_finishconfig(struct cam_periph *periph, union ccb *ccb);
800 static void      xptaction(struct cam_sim *sim, union ccb *work_ccb);
801 static void      xptpoll(struct cam_sim *sim);
802 static inthand2_t swi_cambio;
803 static void      camisr(void *);
804 static void      camisr_runqueue(struct cam_sim *);
805 static dev_match_ret    xptbusmatch(struct dev_match_pattern *patterns,
806                                     u_int num_patterns, struct cam_eb *bus);
807 static dev_match_ret    xptdevicematch(struct dev_match_pattern *patterns,
808                                        u_int num_patterns,
809                                        struct cam_ed *device);
810 static dev_match_ret    xptperiphmatch(struct dev_match_pattern *patterns,
811                                        u_int num_patterns,
812                                        struct cam_periph *periph);
813 static xpt_busfunc_t    xptedtbusfunc;
814 static xpt_targetfunc_t xptedttargetfunc;
815 static xpt_devicefunc_t xptedtdevicefunc;
816 static xpt_periphfunc_t xptedtperiphfunc;
817 static xpt_pdrvfunc_t   xptplistpdrvfunc;
818 static xpt_periphfunc_t xptplistperiphfunc;
819 static int              xptedtmatch(struct ccb_dev_match *cdm);
820 static int              xptperiphlistmatch(struct ccb_dev_match *cdm);
821 static int              xptbustraverse(struct cam_eb *start_bus,
822                                        xpt_busfunc_t *tr_func, void *arg);
823 static int              xpttargettraverse(struct cam_eb *bus,
824                                           struct cam_et *start_target,
825                                           xpt_targetfunc_t *tr_func, void *arg);
826 static int              xptdevicetraverse(struct cam_et *target,
827                                           struct cam_ed *start_device,
828                                           xpt_devicefunc_t *tr_func, void *arg);
829 static int              xptperiphtraverse(struct cam_ed *device,
830                                           struct cam_periph *start_periph,
831                                           xpt_periphfunc_t *tr_func, void *arg);
832 static int              xptpdrvtraverse(struct periph_driver **start_pdrv,
833                                         xpt_pdrvfunc_t *tr_func, void *arg);
834 static int              xptpdperiphtraverse(struct periph_driver **pdrv,
835                                             struct cam_periph *start_periph,
836                                             xpt_periphfunc_t *tr_func,
837                                             void *arg);
838 static xpt_busfunc_t    xptdefbusfunc;
839 static xpt_targetfunc_t xptdeftargetfunc;
840 static xpt_devicefunc_t xptdefdevicefunc;
841 static xpt_periphfunc_t xptdefperiphfunc;
842 static int              xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg);
843 static int              xpt_for_all_devices(xpt_devicefunc_t *tr_func,
844                                             void *arg);
845 static xpt_devicefunc_t xptsetasyncfunc;
846 static xpt_busfunc_t    xptsetasyncbusfunc;
847 static cam_status       xptregister(struct cam_periph *periph,
848                                     void *arg);
849 static cam_status       proberegister(struct cam_periph *periph,
850                                       void *arg);
851 static void      probeschedule(struct cam_periph *probe_periph);
852 static void      probestart(struct cam_periph *periph, union ccb *start_ccb);
853 static void      proberequestdefaultnegotiation(struct cam_periph *periph);
854 static int       proberequestbackoff(struct cam_periph *periph,
855                                      struct cam_ed *device);
856 static void      probedone(struct cam_periph *periph, union ccb *done_ccb);
857 static void      probecleanup(struct cam_periph *periph);
858 static void      xpt_find_quirk(struct cam_ed *device);
859 static void      xpt_devise_transport(struct cam_path *path);
860 static void      xpt_set_transfer_settings(struct ccb_trans_settings *cts,
861                                            struct cam_ed *device,
862                                            int async_update);
863 static void      xpt_toggle_tags(struct cam_path *path);
864 static void      xpt_start_tags(struct cam_path *path);
865 static __inline int xpt_schedule_dev_allocq(struct cam_eb *bus,
866                                             struct cam_ed *dev);
867 static __inline int xpt_schedule_dev_sendq(struct cam_eb *bus,
868                                            struct cam_ed *dev);
869 static __inline int periph_is_queued(struct cam_periph *periph);
870 static __inline int device_is_alloc_queued(struct cam_ed *device);
871 static __inline int device_is_send_queued(struct cam_ed *device);
872 static __inline int dev_allocq_is_runnable(struct cam_devq *devq);
873
874 static __inline int
875 xpt_schedule_dev_allocq(struct cam_eb *bus, struct cam_ed *dev)
876 {
877         int retval;
878
879         if (bus->sim->devq && dev->ccbq.devq_openings > 0) {
880                 if ((dev->flags & CAM_DEV_RESIZE_QUEUE_NEEDED) != 0) {
881                         cam_ccbq_resize(&dev->ccbq,
882                                         dev->ccbq.dev_openings
883                                         + dev->ccbq.dev_active);
884                         dev->flags &= ~CAM_DEV_RESIZE_QUEUE_NEEDED;
885                 }
886                 /*
887                  * The priority of a device waiting for CCB resources
888                  * is that of the the highest priority peripheral driver
889                  * enqueued.
890                  */
891                 retval = xpt_schedule_dev(&bus->sim->devq->alloc_queue,
892                                           &dev->alloc_ccb_entry.pinfo,
893                                           CAMQ_GET_HEAD(&dev->drvq)->priority);
894         } else {
895                 retval = 0;
896         }
897
898         return (retval);
899 }
900
901 static __inline int
902 xpt_schedule_dev_sendq(struct cam_eb *bus, struct cam_ed *dev)
903 {
904         int     retval;
905
906         if (bus->sim->devq && dev->ccbq.dev_openings > 0) {
907                 /*
908                  * The priority of a device waiting for controller
909                  * resources is that of the the highest priority CCB
910                  * enqueued.
911                  */
912                 retval =
913                     xpt_schedule_dev(&bus->sim->devq->send_queue,
914                                      &dev->send_ccb_entry.pinfo,
915                                      CAMQ_GET_HEAD(&dev->ccbq.queue)->priority);
916         } else {
917                 retval = 0;
918         }
919         return (retval);
920 }
921
922 static __inline int
923 periph_is_queued(struct cam_periph *periph)
924 {
925         return (periph->pinfo.index != CAM_UNQUEUED_INDEX);
926 }
927
928 static __inline int
929 device_is_alloc_queued(struct cam_ed *device)
930 {
931         return (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
932 }
933
934 static __inline int
935 device_is_send_queued(struct cam_ed *device)
936 {
937         return (device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX);
938 }
939
940 static __inline int
941 dev_allocq_is_runnable(struct cam_devq *devq)
942 {
943         /*
944          * Have work to do.
945          * Have space to do more work.
946          * Allowed to do work.
947          */
948         return ((devq->alloc_queue.qfrozen_cnt == 0)
949              && (devq->alloc_queue.entries > 0)
950              && (devq->alloc_openings > 0));
951 }
952
953 static void
954 xpt_periph_init(void)
955 {
956         dev_ops_add(&xpt_ops, 0, 0);
957         make_dev(&xpt_ops, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
958 }
959
960 static void
961 probe_periph_init(void)
962 {
963 }
964
965
966 static void
967 xptdone(struct cam_periph *periph, union ccb *done_ccb)
968 {
969         /* Caller will release the CCB */
970         wakeup(&done_ccb->ccb_h.cbfcnp);
971 }
972
973 static int
974 xptopen(struct dev_open_args *ap)
975 {
976         cdev_t dev = ap->a_head.a_dev;
977
978         /*
979          * Only allow read-write access.
980          */
981         if (((ap->a_oflags & FWRITE) == 0) || ((ap->a_oflags & FREAD) == 0))
982                 return(EPERM);
983
984         /*
985          * We don't allow nonblocking access.
986          */
987         if ((ap->a_oflags & O_NONBLOCK) != 0) {
988                 kprintf("%s: can't do nonblocking access\n", devtoname(dev));
989                 return(ENODEV);
990         }
991
992         /* Mark ourselves open */
993         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
994         xsoftc.flags |= XPT_FLAG_OPEN;
995         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
996
997         return(0);
998 }
999
1000 static int
1001 xptclose(struct dev_close_args *ap)
1002 {
1003
1004         /* Mark ourselves closed */
1005         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
1006         xsoftc.flags &= ~XPT_FLAG_OPEN;
1007         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
1008
1009         return(0);
1010 }
1011
1012 /*
1013  * Don't automatically grab the xpt softc lock here even though this is going
1014  * through the xpt device.  The xpt device is really just a back door for
1015  * accessing other devices and SIMs, so the right thing to do is to grab
1016  * the appropriate SIM lock once the bus/SIM is located.
1017  */
1018 static int
1019 xptioctl(struct dev_ioctl_args *ap)
1020 {
1021         int error;
1022
1023         error = 0;
1024
1025         switch(ap->a_cmd) {
1026         /*
1027          * For the transport layer CAMIOCOMMAND ioctl, we really only want
1028          * to accept CCB types that don't quite make sense to send through a
1029          * passthrough driver.
1030          */
1031         case CAMIOCOMMAND: {
1032                 union ccb *ccb;
1033                 union ccb *inccb;
1034                 struct cam_eb *bus;
1035
1036                 inccb = (union ccb *)ap->a_data;
1037
1038                 bus = xpt_find_bus(inccb->ccb_h.path_id);
1039                 if (bus == NULL) {
1040                         error = EINVAL;
1041                         break;
1042                 }
1043
1044                 switch(inccb->ccb_h.func_code) {
1045                 case XPT_SCAN_BUS:
1046                 case XPT_RESET_BUS:
1047                         if ((inccb->ccb_h.target_id != CAM_TARGET_WILDCARD)
1048                          || (inccb->ccb_h.target_lun != CAM_LUN_WILDCARD)) {
1049                                 error = EINVAL;
1050                                 break;
1051                         }
1052                         /* FALLTHROUGH */
1053                 case XPT_PATH_INQ:
1054                 case XPT_ENG_INQ:
1055                 case XPT_SCAN_LUN:
1056
1057                         ccb = xpt_alloc_ccb();
1058
1059                         CAM_SIM_LOCK(bus->sim);
1060
1061                         /*
1062                          * Create a path using the bus, target, and lun the
1063                          * user passed in.
1064                          */
1065                         if (xpt_create_path(&ccb->ccb_h.path, xpt_periph,
1066                                             inccb->ccb_h.path_id,
1067                                             inccb->ccb_h.target_id,
1068                                             inccb->ccb_h.target_lun) !=
1069                                             CAM_REQ_CMP){
1070                                 error = EINVAL;
1071                                 CAM_SIM_UNLOCK(bus->sim);
1072                                 xpt_free_ccb(ccb);
1073                                 break;
1074                         }
1075                         /* Ensure all of our fields are correct */
1076                         xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
1077                                       inccb->ccb_h.pinfo.priority);
1078                         xpt_merge_ccb(ccb, inccb);
1079                         ccb->ccb_h.cbfcnp = xptdone;
1080                         cam_periph_runccb(ccb, NULL, 0, 0, NULL);
1081                         bcopy(ccb, inccb, sizeof(union ccb));
1082                         xpt_free_path(ccb->ccb_h.path);
1083                         xpt_free_ccb(ccb);
1084                         CAM_SIM_UNLOCK(bus->sim);
1085                         break;
1086
1087                 case XPT_DEBUG: {
1088                         union ccb ccb;
1089
1090                         /*
1091                          * This is an immediate CCB, so it's okay to
1092                          * allocate it on the stack.
1093                          */
1094
1095                         CAM_SIM_LOCK(bus->sim);
1096
1097                         /*
1098                          * Create a path using the bus, target, and lun the
1099                          * user passed in.
1100                          */
1101                         if (xpt_create_path(&ccb.ccb_h.path, xpt_periph,
1102                                             inccb->ccb_h.path_id,
1103                                             inccb->ccb_h.target_id,
1104                                             inccb->ccb_h.target_lun) !=
1105                                             CAM_REQ_CMP){
1106                                 error = EINVAL;
1107                                 CAM_SIM_UNLOCK(bus->sim);
1108                                 break;
1109                         }
1110                         /* Ensure all of our fields are correct */
1111                         xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
1112                                       inccb->ccb_h.pinfo.priority);
1113                         xpt_merge_ccb(&ccb, inccb);
1114                         ccb.ccb_h.cbfcnp = xptdone;
1115                         xpt_action(&ccb);
1116                         CAM_SIM_UNLOCK(bus->sim);
1117                         bcopy(&ccb, inccb, sizeof(union ccb));
1118                         xpt_free_path(ccb.ccb_h.path);
1119                         break;
1120
1121                 }
1122                 case XPT_DEV_MATCH: {
1123                         struct cam_periph_map_info mapinfo;
1124                         struct cam_path *old_path;
1125
1126                         /*
1127                          * We can't deal with physical addresses for this
1128                          * type of transaction.
1129                          */
1130                         if (inccb->ccb_h.flags & CAM_DATA_PHYS) {
1131                                 error = EINVAL;
1132                                 break;
1133                         }
1134
1135                         /*
1136                          * Save this in case the caller had it set to
1137                          * something in particular.
1138                          */
1139                         old_path = inccb->ccb_h.path;
1140
1141                         /*
1142                          * We really don't need a path for the matching
1143                          * code.  The path is needed because of the
1144                          * debugging statements in xpt_action().  They
1145                          * assume that the CCB has a valid path.
1146                          */
1147                         inccb->ccb_h.path = xpt_periph->path;
1148
1149                         bzero(&mapinfo, sizeof(mapinfo));
1150
1151                         /*
1152                          * Map the pattern and match buffers into kernel
1153                          * virtual address space.
1154                          */
1155                         error = cam_periph_mapmem(inccb, &mapinfo);
1156
1157                         if (error) {
1158                                 inccb->ccb_h.path = old_path;
1159                                 break;
1160                         }
1161
1162                         /*
1163                          * This is an immediate CCB, we can send it on directly.
1164                          */
1165                         xpt_action(inccb);
1166
1167                         /*
1168                          * Map the buffers back into user space.
1169                          */
1170                         cam_periph_unmapmem(inccb, &mapinfo);
1171
1172                         inccb->ccb_h.path = old_path;
1173
1174                         error = 0;
1175                         break;
1176                 }
1177                 default:
1178                         error = ENOTSUP;
1179                         break;
1180                 }
1181                 xpt_release_bus(bus);
1182                 break;
1183         }
1184         /*
1185          * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
1186          * with the periphal driver name and unit name filled in.  The other
1187          * fields don't really matter as input.  The passthrough driver name
1188          * ("pass"), and unit number are passed back in the ccb.  The current
1189          * device generation number, and the index into the device peripheral
1190          * driver list, and the status are also passed back.  Note that
1191          * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
1192          * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
1193          * (or rather should be) impossible for the device peripheral driver
1194          * list to change since we look at the whole thing in one pass, and
1195          * we do it with lock protection.
1196          *
1197          */
1198         case CAMGETPASSTHRU: {
1199                 union ccb *ccb;
1200                 struct cam_periph *periph;
1201                 struct periph_driver **p_drv;
1202                 char   *name;
1203                 u_int unit;
1204                 u_int cur_generation;
1205                 int base_periph_found;
1206                 int splbreaknum;
1207
1208                 ccb = (union ccb *)ap->a_data;
1209                 unit = ccb->cgdl.unit_number;
1210                 name = ccb->cgdl.periph_name;
1211                 /*
1212                  * Every 100 devices, we want to drop our lock protection to
1213                  * give the software interrupt handler a chance to run.
1214                  * Most systems won't run into this check, but this should
1215                  * avoid starvation in the software interrupt handler in
1216                  * large systems.
1217                  */
1218                 splbreaknum = 100;
1219
1220                 ccb = (union ccb *)ap->a_data;
1221
1222                 base_periph_found = 0;
1223
1224                 /*
1225                  * Sanity check -- make sure we don't get a null peripheral
1226                  * driver name.
1227                  */
1228                 if (*ccb->cgdl.periph_name == '\0') {
1229                         error = EINVAL;
1230                         break;
1231                 }
1232
1233                 /* Keep the list from changing while we traverse it */
1234                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1235 ptstartover:
1236                 cur_generation = xsoftc.xpt_generation;
1237
1238                 /* first find our driver in the list of drivers */
1239                 for (p_drv = periph_drivers; *p_drv != NULL; p_drv++) {
1240                         if (strcmp((*p_drv)->driver_name, name) == 0)
1241                                 break;
1242                 }
1243
1244                 if (*p_drv == NULL) {
1245                         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1246                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1247                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1248                         *ccb->cgdl.periph_name = '\0';
1249                         ccb->cgdl.unit_number = 0;
1250                         error = ENOENT;
1251                         break;
1252                 }
1253
1254                 /*
1255                  * Run through every peripheral instance of this driver
1256                  * and check to see whether it matches the unit passed
1257                  * in by the user.  If it does, get out of the loops and
1258                  * find the passthrough driver associated with that
1259                  * peripheral driver.
1260                  */
1261                 TAILQ_FOREACH(periph, &(*p_drv)->units, unit_links) {
1262
1263                         if (periph->unit_number == unit) {
1264                                 break;
1265                         } else if (--splbreaknum == 0) {
1266                                 lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1267                                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1268                                 splbreaknum = 100;
1269                                 if (cur_generation != xsoftc.xpt_generation)
1270                                        goto ptstartover;
1271                         }
1272                 }
1273                 /*
1274                  * If we found the peripheral driver that the user passed
1275                  * in, go through all of the peripheral drivers for that
1276                  * particular device and look for a passthrough driver.
1277                  */
1278                 if (periph != NULL) {
1279                         struct cam_ed *device;
1280                         int i;
1281
1282                         base_periph_found = 1;
1283                         device = periph->path->device;
1284                         for (i = 0, periph = SLIST_FIRST(&device->periphs);
1285                              periph != NULL;
1286                              periph = SLIST_NEXT(periph, periph_links), i++) {
1287                                 /*
1288                                  * Check to see whether we have a
1289                                  * passthrough device or not.
1290                                  */
1291                                 if (strcmp(periph->periph_name, "pass") == 0) {
1292                                         /*
1293                                          * Fill in the getdevlist fields.
1294                                          */
1295                                         strcpy(ccb->cgdl.periph_name,
1296                                                periph->periph_name);
1297                                         ccb->cgdl.unit_number =
1298                                                 periph->unit_number;
1299                                         if (SLIST_NEXT(periph, periph_links))
1300                                                 ccb->cgdl.status =
1301                                                         CAM_GDEVLIST_MORE_DEVS;
1302                                         else
1303                                                 ccb->cgdl.status =
1304                                                        CAM_GDEVLIST_LAST_DEVICE;
1305                                         ccb->cgdl.generation =
1306                                                 device->generation;
1307                                         ccb->cgdl.index = i;
1308                                         /*
1309                                          * Fill in some CCB header fields
1310                                          * that the user may want.
1311                                          */
1312                                         ccb->ccb_h.path_id =
1313                                                 periph->path->bus->path_id;
1314                                         ccb->ccb_h.target_id =
1315                                                 periph->path->target->target_id;
1316                                         ccb->ccb_h.target_lun =
1317                                                 periph->path->device->lun_id;
1318                                         ccb->ccb_h.status = CAM_REQ_CMP;
1319                                         break;
1320                                 }
1321                         }
1322                 }
1323
1324                 /*
1325                  * If the periph is null here, one of two things has
1326                  * happened.  The first possibility is that we couldn't
1327                  * find the unit number of the particular peripheral driver
1328                  * that the user is asking about.  e.g. the user asks for
1329                  * the passthrough driver for "da11".  We find the list of
1330                  * "da" peripherals all right, but there is no unit 11.
1331                  * The other possibility is that we went through the list
1332                  * of peripheral drivers attached to the device structure,
1333                  * but didn't find one with the name "pass".  Either way,
1334                  * we return ENOENT, since we couldn't find something.
1335                  */
1336                 if (periph == NULL) {
1337                         ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1338                         ccb->cgdl.status = CAM_GDEVLIST_ERROR;
1339                         *ccb->cgdl.periph_name = '\0';
1340                         ccb->cgdl.unit_number = 0;
1341                         error = ENOENT;
1342                         /*
1343                          * It is unfortunate that this is even necessary,
1344                          * but there are many, many clueless users out there.
1345                          * If this is true, the user is looking for the
1346                          * passthrough driver, but doesn't have one in his
1347                          * kernel.
1348                          */
1349                         if (base_periph_found == 1) {
1350                                 kprintf("xptioctl: pass driver is not in the "
1351                                        "kernel\n");
1352                                 kprintf("xptioctl: put \"device pass\" in "
1353                                        "your kernel config file\n");
1354                         }
1355                 }
1356                 lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1357                 break;
1358                 }
1359         default:
1360                 error = ENOTTY;
1361                 break;
1362         }
1363
1364         return(error);
1365 }
1366
1367 static int
1368 cam_module_event_handler(module_t mod, int what, void *arg)
1369 {
1370         int error;
1371
1372         switch (what) {
1373         case MOD_LOAD:
1374                 if ((error = xpt_init(NULL)) != 0)
1375                         return (error);
1376                 break;
1377         case MOD_UNLOAD:
1378                 return EBUSY;
1379         default:
1380                 return EOPNOTSUPP;
1381         }
1382
1383         return 0;
1384 }
1385
1386 /*
1387  * Thread to handle asynchronous main-context requests.
1388  *
1389  * This function is typically used by drivers to perform complex actions
1390  * such as bus scans and engineering requests in a main context instead
1391  * of an interrupt context.
1392  */
1393 static void
1394 xpt_scanner_thread(void *dummy)
1395 {
1396         union ccb       *ccb;
1397 #if 0
1398         struct cam_sim  *sim;
1399 #endif
1400
1401         for (;;) {
1402                 xpt_lock_buses();
1403                 xsoftc.ccb_scanq_running = 1;
1404                 while ((ccb = (void *)TAILQ_FIRST(&xsoftc.ccb_scanq)) != NULL) {
1405                         TAILQ_REMOVE(&xsoftc.ccb_scanq, &ccb->ccb_h,
1406                                      sim_links.tqe);
1407                         xpt_unlock_buses();
1408 #if 0
1409                         sim = ccb->ccb_h.path->bus->sim;
1410                         CAM_SIM_LOCK(sim);
1411 #endif
1412                         xpt_action(ccb);
1413 #if 0
1414                         CAM_SIM_UNLOCK(sim);
1415                         xpt_lock_buses();
1416 #endif
1417                 }
1418                 xsoftc.ccb_scanq_running = 0;
1419                 crit_enter();
1420                 tsleep_interlock(&xsoftc.ccb_scanq);
1421                 xpt_unlock_buses();
1422                 tsleep(&xsoftc.ccb_scanq, PINTERLOCKED, "ccb_scanq", 0);
1423                 crit_exit();
1424         }
1425 }
1426
1427 /*
1428  * Issue an asynchronous asction
1429  */
1430 void
1431 xpt_action_async(union ccb *ccb)
1432 {
1433         xpt_lock_buses();
1434         TAILQ_INSERT_TAIL(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
1435         if (xsoftc.ccb_scanq_running == 0) {
1436                 xsoftc.ccb_scanq_running = 1;
1437                 wakeup(&xsoftc.ccb_scanq);
1438         }
1439         xpt_unlock_buses();
1440 }
1441
1442
1443 /* Functions accessed by the peripheral drivers */
1444 static int
1445 xpt_init(void *dummy)
1446 {
1447         struct cam_sim *xpt_sim;
1448         struct cam_path *path;
1449         struct cam_devq *devq;
1450         cam_status status;
1451
1452         TAILQ_INIT(&xsoftc.xpt_busses);
1453         TAILQ_INIT(&cam_simq);
1454         TAILQ_INIT(&xsoftc.ccb_scanq);
1455         STAILQ_INIT(&xsoftc.highpowerq);
1456         xsoftc.num_highpower = CAM_MAX_HIGHPOWER;
1457
1458         spin_init(&cam_simq_spin);
1459         lockinit(&xsoftc.xpt_lock, "XPT lock", 0, LK_CANRECURSE);
1460         lockinit(&xsoftc.xpt_topo_lock, "XPT topology lock", 0, LK_CANRECURSE);
1461
1462         SLIST_INIT(&cam_dead_sim.ccb_freeq);
1463         TAILQ_INIT(&cam_dead_sim.sim_doneq);
1464         spin_init(&cam_dead_sim.sim_spin);
1465         cam_dead_sim.sim_action = dead_sim_action;
1466         cam_dead_sim.sim_poll = dead_sim_poll;
1467         cam_dead_sim.sim_name = "dead_sim";
1468         cam_dead_sim.lock = &cam_dead_lock;
1469         lockinit(&cam_dead_lock, "XPT dead_sim lock", 0, LK_CANRECURSE);
1470         cam_dead_sim.flags |= CAM_SIM_DEREGISTERED;
1471
1472         /*
1473          * The xpt layer is, itself, the equivelent of a SIM.
1474          * Allow 16 ccbs in the ccb pool for it.  This should
1475          * give decent parallelism when we probe busses and
1476          * perform other XPT functions.
1477          */
1478         devq = cam_simq_alloc(16);
1479         xpt_sim = cam_sim_alloc(xptaction,
1480                                 xptpoll,
1481                                 "xpt",
1482                                 /*softc*/NULL,
1483                                 /*unit*/0,
1484                                 /*lock*/&xsoftc.xpt_lock,
1485                                 /*max_dev_transactions*/0,
1486                                 /*max_tagged_dev_transactions*/0,
1487                                 devq);
1488         cam_simq_release(devq);
1489         if (xpt_sim == NULL)
1490                 return (ENOMEM);
1491
1492         xpt_sim->max_ccbs = 16;
1493
1494         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
1495         if ((status = xpt_bus_register(xpt_sim, /*bus #*/0)) != CAM_SUCCESS) {
1496                 kprintf("xpt_init: xpt_bus_register failed with status %#x,"
1497                        " failing attach\n", status);
1498                 return (EINVAL);
1499         }
1500
1501         /*
1502          * Looking at the XPT from the SIM layer, the XPT is
1503          * the equivelent of a peripheral driver.  Allocate
1504          * a peripheral driver entry for us.
1505          */
1506         if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
1507                                       CAM_TARGET_WILDCARD,
1508                                       CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
1509                 kprintf("xpt_init: xpt_create_path failed with status %#x,"
1510                        " failing attach\n", status);
1511                 return (EINVAL);
1512         }
1513
1514         cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
1515                          path, NULL, 0, xpt_sim);
1516         xpt_free_path(path);
1517
1518         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
1519
1520         /*
1521          * Register a callback for when interrupts are enabled.
1522          */
1523         xsoftc.xpt_config_hook = kmalloc(sizeof(struct intr_config_hook),
1524                                   M_CAMXPT, M_INTWAIT | M_ZERO);
1525         xsoftc.xpt_config_hook->ich_func = xpt_config;
1526         xsoftc.xpt_config_hook->ich_desc = "xpt";
1527         xsoftc.xpt_config_hook->ich_order = 1000;
1528         if (config_intrhook_establish(xsoftc.xpt_config_hook) != 0) {
1529                 kfree (xsoftc.xpt_config_hook, M_CAMXPT);
1530                 kprintf("xpt_init: config_intrhook_establish failed "
1531                        "- failing attach\n");
1532         }
1533
1534         /* fire up rescan thread */
1535         if (kthread_create(xpt_scanner_thread, NULL, NULL, "xpt_thrd")) {
1536                 kprintf("xpt_init: failed to create rescan thread\n");
1537         }
1538         /* Install our software interrupt handlers */
1539         register_swi(SWI_CAMBIO, swi_cambio, NULL, "swi_cambio", NULL);
1540
1541         return (0);
1542 }
1543
1544 static cam_status
1545 xptregister(struct cam_periph *periph, void *arg)
1546 {
1547         struct cam_sim *xpt_sim;
1548
1549         if (periph == NULL) {
1550                 kprintf("xptregister: periph was NULL!!\n");
1551                 return(CAM_REQ_CMP_ERR);
1552         }
1553
1554         xpt_sim = (struct cam_sim *)arg;
1555         xpt_sim->softc = periph;
1556         xpt_periph = periph;
1557         periph->softc = NULL;
1558
1559         return(CAM_REQ_CMP);
1560 }
1561
1562 int32_t
1563 xpt_add_periph(struct cam_periph *periph)
1564 {
1565         struct cam_ed *device;
1566         int32_t  status;
1567         struct periph_list *periph_head;
1568
1569         sim_lock_assert_owned(periph->sim->lock);
1570
1571         device = periph->path->device;
1572
1573         periph_head = &device->periphs;
1574
1575         status = CAM_REQ_CMP;
1576
1577         if (device != NULL) {
1578                 /*
1579                  * Make room for this peripheral
1580                  * so it will fit in the queue
1581                  * when it's scheduled to run
1582                  */
1583                 status = camq_resize(&device->drvq,
1584                                      device->drvq.array_size + 1);
1585
1586                 device->generation++;
1587
1588                 SLIST_INSERT_HEAD(periph_head, periph, periph_links);
1589         }
1590
1591         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1592         xsoftc.xpt_generation++;
1593         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1594
1595         return (status);
1596 }
1597
1598 void
1599 xpt_remove_periph(struct cam_periph *periph)
1600 {
1601         struct cam_ed *device;
1602
1603         sim_lock_assert_owned(periph->sim->lock);
1604
1605         device = periph->path->device;
1606
1607         if (device != NULL) {
1608                 struct periph_list *periph_head;
1609
1610                 periph_head = &device->periphs;
1611
1612                 /* Release the slot for this peripheral */
1613                 camq_resize(&device->drvq, device->drvq.array_size - 1);
1614
1615                 device->generation++;
1616
1617                 SLIST_REMOVE(periph_head, periph, cam_periph, periph_links);
1618         }
1619
1620         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
1621         xsoftc.xpt_generation++;
1622         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
1623 }
1624
1625 void
1626 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1627 {
1628         struct  ccb_pathinq cpi;
1629         struct  ccb_trans_settings cts;
1630         struct  cam_path *path;
1631         u_int   speed;
1632         u_int   freq;
1633         u_int   mb;
1634
1635         sim_lock_assert_owned(periph->sim->lock);
1636
1637         path = periph->path;
1638
1639         /* Report basic attachment and inquiry data */
1640         kprintf("%s%d at %s%d bus %d target %d lun %d\n",
1641                periph->periph_name, periph->unit_number,
1642                path->bus->sim->sim_name,
1643                path->bus->sim->unit_number,
1644                path->bus->sim->bus_id,
1645                path->target->target_id,
1646                path->device->lun_id);
1647         kprintf("%s%d: ", periph->periph_name, periph->unit_number);
1648         scsi_print_inquiry(&path->device->inq_data);
1649
1650         /* Report serial number */
1651         if (path->device->serial_num_len > 0) {
1652                 /* Don't wrap the screen  - print only the first 60 chars */
1653                 kprintf("%s%d: Serial Number %.60s\n", periph->periph_name,
1654                        periph->unit_number, path->device->serial_num);
1655         }
1656
1657         /* Acquire and report transfer speed */
1658         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
1659         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1660         cts.type = CTS_TYPE_CURRENT_SETTINGS;
1661         xpt_action((union ccb*)&cts);
1662         if ((cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1663                 return;
1664         }
1665
1666         /* Ask the SIM for its base transfer speed */
1667         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
1668         cpi.ccb_h.func_code = XPT_PATH_INQ;
1669         xpt_action((union ccb *)&cpi);
1670
1671         speed = cpi.base_transfer_speed;
1672         freq = 0;
1673         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SPI) {
1674                 struct  ccb_trans_settings_spi *spi;
1675
1676                 spi = &cts.xport_specific.spi;
1677                 if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0
1678                   && spi->sync_offset != 0) {
1679                         freq = scsi_calc_syncsrate(spi->sync_period);
1680                         speed = freq;
1681                 }
1682
1683                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
1684                         speed *= (0x01 << spi->bus_width);
1685         }
1686         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_FC) {
1687                 struct  ccb_trans_settings_fc *fc = &cts.xport_specific.fc;
1688                 if (fc->valid & CTS_FC_VALID_SPEED) {
1689                         speed = fc->bitrate;
1690                 }
1691         }
1692
1693         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SAS) {
1694                 struct  ccb_trans_settings_sas *sas = &cts.xport_specific.sas;
1695                 if (sas->valid & CTS_SAS_VALID_SPEED) {
1696                         speed = sas->bitrate;
1697                 }
1698         }
1699
1700         mb = speed / 1000;
1701         if (mb > 0)
1702                 kprintf("%s%d: %d.%03dMB/s transfers",
1703                        periph->periph_name, periph->unit_number,
1704                        mb, speed % 1000);
1705         else
1706                 kprintf("%s%d: %dKB/s transfers", periph->periph_name,
1707                        periph->unit_number, speed);
1708
1709         /* Report additional information about SPI connections */
1710         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SPI) {
1711                 struct  ccb_trans_settings_spi *spi;
1712
1713                 spi = &cts.xport_specific.spi;
1714                 if (freq != 0) {
1715                         kprintf(" (%d.%03dMHz%s, offset %d", freq / 1000,
1716                                freq % 1000,
1717                                (spi->ppr_options & MSG_EXT_PPR_DT_REQ) != 0
1718                              ? " DT" : "",
1719                                spi->sync_offset);
1720                 }
1721                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0
1722                  && spi->bus_width > 0) {
1723                         if (freq != 0) {
1724                                 kprintf(", ");
1725                         } else {
1726                                 kprintf(" (");
1727                         }
1728                         kprintf("%dbit)", 8 * (0x01 << spi->bus_width));
1729                 } else if (freq != 0) {
1730                         kprintf(")");
1731                 }
1732         }
1733         if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_FC) {
1734                 struct  ccb_trans_settings_fc *fc;
1735
1736                 fc = &cts.xport_specific.fc;
1737                 if (fc->valid & CTS_FC_VALID_WWNN)
1738                         kprintf(" WWNN 0x%llx", (long long) fc->wwnn);
1739                 if (fc->valid & CTS_FC_VALID_WWPN)
1740                         kprintf(" WWPN 0x%llx", (long long) fc->wwpn);
1741                 if (fc->valid & CTS_FC_VALID_PORT)
1742                         kprintf(" PortID 0x%x", fc->port);
1743         }
1744
1745         if (path->device->inq_flags & SID_CmdQue
1746          || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1747                 kprintf("\n%s%d: Command Queueing Enabled",
1748                        periph->periph_name, periph->unit_number);
1749         }
1750         kprintf("\n");
1751
1752         /*
1753          * We only want to print the caller's announce string if they've
1754          * passed one in..
1755          */
1756         if (announce_string != NULL)
1757                 kprintf("%s%d: %s\n", periph->periph_name,
1758                        periph->unit_number, announce_string);
1759 }
1760
1761 static dev_match_ret
1762 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1763             struct cam_eb *bus)
1764 {
1765         dev_match_ret retval;
1766         int i;
1767
1768         retval = DM_RET_NONE;
1769
1770         /*
1771          * If we aren't given something to match against, that's an error.
1772          */
1773         if (bus == NULL)
1774                 return(DM_RET_ERROR);
1775
1776         /*
1777          * If there are no match entries, then this bus matches no
1778          * matter what.
1779          */
1780         if ((patterns == NULL) || (num_patterns == 0))
1781                 return(DM_RET_DESCEND | DM_RET_COPY);
1782
1783         for (i = 0; i < num_patterns; i++) {
1784                 struct bus_match_pattern *cur_pattern;
1785
1786                 /*
1787                  * If the pattern in question isn't for a bus node, we
1788                  * aren't interested.  However, we do indicate to the
1789                  * calling routine that we should continue descending the
1790                  * tree, since the user wants to match against lower-level
1791                  * EDT elements.
1792                  */
1793                 if (patterns[i].type != DEV_MATCH_BUS) {
1794                         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1795                                 retval |= DM_RET_DESCEND;
1796                         continue;
1797                 }
1798
1799                 cur_pattern = &patterns[i].pattern.bus_pattern;
1800
1801                 /*
1802                  * If they want to match any bus node, we give them any
1803                  * device node.
1804                  */
1805                 if (cur_pattern->flags == BUS_MATCH_ANY) {
1806                         /* set the copy flag */
1807                         retval |= DM_RET_COPY;
1808
1809                         /*
1810                          * If we've already decided on an action, go ahead
1811                          * and return.
1812                          */
1813                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1814                                 return(retval);
1815                 }
1816
1817                 /*
1818                  * Not sure why someone would do this...
1819                  */
1820                 if (cur_pattern->flags == BUS_MATCH_NONE)
1821                         continue;
1822
1823                 if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1824                  && (cur_pattern->path_id != bus->path_id))
1825                         continue;
1826
1827                 if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1828                  && (cur_pattern->bus_id != bus->sim->bus_id))
1829                         continue;
1830
1831                 if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1832                  && (cur_pattern->unit_number != bus->sim->unit_number))
1833                         continue;
1834
1835                 if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1836                  && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1837                              DEV_IDLEN) != 0))
1838                         continue;
1839
1840                 /*
1841                  * If we get to this point, the user definitely wants
1842                  * information on this bus.  So tell the caller to copy the
1843                  * data out.
1844                  */
1845                 retval |= DM_RET_COPY;
1846
1847                 /*
1848                  * If the return action has been set to descend, then we
1849                  * know that we've already seen a non-bus matching
1850                  * expression, therefore we need to further descend the tree.
1851                  * This won't change by continuing around the loop, so we
1852                  * go ahead and return.  If we haven't seen a non-bus
1853                  * matching expression, we keep going around the loop until
1854                  * we exhaust the matching expressions.  We'll set the stop
1855                  * flag once we fall out of the loop.
1856                  */
1857                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1858                         return(retval);
1859         }
1860
1861         /*
1862          * If the return action hasn't been set to descend yet, that means
1863          * we haven't seen anything other than bus matching patterns.  So
1864          * tell the caller to stop descending the tree -- the user doesn't
1865          * want to match against lower level tree elements.
1866          */
1867         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1868                 retval |= DM_RET_STOP;
1869
1870         return(retval);
1871 }
1872
1873 static dev_match_ret
1874 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1875                struct cam_ed *device)
1876 {
1877         dev_match_ret retval;
1878         int i;
1879
1880         retval = DM_RET_NONE;
1881
1882         /*
1883          * If we aren't given something to match against, that's an error.
1884          */
1885         if (device == NULL)
1886                 return(DM_RET_ERROR);
1887
1888         /*
1889          * If there are no match entries, then this device matches no
1890          * matter what.
1891          */
1892         if ((patterns == NULL) || (num_patterns == 0))
1893                 return(DM_RET_DESCEND | DM_RET_COPY);
1894
1895         for (i = 0; i < num_patterns; i++) {
1896                 struct device_match_pattern *cur_pattern;
1897
1898                 /*
1899                  * If the pattern in question isn't for a device node, we
1900                  * aren't interested.
1901                  */
1902                 if (patterns[i].type != DEV_MATCH_DEVICE) {
1903                         if ((patterns[i].type == DEV_MATCH_PERIPH)
1904                          && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1905                                 retval |= DM_RET_DESCEND;
1906                         continue;
1907                 }
1908
1909                 cur_pattern = &patterns[i].pattern.device_pattern;
1910
1911                 /*
1912                  * If they want to match any device node, we give them any
1913                  * device node.
1914                  */
1915                 if (cur_pattern->flags == DEV_MATCH_ANY) {
1916                         /* set the copy flag */
1917                         retval |= DM_RET_COPY;
1918
1919
1920                         /*
1921                          * If we've already decided on an action, go ahead
1922                          * and return.
1923                          */
1924                         if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1925                                 return(retval);
1926                 }
1927
1928                 /*
1929                  * Not sure why someone would do this...
1930                  */
1931                 if (cur_pattern->flags == DEV_MATCH_NONE)
1932                         continue;
1933
1934                 if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1935                  && (cur_pattern->path_id != device->target->bus->path_id))
1936                         continue;
1937
1938                 if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1939                  && (cur_pattern->target_id != device->target->target_id))
1940                         continue;
1941
1942                 if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1943                  && (cur_pattern->target_lun != device->lun_id))
1944                         continue;
1945
1946                 if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1947                  && (cam_quirkmatch((caddr_t)&device->inq_data,
1948                                     (caddr_t)&cur_pattern->inq_pat,
1949                                     1, sizeof(cur_pattern->inq_pat),
1950                                     scsi_static_inquiry_match) == NULL))
1951                         continue;
1952
1953                 /*
1954                  * If we get to this point, the user definitely wants
1955                  * information on this device.  So tell the caller to copy
1956                  * the data out.
1957                  */
1958                 retval |= DM_RET_COPY;
1959
1960                 /*
1961                  * If the return action has been set to descend, then we
1962                  * know that we've already seen a peripheral matching
1963                  * expression, therefore we need to further descend the tree.
1964                  * This won't change by continuing around the loop, so we
1965                  * go ahead and return.  If we haven't seen a peripheral
1966                  * matching expression, we keep going around the loop until
1967                  * we exhaust the matching expressions.  We'll set the stop
1968                  * flag once we fall out of the loop.
1969                  */
1970                 if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1971                         return(retval);
1972         }
1973
1974         /*
1975          * If the return action hasn't been set to descend yet, that means
1976          * we haven't seen any peripheral matching patterns.  So tell the
1977          * caller to stop descending the tree -- the user doesn't want to
1978          * match against lower level tree elements.
1979          */
1980         if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1981                 retval |= DM_RET_STOP;
1982
1983         return(retval);
1984 }
1985
1986 /*
1987  * Match a single peripheral against any number of match patterns.
1988  */
1989 static dev_match_ret
1990 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1991                struct cam_periph *periph)
1992 {
1993         dev_match_ret retval;
1994         int i;
1995
1996         /*
1997          * If we aren't given something to match against, that's an error.
1998          */
1999         if (periph == NULL)
2000                 return(DM_RET_ERROR);
2001
2002         /*
2003          * If there are no match entries, then this peripheral matches no
2004          * matter what.
2005          */
2006         if ((patterns == NULL) || (num_patterns == 0))
2007                 return(DM_RET_STOP | DM_RET_COPY);
2008
2009         /*
2010          * There aren't any nodes below a peripheral node, so there's no
2011          * reason to descend the tree any further.
2012          */
2013         retval = DM_RET_STOP;
2014
2015         for (i = 0; i < num_patterns; i++) {
2016                 struct periph_match_pattern *cur_pattern;
2017
2018                 /*
2019                  * If the pattern in question isn't for a peripheral, we
2020                  * aren't interested.
2021                  */
2022                 if (patterns[i].type != DEV_MATCH_PERIPH)
2023                         continue;
2024
2025                 cur_pattern = &patterns[i].pattern.periph_pattern;
2026
2027                 /*
2028                  * If they want to match on anything, then we will do so.
2029                  */
2030                 if (cur_pattern->flags == PERIPH_MATCH_ANY) {
2031                         /* set the copy flag */
2032                         retval |= DM_RET_COPY;
2033
2034                         /*
2035                          * We've already set the return action to stop,
2036                          * since there are no nodes below peripherals in
2037                          * the tree.
2038                          */
2039                         return(retval);
2040                 }
2041
2042                 /*
2043                  * Not sure why someone would do this...
2044                  */
2045                 if (cur_pattern->flags == PERIPH_MATCH_NONE)
2046                         continue;
2047
2048                 if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
2049                  && (cur_pattern->path_id != periph->path->bus->path_id))
2050                         continue;
2051
2052                 /*
2053                  * For the target and lun id's, we have to make sure the
2054                  * target and lun pointers aren't NULL.  The xpt peripheral
2055                  * has a wildcard target and device.
2056                  */
2057                 if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
2058                  && ((periph->path->target == NULL)
2059                  ||(cur_pattern->target_id != periph->path->target->target_id)))
2060                         continue;
2061
2062                 if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
2063                  && ((periph->path->device == NULL)
2064                  || (cur_pattern->target_lun != periph->path->device->lun_id)))
2065                         continue;
2066
2067                 if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
2068                  && (cur_pattern->unit_number != periph->unit_number))
2069                         continue;
2070
2071                 if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
2072                  && (strncmp(cur_pattern->periph_name, periph->periph_name,
2073                              DEV_IDLEN) != 0))
2074                         continue;
2075
2076                 /*
2077                  * If we get to this point, the user definitely wants
2078                  * information on this peripheral.  So tell the caller to
2079                  * copy the data out.
2080                  */
2081                 retval |= DM_RET_COPY;
2082
2083                 /*
2084                  * The return action has already been set to stop, since
2085                  * peripherals don't have any nodes below them in the EDT.
2086                  */
2087                 return(retval);
2088         }
2089
2090         /*
2091          * If we get to this point, the peripheral that was passed in
2092          * doesn't match any of the patterns.
2093          */
2094         return(retval);
2095 }
2096
2097 static int
2098 xptedtbusfunc(struct cam_eb *bus, void *arg)
2099 {
2100         struct ccb_dev_match *cdm;
2101         dev_match_ret retval;
2102
2103         cdm = (struct ccb_dev_match *)arg;
2104
2105         /*
2106          * If our position is for something deeper in the tree, that means
2107          * that we've already seen this node.  So, we keep going down.
2108          */
2109         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2110          && (cdm->pos.cookie.bus == bus)
2111          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2112          && (cdm->pos.cookie.target != NULL))
2113                 retval = DM_RET_DESCEND;
2114         else
2115                 retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
2116
2117         /*
2118          * If we got an error, bail out of the search.
2119          */
2120         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2121                 cdm->status = CAM_DEV_MATCH_ERROR;
2122                 return(0);
2123         }
2124
2125         /*
2126          * If the copy flag is set, copy this bus out.
2127          */
2128         if (retval & DM_RET_COPY) {
2129                 int spaceleft, j;
2130
2131                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2132                         sizeof(struct dev_match_result));
2133
2134                 /*
2135                  * If we don't have enough space to put in another
2136                  * match result, save our position and tell the
2137                  * user there are more devices to check.
2138                  */
2139                 if (spaceleft < sizeof(struct dev_match_result)) {
2140                         bzero(&cdm->pos, sizeof(cdm->pos));
2141                         cdm->pos.position_type =
2142                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
2143
2144                         cdm->pos.cookie.bus = bus;
2145                         cdm->pos.generations[CAM_BUS_GENERATION]=
2146                                 xsoftc.bus_generation;
2147                         cdm->status = CAM_DEV_MATCH_MORE;
2148                         return(0);
2149                 }
2150                 j = cdm->num_matches;
2151                 cdm->num_matches++;
2152                 cdm->matches[j].type = DEV_MATCH_BUS;
2153                 cdm->matches[j].result.bus_result.path_id = bus->path_id;
2154                 cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
2155                 cdm->matches[j].result.bus_result.unit_number =
2156                         bus->sim->unit_number;
2157                 strncpy(cdm->matches[j].result.bus_result.dev_name,
2158                         bus->sim->sim_name, DEV_IDLEN);
2159         }
2160
2161         /*
2162          * If the user is only interested in busses, there's no
2163          * reason to descend to the next level in the tree.
2164          */
2165         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2166                 return(1);
2167
2168         /*
2169          * If there is a target generation recorded, check it to
2170          * make sure the target list hasn't changed.
2171          */
2172         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2173          && (bus == cdm->pos.cookie.bus)
2174          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2175          && (cdm->pos.generations[CAM_TARGET_GENERATION] != 0)
2176          && (cdm->pos.generations[CAM_TARGET_GENERATION] !=
2177              bus->generation)) {
2178                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2179                 return(0);
2180         }
2181
2182         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2183          && (cdm->pos.cookie.bus == bus)
2184          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2185          && (cdm->pos.cookie.target != NULL))
2186                 return(xpttargettraverse(bus,
2187                                         (struct cam_et *)cdm->pos.cookie.target,
2188                                          xptedttargetfunc, arg));
2189         else
2190                 return(xpttargettraverse(bus, NULL, xptedttargetfunc, arg));
2191 }
2192
2193 static int
2194 xptedttargetfunc(struct cam_et *target, void *arg)
2195 {
2196         struct ccb_dev_match *cdm;
2197
2198         cdm = (struct ccb_dev_match *)arg;
2199
2200         /*
2201          * If there is a device list generation recorded, check it to
2202          * make sure the device list hasn't changed.
2203          */
2204         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2205          && (cdm->pos.cookie.bus == target->bus)
2206          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2207          && (cdm->pos.cookie.target == target)
2208          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2209          && (cdm->pos.generations[CAM_DEV_GENERATION] != 0)
2210          && (cdm->pos.generations[CAM_DEV_GENERATION] !=
2211              target->generation)) {
2212                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2213                 return(0);
2214         }
2215
2216         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2217          && (cdm->pos.cookie.bus == target->bus)
2218          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2219          && (cdm->pos.cookie.target == target)
2220          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2221          && (cdm->pos.cookie.device != NULL))
2222                 return(xptdevicetraverse(target,
2223                                         (struct cam_ed *)cdm->pos.cookie.device,
2224                                          xptedtdevicefunc, arg));
2225         else
2226                 return(xptdevicetraverse(target, NULL, xptedtdevicefunc, arg));
2227 }
2228
2229 static int
2230 xptedtdevicefunc(struct cam_ed *device, void *arg)
2231 {
2232
2233         struct ccb_dev_match *cdm;
2234         dev_match_ret retval;
2235
2236         cdm = (struct ccb_dev_match *)arg;
2237
2238         /*
2239          * If our position is for something deeper in the tree, that means
2240          * that we've already seen this node.  So, we keep going down.
2241          */
2242         if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2243          && (cdm->pos.cookie.device == device)
2244          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2245          && (cdm->pos.cookie.periph != NULL))
2246                 retval = DM_RET_DESCEND;
2247         else
2248                 retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
2249                                         device);
2250
2251         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2252                 cdm->status = CAM_DEV_MATCH_ERROR;
2253                 return(0);
2254         }
2255
2256         /*
2257          * If the copy flag is set, copy this device out.
2258          */
2259         if (retval & DM_RET_COPY) {
2260                 int spaceleft, j;
2261
2262                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2263                         sizeof(struct dev_match_result));
2264
2265                 /*
2266                  * If we don't have enough space to put in another
2267                  * match result, save our position and tell the
2268                  * user there are more devices to check.
2269                  */
2270                 if (spaceleft < sizeof(struct dev_match_result)) {
2271                         bzero(&cdm->pos, sizeof(cdm->pos));
2272                         cdm->pos.position_type =
2273                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2274                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
2275
2276                         cdm->pos.cookie.bus = device->target->bus;
2277                         cdm->pos.generations[CAM_BUS_GENERATION]=
2278                                 xsoftc.bus_generation;
2279                         cdm->pos.cookie.target = device->target;
2280                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2281                                 device->target->bus->generation;
2282                         cdm->pos.cookie.device = device;
2283                         cdm->pos.generations[CAM_DEV_GENERATION] =
2284                                 device->target->generation;
2285                         cdm->status = CAM_DEV_MATCH_MORE;
2286                         return(0);
2287                 }
2288                 j = cdm->num_matches;
2289                 cdm->num_matches++;
2290                 cdm->matches[j].type = DEV_MATCH_DEVICE;
2291                 cdm->matches[j].result.device_result.path_id =
2292                         device->target->bus->path_id;
2293                 cdm->matches[j].result.device_result.target_id =
2294                         device->target->target_id;
2295                 cdm->matches[j].result.device_result.target_lun =
2296                         device->lun_id;
2297                 bcopy(&device->inq_data,
2298                       &cdm->matches[j].result.device_result.inq_data,
2299                       sizeof(struct scsi_inquiry_data));
2300
2301                 /* Let the user know whether this device is unconfigured */
2302                 if (device->flags & CAM_DEV_UNCONFIGURED)
2303                         cdm->matches[j].result.device_result.flags =
2304                                 DEV_RESULT_UNCONFIGURED;
2305                 else
2306                         cdm->matches[j].result.device_result.flags =
2307                                 DEV_RESULT_NOFLAG;
2308         }
2309
2310         /*
2311          * If the user isn't interested in peripherals, don't descend
2312          * the tree any further.
2313          */
2314         if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
2315                 return(1);
2316
2317         /*
2318          * If there is a peripheral list generation recorded, make sure
2319          * it hasn't changed.
2320          */
2321         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2322          && (device->target->bus == cdm->pos.cookie.bus)
2323          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2324          && (device->target == cdm->pos.cookie.target)
2325          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2326          && (device == cdm->pos.cookie.device)
2327          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2328          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2329          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2330              device->generation)){
2331                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2332                 return(0);
2333         }
2334
2335         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2336          && (cdm->pos.cookie.bus == device->target->bus)
2337          && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
2338          && (cdm->pos.cookie.target == device->target)
2339          && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
2340          && (cdm->pos.cookie.device == device)
2341          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2342          && (cdm->pos.cookie.periph != NULL))
2343                 return(xptperiphtraverse(device,
2344                                 (struct cam_periph *)cdm->pos.cookie.periph,
2345                                 xptedtperiphfunc, arg));
2346         else
2347                 return(xptperiphtraverse(device, NULL, xptedtperiphfunc, arg));
2348 }
2349
2350 static int
2351 xptedtperiphfunc(struct cam_periph *periph, void *arg)
2352 {
2353         struct ccb_dev_match *cdm;
2354         dev_match_ret retval;
2355
2356         cdm = (struct ccb_dev_match *)arg;
2357
2358         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2359
2360         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2361                 cdm->status = CAM_DEV_MATCH_ERROR;
2362                 return(0);
2363         }
2364
2365         /*
2366          * If the copy flag is set, copy this peripheral out.
2367          */
2368         if (retval & DM_RET_COPY) {
2369                 int spaceleft, j;
2370
2371                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2372                         sizeof(struct dev_match_result));
2373
2374                 /*
2375                  * If we don't have enough space to put in another
2376                  * match result, save our position and tell the
2377                  * user there are more devices to check.
2378                  */
2379                 if (spaceleft < sizeof(struct dev_match_result)) {
2380                         bzero(&cdm->pos, sizeof(cdm->pos));
2381                         cdm->pos.position_type =
2382                                 CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
2383                                 CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
2384                                 CAM_DEV_POS_PERIPH;
2385
2386                         cdm->pos.cookie.bus = periph->path->bus;
2387                         cdm->pos.generations[CAM_BUS_GENERATION]=
2388                                 xsoftc.bus_generation;
2389                         cdm->pos.cookie.target = periph->path->target;
2390                         cdm->pos.generations[CAM_TARGET_GENERATION] =
2391                                 periph->path->bus->generation;
2392                         cdm->pos.cookie.device = periph->path->device;
2393                         cdm->pos.generations[CAM_DEV_GENERATION] =
2394                                 periph->path->target->generation;
2395                         cdm->pos.cookie.periph = periph;
2396                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2397                                 periph->path->device->generation;
2398                         cdm->status = CAM_DEV_MATCH_MORE;
2399                         return(0);
2400                 }
2401
2402                 j = cdm->num_matches;
2403                 cdm->num_matches++;
2404                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2405                 cdm->matches[j].result.periph_result.path_id =
2406                         periph->path->bus->path_id;
2407                 cdm->matches[j].result.periph_result.target_id =
2408                         periph->path->target->target_id;
2409                 cdm->matches[j].result.periph_result.target_lun =
2410                         periph->path->device->lun_id;
2411                 cdm->matches[j].result.periph_result.unit_number =
2412                         periph->unit_number;
2413                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2414                         periph->periph_name, DEV_IDLEN);
2415         }
2416
2417         return(1);
2418 }
2419
2420 static int
2421 xptedtmatch(struct ccb_dev_match *cdm)
2422 {
2423         int ret;
2424
2425         cdm->num_matches = 0;
2426
2427         /*
2428          * Check the bus list generation.  If it has changed, the user
2429          * needs to reset everything and start over.
2430          */
2431         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2432          && (cdm->pos.generations[CAM_BUS_GENERATION] != 0)
2433          && (cdm->pos.generations[CAM_BUS_GENERATION] != xsoftc.bus_generation)) {
2434                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2435                 return(0);
2436         }
2437
2438         if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2439          && (cdm->pos.cookie.bus != NULL))
2440                 ret = xptbustraverse((struct cam_eb *)cdm->pos.cookie.bus,
2441                                      xptedtbusfunc, cdm);
2442         else
2443                 ret = xptbustraverse(NULL, xptedtbusfunc, cdm);
2444
2445         /*
2446          * If we get back 0, that means that we had to stop before fully
2447          * traversing the EDT.  It also means that one of the subroutines
2448          * has set the status field to the proper value.  If we get back 1,
2449          * we've fully traversed the EDT and copied out any matching entries.
2450          */
2451         if (ret == 1)
2452                 cdm->status = CAM_DEV_MATCH_LAST;
2453
2454         return(ret);
2455 }
2456
2457 static int
2458 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
2459 {
2460         struct ccb_dev_match *cdm;
2461
2462         cdm = (struct ccb_dev_match *)arg;
2463
2464         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2465          && (cdm->pos.cookie.pdrv == pdrv)
2466          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2467          && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
2468          && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2469              (*pdrv)->generation)) {
2470                 cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2471                 return(0);
2472         }
2473
2474         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2475          && (cdm->pos.cookie.pdrv == pdrv)
2476          && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2477          && (cdm->pos.cookie.periph != NULL))
2478                 return(xptpdperiphtraverse(pdrv,
2479                                 (struct cam_periph *)cdm->pos.cookie.periph,
2480                                 xptplistperiphfunc, arg));
2481         else
2482                 return(xptpdperiphtraverse(pdrv, NULL,xptplistperiphfunc, arg));
2483 }
2484
2485 static int
2486 xptplistperiphfunc(struct cam_periph *periph, void *arg)
2487 {
2488         struct ccb_dev_match *cdm;
2489         dev_match_ret retval;
2490
2491         cdm = (struct ccb_dev_match *)arg;
2492
2493         retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2494
2495         if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2496                 cdm->status = CAM_DEV_MATCH_ERROR;
2497                 return(0);
2498         }
2499
2500         /*
2501          * If the copy flag is set, copy this peripheral out.
2502          */
2503         if (retval & DM_RET_COPY) {
2504                 int spaceleft, j;
2505
2506                 spaceleft = cdm->match_buf_len - (cdm->num_matches *
2507                         sizeof(struct dev_match_result));
2508
2509                 /*
2510                  * If we don't have enough space to put in another
2511                  * match result, save our position and tell the
2512                  * user there are more devices to check.
2513                  */
2514                 if (spaceleft < sizeof(struct dev_match_result)) {
2515                         struct periph_driver **pdrv;
2516
2517                         pdrv = NULL;
2518                         bzero(&cdm->pos, sizeof(cdm->pos));
2519                         cdm->pos.position_type =
2520                                 CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2521                                 CAM_DEV_POS_PERIPH;
2522
2523                         /*
2524                          * This may look a bit non-sensical, but it is
2525                          * actually quite logical.  There are very few
2526                          * peripheral drivers, and bloating every peripheral
2527                          * structure with a pointer back to its parent
2528                          * peripheral driver linker set entry would cost
2529                          * more in the long run than doing this quick lookup.
2530                          */
2531                         for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
2532                                 if (strcmp((*pdrv)->driver_name,
2533                                     periph->periph_name) == 0)
2534                                         break;
2535                         }
2536
2537                         if (*pdrv == NULL) {
2538                                 cdm->status = CAM_DEV_MATCH_ERROR;
2539                                 return(0);
2540                         }
2541
2542                         cdm->pos.cookie.pdrv = pdrv;
2543                         /*
2544                          * The periph generation slot does double duty, as
2545                          * does the periph pointer slot.  They are used for
2546                          * both edt and pdrv lookups and positioning.
2547                          */
2548                         cdm->pos.cookie.periph = periph;
2549                         cdm->pos.generations[CAM_PERIPH_GENERATION] =
2550                                 (*pdrv)->generation;
2551                         cdm->status = CAM_DEV_MATCH_MORE;
2552                         return(0);
2553                 }
2554
2555                 j = cdm->num_matches;
2556                 cdm->num_matches++;
2557                 cdm->matches[j].type = DEV_MATCH_PERIPH;
2558                 cdm->matches[j].result.periph_result.path_id =
2559                         periph->path->bus->path_id;
2560
2561                 /*
2562                  * The transport layer peripheral doesn't have a target or
2563                  * lun.
2564                  */
2565                 if (periph->path->target)
2566                         cdm->matches[j].result.periph_result.target_id =
2567                                 periph->path->target->target_id;
2568                 else
2569                         cdm->matches[j].result.periph_result.target_id = -1;
2570
2571                 if (periph->path->device)
2572                         cdm->matches[j].result.periph_result.target_lun =
2573                                 periph->path->device->lun_id;
2574                 else
2575                         cdm->matches[j].result.periph_result.target_lun = -1;
2576
2577                 cdm->matches[j].result.periph_result.unit_number =
2578                         periph->unit_number;
2579                 strncpy(cdm->matches[j].result.periph_result.periph_name,
2580                         periph->periph_name, DEV_IDLEN);
2581         }
2582
2583         return(1);
2584 }
2585
2586 static int
2587 xptperiphlistmatch(struct ccb_dev_match *cdm)
2588 {
2589         int ret;
2590
2591         cdm->num_matches = 0;
2592
2593         /*
2594          * At this point in the edt traversal function, we check the bus
2595          * list generation to make sure that no busses have been added or
2596          * removed since the user last sent a XPT_DEV_MATCH ccb through.
2597          * For the peripheral driver list traversal function, however, we
2598          * don't have to worry about new peripheral driver types coming or
2599          * going; they're in a linker set, and therefore can't change
2600          * without a recompile.
2601          */
2602
2603         if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2604          && (cdm->pos.cookie.pdrv != NULL))
2605                 ret = xptpdrvtraverse(
2606                                 (struct periph_driver **)cdm->pos.cookie.pdrv,
2607                                 xptplistpdrvfunc, cdm);
2608         else
2609                 ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2610
2611         /*
2612          * If we get back 0, that means that we had to stop before fully
2613          * traversing the peripheral driver tree.  It also means that one of
2614          * the subroutines has set the status field to the proper value.  If
2615          * we get back 1, we've fully traversed the EDT and copied out any
2616          * matching entries.
2617          */
2618         if (ret == 1)
2619                 cdm->status = CAM_DEV_MATCH_LAST;
2620
2621         return(ret);
2622 }
2623
2624 static int
2625 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2626 {
2627         struct cam_eb *bus, *next_bus;
2628         int retval;
2629
2630         retval = 1;
2631
2632         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
2633         for (bus = (start_bus ? start_bus : TAILQ_FIRST(&xsoftc.xpt_busses));
2634              bus != NULL;
2635              bus = next_bus) {
2636                 next_bus = TAILQ_NEXT(bus, links);
2637
2638                 lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
2639                 CAM_SIM_LOCK(bus->sim);
2640                 retval = tr_func(bus, arg);
2641                 CAM_SIM_UNLOCK(bus->sim);
2642                 if (retval == 0)
2643                         return(retval);
2644                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
2645         }
2646         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
2647
2648         return(retval);
2649 }
2650
2651 static int
2652 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2653                   xpt_targetfunc_t *tr_func, void *arg)
2654 {
2655         struct cam_et *target, *next_target;
2656         int retval;
2657
2658         retval = 1;
2659         for (target = (start_target ? start_target :
2660                        TAILQ_FIRST(&bus->et_entries));
2661              target != NULL; target = next_target) {
2662
2663                 next_target = TAILQ_NEXT(target, links);
2664
2665                 retval = tr_func(target, arg);
2666
2667                 if (retval == 0)
2668                         return(retval);
2669         }
2670
2671         return(retval);
2672 }
2673
2674 static int
2675 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2676                   xpt_devicefunc_t *tr_func, void *arg)
2677 {
2678         struct cam_ed *device, *next_device;
2679         int retval;
2680
2681         retval = 1;
2682         for (device = (start_device ? start_device :
2683                        TAILQ_FIRST(&target->ed_entries));
2684              device != NULL;
2685              device = next_device) {
2686
2687                 next_device = TAILQ_NEXT(device, links);
2688
2689                 retval = tr_func(device, arg);
2690
2691                 if (retval == 0)
2692                         return(retval);
2693         }
2694
2695         return(retval);
2696 }
2697
2698 static int
2699 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2700                   xpt_periphfunc_t *tr_func, void *arg)
2701 {
2702         struct cam_periph *periph, *next_periph;
2703         int retval;
2704
2705         retval = 1;
2706
2707         for (periph = (start_periph ? start_periph :
2708                        SLIST_FIRST(&device->periphs));
2709              periph != NULL;
2710              periph = next_periph) {
2711
2712                 next_periph = SLIST_NEXT(periph, periph_links);
2713
2714                 retval = tr_func(periph, arg);
2715                 if (retval == 0)
2716                         return(retval);
2717         }
2718
2719         return(retval);
2720 }
2721
2722 static int
2723 xptpdrvtraverse(struct periph_driver **start_pdrv,
2724                 xpt_pdrvfunc_t *tr_func, void *arg)
2725 {
2726         struct periph_driver **pdrv;
2727         int retval;
2728
2729         retval = 1;
2730
2731         /*
2732          * We don't traverse the peripheral driver list like we do the
2733          * other lists, because it is a linker set, and therefore cannot be
2734          * changed during runtime.  If the peripheral driver list is ever
2735          * re-done to be something other than a linker set (i.e. it can
2736          * change while the system is running), the list traversal should
2737          * be modified to work like the other traversal functions.
2738          */
2739         for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2740              *pdrv != NULL; pdrv++) {
2741                 retval = tr_func(pdrv, arg);
2742
2743                 if (retval == 0)
2744                         return(retval);
2745         }
2746
2747         return(retval);
2748 }
2749
2750 static int
2751 xptpdperiphtraverse(struct periph_driver **pdrv,
2752                     struct cam_periph *start_periph,
2753                     xpt_periphfunc_t *tr_func, void *arg)
2754 {
2755         struct cam_periph *periph, *next_periph;
2756         int retval;
2757
2758         retval = 1;
2759
2760         for (periph = (start_periph ? start_periph :
2761              TAILQ_FIRST(&(*pdrv)->units)); periph != NULL;
2762              periph = next_periph) {
2763
2764                 next_periph = TAILQ_NEXT(periph, unit_links);
2765
2766                 retval = tr_func(periph, arg);
2767                 if (retval == 0)
2768                         return(retval);
2769         }
2770         return(retval);
2771 }
2772
2773 static int
2774 xptdefbusfunc(struct cam_eb *bus, void *arg)
2775 {
2776         struct xpt_traverse_config *tr_config;
2777
2778         tr_config = (struct xpt_traverse_config *)arg;
2779
2780         if (tr_config->depth == XPT_DEPTH_BUS) {
2781                 xpt_busfunc_t *tr_func;
2782
2783                 tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2784
2785                 return(tr_func(bus, tr_config->tr_arg));
2786         } else
2787                 return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2788 }
2789
2790 static int
2791 xptdeftargetfunc(struct cam_et *target, void *arg)
2792 {
2793         struct xpt_traverse_config *tr_config;
2794
2795         tr_config = (struct xpt_traverse_config *)arg;
2796
2797         if (tr_config->depth == XPT_DEPTH_TARGET) {
2798                 xpt_targetfunc_t *tr_func;
2799
2800                 tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2801
2802                 return(tr_func(target, tr_config->tr_arg));
2803         } else
2804                 return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2805 }
2806
2807 static int
2808 xptdefdevicefunc(struct cam_ed *device, void *arg)
2809 {
2810         struct xpt_traverse_config *tr_config;
2811
2812         tr_config = (struct xpt_traverse_config *)arg;
2813
2814         if (tr_config->depth == XPT_DEPTH_DEVICE) {
2815                 xpt_devicefunc_t *tr_func;
2816
2817                 tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2818
2819                 return(tr_func(device, tr_config->tr_arg));
2820         } else
2821                 return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2822 }
2823
2824 static int
2825 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2826 {
2827         struct xpt_traverse_config *tr_config;
2828         xpt_periphfunc_t *tr_func;
2829
2830         tr_config = (struct xpt_traverse_config *)arg;
2831
2832         tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2833
2834         /*
2835          * Unlike the other default functions, we don't check for depth
2836          * here.  The peripheral driver level is the last level in the EDT,
2837          * so if we're here, we should execute the function in question.
2838          */
2839         return(tr_func(periph, tr_config->tr_arg));
2840 }
2841
2842 /*
2843  * Execute the given function for every bus in the EDT.
2844  */
2845 static int
2846 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2847 {
2848         struct xpt_traverse_config tr_config;
2849
2850         tr_config.depth = XPT_DEPTH_BUS;
2851         tr_config.tr_func = tr_func;
2852         tr_config.tr_arg = arg;
2853
2854         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2855 }
2856
2857 /*
2858  * Execute the given function for every device in the EDT.
2859  */
2860 static int
2861 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2862 {
2863         struct xpt_traverse_config tr_config;
2864
2865         tr_config.depth = XPT_DEPTH_DEVICE;
2866         tr_config.tr_func = tr_func;
2867         tr_config.tr_arg = arg;
2868
2869         return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2870 }
2871
2872 static int
2873 xptsetasyncfunc(struct cam_ed *device, void *arg)
2874 {
2875         struct cam_path path;
2876         struct ccb_getdev cgd;
2877         struct async_node *cur_entry;
2878
2879         cur_entry = (struct async_node *)arg;
2880
2881         /*
2882          * Don't report unconfigured devices (Wildcard devs,
2883          * devices only for target mode, device instances
2884          * that have been invalidated but are waiting for
2885          * their last reference count to be released).
2886          */
2887         if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2888                 return (1);
2889
2890         xpt_compile_path(&path,
2891                          NULL,
2892                          device->target->bus->path_id,
2893                          device->target->target_id,
2894                          device->lun_id);
2895         xpt_setup_ccb(&cgd.ccb_h, &path, /*priority*/1);
2896         cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2897         xpt_action((union ccb *)&cgd);
2898         cur_entry->callback(cur_entry->callback_arg,
2899                             AC_FOUND_DEVICE,
2900                             &path, &cgd);
2901         xpt_release_path(&path);
2902
2903         return(1);
2904 }
2905
2906 static int
2907 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2908 {
2909         struct cam_path path;
2910         struct ccb_pathinq cpi;
2911         struct async_node *cur_entry;
2912
2913         cur_entry = (struct async_node *)arg;
2914
2915         xpt_compile_path(&path, /*periph*/NULL,
2916                          bus->sim->path_id,
2917                          CAM_TARGET_WILDCARD,
2918                          CAM_LUN_WILDCARD);
2919         xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
2920         cpi.ccb_h.func_code = XPT_PATH_INQ;
2921         xpt_action((union ccb *)&cpi);
2922         cur_entry->callback(cur_entry->callback_arg,
2923                             AC_PATH_REGISTERED,
2924                             &path, &cpi);
2925         xpt_release_path(&path);
2926
2927         return(1);
2928 }
2929
2930 static void
2931 xpt_action_sasync_cb(void *context, int pending)
2932 {
2933         struct async_node *cur_entry;
2934         struct xpt_task *task;
2935         uint32_t added;
2936
2937         task = (struct xpt_task *)context;
2938         cur_entry = (struct async_node *)task->data1;
2939         added = task->data2;
2940
2941         if ((added & AC_FOUND_DEVICE) != 0) {
2942                 /*
2943                  * Get this peripheral up to date with all
2944                  * the currently existing devices.
2945                  */
2946                 xpt_for_all_devices(xptsetasyncfunc, cur_entry);
2947         }
2948         if ((added & AC_PATH_REGISTERED) != 0) {
2949                 /*
2950                  * Get this peripheral up to date with all
2951                  * the currently existing busses.
2952                  */
2953                 xpt_for_all_busses(xptsetasyncbusfunc, cur_entry);
2954         }
2955
2956         kfree(task, M_CAMXPT);
2957 }
2958
2959 void
2960 xpt_action(union ccb *start_ccb)
2961 {
2962         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_action\n"));
2963
2964         start_ccb->ccb_h.status = CAM_REQ_INPROG;
2965
2966         switch (start_ccb->ccb_h.func_code) {
2967         case XPT_SCSI_IO:
2968         {
2969                 struct cam_ed *device;
2970 #ifdef CAMDEBUG
2971                 char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
2972                 struct cam_path *path;
2973
2974                 path = start_ccb->ccb_h.path;
2975 #endif
2976
2977                 /*
2978                  * For the sake of compatibility with SCSI-1
2979                  * devices that may not understand the identify
2980                  * message, we include lun information in the
2981                  * second byte of all commands.  SCSI-1 specifies
2982                  * that luns are a 3 bit value and reserves only 3
2983                  * bits for lun information in the CDB.  Later
2984                  * revisions of the SCSI spec allow for more than 8
2985                  * luns, but have deprecated lun information in the
2986                  * CDB.  So, if the lun won't fit, we must omit.
2987                  *
2988                  * Also be aware that during initial probing for devices,
2989                  * the inquiry information is unknown but initialized to 0.
2990                  * This means that this code will be exercised while probing
2991                  * devices with an ANSI revision greater than 2.
2992                  */
2993                 device = start_ccb->ccb_h.path->device;
2994                 if (device->protocol_version <= SCSI_REV_2
2995                  && start_ccb->ccb_h.target_lun < 8
2996                  && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2997
2998                         start_ccb->csio.cdb_io.cdb_bytes[1] |=
2999                             start_ccb->ccb_h.target_lun << 5;
3000                 }
3001                 start_ccb->csio.scsi_status = SCSI_STATUS_OK;
3002                 CAM_DEBUG(path, CAM_DEBUG_CDB,("%s. CDB: %s\n",
3003                           scsi_op_desc(start_ccb->csio.cdb_io.cdb_bytes[0],
3004                                        &path->device->inq_data),
3005                           scsi_cdb_string(start_ccb->csio.cdb_io.cdb_bytes,
3006                                           cdb_str, sizeof(cdb_str))));
3007                 /* FALLTHROUGH */
3008         }
3009         case XPT_TARGET_IO:
3010         case XPT_CONT_TARGET_IO:
3011                 start_ccb->csio.sense_resid = 0;
3012                 start_ccb->csio.resid = 0;
3013                 /* FALLTHROUGH */
3014         case XPT_RESET_DEV:
3015         case XPT_ENG_EXEC:
3016         {
3017                 struct cam_path *path;
3018                 struct cam_sim *sim;
3019                 int runq;
3020
3021                 path = start_ccb->ccb_h.path;
3022
3023                 sim = path->bus->sim;
3024                 if (sim == &cam_dead_sim) {
3025                         /* The SIM has gone; just execute the CCB directly. */
3026                         cam_ccbq_send_ccb(&path->device->ccbq, start_ccb);
3027                         (*(sim->sim_action))(sim, start_ccb);
3028                         break;
3029                 }
3030
3031                 cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
3032                 if (path->device->qfrozen_cnt == 0)
3033                         runq = xpt_schedule_dev_sendq(path->bus, path->device);
3034                 else
3035                         runq = 0;
3036                 if (runq != 0)
3037                         xpt_run_dev_sendq(path->bus);
3038                 break;
3039         }
3040         case XPT_SET_TRAN_SETTINGS:
3041         {
3042                 xpt_set_transfer_settings(&start_ccb->cts,
3043                                           start_ccb->ccb_h.path->device,
3044                                           /*async_update*/FALSE);
3045                 break;
3046         }
3047         case XPT_CALC_GEOMETRY:
3048         {
3049                 struct cam_sim *sim;
3050
3051                 /* Filter out garbage */
3052                 if (start_ccb->ccg.block_size == 0
3053                  || start_ccb->ccg.volume_size == 0) {
3054                         start_ccb->ccg.cylinders = 0;
3055                         start_ccb->ccg.heads = 0;
3056                         start_ccb->ccg.secs_per_track = 0;
3057                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3058                         break;
3059                 }
3060                 sim = start_ccb->ccb_h.path->bus->sim;
3061                 (*(sim->sim_action))(sim, start_ccb);
3062                 break;
3063         }
3064         case XPT_ABORT:
3065         {
3066                 union ccb* abort_ccb;
3067
3068                 abort_ccb = start_ccb->cab.abort_ccb;
3069                 if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
3070
3071                         if (abort_ccb->ccb_h.pinfo.index >= 0) {
3072                                 struct cam_ccbq *ccbq;
3073
3074                                 ccbq = &abort_ccb->ccb_h.path->device->ccbq;
3075                                 cam_ccbq_remove_ccb(ccbq, abort_ccb);
3076                                 abort_ccb->ccb_h.status =
3077                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
3078                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
3079                                 xpt_done(abort_ccb);
3080                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3081                                 break;
3082                         }
3083                         if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
3084                          && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
3085                                 /*
3086                                  * We've caught this ccb en route to
3087                                  * the SIM.  Flag it for abort and the
3088                                  * SIM will do so just before starting
3089                                  * real work on the CCB.
3090                                  */
3091                                 abort_ccb->ccb_h.status =
3092                                     CAM_REQ_ABORTED|CAM_DEV_QFRZN;
3093                                 xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
3094                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3095                                 break;
3096                         }
3097                 }
3098                 if (XPT_FC_IS_QUEUED(abort_ccb)
3099                  && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
3100                         /*
3101                          * It's already completed but waiting
3102                          * for our SWI to get to it.
3103                          */
3104                         start_ccb->ccb_h.status = CAM_UA_ABORT;
3105                         break;
3106                 }
3107                 /*
3108                  * If we weren't able to take care of the abort request
3109                  * in the XPT, pass the request down to the SIM for processing.
3110                  */
3111                 /* FALLTHROUGH */
3112         }
3113         case XPT_ACCEPT_TARGET_IO:
3114         case XPT_EN_LUN:
3115         case XPT_IMMED_NOTIFY:
3116         case XPT_NOTIFY_ACK:
3117         case XPT_GET_TRAN_SETTINGS:
3118         case XPT_RESET_BUS:
3119         {
3120                 struct cam_sim *sim;
3121
3122                 sim = start_ccb->ccb_h.path->bus->sim;
3123                 (*(sim->sim_action))(sim, start_ccb);
3124                 break;
3125         }
3126         case XPT_PATH_INQ:
3127         {
3128                 struct cam_sim *sim;
3129
3130                 sim = start_ccb->ccb_h.path->bus->sim;
3131                 (*(sim->sim_action))(sim, start_ccb);
3132                 break;
3133         }
3134         case XPT_PATH_STATS:
3135                 start_ccb->cpis.last_reset =
3136                         start_ccb->ccb_h.path->bus->last_reset;
3137                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3138                 break;
3139         case XPT_GDEV_TYPE:
3140         {
3141                 struct cam_ed *dev;
3142
3143                 dev = start_ccb->ccb_h.path->device;
3144                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
3145                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3146                 } else {
3147                         struct ccb_getdev *cgd;
3148                         struct cam_eb *bus;
3149                         struct cam_et *tar;
3150
3151                         cgd = &start_ccb->cgd;
3152                         bus = cgd->ccb_h.path->bus;
3153                         tar = cgd->ccb_h.path->target;
3154                         cgd->inq_data = dev->inq_data;
3155                         cgd->ccb_h.status = CAM_REQ_CMP;
3156                         cgd->serial_num_len = dev->serial_num_len;
3157                         if ((dev->serial_num_len > 0)
3158                          && (dev->serial_num != NULL))
3159                                 bcopy(dev->serial_num, cgd->serial_num,
3160                                       dev->serial_num_len);
3161                 }
3162                 break;
3163         }
3164         case XPT_GDEV_STATS:
3165         {
3166                 struct cam_ed *dev;
3167
3168                 dev = start_ccb->ccb_h.path->device;
3169                 if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
3170                         start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3171                 } else {
3172                         struct ccb_getdevstats *cgds;
3173                         struct cam_eb *bus;
3174                         struct cam_et *tar;
3175
3176                         cgds = &start_ccb->cgds;
3177                         bus = cgds->ccb_h.path->bus;
3178                         tar = cgds->ccb_h.path->target;
3179                         cgds->dev_openings = dev->ccbq.dev_openings;
3180                         cgds->dev_active = dev->ccbq.dev_active;
3181                         cgds->devq_openings = dev->ccbq.devq_openings;
3182                         cgds->devq_queued = dev->ccbq.queue.entries;
3183                         cgds->held = dev->ccbq.held;
3184                         cgds->last_reset = tar->last_reset;
3185                         cgds->maxtags = dev->quirk->maxtags;
3186                         cgds->mintags = dev->quirk->mintags;
3187                         if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
3188                                 cgds->last_reset = bus->last_reset;
3189                         cgds->ccb_h.status = CAM_REQ_CMP;
3190                 }
3191                 break;
3192         }
3193         case XPT_GDEVLIST:
3194         {
3195                 struct cam_periph       *nperiph;
3196                 struct periph_list      *periph_head;
3197                 struct ccb_getdevlist   *cgdl;
3198                 u_int                   i;
3199                 struct cam_ed           *device;
3200                 int                     found;
3201
3202
3203                 found = 0;
3204
3205                 /*
3206                  * Don't want anyone mucking with our data.
3207                  */
3208                 device = start_ccb->ccb_h.path->device;
3209                 periph_head = &device->periphs;
3210                 cgdl = &start_ccb->cgdl;
3211
3212                 /*
3213                  * Check and see if the list has changed since the user
3214                  * last requested a list member.  If so, tell them that the
3215                  * list has changed, and therefore they need to start over
3216                  * from the beginning.
3217                  */
3218                 if ((cgdl->index != 0) &&
3219                     (cgdl->generation != device->generation)) {
3220                         cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
3221                         break;
3222                 }
3223
3224                 /*
3225                  * Traverse the list of peripherals and attempt to find
3226                  * the requested peripheral.
3227                  */
3228                 for (nperiph = SLIST_FIRST(periph_head), i = 0;
3229                      (nperiph != NULL) && (i <= cgdl->index);
3230                      nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
3231                         if (i == cgdl->index) {
3232                                 strncpy(cgdl->periph_name,
3233                                         nperiph->periph_name,
3234                                         DEV_IDLEN);
3235                                 cgdl->unit_number = nperiph->unit_number;
3236                                 found = 1;
3237                         }
3238                 }
3239                 if (found == 0) {
3240                         cgdl->status = CAM_GDEVLIST_ERROR;
3241                         break;
3242                 }
3243
3244                 if (nperiph == NULL)
3245                         cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
3246                 else
3247                         cgdl->status = CAM_GDEVLIST_MORE_DEVS;
3248
3249                 cgdl->index++;
3250                 cgdl->generation = device->generation;
3251
3252                 cgdl->ccb_h.status = CAM_REQ_CMP;
3253                 break;
3254         }
3255         case XPT_DEV_MATCH:
3256         {
3257                 dev_pos_type position_type;
3258                 struct ccb_dev_match *cdm;
3259                 int ret;
3260
3261                 cdm = &start_ccb->cdm;
3262
3263                 /*
3264                  * There are two ways of getting at information in the EDT.
3265                  * The first way is via the primary EDT tree.  It starts
3266                  * with a list of busses, then a list of targets on a bus,
3267                  * then devices/luns on a target, and then peripherals on a
3268                  * device/lun.  The "other" way is by the peripheral driver
3269                  * lists.  The peripheral driver lists are organized by
3270                  * peripheral driver.  (obviously)  So it makes sense to
3271                  * use the peripheral driver list if the user is looking
3272                  * for something like "da1", or all "da" devices.  If the
3273                  * user is looking for something on a particular bus/target
3274                  * or lun, it's generally better to go through the EDT tree.
3275                  */
3276
3277                 if (cdm->pos.position_type != CAM_DEV_POS_NONE)
3278                         position_type = cdm->pos.position_type;
3279                 else {
3280                         u_int i;
3281
3282                         position_type = CAM_DEV_POS_NONE;
3283
3284                         for (i = 0; i < cdm->num_patterns; i++) {
3285                                 if ((cdm->patterns[i].type == DEV_MATCH_BUS)
3286                                  ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
3287                                         position_type = CAM_DEV_POS_EDT;
3288                                         break;
3289                                 }
3290                         }
3291
3292                         if (cdm->num_patterns == 0)
3293                                 position_type = CAM_DEV_POS_EDT;
3294                         else if (position_type == CAM_DEV_POS_NONE)
3295                                 position_type = CAM_DEV_POS_PDRV;
3296                 }
3297
3298                 switch(position_type & CAM_DEV_POS_TYPEMASK) {
3299                 case CAM_DEV_POS_EDT:
3300                         ret = xptedtmatch(cdm);
3301                         break;
3302                 case CAM_DEV_POS_PDRV:
3303                         ret = xptperiphlistmatch(cdm);
3304                         break;
3305                 default:
3306                         cdm->status = CAM_DEV_MATCH_ERROR;
3307                         break;
3308                 }
3309
3310                 if (cdm->status == CAM_DEV_MATCH_ERROR)
3311                         start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3312                 else
3313                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3314
3315                 break;
3316         }
3317         case XPT_SASYNC_CB:
3318         {
3319                 struct ccb_setasync *csa;
3320                 struct async_node *cur_entry;
3321                 struct async_list *async_head;
3322                 u_int32_t added;
3323
3324                 csa = &start_ccb->csa;
3325                 added = csa->event_enable;
3326                 async_head = &csa->ccb_h.path->device->asyncs;
3327
3328                 /*
3329                  * If there is already an entry for us, simply
3330                  * update it.
3331                  */
3332                 cur_entry = SLIST_FIRST(async_head);
3333                 while (cur_entry != NULL) {
3334                         if ((cur_entry->callback_arg == csa->callback_arg)
3335                          && (cur_entry->callback == csa->callback))
3336                                 break;
3337                         cur_entry = SLIST_NEXT(cur_entry, links);
3338                 }
3339
3340                 if (cur_entry != NULL) {
3341                         /*
3342                          * If the request has no flags set,
3343                          * remove the entry.
3344                          */
3345                         added &= ~cur_entry->event_enable;
3346                         if (csa->event_enable == 0) {
3347                                 SLIST_REMOVE(async_head, cur_entry,
3348                                              async_node, links);
3349                                 csa->ccb_h.path->device->refcount--;
3350                                 kfree(cur_entry, M_CAMXPT);
3351                         } else {
3352                                 cur_entry->event_enable = csa->event_enable;
3353                         }
3354                 } else {
3355                         cur_entry = kmalloc(sizeof(*cur_entry), M_CAMXPT,
3356                                            M_INTWAIT);
3357                         cur_entry->event_enable = csa->event_enable;
3358                         cur_entry->callback_arg = csa->callback_arg;
3359                         cur_entry->callback = csa->callback;
3360                         SLIST_INSERT_HEAD(async_head, cur_entry, links);
3361                         csa->ccb_h.path->device->refcount++;
3362                 }
3363
3364                 /*
3365                  * Need to decouple this operation via a taskqueue so that
3366                  * the locking doesn't become a mess.
3367                  */
3368                 if ((added & (AC_FOUND_DEVICE | AC_PATH_REGISTERED)) != 0) {
3369                         struct xpt_task *task;
3370
3371                         task = kmalloc(sizeof(struct xpt_task), M_CAMXPT,
3372                                       M_INTWAIT);
3373
3374                         TASK_INIT(&task->task, 0, xpt_action_sasync_cb, task);
3375                         task->data1 = cur_entry;
3376                         task->data2 = added;
3377                         taskqueue_enqueue(taskqueue_thread[mycpuid],
3378                                           &task->task);
3379                 }
3380
3381                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3382                 break;
3383         }
3384         case XPT_REL_SIMQ:
3385         {
3386                 struct ccb_relsim *crs;
3387                 struct cam_ed *dev;
3388
3389                 crs = &start_ccb->crs;
3390                 dev = crs->ccb_h.path->device;
3391                 if (dev == NULL) {
3392
3393                         crs->ccb_h.status = CAM_DEV_NOT_THERE;
3394                         break;
3395                 }
3396
3397                 if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
3398
3399                         if (INQ_DATA_TQ_ENABLED(&dev->inq_data)) {
3400                                 /* Don't ever go below one opening */
3401                                 if (crs->openings > 0) {
3402                                         xpt_dev_ccbq_resize(crs->ccb_h.path,
3403                                                             crs->openings);
3404
3405                                         if (bootverbose) {
3406                                                 xpt_print(crs->ccb_h.path,
3407                                                     "tagged openings now %d\n",
3408                                                     crs->openings);
3409                                         }
3410                                 }
3411                         }
3412                 }
3413
3414                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
3415
3416                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
3417
3418                                 /*
3419                                  * Just extend the old timeout and decrement
3420                                  * the freeze count so that a single timeout
3421                                  * is sufficient for releasing the queue.
3422                                  */
3423                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3424                                 callout_stop(&dev->callout);
3425                         } else {
3426
3427                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3428                         }
3429
3430                         callout_reset(&dev->callout,
3431                                       (crs->release_timeout * hz) / 1000, 
3432                                       xpt_release_devq_timeout, dev);
3433
3434                         dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
3435
3436                 }
3437
3438                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
3439
3440                         if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
3441                                 /*
3442                                  * Decrement the freeze count so that a single
3443                                  * completion is still sufficient to unfreeze
3444                                  * the queue.
3445                                  */
3446                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3447                         } else {
3448
3449                                 dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3450                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3451                         }
3452                 }
3453
3454                 if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3455
3456                         if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3457                          || (dev->ccbq.dev_active == 0)) {
3458
3459                                 start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3460                         } else {
3461
3462                                 dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3463                                 start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3464                         }
3465                 }
3466                 
3467                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0) {
3468
3469                         xpt_release_devq(crs->ccb_h.path, /*count*/1,
3470                                          /*run_queue*/TRUE);
3471                 }
3472                 start_ccb->crs.qfrozen_cnt = dev->qfrozen_cnt;
3473                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3474                 break;
3475         }
3476         case XPT_SCAN_BUS:
3477                 xpt_scan_bus(start_ccb->ccb_h.path->periph, start_ccb);
3478                 break;
3479         case XPT_SCAN_LUN:
3480                 xpt_scan_lun(start_ccb->ccb_h.path->periph,
3481                              start_ccb->ccb_h.path, start_ccb->crcn.flags,
3482                              start_ccb);
3483                 break;
3484         case XPT_DEBUG: {
3485 #ifdef CAMDEBUG
3486 #ifdef CAM_DEBUG_DELAY
3487                 cam_debug_delay = CAM_DEBUG_DELAY;
3488 #endif
3489                 cam_dflags = start_ccb->cdbg.flags;
3490                 if (cam_dpath != NULL) {
3491                         xpt_free_path(cam_dpath);
3492                         cam_dpath = NULL;
3493                 }
3494
3495                 if (cam_dflags != CAM_DEBUG_NONE) {
3496                         if (xpt_create_path(&cam_dpath, xpt_periph,
3497                                             start_ccb->ccb_h.path_id,
3498                                             start_ccb->ccb_h.target_id,
3499                                             start_ccb->ccb_h.target_lun) !=
3500                                             CAM_REQ_CMP) {
3501                                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3502                                 cam_dflags = CAM_DEBUG_NONE;
3503                         } else {
3504                                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3505                                 xpt_print(cam_dpath, "debugging flags now %x\n",
3506                                     cam_dflags);
3507                         }
3508                 } else {
3509                         cam_dpath = NULL;
3510                         start_ccb->ccb_h.status = CAM_REQ_CMP;
3511                 }
3512 #else /* !CAMDEBUG */
3513                 start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3514 #endif /* CAMDEBUG */
3515                 break;
3516         }
3517         case XPT_NOOP:
3518                 if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3519                         xpt_freeze_devq(start_ccb->ccb_h.path, 1);
3520                 start_ccb->ccb_h.status = CAM_REQ_CMP;
3521                 break;
3522         default:
3523         case XPT_SDEV_TYPE:
3524         case XPT_TERM_IO:
3525         case XPT_ENG_INQ:
3526                 /* XXX Implement */
3527                 start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3528                 break;
3529         }
3530 }
3531
3532 void
3533 xpt_polled_action(union ccb *start_ccb)
3534 {
3535         u_int32_t timeout;
3536         struct    cam_sim *sim;
3537         struct    cam_devq *devq;
3538         struct    cam_ed *dev;
3539
3540         timeout = start_ccb->ccb_h.timeout;
3541         sim = start_ccb->ccb_h.path->bus->sim;
3542         devq = sim->devq;
3543         dev = start_ccb->ccb_h.path->device;
3544
3545         sim_lock_assert_owned(sim->lock);
3546
3547         /*
3548          * Steal an opening so that no other queued requests
3549          * can get it before us while we simulate interrupts.
3550          */
3551         dev->ccbq.devq_openings--;
3552         dev->ccbq.dev_openings--;
3553
3554         while(((devq && devq->send_openings <= 0) || dev->ccbq.dev_openings < 0)
3555            && (--timeout > 0)) {
3556                 DELAY(1000);
3557                 (*(sim->sim_poll))(sim);
3558                 camisr_runqueue(sim);
3559         }
3560
3561         dev->ccbq.devq_openings++;
3562         dev->ccbq.dev_openings++;
3563
3564         if (timeout != 0) {
3565                 xpt_action(start_ccb);
3566                 while(--timeout > 0) {
3567                         (*(sim->sim_poll))(sim);
3568                         camisr_runqueue(sim);
3569                         if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3570                             != CAM_REQ_INPROG)
3571                                 break;
3572                         DELAY(1000);
3573                 }
3574                 if (timeout == 0) {
3575                         /*
3576                          * XXX Is it worth adding a sim_timeout entry
3577                          * point so we can attempt recovery?  If
3578                          * this is only used for dumps, I don't think
3579                          * it is.
3580                          */
3581                         start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3582                 }
3583         } else {
3584                 start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3585         }
3586 }
3587
3588 /*
3589  * Schedule a peripheral driver to receive a ccb when it's
3590  * target device has space for more transactions.
3591  */
3592 void
3593 xpt_schedule(struct cam_periph *perph, u_int32_t new_priority)
3594 {
3595         struct cam_ed *device;
3596         union ccb *work_ccb;
3597         int runq;
3598
3599         sim_lock_assert_owned(perph->sim->lock);
3600
3601         CAM_DEBUG(perph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3602         device = perph->path->device;
3603         if (periph_is_queued(perph)) {
3604                 /* Simply reorder based on new priority */
3605                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3606                           ("   change priority to %d\n", new_priority));
3607                 if (new_priority < perph->pinfo.priority) {
3608                         camq_change_priority(&device->drvq,
3609                                              perph->pinfo.index,
3610                                              new_priority);
3611                 }
3612                 runq = 0;
3613         } else if (perph->path->bus->sim == &cam_dead_sim) {
3614                 /* The SIM is gone so just call periph_start directly. */
3615                 work_ccb = xpt_get_ccb(perph->path->device);
3616                 if (work_ccb == NULL)
3617                         return; /* XXX */
3618                 xpt_setup_ccb(&work_ccb->ccb_h, perph->path, new_priority);
3619                 perph->pinfo.priority = new_priority;
3620                 perph->periph_start(perph, work_ccb);
3621                 return;
3622         } else {
3623                 /* New entry on the queue */
3624                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3625                           ("   added periph to queue\n"));
3626                 perph->pinfo.priority = new_priority;
3627                 perph->pinfo.generation = ++device->drvq.generation;
3628                 camq_insert(&device->drvq, &perph->pinfo);
3629                 runq = xpt_schedule_dev_allocq(perph->path->bus, device);
3630         }
3631         if (runq != 0) {
3632                 CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3633                           ("   calling xpt_run_devq\n"));
3634                 xpt_run_dev_allocq(perph->path->bus);
3635         }
3636 }
3637
3638
3639 /*
3640  * Schedule a device to run on a given queue.
3641  * If the device was inserted as a new entry on the queue,
3642  * return 1 meaning the device queue should be run. If we
3643  * were already queued, implying someone else has already
3644  * started the queue, return 0 so the caller doesn't attempt
3645  * to run the queue.
3646  */
3647 static int
3648 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3649                  u_int32_t new_priority)
3650 {
3651         int retval;
3652         u_int32_t old_priority;
3653
3654         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3655
3656         old_priority = pinfo->priority;
3657
3658         /*
3659          * Are we already queued?
3660          */
3661         if (pinfo->index != CAM_UNQUEUED_INDEX) {
3662                 /* Simply reorder based on new priority */
3663                 if (new_priority < old_priority) {
3664                         camq_change_priority(queue, pinfo->index,
3665                                              new_priority);
3666                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3667                                         ("changed priority to %d\n",
3668                                          new_priority));
3669                 }
3670                 retval = 0;
3671         } else {
3672                 /* New entry on the queue */
3673                 if (new_priority < old_priority)
3674                         pinfo->priority = new_priority;
3675
3676                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3677                                 ("Inserting onto queue\n"));
3678                 pinfo->generation = ++queue->generation;
3679                 camq_insert(queue, pinfo);
3680                 retval = 1;
3681         }
3682         return (retval);
3683 }
3684
3685 static void
3686 xpt_run_dev_allocq(struct cam_eb *bus)
3687 {
3688         struct  cam_devq *devq;
3689
3690         if ((devq = bus->sim->devq) == NULL) {
3691                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq: NULL devq\n"));
3692                 return;
3693         }
3694         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq\n"));
3695
3696         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3697                         ("   qfrozen_cnt == 0x%x, entries == %d, "
3698                          "openings == %d, active == %d\n",
3699                          devq->alloc_queue.qfrozen_cnt,
3700                          devq->alloc_queue.entries,
3701                          devq->alloc_openings,
3702                          devq->alloc_active));
3703
3704         devq->alloc_queue.qfrozen_cnt++;
3705         while ((devq->alloc_queue.entries > 0)
3706             && (devq->alloc_openings > 0)
3707             && (devq->alloc_queue.qfrozen_cnt <= 1)) {
3708                 struct  cam_ed_qinfo *qinfo;
3709                 struct  cam_ed *device;
3710                 union   ccb *work_ccb;
3711                 struct  cam_periph *drv;
3712                 struct  camq *drvq;
3713
3714                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
3715                                                            CAMQ_HEAD);
3716                 device = qinfo->device;
3717
3718                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3719                                 ("running device %p\n", device));
3720
3721                 drvq = &device->drvq;
3722
3723 #ifdef CAMDEBUG
3724                 if (drvq->entries <= 0) {
3725                         panic("xpt_run_dev_allocq: "
3726                               "Device on queue without any work to do");
3727                 }
3728 #endif
3729                 if ((work_ccb = xpt_get_ccb(device)) != NULL) {
3730                         devq->alloc_openings--;
3731                         devq->alloc_active++;
3732                         drv = (struct cam_periph*)camq_remove(drvq, CAMQ_HEAD);
3733                         xpt_setup_ccb(&work_ccb->ccb_h, drv->path,
3734                                       drv->pinfo.priority);
3735                         CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3736                                         ("calling periph start\n"));
3737                         drv->periph_start(drv, work_ccb);
3738                 } else {
3739                         /*
3740                          * Malloc failure in alloc_ccb
3741                          */
3742                         /*
3743                          * XXX add us to a list to be run from free_ccb
3744                          * if we don't have any ccbs active on this
3745                          * device queue otherwise we may never get run
3746                          * again.
3747                          */
3748                         break;
3749                 }
3750
3751                 if (drvq->entries > 0) {
3752                         /* We have more work.  Attempt to reschedule */
3753                         xpt_schedule_dev_allocq(bus, device);
3754                 }
3755         }
3756         devq->alloc_queue.qfrozen_cnt--;
3757 }
3758
3759 static void
3760 xpt_run_dev_sendq(struct cam_eb *bus)
3761 {
3762         struct  cam_devq *devq;
3763
3764         if ((devq = bus->sim->devq) == NULL) {
3765                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq: NULL devq\n"));
3766                 return;
3767         }
3768         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_sendq\n"));
3769
3770         devq->send_queue.qfrozen_cnt++;
3771         while ((devq->send_queue.entries > 0)
3772             && (devq->send_openings > 0)) {
3773                 struct  cam_ed_qinfo *qinfo;
3774                 struct  cam_ed *device;
3775                 union ccb *work_ccb;
3776                 struct  cam_sim *sim;
3777
3778                 if (devq->send_queue.qfrozen_cnt > 1) {
3779                         break;
3780                 }
3781
3782                 qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
3783                                                            CAMQ_HEAD);
3784                 device = qinfo->device;
3785
3786                 /*
3787                  * If the device has been "frozen", don't attempt
3788                  * to run it.
3789                  */
3790                 if (device->qfrozen_cnt > 0) {
3791                         continue;
3792                 }
3793
3794                 CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3795                                 ("running device %p\n", device));
3796
3797                 work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3798                 if (work_ccb == NULL) {
3799                         kprintf("device on run queue with no ccbs???\n");
3800                         continue;
3801                 }
3802
3803                 if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3804
3805                         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
3806                         if (xsoftc.num_highpower <= 0) {
3807                                 /*
3808                                  * We got a high power command, but we
3809                                  * don't have any available slots.  Freeze
3810                                  * the device queue until we have a slot
3811                                  * available.
3812                                  */
3813                                 device->qfrozen_cnt++;
3814                                 STAILQ_INSERT_TAIL(&xsoftc.highpowerq,
3815                                                    &work_ccb->ccb_h,
3816                                                    xpt_links.stqe);
3817
3818                                 lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
3819                                 continue;
3820                         } else {
3821                                 /*
3822                                  * Consume a high power slot while
3823                                  * this ccb runs.
3824                                  */
3825                                 xsoftc.num_highpower--;
3826                         }
3827                         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
3828                 }
3829                 devq->active_dev = device;
3830                 cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3831
3832                 cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3833
3834                 devq->send_openings--;
3835                 devq->send_active++;
3836
3837                 if (device->ccbq.queue.entries > 0)
3838                         xpt_schedule_dev_sendq(bus, device);
3839
3840                 if (work_ccb && (work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0){
3841                         /*
3842                          * The client wants to freeze the queue
3843                          * after this CCB is sent.
3844                          */
3845                         device->qfrozen_cnt++;
3846                 }
3847
3848                 /* In Target mode, the peripheral driver knows best... */
3849                 if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3850                         if ((device->inq_flags & SID_CmdQue) != 0
3851                          && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3852                                 work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3853                         else
3854                                 /*
3855                                  * Clear this in case of a retried CCB that
3856                                  * failed due to a rejected tag.
3857                                  */
3858                                 work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3859                 }
3860
3861                 /*
3862                  * Device queues can be shared among multiple sim instances
3863                  * that reside on different busses.  Use the SIM in the queue
3864                  * CCB's path, rather than the one in the bus that was passed
3865                  * into this function.
3866                  */
3867                 sim = work_ccb->ccb_h.path->bus->sim;
3868                 (*(sim->sim_action))(sim, work_ccb);
3869
3870                 devq->active_dev = NULL;
3871         }
3872         devq->send_queue.qfrozen_cnt--;
3873 }
3874
3875 /*
3876  * This function merges stuff from the slave ccb into the master ccb, while
3877  * keeping important fields in the master ccb constant.
3878  */
3879 void
3880 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3881 {
3882         /*
3883          * Pull fields that are valid for peripheral drivers to set
3884          * into the master CCB along with the CCB "payload".
3885          */
3886         master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3887         master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3888         master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3889         master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3890         bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3891               sizeof(union ccb) - sizeof(struct ccb_hdr));
3892 }
3893
3894 void
3895 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3896 {
3897         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3898         callout_init(&ccb_h->timeout_ch);
3899         ccb_h->pinfo.priority = priority;
3900         ccb_h->path = path;
3901         ccb_h->path_id = path->bus->path_id;
3902         if (path->target)
3903                 ccb_h->target_id = path->target->target_id;
3904         else
3905                 ccb_h->target_id = CAM_TARGET_WILDCARD;
3906         if (path->device) {
3907                 ccb_h->target_lun = path->device->lun_id;
3908                 ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3909         } else {
3910                 ccb_h->target_lun = CAM_TARGET_WILDCARD;
3911         }
3912         ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3913         ccb_h->flags = 0;
3914 }
3915
3916 /* Path manipulation functions */
3917 cam_status
3918 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3919                 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3920 {
3921         struct     cam_path *path;
3922         cam_status status;
3923
3924         path = kmalloc(sizeof(*path), M_CAMXPT, M_INTWAIT);
3925         status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3926         if (status != CAM_REQ_CMP) {
3927                 kfree(path, M_CAMXPT);
3928                 path = NULL;
3929         }
3930         *new_path_ptr = path;
3931         return (status);
3932 }
3933
3934 cam_status
3935 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3936                          struct cam_periph *periph, path_id_t path_id,
3937                          target_id_t target_id, lun_id_t lun_id)
3938 {
3939         struct     cam_path *path;
3940         struct     cam_eb *bus = NULL;
3941         cam_status status;
3942         int        need_unlock = 0;
3943
3944         path = (struct cam_path *)kmalloc(sizeof(*path), M_CAMXPT, M_WAITOK);
3945
3946         if (path_id != CAM_BUS_WILDCARD) {
3947                 bus = xpt_find_bus(path_id);
3948                 if (bus != NULL) {
3949                         need_unlock = 1;
3950                         CAM_SIM_LOCK(bus->sim);
3951                 }
3952         }
3953         status = xpt_compile_path(path, periph, path_id, target_id, lun_id);
3954         if (need_unlock)
3955                 CAM_SIM_UNLOCK(bus->sim);
3956         if (status != CAM_REQ_CMP) {
3957                 kfree(path, M_CAMXPT);
3958                 path = NULL;
3959         }
3960         *new_path_ptr = path;
3961         return (status);
3962 }
3963
3964 static cam_status
3965 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3966                  path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3967 {
3968         struct       cam_eb *bus;
3969         struct       cam_et *target;
3970         struct       cam_ed *device;
3971         cam_status   status;
3972
3973         status = CAM_REQ_CMP;   /* Completed without error */
3974         target = NULL;          /* Wildcarded */
3975         device = NULL;          /* Wildcarded */
3976
3977         /*
3978          * We will potentially modify the EDT, so block interrupts
3979          * that may attempt to create cam paths.
3980          */
3981         bus = xpt_find_bus(path_id);
3982         if (bus == NULL) {
3983                 status = CAM_PATH_INVALID;
3984         } else {
3985                 target = xpt_find_target(bus, target_id);
3986                 if (target == NULL) {
3987                         /* Create one */
3988                         struct cam_et *new_target;
3989
3990                         new_target = xpt_alloc_target(bus, target_id);
3991                         if (new_target == NULL) {
3992                                 status = CAM_RESRC_UNAVAIL;
3993                         } else {
3994                                 target = new_target;
3995                         }
3996                 }
3997                 if (target != NULL) {
3998                         device = xpt_find_device(target, lun_id);
3999                         if (device == NULL) {
4000                                 /* Create one */
4001                                 struct cam_ed *new_device;
4002
4003                                 new_device = xpt_alloc_device(bus,
4004                                                               target,
4005                                                               lun_id);
4006                                 if (new_device == NULL) {
4007                                         status = CAM_RESRC_UNAVAIL;
4008                                 } else {
4009                                         device = new_device;
4010                                 }
4011                         }
4012                 }
4013         }
4014
4015         /*
4016          * Only touch the user's data if we are successful.
4017          */
4018         if (status == CAM_REQ_CMP) {
4019                 new_path->periph = perph;
4020                 new_path->bus = bus;
4021                 new_path->target = target;
4022                 new_path->device = device;
4023                 CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
4024         } else {
4025                 if (device != NULL)
4026                         xpt_release_device(bus, target, device);
4027                 if (target != NULL)
4028                         xpt_release_target(bus, target);
4029                 if (bus != NULL)
4030                         xpt_release_bus(bus);
4031         }
4032         return (status);
4033 }
4034
4035 static void
4036 xpt_release_path(struct cam_path *path)
4037 {
4038         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
4039         if (path->device != NULL) {
4040                 xpt_release_device(path->bus, path->target, path->device);
4041                 path->device = NULL;
4042         }
4043         if (path->target != NULL) {
4044                 xpt_release_target(path->bus, path->target);
4045                 path->target = NULL;
4046         }
4047         if (path->bus != NULL) {
4048                 xpt_release_bus(path->bus);
4049                 path->bus = NULL;
4050         }
4051 }
4052
4053 void
4054 xpt_free_path(struct cam_path *path)
4055 {
4056         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
4057         xpt_release_path(path);
4058         kfree(path, M_CAMXPT);
4059 }
4060
4061
4062 /*
4063  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
4064  * in path1, 2 for match with wildcards in path2.
4065  */
4066 int
4067 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
4068 {
4069         int retval = 0;
4070
4071         if (path1->bus != path2->bus) {
4072                 if (path1->bus->path_id == CAM_BUS_WILDCARD)
4073                         retval = 1;
4074                 else if (path2->bus->path_id == CAM_BUS_WILDCARD)
4075                         retval = 2;
4076                 else
4077                         return (-1);
4078         }
4079         if (path1->target != path2->target) {
4080                 if (path1->target->target_id == CAM_TARGET_WILDCARD) {
4081                         if (retval == 0)
4082                                 retval = 1;
4083                 } else if (path2->target->target_id == CAM_TARGET_WILDCARD)
4084                         retval = 2;
4085                 else
4086                         return (-1);
4087         }
4088         if (path1->device != path2->device) {
4089                 if (path1->device->lun_id == CAM_LUN_WILDCARD) {
4090                         if (retval == 0)
4091                                 retval = 1;
4092                 } else if (path2->device->lun_id == CAM_LUN_WILDCARD)
4093                         retval = 2;
4094                 else
4095                         return (-1);
4096         }
4097         return (retval);
4098 }
4099
4100 void
4101 xpt_print_path(struct cam_path *path)
4102 {
4103
4104         if (path == NULL)
4105                 kprintf("(nopath): ");
4106         else {
4107                 if (path->periph != NULL)
4108                         kprintf("(%s%d:", path->periph->periph_name,
4109                                path->periph->unit_number);
4110                 else
4111                         kprintf("(noperiph:");
4112
4113                 if (path->bus != NULL)
4114                         kprintf("%s%d:%d:", path->bus->sim->sim_name,
4115                                path->bus->sim->unit_number,
4116                                path->bus->sim->bus_id);
4117                 else
4118                         kprintf("nobus:");
4119
4120                 if (path->target != NULL)
4121                         kprintf("%d:", path->target->target_id);
4122                 else
4123                         kprintf("X:");
4124
4125                 if (path->device != NULL)
4126                         kprintf("%d): ", path->device->lun_id);
4127                 else
4128                         kprintf("X): ");
4129         }
4130 }
4131
4132 void
4133 xpt_print(struct cam_path *path, const char *fmt, ...)
4134 {
4135         __va_list ap;
4136         xpt_print_path(path);
4137         __va_start(ap, fmt);
4138         kvprintf(fmt, ap);
4139         __va_end(ap);
4140 }
4141
4142 int
4143 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
4144 {
4145         struct sbuf sb;
4146
4147         sim_lock_assert_owned(path->bus->sim->lock);
4148
4149         sbuf_new(&sb, str, str_len, 0);
4150
4151         if (path == NULL)
4152                 sbuf_printf(&sb, "(nopath): ");
4153         else {
4154                 if (path->periph != NULL)
4155                         sbuf_printf(&sb, "(%s%d:", path->periph->periph_name,
4156                                     path->periph->unit_number);
4157                 else
4158                         sbuf_printf(&sb, "(noperiph:");
4159
4160                 if (path->bus != NULL)
4161                         sbuf_printf(&sb, "%s%d:%d:", path->bus->sim->sim_name,
4162                                     path->bus->sim->unit_number,
4163                                     path->bus->sim->bus_id);
4164                 else
4165                         sbuf_printf(&sb, "nobus:");
4166
4167                 if (path->target != NULL)
4168                         sbuf_printf(&sb, "%d:", path->target->target_id);
4169                 else
4170                         sbuf_printf(&sb, "X:");
4171
4172                 if (path->device != NULL)
4173                         sbuf_printf(&sb, "%d): ", path->device->lun_id);
4174                 else
4175                         sbuf_printf(&sb, "X): ");
4176         }
4177         sbuf_finish(&sb);
4178
4179         return(sbuf_len(&sb));
4180 }
4181
4182 path_id_t
4183 xpt_path_path_id(struct cam_path *path)
4184 {
4185         sim_lock_assert_owned(path->bus->sim->lock);
4186
4187         return(path->bus->path_id);
4188 }
4189
4190 target_id_t
4191 xpt_path_target_id(struct cam_path *path)
4192 {
4193         sim_lock_assert_owned(path->bus->sim->lock);
4194
4195         if (path->target != NULL)
4196                 return (path->target->target_id);
4197         else
4198                 return (CAM_TARGET_WILDCARD);
4199 }
4200
4201 lun_id_t
4202 xpt_path_lun_id(struct cam_path *path)
4203 {
4204         sim_lock_assert_owned(path->bus->sim->lock);
4205
4206         if (path->device != NULL)
4207                 return (path->device->lun_id);
4208         else
4209                 return (CAM_LUN_WILDCARD);
4210 }
4211
4212 struct cam_sim *
4213 xpt_path_sim(struct cam_path *path)
4214 {
4215         return (path->bus->sim);
4216 }
4217
4218 struct cam_periph*
4219 xpt_path_periph(struct cam_path *path)
4220 {
4221         sim_lock_assert_owned(path->bus->sim->lock);
4222
4223         return (path->periph);
4224 }
4225
4226 /*
4227  * Release a CAM control block for the caller.  Remit the cost of the structure
4228  * to the device referenced by the path.  If the this device had no 'credits'
4229  * and peripheral drivers have registered async callbacks for this notification
4230  * call them now.
4231  */
4232 void
4233 xpt_release_ccb(union ccb *free_ccb)
4234 {
4235         struct   cam_path *path;
4236         struct   cam_ed *device;
4237         struct   cam_eb *bus;
4238         struct   cam_sim *sim;
4239
4240         CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
4241         path = free_ccb->ccb_h.path;
4242         device = path->device;
4243         bus = path->bus;
4244         sim = bus->sim;
4245
4246         sim_lock_assert_owned(sim->lock);
4247
4248         cam_ccbq_release_opening(&device->ccbq);
4249         if (sim->ccb_count > sim->max_ccbs) {
4250                 xpt_free_ccb(free_ccb);
4251                 sim->ccb_count--;
4252         } else if (sim == &cam_dead_sim) {
4253                 xpt_free_ccb(free_ccb);
4254         } else  {
4255                 SLIST_INSERT_HEAD(&sim->ccb_freeq, &free_ccb->ccb_h,
4256                     xpt_links.sle);
4257         }
4258         if (sim->devq == NULL) {
4259                 return;
4260         }
4261         sim->devq->alloc_openings++;
4262         sim->devq->alloc_active--;
4263         /* XXX Turn this into an inline function - xpt_run_device?? */
4264         if ((device_is_alloc_queued(device) == 0)
4265          && (device->drvq.entries > 0)) {
4266                 xpt_schedule_dev_allocq(bus, device);
4267         }
4268         if (dev_allocq_is_runnable(sim->devq))
4269                 xpt_run_dev_allocq(bus);
4270 }
4271
4272 /* Functions accessed by SIM drivers */
4273
4274 /*
4275  * A sim structure, listing the SIM entry points and instance
4276  * identification info is passed to xpt_bus_register to hook the SIM
4277  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
4278  * for this new bus and places it in the array of busses and assigns
4279  * it a path_id.  The path_id may be influenced by "hard wiring"
4280  * information specified by the user.  Once interrupt services are
4281  * availible, the bus will be probed.
4282  */
4283 int32_t
4284 xpt_bus_register(struct cam_sim *sim, u_int32_t bus)
4285 {
4286         struct cam_eb *new_bus;
4287         struct cam_eb *old_bus;
4288         struct ccb_pathinq cpi;
4289
4290         sim_lock_assert_owned(sim->lock);
4291
4292         sim->bus_id = bus;
4293         new_bus = kmalloc(sizeof(*new_bus), M_CAMXPT, M_INTWAIT);
4294
4295         if (strcmp(sim->sim_name, "xpt") != 0) {
4296                 sim->path_id =
4297                     xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
4298         }
4299
4300         TAILQ_INIT(&new_bus->et_entries);
4301         new_bus->path_id = sim->path_id;
4302         new_bus->sim = sim;
4303         ++sim->refcount;
4304         timevalclear(&new_bus->last_reset);
4305         new_bus->flags = 0;
4306         new_bus->refcount = 1;  /* Held until a bus_deregister event */
4307         new_bus->generation = 0;
4308         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
4309         old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4310         while (old_bus != NULL
4311             && old_bus->path_id < new_bus->path_id)
4312                 old_bus = TAILQ_NEXT(old_bus, links);
4313         if (old_bus != NULL)
4314                 TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
4315         else
4316                 TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
4317         xsoftc.bus_generation++;
4318         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
4319
4320         /* Notify interested parties */
4321         if (sim->path_id != CAM_XPT_PATH_ID) {
4322                 struct cam_path path;
4323
4324                 xpt_compile_path(&path, /*periph*/NULL, sim->path_id,
4325                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4326                 xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
4327                 cpi.ccb_h.func_code = XPT_PATH_INQ;
4328                 xpt_action((union ccb *)&cpi);
4329                 xpt_async(AC_PATH_REGISTERED, &path, &cpi);
4330                 xpt_release_path(&path);
4331         }
4332         return (CAM_SUCCESS);
4333 }
4334
4335 /*
4336  * Deregister a bus.  We must clean out all transactions pending on the bus.
4337  * This routine is typically called prior to cam_sim_free() (e.g. see
4338  * dev/usbmisc/umass/umass.c)
4339  */
4340 int32_t
4341 xpt_bus_deregister(path_id_t pathid)
4342 {
4343         struct cam_path bus_path;
4344         struct cam_et *target;
4345         struct cam_ed *device;
4346         struct cam_ed_qinfo *qinfo;
4347         struct cam_devq *devq;
4348         struct cam_periph *periph;
4349         struct cam_sim *ccbsim;
4350         union ccb *work_ccb;
4351         cam_status status;
4352         int retries = 0;
4353
4354         status = xpt_compile_path(&bus_path, NULL, pathid,
4355                                   CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4356         if (status != CAM_REQ_CMP)
4357                 return (status);
4358
4359         /*
4360          * This should clear out all pending requests and timeouts, but
4361          * the ccb's may be queued to a software interrupt.
4362          *
4363          * XXX AC_LOST_DEVICE does not precisely abort the pending requests,
4364          * and it really ought to.
4365          */
4366         xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4367         xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4368
4369         /*
4370          * Mark the SIM as having been deregistered.  This prevents
4371          * certain operations from re-queueing to it, stops new devices
4372          * from being added, etc.
4373          */
4374         devq = bus_path.bus->sim->devq;
4375         ccbsim = bus_path.bus->sim;
4376         ccbsim->flags |= CAM_SIM_DEREGISTERED;
4377
4378 again:
4379         /*
4380          * Execute any pending operations now. 
4381          */
4382         while ((qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
4383             CAMQ_HEAD)) != NULL ||
4384             (qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->alloc_queue,
4385             CAMQ_HEAD)) != NULL) {
4386                 do {
4387                         device = qinfo->device;
4388                         work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
4389                         if (work_ccb != NULL) {
4390                                 devq->active_dev = device;
4391                                 cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
4392                                 cam_ccbq_send_ccb(&device->ccbq, work_ccb);
4393                                 (*(ccbsim->sim_action))(ccbsim, work_ccb);
4394                         }
4395
4396                         periph = (struct cam_periph *)camq_remove(&device->drvq,
4397                             CAMQ_HEAD);
4398                         if (periph != NULL)
4399                                 xpt_schedule(periph, periph->pinfo.priority);
4400                 } while (work_ccb != NULL || periph != NULL);
4401         }
4402
4403         /*
4404          * Make sure all completed CCBs are processed. 
4405          */
4406         while (!TAILQ_EMPTY(&ccbsim->sim_doneq)) {
4407                 camisr_runqueue(ccbsim);
4408         }
4409
4410         /*
4411          * Check for requeues, reissues asyncs if necessary
4412          */
4413         if (CAMQ_GET_HEAD(&devq->send_queue))
4414                 kprintf("camq: devq send_queue still in use (%d entries)\n",
4415                         devq->send_queue.entries);
4416         if (CAMQ_GET_HEAD(&devq->alloc_queue))
4417                 kprintf("camq: devq alloc_queue still in use (%d entries)\n",
4418                         devq->alloc_queue.entries);
4419         if (CAMQ_GET_HEAD(&devq->send_queue) || 
4420             CAMQ_GET_HEAD(&devq->alloc_queue)) {
4421                 if (++retries < 5) {
4422                         xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4423                         xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4424                         goto again;
4425                 }
4426         }
4427
4428         /*
4429          * Retarget the bus and all cached sim pointers to dead_sim.
4430          *
4431          * Various CAM subsystems may be holding on to targets, devices,
4432          * and/or peripherals and may attempt to use the sim pointer cached
4433          * in some of these structures during close.
4434          */
4435         bus_path.bus->sim = &cam_dead_sim;
4436         TAILQ_FOREACH(target, &bus_path.bus->et_entries, links) {
4437                 TAILQ_FOREACH(device, &target->ed_entries, links) {
4438                         device->sim = &cam_dead_sim;
4439                         SLIST_FOREACH(periph, &device->periphs, periph_links) {
4440                                 periph->sim = &cam_dead_sim;
4441                         }
4442                 }
4443         }
4444
4445         /*
4446          * Repeat the async's for the benefit of any new devices, such as
4447          * might be created from completed probes.  Any new device
4448          * ops will run on dead_sim.
4449          *
4450          * XXX There are probably races :-(
4451          */
4452         CAM_SIM_LOCK(&cam_dead_sim);
4453         xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4454         xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4455         CAM_SIM_UNLOCK(&cam_dead_sim);
4456
4457         /* Release the reference count held while registered. */
4458         xpt_release_bus(bus_path.bus);
4459         xpt_release_path(&bus_path);
4460
4461         /* Release the ref we got when the bus was registered */
4462         cam_sim_release(ccbsim, 0);
4463
4464         return (CAM_REQ_CMP);
4465 }
4466
4467 static path_id_t
4468 xptnextfreepathid(void)
4469 {
4470         struct cam_eb *bus;
4471         path_id_t pathid;
4472         char *strval;
4473
4474         pathid = 0;
4475         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
4476         bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4477 retry:
4478         /* Find an unoccupied pathid */
4479         while (bus != NULL && bus->path_id <= pathid) {
4480                 if (bus->path_id == pathid)
4481                         pathid++;
4482                 bus = TAILQ_NEXT(bus, links);
4483         }
4484         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
4485
4486         /*
4487          * Ensure that this pathid is not reserved for
4488          * a bus that may be registered in the future.
4489          */
4490         if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4491                 ++pathid;
4492                 /* Start the search over */
4493                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
4494                 goto retry;
4495         }
4496         return (pathid);
4497 }
4498
4499 static path_id_t
4500 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4501 {
4502         path_id_t pathid;
4503         int i, dunit, val;
4504         char buf[32];
4505
4506         pathid = CAM_XPT_PATH_ID;
4507         ksnprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4508         i = -1;
4509         while ((i = resource_query_string(i, "at", buf)) != -1) {
4510                 if (strcmp(resource_query_name(i), "scbus")) {
4511                         /* Avoid a bit of foot shooting. */
4512                         continue;
4513                 }
4514                 dunit = resource_query_unit(i);
4515                 if (dunit < 0)          /* unwired?! */
4516                         continue;
4517                 if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4518                         if (sim_bus == val) {
4519                                 pathid = dunit;
4520                                 break;
4521                         }
4522                 } else if (sim_bus == 0) {
4523                         /* Unspecified matches bus 0 */
4524                         pathid = dunit;
4525                         break;
4526                 } else {
4527                         kprintf("Ambiguous scbus configuration for %s%d "
4528                                "bus %d, cannot wire down.  The kernel "
4529                                "config entry for scbus%d should "
4530                                "specify a controller bus.\n"
4531                                "Scbus will be assigned dynamically.\n",
4532                                sim_name, sim_unit, sim_bus, dunit);
4533                         break;
4534                 }
4535         }
4536
4537         if (pathid == CAM_XPT_PATH_ID)
4538                 pathid = xptnextfreepathid();
4539         return (pathid);
4540 }
4541
4542 void
4543 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4544 {
4545         struct cam_eb *bus;
4546         struct cam_et *target, *next_target;
4547         struct cam_ed *device, *next_device;
4548
4549         sim_lock_assert_owned(path->bus->sim->lock);
4550
4551         CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_async\n"));
4552
4553         /*
4554          * Most async events come from a CAM interrupt context.  In
4555          * a few cases, the error recovery code at the peripheral layer,
4556          * which may run from our SWI or a process context, may signal
4557          * deferred events with a call to xpt_async.
4558          */
4559
4560         bus = path->bus;
4561
4562         if (async_code == AC_BUS_RESET) {
4563                 /* Update our notion of when the last reset occurred */
4564                 microuptime(&bus->last_reset);
4565         }
4566
4567         for (target = TAILQ_FIRST(&bus->et_entries);
4568              target != NULL;
4569              target = next_target) {
4570
4571                 next_target = TAILQ_NEXT(target, links);
4572
4573                 if (path->target != target
4574                  && path->target->target_id != CAM_TARGET_WILDCARD
4575                  && target->target_id != CAM_TARGET_WILDCARD)
4576                         continue;
4577
4578                 if (async_code == AC_SENT_BDR) {
4579                         /* Update our notion of when the last reset occurred */
4580                         microuptime(&path->target->last_reset);
4581                 }
4582
4583                 for (device = TAILQ_FIRST(&target->ed_entries);
4584                      device != NULL;
4585                      device = next_device) {
4586
4587                         next_device = TAILQ_NEXT(device, links);
4588
4589                         if (path->device != device
4590                          && path->device->lun_id != CAM_LUN_WILDCARD
4591                          && device->lun_id != CAM_LUN_WILDCARD)
4592                                 continue;
4593
4594                         xpt_dev_async(async_code, bus, target,
4595                                       device, async_arg);
4596
4597                         xpt_async_bcast(&device->asyncs, async_code,
4598                                         path, async_arg);
4599                 }
4600         }
4601
4602         /*
4603          * If this wasn't a fully wildcarded async, tell all
4604          * clients that want all async events.
4605          */
4606         if (bus != xpt_periph->path->bus)
4607                 xpt_async_bcast(&xpt_periph->path->device->asyncs, async_code,
4608                                 path, async_arg);
4609 }
4610
4611 static void
4612 xpt_async_bcast(struct async_list *async_head,
4613                 u_int32_t async_code,
4614                 struct cam_path *path, void *async_arg)
4615 {
4616         struct async_node *cur_entry;
4617
4618         cur_entry = SLIST_FIRST(async_head);
4619         while (cur_entry != NULL) {
4620                 struct async_node *next_entry;
4621                 /*
4622                  * Grab the next list entry before we call the current
4623                  * entry's callback.  This is because the callback function
4624                  * can delete its async callback entry.
4625                  */
4626                 next_entry = SLIST_NEXT(cur_entry, links);
4627                 if ((cur_entry->event_enable & async_code) != 0)
4628                         cur_entry->callback(cur_entry->callback_arg,
4629                                             async_code, path,
4630                                             async_arg);
4631                 cur_entry = next_entry;
4632         }
4633 }
4634
4635 /*
4636  * Handle any per-device event notifications that require action by the XPT.
4637  */
4638 static void
4639 xpt_dev_async(u_int32_t async_code, struct cam_eb *bus, struct cam_et *target,
4640               struct cam_ed *device, void *async_arg)
4641 {
4642         cam_status status;
4643         struct cam_path newpath;
4644
4645         /*
4646          * We only need to handle events for real devices.
4647          */
4648         if (target->target_id == CAM_TARGET_WILDCARD
4649          || device->lun_id == CAM_LUN_WILDCARD)
4650                 return;
4651
4652         /*
4653          * We need our own path with wildcards expanded to
4654          * handle certain types of events.
4655          */
4656         if ((async_code == AC_SENT_BDR)
4657          || (async_code == AC_BUS_RESET)
4658          || (async_code == AC_INQ_CHANGED))
4659                 status = xpt_compile_path(&newpath, NULL,
4660                                           bus->path_id,
4661                                           target->target_id,
4662                                           device->lun_id);
4663         else
4664                 status = CAM_REQ_CMP_ERR;
4665
4666         if (status == CAM_REQ_CMP) {
4667
4668                 /*
4669                  * Allow transfer negotiation to occur in a
4670                  * tag free environment.
4671                  */
4672                 if (async_code == AC_SENT_BDR
4673                  || async_code == AC_BUS_RESET)
4674                         xpt_toggle_tags(&newpath);
4675
4676                 if (async_code == AC_INQ_CHANGED) {
4677                         /*
4678                          * We've sent a start unit command, or
4679                          * something similar to a device that
4680                          * may have caused its inquiry data to
4681                          * change. So we re-scan the device to
4682                          * refresh the inquiry data for it.
4683                          */
4684                         xpt_scan_lun(newpath.periph, &newpath,
4685                                      CAM_EXPECT_INQ_CHANGE, NULL);
4686                 }
4687                 xpt_release_path(&newpath);
4688         } else if (async_code == AC_LOST_DEVICE) {
4689                 /*
4690                  * When we lose a device the device may be about to detach
4691                  * the sim, we have to clear out all pending timeouts and
4692                  * requests before that happens.  XXX it would be nice if
4693                  * we could abort the requests pertaining to the device.
4694                  */
4695                 xpt_release_devq_timeout(device);
4696                 if ((device->flags & CAM_DEV_UNCONFIGURED) == 0) {
4697                         device->flags |= CAM_DEV_UNCONFIGURED;
4698                         xpt_release_device(bus, target, device);
4699                 }
4700         } else if (async_code == AC_TRANSFER_NEG) {
4701                 struct ccb_trans_settings *settings;
4702
4703                 settings = (struct ccb_trans_settings *)async_arg;
4704                 xpt_set_transfer_settings(settings, device,
4705                                           /*async_update*/TRUE);
4706         }
4707 }
4708
4709 u_int32_t
4710 xpt_freeze_devq(struct cam_path *path, u_int count)
4711 {
4712         struct ccb_hdr *ccbh;
4713
4714         sim_lock_assert_owned(path->bus->sim->lock);
4715
4716         path->device->qfrozen_cnt += count;
4717
4718         /*
4719          * Mark the last CCB in the queue as needing
4720          * to be requeued if the driver hasn't
4721          * changed it's state yet.  This fixes a race
4722          * where a ccb is just about to be queued to
4723          * a controller driver when it's interrupt routine
4724          * freezes the queue.  To completly close the
4725          * hole, controller drives must check to see
4726          * if a ccb's status is still CAM_REQ_INPROG
4727          * just before they queue
4728          * the CCB.  See ahc_action/ahc_freeze_devq for
4729          * an example.
4730          */
4731         ccbh = TAILQ_LAST(&path->device->ccbq.active_ccbs, ccb_hdr_tailq);
4732         if (ccbh && ccbh->status == CAM_REQ_INPROG)
4733                 ccbh->status = CAM_REQUEUE_REQ;
4734         return (path->device->qfrozen_cnt);
4735 }
4736
4737 u_int32_t
4738 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4739 {
4740         sim_lock_assert_owned(sim->lock);
4741
4742         if (sim->devq == NULL)
4743                 return(count);
4744         sim->devq->send_queue.qfrozen_cnt += count;
4745         if (sim->devq->active_dev != NULL) {
4746                 struct ccb_hdr *ccbh;
4747
4748                 ccbh = TAILQ_LAST(&sim->devq->active_dev->ccbq.active_ccbs,
4749                                   ccb_hdr_tailq);
4750                 if (ccbh && ccbh->status == CAM_REQ_INPROG)
4751                         ccbh->status = CAM_REQUEUE_REQ;
4752         }
4753         return (sim->devq->send_queue.qfrozen_cnt);
4754 }
4755
4756 /*
4757  * WARNING: most devices, especially USB/UMASS, may detach their sim early.
4758  * We ref-count the sim (and the bus only NULLs it out when the bus has been
4759  * freed, which is not the case here), but the device queue is also freed XXX
4760  * and we have to check that here.
4761  *
4762  * XXX fixme: could we simply not null-out the device queue via 
4763  * cam_sim_free()?
4764  */
4765 static void
4766 xpt_release_devq_timeout(void *arg)
4767 {
4768         struct cam_ed *device;
4769
4770         device = (struct cam_ed *)arg;
4771
4772         xpt_release_devq_device(device, /*count*/1, /*run_queue*/TRUE);
4773 }
4774
4775 void
4776 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4777 {
4778         sim_lock_assert_owned(path->bus->sim->lock);
4779
4780         xpt_release_devq_device(path->device, count, run_queue);
4781 }
4782
4783 static void
4784 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4785 {
4786         int     rundevq;
4787
4788         rundevq = 0;
4789
4790         if (dev->qfrozen_cnt > 0) {
4791
4792                 count = (count > dev->qfrozen_cnt) ? dev->qfrozen_cnt : count;
4793                 dev->qfrozen_cnt -= count;
4794                 if (dev->qfrozen_cnt == 0) {
4795
4796                         /*
4797                          * No longer need to wait for a successful
4798                          * command completion.
4799                          */
4800                         dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4801
4802                         /*
4803                          * Remove any timeouts that might be scheduled
4804                          * to release this queue.
4805                          */
4806                         if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4807                                 callout_stop(&dev->callout);
4808                                 dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4809                         }
4810
4811                         /*
4812                          * Now that we are unfrozen schedule the
4813                          * device so any pending transactions are
4814                          * run.
4815                          */
4816                         if ((dev->ccbq.queue.entries > 0)
4817                          && (xpt_schedule_dev_sendq(dev->target->bus, dev))
4818                          && (run_queue != 0)) {
4819                                 rundevq = 1;
4820                         }
4821                 }
4822         }
4823         if (rundevq != 0)
4824                 xpt_run_dev_sendq(dev->target->bus);
4825 }
4826
4827 void
4828 xpt_release_simq(struct cam_sim *sim, int run_queue)
4829 {
4830         struct  camq *sendq;
4831
4832         sim_lock_assert_owned(sim->lock);
4833
4834         if (sim->devq == NULL)
4835                 return;
4836
4837         sendq = &(sim->devq->send_queue);
4838         if (sendq->qfrozen_cnt > 0) {
4839                 sendq->qfrozen_cnt--;
4840                 if (sendq->qfrozen_cnt == 0) {
4841                         struct cam_eb *bus;
4842
4843                         /*
4844                          * If there is a timeout scheduled to release this
4845                          * sim queue, remove it.  The queue frozen count is
4846                          * already at 0.
4847                          */
4848                         if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4849                                 callout_stop(&sim->callout);
4850                                 sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4851                         }
4852                         bus = xpt_find_bus(sim->path_id);
4853
4854                         if (run_queue) {
4855                                 /*
4856                                  * Now that we are unfrozen run the send queue.
4857                                  */
4858                                 xpt_run_dev_sendq(bus);
4859                         }
4860                         xpt_release_bus(bus);
4861                 }
4862         }
4863 }
4864
4865 void
4866 xpt_done(union ccb *done_ccb)
4867 {
4868         struct cam_sim *sim;
4869
4870         CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_done\n"));
4871         if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
4872                 /*
4873                  * Queue up the request for handling by our SWI handler
4874                  * any of the "non-immediate" type of ccbs.
4875                  */
4876                 sim = done_ccb->ccb_h.path->bus->sim;
4877                 switch (done_ccb->ccb_h.path->periph->type) {
4878                 case CAM_PERIPH_BIO:
4879                         spin_lock_wr(&sim->sim_spin);
4880                         TAILQ_INSERT_TAIL(&sim->sim_doneq, &done_ccb->ccb_h,
4881                                           sim_links.tqe);
4882                         done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4883                         spin_unlock_wr(&sim->sim_spin);
4884                         if ((sim->flags & CAM_SIM_ON_DONEQ) == 0) {
4885                                 spin_lock_wr(&cam_simq_spin);
4886                                 if ((sim->flags & CAM_SIM_ON_DONEQ) == 0) {
4887                                         TAILQ_INSERT_TAIL(&cam_simq, sim,
4888                                                           links);
4889                                         sim->flags |= CAM_SIM_ON_DONEQ;
4890                                 }
4891                                 spin_unlock_wr(&cam_simq_spin);
4892                         }
4893                         if ((done_ccb->ccb_h.flags & CAM_POLLED) == 0)
4894                                 setsoftcambio();
4895                         break;
4896                 default:
4897                         panic("unknown periph type %d",
4898                                 done_ccb->ccb_h.path->periph->type);
4899                 }
4900         }
4901 }
4902
4903 union ccb *
4904 xpt_alloc_ccb(void)
4905 {
4906         union ccb *new_ccb;
4907
4908         new_ccb = kmalloc(sizeof(*new_ccb), M_CAMXPT, M_INTWAIT | M_ZERO);
4909         return (new_ccb);
4910 }
4911
4912 void
4913 xpt_free_ccb(union ccb *free_ccb)
4914 {
4915         kfree(free_ccb, M_CAMXPT);
4916 }
4917
4918
4919
4920 /* Private XPT functions */
4921
4922 /*
4923  * Get a CAM control block for the caller. Charge the structure to the device
4924  * referenced by the path.  If the this device has no 'credits' then the
4925  * device already has the maximum number of outstanding operations under way
4926  * and we return NULL. If we don't have sufficient resources to allocate more
4927  * ccbs, we also return NULL.
4928  */
4929 static union ccb *
4930 xpt_get_ccb(struct cam_ed *device)
4931 {
4932         union ccb *new_ccb;
4933         struct cam_sim *sim;
4934
4935         sim = device->sim;
4936         if ((new_ccb = (union ccb *)SLIST_FIRST(&sim->ccb_freeq)) == NULL) {
4937                 new_ccb = xpt_alloc_ccb();
4938                 if ((sim->flags & CAM_SIM_MPSAFE) == 0)
4939                         callout_init(&new_ccb->ccb_h.timeout_ch);
4940                 SLIST_INSERT_HEAD(&sim->ccb_freeq, &new_ccb->ccb_h,
4941                                   xpt_links.sle);
4942                 sim->ccb_count++;
4943         }
4944         cam_ccbq_take_opening(&device->ccbq);
4945         SLIST_REMOVE_HEAD(&sim->ccb_freeq, xpt_links.sle);
4946         return (new_ccb);
4947 }
4948
4949 static void
4950 xpt_release_bus(struct cam_eb *bus)
4951 {
4952
4953         if ((--bus->refcount == 0)
4954          && (TAILQ_FIRST(&bus->et_entries) == NULL)) {
4955                 lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
4956                 TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4957                 xsoftc.bus_generation++;
4958                 lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
4959                 kfree(bus, M_CAMXPT);
4960         }
4961 }
4962
4963 static struct cam_et *
4964 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4965 {
4966         struct cam_et *target;
4967         struct cam_et *cur_target;
4968
4969         target = kmalloc(sizeof(*target), M_CAMXPT, M_INTWAIT);
4970
4971         TAILQ_INIT(&target->ed_entries);
4972         target->bus = bus;
4973         target->target_id = target_id;
4974         target->refcount = 1;
4975         target->generation = 0;
4976         timevalclear(&target->last_reset);
4977         /*
4978          * Hold a reference to our parent bus so it
4979          * will not go away before we do.
4980          */
4981         bus->refcount++;
4982
4983         /* Insertion sort into our bus's target list */
4984         cur_target = TAILQ_FIRST(&bus->et_entries);
4985         while (cur_target != NULL && cur_target->target_id < target_id)
4986                 cur_target = TAILQ_NEXT(cur_target, links);
4987
4988         if (cur_target != NULL) {
4989                 TAILQ_INSERT_BEFORE(cur_target, target, links);
4990         } else {
4991                 TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4992         }
4993         bus->generation++;
4994         return (target);
4995 }
4996
4997 static void
4998 xpt_release_target(struct cam_eb *bus, struct cam_et *target)
4999 {
5000         if (target->refcount == 1) {
5001                 KKASSERT(TAILQ_FIRST(&target->ed_entries) == NULL);
5002                 TAILQ_REMOVE(&bus->et_entries, target, links);
5003                 bus->generation++;
5004                 xpt_release_bus(bus);
5005                 KKASSERT(target->refcount == 1);
5006                 kfree(target, M_CAMXPT);
5007         } else {
5008                 --target->refcount;
5009         }
5010 }
5011
5012 static struct cam_ed *
5013 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
5014 {
5015         struct     cam_path path;
5016         struct     cam_ed *device;
5017         struct     cam_devq *devq;
5018         cam_status status;
5019
5020         /*
5021          * Disallow new devices while trying to deregister a sim
5022          */
5023         if (bus->sim->flags & CAM_SIM_DEREGISTERED)
5024                 return (NULL);
5025
5026         /*
5027          * Make space for us in the device queue on our bus
5028          */
5029         devq = bus->sim->devq;
5030         if (devq == NULL)
5031                 return(NULL);
5032         status = cam_devq_resize(devq, devq->alloc_queue.array_size + 1);
5033
5034         if (status != CAM_REQ_CMP) {
5035                 device = NULL;
5036         } else {
5037                 device = kmalloc(sizeof(*device), M_CAMXPT, M_INTWAIT);
5038         }
5039
5040         if (device != NULL) {
5041                 struct cam_ed *cur_device;
5042
5043                 cam_init_pinfo(&device->alloc_ccb_entry.pinfo);
5044                 device->alloc_ccb_entry.device = device;
5045                 cam_init_pinfo(&device->send_ccb_entry.pinfo);
5046                 device->send_ccb_entry.device = device;
5047                 device->target = target;
5048                 device->lun_id = lun_id;
5049                 device->sim = bus->sim;
5050                 /* Initialize our queues */
5051                 if (camq_init(&device->drvq, 0) != 0) {
5052                         kfree(device, M_CAMXPT);
5053                         return (NULL);
5054                 }
5055                 if (cam_ccbq_init(&device->ccbq,
5056                                   bus->sim->max_dev_openings) != 0) {
5057                         camq_fini(&device->drvq);
5058                         kfree(device, M_CAMXPT);
5059                         return (NULL);
5060                 }
5061                 SLIST_INIT(&device->asyncs);
5062                 SLIST_INIT(&device->periphs);
5063                 device->generation = 0;
5064                 device->owner = NULL;
5065                 /*
5066                  * Take the default quirk entry until we have inquiry
5067                  * data and can determine a better quirk to use.
5068                  */
5069                 device->quirk = &xpt_quirk_table[xpt_quirk_table_size - 1];
5070                 bzero(&device->inq_data, sizeof(device->inq_data));
5071                 device->inq_flags = 0;
5072                 device->queue_flags = 0;
5073                 device->serial_num = NULL;
5074                 device->serial_num_len = 0;
5075                 device->qfrozen_cnt = 0;
5076                 device->flags = CAM_DEV_UNCONFIGURED;
5077                 device->tag_delay_count = 0;
5078                 device->tag_saved_openings = 0;
5079                 device->refcount = 1;
5080                 callout_init(&device->callout);
5081
5082                 /*
5083                  * Hold a reference to our parent target so it
5084                  * will not go away before we do.
5085                  */
5086                 target->refcount++;
5087
5088                 /*
5089                  * XXX should be limited by number of CCBs this bus can
5090                  * do.
5091                  */
5092                 bus->sim->max_ccbs += device->ccbq.devq_openings;
5093                 /* Insertion sort into our target's device list */
5094                 cur_device = TAILQ_FIRST(&target->ed_entries);
5095                 while (cur_device != NULL && cur_device->lun_id < lun_id)
5096                         cur_device = TAILQ_NEXT(cur_device, links);
5097                 if (cur_device != NULL) {
5098                         TAILQ_INSERT_BEFORE(cur_device, device, links);
5099                 } else {
5100                         TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
5101                 }
5102                 target->generation++;
5103                 if (lun_id != CAM_LUN_WILDCARD) {
5104                         xpt_compile_path(&path,
5105                                          NULL,
5106                                          bus->path_id,
5107                                          target->target_id,
5108                                          lun_id);
5109                         xpt_devise_transport(&path);
5110                         xpt_release_path(&path);
5111                 }
5112         }
5113         return (device);
5114 }
5115
5116 static void
5117 xpt_reference_device(struct cam_ed *device)
5118 {
5119         ++device->refcount;
5120 }
5121
5122 static void
5123 xpt_release_device(struct cam_eb *bus, struct cam_et *target,
5124                    struct cam_ed *device)
5125 {
5126         struct cam_devq *devq;
5127
5128         if (device->refcount == 1) {
5129                 KKASSERT(device->flags & CAM_DEV_UNCONFIGURED);
5130
5131                 if (device->alloc_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX
5132                  || device->send_ccb_entry.pinfo.index != CAM_UNQUEUED_INDEX)
5133                         panic("Removing device while still queued for ccbs");
5134
5135                 if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
5136                         device->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
5137                         callout_stop(&device->callout);
5138                 }
5139
5140                 TAILQ_REMOVE(&target->ed_entries, device,links);
5141                 target->generation++;
5142                 bus->sim->max_ccbs -= device->ccbq.devq_openings;
5143                 if ((devq = bus->sim->devq) != NULL) {
5144                         /* Release our slot in the devq */
5145                         cam_devq_resize(devq, devq->alloc_queue.array_size - 1);
5146                 }
5147                 camq_fini(&device->drvq);
5148                 camq_fini(&device->ccbq.queue);
5149                 xpt_release_target(bus, target);
5150                 KKASSERT(device->refcount == 1);
5151                 kfree(device, M_CAMXPT);
5152         } else {
5153                 --device->refcount;
5154         }
5155 }
5156
5157 static u_int32_t
5158 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
5159 {
5160         int     diff;
5161         int     result;
5162         struct  cam_ed *dev;
5163
5164         dev = path->device;
5165
5166         diff = newopenings - (dev->ccbq.dev_active + dev->ccbq.dev_openings);
5167         result = cam_ccbq_resize(&dev->ccbq, newopenings);
5168         if (result == CAM_REQ_CMP && (diff < 0)) {
5169                 dev->flags |= CAM_DEV_RESIZE_QUEUE_NEEDED;
5170         }
5171         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5172          || (dev->inq_flags & SID_CmdQue) != 0)
5173                 dev->tag_saved_openings = newopenings;
5174         /* Adjust the global limit */
5175         dev->sim->max_ccbs += diff;
5176         return (result);
5177 }
5178
5179 static struct cam_eb *
5180 xpt_find_bus(path_id_t path_id)
5181 {
5182         struct cam_eb *bus;
5183
5184         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
5185         TAILQ_FOREACH(bus, &xsoftc.xpt_busses, links) {
5186                 if (bus->path_id == path_id) {
5187                         bus->refcount++;
5188                         break;
5189                 }
5190         }
5191         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
5192         return (bus);
5193 }
5194
5195 static struct cam_et *
5196 xpt_find_target(struct cam_eb *bus, target_id_t target_id)
5197 {
5198         struct cam_et *target;
5199
5200         TAILQ_FOREACH(target, &bus->et_entries, links) {
5201                 if (target->target_id == target_id) {
5202                         target->refcount++;
5203                         break;
5204                 }
5205         }
5206         return (target);
5207 }
5208
5209 static struct cam_ed *
5210 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
5211 {
5212         struct cam_ed *device;
5213
5214         TAILQ_FOREACH(device, &target->ed_entries, links) {
5215                 if (device->lun_id == lun_id) {
5216                         device->refcount++;
5217                         break;
5218                 }
5219         }
5220         return (device);
5221 }
5222
5223 typedef struct {
5224         union   ccb *request_ccb;
5225         struct  ccb_pathinq *cpi;
5226         int     counter;
5227 } xpt_scan_bus_info;
5228
5229 /*
5230  * To start a scan, request_ccb is an XPT_SCAN_BUS ccb.
5231  * As the scan progresses, xpt_scan_bus is used as the
5232  * callback on completion function.
5233  */
5234 static void
5235 xpt_scan_bus(struct cam_periph *periph, union ccb *request_ccb)
5236 {
5237         CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
5238                   ("xpt_scan_bus\n"));
5239         switch (request_ccb->ccb_h.func_code) {
5240         case XPT_SCAN_BUS:
5241         {
5242                 xpt_scan_bus_info *scan_info;
5243                 union   ccb *work_ccb;
5244                 struct  cam_path *path;
5245                 u_int   i;
5246                 u_int   max_target;
5247                 u_int   initiator_id;
5248
5249                 /* Find out the characteristics of the bus */
5250                 work_ccb = xpt_alloc_ccb();
5251                 xpt_setup_ccb(&work_ccb->ccb_h, request_ccb->ccb_h.path,
5252                               request_ccb->ccb_h.pinfo.priority);
5253                 work_ccb->ccb_h.func_code = XPT_PATH_INQ;
5254                 xpt_action(work_ccb);
5255                 if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
5256                         request_ccb->ccb_h.status = work_ccb->ccb_h.status;
5257                         xpt_free_ccb(work_ccb);
5258                         xpt_done(request_ccb);
5259                         return;
5260                 }
5261
5262                 if ((work_ccb->cpi.hba_misc & PIM_NOINITIATOR) != 0) {
5263                         /*
5264                          * Can't scan the bus on an adapter that
5265                          * cannot perform the initiator role.
5266                          */
5267                         request_ccb->ccb_h.status = CAM_REQ_CMP;
5268                         xpt_free_ccb(work_ccb);
5269                         xpt_done(request_ccb);
5270                         return;
5271                 }
5272
5273                 /* Save some state for use while we probe for devices */
5274                 scan_info = (xpt_scan_bus_info *)
5275                     kmalloc(sizeof(xpt_scan_bus_info), M_CAMXPT, M_INTWAIT);
5276                 scan_info->request_ccb = request_ccb;
5277                 scan_info->cpi = &work_ccb->cpi;
5278
5279                 /* Cache on our stack so we can work asynchronously */
5280                 max_target = scan_info->cpi->max_target;
5281                 initiator_id = scan_info->cpi->initiator_id;
5282
5283
5284                 /*
5285                  * We can scan all targets in parallel, or do it sequentially.
5286                  */
5287                 if (scan_info->cpi->hba_misc & PIM_SEQSCAN) {
5288                         max_target = 0;
5289                         scan_info->counter = 0;
5290                 } else {
5291                         scan_info->counter = scan_info->cpi->max_target + 1;
5292                         if (scan_info->cpi->initiator_id < scan_info->counter) {
5293                                 scan_info->counter--;
5294                         }
5295                 }
5296
5297                 for (i = 0; i <= max_target; i++) {
5298                         cam_status status;
5299                         if (i == initiator_id)
5300                                 continue;
5301
5302                         status = xpt_create_path(&path, xpt_periph,
5303                                                  request_ccb->ccb_h.path_id,
5304                                                  i, 0);
5305                         if (status != CAM_REQ_CMP) {
5306                                 kprintf("xpt_scan_bus: xpt_create_path failed"
5307                                        " with status %#x, bus scan halted\n",
5308                                        status);
5309                                 kfree(scan_info, M_CAMXPT);
5310                                 request_ccb->ccb_h.status = status;
5311                                 xpt_free_ccb(work_ccb);
5312                                 xpt_done(request_ccb);
5313                                 break;
5314                         }
5315                         work_ccb = xpt_alloc_ccb();
5316                         xpt_setup_ccb(&work_ccb->ccb_h, path,
5317                                       request_ccb->ccb_h.pinfo.priority);
5318                         work_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5319                         work_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5320                         work_ccb->ccb_h.ppriv_ptr0 = scan_info;
5321                         work_ccb->crcn.flags = request_ccb->crcn.flags;
5322                         xpt_action(work_ccb);
5323                 }
5324                 break;
5325         }
5326         case XPT_SCAN_LUN:
5327         {
5328                 cam_status status;
5329                 struct cam_path *path;
5330                 xpt_scan_bus_info *scan_info;
5331                 path_id_t path_id;
5332                 target_id_t target_id;
5333                 lun_id_t lun_id;
5334
5335                 /* Reuse the same CCB to query if a device was really found */
5336                 scan_info = (xpt_scan_bus_info *)request_ccb->ccb_h.ppriv_ptr0;
5337                 xpt_setup_ccb(&request_ccb->ccb_h, request_ccb->ccb_h.path,
5338                               request_ccb->ccb_h.pinfo.priority);
5339                 request_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
5340
5341                 path_id = request_ccb->ccb_h.path_id;
5342                 target_id = request_ccb->ccb_h.target_id;
5343                 lun_id = request_ccb->ccb_h.target_lun;
5344                 xpt_action(request_ccb);
5345
5346                 if (request_ccb->ccb_h.status != CAM_REQ_CMP) {
5347                         struct cam_ed *device;
5348                         struct cam_et *target;
5349                         int phl;
5350
5351                         /*
5352                          * If we already probed lun 0 successfully, or
5353                          * we have additional configured luns on this
5354                          * target that might have "gone away", go onto
5355                          * the next lun.
5356                          */
5357                         target = request_ccb->ccb_h.path->target;
5358                         /*
5359                          * We may touch devices that we don't
5360                          * hold references too, so ensure they
5361                          * don't disappear out from under us.
5362                          * The target above is referenced by the
5363                          * path in the request ccb.
5364                          */
5365                         phl = 0;
5366                         device = TAILQ_FIRST(&target->ed_entries);
5367                         if (device != NULL) {
5368                                 phl = CAN_SRCH_HI_SPARSE(device);
5369                                 if (device->lun_id == 0)
5370                                         device = TAILQ_NEXT(device, links);
5371                         }
5372                         if ((lun_id != 0) || (device != NULL)) {
5373                                 if (lun_id < (CAM_SCSI2_MAXLUN-1) || phl)
5374                                         lun_id++;
5375                         }
5376                 } else {
5377                         struct cam_ed *device;
5378
5379                         device = request_ccb->ccb_h.path->device;
5380
5381                         if ((device->quirk->quirks & CAM_QUIRK_NOLUNS) == 0) {
5382                                 /* Try the next lun */
5383                                 if (lun_id < (CAM_SCSI2_MAXLUN-1)
5384                                   || CAN_SRCH_HI_DENSE(device))
5385                                         lun_id++;
5386                         }
5387                 }
5388
5389                 /*
5390                  * Free the current request path- we're done with it.
5391                  */
5392                 xpt_free_path(request_ccb->ccb_h.path);
5393
5394                 /*
5395                  * Check to see if we scan any further luns.
5396                  */
5397                 if (lun_id == request_ccb->ccb_h.target_lun
5398                  || lun_id > scan_info->cpi->max_lun) {
5399                         int done;
5400
5401  hop_again:
5402                         done = 0;
5403                         if (scan_info->cpi->hba_misc & PIM_SEQSCAN) {
5404                                 scan_info->counter++;
5405                                 if (scan_info->counter ==
5406                                     scan_info->cpi->initiator_id) {
5407                                         scan_info->counter++;
5408                                 }
5409                                 if (scan_info->counter >=
5410                                     scan_info->cpi->max_target+1) {
5411                                         done = 1;
5412                                 }
5413                         } else {
5414                                 scan_info->counter--;
5415                                 if (scan_info->counter == 0) {
5416                                         done = 1;
5417                                 }
5418                         }
5419                         if (done) {
5420                                 xpt_free_ccb(request_ccb);
5421                                 xpt_free_ccb((union ccb *)scan_info->cpi);
5422                                 request_ccb = scan_info->request_ccb;
5423                                 kfree(scan_info, M_CAMXPT);
5424                                 request_ccb->ccb_h.status = CAM_REQ_CMP;
5425                                 xpt_done(request_ccb);
5426                                 break;
5427                         }
5428
5429                         if ((scan_info->cpi->hba_misc & PIM_SEQSCAN) == 0) {
5430                                 break;
5431                         }
5432                         status = xpt_create_path(&path, xpt_periph,
5433                             scan_info->request_ccb->ccb_h.path_id,
5434                             scan_info->counter, 0);
5435                         if (status != CAM_REQ_CMP) {
5436                                 kprintf("xpt_scan_bus: xpt_create_path failed"
5437                                     " with status %#x, bus scan halted\n",
5438                                     status);
5439                                 xpt_free_ccb(request_ccb);
5440                                 xpt_free_ccb((union ccb *)scan_info->cpi);
5441                                 request_ccb = scan_info->request_ccb;
5442                                 kfree(scan_info, M_CAMXPT);
5443                                 request_ccb->ccb_h.status = status;
5444                                 xpt_done(request_ccb);
5445                                 break;
5446                         }
5447                         xpt_setup_ccb(&request_ccb->ccb_h, path,
5448                             request_ccb->ccb_h.pinfo.priority);
5449                         request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5450                         request_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5451                         request_ccb->ccb_h.ppriv_ptr0 = scan_info;
5452                         request_ccb->crcn.flags =
5453                             scan_info->request_ccb->crcn.flags;
5454                 } else {
5455                         status = xpt_create_path(&path, xpt_periph,
5456                                                  path_id, target_id, lun_id);
5457                         if (status != CAM_REQ_CMP) {
5458                                 kprintf("xpt_scan_bus: xpt_create_path failed "
5459                                        "with status %#x, halting LUN scan\n",
5460                                        status);
5461                                 goto hop_again;
5462                         }
5463                         xpt_setup_ccb(&request_ccb->ccb_h, path,
5464                                       request_ccb->ccb_h.pinfo.priority);
5465                         request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5466                         request_ccb->ccb_h.cbfcnp = xpt_scan_bus;
5467                         request_ccb->ccb_h.ppriv_ptr0 = scan_info;
5468                         request_ccb->crcn.flags =
5469                                 scan_info->request_ccb->crcn.flags;
5470                 }
5471                 xpt_action(request_ccb);
5472                 break;
5473         }
5474         default:
5475                 break;
5476         }
5477 }
5478
5479 typedef enum {
5480         PROBE_TUR,
5481         PROBE_INQUIRY,  /* this counts as DV0 for Basic Domain Validation */
5482         PROBE_FULL_INQUIRY,
5483         PROBE_MODE_SENSE,
5484         PROBE_SERIAL_NUM_0,
5485         PROBE_SERIAL_NUM_1,
5486         PROBE_TUR_FOR_NEGOTIATION,
5487         PROBE_INQUIRY_BASIC_DV1,
5488         PROBE_INQUIRY_BASIC_DV2,
5489         PROBE_DV_EXIT
5490 } probe_action;
5491
5492 typedef enum {
5493         PROBE_INQUIRY_CKSUM     = 0x01,
5494         PROBE_SERIAL_CKSUM      = 0x02,
5495         PROBE_NO_ANNOUNCE       = 0x04
5496 } probe_flags;
5497
5498 typedef struct {
5499         TAILQ_HEAD(, ccb_hdr) request_ccbs;
5500         probe_action    action;
5501         union ccb       saved_ccb;
5502         probe_flags     flags;
5503         MD5_CTX         context;
5504         u_int8_t        digest[16];
5505 } probe_softc;
5506
5507 static void
5508 xpt_scan_lun(struct cam_periph *periph, struct cam_path *path,
5509              cam_flags flags, union ccb *request_ccb)
5510 {
5511         struct ccb_pathinq cpi;
5512         cam_status status;
5513         struct cam_path *new_path;
5514         struct cam_periph *old_periph;
5515         
5516         CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
5517                   ("xpt_scan_lun\n"));
5518
5519         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
5520         cpi.ccb_h.func_code = XPT_PATH_INQ;
5521         xpt_action((union ccb *)&cpi);
5522
5523         if (cpi.ccb_h.status != CAM_REQ_CMP) {
5524                 if (request_ccb != NULL) {
5525                         request_ccb->ccb_h.status = cpi.ccb_h.status;
5526                         xpt_done(request_ccb);
5527                 }
5528                 return;
5529         }
5530
5531         if ((cpi.hba_misc & PIM_NOINITIATOR) != 0) {
5532                 /*
5533                  * Can't scan the bus on an adapter that
5534                  * cannot perform the initiator role.
5535                  */
5536                 if (request_ccb != NULL) {
5537                         request_ccb->ccb_h.status = CAM_REQ_CMP;
5538                         xpt_done(request_ccb);
5539                 }
5540                 return;
5541         }
5542
5543         if (request_ccb == NULL) {
5544                 request_ccb = kmalloc(sizeof(union ccb), M_CAMXPT, M_INTWAIT);
5545                 new_path = kmalloc(sizeof(*new_path), M_CAMXPT, M_INTWAIT);
5546                 status = xpt_compile_path(new_path, xpt_periph,
5547                                           path->bus->path_id,
5548                                           path->target->target_id,
5549                                           path->device->lun_id);
5550
5551                 if (status != CAM_REQ_CMP) {
5552                         xpt_print(path, "xpt_scan_lun: can't compile path, "
5553                             "can't continue\n");
5554                         kfree(request_ccb, M_CAMXPT);
5555                         kfree(new_path, M_CAMXPT);
5556                         return;
5557                 }
5558                 xpt_setup_ccb(&request_ccb->ccb_h, new_path, /*priority*/ 1);
5559                 request_ccb->ccb_h.cbfcnp = xptscandone;
5560                 request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
5561                 request_ccb->crcn.flags = flags;
5562         }
5563
5564         if ((old_periph = cam_periph_find(path, "probe")) != NULL) {
5565                 probe_softc *softc;
5566
5567                 softc = (probe_softc *)old_periph->softc;
5568                 TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5569                                   periph_links.tqe);
5570         } else {
5571                 status = cam_periph_alloc(proberegister, NULL, probecleanup,
5572                                           probestart, "probe",
5573                                           CAM_PERIPH_BIO,
5574                                           request_ccb->ccb_h.path, NULL, 0,
5575                                           request_ccb);
5576
5577                 if (status != CAM_REQ_CMP) {
5578                         xpt_print(path, "xpt_scan_lun: cam_alloc_periph "
5579                             "returned an error, can't continue probe\n");
5580                         request_ccb->ccb_h.status = status;
5581                         xpt_done(request_ccb);
5582                 }
5583         }
5584 }
5585
5586 static void
5587 xptscandone(struct cam_periph *periph, union ccb *done_ccb)
5588 {
5589         xpt_release_path(done_ccb->ccb_h.path);
5590         kfree(done_ccb->ccb_h.path, M_CAMXPT);
5591         kfree(done_ccb, M_CAMXPT);
5592 }
5593
5594 static cam_status
5595 proberegister(struct cam_periph *periph, void *arg)
5596 {
5597         union ccb *request_ccb; /* CCB representing the probe request */
5598         cam_status status;
5599         probe_softc *softc;
5600
5601         request_ccb = (union ccb *)arg;
5602         if (periph == NULL) {
5603                 kprintf("proberegister: periph was NULL!!\n");
5604                 return(CAM_REQ_CMP_ERR);
5605         }
5606
5607         if (request_ccb == NULL) {
5608                 kprintf("proberegister: no probe CCB, "
5609                        "can't register device\n");
5610                 return(CAM_REQ_CMP_ERR);
5611         }
5612
5613         softc = kmalloc(sizeof(*softc), M_CAMXPT, M_INTWAIT | M_ZERO);
5614         TAILQ_INIT(&softc->request_ccbs);
5615         TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
5616                           periph_links.tqe);
5617         softc->flags = 0;
5618         periph->softc = softc;
5619         status = cam_periph_acquire(periph);
5620         if (status != CAM_REQ_CMP) {
5621                 return (status);
5622         }
5623
5624
5625         /*
5626          * Ensure we've waited at least a bus settle
5627          * delay before attempting to probe the device.
5628          * For HBAs that don't do bus resets, this won't make a difference.
5629          */
5630         cam_periph_freeze_after_event(periph, &periph->path->bus->last_reset,
5631                                       scsi_delay);
5632         probeschedule(periph);
5633         return(CAM_REQ_CMP);
5634 }
5635
5636 static void
5637 probeschedule(struct cam_periph *periph)
5638 {
5639         struct ccb_pathinq cpi;
5640         union ccb *ccb;
5641         probe_softc *softc;
5642
5643         softc = (probe_softc *)periph->softc;
5644         ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
5645
5646         xpt_setup_ccb(&cpi.ccb_h, periph->path, /*priority*/1);
5647         cpi.ccb_h.func_code = XPT_PATH_INQ;
5648         xpt_action((union ccb *)&cpi);
5649
5650         /*
5651          * If a device has gone away and another device, or the same one,
5652          * is back in the same place, it should have a unit attention
5653          * condition pending.  It will not report the unit attention in
5654          * response to an inquiry, which may leave invalid transfer
5655          * negotiations in effect.  The TUR will reveal the unit attention
5656          * condition.  Only send the TUR for lun 0, since some devices
5657          * will get confused by commands other than inquiry to non-existent
5658          * luns.  If you think a device has gone away start your scan from
5659          * lun 0.  This will insure that any bogus transfer settings are
5660          * invalidated.
5661          *
5662          * If we haven't seen the device before and the controller supports
5663          * some kind of transfer negotiation, negotiate with the first
5664          * sent command if no bus reset was performed at startup.  This
5665          * ensures that the device is not confused by transfer negotiation
5666          * settings left over by loader or BIOS action.
5667          */
5668         if (((ccb->ccb_h.path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
5669          && (ccb->ccb_h.target_lun == 0)) {
5670                 softc->action = PROBE_TUR;
5671         } else if ((cpi.hba_inquiry & (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE)) != 0
5672               && (cpi.hba_misc & PIM_NOBUSRESET) != 0) {
5673                 proberequestdefaultnegotiation(periph);
5674                 softc->action = PROBE_INQUIRY;
5675         } else {
5676                 softc->action = PROBE_INQUIRY;
5677         }
5678
5679         if (ccb->crcn.flags & CAM_EXPECT_INQ_CHANGE)
5680                 softc->flags |= PROBE_NO_ANNOUNCE;
5681         else
5682                 softc->flags &= ~PROBE_NO_ANNOUNCE;
5683
5684         xpt_schedule(periph, ccb->ccb_h.pinfo.priority);
5685 }
5686
5687 static void
5688 probestart(struct cam_periph *periph, union ccb *start_ccb)
5689 {
5690         /* Probe the device that our peripheral driver points to */
5691         struct ccb_scsiio *csio;
5692         probe_softc *softc;
5693
5694         CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probestart\n"));
5695
5696         softc = (probe_softc *)periph->softc;
5697         csio = &start_ccb->csio;
5698
5699         switch (softc->action) {
5700         case PROBE_TUR:
5701         case PROBE_TUR_FOR_NEGOTIATION:
5702         case PROBE_DV_EXIT:
5703         {
5704                 scsi_test_unit_ready(csio,
5705                                      /*retries*/4,
5706                                      probedone,
5707                                      MSG_SIMPLE_Q_TAG,
5708                                      SSD_FULL_SIZE,
5709                                      /*timeout*/60000);
5710                 break;
5711         }
5712         case PROBE_INQUIRY:
5713         case PROBE_FULL_INQUIRY:
5714         case PROBE_INQUIRY_BASIC_DV1:
5715         case PROBE_INQUIRY_BASIC_DV2:
5716         {
5717                 u_int inquiry_len;
5718                 struct scsi_inquiry_data *inq_buf;
5719
5720                 inq_buf = &periph->path->device->inq_data;
5721
5722                 /*
5723                  * If the device is currently configured, we calculate an
5724                  * MD5 checksum of the inquiry data, and if the serial number
5725                  * length is greater than 0, add the serial number data
5726                  * into the checksum as well.  Once the inquiry and the
5727                  * serial number check finish, we attempt to figure out
5728                  * whether we still have the same device.
5729                  */
5730                 if ((periph->path->device->flags & CAM_DEV_UNCONFIGURED) == 0) {
5731
5732                         MD5Init(&softc->context);
5733                         MD5Update(&softc->context, (unsigned char *)inq_buf,
5734                                   sizeof(struct scsi_inquiry_data));
5735                         softc->flags |= PROBE_INQUIRY_CKSUM;
5736                         if (periph->path->device->serial_num_len > 0) {
5737                                 MD5Update(&softc->context,
5738                                           periph->path->device->serial_num,
5739                                           periph->path->device->serial_num_len);
5740                                 softc->flags |= PROBE_SERIAL_CKSUM;
5741                         }
5742                         MD5Final(softc->digest, &softc->context);
5743                 }
5744
5745                 if (softc->action == PROBE_INQUIRY)
5746                         inquiry_len = SHORT_INQUIRY_LENGTH;
5747                 else
5748                         inquiry_len = SID_ADDITIONAL_LENGTH(inq_buf);
5749
5750                 /*
5751                  * Some parallel SCSI devices fail to send an
5752                  * ignore wide residue message when dealing with
5753                  * odd length inquiry requests.  Round up to be
5754                  * safe.
5755                  */
5756                 inquiry_len = roundup2(inquiry_len, 2);
5757
5758                 if (softc->action == PROBE_INQUIRY_BASIC_DV1
5759                  || softc->action == PROBE_INQUIRY_BASIC_DV2) {
5760                         inq_buf = kmalloc(inquiry_len, M_CAMXPT, M_INTWAIT);
5761                 }
5762                 scsi_inquiry(csio,
5763                              /*retries*/4,
5764                              probedone,
5765                              MSG_SIMPLE_Q_TAG,
5766                              (u_int8_t *)inq_buf,
5767                              inquiry_len,
5768                              /*evpd*/FALSE,
5769                              /*page_code*/0,
5770                              SSD_MIN_SIZE,
5771                              /*timeout*/60 * 1000);
5772                 break;
5773         }
5774         case PROBE_MODE_SENSE:
5775         {
5776                 void  *mode_buf;
5777                 int    mode_buf_len;
5778
5779                 mode_buf_len = sizeof(struct scsi_mode_header_6)
5780                              + sizeof(struct scsi_mode_blk_desc)
5781                              + sizeof(struct scsi_control_page);
5782                 mode_buf = kmalloc(mode_buf_len, M_CAMXPT, M_INTWAIT);
5783                 scsi_mode_sense(csio,
5784                                 /*retries*/4,
5785                                 probedone,
5786                                 MSG_SIMPLE_Q_TAG,
5787                                 /*dbd*/FALSE,
5788                                 SMS_PAGE_CTRL_CURRENT,
5789                                 SMS_CONTROL_MODE_PAGE,
5790                                 mode_buf,
5791                                 mode_buf_len,
5792                                 SSD_FULL_SIZE,
5793                                 /*timeout*/60000);
5794                 break;
5795         }
5796         case PROBE_SERIAL_NUM_0:
5797         {
5798                 struct scsi_vpd_supported_page_list *vpd_list = NULL;
5799                 struct cam_ed *device;
5800
5801                 device = periph->path->device;
5802                 if ((device->quirk->quirks & CAM_QUIRK_NOSERIAL) == 0) {
5803                         vpd_list = kmalloc(sizeof(*vpd_list), M_CAMXPT,
5804                             M_INTWAIT | M_ZERO);
5805                 }
5806
5807                 if (vpd_list != NULL) {
5808                         scsi_inquiry(csio,
5809                                      /*retries*/4,
5810                                      probedone,
5811                                      MSG_SIMPLE_Q_TAG,
5812                                      (u_int8_t *)vpd_list,
5813                                      sizeof(*vpd_list),
5814                                      /*evpd*/TRUE,
5815                                      SVPD_SUPPORTED_PAGE_LIST,
5816                                      SSD_MIN_SIZE,
5817                                      /*timeout*/60 * 1000);
5818                         break;
5819                 }
5820                 /*
5821                  * We'll have to do without, let our probedone
5822                  * routine finish up for us.
5823                  */
5824                 start_ccb->csio.data_ptr = NULL;
5825                 probedone(periph, start_ccb);
5826                 return;
5827         }
5828         case PROBE_SERIAL_NUM_1:
5829         {
5830                 struct scsi_vpd_unit_serial_number *serial_buf;
5831                 struct cam_ed* device;
5832
5833                 serial_buf = NULL;
5834                 device = periph->path->device;
5835                 device->serial_num = NULL;
5836                 device->serial_num_len = 0;
5837
5838                 serial_buf = (struct scsi_vpd_unit_serial_number *)
5839                         kmalloc(sizeof(*serial_buf), M_CAMXPT,
5840                                 M_INTWAIT | M_ZERO);
5841                 scsi_inquiry(csio,
5842                              /*retries*/4,
5843                              probedone,
5844                              MSG_SIMPLE_Q_TAG,
5845                              (u_int8_t *)serial_buf,
5846                              sizeof(*serial_buf),
5847                              /*evpd*/TRUE,
5848                              SVPD_UNIT_SERIAL_NUMBER,
5849                              SSD_MIN_SIZE,
5850                              /*timeout*/60 * 1000);
5851                 break;
5852         }
5853         }
5854         xpt_action(start_ccb);
5855 }
5856
5857 static void
5858 proberequestdefaultnegotiation(struct cam_periph *periph)
5859 {
5860         struct ccb_trans_settings cts;
5861
5862         xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
5863         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
5864         cts.type = CTS_TYPE_USER_SETTINGS;
5865         xpt_action((union ccb *)&cts);
5866         if ((cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5867                 return;
5868         }
5869         cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
5870         cts.type = CTS_TYPE_CURRENT_SETTINGS;
5871         xpt_action((union ccb *)&cts);
5872 }
5873
5874 /*
5875  * Backoff Negotiation Code- only pertinent for SPI devices.
5876  */
5877 static int
5878 proberequestbackoff(struct cam_periph *periph, struct cam_ed *device)
5879 {
5880         struct ccb_trans_settings cts;
5881         struct ccb_trans_settings_spi *spi;
5882
5883         memset(&cts, 0, sizeof (cts));
5884         xpt_setup_ccb(&cts.ccb_h, periph->path, /*priority*/1);
5885         cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
5886         cts.type = CTS_TYPE_CURRENT_SETTINGS;
5887         xpt_action((union ccb *)&cts);
5888         if ((cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5889                 if (bootverbose) {
5890                         xpt_print(periph->path,
5891                             "failed to get current device settings\n");
5892                 }
5893                 return (0);
5894         }
5895         if (cts.transport != XPORT_SPI) {
5896                 if (bootverbose) {
5897                         xpt_print(periph->path, "not SPI transport\n");
5898                 }
5899                 return (0);
5900         }
5901         spi = &cts.xport_specific.spi;
5902
5903         /*
5904          * We cannot renegotiate sync rate if we don't have one.
5905          */
5906         if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0) {
5907                 if (bootverbose) {
5908                         xpt_print(periph->path, "no sync rate known\n");
5909                 }
5910                 return (0);
5911         }
5912
5913         /*
5914          * We'll assert that we don't have to touch PPR options- the
5915          * SIM will see what we do with period and offset and adjust
5916          * the PPR options as appropriate.
5917          */
5918
5919         /*
5920          * A sync rate with unknown or zero offset is nonsensical.
5921          * A sync period of zero means Async.
5922          */
5923         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0
5924          || spi->sync_offset == 0 || spi->sync_period == 0) {
5925                 if (bootverbose) {
5926                         xpt_print(periph->path, "no sync rate available\n");
5927                 }
5928                 return (0);
5929         }
5930
5931         if (device->flags & CAM_DEV_DV_HIT_BOTTOM) {
5932                 CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5933                     ("hit async: giving up on DV\n"));
5934                 return (0);
5935         }
5936
5937
5938         /*
5939          * Jump sync_period up by one, but stop at 5MHz and fall back to Async.
5940          * We don't try to remember 'last' settings to see if the SIM actually
5941          * gets into the speed we want to set. We check on the SIM telling
5942          * us that a requested speed is bad, but otherwise don't try and
5943          * check the speed due to the asynchronous and handshake nature
5944          * of speed setting.
5945          */
5946         spi->valid = CTS_SPI_VALID_SYNC_RATE | CTS_SPI_VALID_SYNC_OFFSET;
5947         for (;;) {
5948                 spi->sync_period++;
5949                 if (spi->sync_period >= 0xf) {
5950                         spi->sync_period = 0;
5951                         spi->sync_offset = 0;
5952                         CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5953                             ("setting to async for DV\n"));
5954                         /*
5955                          * Once we hit async, we don't want to try
5956                          * any more settings.
5957                          */
5958                         device->flags |= CAM_DEV_DV_HIT_BOTTOM;
5959                 } else if (bootverbose) {
5960                         CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5961                             ("DV: period 0x%x\n", spi->sync_period));
5962                         kprintf("setting period to 0x%x\n", spi->sync_period);
5963                 }
5964                 cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
5965                 cts.type = CTS_TYPE_CURRENT_SETTINGS;
5966                 xpt_action((union ccb *)&cts);
5967                 if ((cts.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
5968                         break;
5969                 }
5970                 CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
5971                     ("DV: failed to set period 0x%x\n", spi->sync_period));
5972                 if (spi->sync_period == 0) {
5973                         return (0);
5974                 }
5975         }
5976         return (1);
5977 }
5978
5979 static void
5980 probedone(struct cam_periph *periph, union ccb *done_ccb)
5981 {
5982         probe_softc *softc;
5983         struct cam_path *path;
5984         u_int32_t  priority;
5985
5986         CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probedone\n"));
5987
5988         softc = (probe_softc *)periph->softc;
5989         path = done_ccb->ccb_h.path;
5990         priority = done_ccb->ccb_h.pinfo.priority;
5991
5992         switch (softc->action) {
5993         case PROBE_TUR:
5994         {
5995                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5996
5997                         if (cam_periph_error(done_ccb, 0,
5998                                              SF_NO_PRINT, NULL) == ERESTART)
5999                                 return;
6000                         else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
6001                                 /* Don't wedge the queue */
6002                                 xpt_release_devq(done_ccb->ccb_h.path,
6003                                                  /*count*/1,
6004                                                  /*run_queue*/TRUE);
6005                 }
6006                 softc->action = PROBE_INQUIRY;
6007                 xpt_release_ccb(done_ccb);
6008                 xpt_schedule(periph, priority);
6009                 return;
6010         }
6011         case PROBE_INQUIRY:
6012         case PROBE_FULL_INQUIRY:
6013         {
6014                 if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
6015                         struct scsi_inquiry_data *inq_buf;
6016                         u_int8_t periph_qual;
6017
6018                         path->device->flags |= CAM_DEV_INQUIRY_DATA_VALID;
6019                         inq_buf = &path->device->inq_data;
6020
6021                         periph_qual = SID_QUAL(inq_buf);
6022
6023                         switch(periph_qual) {
6024                         case SID_QUAL_LU_CONNECTED:
6025                         {
6026                                 u_int8_t len;
6027
6028                                 /*
6029                                  * We conservatively request only
6030                                  * SHORT_INQUIRY_LEN bytes of inquiry
6031                                  * information during our first try
6032                                  * at sending an INQUIRY. If the device
6033                                  * has more information to give,
6034                                  * perform a second request specifying
6035                                  * the amount of information the device
6036                                  * is willing to give.
6037                                  */
6038                                 len = inq_buf->additional_length
6039                                     + offsetof(struct scsi_inquiry_data,
6040                                                 additional_length) + 1;
6041                                 if (softc->action == PROBE_INQUIRY
6042                                     && len > SHORT_INQUIRY_LENGTH) {
6043                                         softc->action = PROBE_FULL_INQUIRY;
6044                                         xpt_release_ccb(done_ccb);
6045                                         xpt_schedule(periph, priority);
6046                                         return;
6047                                 }
6048
6049                                 xpt_find_quirk(path->device);
6050
6051                                 xpt_devise_transport(path);
6052                                 if (INQ_DATA_TQ_ENABLED(inq_buf))
6053                                         softc->action = PROBE_MODE_SENSE;
6054                                 else
6055                                         softc->action = PROBE_SERIAL_NUM_0;
6056
6057                                 path->device->flags &= ~CAM_DEV_UNCONFIGURED;
6058                                 xpt_reference_device(path->device);
6059
6060                                 xpt_release_ccb(done_ccb);
6061                                 xpt_schedule(periph, priority);
6062                                 return;
6063                         }
6064                         default:
6065                                 break;
6066                         }
6067                 } else if (cam_periph_error(done_ccb, 0,
6068                                             done_ccb->ccb_h.target_lun > 0
6069                                             ? SF_RETRY_UA|SF_QUIET_IR
6070                                             : SF_RETRY_UA,
6071                                             &softc->saved_ccb) == ERESTART) {
6072                         return;
6073                 } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6074                         /* Don't wedge the queue */
6075                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6076                                          /*run_queue*/TRUE);
6077                 }
6078                 /*
6079                  * If we get to this point, we got an error status back
6080                  * from the inquiry and the error status doesn't require
6081                  * automatically retrying the command.  Therefore, the
6082                  * inquiry failed.  If we had inquiry information before
6083                  * for this device, but this latest inquiry command failed,
6084                  * the device has probably gone away.  If this device isn't
6085                  * already marked unconfigured, notify the peripheral
6086                  * drivers that this device is no more.
6087                  */
6088                 if ((path->device->flags & CAM_DEV_UNCONFIGURED) == 0) {
6089                         /* Send the async notification. */
6090                         xpt_async(AC_LOST_DEVICE, path, NULL);
6091                 }
6092
6093                 xpt_release_ccb(done_ccb);
6094                 break;
6095         }
6096         case PROBE_MODE_SENSE:
6097         {
6098                 struct ccb_scsiio *csio;
6099                 struct scsi_mode_header_6 *mode_hdr;
6100
6101                 csio = &done_ccb->csio;
6102                 mode_hdr = (struct scsi_mode_header_6 *)csio->data_ptr;
6103                 if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
6104                         struct scsi_control_page *page;
6105                         u_int8_t *offset;
6106
6107                         offset = ((u_int8_t *)&mode_hdr[1])
6108                             + mode_hdr->blk_desc_len;
6109                         page = (struct scsi_control_page *)offset;
6110                         path->device->queue_flags = page->queue_flags;
6111                 } else if (cam_periph_error(done_ccb, 0,
6112                                             SF_RETRY_UA|SF_NO_PRINT,
6113                                             &softc->saved_ccb) == ERESTART) {
6114                         return;
6115                 } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6116                         /* Don't wedge the queue */
6117                         xpt_release_devq(done_ccb->ccb_h.path,
6118                                          /*count*/1, /*run_queue*/TRUE);
6119                 }
6120                 xpt_release_ccb(done_ccb);
6121                 kfree(mode_hdr, M_CAMXPT);
6122                 softc->action = PROBE_SERIAL_NUM_0;
6123                 xpt_schedule(periph, priority);
6124                 return;
6125         }
6126         case PROBE_SERIAL_NUM_0:
6127         {
6128                 struct ccb_scsiio *csio;
6129                 struct scsi_vpd_supported_page_list *page_list;
6130                 int length, serialnum_supported, i;
6131
6132                 serialnum_supported = 0;
6133                 csio = &done_ccb->csio;
6134                 page_list =
6135                     (struct scsi_vpd_supported_page_list *)csio->data_ptr;
6136
6137                 if (page_list == NULL) {
6138                         /*
6139                          * Don't process the command as it was never sent
6140                          */
6141                 } else if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP
6142                     && (page_list->length > 0)) {
6143                         length = min(page_list->length,
6144                             SVPD_SUPPORTED_PAGES_SIZE);
6145                         for (i = 0; i < length; i++) {
6146                                 if (page_list->list[i] ==
6147                                     SVPD_UNIT_SERIAL_NUMBER) {
6148                                         serialnum_supported = 1;
6149                                         break;
6150                                 }
6151                         }
6152                 } else if (cam_periph_error(done_ccb, 0,
6153                                             SF_RETRY_UA|SF_NO_PRINT,
6154                                             &softc->saved_ccb) == ERESTART) {
6155                         return;
6156                 } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6157                         /* Don't wedge the queue */
6158                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6159                                          /*run_queue*/TRUE);
6160                 }
6161
6162                 if (page_list != NULL)
6163                         kfree(page_list, M_DEVBUF);
6164
6165                 if (serialnum_supported) {
6166                         xpt_release_ccb(done_ccb);
6167                         softc->action = PROBE_SERIAL_NUM_1;
6168                         xpt_schedule(periph, priority);
6169                         return;
6170                 }
6171                 xpt_release_ccb(done_ccb);
6172                 softc->action = PROBE_TUR_FOR_NEGOTIATION;
6173                 xpt_schedule(periph, done_ccb->ccb_h.pinfo.priority);
6174                 return;
6175         }
6176
6177         case PROBE_SERIAL_NUM_1:
6178         {
6179                 struct ccb_scsiio *csio;
6180                 struct scsi_vpd_unit_serial_number *serial_buf;
6181                 u_int32_t  priority;
6182                 int changed;
6183                 int have_serialnum;
6184
6185                 changed = 1;
6186                 have_serialnum = 0;
6187                 csio = &done_ccb->csio;
6188                 priority = done_ccb->ccb_h.pinfo.priority;
6189                 serial_buf =
6190                     (struct scsi_vpd_unit_serial_number *)csio->data_ptr;
6191
6192                 /* Clean up from previous instance of this device */
6193                 if (path->device->serial_num != NULL) {
6194                         kfree(path->device->serial_num, M_CAMXPT);
6195                         path->device->serial_num = NULL;
6196                         path->device->serial_num_len = 0;
6197                 }
6198
6199                 if (serial_buf == NULL) {
6200                         /*
6201                          * Don't process the command as it was never sent
6202                          */
6203                 } else if ((csio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP
6204                         && (serial_buf->length > 0)) {
6205
6206                         have_serialnum = 1;
6207                         path->device->serial_num =
6208                                 kmalloc((serial_buf->length + 1),
6209                                        M_CAMXPT, M_INTWAIT);
6210                         bcopy(serial_buf->serial_num,
6211                               path->device->serial_num,
6212                               serial_buf->length);
6213                         path->device->serial_num_len = serial_buf->length;
6214                         path->device->serial_num[serial_buf->length] = '\0';
6215                 } else if (cam_periph_error(done_ccb, 0,
6216                                             SF_RETRY_UA|SF_NO_PRINT,
6217                                             &softc->saved_ccb) == ERESTART) {
6218                         return;
6219                 } else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6220                         /* Don't wedge the queue */
6221                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6222                                          /*run_queue*/TRUE);
6223                 }
6224
6225                 /*
6226                  * Let's see if we have seen this device before.
6227                  */
6228                 if ((softc->flags & PROBE_INQUIRY_CKSUM) != 0) {
6229                         MD5_CTX context;
6230                         u_int8_t digest[16];
6231
6232                         MD5Init(&context);
6233
6234                         MD5Update(&context,
6235                                   (unsigned char *)&path->device->inq_data,
6236                                   sizeof(struct scsi_inquiry_data));
6237
6238                         if (have_serialnum)
6239                                 MD5Update(&context, serial_buf->serial_num,
6240                                           serial_buf->length);
6241
6242                         MD5Final(digest, &context);
6243                         if (bcmp(softc->digest, digest, 16) == 0)
6244                                 changed = 0;
6245
6246                         /*
6247                          * XXX Do we need to do a TUR in order to ensure
6248                          *     that the device really hasn't changed???
6249                          */
6250                         if ((changed != 0)
6251                          && ((softc->flags & PROBE_NO_ANNOUNCE) == 0))
6252                                 xpt_async(AC_LOST_DEVICE, path, NULL);
6253                 }
6254                 if (serial_buf != NULL)
6255                         kfree(serial_buf, M_CAMXPT);
6256
6257                 if (changed != 0) {
6258                         /*
6259                          * Now that we have all the necessary
6260                          * information to safely perform transfer
6261                          * negotiations... Controllers don't perform
6262                          * any negotiation or tagged queuing until
6263                          * after the first XPT_SET_TRAN_SETTINGS ccb is
6264                          * received.  So, on a new device, just retrieve
6265                          * the user settings, and set them as the current
6266                          * settings to set the device up.
6267                          */
6268                         proberequestdefaultnegotiation(periph);
6269                         xpt_release_ccb(done_ccb);
6270
6271                         /*
6272                          * Perform a TUR to allow the controller to
6273                          * perform any necessary transfer negotiation.
6274                          */
6275                         softc->action = PROBE_TUR_FOR_NEGOTIATION;
6276                         xpt_schedule(periph, priority);
6277                         return;
6278                 }
6279                 xpt_release_ccb(done_ccb);
6280                 break;
6281         }
6282         case PROBE_TUR_FOR_NEGOTIATION:
6283         case PROBE_DV_EXIT:
6284                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6285                         /* Don't wedge the queue */
6286                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6287                                          /*run_queue*/TRUE);
6288                 }
6289
6290                 xpt_reference_device(path->device);
6291                 /*
6292                  * Do Domain Validation for lun 0 on devices that claim
6293                  * to support Synchronous Transfer modes.
6294                  */
6295                 if (softc->action == PROBE_TUR_FOR_NEGOTIATION
6296                  && done_ccb->ccb_h.target_lun == 0
6297                  && (path->device->inq_data.flags & SID_Sync) != 0
6298                  && (path->device->flags & CAM_DEV_IN_DV) == 0) {
6299                         CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
6300                             ("Begin Domain Validation\n"));
6301                         path->device->flags |= CAM_DEV_IN_DV;
6302                         xpt_release_ccb(done_ccb);
6303                         softc->action = PROBE_INQUIRY_BASIC_DV1;
6304                         xpt_schedule(periph, priority);
6305                         return;
6306                 }
6307                 if (softc->action == PROBE_DV_EXIT) {
6308                         CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
6309                             ("Leave Domain Validation\n"));
6310                 }
6311                 path->device->flags &=
6312                     ~(CAM_DEV_UNCONFIGURED|CAM_DEV_IN_DV|CAM_DEV_DV_HIT_BOTTOM);
6313                 if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
6314                         /* Inform the XPT that a new device has been found */
6315                         done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
6316                         xpt_action(done_ccb);
6317                         xpt_async(AC_FOUND_DEVICE, done_ccb->ccb_h.path,
6318                                   done_ccb);
6319                 }
6320                 xpt_release_ccb(done_ccb);
6321                 break;
6322         case PROBE_INQUIRY_BASIC_DV1:
6323         case PROBE_INQUIRY_BASIC_DV2:
6324         {
6325                 struct scsi_inquiry_data *nbuf;
6326                 struct ccb_scsiio *csio;
6327
6328                 if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
6329                         /* Don't wedge the queue */
6330                         xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
6331                                          /*run_queue*/TRUE);
6332                 }
6333                 csio = &done_ccb->csio;
6334                 nbuf = (struct scsi_inquiry_data *)csio->data_ptr;
6335                 if (bcmp(nbuf, &path->device->inq_data, SHORT_INQUIRY_LENGTH)) {
6336                         xpt_print(path,
6337                             "inquiry data fails comparison at DV%d step\n",
6338                             softc->action == PROBE_INQUIRY_BASIC_DV1 ? 1 : 2);
6339                         if (proberequestbackoff(periph, path->device)) {
6340                                 path->device->flags &= ~CAM_DEV_IN_DV;
6341                                 softc->action = PROBE_TUR_FOR_NEGOTIATION;
6342                         } else {
6343                                 /* give up */
6344                                 softc->action = PROBE_DV_EXIT;
6345                         }
6346                         kfree(nbuf, M_CAMXPT);
6347                         xpt_release_ccb(done_ccb);
6348                         xpt_schedule(periph, priority);
6349                         return;
6350                 }
6351                 kfree(nbuf, M_CAMXPT);
6352                 if (softc->action == PROBE_INQUIRY_BASIC_DV1) {
6353                         softc->action = PROBE_INQUIRY_BASIC_DV2;
6354                         xpt_release_ccb(done_ccb);
6355                         xpt_schedule(periph, priority);
6356                         return;
6357                 }
6358                 if (softc->action == PROBE_DV_EXIT) {
6359                         CAM_DEBUG(periph->path, CAM_DEBUG_INFO,
6360                             ("Leave Domain Validation Successfully\n"));
6361                 }
6362                 path->device->flags &=
6363                     ~(CAM_DEV_UNCONFIGURED|CAM_DEV_IN_DV|CAM_DEV_DV_HIT_BOTTOM);
6364                 if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
6365                         /* Inform the XPT that a new device has been found */
6366                         done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
6367                         xpt_action(done_ccb);
6368                         xpt_async(AC_FOUND_DEVICE, done_ccb->ccb_h.path,
6369                                   done_ccb);
6370                 }
6371                 xpt_release_ccb(done_ccb);
6372                 break;
6373         }
6374         }
6375         done_ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
6376         TAILQ_REMOVE(&softc->request_ccbs, &done_ccb->ccb_h, periph_links.tqe);
6377         done_ccb->ccb_h.status = CAM_REQ_CMP;
6378         xpt_done(done_ccb);
6379         if (TAILQ_FIRST(&softc->request_ccbs) == NULL) {
6380                 cam_periph_invalidate(periph);
6381                 cam_periph_release(periph);
6382         } else {
6383                 probeschedule(periph);
6384         }
6385 }
6386
6387 static void
6388 probecleanup(struct cam_periph *periph)
6389 {
6390         kfree(periph->softc, M_CAMXPT);
6391 }
6392
6393 static void
6394 xpt_find_quirk(struct cam_ed *device)
6395 {
6396         caddr_t match;
6397
6398         match = cam_quirkmatch((caddr_t)&device->inq_data,
6399                                (caddr_t)xpt_quirk_table,
6400                                sizeof(xpt_quirk_table)/sizeof(*xpt_quirk_table),
6401                                sizeof(*xpt_quirk_table), scsi_inquiry_match);
6402
6403         if (match == NULL)
6404                 panic("xpt_find_quirk: device didn't match wildcard entry!!");
6405
6406         device->quirk = (struct xpt_quirk_entry *)match;
6407 }
6408
6409 static int
6410 sysctl_cam_search_luns(SYSCTL_HANDLER_ARGS)
6411 {
6412         int error, bool;
6413
6414         bool = cam_srch_hi;
6415         error = sysctl_handle_int(oidp, &bool, 0, req);
6416         if (error != 0 || req->newptr == NULL)
6417                 return (error);
6418         if (bool == 0 || bool == 1) {
6419                 cam_srch_hi = bool;
6420                 return (0);
6421         } else {
6422                 return (EINVAL);
6423         }
6424 }
6425
6426 static void
6427 xpt_devise_transport(struct cam_path *path)
6428 {
6429         struct ccb_pathinq cpi;
6430         struct ccb_trans_settings cts;
6431         struct scsi_inquiry_data *inq_buf;
6432
6433         /* Get transport information from the SIM */
6434         xpt_setup_ccb(&cpi.ccb_h, path, /*priority*/1);
6435         cpi.ccb_h.func_code = XPT_PATH_INQ;
6436         xpt_action((union ccb *)&cpi);
6437
6438         inq_buf = NULL;
6439         if ((path->device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0)
6440                 inq_buf = &path->device->inq_data;
6441         path->device->protocol = PROTO_SCSI;
6442         path->device->protocol_version =
6443             inq_buf != NULL ? SID_ANSI_REV(inq_buf) : cpi.protocol_version;
6444         path->device->transport = cpi.transport;
6445         path->device->transport_version = cpi.transport_version;
6446
6447         /*
6448          * Any device not using SPI3 features should
6449          * be considered SPI2 or lower.
6450          */
6451         if (inq_buf != NULL) {
6452                 if (path->device->transport == XPORT_SPI
6453                  && (inq_buf->spi3data & SID_SPI_MASK) == 0
6454                  && path->device->transport_version > 2)
6455                         path->device->transport_version = 2;
6456         } else {
6457                 struct cam_ed* otherdev;
6458
6459                 for (otherdev = TAILQ_FIRST(&path->target->ed_entries);
6460                      otherdev != NULL;
6461                      otherdev = TAILQ_NEXT(otherdev, links)) {
6462                         if (otherdev != path->device)
6463                                 break;
6464                 }
6465
6466                 if (otherdev != NULL) {
6467                         /*
6468                          * Initially assume the same versioning as
6469                          * prior luns for this target.
6470                          */
6471                         path->device->protocol_version =
6472                             otherdev->protocol_version;
6473                         path->device->transport_version =
6474                             otherdev->transport_version;
6475                 } else {
6476                         /* Until we know better, opt for safty */
6477                         path->device->protocol_version = 2;
6478                         if (path->device->transport == XPORT_SPI)
6479                                 path->device->transport_version = 2;
6480                         else
6481                                 path->device->transport_version = 0;
6482                 }
6483         }
6484
6485         /*
6486          * XXX
6487          * For a device compliant with SPC-2 we should be able
6488          * to determine the transport version supported by
6489          * scrutinizing the version descriptors in the
6490          * inquiry buffer.
6491          */
6492
6493         /* Tell the controller what we think */
6494         xpt_setup_ccb(&cts.ccb_h, path, /*priority*/1);
6495         cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
6496         cts.type = CTS_TYPE_CURRENT_SETTINGS;
6497         cts.transport = path->device->transport;
6498         cts.transport_version = path->device->transport_version;
6499         cts.protocol = path->device->protocol;
6500         cts.protocol_version = path->device->protocol_version;
6501         cts.proto_specific.valid = 0;
6502         cts.xport_specific.valid = 0;
6503         xpt_action((union ccb *)&cts);
6504 }
6505
6506 static void
6507 xpt_set_transfer_settings(struct ccb_trans_settings *cts, struct cam_ed *device,
6508                           int async_update)
6509 {
6510         struct  ccb_pathinq cpi;
6511         struct  ccb_trans_settings cur_cts;
6512         struct  ccb_trans_settings_scsi *scsi;
6513         struct  ccb_trans_settings_scsi *cur_scsi;
6514         struct  cam_sim *sim;
6515         struct  scsi_inquiry_data *inq_data;
6516
6517         if (device == NULL) {
6518                 cts->ccb_h.status = CAM_PATH_INVALID;
6519                 xpt_done((union ccb *)cts);
6520                 return;
6521         }
6522
6523         if (cts->protocol == PROTO_UNKNOWN
6524          || cts->protocol == PROTO_UNSPECIFIED) {
6525                 cts->protocol = device->protocol;
6526                 cts->protocol_version = device->protocol_version;
6527         }
6528
6529         if (cts->protocol_version == PROTO_VERSION_UNKNOWN
6530          || cts->protocol_version == PROTO_VERSION_UNSPECIFIED)
6531                 cts->protocol_version = device->protocol_version;
6532
6533         if (cts->protocol != device->protocol) {
6534                 xpt_print(cts->ccb_h.path, "Uninitialized Protocol %x:%x?\n",
6535                        cts->protocol, device->protocol);
6536                 cts->protocol = device->protocol;
6537         }
6538
6539         if (cts->protocol_version > device->protocol_version) {
6540                 if (bootverbose) {
6541                         xpt_print(cts->ccb_h.path, "Down reving Protocol "
6542                             "Version from %d to %d?\n", cts->protocol_version,
6543                             device->protocol_version);
6544                 }
6545                 cts->protocol_version = device->protocol_version;
6546         }
6547
6548         if (cts->transport == XPORT_UNKNOWN
6549          || cts->transport == XPORT_UNSPECIFIED) {
6550                 cts->transport = device->transport;
6551                 cts->transport_version = device->transport_version;
6552         }
6553
6554         if (cts->transport_version == XPORT_VERSION_UNKNOWN
6555          || cts->transport_version == XPORT_VERSION_UNSPECIFIED)
6556                 cts->transport_version = device->transport_version;
6557
6558         if (cts->transport != device->transport) {
6559                 xpt_print(cts->ccb_h.path, "Uninitialized Transport %x:%x?\n",
6560                     cts->transport, device->transport);
6561                 cts->transport = device->transport;
6562         }
6563
6564         if (cts->transport_version > device->transport_version) {
6565                 if (bootverbose) {
6566                         xpt_print(cts->ccb_h.path, "Down reving Transport "
6567                             "Version from %d to %d?\n", cts->transport_version,
6568                             device->transport_version);
6569                 }
6570                 cts->transport_version = device->transport_version;
6571         }
6572
6573         sim = cts->ccb_h.path->bus->sim;
6574
6575         /*
6576          * Nothing more of interest to do unless
6577          * this is a device connected via the
6578          * SCSI protocol.
6579          */
6580         if (cts->protocol != PROTO_SCSI) {
6581                 if (async_update == FALSE)
6582                         (*(sim->sim_action))(sim, (union ccb *)cts);
6583                 return;
6584         }
6585
6586         inq_data = &device->inq_data;
6587         scsi = &cts->proto_specific.scsi;
6588         xpt_setup_ccb(&cpi.ccb_h, cts->ccb_h.path, /*priority*/1);
6589         cpi.ccb_h.func_code = XPT_PATH_INQ;
6590         xpt_action((union ccb *)&cpi);
6591
6592         /* SCSI specific sanity checking */
6593         if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0
6594          || (INQ_DATA_TQ_ENABLED(inq_data)) == 0
6595          || (device->queue_flags & SCP_QUEUE_DQUE) != 0
6596          || (device->quirk->mintags == 0)) {
6597                 /*
6598                  * Can't tag on hardware that doesn't support tags,
6599                  * doesn't have it enabled, or has broken tag support.
6600                  */
6601                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6602         }
6603
6604         if (async_update == FALSE) {
6605                 /*
6606                  * Perform sanity checking against what the
6607                  * controller and device can do.
6608                  */
6609                 xpt_setup_ccb(&cur_cts.ccb_h, cts->ccb_h.path, /*priority*/1);
6610                 cur_cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
6611                 cur_cts.type = cts->type;
6612                 xpt_action((union ccb *)&cur_cts);
6613                 if ((cur_cts.ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
6614                         return;
6615                 }
6616                 cur_scsi = &cur_cts.proto_specific.scsi;
6617                 if ((scsi->valid & CTS_SCSI_VALID_TQ) == 0) {
6618                         scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6619                         scsi->flags |= cur_scsi->flags & CTS_SCSI_FLAGS_TAG_ENB;
6620                 }
6621                 if ((cur_scsi->valid & CTS_SCSI_VALID_TQ) == 0)
6622                         scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6623         }
6624
6625         /* SPI specific sanity checking */
6626         if (cts->transport == XPORT_SPI && async_update == FALSE) {
6627                 u_int spi3caps;
6628                 struct ccb_trans_settings_spi *spi;
6629                 struct ccb_trans_settings_spi *cur_spi;
6630
6631                 spi = &cts->xport_specific.spi;
6632
6633                 cur_spi = &cur_cts.xport_specific.spi;
6634
6635                 /* Fill in any gaps in what the user gave us */
6636                 if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
6637                         spi->sync_period = cur_spi->sync_period;
6638                 if ((cur_spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
6639                         spi->sync_period = 0;
6640                 if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
6641                         spi->sync_offset = cur_spi->sync_offset;
6642                 if ((cur_spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
6643                         spi->sync_offset = 0;
6644                 if ((spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
6645                         spi->ppr_options = cur_spi->ppr_options;
6646                 if ((cur_spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
6647                         spi->ppr_options = 0;
6648                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
6649                         spi->bus_width = cur_spi->bus_width;
6650                 if ((cur_spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
6651                         spi->bus_width = 0;
6652                 if ((spi->valid & CTS_SPI_VALID_DISC) == 0) {
6653                         spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
6654                         spi->flags |= cur_spi->flags & CTS_SPI_FLAGS_DISC_ENB;
6655                 }
6656                 if ((cur_spi->valid & CTS_SPI_VALID_DISC) == 0)
6657                         spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
6658                 if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
6659                   && (inq_data->flags & SID_Sync) == 0
6660                   && cts->type == CTS_TYPE_CURRENT_SETTINGS)
6661                  || ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0)
6662                  || (spi->sync_offset == 0)
6663                  || (spi->sync_period == 0)) {
6664                         /* Force async */
6665                         spi->sync_period = 0;
6666                         spi->sync_offset = 0;
6667                 }
6668
6669                 switch (spi->bus_width) {
6670                 case MSG_EXT_WDTR_BUS_32_BIT:
6671                         if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6672                           || (inq_data->flags & SID_WBus32) != 0
6673                           || cts->type == CTS_TYPE_USER_SETTINGS)
6674                          && (cpi.hba_inquiry & PI_WIDE_32) != 0)
6675                                 break;
6676                         /* Fall Through to 16-bit */
6677                 case MSG_EXT_WDTR_BUS_16_BIT:
6678                         if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
6679                           || (inq_data->flags & SID_WBus16) != 0
6680                           || cts->type == CTS_TYPE_USER_SETTINGS)
6681                          && (cpi.hba_inquiry & PI_WIDE_16) != 0) {
6682                                 spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
6683                                 break;
6684                         }
6685                         /* Fall Through to 8-bit */
6686                 default: /* New bus width?? */
6687                 case MSG_EXT_WDTR_BUS_8_BIT:
6688                         /* All targets can do this */
6689                         spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
6690                         break;
6691                 }
6692
6693                 spi3caps = cpi.xport_specific.spi.ppr_options;
6694                 if ((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
6695                  && cts->type == CTS_TYPE_CURRENT_SETTINGS)
6696                         spi3caps &= inq_data->spi3data;
6697
6698                 if ((spi3caps & SID_SPI_CLOCK_DT) == 0)
6699                         spi->ppr_options &= ~MSG_EXT_PPR_DT_REQ;
6700
6701                 if ((spi3caps & SID_SPI_IUS) == 0)
6702                         spi->ppr_options &= ~MSG_EXT_PPR_IU_REQ;
6703
6704                 if ((spi3caps & SID_SPI_QAS) == 0)
6705                         spi->ppr_options &= ~MSG_EXT_PPR_QAS_REQ;
6706
6707                 /* No SPI Transfer settings are allowed unless we are wide */
6708                 if (spi->bus_width == 0)
6709                         spi->ppr_options = 0;
6710
6711                 if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) == 0) {
6712                         /*
6713                          * Can't tag queue without disconnection.
6714                          */
6715                         scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
6716                         scsi->valid |= CTS_SCSI_VALID_TQ;
6717                 }
6718
6719                 /*
6720                  * If we are currently performing tagged transactions to
6721                  * this device and want to change its negotiation parameters,
6722                  * go non-tagged for a bit to give the controller a chance to
6723                  * negotiate unhampered by tag messages.
6724                  */
6725                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS
6726                  && (device->inq_flags & SID_CmdQue) != 0
6727                  && (scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
6728                  && (spi->flags & (CTS_SPI_VALID_SYNC_RATE|
6729                                    CTS_SPI_VALID_SYNC_OFFSET|
6730                                    CTS_SPI_VALID_BUS_WIDTH)) != 0)
6731                         xpt_toggle_tags(cts->ccb_h.path);
6732         }
6733
6734         if (cts->type == CTS_TYPE_CURRENT_SETTINGS
6735          && (scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
6736                 int device_tagenb;
6737
6738                 /*
6739                  * If we are transitioning from tags to no-tags or
6740                  * vice-versa, we need to carefully freeze and restart
6741                  * the queue so that we don't overlap tagged and non-tagged
6742                  * commands.  We also temporarily stop tags if there is
6743                  * a change in transfer negotiation settings to allow
6744                  * "tag-less" negotiation.
6745                  */
6746                 if ((device->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6747                  || (device->inq_flags & SID_CmdQue) != 0)
6748                         device_tagenb = TRUE;
6749                 else
6750                         device_tagenb = FALSE;
6751
6752                 if (((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
6753                   && device_tagenb == FALSE)
6754                  || ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) == 0
6755                   && device_tagenb == TRUE)) {
6756
6757                         if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0) {
6758                                 /*
6759                                  * Delay change to use tags until after a
6760                                  * few commands have gone to this device so
6761                                  * the controller has time to perform transfer
6762                                  * negotiations without tagged messages getting
6763                                  * in the way.
6764                                  */
6765                                 device->tag_delay_count = CAM_TAG_DELAY_COUNT;
6766                                 device->flags |= CAM_DEV_TAG_AFTER_COUNT;
6767                         } else {
6768                                 struct ccb_relsim crs;
6769
6770                                 xpt_freeze_devq(cts->ccb_h.path, /*count*/1);
6771                                 device->inq_flags &= ~SID_CmdQue;
6772                                 xpt_dev_ccbq_resize(cts->ccb_h.path,
6773                                                     sim->max_dev_openings);
6774                                 device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
6775                                 device->tag_delay_count = 0;
6776
6777                                 xpt_setup_ccb(&crs.ccb_h, cts->ccb_h.path,
6778                                               /*priority*/1);
6779                                 crs.ccb_h.func_code = XPT_REL_SIMQ;
6780                                 crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
6781                                 crs.openings
6782                                     = crs.release_timeout
6783                                     = crs.qfrozen_cnt
6784                                     = 0;
6785                                 xpt_action((union ccb *)&crs);
6786                         }
6787                 }
6788         }
6789         if (async_update == FALSE)
6790                 (*(sim->sim_action))(sim, (union ccb *)cts);
6791 }
6792
6793 static void
6794 xpt_toggle_tags(struct cam_path *path)
6795 {
6796         struct cam_ed *dev;
6797
6798         /*
6799          * Give controllers a chance to renegotiate
6800          * before starting tag operations.  We
6801          * "toggle" tagged queuing off then on
6802          * which causes the tag enable command delay
6803          * counter to come into effect.
6804          */
6805         dev = path->device;
6806         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
6807          || ((dev->inq_flags & SID_CmdQue) != 0
6808           && (dev->inq_flags & (SID_Sync|SID_WBus16|SID_WBus32)) != 0)) {
6809                 struct ccb_trans_settings cts;
6810
6811                 xpt_setup_ccb(&cts.ccb_h, path, 1);
6812                 cts.protocol = PROTO_SCSI;
6813                 cts.protocol_version = PROTO_VERSION_UNSPECIFIED;
6814                 cts.transport = XPORT_UNSPECIFIED;
6815                 cts.transport_version = XPORT_VERSION_UNSPECIFIED;
6816                 cts.proto_specific.scsi.flags = 0;
6817                 cts.proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
6818                 xpt_set_transfer_settings(&cts, path->device,
6819                                           /*async_update*/TRUE);
6820                 cts.proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
6821                 xpt_set_transfer_settings(&cts, path->device,
6822                                           /*async_update*/TRUE);
6823         }
6824 }
6825
6826 static void
6827 xpt_start_tags(struct cam_path *path)
6828 {
6829         struct ccb_relsim crs;
6830         struct cam_ed *device;
6831         struct cam_sim *sim;
6832         int    newopenings;
6833
6834         device = path->device;
6835         sim = path->bus->sim;
6836         device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
6837         xpt_freeze_devq(path, /*count*/1);
6838         device->inq_flags |= SID_CmdQue;
6839         if (device->tag_saved_openings != 0)
6840                 newopenings = device->tag_saved_openings;
6841         else
6842                 newopenings = min(device->quirk->maxtags,
6843                                   sim->max_tagged_dev_openings);
6844         xpt_dev_ccbq_resize(path, newopenings);
6845         xpt_setup_ccb(&crs.ccb_h, path, /*priority*/1);
6846         crs.ccb_h.func_code = XPT_REL_SIMQ;
6847         crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
6848         crs.openings
6849             = crs.release_timeout
6850             = crs.qfrozen_cnt
6851             = 0;
6852         xpt_action((union ccb *)&crs);
6853 }
6854
6855 static int busses_to_config;
6856 static int busses_to_reset;
6857
6858 static int
6859 xptconfigbuscountfunc(struct cam_eb *bus, void *arg)
6860 {
6861
6862         sim_lock_assert_owned(bus->sim->lock);
6863
6864         if (bus->path_id != CAM_XPT_PATH_ID) {
6865                 struct cam_path path;
6866                 struct ccb_pathinq cpi;
6867                 int can_negotiate;
6868
6869                 busses_to_config++;
6870                 xpt_compile_path(&path, NULL, bus->path_id,
6871                                  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
6872                 xpt_setup_ccb(&cpi.ccb_h, &path, /*priority*/1);
6873                 cpi.ccb_h.func_code = XPT_PATH_INQ;
6874                 xpt_action((union ccb *)&cpi);
6875                 can_negotiate = cpi.hba_inquiry;
6876                 can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
6877                 if ((cpi.hba_misc & PIM_NOBUSRESET) == 0
6878                  && can_negotiate)
6879                         busses_to_reset++;
6880                 xpt_release_path(&path);
6881         }
6882
6883         return(1);
6884 }
6885
6886 static int
6887 xptconfigfunc(struct cam_eb *bus, void *arg)
6888 {
6889         struct  cam_path *path;
6890         union   ccb *work_ccb;
6891
6892         sim_lock_assert_owned(bus->sim->lock);
6893
6894         if (bus->path_id != CAM_XPT_PATH_ID) {
6895                 cam_status status;
6896                 int can_negotiate;
6897
6898                 work_ccb = xpt_alloc_ccb();
6899                 if ((status = xpt_create_path(&path, xpt_periph, bus->path_id,
6900                                               CAM_TARGET_WILDCARD,
6901                                               CAM_LUN_WILDCARD)) !=CAM_REQ_CMP){
6902                         kprintf("xptconfigfunc: xpt_create_path failed with "
6903                                "status %#x for bus %d\n", status, bus->path_id);
6904                         kprintf("xptconfigfunc: halting bus configuration\n");
6905                         xpt_free_ccb(work_ccb);
6906                         busses_to_config--;
6907                         xpt_finishconfig(xpt_periph, NULL);
6908                         return(0);
6909                 }
6910                 xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
6911                 work_ccb->ccb_h.func_code = XPT_PATH_INQ;
6912                 xpt_action(work_ccb);
6913                 if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
6914                         kprintf("xptconfigfunc: CPI failed on bus %d "
6915                                "with status %d\n", bus->path_id,
6916                                work_ccb->ccb_h.status);
6917                         xpt_finishconfig(xpt_periph, work_ccb);
6918                         return(1);
6919                 }
6920
6921                 can_negotiate = work_ccb->cpi.hba_inquiry;
6922                 can_negotiate &= (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE);
6923                 if ((work_ccb->cpi.hba_misc & PIM_NOBUSRESET) == 0
6924                  && (can_negotiate != 0)) {
6925                         xpt_setup_ccb(&work_ccb->ccb_h, path, /*priority*/1);
6926                         work_ccb->ccb_h.func_code = XPT_RESET_BUS;
6927                         work_ccb->ccb_h.cbfcnp = NULL;
6928                         CAM_DEBUG(path, CAM_DEBUG_SUBTRACE,
6929                                   ("Resetting Bus\n"));
6930                         xpt_action(work_ccb);
6931                         xpt_finishconfig(xpt_periph, work_ccb);
6932                 } else {
6933                         /* Act as though we performed a successful BUS RESET */
6934                         work_ccb->ccb_h.func_code = XPT_RESET_BUS;
6935                         xpt_finishconfig(xpt_periph, work_ccb);
6936                 }
6937         }
6938
6939         return(1);
6940 }
6941
6942 static void
6943 xpt_config(void *arg)
6944 {
6945         /*
6946          * Now that interrupts are enabled, go find our devices
6947          */
6948
6949 #ifdef CAMDEBUG
6950         /* Setup debugging flags and path */
6951 #ifdef CAM_DEBUG_FLAGS
6952         cam_dflags = CAM_DEBUG_FLAGS;
6953 #else /* !CAM_DEBUG_FLAGS */
6954         cam_dflags = CAM_DEBUG_NONE;
6955 #endif /* CAM_DEBUG_FLAGS */
6956 #ifdef CAM_DEBUG_BUS
6957         if (cam_dflags != CAM_DEBUG_NONE) {
6958                 /*
6959                  * Locking is specifically omitted here.  No SIMs have
6960                  * registered yet, so xpt_create_path will only be searching
6961                  * empty lists of targets and devices.
6962                  */
6963                 if (xpt_create_path(&cam_dpath, xpt_periph,
6964                                     CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
6965                                     CAM_DEBUG_LUN) != CAM_REQ_CMP) {
6966                         kprintf("xpt_config: xpt_create_path() failed for debug"
6967                                " target %d:%d:%d, debugging disabled\n",
6968                                CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
6969                         cam_dflags = CAM_DEBUG_NONE;
6970                 }
6971         } else
6972                 cam_dpath = NULL;
6973 #else /* !CAM_DEBUG_BUS */
6974         cam_dpath = NULL;
6975 #endif /* CAM_DEBUG_BUS */
6976 #endif /* CAMDEBUG */
6977
6978         /*
6979          * Scan all installed busses.
6980          */
6981         xpt_for_all_busses(xptconfigbuscountfunc, NULL);
6982
6983         if (busses_to_config == 0) {
6984                 /* Call manually because we don't have any busses */
6985                 xpt_finishconfig(xpt_periph, NULL);
6986         } else  {
6987                 if (busses_to_reset > 0 && scsi_delay >= 2000) {
6988                         kprintf("Waiting %d seconds for SCSI "
6989                                "devices to settle\n", scsi_delay/1000);
6990                 }
6991                 xpt_for_all_busses(xptconfigfunc, NULL);
6992         }
6993 }
6994
6995 /*
6996  * If the given device only has one peripheral attached to it, and if that
6997  * peripheral is the passthrough driver, announce it.  This insures that the
6998  * user sees some sort of announcement for every peripheral in their system.
6999  */
7000 static int
7001 xptpassannouncefunc(struct cam_ed *device, void *arg)
7002 {
7003         struct cam_periph *periph;
7004         int i;
7005
7006         for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
7007              periph = SLIST_NEXT(periph, periph_links), i++);
7008
7009         periph = SLIST_FIRST(&device->periphs);
7010         if ((i == 1)
7011          && (strncmp(periph->periph_name, "pass", 4) == 0))
7012                 xpt_announce_periph(periph, NULL);
7013
7014         return(1);
7015 }
7016
7017 static void
7018 xpt_finishconfig_task(void *context, int pending)
7019 {
7020         struct  periph_driver **p_drv;
7021         int     i;
7022
7023         if (busses_to_config == 0) {
7024                 /* Register all the peripheral drivers */
7025                 /* XXX This will have to change when we have loadable modules */
7026                 p_drv = periph_drivers;
7027                 for (i = 0; p_drv[i] != NULL; i++) {
7028                         (*p_drv[i]->init)();
7029                 }
7030
7031                 /*
7032                  * Check for devices with no "standard" peripheral driver
7033                  * attached.  For any devices like that, announce the
7034                  * passthrough driver so the user will see something.
7035                  */
7036                 xpt_for_all_devices(xptpassannouncefunc, NULL);
7037
7038                 /* Release our hook so that the boot can continue. */
7039                 config_intrhook_disestablish(xsoftc.xpt_config_hook);
7040                 kfree(xsoftc.xpt_config_hook, M_CAMXPT);
7041                 xsoftc.xpt_config_hook = NULL;
7042         }
7043
7044         kfree(context, M_CAMXPT);
7045 }
7046
7047 static void
7048 xpt_finishconfig(struct cam_periph *periph, union ccb *done_ccb)
7049 {
7050         struct  xpt_task *task;
7051
7052         if (done_ccb != NULL) {
7053                 CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
7054                           ("xpt_finishconfig\n"));
7055                 switch(done_ccb->ccb_h.func_code) {
7056                 case XPT_RESET_BUS:
7057                         if (done_ccb->ccb_h.status == CAM_REQ_CMP) {
7058                                 done_ccb->ccb_h.func_code = XPT_SCAN_BUS;
7059                                 done_ccb->ccb_h.cbfcnp = xpt_finishconfig;
7060                                 done_ccb->crcn.flags = 0;
7061                                 xpt_action(done_ccb);
7062                                 return;
7063                         }
7064                         /* FALLTHROUGH */
7065                 case XPT_SCAN_BUS:
7066                 default:
7067                         xpt_free_path(done_ccb->ccb_h.path);
7068                         busses_to_config--;
7069                         break;
7070                 }
7071         }
7072
7073         if (busses_to_config == 0) {
7074                 task = kmalloc(sizeof(struct xpt_task), M_CAMXPT, M_INTWAIT);
7075                 TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
7076                 taskqueue_enqueue(taskqueue_thread[mycpuid], &task->task);
7077         }
7078
7079         if (done_ccb != NULL)
7080                 xpt_free_ccb(done_ccb);
7081 }
7082
7083 cam_status
7084 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
7085                    struct cam_path *path)
7086 {
7087         struct ccb_setasync csa;
7088         cam_status status;
7089         int xptpath = 0;
7090
7091         if (path == NULL) {
7092                 lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
7093                 status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
7094                                          CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
7095                 if (status != CAM_REQ_CMP) {
7096                         lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
7097                         return (status);
7098                 }
7099                 xptpath = 1;
7100         }
7101
7102         xpt_setup_ccb(&csa.ccb_h, path, /*priority*/5);
7103         csa.ccb_h.func_code = XPT_SASYNC_CB;
7104         csa.event_enable = event;
7105         csa.callback = cbfunc;
7106         csa.callback_arg = cbarg;
7107         xpt_action((union ccb *)&csa);
7108         status = csa.ccb_h.status;
7109         if (xptpath) {
7110                 xpt_free_path(path);
7111                 lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
7112         }
7113         return (status);
7114 }
7115
7116 static void
7117 xptaction(struct cam_sim *sim, union ccb *work_ccb)
7118 {
7119         CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
7120
7121         switch (work_ccb->ccb_h.func_code) {
7122         /* Common cases first */
7123         case XPT_PATH_INQ:              /* Path routing inquiry */
7124         {
7125                 struct ccb_pathinq *cpi;
7126
7127                 cpi = &work_ccb->cpi;
7128                 cpi->version_num = 1; /* XXX??? */
7129                 cpi->hba_inquiry = 0;
7130                 cpi->target_sprt = 0;
7131                 cpi->hba_misc = 0;
7132                 cpi->hba_eng_cnt = 0;
7133                 cpi->max_target = 0;
7134                 cpi->max_lun = 0;
7135                 cpi->initiator_id = 0;
7136                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
7137                 strncpy(cpi->hba_vid, "", HBA_IDLEN);
7138                 strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
7139                 cpi->unit_number = sim->unit_number;
7140                 cpi->bus_id = sim->bus_id;
7141                 cpi->base_transfer_speed = 0;
7142                 cpi->protocol = PROTO_UNSPECIFIED;
7143                 cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
7144                 cpi->transport = XPORT_UNSPECIFIED;
7145                 cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
7146                 cpi->ccb_h.status = CAM_REQ_CMP;
7147                 xpt_done(work_ccb);
7148                 break;
7149         }
7150         default:
7151                 work_ccb->ccb_h.status = CAM_REQ_INVALID;
7152                 xpt_done(work_ccb);
7153                 break;
7154         }
7155 }
7156
7157 /*
7158  * The xpt as a "controller" has no interrupt sources, so polling
7159  * is a no-op.
7160  */
7161 static void
7162 xptpoll(struct cam_sim *sim)
7163 {
7164 }
7165
7166 void
7167 xpt_lock_buses(void)
7168 {
7169         lockmgr(&xsoftc.xpt_topo_lock, LK_EXCLUSIVE);
7170 }
7171
7172 void
7173 xpt_unlock_buses(void)
7174 {
7175         lockmgr(&xsoftc.xpt_topo_lock, LK_RELEASE);
7176 }
7177
7178
7179 /*
7180  * Should only be called by the machine interrupt dispatch routines,
7181  * so put these prototypes here instead of in the header.
7182  */
7183
7184 static void
7185 swi_cambio(void *arg, void *frame)
7186 {
7187         camisr(NULL);
7188 }
7189
7190 static void
7191 camisr(void *dummy)
7192 {
7193         cam_simq_t queue;
7194         struct cam_sim *sim;
7195
7196         spin_lock_wr(&cam_simq_spin);
7197         TAILQ_INIT(&queue);
7198         TAILQ_CONCAT(&queue, &cam_simq, links);
7199         spin_unlock_wr(&cam_simq_spin);
7200
7201         while ((sim = TAILQ_FIRST(&queue)) != NULL) {
7202                 TAILQ_REMOVE(&queue, sim, links);
7203                 CAM_SIM_LOCK(sim);
7204                 sim->flags &= ~CAM_SIM_ON_DONEQ;
7205                 camisr_runqueue(sim);
7206                 CAM_SIM_UNLOCK(sim);
7207         }
7208 }
7209
7210 static void
7211 camisr_runqueue(struct cam_sim *sim)
7212 {
7213         struct  ccb_hdr *ccb_h;
7214         int     runq;
7215
7216         spin_lock_wr(&sim->sim_spin);
7217         while ((ccb_h = TAILQ_FIRST(&sim->sim_doneq)) != NULL) {
7218                 TAILQ_REMOVE(&sim->sim_doneq, ccb_h, sim_links.tqe);
7219                 spin_unlock_wr(&sim->sim_spin);
7220                 ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
7221
7222                 CAM_DEBUG(ccb_h->path, CAM_DEBUG_TRACE,
7223                           ("camisr\n"));
7224
7225                 runq = FALSE;
7226
7227                 if (ccb_h->flags & CAM_HIGH_POWER) {
7228                         struct highpowerlist    *hphead;
7229                         struct cam_ed           *device;
7230                         union ccb               *send_ccb;
7231
7232                         lockmgr(&xsoftc.xpt_lock, LK_EXCLUSIVE);
7233                         hphead = &xsoftc.highpowerq;
7234
7235                         send_ccb = (union ccb *)STAILQ_FIRST(hphead);
7236
7237                         /*
7238                          * Increment the count since this command is done.
7239                          */
7240                         xsoftc.num_highpower++;
7241
7242                         /*
7243                          * Any high powered commands queued up?
7244                          */
7245                         if (send_ccb != NULL) {
7246                                 device = send_ccb->ccb_h.path->device;
7247
7248                                 STAILQ_REMOVE_HEAD(hphead, xpt_links.stqe);
7249                                 lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
7250
7251                                 xpt_release_devq(send_ccb->ccb_h.path,
7252                                                  /*count*/1, /*runqueue*/TRUE);
7253                         } else
7254                                 lockmgr(&xsoftc.xpt_lock, LK_RELEASE);
7255                 }
7256
7257                 if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
7258                         struct cam_ed *dev;
7259
7260                         dev = ccb_h->path->device;
7261
7262                         cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
7263
7264                         /*
7265                          * devq may be NULL if this is cam_dead_sim
7266                          */
7267                         if (ccb_h->path->bus->sim->devq) {
7268                                 ccb_h->path->bus->sim->devq->send_active--;
7269                                 ccb_h->path->bus->sim->devq->send_openings++;
7270                         }
7271
7272                         if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
7273                           && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)
7274                          || ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
7275                           && (dev->ccbq.dev_active == 0))) {
7276
7277                                 xpt_release_devq(ccb_h->path, /*count*/1,
7278                                                  /*run_queue*/TRUE);
7279                         }
7280
7281                         if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
7282                          && (--dev->tag_delay_count == 0))
7283                                 xpt_start_tags(ccb_h->path);
7284
7285                         if ((dev->ccbq.queue.entries > 0)
7286                          && (dev->qfrozen_cnt == 0)
7287                          && (device_is_send_queued(dev) == 0)) {
7288                                 runq = xpt_schedule_dev_sendq(ccb_h->path->bus,
7289                                                               dev);
7290                         }
7291                 }
7292
7293                 if (ccb_h->status & CAM_RELEASE_SIMQ) {
7294                         xpt_release_simq(ccb_h->path->bus->sim,
7295                                          /*run_queue*/TRUE);
7296                         ccb_h->status &= ~CAM_RELEASE_SIMQ;
7297                         runq = FALSE;
7298                 }
7299
7300                 if ((ccb_h->flags & CAM_DEV_QFRZDIS)
7301                  && (ccb_h->status & CAM_DEV_QFRZN)) {
7302                         xpt_release_devq(ccb_h->path, /*count*/1,
7303                                          /*run_queue*/TRUE);
7304                         ccb_h->status &= ~CAM_DEV_QFRZN;
7305                 } else if (runq) {
7306                         xpt_run_dev_sendq(ccb_h->path->bus);
7307                 }
7308
7309                 /* Call the peripheral driver's callback */
7310                 (*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
7311                 spin_lock_wr(&sim->sim_spin);
7312         }
7313         spin_unlock_wr(&sim->sim_spin);
7314 }
7315
7316 /*
7317  * The dead_sim isn't completely hooked into CAM, we have to make sure
7318  * the doneq is cleared after calling xpt_done() so cam_periph_ccbwait()
7319  * doesn't block.
7320  */
7321 static void
7322 dead_sim_action(struct cam_sim *sim, union ccb *ccb)
7323 {
7324
7325         ccb->ccb_h.status = CAM_DEV_NOT_THERE;
7326         xpt_done(ccb);
7327         camisr_runqueue(sim);
7328 }
7329
7330 static void
7331 dead_sim_poll(struct cam_sim *sim)
7332 {
7333 }