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