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