1/*-
2 * Implementation of the SCSI Transport
3 *
4 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5 *
6 * Copyright (c) 1997, 1998, 1999 Justin T. Gibbs.
7 * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions, and the following disclaimer,
15 *    without modification, immediately at the beginning of the file.
16 * 2. The name of the author may not be used to endorse or promote products
17 *    derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
23 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD$");
34
35#include <sys/param.h>
36#include <sys/bus.h>
37#include <sys/systm.h>
38#include <sys/types.h>
39#include <sys/malloc.h>
40#include <sys/kernel.h>
41#include <sys/time.h>
42#include <sys/conf.h>
43#include <sys/fcntl.h>
44#include <sys/md5.h>
45#include <sys/sbuf.h>
46
47#include <sys/lock.h>
48#include <sys/mutex.h>
49#include <sys/sysctl.h>
50
51#include <cam/cam.h>
52#include <cam/cam_ccb.h>
53#include <cam/cam_queue.h>
54#include <cam/cam_periph.h>
55#include <cam/cam_sim.h>
56#include <cam/cam_xpt.h>
57#include <cam/cam_xpt_sim.h>
58#include <cam/cam_xpt_periph.h>
59#include <cam/cam_xpt_internal.h>
60#include <cam/cam_debug.h>
61
62#include <cam/scsi/scsi_all.h>
63#include <cam/scsi/scsi_message.h>
64#include <cam/scsi/scsi_pass.h>
65#include <machine/stdarg.h>	/* for xpt_print below */
66#include "opt_cam.h"
67
68struct scsi_quirk_entry {
69	struct scsi_inquiry_pattern inq_pat;
70	u_int8_t quirks;
71#define	CAM_QUIRK_NOLUNS	0x01
72#define	CAM_QUIRK_NOVPDS	0x02
73#define	CAM_QUIRK_HILUNS	0x04
74#define	CAM_QUIRK_NOHILUNS	0x08
75#define	CAM_QUIRK_NORPTLUNS	0x10
76	u_int mintags;
77	u_int maxtags;
78};
79#define SCSI_QUIRK(dev)	((struct scsi_quirk_entry *)((dev)->quirk))
80
81static int cam_srch_hi = 0;
82static int sysctl_cam_search_luns(SYSCTL_HANDLER_ARGS);
83SYSCTL_PROC(_kern_cam, OID_AUTO, cam_srch_hi,
84    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT, 0, 0,
85    sysctl_cam_search_luns, "I",
86    "allow search above LUN 7 for SCSI3 and greater devices");
87
88#define	CAM_SCSI2_MAXLUN	8
89#define	CAM_CAN_GET_SIMPLE_LUN(x, i)				\
90	((((x)->luns[i].lundata[0] & RPL_LUNDATA_ATYP_MASK) ==	\
91	RPL_LUNDATA_ATYP_PERIPH) ||				\
92	(((x)->luns[i].lundata[0] & RPL_LUNDATA_ATYP_MASK) ==	\
93	RPL_LUNDATA_ATYP_FLAT))
94#define	CAM_GET_SIMPLE_LUN(lp, i, lval)					\
95	if (((lp)->luns[(i)].lundata[0] & RPL_LUNDATA_ATYP_MASK) == 	\
96	    RPL_LUNDATA_ATYP_PERIPH) {					\
97		(lval) = (lp)->luns[(i)].lundata[1];			\
98	} else {							\
99		(lval) = (lp)->luns[(i)].lundata[0];			\
100		(lval) &= RPL_LUNDATA_FLAT_LUN_MASK;			\
101		(lval) <<= 8;						\
102		(lval) |=  (lp)->luns[(i)].lundata[1];			\
103	}
104#define	CAM_GET_LUN(lp, i, lval)					\
105	(lval) = scsi_8btou64((lp)->luns[(i)].lundata);			\
106	(lval) = CAM_EXTLUN_BYTE_SWIZZLE(lval);
107
108/*
109 * If we're not quirked to search <= the first 8 luns
110 * and we are either quirked to search above lun 8,
111 * or we're > SCSI-2 and we've enabled hilun searching,
112 * or we're > SCSI-2 and the last lun was a success,
113 * we can look for luns above lun 8.
114 */
115#define	CAN_SRCH_HI_SPARSE(dv)					\
116  (((SCSI_QUIRK(dv)->quirks & CAM_QUIRK_NOHILUNS) == 0) 	\
117  && ((SCSI_QUIRK(dv)->quirks & CAM_QUIRK_HILUNS)		\
118  || (SID_ANSI_REV(&dv->inq_data) > SCSI_REV_2 && cam_srch_hi)))
119
120#define	CAN_SRCH_HI_DENSE(dv)					\
121  (((SCSI_QUIRK(dv)->quirks & CAM_QUIRK_NOHILUNS) == 0) 	\
122  && ((SCSI_QUIRK(dv)->quirks & CAM_QUIRK_HILUNS)		\
123  || (SID_ANSI_REV(&dv->inq_data) > SCSI_REV_2)))
124
125static periph_init_t probe_periph_init;
126
127static struct periph_driver probe_driver =
128{
129	probe_periph_init, "probe",
130	TAILQ_HEAD_INITIALIZER(probe_driver.units), /* generation */ 0,
131	CAM_PERIPH_DRV_EARLY
132};
133
134PERIPHDRIVER_DECLARE(probe, probe_driver);
135
136typedef enum {
137	PROBE_TUR,
138	PROBE_INQUIRY,	/* this counts as DV0 for Basic Domain Validation */
139	PROBE_FULL_INQUIRY,
140	PROBE_REPORT_LUNS,
141	PROBE_MODE_SENSE,
142	PROBE_SUPPORTED_VPD_LIST,
143	PROBE_DEVICE_ID,
144	PROBE_EXTENDED_INQUIRY,
145	PROBE_SERIAL_NUM,
146	PROBE_TUR_FOR_NEGOTIATION,
147	PROBE_INQUIRY_BASIC_DV1,
148	PROBE_INQUIRY_BASIC_DV2,
149	PROBE_DV_EXIT,
150	PROBE_DONE,
151	PROBE_INVALID
152} probe_action;
153
154static char *probe_action_text[] = {
155	"PROBE_TUR",
156	"PROBE_INQUIRY",
157	"PROBE_FULL_INQUIRY",
158	"PROBE_REPORT_LUNS",
159	"PROBE_MODE_SENSE",
160	"PROBE_SUPPORTED_VPD_LIST",
161	"PROBE_DEVICE_ID",
162	"PROBE_EXTENDED_INQUIRY",
163	"PROBE_SERIAL_NUM",
164	"PROBE_TUR_FOR_NEGOTIATION",
165	"PROBE_INQUIRY_BASIC_DV1",
166	"PROBE_INQUIRY_BASIC_DV2",
167	"PROBE_DV_EXIT",
168	"PROBE_DONE",
169	"PROBE_INVALID"
170};
171
172#define PROBE_SET_ACTION(softc, newaction)	\
173do {									\
174	char **text;							\
175	text = probe_action_text;					\
176	CAM_DEBUG((softc)->periph->path, CAM_DEBUG_PROBE,		\
177	    ("Probe %s to %s\n", text[(softc)->action],			\
178	    text[(newaction)]));					\
179	(softc)->action = (newaction);					\
180} while(0)
181
182typedef enum {
183	PROBE_INQUIRY_CKSUM	= 0x01,
184	PROBE_SERIAL_CKSUM	= 0x02,
185	PROBE_NO_ANNOUNCE	= 0x04,
186	PROBE_EXTLUN		= 0x08
187} probe_flags;
188
189typedef struct {
190	TAILQ_HEAD(, ccb_hdr) request_ccbs;
191	probe_action	action;
192	union ccb	saved_ccb;
193	probe_flags	flags;
194	MD5_CTX		context;
195	u_int8_t	digest[16];
196	struct cam_periph *periph;
197} probe_softc;
198
199static const char quantum[] = "QUANTUM";
200static const char sony[] = "SONY";
201static const char west_digital[] = "WDIGTL";
202static const char samsung[] = "SAMSUNG";
203static const char seagate[] = "SEAGATE";
204static const char microp[] = "MICROP";
205
206static struct scsi_quirk_entry scsi_quirk_table[] =
207{
208	{
209		/* Reports QUEUE FULL for temporary resource shortages */
210		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP39100*", "*" },
211		/*quirks*/0, /*mintags*/24, /*maxtags*/32
212	},
213	{
214		/* Reports QUEUE FULL for temporary resource shortages */
215		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP34550*", "*" },
216		/*quirks*/0, /*mintags*/24, /*maxtags*/32
217	},
218	{
219		/* Reports QUEUE FULL for temporary resource shortages */
220		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "XP32275*", "*" },
221		/*quirks*/0, /*mintags*/24, /*maxtags*/32
222	},
223	{
224		/* Broken tagged queuing drive */
225		{ T_DIRECT, SIP_MEDIA_FIXED, microp, "4421-07*", "*" },
226		/*quirks*/0, /*mintags*/0, /*maxtags*/0
227	},
228	{
229		/* Broken tagged queuing drive */
230		{ T_DIRECT, SIP_MEDIA_FIXED, "HP", "C372*", "*" },
231		/*quirks*/0, /*mintags*/0, /*maxtags*/0
232	},
233	{
234		/* Broken tagged queuing drive */
235		{ T_DIRECT, SIP_MEDIA_FIXED, microp, "3391*", "x43h" },
236		/*quirks*/0, /*mintags*/0, /*maxtags*/0
237	},
238	{
239		/*
240		 * Unfortunately, the Quantum Atlas III has the same
241		 * problem as the Atlas II drives above.
242		 * Reported by: "Johan Granlund" <johan@granlund.nu>
243		 *
244		 * For future reference, the drive with the problem was:
245		 * QUANTUM QM39100TD-SW N1B0
246		 *
247		 * It's possible that Quantum will fix the problem in later
248		 * firmware revisions.  If that happens, the quirk entry
249		 * will need to be made specific to the firmware revisions
250		 * with the problem.
251		 *
252		 */
253		/* Reports QUEUE FULL for temporary resource shortages */
254		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM39100*", "*" },
255		/*quirks*/0, /*mintags*/24, /*maxtags*/32
256	},
257	{
258		/*
259		 * 18 Gig Atlas III, same problem as the 9G version.
260		 * Reported by: Andre Albsmeier
261		 *		<andre.albsmeier@mchp.siemens.de>
262		 *
263		 * For future reference, the drive with the problem was:
264		 * QUANTUM QM318000TD-S N491
265		 */
266		/* Reports QUEUE FULL for temporary resource shortages */
267		{ T_DIRECT, SIP_MEDIA_FIXED, quantum, "QM318000*", "*" },
268		/*quirks*/0, /*mintags*/24, /*maxtags*/32
269	},
270	{
271		/*
272		 * Broken tagged queuing drive
273		 * Reported by: Bret Ford <bford@uop.cs.uop.edu>
274		 *         and: Martin Renters <martin@tdc.on.ca>
275		 */
276		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST410800*", "71*" },
277		/*quirks*/0, /*mintags*/0, /*maxtags*/0
278	},
279		/*
280		 * The Seagate Medalist Pro drives have very poor write
281		 * performance with anything more than 2 tags.
282		 *
283		 * Reported by:  Paul van der Zwan <paulz@trantor.xs4all.nl>
284		 * Drive:  <SEAGATE ST36530N 1444>
285		 *
286		 * Reported by:  Jeremy Lea <reg@shale.csir.co.za>
287		 * Drive:  <SEAGATE ST34520W 1281>
288		 *
289		 * No one has actually reported that the 9G version
290		 * (ST39140*) of the Medalist Pro has the same problem, but
291		 * we're assuming that it does because the 4G and 6.5G
292		 * versions of the drive are broken.
293		 */
294	{
295		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST34520*", "*"},
296		/*quirks*/0, /*mintags*/2, /*maxtags*/2
297	},
298	{
299		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST36530*", "*"},
300		/*quirks*/0, /*mintags*/2, /*maxtags*/2
301	},
302	{
303		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST39140*", "*"},
304		/*quirks*/0, /*mintags*/2, /*maxtags*/2
305	},
306	{
307		/*
308		 * Experiences command timeouts under load with a
309		 * tag count higher than 55.
310		 */
311		{ T_DIRECT, SIP_MEDIA_FIXED, seagate, "ST3146855LW", "*"},
312		/*quirks*/0, /*mintags*/2, /*maxtags*/55
313	},
314	{
315		/*
316		 * Slow when tagged queueing is enabled.  Write performance
317		 * steadily drops off with more and more concurrent
318		 * transactions.  Best sequential write performance with
319		 * tagged queueing turned off and write caching turned on.
320		 *
321		 * PR:  kern/10398
322		 * Submitted by:  Hideaki Okada <hokada@isl.melco.co.jp>
323		 * Drive:  DCAS-34330 w/ "S65A" firmware.
324		 *
325		 * The drive with the problem had the "S65A" firmware
326		 * revision, and has also been reported (by Stephen J.
327		 * Roznowski <sjr@home.net>) for a drive with the "S61A"
328		 * firmware revision.
329		 *
330		 * Although no one has reported problems with the 2 gig
331		 * version of the DCAS drive, the assumption is that it
332		 * has the same problems as the 4 gig version.  Therefore
333		 * this quirk entries disables tagged queueing for all
334		 * DCAS drives.
335		 */
336		{ T_DIRECT, SIP_MEDIA_FIXED, "IBM", "DCAS*", "*" },
337		/*quirks*/0, /*mintags*/0, /*maxtags*/0
338	},
339	{
340		/* Broken tagged queuing drive */
341		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "iomega", "jaz*", "*" },
342		/*quirks*/0, /*mintags*/0, /*maxtags*/0
343	},
344	{
345		/* Broken tagged queuing drive */
346		{ T_DIRECT, SIP_MEDIA_FIXED, "CONNER", "CFP2107*", "*" },
347		/*quirks*/0, /*mintags*/0, /*maxtags*/0
348	},
349	{
350		/* This does not support other than LUN 0 */
351		{ T_DIRECT, SIP_MEDIA_FIXED, "VMware*", "*", "*" },
352		CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
353	},
354	{
355		/*
356		 * Broken tagged queuing drive.
357		 * Submitted by:
358		 * NAKAJI Hiroyuki <nakaji@zeisei.dpri.kyoto-u.ac.jp>
359		 * in PR kern/9535
360		 */
361		{ T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN34324U*", "*" },
362		/*quirks*/0, /*mintags*/0, /*maxtags*/0
363	},
364        {
365		/*
366		 * Slow when tagged queueing is enabled. (1.5MB/sec versus
367		 * 8MB/sec.)
368		 * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
369		 * Best performance with these drives is achieved with
370		 * tagged queueing turned off, and write caching turned on.
371		 */
372		{ T_DIRECT, SIP_MEDIA_FIXED, west_digital, "WDE*", "*" },
373		/*quirks*/0, /*mintags*/0, /*maxtags*/0
374        },
375        {
376		/*
377		 * Slow when tagged queueing is enabled. (1.5MB/sec versus
378		 * 8MB/sec.)
379		 * Submitted by: Andrew Gallatin <gallatin@cs.duke.edu>
380		 * Best performance with these drives is achieved with
381		 * tagged queueing turned off, and write caching turned on.
382		 */
383		{ T_DIRECT, SIP_MEDIA_FIXED, west_digital, "ENTERPRISE", "*" },
384		/*quirks*/0, /*mintags*/0, /*maxtags*/0
385        },
386	{
387		/*
388		 * Doesn't handle queue full condition correctly,
389		 * so we need to limit maxtags to what the device
390		 * can handle instead of determining this automatically.
391		 */
392		{ T_DIRECT, SIP_MEDIA_FIXED, samsung, "WN321010S*", "*" },
393		/*quirks*/0, /*mintags*/2, /*maxtags*/32
394	},
395	{
396		/* Really only one LUN */
397		{ T_ENCLOSURE, SIP_MEDIA_FIXED, "SUN", "SENA", "*" },
398		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
399	},
400	{
401		/* I can't believe we need a quirk for DPT volumes. */
402		{ T_ANY, SIP_MEDIA_FIXED|SIP_MEDIA_REMOVABLE, "DPT", "*", "*" },
403		CAM_QUIRK_NOLUNS,
404		/*mintags*/0, /*maxtags*/255
405	},
406	{
407		/*
408		 * Many Sony CDROM drives don't like multi-LUN probing.
409		 */
410		{ T_CDROM, SIP_MEDIA_REMOVABLE, sony, "CD-ROM CDU*", "*" },
411		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
412	},
413	{
414		/*
415		 * This drive doesn't like multiple LUN probing.
416		 * Submitted by:  Parag Patel <parag@cgt.com>
417		 */
418		{ T_WORM, SIP_MEDIA_REMOVABLE, sony, "CD-R   CDU9*", "*" },
419		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
420	},
421	{
422		{ T_WORM, SIP_MEDIA_REMOVABLE, "YAMAHA", "CDR100*", "*" },
423		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
424	},
425	{
426		/*
427		 * The 8200 doesn't like multi-lun probing, and probably
428		 * don't like serial number requests either.
429		 */
430		{
431			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
432			"EXB-8200*", "*"
433		},
434		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
435	},
436	{
437		/*
438		 * Let's try the same as above, but for a drive that says
439		 * it's an IPL-6860 but is actually an EXB 8200.
440		 */
441		{
442			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "EXABYTE",
443			"IPL-6860*", "*"
444		},
445		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
446	},
447	{
448		/*
449		 * These Hitachi drives don't like multi-lun probing.
450		 * The PR submitter has a DK319H, but says that the Linux
451		 * kernel has a similar work-around for the DK312 and DK314,
452		 * so all DK31* drives are quirked here.
453		 * PR:            misc/18793
454		 * Submitted by:  Paul Haddad <paul@pth.com>
455		 */
456		{ T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK31*", "*" },
457		CAM_QUIRK_NOLUNS, /*mintags*/2, /*maxtags*/255
458	},
459	{
460		/*
461		 * The Hitachi CJ series with J8A8 firmware apparently has
462		 * problems with tagged commands.
463		 * PR: 23536
464		 * Reported by: amagai@nue.org
465		 */
466		{ T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "DK32CJ*", "J8A8" },
467		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
468	},
469	{
470		/*
471		 * These are the large storage arrays.
472		 * Submitted by:  William Carrel <william.carrel@infospace.com>
473		 */
474		{ T_DIRECT, SIP_MEDIA_FIXED, "HITACHI", "OPEN*", "*" },
475		CAM_QUIRK_HILUNS, 2, 1024
476	},
477	{
478		/*
479		 * This old revision of the TDC3600 is also SCSI-1, and
480		 * hangs upon serial number probing.
481		 */
482		{
483			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "TANDBERG",
484			" TDC 3600", "U07:"
485		},
486		CAM_QUIRK_NOVPDS, /*mintags*/0, /*maxtags*/0
487	},
488	{
489		/*
490		 * Would repond to all LUNs if asked for.
491		 */
492		{
493			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "CALIPER",
494			"CP150", "*"
495		},
496		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
497	},
498	{
499		/*
500		 * Would repond to all LUNs if asked for.
501		 */
502		{
503			T_SEQUENTIAL, SIP_MEDIA_REMOVABLE, "KENNEDY",
504			"96X2*", "*"
505		},
506		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
507	},
508	{
509		/* Submitted by: Matthew Dodd <winter@jurai.net> */
510		{ T_PROCESSOR, SIP_MEDIA_FIXED, "Cabletrn", "EA41*", "*" },
511		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
512	},
513	{
514		/* Submitted by: Matthew Dodd <winter@jurai.net> */
515		{ T_PROCESSOR, SIP_MEDIA_FIXED, "CABLETRN", "EA41*", "*" },
516		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
517	},
518	{
519		/* TeraSolutions special settings for TRC-22 RAID */
520		{ T_DIRECT, SIP_MEDIA_FIXED, "TERASOLU", "TRC-22", "*" },
521		  /*quirks*/0, /*mintags*/55, /*maxtags*/255
522	},
523	{
524		/* Veritas Storage Appliance */
525		{ T_DIRECT, SIP_MEDIA_FIXED, "VERITAS", "*", "*" },
526		  CAM_QUIRK_HILUNS, /*mintags*/2, /*maxtags*/1024
527	},
528	{
529		/*
530		 * Would respond to all LUNs.  Device type and removable
531		 * flag are jumper-selectable.
532		 */
533		{ T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED, "MaxOptix",
534		  "Tahiti 1", "*"
535		},
536		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
537	},
538	{
539		/* EasyRAID E5A aka. areca ARC-6010 */
540		{ T_DIRECT, SIP_MEDIA_FIXED, "easyRAID", "*", "*" },
541		  CAM_QUIRK_NOHILUNS, /*mintags*/2, /*maxtags*/255
542	},
543	{
544		{ T_ENCLOSURE, SIP_MEDIA_FIXED, "DP", "BACKPLANE", "*" },
545		CAM_QUIRK_NOLUNS, /*mintags*/0, /*maxtags*/0
546	},
547	{
548		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "Garmin", "*", "*" },
549		CAM_QUIRK_NORPTLUNS, /*mintags*/2, /*maxtags*/255
550	},
551	{
552		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic", "STORAGE DEVICE*", "120?" },
553		CAM_QUIRK_NORPTLUNS, /*mintags*/2, /*maxtags*/255
554	},
555	{
556		{ T_DIRECT, SIP_MEDIA_REMOVABLE, "Generic", "MassStorageClass", "1533" },
557		CAM_QUIRK_NORPTLUNS, /*mintags*/2, /*maxtags*/255
558	},
559	{
560		/* Default tagged queuing parameters for all devices */
561		{
562		  T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
563		  /*vendor*/"*", /*product*/"*", /*revision*/"*"
564		},
565		/*quirks*/0, /*mintags*/2, /*maxtags*/255
566	},
567};
568
569static cam_status	proberegister(struct cam_periph *periph,
570				      void *arg);
571static void	 probeschedule(struct cam_periph *probe_periph);
572static void	 probestart(struct cam_periph *periph, union ccb *start_ccb);
573static void	 proberequestdefaultnegotiation(struct cam_periph *periph);
574static int       proberequestbackoff(struct cam_periph *periph,
575				     struct cam_ed *device);
576static void	 probedone(struct cam_periph *periph, union ccb *done_ccb);
577static void	 probe_purge_old(struct cam_path *path,
578				 struct scsi_report_luns_data *new,
579				 probe_flags flags);
580static void	 probecleanup(struct cam_periph *periph);
581static void	 scsi_find_quirk(struct cam_ed *device);
582static void	 scsi_scan_bus(struct cam_periph *periph, union ccb *ccb);
583static void	 scsi_scan_lun(struct cam_periph *periph,
584			       struct cam_path *path, cam_flags flags,
585			       union ccb *ccb);
586static void	 xptscandone(struct cam_periph *periph, union ccb *done_ccb);
587static struct cam_ed *
588		 scsi_alloc_device(struct cam_eb *bus, struct cam_et *target,
589				   lun_id_t lun_id);
590static void	 scsi_devise_transport(struct cam_path *path);
591static void	 scsi_set_transfer_settings(struct ccb_trans_settings *cts,
592					    struct cam_path *path,
593					    int async_update);
594static void	 scsi_toggle_tags(struct cam_path *path);
595static void	 scsi_dev_async(u_int32_t async_code,
596				struct cam_eb *bus,
597				struct cam_et *target,
598				struct cam_ed *device,
599				void *async_arg);
600static void	 scsi_action(union ccb *start_ccb);
601static void	 scsi_announce_periph(struct cam_periph *periph);
602static void	 scsi_announce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb);
603static void	 scsi_proto_announce(struct cam_ed *device);
604static void	 scsi_proto_announce_sbuf(struct cam_ed *device,
605					  struct sbuf *sb);
606static void	 scsi_proto_denounce(struct cam_ed *device);
607static void	 scsi_proto_denounce_sbuf(struct cam_ed *device,
608					  struct sbuf *sb);
609static void	 scsi_proto_debug_out(union ccb *ccb);
610static void	 _scsi_announce_periph(struct cam_periph *, u_int *, u_int *, struct ccb_trans_settings *);
611
612static struct xpt_xport_ops scsi_xport_ops = {
613	.alloc_device = scsi_alloc_device,
614	.action = scsi_action,
615	.async = scsi_dev_async,
616	.announce = scsi_announce_periph,
617	.announce_sbuf = scsi_announce_periph_sbuf,
618};
619#define SCSI_XPT_XPORT(x, X)			\
620static struct xpt_xport scsi_xport_ ## x = {	\
621	.xport = XPORT_ ## X,			\
622	.name = #x,				\
623	.ops = &scsi_xport_ops,			\
624};						\
625CAM_XPT_XPORT(scsi_xport_ ## x);
626
627SCSI_XPT_XPORT(spi, SPI);
628SCSI_XPT_XPORT(sas, SAS);
629SCSI_XPT_XPORT(fc, FC);
630SCSI_XPT_XPORT(usb, USB);
631SCSI_XPT_XPORT(iscsi, ISCSI);
632SCSI_XPT_XPORT(srp, SRP);
633SCSI_XPT_XPORT(ppb, PPB);
634
635#undef SCSI_XPORT_XPORT
636
637static struct xpt_proto_ops scsi_proto_ops = {
638	.announce = scsi_proto_announce,
639	.announce_sbuf = scsi_proto_announce_sbuf,
640	.denounce = scsi_proto_denounce,
641	.denounce_sbuf = scsi_proto_denounce_sbuf,
642	.debug_out = scsi_proto_debug_out,
643};
644static struct xpt_proto scsi_proto = {
645	.proto = PROTO_SCSI,
646	.name = "scsi",
647	.ops = &scsi_proto_ops,
648};
649CAM_XPT_PROTO(scsi_proto);
650
651static void
652probe_periph_init(void)
653{
654}
655
656static cam_status
657proberegister(struct cam_periph *periph, void *arg)
658{
659	union ccb *request_ccb;	/* CCB representing the probe request */
660	probe_softc *softc;
661
662	request_ccb = (union ccb *)arg;
663	if (request_ccb == NULL) {
664		printf("proberegister: no probe CCB, "
665		       "can't register device\n");
666		return(CAM_REQ_CMP_ERR);
667	}
668
669	softc = (probe_softc *)malloc(sizeof(*softc), M_CAMXPT, M_NOWAIT);
670
671	if (softc == NULL) {
672		printf("proberegister: Unable to probe new device. "
673		       "Unable to allocate softc\n");
674		return(CAM_REQ_CMP_ERR);
675	}
676	TAILQ_INIT(&softc->request_ccbs);
677	TAILQ_INSERT_TAIL(&softc->request_ccbs, &request_ccb->ccb_h,
678			  periph_links.tqe);
679	softc->flags = 0;
680	periph->softc = softc;
681	softc->periph = periph;
682	softc->action = PROBE_INVALID;
683	if (cam_periph_acquire(periph) != 0)
684		return (CAM_REQ_CMP_ERR);
685
686	CAM_DEBUG(periph->path, CAM_DEBUG_PROBE, ("Probe started\n"));
687	scsi_devise_transport(periph->path);
688
689	/*
690	 * Ensure we've waited at least a bus settle
691	 * delay before attempting to probe the device.
692	 * For HBAs that don't do bus resets, this won't make a difference.
693	 */
694	cam_periph_freeze_after_event(periph, &periph->path->bus->last_reset,
695				      scsi_delay);
696	probeschedule(periph);
697	return(CAM_REQ_CMP);
698}
699
700static void
701probeschedule(struct cam_periph *periph)
702{
703	struct ccb_pathinq cpi;
704	union ccb *ccb;
705	probe_softc *softc;
706
707	softc = (probe_softc *)periph->softc;
708	ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
709
710	xpt_path_inq(&cpi, periph->path);
711
712	/*
713	 * If a device has gone away and another device, or the same one,
714	 * is back in the same place, it should have a unit attention
715	 * condition pending.  It will not report the unit attention in
716	 * response to an inquiry, which may leave invalid transfer
717	 * negotiations in effect.  The TUR will reveal the unit attention
718	 * condition.  Only send the TUR for lun 0, since some devices
719	 * will get confused by commands other than inquiry to non-existent
720	 * luns.  If you think a device has gone away start your scan from
721	 * lun 0.  This will insure that any bogus transfer settings are
722	 * invalidated.
723	 *
724	 * If we haven't seen the device before and the controller supports
725	 * some kind of transfer negotiation, negotiate with the first
726	 * sent command if no bus reset was performed at startup.  This
727	 * ensures that the device is not confused by transfer negotiation
728	 * settings left over by loader or BIOS action.
729	 */
730	if (((ccb->ccb_h.path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
731	 && (ccb->ccb_h.target_lun == 0)) {
732		PROBE_SET_ACTION(softc, PROBE_TUR);
733	} else if ((cpi.hba_inquiry & (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE)) != 0
734	      && (cpi.hba_misc & PIM_NOBUSRESET) != 0) {
735		proberequestdefaultnegotiation(periph);
736		PROBE_SET_ACTION(softc, PROBE_INQUIRY);
737	} else {
738		PROBE_SET_ACTION(softc, PROBE_INQUIRY);
739	}
740
741	if (ccb->crcn.flags & CAM_EXPECT_INQ_CHANGE)
742		softc->flags |= PROBE_NO_ANNOUNCE;
743	else
744		softc->flags &= ~PROBE_NO_ANNOUNCE;
745
746	if (cpi.hba_misc & PIM_EXTLUNS)
747		softc->flags |= PROBE_EXTLUN;
748	else
749		softc->flags &= ~PROBE_EXTLUN;
750
751	xpt_schedule(periph, CAM_PRIORITY_XPT);
752}
753
754static void
755probestart(struct cam_periph *periph, union ccb *start_ccb)
756{
757	/* Probe the device that our peripheral driver points to */
758	struct ccb_scsiio *csio;
759	probe_softc *softc;
760
761	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probestart\n"));
762
763	softc = (probe_softc *)periph->softc;
764	csio = &start_ccb->csio;
765again:
766
767	switch (softc->action) {
768	case PROBE_TUR:
769	case PROBE_TUR_FOR_NEGOTIATION:
770	case PROBE_DV_EXIT:
771	{
772		scsi_test_unit_ready(csio,
773				     /*retries*/4,
774				     probedone,
775				     MSG_SIMPLE_Q_TAG,
776				     SSD_FULL_SIZE,
777				     /*timeout*/60000);
778		break;
779	}
780	case PROBE_INQUIRY:
781	case PROBE_FULL_INQUIRY:
782	case PROBE_INQUIRY_BASIC_DV1:
783	case PROBE_INQUIRY_BASIC_DV2:
784	{
785		u_int inquiry_len;
786		struct scsi_inquiry_data *inq_buf;
787
788		inq_buf = &periph->path->device->inq_data;
789
790		/*
791		 * If the device is currently configured, we calculate an
792		 * MD5 checksum of the inquiry data, and if the serial number
793		 * length is greater than 0, add the serial number data
794		 * into the checksum as well.  Once the inquiry and the
795		 * serial number check finish, we attempt to figure out
796		 * whether we still have the same device.
797		 */
798		if (((periph->path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
799		 && ((softc->flags & PROBE_INQUIRY_CKSUM) == 0)) {
800
801			MD5Init(&softc->context);
802			MD5Update(&softc->context, (unsigned char *)inq_buf,
803				  sizeof(struct scsi_inquiry_data));
804			softc->flags |= PROBE_INQUIRY_CKSUM;
805			if (periph->path->device->serial_num_len > 0) {
806				MD5Update(&softc->context,
807					  periph->path->device->serial_num,
808					  periph->path->device->serial_num_len);
809				softc->flags |= PROBE_SERIAL_CKSUM;
810			}
811			MD5Final(softc->digest, &softc->context);
812		}
813
814		if (softc->action == PROBE_INQUIRY)
815			inquiry_len = SHORT_INQUIRY_LENGTH;
816		else
817			inquiry_len = SID_ADDITIONAL_LENGTH(inq_buf);
818
819		/*
820		 * Some parallel SCSI devices fail to send an
821		 * ignore wide residue message when dealing with
822		 * odd length inquiry requests.  Round up to be
823		 * safe.
824		 */
825		inquiry_len = roundup2(inquiry_len, 2);
826
827		if (softc->action == PROBE_INQUIRY_BASIC_DV1
828		 || softc->action == PROBE_INQUIRY_BASIC_DV2) {
829			inq_buf = malloc(inquiry_len, M_CAMXPT, M_NOWAIT);
830		}
831		if (inq_buf == NULL) {
832			xpt_print(periph->path, "malloc failure- skipping Basic"
833			    "Domain Validation\n");
834			PROBE_SET_ACTION(softc, PROBE_DV_EXIT);
835			scsi_test_unit_ready(csio,
836					     /*retries*/4,
837					     probedone,
838					     MSG_SIMPLE_Q_TAG,
839					     SSD_FULL_SIZE,
840					     /*timeout*/60000);
841			break;
842		}
843		scsi_inquiry(csio,
844			     /*retries*/4,
845			     probedone,
846			     MSG_SIMPLE_Q_TAG,
847			     (u_int8_t *)inq_buf,
848			     inquiry_len,
849			     /*evpd*/FALSE,
850			     /*page_code*/0,
851			     SSD_MIN_SIZE,
852			     /*timeout*/60 * 1000);
853		break;
854	}
855	case PROBE_REPORT_LUNS:
856	{
857		void *rp;
858
859		rp = malloc(periph->path->target->rpl_size,
860		    M_CAMXPT, M_NOWAIT | M_ZERO);
861		if (rp == NULL) {
862			struct scsi_inquiry_data *inq_buf;
863			inq_buf = &periph->path->device->inq_data;
864			xpt_print(periph->path,
865			    "Unable to alloc report luns storage\n");
866			if (INQ_DATA_TQ_ENABLED(inq_buf))
867				PROBE_SET_ACTION(softc, PROBE_MODE_SENSE);
868			else
869				PROBE_SET_ACTION(softc,
870				    PROBE_SUPPORTED_VPD_LIST);
871			goto again;
872		}
873		scsi_report_luns(csio, 5, probedone, MSG_SIMPLE_Q_TAG,
874		    RPL_REPORT_DEFAULT, rp, periph->path->target->rpl_size,
875		    SSD_FULL_SIZE, 60000); break;
876		break;
877	}
878	case PROBE_MODE_SENSE:
879	{
880		void  *mode_buf;
881		int    mode_buf_len;
882
883		mode_buf_len = sizeof(struct scsi_mode_header_6)
884			     + sizeof(struct scsi_mode_blk_desc)
885			     + sizeof(struct scsi_control_page);
886		mode_buf = malloc(mode_buf_len, M_CAMXPT, M_NOWAIT);
887		if (mode_buf != NULL) {
888	                scsi_mode_sense(csio,
889					/*retries*/4,
890					probedone,
891					MSG_SIMPLE_Q_TAG,
892					/*dbd*/FALSE,
893					SMS_PAGE_CTRL_CURRENT,
894					SMS_CONTROL_MODE_PAGE,
895					mode_buf,
896					mode_buf_len,
897					SSD_FULL_SIZE,
898					/*timeout*/60000);
899			break;
900		}
901		xpt_print(periph->path, "Unable to mode sense control page - "
902		    "malloc failure\n");
903		PROBE_SET_ACTION(softc, PROBE_SUPPORTED_VPD_LIST);
904	}
905	/* FALLTHROUGH */
906	case PROBE_SUPPORTED_VPD_LIST:
907	{
908		struct scsi_vpd_supported_page_list *vpd_list;
909		struct cam_ed *device;
910
911		vpd_list = NULL;
912		device = periph->path->device;
913
914		if ((SCSI_QUIRK(device)->quirks & CAM_QUIRK_NOVPDS) == 0)
915			vpd_list = malloc(sizeof(*vpd_list), M_CAMXPT,
916			    M_NOWAIT | M_ZERO);
917
918		if (vpd_list != NULL) {
919			scsi_inquiry(csio,
920				     /*retries*/4,
921				     probedone,
922				     MSG_SIMPLE_Q_TAG,
923				     (u_int8_t *)vpd_list,
924				     sizeof(*vpd_list),
925				     /*evpd*/TRUE,
926				     SVPD_SUPPORTED_PAGE_LIST,
927				     SSD_MIN_SIZE,
928				     /*timeout*/60 * 1000);
929			break;
930		}
931done:
932		/*
933		 * We'll have to do without, let our probedone
934		 * routine finish up for us.
935		 */
936		start_ccb->csio.data_ptr = NULL;
937		cam_freeze_devq(periph->path);
938		cam_periph_doacquire(periph);
939		probedone(periph, start_ccb);
940		return;
941	}
942	case PROBE_DEVICE_ID:
943	{
944		struct scsi_vpd_device_id *devid;
945
946		devid = NULL;
947		if (scsi_vpd_supported_page(periph, SVPD_DEVICE_ID))
948			devid = malloc(SVPD_DEVICE_ID_MAX_SIZE, M_CAMXPT,
949			    M_NOWAIT | M_ZERO);
950
951		if (devid != NULL) {
952			scsi_inquiry(csio,
953				     /*retries*/4,
954				     probedone,
955				     MSG_SIMPLE_Q_TAG,
956				     (uint8_t *)devid,
957				     SVPD_DEVICE_ID_MAX_SIZE,
958				     /*evpd*/TRUE,
959				     SVPD_DEVICE_ID,
960				     SSD_MIN_SIZE,
961				     /*timeout*/60 * 1000);
962			break;
963		}
964		goto done;
965	}
966	case PROBE_EXTENDED_INQUIRY:
967	{
968		struct scsi_vpd_extended_inquiry_data *ext_inq;
969
970		ext_inq = NULL;
971		if (scsi_vpd_supported_page(periph, SVPD_EXTENDED_INQUIRY_DATA))
972			ext_inq = malloc(sizeof(*ext_inq), M_CAMXPT,
973			    M_NOWAIT | M_ZERO);
974
975		if (ext_inq != NULL) {
976			scsi_inquiry(csio,
977				     /*retries*/4,
978				     probedone,
979				     MSG_SIMPLE_Q_TAG,
980				     (uint8_t *)ext_inq,
981				     sizeof(*ext_inq),
982				     /*evpd*/TRUE,
983				     SVPD_EXTENDED_INQUIRY_DATA,
984				     SSD_MIN_SIZE,
985				     /*timeout*/60 * 1000);
986			break;
987		}
988		/*
989		 * We'll have to do without, let our probedone
990		 * routine finish up for us.
991		 */
992		goto done;
993	}
994	case PROBE_SERIAL_NUM:
995	{
996		struct scsi_vpd_unit_serial_number *serial_buf;
997		struct cam_ed* device;
998
999		serial_buf = NULL;
1000		device = periph->path->device;
1001		if (device->serial_num != NULL) {
1002			free(device->serial_num, M_CAMXPT);
1003			device->serial_num = NULL;
1004			device->serial_num_len = 0;
1005		}
1006
1007		if (scsi_vpd_supported_page(periph, SVPD_UNIT_SERIAL_NUMBER))
1008			serial_buf = (struct scsi_vpd_unit_serial_number *)
1009				malloc(sizeof(*serial_buf), M_CAMXPT,
1010				    M_NOWAIT|M_ZERO);
1011
1012		if (serial_buf != NULL) {
1013			scsi_inquiry(csio,
1014				     /*retries*/4,
1015				     probedone,
1016				     MSG_SIMPLE_Q_TAG,
1017				     (u_int8_t *)serial_buf,
1018				     sizeof(*serial_buf),
1019				     /*evpd*/TRUE,
1020				     SVPD_UNIT_SERIAL_NUMBER,
1021				     SSD_MIN_SIZE,
1022				     /*timeout*/60 * 1000);
1023			break;
1024		}
1025		goto done;
1026	}
1027	default:
1028		panic("probestart: invalid action state 0x%x\n", softc->action);
1029	}
1030	start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
1031	cam_periph_doacquire(periph);
1032	xpt_action(start_ccb);
1033}
1034
1035static void
1036proberequestdefaultnegotiation(struct cam_periph *periph)
1037{
1038	struct ccb_trans_settings cts;
1039
1040	xpt_setup_ccb(&cts.ccb_h, periph->path, CAM_PRIORITY_NONE);
1041	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1042	cts.type = CTS_TYPE_USER_SETTINGS;
1043	xpt_action((union ccb *)&cts);
1044	if (cam_ccb_status((union ccb *)&cts) != CAM_REQ_CMP) {
1045		return;
1046	}
1047	cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1048	cts.type = CTS_TYPE_CURRENT_SETTINGS;
1049	xpt_action((union ccb *)&cts);
1050}
1051
1052/*
1053 * Backoff Negotiation Code- only pertinent for SPI devices.
1054 */
1055static int
1056proberequestbackoff(struct cam_periph *periph, struct cam_ed *device)
1057{
1058	struct ccb_trans_settings cts;
1059	struct ccb_trans_settings_spi *spi;
1060
1061	memset(&cts, 0, sizeof (cts));
1062	xpt_setup_ccb(&cts.ccb_h, periph->path, CAM_PRIORITY_NONE);
1063	cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
1064	cts.type = CTS_TYPE_CURRENT_SETTINGS;
1065	xpt_action((union ccb *)&cts);
1066	if (cam_ccb_status((union ccb *)&cts) != CAM_REQ_CMP) {
1067		if (bootverbose) {
1068			xpt_print(periph->path,
1069			    "failed to get current device settings\n");
1070		}
1071		return (0);
1072	}
1073	if (cts.transport != XPORT_SPI) {
1074		if (bootverbose) {
1075			xpt_print(periph->path, "not SPI transport\n");
1076		}
1077		return (0);
1078	}
1079	spi = &cts.xport_specific.spi;
1080
1081	/*
1082	 * We cannot renegotiate sync rate if we don't have one.
1083	 */
1084	if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0) {
1085		if (bootverbose) {
1086			xpt_print(periph->path, "no sync rate known\n");
1087		}
1088		return (0);
1089	}
1090
1091	/*
1092	 * We'll assert that we don't have to touch PPR options- the
1093	 * SIM will see what we do with period and offset and adjust
1094	 * the PPR options as appropriate.
1095	 */
1096
1097	/*
1098	 * A sync rate with unknown or zero offset is nonsensical.
1099	 * A sync period of zero means Async.
1100	 */
1101	if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0
1102	 || spi->sync_offset == 0 || spi->sync_period == 0) {
1103		if (bootverbose) {
1104			xpt_print(periph->path, "no sync rate available\n");
1105		}
1106		return (0);
1107	}
1108
1109	if (device->flags & CAM_DEV_DV_HIT_BOTTOM) {
1110		CAM_DEBUG(periph->path, CAM_DEBUG_PROBE,
1111		    ("hit async: giving up on DV\n"));
1112		return (0);
1113	}
1114
1115
1116	/*
1117	 * Jump sync_period up by one, but stop at 5MHz and fall back to Async.
1118	 * We don't try to remember 'last' settings to see if the SIM actually
1119	 * gets into the speed we want to set. We check on the SIM telling
1120	 * us that a requested speed is bad, but otherwise don't try and
1121	 * check the speed due to the asynchronous and handshake nature
1122	 * of speed setting.
1123	 */
1124	spi->valid = CTS_SPI_VALID_SYNC_RATE | CTS_SPI_VALID_SYNC_OFFSET;
1125	for (;;) {
1126		spi->sync_period++;
1127		if (spi->sync_period >= 0xf) {
1128			spi->sync_period = 0;
1129			spi->sync_offset = 0;
1130			CAM_DEBUG(periph->path, CAM_DEBUG_PROBE,
1131			    ("setting to async for DV\n"));
1132			/*
1133			 * Once we hit async, we don't want to try
1134			 * any more settings.
1135			 */
1136			device->flags |= CAM_DEV_DV_HIT_BOTTOM;
1137		} else if (bootverbose) {
1138			CAM_DEBUG(periph->path, CAM_DEBUG_PROBE,
1139			    ("DV: period 0x%x\n", spi->sync_period));
1140			printf("setting period to 0x%x\n", spi->sync_period);
1141		}
1142		cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
1143		cts.type = CTS_TYPE_CURRENT_SETTINGS;
1144		xpt_action((union ccb *)&cts);
1145		if (cam_ccb_status((union ccb *)&cts) != CAM_REQ_CMP) {
1146			break;
1147		}
1148		CAM_DEBUG(periph->path, CAM_DEBUG_PROBE,
1149		    ("DV: failed to set period 0x%x\n", spi->sync_period));
1150		if (spi->sync_period == 0) {
1151			return (0);
1152		}
1153	}
1154	return (1);
1155}
1156
1157#define CCB_COMPLETED_OK(ccb) (((ccb).status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1158
1159static void
1160probedone(struct cam_periph *periph, union ccb *done_ccb)
1161{
1162	probe_softc *softc;
1163	struct cam_path *path;
1164	struct scsi_inquiry_data *inq_buf;
1165	u_int32_t  priority;
1166
1167	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("probedone\n"));
1168
1169	softc = (probe_softc *)periph->softc;
1170	path = done_ccb->ccb_h.path;
1171	priority = done_ccb->ccb_h.pinfo.priority;
1172	cam_periph_assert(periph, MA_OWNED);
1173
1174	switch (softc->action) {
1175	case PROBE_TUR:
1176	{
1177		if (cam_ccb_status(done_ccb) != CAM_REQ_CMP) {
1178
1179			if (cam_periph_error(done_ccb, 0, SF_NO_PRINT) ==
1180			    ERESTART) {
1181outr:
1182				/* Drop freeze taken due to CAM_DEV_QFREEZE */
1183				cam_release_devq(path, 0, 0, 0, FALSE);
1184				return;
1185			}
1186			else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
1187				/* Don't wedge the queue */
1188				xpt_release_devq(done_ccb->ccb_h.path,
1189						 /*count*/1,
1190						 /*run_queue*/TRUE);
1191		}
1192		PROBE_SET_ACTION(softc, PROBE_INQUIRY);
1193		xpt_release_ccb(done_ccb);
1194		xpt_schedule(periph, priority);
1195out:
1196		/* Drop freeze taken due to CAM_DEV_QFREEZE and release. */
1197		cam_release_devq(path, 0, 0, 0, FALSE);
1198		cam_periph_release_locked(periph);
1199		return;
1200	}
1201	case PROBE_INQUIRY:
1202	case PROBE_FULL_INQUIRY:
1203	{
1204		if (cam_ccb_status(done_ccb) == CAM_REQ_CMP) {
1205			u_int8_t periph_qual;
1206
1207			path->device->flags |= CAM_DEV_INQUIRY_DATA_VALID;
1208			scsi_find_quirk(path->device);
1209			inq_buf = &path->device->inq_data;
1210
1211			periph_qual = SID_QUAL(inq_buf);
1212
1213			if (periph_qual == SID_QUAL_LU_CONNECTED ||
1214			    periph_qual == SID_QUAL_LU_OFFLINE) {
1215				u_int8_t len;
1216
1217				/*
1218				 * We conservatively request only
1219				 * SHORT_INQUIRY_LEN bytes of inquiry
1220				 * information during our first try
1221				 * at sending an INQUIRY. If the device
1222				 * has more information to give,
1223				 * perform a second request specifying
1224				 * the amount of information the device
1225				 * is willing to give.
1226				 */
1227				len = inq_buf->additional_length
1228				    + offsetof(struct scsi_inquiry_data,
1229                                               additional_length) + 1;
1230				if (softc->action == PROBE_INQUIRY
1231				    && len > SHORT_INQUIRY_LENGTH) {
1232					PROBE_SET_ACTION(softc, PROBE_FULL_INQUIRY);
1233					xpt_release_ccb(done_ccb);
1234					xpt_schedule(periph, priority);
1235					goto out;
1236				}
1237
1238				scsi_devise_transport(path);
1239
1240				if (path->device->lun_id == 0 &&
1241				    SID_ANSI_REV(inq_buf) > SCSI_REV_SPC2 &&
1242				    (SCSI_QUIRK(path->device)->quirks &
1243				     CAM_QUIRK_NORPTLUNS) == 0) {
1244					PROBE_SET_ACTION(softc,
1245					    PROBE_REPORT_LUNS);
1246					/*
1247					 * Start with room for *one* lun.
1248					 */
1249					periph->path->target->rpl_size = 16;
1250				} else if (INQ_DATA_TQ_ENABLED(inq_buf))
1251					PROBE_SET_ACTION(softc,
1252					    PROBE_MODE_SENSE);
1253				else
1254					PROBE_SET_ACTION(softc,
1255					    PROBE_SUPPORTED_VPD_LIST);
1256
1257				if (path->device->flags & CAM_DEV_UNCONFIGURED) {
1258					path->device->flags &= ~CAM_DEV_UNCONFIGURED;
1259					xpt_acquire_device(path->device);
1260				}
1261				xpt_release_ccb(done_ccb);
1262				xpt_schedule(periph, priority);
1263				goto out;
1264			} else if (path->device->lun_id == 0 &&
1265			    SID_ANSI_REV(inq_buf) >= SCSI_REV_SPC2 &&
1266			    (SCSI_QUIRK(path->device)->quirks &
1267			     CAM_QUIRK_NORPTLUNS) == 0) {
1268				PROBE_SET_ACTION(softc, PROBE_REPORT_LUNS);
1269				periph->path->target->rpl_size = 16;
1270				xpt_release_ccb(done_ccb);
1271				xpt_schedule(periph, priority);
1272				goto out;
1273			}
1274		} else if (cam_periph_error(done_ccb, 0,
1275					    done_ccb->ccb_h.target_lun > 0
1276					    ? SF_RETRY_UA|SF_QUIET_IR
1277					    : SF_RETRY_UA) == ERESTART) {
1278			goto outr;
1279		} else {
1280			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1281				/* Don't wedge the queue */
1282				xpt_release_devq(done_ccb->ccb_h.path,
1283				    /*count*/1, /*run_queue*/TRUE);
1284			}
1285			path->device->flags &= ~CAM_DEV_INQUIRY_DATA_VALID;
1286		}
1287		/*
1288		 * If we get to this point, we got an error status back
1289		 * from the inquiry and the error status doesn't require
1290		 * automatically retrying the command.  Therefore, the
1291		 * inquiry failed.  If we had inquiry information before
1292		 * for this device, but this latest inquiry command failed,
1293		 * the device has probably gone away.  If this device isn't
1294		 * already marked unconfigured, notify the peripheral
1295		 * drivers that this device is no more.
1296		 */
1297		if ((path->device->flags & CAM_DEV_UNCONFIGURED) == 0)
1298			/* Send the async notification. */
1299			xpt_async(AC_LOST_DEVICE, path, NULL);
1300		PROBE_SET_ACTION(softc, PROBE_INVALID);
1301
1302		xpt_release_ccb(done_ccb);
1303		break;
1304	}
1305	case PROBE_REPORT_LUNS:
1306	{
1307		struct ccb_scsiio *csio;
1308		struct scsi_report_luns_data *lp;
1309		u_int nlun, maxlun;
1310
1311		csio = &done_ccb->csio;
1312
1313		lp = (struct scsi_report_luns_data *)csio->data_ptr;
1314		nlun = scsi_4btoul(lp->length) / 8;
1315		maxlun = (csio->dxfer_len / 8) - 1;
1316
1317		if (cam_ccb_status(done_ccb) != CAM_REQ_CMP) {
1318			if (cam_periph_error(done_ccb, 0,
1319				done_ccb->ccb_h.target_lun > 0 ?
1320				SF_RETRY_UA|SF_QUIET_IR : SF_RETRY_UA) ==
1321			    ERESTART) {
1322				goto outr;
1323			}
1324			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1325				xpt_release_devq(done_ccb->ccb_h.path, 1,
1326				    TRUE);
1327			}
1328			free(lp, M_CAMXPT);
1329			lp = NULL;
1330		} else if (nlun > maxlun) {
1331			/*
1332			 * Reallocate and retry to cover all luns
1333			 */
1334			CAM_DEBUG(path, CAM_DEBUG_PROBE,
1335			    ("Probe: reallocating REPORT_LUNS for %u luns\n",
1336			     nlun));
1337			free(lp, M_CAMXPT);
1338			path->target->rpl_size = (nlun << 3) + 8;
1339			xpt_release_ccb(done_ccb);
1340			xpt_schedule(periph, priority);
1341			goto out;
1342		} else if (nlun == 0) {
1343			/*
1344			 * If there don't appear to be any luns, bail.
1345			 */
1346			free(lp, M_CAMXPT);
1347			lp = NULL;
1348		} else {
1349			lun_id_t lun;
1350			int idx;
1351
1352			CAM_DEBUG(path, CAM_DEBUG_PROBE,
1353			   ("Probe: %u lun(s) reported\n", nlun));
1354
1355			CAM_GET_LUN(lp, 0, lun);
1356			/*
1357			 * If the first lun is not lun 0, then either there
1358			 * is no lun 0 in the list, or the list is unsorted.
1359			 */
1360			if (lun != 0) {
1361				for (idx = 0; idx < nlun; idx++) {
1362					CAM_GET_LUN(lp, idx, lun);
1363					if (lun == 0) {
1364						break;
1365					}
1366				}
1367				if (idx != nlun) {
1368					uint8_t tlun[8];
1369					memcpy(tlun,
1370					    lp->luns[0].lundata, 8);
1371					memcpy(lp->luns[0].lundata,
1372					    lp->luns[idx].lundata, 8);
1373					memcpy(lp->luns[idx].lundata,
1374					    tlun, 8);
1375					CAM_DEBUG(path, CAM_DEBUG_PROBE,
1376					    ("lun 0 in position %u\n", idx));
1377				}
1378			}
1379			/*
1380			 * If we have an old lun list, We can either
1381			 * retest luns that appear to have been dropped,
1382			 * or just nuke them.  We'll opt for the latter.
1383			 * This function will also install the new list
1384			 * in the target structure.
1385			 */
1386			probe_purge_old(path, lp, softc->flags);
1387			lp = NULL;
1388		}
1389		/* The processing above should either exit via a `goto
1390		 * out` or leave the `lp` variable `NULL` and (if
1391		 * applicable) `free()` the storage to which it had
1392		 * pointed. Assert here that is the case.
1393		 */
1394		KASSERT(lp == NULL, ("%s: lp is not NULL", __func__));
1395		inq_buf = &path->device->inq_data;
1396		if (path->device->flags & CAM_DEV_INQUIRY_DATA_VALID &&
1397		    (SID_QUAL(inq_buf) == SID_QUAL_LU_CONNECTED ||
1398		    SID_QUAL(inq_buf) == SID_QUAL_LU_OFFLINE)) {
1399			if (INQ_DATA_TQ_ENABLED(inq_buf))
1400				PROBE_SET_ACTION(softc, PROBE_MODE_SENSE);
1401			else
1402				PROBE_SET_ACTION(softc,
1403				    PROBE_SUPPORTED_VPD_LIST);
1404			xpt_release_ccb(done_ccb);
1405			xpt_schedule(periph, priority);
1406			goto out;
1407		}
1408		PROBE_SET_ACTION(softc, PROBE_INVALID);
1409		xpt_release_ccb(done_ccb);
1410		break;
1411	}
1412	case PROBE_MODE_SENSE:
1413	{
1414		struct ccb_scsiio *csio;
1415		struct scsi_mode_header_6 *mode_hdr;
1416
1417		csio = &done_ccb->csio;
1418		mode_hdr = (struct scsi_mode_header_6 *)csio->data_ptr;
1419		if (cam_ccb_status(done_ccb) == CAM_REQ_CMP) {
1420			struct scsi_control_page *page;
1421			u_int8_t *offset;
1422
1423			offset = ((u_int8_t *)&mode_hdr[1])
1424			    + mode_hdr->blk_desc_len;
1425			page = (struct scsi_control_page *)offset;
1426			path->device->queue_flags = page->queue_flags;
1427		} else if (cam_periph_error(done_ccb, 0,
1428			SF_RETRY_UA|SF_NO_PRINT) == ERESTART) {
1429			goto outr;
1430		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1431			/* Don't wedge the queue */
1432			xpt_release_devq(done_ccb->ccb_h.path,
1433					 /*count*/1, /*run_queue*/TRUE);
1434		}
1435		xpt_release_ccb(done_ccb);
1436		free(mode_hdr, M_CAMXPT);
1437		PROBE_SET_ACTION(softc, PROBE_SUPPORTED_VPD_LIST);
1438		xpt_schedule(periph, priority);
1439		goto out;
1440	}
1441	case PROBE_SUPPORTED_VPD_LIST:
1442	{
1443		struct ccb_scsiio *csio;
1444		struct scsi_vpd_supported_page_list *page_list;
1445
1446		csio = &done_ccb->csio;
1447		page_list =
1448		    (struct scsi_vpd_supported_page_list *)csio->data_ptr;
1449
1450		if (path->device->supported_vpds != NULL) {
1451			free(path->device->supported_vpds, M_CAMXPT);
1452			path->device->supported_vpds = NULL;
1453			path->device->supported_vpds_len = 0;
1454		}
1455
1456		if (page_list == NULL) {
1457			/*
1458			 * Don't process the command as it was never sent
1459			 */
1460		} else if (CCB_COMPLETED_OK(csio->ccb_h)) {
1461			/* Got vpd list */
1462			path->device->supported_vpds_len = page_list->length +
1463			    SVPD_SUPPORTED_PAGES_HDR_LEN;
1464			path->device->supported_vpds = (uint8_t *)page_list;
1465			xpt_release_ccb(done_ccb);
1466			PROBE_SET_ACTION(softc, PROBE_DEVICE_ID);
1467			xpt_schedule(periph, priority);
1468			goto out;
1469		} else if (cam_periph_error(done_ccb, 0,
1470			SF_RETRY_UA|SF_NO_PRINT) == ERESTART) {
1471			goto outr;
1472		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1473			/* Don't wedge the queue */
1474			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
1475					 /*run_queue*/TRUE);
1476		}
1477
1478		if (page_list)
1479			free(page_list, M_CAMXPT);
1480		/* No VPDs available, skip to device check. */
1481		csio->data_ptr = NULL;
1482		goto probe_device_check;
1483	}
1484	case PROBE_DEVICE_ID:
1485	{
1486		struct scsi_vpd_device_id *devid;
1487		struct ccb_scsiio *csio;
1488		uint32_t length = 0;
1489
1490		csio = &done_ccb->csio;
1491		devid = (struct scsi_vpd_device_id *)csio->data_ptr;
1492
1493		/* Clean up from previous instance of this device */
1494		if (path->device->device_id != NULL) {
1495			path->device->device_id_len = 0;
1496			free(path->device->device_id, M_CAMXPT);
1497			path->device->device_id = NULL;
1498		}
1499
1500		if (devid == NULL) {
1501			/* Don't process the command as it was never sent */
1502		} else if (CCB_COMPLETED_OK(csio->ccb_h)) {
1503			length = scsi_2btoul(devid->length);
1504			if (length != 0) {
1505				/*
1506				 * NB: device_id_len is actual response
1507				 * size, not buffer size.
1508				 */
1509				path->device->device_id_len = length +
1510				    SVPD_DEVICE_ID_HDR_LEN;
1511				path->device->device_id = (uint8_t *)devid;
1512			}
1513		} else if (cam_periph_error(done_ccb, 0,
1514			SF_RETRY_UA) == ERESTART) {
1515			goto outr;
1516		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1517			/* Don't wedge the queue */
1518			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
1519					 /*run_queue*/TRUE);
1520		}
1521
1522		/* Free the device id space if we don't use it */
1523		if (devid && length == 0)
1524			free(devid, M_CAMXPT);
1525		xpt_release_ccb(done_ccb);
1526		PROBE_SET_ACTION(softc, PROBE_EXTENDED_INQUIRY);
1527		xpt_schedule(periph, priority);
1528		goto out;
1529	}
1530	case PROBE_EXTENDED_INQUIRY: {
1531		struct scsi_vpd_extended_inquiry_data *ext_inq;
1532		struct ccb_scsiio *csio;
1533		int32_t length = 0;
1534
1535		csio = &done_ccb->csio;
1536		ext_inq = (struct scsi_vpd_extended_inquiry_data *)
1537		    csio->data_ptr;
1538		if (path->device->ext_inq != NULL) {
1539			path->device->ext_inq_len = 0;
1540			free(path->device->ext_inq, M_CAMXPT);
1541			path->device->ext_inq = NULL;
1542		}
1543
1544		if (ext_inq == NULL) {
1545			/* Don't process the command as it was never sent */
1546		} else if (CCB_COMPLETED_OK(csio->ccb_h)) {
1547			length = scsi_2btoul(ext_inq->page_length) +
1548			    __offsetof(struct scsi_vpd_extended_inquiry_data,
1549			    flags1);
1550			length = min(length, sizeof(*ext_inq));
1551			length -= csio->resid;
1552			if (length > 0) {
1553				path->device->ext_inq_len = length;
1554				path->device->ext_inq = (uint8_t *)ext_inq;
1555			}
1556		} else if (cam_periph_error(done_ccb, 0, SF_RETRY_UA) ==
1557		    ERESTART) {
1558			goto outr;
1559		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1560			/* Don't wedge the queue */
1561			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
1562					 /*run_queue*/TRUE);
1563		}
1564
1565		/* Free the device id space if we don't use it */
1566		if (ext_inq && length <= 0)
1567			free(ext_inq, M_CAMXPT);
1568		xpt_release_ccb(done_ccb);
1569		PROBE_SET_ACTION(softc, PROBE_SERIAL_NUM);
1570		xpt_schedule(periph, priority);
1571		goto out;
1572	}
1573
1574probe_device_check:
1575	case PROBE_SERIAL_NUM:
1576	{
1577		struct ccb_scsiio *csio;
1578		struct scsi_vpd_unit_serial_number *serial_buf;
1579		u_int32_t  priority;
1580		int changed;
1581		int have_serialnum;
1582
1583		changed = 1;
1584		have_serialnum = 0;
1585		csio = &done_ccb->csio;
1586		priority = done_ccb->ccb_h.pinfo.priority;
1587		serial_buf =
1588		    (struct scsi_vpd_unit_serial_number *)csio->data_ptr;
1589
1590		if (serial_buf == NULL) {
1591			/*
1592			 * Don't process the command as it was never sent
1593			 */
1594		} else if (cam_ccb_status(done_ccb) == CAM_REQ_CMP
1595			&& (serial_buf->length > 0)) {
1596
1597			have_serialnum = 1;
1598			path->device->serial_num =
1599				(u_int8_t *)malloc((serial_buf->length + 1),
1600						   M_CAMXPT, M_NOWAIT);
1601			if (path->device->serial_num != NULL) {
1602				int start, slen;
1603
1604				start = strspn(serial_buf->serial_num, " ");
1605				slen = serial_buf->length - start;
1606				if (slen <= 0) {
1607					/*
1608					 * SPC5r05 says that an all-space serial
1609					 * number means no product serial number
1610					 * is available
1611					 */
1612					slen = 0;
1613				}
1614				memcpy(path->device->serial_num,
1615				       &serial_buf->serial_num[start], slen);
1616				path->device->serial_num_len = slen;
1617				path->device->serial_num[slen] = '\0';
1618			}
1619		} else if (cam_periph_error(done_ccb, 0,
1620			SF_RETRY_UA|SF_NO_PRINT) == ERESTART) {
1621			goto outr;
1622		} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1623			/* Don't wedge the queue */
1624			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
1625					 /*run_queue*/TRUE);
1626		}
1627
1628		/*
1629		 * Let's see if we have seen this device before.
1630		 */
1631		if ((softc->flags & PROBE_INQUIRY_CKSUM) != 0) {
1632			MD5_CTX context;
1633			u_int8_t digest[16];
1634
1635			MD5Init(&context);
1636
1637			MD5Update(&context,
1638				  (unsigned char *)&path->device->inq_data,
1639				  sizeof(struct scsi_inquiry_data));
1640
1641			if (have_serialnum)
1642				MD5Update(&context, path->device->serial_num,
1643					  path->device->serial_num_len);
1644
1645			MD5Final(digest, &context);
1646			if (bcmp(softc->digest, digest, 16) == 0)
1647				changed = 0;
1648
1649			/*
1650			 * XXX Do we need to do a TUR in order to ensure
1651			 *     that the device really hasn't changed???
1652			 */
1653			if ((changed != 0)
1654			 && ((softc->flags & PROBE_NO_ANNOUNCE) == 0))
1655				xpt_async(AC_LOST_DEVICE, path, NULL);
1656		}
1657		if (serial_buf != NULL)
1658			free(serial_buf, M_CAMXPT);
1659
1660		if (changed != 0) {
1661			/*
1662			 * Now that we have all the necessary
1663			 * information to safely perform transfer
1664			 * negotiations... Controllers don't perform
1665			 * any negotiation or tagged queuing until
1666			 * after the first XPT_SET_TRAN_SETTINGS ccb is
1667			 * received.  So, on a new device, just retrieve
1668			 * the user settings, and set them as the current
1669			 * settings to set the device up.
1670			 */
1671			proberequestdefaultnegotiation(periph);
1672			xpt_release_ccb(done_ccb);
1673
1674			/*
1675			 * Perform a TUR to allow the controller to
1676			 * perform any necessary transfer negotiation.
1677			 */
1678			PROBE_SET_ACTION(softc, PROBE_TUR_FOR_NEGOTIATION);
1679			xpt_schedule(periph, priority);
1680			goto out;
1681		}
1682		xpt_release_ccb(done_ccb);
1683		break;
1684	}
1685	case PROBE_TUR_FOR_NEGOTIATION:
1686	case PROBE_DV_EXIT:
1687		if (cam_ccb_status(done_ccb) != CAM_REQ_CMP) {
1688			if (cam_periph_error(done_ccb, 0, SF_NO_PRINT |
1689			    SF_NO_RECOVERY | SF_NO_RETRY) == ERESTART)
1690				goto outr;
1691		}
1692		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1693			/* Don't wedge the queue */
1694			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
1695					 /*run_queue*/TRUE);
1696		}
1697		/*
1698		 * Do Domain Validation for lun 0 on devices that claim
1699		 * to support Synchronous Transfer modes.
1700		 */
1701	 	if (softc->action == PROBE_TUR_FOR_NEGOTIATION
1702		 && done_ccb->ccb_h.target_lun == 0
1703		 && (path->device->inq_data.flags & SID_Sync) != 0
1704                 && (path->device->flags & CAM_DEV_IN_DV) == 0) {
1705			CAM_DEBUG(periph->path, CAM_DEBUG_PROBE,
1706			    ("Begin Domain Validation\n"));
1707			path->device->flags |= CAM_DEV_IN_DV;
1708			xpt_release_ccb(done_ccb);
1709			PROBE_SET_ACTION(softc, PROBE_INQUIRY_BASIC_DV1);
1710			xpt_schedule(periph, priority);
1711			goto out;
1712		}
1713		if (softc->action == PROBE_DV_EXIT) {
1714			CAM_DEBUG(periph->path, CAM_DEBUG_PROBE,
1715			    ("Leave Domain Validation\n"));
1716		}
1717		if (path->device->flags & CAM_DEV_UNCONFIGURED) {
1718			path->device->flags &= ~CAM_DEV_UNCONFIGURED;
1719			xpt_acquire_device(path->device);
1720		}
1721		path->device->flags &=
1722		    ~(CAM_DEV_IN_DV|CAM_DEV_DV_HIT_BOTTOM);
1723		if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
1724			/* Inform the XPT that a new device has been found */
1725			done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
1726			xpt_action(done_ccb);
1727			xpt_async(AC_FOUND_DEVICE, done_ccb->ccb_h.path,
1728				  done_ccb);
1729		}
1730		PROBE_SET_ACTION(softc, PROBE_DONE);
1731		xpt_release_ccb(done_ccb);
1732		break;
1733	case PROBE_INQUIRY_BASIC_DV1:
1734	case PROBE_INQUIRY_BASIC_DV2:
1735	{
1736		struct scsi_inquiry_data *nbuf;
1737		struct ccb_scsiio *csio;
1738
1739		if (cam_ccb_status(done_ccb) != CAM_REQ_CMP) {
1740			if (cam_periph_error(done_ccb, 0, SF_NO_PRINT |
1741			    SF_NO_RECOVERY | SF_NO_RETRY) == ERESTART)
1742				goto outr;
1743		}
1744		if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1745			/* Don't wedge the queue */
1746			xpt_release_devq(done_ccb->ccb_h.path, /*count*/1,
1747					 /*run_queue*/TRUE);
1748		}
1749		csio = &done_ccb->csio;
1750		nbuf = (struct scsi_inquiry_data *)csio->data_ptr;
1751		if (bcmp(nbuf, &path->device->inq_data, SHORT_INQUIRY_LENGTH)) {
1752			xpt_print(path,
1753			    "inquiry data fails comparison at DV%d step\n",
1754			    softc->action == PROBE_INQUIRY_BASIC_DV1 ? 1 : 2);
1755			if (proberequestbackoff(periph, path->device)) {
1756				path->device->flags &= ~CAM_DEV_IN_DV;
1757				PROBE_SET_ACTION(softc, PROBE_TUR_FOR_NEGOTIATION);
1758			} else {
1759				/* give up */
1760				PROBE_SET_ACTION(softc, PROBE_DV_EXIT);
1761			}
1762			free(nbuf, M_CAMXPT);
1763			xpt_release_ccb(done_ccb);
1764			xpt_schedule(periph, priority);
1765			goto out;
1766		}
1767		free(nbuf, M_CAMXPT);
1768		if (softc->action == PROBE_INQUIRY_BASIC_DV1) {
1769			PROBE_SET_ACTION(softc, PROBE_INQUIRY_BASIC_DV2);
1770			xpt_release_ccb(done_ccb);
1771			xpt_schedule(periph, priority);
1772			goto out;
1773		}
1774		if (softc->action == PROBE_INQUIRY_BASIC_DV2) {
1775			CAM_DEBUG(periph->path, CAM_DEBUG_PROBE,
1776			    ("Leave Domain Validation Successfully\n"));
1777		}
1778		if (path->device->flags & CAM_DEV_UNCONFIGURED) {
1779			path->device->flags &= ~CAM_DEV_UNCONFIGURED;
1780			xpt_acquire_device(path->device);
1781		}
1782		path->device->flags &=
1783		    ~(CAM_DEV_IN_DV|CAM_DEV_DV_HIT_BOTTOM);
1784		if ((softc->flags & PROBE_NO_ANNOUNCE) == 0) {
1785			/* Inform the XPT that a new device has been found */
1786			done_ccb->ccb_h.func_code = XPT_GDEV_TYPE;
1787			xpt_action(done_ccb);
1788			xpt_async(AC_FOUND_DEVICE, done_ccb->ccb_h.path,
1789				  done_ccb);
1790		}
1791		PROBE_SET_ACTION(softc, PROBE_DONE);
1792		xpt_release_ccb(done_ccb);
1793		break;
1794	}
1795	default:
1796		panic("probedone: invalid action state 0x%x\n", softc->action);
1797	}
1798	done_ccb = (union ccb *)TAILQ_FIRST(&softc->request_ccbs);
1799	TAILQ_REMOVE(&softc->request_ccbs, &done_ccb->ccb_h, periph_links.tqe);
1800	done_ccb->ccb_h.status = CAM_REQ_CMP;
1801	xpt_done(done_ccb);
1802	if (TAILQ_FIRST(&softc->request_ccbs) == NULL) {
1803		CAM_DEBUG(periph->path, CAM_DEBUG_PROBE, ("Probe completed\n"));
1804		/* Drop freeze taken due to CAM_DEV_QFREEZE flag set. */
1805		cam_release_devq(path, 0, 0, 0, FALSE);
1806		cam_periph_release_locked(periph);
1807		cam_periph_invalidate(periph);
1808		cam_periph_release_locked(periph);
1809	} else {
1810		probeschedule(periph);
1811		goto out;
1812	}
1813}
1814
1815static void
1816probe_purge_old(struct cam_path *path, struct scsi_report_luns_data *new,
1817    probe_flags flags)
1818{
1819	struct cam_path *tp;
1820	struct scsi_report_luns_data *old;
1821	u_int idx1, idx2, nlun_old, nlun_new;
1822	lun_id_t this_lun;
1823	u_int8_t *ol, *nl;
1824
1825	if (path->target == NULL) {
1826		return;
1827	}
1828	mtx_lock(&path->target->luns_mtx);
1829	old = path->target->luns;
1830	path->target->luns = new;
1831	mtx_unlock(&path->target->luns_mtx);
1832	if (old == NULL)
1833		return;
1834	nlun_old = scsi_4btoul(old->length) / 8;
1835	nlun_new = scsi_4btoul(new->length) / 8;
1836
1837	/*
1838	 * We are not going to assume sorted lists. Deal.
1839	 */
1840	for (idx1 = 0; idx1 < nlun_old; idx1++) {
1841		ol = old->luns[idx1].lundata;
1842		for (idx2 = 0; idx2 < nlun_new; idx2++) {
1843			nl = new->luns[idx2].lundata;
1844			if (memcmp(nl, ol, 8) == 0) {
1845				break;
1846			}
1847		}
1848		if (idx2 < nlun_new) {
1849			continue;
1850		}
1851		/*
1852		 * An 'old' item not in the 'new' list.
1853		 * Nuke it. Except that if it is lun 0,
1854		 * that would be what the probe state
1855		 * machine is currently working on,
1856		 * so we won't do that.
1857		 */
1858		CAM_GET_LUN(old, idx1, this_lun);
1859		if (this_lun == 0) {
1860			continue;
1861		}
1862
1863		/*
1864		 * We also cannot nuke it if it is
1865		 * not in a lun format we understand
1866		 * and replace the LUN with a "simple" LUN
1867		 * if that is all the HBA supports.
1868		 */
1869		if (!(flags & PROBE_EXTLUN)) {
1870			if (!CAM_CAN_GET_SIMPLE_LUN(old, idx1))
1871				continue;
1872			CAM_GET_SIMPLE_LUN(old, idx1, this_lun);
1873		}
1874
1875		if (xpt_create_path(&tp, NULL, xpt_path_path_id(path),
1876		    xpt_path_target_id(path), this_lun) == CAM_REQ_CMP) {
1877			xpt_async(AC_LOST_DEVICE, tp, NULL);
1878			xpt_free_path(tp);
1879		}
1880	}
1881	free(old, M_CAMXPT);
1882}
1883
1884static void
1885probecleanup(struct cam_periph *periph)
1886{
1887	free(periph->softc, M_CAMXPT);
1888}
1889
1890static void
1891scsi_find_quirk(struct cam_ed *device)
1892{
1893	struct scsi_quirk_entry *quirk;
1894	caddr_t	match;
1895
1896	match = cam_quirkmatch((caddr_t)&device->inq_data,
1897			       (caddr_t)scsi_quirk_table,
1898			       nitems(scsi_quirk_table),
1899			       sizeof(*scsi_quirk_table), scsi_inquiry_match);
1900
1901	if (match == NULL)
1902		panic("xpt_find_quirk: device didn't match wildcard entry!!");
1903
1904	quirk = (struct scsi_quirk_entry *)match;
1905	device->quirk = quirk;
1906	device->mintags = quirk->mintags;
1907	device->maxtags = quirk->maxtags;
1908}
1909
1910static int
1911sysctl_cam_search_luns(SYSCTL_HANDLER_ARGS)
1912{
1913	int error, val;
1914
1915	val = cam_srch_hi;
1916	error = sysctl_handle_int(oidp, &val, 0, req);
1917	if (error != 0 || req->newptr == NULL)
1918		return (error);
1919	if (val == 0 || val == 1) {
1920		cam_srch_hi = val;
1921		return (0);
1922	} else {
1923		return (EINVAL);
1924	}
1925}
1926
1927typedef struct {
1928	union	ccb *request_ccb;
1929	struct 	ccb_pathinq *cpi;
1930	int	counter;
1931	int	lunindex[0];
1932} scsi_scan_bus_info;
1933
1934/*
1935 * To start a scan, request_ccb is an XPT_SCAN_BUS ccb.
1936 * As the scan progresses, scsi_scan_bus is used as the
1937 * callback on completion function.
1938 */
1939static void
1940scsi_scan_bus(struct cam_periph *periph, union ccb *request_ccb)
1941{
1942	struct mtx *mtx;
1943
1944	CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
1945		  ("scsi_scan_bus\n"));
1946	switch (request_ccb->ccb_h.func_code) {
1947	case XPT_SCAN_BUS:
1948	case XPT_SCAN_TGT:
1949	{
1950		scsi_scan_bus_info *scan_info;
1951		union	ccb *work_ccb, *reset_ccb;
1952		struct	cam_path *path;
1953		u_int	i;
1954		u_int	low_target, max_target;
1955		u_int	initiator_id;
1956
1957		/* Find out the characteristics of the bus */
1958		work_ccb = xpt_alloc_ccb_nowait();
1959		if (work_ccb == NULL) {
1960			request_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
1961			xpt_done(request_ccb);
1962			return;
1963		}
1964		xpt_setup_ccb(&work_ccb->ccb_h, request_ccb->ccb_h.path,
1965			      request_ccb->ccb_h.pinfo.priority);
1966		work_ccb->ccb_h.func_code = XPT_PATH_INQ;
1967		xpt_action(work_ccb);
1968		if (work_ccb->ccb_h.status != CAM_REQ_CMP) {
1969			request_ccb->ccb_h.status = work_ccb->ccb_h.status;
1970			xpt_free_ccb(work_ccb);
1971			xpt_done(request_ccb);
1972			return;
1973		}
1974
1975		if ((work_ccb->cpi.hba_misc & PIM_NOINITIATOR) != 0) {
1976			/*
1977			 * Can't scan the bus on an adapter that
1978			 * cannot perform the initiator role.
1979			 */
1980			request_ccb->ccb_h.status = CAM_REQ_CMP;
1981			xpt_free_ccb(work_ccb);
1982			xpt_done(request_ccb);
1983			return;
1984		}
1985
1986		/* We may need to reset bus first, if we haven't done it yet. */
1987		if ((work_ccb->cpi.hba_inquiry &
1988		    (PI_WIDE_32|PI_WIDE_16|PI_SDTR_ABLE)) &&
1989		    !(work_ccb->cpi.hba_misc & PIM_NOBUSRESET) &&
1990		    !timevalisset(&request_ccb->ccb_h.path->bus->last_reset) &&
1991		    (reset_ccb = xpt_alloc_ccb_nowait()) != NULL) {
1992			xpt_setup_ccb(&reset_ccb->ccb_h, request_ccb->ccb_h.path,
1993			      CAM_PRIORITY_NONE);
1994			reset_ccb->ccb_h.func_code = XPT_RESET_BUS;
1995			xpt_action(reset_ccb);
1996			if (reset_ccb->ccb_h.status != CAM_REQ_CMP) {
1997				request_ccb->ccb_h.status = reset_ccb->ccb_h.status;
1998				xpt_free_ccb(reset_ccb);
1999				xpt_free_ccb(work_ccb);
2000				xpt_done(request_ccb);
2001				return;
2002			}
2003			xpt_free_ccb(reset_ccb);
2004		}
2005
2006		/* Save some state for use while we probe for devices */
2007		scan_info = (scsi_scan_bus_info *) malloc(sizeof(scsi_scan_bus_info) +
2008		    (work_ccb->cpi.max_target * sizeof (u_int)), M_CAMXPT, M_ZERO|M_NOWAIT);
2009		if (scan_info == NULL) {
2010			request_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
2011			xpt_free_ccb(work_ccb);
2012			xpt_done(request_ccb);
2013			return;
2014		}
2015		CAM_DEBUG(request_ccb->ccb_h.path, CAM_DEBUG_TRACE,
2016		   ("SCAN start for %p\n", scan_info));
2017		scan_info->request_ccb = request_ccb;
2018		scan_info->cpi = &work_ccb->cpi;
2019
2020		/* Cache on our stack so we can work asynchronously */
2021		max_target = scan_info->cpi->max_target;
2022		low_target = 0;
2023		initiator_id = scan_info->cpi->initiator_id;
2024
2025
2026		/*
2027		 * We can scan all targets in parallel, or do it sequentially.
2028		 */
2029
2030		if (request_ccb->ccb_h.func_code == XPT_SCAN_TGT) {
2031			max_target = low_target = request_ccb->ccb_h.target_id;
2032			scan_info->counter = 0;
2033		} else if (scan_info->cpi->hba_misc & PIM_SEQSCAN) {
2034			max_target = 0;
2035			scan_info->counter = 0;
2036		} else {
2037			scan_info->counter = scan_info->cpi->max_target + 1;
2038			if (scan_info->cpi->initiator_id < scan_info->counter) {
2039				scan_info->counter--;
2040			}
2041		}
2042		mtx = xpt_path_mtx(scan_info->request_ccb->ccb_h.path);
2043		mtx_unlock(mtx);
2044
2045		for (i = low_target; i <= max_target; i++) {
2046			cam_status status;
2047			if (i == initiator_id)
2048				continue;
2049
2050			status = xpt_create_path(&path, NULL,
2051						 request_ccb->ccb_h.path_id,
2052						 i, 0);
2053			if (status != CAM_REQ_CMP) {
2054				printf("scsi_scan_bus: xpt_create_path failed"
2055				       " with status %#x, bus scan halted\n",
2056				       status);
2057				free(scan_info, M_CAMXPT);
2058				request_ccb->ccb_h.status = status;
2059				xpt_free_ccb(work_ccb);
2060				xpt_done(request_ccb);
2061				break;
2062			}
2063			work_ccb = xpt_alloc_ccb_nowait();
2064			if (work_ccb == NULL) {
2065				xpt_free_ccb((union ccb *)scan_info->cpi);
2066				free(scan_info, M_CAMXPT);
2067				xpt_free_path(path);
2068				request_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
2069				xpt_done(request_ccb);
2070				break;
2071			}
2072			xpt_setup_ccb(&work_ccb->ccb_h, path,
2073				      request_ccb->ccb_h.pinfo.priority);
2074			work_ccb->ccb_h.func_code = XPT_SCAN_LUN;
2075			work_ccb->ccb_h.cbfcnp = scsi_scan_bus;
2076			work_ccb->ccb_h.flags |= CAM_UNLOCKED;
2077			work_ccb->ccb_h.ppriv_ptr0 = scan_info;
2078			work_ccb->crcn.flags = request_ccb->crcn.flags;
2079			xpt_action(work_ccb);
2080		}
2081
2082		mtx_lock(mtx);
2083		break;
2084	}
2085	case XPT_SCAN_LUN:
2086	{
2087		cam_status status;
2088		struct cam_path *path, *oldpath;
2089		scsi_scan_bus_info *scan_info;
2090		struct cam_et *target;
2091		struct cam_ed *device, *nextdev;
2092		int next_target;
2093		path_id_t path_id;
2094		target_id_t target_id;
2095		lun_id_t lun_id;
2096
2097		oldpath = request_ccb->ccb_h.path;
2098
2099		status = cam_ccb_status(request_ccb);
2100		scan_info = (scsi_scan_bus_info *)request_ccb->ccb_h.ppriv_ptr0;
2101		path_id = request_ccb->ccb_h.path_id;
2102		target_id = request_ccb->ccb_h.target_id;
2103		lun_id = request_ccb->ccb_h.target_lun;
2104		target = request_ccb->ccb_h.path->target;
2105		next_target = 1;
2106
2107		mtx = xpt_path_mtx(scan_info->request_ccb->ccb_h.path);
2108		mtx_lock(mtx);
2109		mtx_lock(&target->luns_mtx);
2110		if (target->luns) {
2111			lun_id_t first;
2112			u_int nluns = scsi_4btoul(target->luns->length) / 8;
2113
2114			/*
2115			 * Make sure we skip over lun 0 if it's the first member
2116			 * of the list as we've actually just finished probing
2117			 * it.
2118			 */
2119			CAM_GET_LUN(target->luns, 0, first);
2120			if (first == 0 && scan_info->lunindex[target_id] == 0) {
2121				scan_info->lunindex[target_id]++;
2122			}
2123
2124			/*
2125			 * Skip any LUNs that the HBA can't deal with.
2126			 */
2127			while (scan_info->lunindex[target_id] < nluns) {
2128				if (scan_info->cpi->hba_misc & PIM_EXTLUNS) {
2129					CAM_GET_LUN(target->luns,
2130					    scan_info->lunindex[target_id],
2131					    lun_id);
2132					break;
2133				}
2134
2135				if (CAM_CAN_GET_SIMPLE_LUN(target->luns,
2136				    scan_info->lunindex[target_id])) {
2137					CAM_GET_SIMPLE_LUN(target->luns,
2138					    scan_info->lunindex[target_id],
2139					    lun_id);
2140					break;
2141				}
2142
2143				scan_info->lunindex[target_id]++;
2144			}
2145
2146			if (scan_info->lunindex[target_id] < nluns) {
2147				mtx_unlock(&target->luns_mtx);
2148				next_target = 0;
2149				CAM_DEBUG(request_ccb->ccb_h.path,
2150				    CAM_DEBUG_PROBE,
2151				   ("next lun to try at index %u is %jx\n",
2152				   scan_info->lunindex[target_id],
2153				   (uintmax_t)lun_id));
2154				scan_info->lunindex[target_id]++;
2155			} else {
2156				mtx_unlock(&target->luns_mtx);
2157				/* We're done with scanning all luns. */
2158			}
2159		} else {
2160			mtx_unlock(&target->luns_mtx);
2161			device = request_ccb->ccb_h.path->device;
2162			/* Continue sequential LUN scan if: */
2163			/*  -- we have more LUNs that need recheck */
2164			mtx_lock(&target->bus->eb_mtx);
2165			nextdev = device;
2166			while ((nextdev = TAILQ_NEXT(nextdev, links)) != NULL)
2167				if ((nextdev->flags & CAM_DEV_UNCONFIGURED) == 0)
2168					break;
2169			mtx_unlock(&target->bus->eb_mtx);
2170			if (nextdev != NULL) {
2171				next_target = 0;
2172			/*  -- stop if CAM_QUIRK_NOLUNS is set. */
2173			} else if (SCSI_QUIRK(device)->quirks & CAM_QUIRK_NOLUNS) {
2174				next_target = 1;
2175			/*  -- this LUN is connected and its SCSI version
2176			 *     allows more LUNs. */
2177			} else if ((device->flags & CAM_DEV_UNCONFIGURED) == 0) {
2178				if (lun_id < (CAM_SCSI2_MAXLUN-1) ||
2179				    CAN_SRCH_HI_DENSE(device))
2180					next_target = 0;
2181			/*  -- this LUN is disconnected, its SCSI version
2182			 *     allows more LUNs and we guess they may be. */
2183			} else if ((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0) {
2184				if (lun_id < (CAM_SCSI2_MAXLUN-1) ||
2185				    CAN_SRCH_HI_SPARSE(device))
2186					next_target = 0;
2187			}
2188			if (next_target == 0) {
2189				lun_id++;
2190				if (lun_id > scan_info->cpi->max_lun)
2191					next_target = 1;
2192			}
2193		}
2194
2195		/*
2196		 * Check to see if we scan any further luns.
2197		 */
2198		if (next_target) {
2199			int done;
2200
2201			/*
2202			 * Free the current request path- we're done with it.
2203			 */
2204			xpt_free_path(oldpath);
2205 hop_again:
2206			done = 0;
2207			if (scan_info->request_ccb->ccb_h.func_code == XPT_SCAN_TGT) {
2208				done = 1;
2209			} else if (scan_info->cpi->hba_misc & PIM_SEQSCAN) {
2210				scan_info->counter++;
2211				if (scan_info->counter ==
2212				    scan_info->cpi->initiator_id) {
2213					scan_info->counter++;
2214				}
2215				if (scan_info->counter >=
2216				    scan_info->cpi->max_target+1) {
2217					done = 1;
2218				}
2219			} else {
2220				scan_info->counter--;
2221				if (scan_info->counter == 0) {
2222					done = 1;
2223				}
2224			}
2225			if (done) {
2226				mtx_unlock(mtx);
2227				xpt_free_ccb(request_ccb);
2228				xpt_free_ccb((union ccb *)scan_info->cpi);
2229				request_ccb = scan_info->request_ccb;
2230				CAM_DEBUG(request_ccb->ccb_h.path,
2231				    CAM_DEBUG_TRACE,
2232				   ("SCAN done for %p\n", scan_info));
2233				free(scan_info, M_CAMXPT);
2234				request_ccb->ccb_h.status = CAM_REQ_CMP;
2235				xpt_done(request_ccb);
2236				break;
2237			}
2238
2239			if ((scan_info->cpi->hba_misc & PIM_SEQSCAN) == 0) {
2240				mtx_unlock(mtx);
2241				xpt_free_ccb(request_ccb);
2242				break;
2243			}
2244			status = xpt_create_path(&path, NULL,
2245			    scan_info->request_ccb->ccb_h.path_id,
2246			    scan_info->counter, 0);
2247			if (status != CAM_REQ_CMP) {
2248				mtx_unlock(mtx);
2249				printf("scsi_scan_bus: xpt_create_path failed"
2250				    " with status %#x, bus scan halted\n",
2251			       	    status);
2252				xpt_free_ccb(request_ccb);
2253				xpt_free_ccb((union ccb *)scan_info->cpi);
2254				request_ccb = scan_info->request_ccb;
2255				free(scan_info, M_CAMXPT);
2256				request_ccb->ccb_h.status = status;
2257				xpt_done(request_ccb);
2258				break;
2259			}
2260			xpt_setup_ccb(&request_ccb->ccb_h, path,
2261			    request_ccb->ccb_h.pinfo.priority);
2262			request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
2263			request_ccb->ccb_h.cbfcnp = scsi_scan_bus;
2264			request_ccb->ccb_h.flags |= CAM_UNLOCKED;
2265			request_ccb->ccb_h.ppriv_ptr0 = scan_info;
2266			request_ccb->crcn.flags =
2267			    scan_info->request_ccb->crcn.flags;
2268		} else {
2269			status = xpt_create_path(&path, NULL,
2270						 path_id, target_id, lun_id);
2271			/*
2272			 * Free the old request path- we're done with it. We
2273			 * do this *after* creating the new path so that
2274			 * we don't remove a target that has our lun list
2275			 * in the case that lun 0 is not present.
2276			 */
2277			xpt_free_path(oldpath);
2278			if (status != CAM_REQ_CMP) {
2279				printf("scsi_scan_bus: xpt_create_path failed "
2280				       "with status %#x, halting LUN scan\n",
2281			 	       status);
2282				goto hop_again;
2283			}
2284			xpt_setup_ccb(&request_ccb->ccb_h, path,
2285				      request_ccb->ccb_h.pinfo.priority);
2286			request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
2287			request_ccb->ccb_h.cbfcnp = scsi_scan_bus;
2288			request_ccb->ccb_h.flags |= CAM_UNLOCKED;
2289			request_ccb->ccb_h.ppriv_ptr0 = scan_info;
2290			request_ccb->crcn.flags =
2291				scan_info->request_ccb->crcn.flags;
2292		}
2293		mtx_unlock(mtx);
2294		xpt_action(request_ccb);
2295		break;
2296	}
2297	default:
2298		break;
2299	}
2300}
2301
2302static void
2303scsi_scan_lun(struct cam_periph *periph, struct cam_path *path,
2304	     cam_flags flags, union ccb *request_ccb)
2305{
2306	struct ccb_pathinq cpi;
2307	cam_status status;
2308	struct cam_path *new_path;
2309	struct cam_periph *old_periph;
2310	int lock;
2311
2312	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("scsi_scan_lun\n"));
2313
2314	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NONE);
2315	cpi.ccb_h.func_code = XPT_PATH_INQ;
2316	xpt_action((union ccb *)&cpi);
2317
2318	if (cpi.ccb_h.status != CAM_REQ_CMP) {
2319		if (request_ccb != NULL) {
2320			request_ccb->ccb_h.status = cpi.ccb_h.status;
2321			xpt_done(request_ccb);
2322		}
2323		return;
2324	}
2325
2326	if ((cpi.hba_misc & PIM_NOINITIATOR) != 0) {
2327		/*
2328		 * Can't scan the bus on an adapter that
2329		 * cannot perform the initiator role.
2330		 */
2331		if (request_ccb != NULL) {
2332			request_ccb->ccb_h.status = CAM_REQ_CMP;
2333			xpt_done(request_ccb);
2334		}
2335		return;
2336	}
2337
2338	if (request_ccb == NULL) {
2339		request_ccb = xpt_alloc_ccb_nowait();
2340		if (request_ccb == NULL) {
2341			xpt_print(path, "scsi_scan_lun: can't allocate CCB, "
2342			    "can't continue\n");
2343			return;
2344		}
2345		status = xpt_create_path(&new_path, NULL,
2346					  path->bus->path_id,
2347					  path->target->target_id,
2348					  path->device->lun_id);
2349		if (status != CAM_REQ_CMP) {
2350			xpt_print(path, "scsi_scan_lun: can't create path, "
2351			    "can't continue\n");
2352			xpt_free_ccb(request_ccb);
2353			return;
2354		}
2355		xpt_setup_ccb(&request_ccb->ccb_h, new_path, CAM_PRIORITY_XPT);
2356		request_ccb->ccb_h.cbfcnp = xptscandone;
2357		request_ccb->ccb_h.func_code = XPT_SCAN_LUN;
2358		request_ccb->ccb_h.flags |= CAM_UNLOCKED;
2359		request_ccb->crcn.flags = flags;
2360	}
2361
2362	lock = (xpt_path_owned(path) == 0);
2363	if (lock)
2364		xpt_path_lock(path);
2365	if ((old_periph = cam_periph_find(path, "probe")) != NULL) {
2366		if ((old_periph->flags & CAM_PERIPH_INVALID) == 0) {
2367			probe_softc *softc;
2368
2369			softc = (probe_softc *)old_periph->softc;
2370			TAILQ_INSERT_TAIL(&softc->request_ccbs,
2371			    &request_ccb->ccb_h, periph_links.tqe);
2372		} else {
2373			request_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2374			xpt_done(request_ccb);
2375		}
2376	} else {
2377		status = cam_periph_alloc(proberegister, NULL, probecleanup,
2378					  probestart, "probe",
2379					  CAM_PERIPH_BIO,
2380					  request_ccb->ccb_h.path, NULL, 0,
2381					  request_ccb);
2382
2383		if (status != CAM_REQ_CMP) {
2384			xpt_print(path, "scsi_scan_lun: cam_alloc_periph "
2385			    "returned an error, can't continue probe\n");
2386			request_ccb->ccb_h.status = status;
2387			xpt_done(request_ccb);
2388		}
2389	}
2390	if (lock)
2391		xpt_path_unlock(path);
2392}
2393
2394static void
2395xptscandone(struct cam_periph *periph, union ccb *done_ccb)
2396{
2397
2398	xpt_free_path(done_ccb->ccb_h.path);
2399	xpt_free_ccb(done_ccb);
2400}
2401
2402static struct cam_ed *
2403scsi_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
2404{
2405	struct scsi_quirk_entry *quirk;
2406	struct cam_ed *device;
2407
2408	device = xpt_alloc_device(bus, target, lun_id);
2409	if (device == NULL)
2410		return (NULL);
2411
2412	/*
2413	 * Take the default quirk entry until we have inquiry
2414	 * data and can determine a better quirk to use.
2415	 */
2416	quirk = &scsi_quirk_table[nitems(scsi_quirk_table) - 1];
2417	device->quirk = (void *)quirk;
2418	device->mintags = quirk->mintags;
2419	device->maxtags = quirk->maxtags;
2420	bzero(&device->inq_data, sizeof(device->inq_data));
2421	device->inq_flags = 0;
2422	device->queue_flags = 0;
2423	device->serial_num = NULL;
2424	device->serial_num_len = 0;
2425	device->device_id = NULL;
2426	device->device_id_len = 0;
2427	device->supported_vpds = NULL;
2428	device->supported_vpds_len = 0;
2429	return (device);
2430}
2431
2432static void
2433scsi_devise_transport(struct cam_path *path)
2434{
2435	struct ccb_pathinq cpi;
2436	struct ccb_trans_settings cts;
2437	struct scsi_inquiry_data *inq_buf;
2438
2439	/* Get transport information from the SIM */
2440	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NONE);
2441	cpi.ccb_h.func_code = XPT_PATH_INQ;
2442	xpt_action((union ccb *)&cpi);
2443
2444	inq_buf = NULL;
2445	if ((path->device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0)
2446		inq_buf = &path->device->inq_data;
2447	path->device->protocol = PROTO_SCSI;
2448	path->device->protocol_version =
2449	    inq_buf != NULL ? SID_ANSI_REV(inq_buf) : cpi.protocol_version;
2450	path->device->transport = cpi.transport;
2451	path->device->transport_version = cpi.transport_version;
2452
2453	/*
2454	 * Any device not using SPI3 features should
2455	 * be considered SPI2 or lower.
2456	 */
2457	if (inq_buf != NULL) {
2458		if (path->device->transport == XPORT_SPI
2459		 && (inq_buf->spi3data & SID_SPI_MASK) == 0
2460		 && path->device->transport_version > 2)
2461			path->device->transport_version = 2;
2462	} else {
2463		struct cam_ed* otherdev;
2464
2465		for (otherdev = TAILQ_FIRST(&path->target->ed_entries);
2466		     otherdev != NULL;
2467		     otherdev = TAILQ_NEXT(otherdev, links)) {
2468			if (otherdev != path->device)
2469				break;
2470		}
2471
2472		if (otherdev != NULL) {
2473			/*
2474			 * Initially assume the same versioning as
2475			 * prior luns for this target.
2476			 */
2477			path->device->protocol_version =
2478			    otherdev->protocol_version;
2479			path->device->transport_version =
2480			    otherdev->transport_version;
2481		} else {
2482			/* Until we know better, opt for safety */
2483			path->device->protocol_version = 2;
2484			if (path->device->transport == XPORT_SPI)
2485				path->device->transport_version = 2;
2486			else
2487				path->device->transport_version = 0;
2488		}
2489	}
2490
2491	/*
2492	 * XXX
2493	 * For a device compliant with SPC-2 we should be able
2494	 * to determine the transport version supported by
2495	 * scrutinizing the version descriptors in the
2496	 * inquiry buffer.
2497	 */
2498
2499	/* Tell the controller what we think */
2500	xpt_setup_ccb(&cts.ccb_h, path, CAM_PRIORITY_NONE);
2501	cts.ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
2502	cts.type = CTS_TYPE_CURRENT_SETTINGS;
2503	cts.transport = path->device->transport;
2504	cts.transport_version = path->device->transport_version;
2505	cts.protocol = path->device->protocol;
2506	cts.protocol_version = path->device->protocol_version;
2507	cts.proto_specific.valid = 0;
2508	cts.xport_specific.valid = 0;
2509	xpt_action((union ccb *)&cts);
2510}
2511
2512static void
2513scsi_dev_advinfo(union ccb *start_ccb)
2514{
2515	struct cam_ed *device;
2516	struct ccb_dev_advinfo *cdai;
2517	off_t amt;
2518
2519	xpt_path_assert(start_ccb->ccb_h.path, MA_OWNED);
2520	start_ccb->ccb_h.status = CAM_REQ_INVALID;
2521	device = start_ccb->ccb_h.path->device;
2522	cdai = &start_ccb->cdai;
2523	switch(cdai->buftype) {
2524	case CDAI_TYPE_SCSI_DEVID:
2525		if (cdai->flags & CDAI_FLAG_STORE)
2526			return;
2527		cdai->provsiz = device->device_id_len;
2528		if (device->device_id_len == 0)
2529			break;
2530		amt = device->device_id_len;
2531		if (cdai->provsiz > cdai->bufsiz)
2532			amt = cdai->bufsiz;
2533		memcpy(cdai->buf, device->device_id, amt);
2534		break;
2535	case CDAI_TYPE_SERIAL_NUM:
2536		if (cdai->flags & CDAI_FLAG_STORE)
2537			return;
2538		cdai->provsiz = device->serial_num_len;
2539		if (device->serial_num_len == 0)
2540			break;
2541		amt = device->serial_num_len;
2542		if (cdai->provsiz > cdai->bufsiz)
2543			amt = cdai->bufsiz;
2544		memcpy(cdai->buf, device->serial_num, amt);
2545		break;
2546	case CDAI_TYPE_PHYS_PATH:
2547		if (cdai->flags & CDAI_FLAG_STORE) {
2548			if (device->physpath != NULL) {
2549				free(device->physpath, M_CAMXPT);
2550				device->physpath = NULL;
2551				device->physpath_len = 0;
2552			}
2553			/* Clear existing buffer if zero length */
2554			if (cdai->bufsiz == 0)
2555				break;
2556			device->physpath = malloc(cdai->bufsiz, M_CAMXPT, M_NOWAIT);
2557			if (device->physpath == NULL) {
2558				start_ccb->ccb_h.status = CAM_REQ_ABORTED;
2559				return;
2560			}
2561			device->physpath_len = cdai->bufsiz;
2562			memcpy(device->physpath, cdai->buf, cdai->bufsiz);
2563		} else {
2564			cdai->provsiz = device->physpath_len;
2565			if (device->physpath_len == 0)
2566				break;
2567			amt = device->physpath_len;
2568			if (cdai->provsiz > cdai->bufsiz)
2569				amt = cdai->bufsiz;
2570			memcpy(cdai->buf, device->physpath, amt);
2571		}
2572		break;
2573	case CDAI_TYPE_RCAPLONG:
2574		if (cdai->flags & CDAI_FLAG_STORE) {
2575			if (device->rcap_buf != NULL) {
2576				free(device->rcap_buf, M_CAMXPT);
2577				device->rcap_buf = NULL;
2578			}
2579
2580			device->rcap_len = cdai->bufsiz;
2581			/* Clear existing buffer if zero length */
2582			if (cdai->bufsiz == 0)
2583				break;
2584
2585			device->rcap_buf = malloc(cdai->bufsiz, M_CAMXPT,
2586						  M_NOWAIT);
2587			if (device->rcap_buf == NULL) {
2588				start_ccb->ccb_h.status = CAM_REQ_ABORTED;
2589				return;
2590			}
2591
2592			memcpy(device->rcap_buf, cdai->buf, cdai->bufsiz);
2593		} else {
2594			cdai->provsiz = device->rcap_len;
2595			if (device->rcap_len == 0)
2596				break;
2597			amt = device->rcap_len;
2598			if (cdai->provsiz > cdai->bufsiz)
2599				amt = cdai->bufsiz;
2600			memcpy(cdai->buf, device->rcap_buf, amt);
2601		}
2602		break;
2603	case CDAI_TYPE_EXT_INQ:
2604		/*
2605		 * We fetch extended inquiry data during probe, if
2606		 * available.  We don't allow changing it.
2607		 */
2608		if (cdai->flags & CDAI_FLAG_STORE)
2609			return;
2610		cdai->provsiz = device->ext_inq_len;
2611		if (device->ext_inq_len == 0)
2612			break;
2613		amt = device->ext_inq_len;
2614		if (cdai->provsiz > cdai->bufsiz)
2615			amt = cdai->bufsiz;
2616		memcpy(cdai->buf, device->ext_inq, amt);
2617		break;
2618	default:
2619		return;
2620	}
2621	start_ccb->ccb_h.status = CAM_REQ_CMP;
2622
2623	if (cdai->flags & CDAI_FLAG_STORE) {
2624		xpt_async(AC_ADVINFO_CHANGED, start_ccb->ccb_h.path,
2625			  (void *)(uintptr_t)cdai->buftype);
2626	}
2627}
2628
2629static void
2630scsi_action(union ccb *start_ccb)
2631{
2632
2633	switch (start_ccb->ccb_h.func_code) {
2634	case XPT_SET_TRAN_SETTINGS:
2635	{
2636		scsi_set_transfer_settings(&start_ccb->cts,
2637					   start_ccb->ccb_h.path,
2638					   /*async_update*/FALSE);
2639		break;
2640	}
2641	case XPT_SCAN_BUS:
2642	case XPT_SCAN_TGT:
2643		scsi_scan_bus(start_ccb->ccb_h.path->periph, start_ccb);
2644		break;
2645	case XPT_SCAN_LUN:
2646		scsi_scan_lun(start_ccb->ccb_h.path->periph,
2647			      start_ccb->ccb_h.path, start_ccb->crcn.flags,
2648			      start_ccb);
2649		break;
2650	case XPT_DEV_ADVINFO:
2651	{
2652		scsi_dev_advinfo(start_ccb);
2653		break;
2654	}
2655	default:
2656		xpt_action_default(start_ccb);
2657		break;
2658	}
2659}
2660
2661static void
2662scsi_set_transfer_settings(struct ccb_trans_settings *cts, struct cam_path *path,
2663			   int async_update)
2664{
2665	struct	ccb_pathinq cpi;
2666	struct	ccb_trans_settings cur_cts;
2667	struct	ccb_trans_settings_scsi *scsi;
2668	struct	ccb_trans_settings_scsi *cur_scsi;
2669	struct	scsi_inquiry_data *inq_data;
2670	struct	cam_ed *device;
2671
2672	if (path == NULL || (device = path->device) == NULL) {
2673		cts->ccb_h.status = CAM_PATH_INVALID;
2674		xpt_done((union ccb *)cts);
2675		return;
2676	}
2677
2678	if (cts->protocol == PROTO_UNKNOWN
2679	 || cts->protocol == PROTO_UNSPECIFIED) {
2680		cts->protocol = device->protocol;
2681		cts->protocol_version = device->protocol_version;
2682	}
2683
2684	if (cts->protocol_version == PROTO_VERSION_UNKNOWN
2685	 || cts->protocol_version == PROTO_VERSION_UNSPECIFIED)
2686		cts->protocol_version = device->protocol_version;
2687
2688	if (cts->protocol != device->protocol) {
2689		xpt_print(path, "Uninitialized Protocol %x:%x?\n",
2690		       cts->protocol, device->protocol);
2691		cts->protocol = device->protocol;
2692	}
2693
2694	if (cts->protocol_version > device->protocol_version) {
2695		if (bootverbose) {
2696			xpt_print(path, "Down reving Protocol "
2697			    "Version from %d to %d?\n", cts->protocol_version,
2698			    device->protocol_version);
2699		}
2700		cts->protocol_version = device->protocol_version;
2701	}
2702
2703	if (cts->transport == XPORT_UNKNOWN
2704	 || cts->transport == XPORT_UNSPECIFIED) {
2705		cts->transport = device->transport;
2706		cts->transport_version = device->transport_version;
2707	}
2708
2709	if (cts->transport_version == XPORT_VERSION_UNKNOWN
2710	 || cts->transport_version == XPORT_VERSION_UNSPECIFIED)
2711		cts->transport_version = device->transport_version;
2712
2713	if (cts->transport != device->transport) {
2714		xpt_print(path, "Uninitialized Transport %x:%x?\n",
2715		    cts->transport, device->transport);
2716		cts->transport = device->transport;
2717	}
2718
2719	if (cts->transport_version > device->transport_version) {
2720		if (bootverbose) {
2721			xpt_print(path, "Down reving Transport "
2722			    "Version from %d to %d?\n", cts->transport_version,
2723			    device->transport_version);
2724		}
2725		cts->transport_version = device->transport_version;
2726	}
2727
2728	/*
2729	 * Nothing more of interest to do unless
2730	 * this is a device connected via the
2731	 * SCSI protocol.
2732	 */
2733	if (cts->protocol != PROTO_SCSI) {
2734		if (async_update == FALSE)
2735			xpt_action_default((union ccb *)cts);
2736		return;
2737	}
2738
2739	inq_data = &device->inq_data;
2740	scsi = &cts->proto_specific.scsi;
2741	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NONE);
2742	cpi.ccb_h.func_code = XPT_PATH_INQ;
2743	xpt_action((union ccb *)&cpi);
2744
2745	/* SCSI specific sanity checking */
2746	if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0
2747	 || (INQ_DATA_TQ_ENABLED(inq_data)) == 0
2748	 || (device->queue_flags & SCP_QUEUE_DQUE) != 0
2749	 || (device->mintags == 0)) {
2750		/*
2751		 * Can't tag on hardware that doesn't support tags,
2752		 * doesn't have it enabled, or has broken tag support.
2753		 */
2754		scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
2755	}
2756
2757	if (async_update == FALSE) {
2758		/*
2759		 * Perform sanity checking against what the
2760		 * controller and device can do.
2761		 */
2762		xpt_setup_ccb(&cur_cts.ccb_h, path, CAM_PRIORITY_NONE);
2763		cur_cts.ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
2764		cur_cts.type = cts->type;
2765		xpt_action((union ccb *)&cur_cts);
2766		if (cam_ccb_status((union ccb *)&cur_cts) != CAM_REQ_CMP) {
2767			return;
2768		}
2769		cur_scsi = &cur_cts.proto_specific.scsi;
2770		if ((scsi->valid & CTS_SCSI_VALID_TQ) == 0) {
2771			scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
2772			scsi->flags |= cur_scsi->flags & CTS_SCSI_FLAGS_TAG_ENB;
2773		}
2774		if ((cur_scsi->valid & CTS_SCSI_VALID_TQ) == 0)
2775			scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
2776	}
2777
2778	/* SPI specific sanity checking */
2779	if (cts->transport == XPORT_SPI && async_update == FALSE) {
2780		u_int spi3caps;
2781		struct ccb_trans_settings_spi *spi;
2782		struct ccb_trans_settings_spi *cur_spi;
2783
2784		spi = &cts->xport_specific.spi;
2785
2786		cur_spi = &cur_cts.xport_specific.spi;
2787
2788		/* Fill in any gaps in what the user gave us */
2789		if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
2790			spi->sync_period = cur_spi->sync_period;
2791		if ((cur_spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0)
2792			spi->sync_period = 0;
2793		if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
2794			spi->sync_offset = cur_spi->sync_offset;
2795		if ((cur_spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0)
2796			spi->sync_offset = 0;
2797		if ((spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
2798			spi->ppr_options = cur_spi->ppr_options;
2799		if ((cur_spi->valid & CTS_SPI_VALID_PPR_OPTIONS) == 0)
2800			spi->ppr_options = 0;
2801		if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
2802			spi->bus_width = cur_spi->bus_width;
2803		if ((cur_spi->valid & CTS_SPI_VALID_BUS_WIDTH) == 0)
2804			spi->bus_width = 0;
2805		if ((spi->valid & CTS_SPI_VALID_DISC) == 0) {
2806			spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
2807			spi->flags |= cur_spi->flags & CTS_SPI_FLAGS_DISC_ENB;
2808		}
2809		if ((cur_spi->valid & CTS_SPI_VALID_DISC) == 0)
2810			spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
2811		if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
2812		  && (inq_data->flags & SID_Sync) == 0
2813		  && cts->type == CTS_TYPE_CURRENT_SETTINGS)
2814		 || ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0)) {
2815			/* Force async */
2816			spi->sync_period = 0;
2817			spi->sync_offset = 0;
2818		}
2819
2820		switch (spi->bus_width) {
2821		case MSG_EXT_WDTR_BUS_32_BIT:
2822			if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
2823			  || (inq_data->flags & SID_WBus32) != 0
2824			  || cts->type == CTS_TYPE_USER_SETTINGS)
2825			 && (cpi.hba_inquiry & PI_WIDE_32) != 0)
2826				break;
2827			/* Fall Through to 16-bit */
2828		case MSG_EXT_WDTR_BUS_16_BIT:
2829			if (((device->flags & CAM_DEV_INQUIRY_DATA_VALID) == 0
2830			  || (inq_data->flags & SID_WBus16) != 0
2831			  || cts->type == CTS_TYPE_USER_SETTINGS)
2832			 && (cpi.hba_inquiry & PI_WIDE_16) != 0) {
2833				spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
2834				break;
2835			}
2836			/* Fall Through to 8-bit */
2837		default: /* New bus width?? */
2838		case MSG_EXT_WDTR_BUS_8_BIT:
2839			/* All targets can do this */
2840			spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
2841			break;
2842		}
2843
2844		spi3caps = cpi.xport_specific.spi.ppr_options;
2845		if ((device->flags & CAM_DEV_INQUIRY_DATA_VALID) != 0
2846		 && cts->type == CTS_TYPE_CURRENT_SETTINGS)
2847			spi3caps &= inq_data->spi3data;
2848
2849		if ((spi3caps & SID_SPI_CLOCK_DT) == 0)
2850			spi->ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2851
2852		if ((spi3caps & SID_SPI_IUS) == 0)
2853			spi->ppr_options &= ~MSG_EXT_PPR_IU_REQ;
2854
2855		if ((spi3caps & SID_SPI_QAS) == 0)
2856			spi->ppr_options &= ~MSG_EXT_PPR_QAS_REQ;
2857
2858		/* No SPI Transfer settings are allowed unless we are wide */
2859		if (spi->bus_width == 0)
2860			spi->ppr_options = 0;
2861
2862		if ((spi->valid & CTS_SPI_VALID_DISC)
2863		 && ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) == 0)) {
2864			/*
2865			 * Can't tag queue without disconnection.
2866			 */
2867			scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
2868			scsi->valid |= CTS_SCSI_VALID_TQ;
2869		}
2870
2871		/*
2872		 * If we are currently performing tagged transactions to
2873		 * this device and want to change its negotiation parameters,
2874		 * go non-tagged for a bit to give the controller a chance to
2875		 * negotiate unhampered by tag messages.
2876		 */
2877		if (cts->type == CTS_TYPE_CURRENT_SETTINGS
2878		 && (device->inq_flags & SID_CmdQue) != 0
2879		 && (scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
2880		 && (spi->flags & (CTS_SPI_VALID_SYNC_RATE|
2881				   CTS_SPI_VALID_SYNC_OFFSET|
2882				   CTS_SPI_VALID_BUS_WIDTH)) != 0)
2883			scsi_toggle_tags(path);
2884	}
2885
2886	if (cts->type == CTS_TYPE_CURRENT_SETTINGS
2887	 && (scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
2888		int device_tagenb;
2889
2890		/*
2891		 * If we are transitioning from tags to no-tags or
2892		 * vice-versa, we need to carefully freeze and restart
2893		 * the queue so that we don't overlap tagged and non-tagged
2894		 * commands.  We also temporarily stop tags if there is
2895		 * a change in transfer negotiation settings to allow
2896		 * "tag-less" negotiation.
2897		 */
2898		if ((device->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
2899		 || (device->inq_flags & SID_CmdQue) != 0)
2900			device_tagenb = TRUE;
2901		else
2902			device_tagenb = FALSE;
2903
2904		if (((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0
2905		  && device_tagenb == FALSE)
2906		 || ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) == 0
2907		  && device_tagenb == TRUE)) {
2908
2909			if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0) {
2910				/*
2911				 * Delay change to use tags until after a
2912				 * few commands have gone to this device so
2913				 * the controller has time to perform transfer
2914				 * negotiations without tagged messages getting
2915				 * in the way.
2916				 */
2917				device->tag_delay_count = CAM_TAG_DELAY_COUNT;
2918				device->flags |= CAM_DEV_TAG_AFTER_COUNT;
2919			} else {
2920				xpt_stop_tags(path);
2921			}
2922		}
2923	}
2924	if (async_update == FALSE)
2925		xpt_action_default((union ccb *)cts);
2926}
2927
2928static void
2929scsi_toggle_tags(struct cam_path *path)
2930{
2931	struct cam_ed *dev;
2932
2933	/*
2934	 * Give controllers a chance to renegotiate
2935	 * before starting tag operations.  We
2936	 * "toggle" tagged queuing off then on
2937	 * which causes the tag enable command delay
2938	 * counter to come into effect.
2939	 */
2940	dev = path->device;
2941	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
2942	 || ((dev->inq_flags & SID_CmdQue) != 0
2943 	  && (dev->inq_flags & (SID_Sync|SID_WBus16|SID_WBus32)) != 0)) {
2944		struct ccb_trans_settings cts;
2945
2946		xpt_setup_ccb(&cts.ccb_h, path, CAM_PRIORITY_NONE);
2947		cts.protocol = PROTO_SCSI;
2948		cts.protocol_version = PROTO_VERSION_UNSPECIFIED;
2949		cts.transport = XPORT_UNSPECIFIED;
2950		cts.transport_version = XPORT_VERSION_UNSPECIFIED;
2951		cts.proto_specific.scsi.flags = 0;
2952		cts.proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
2953		scsi_set_transfer_settings(&cts, path,
2954					  /*async_update*/TRUE);
2955		cts.proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
2956		scsi_set_transfer_settings(&cts, path,
2957					  /*async_update*/TRUE);
2958	}
2959}
2960
2961/*
2962 * Handle any per-device event notifications that require action by the XPT.
2963 */
2964static void
2965scsi_dev_async(u_int32_t async_code, struct cam_eb *bus, struct cam_et *target,
2966	      struct cam_ed *device, void *async_arg)
2967{
2968	cam_status status;
2969	struct cam_path newpath;
2970
2971	/*
2972	 * We only need to handle events for real devices.
2973	 */
2974	if (target->target_id == CAM_TARGET_WILDCARD
2975	 || device->lun_id == CAM_LUN_WILDCARD)
2976		return;
2977
2978	/*
2979	 * We need our own path with wildcards expanded to
2980	 * handle certain types of events.
2981	 */
2982	if ((async_code == AC_SENT_BDR)
2983	 || (async_code == AC_BUS_RESET)
2984	 || (async_code == AC_INQ_CHANGED))
2985		status = xpt_compile_path(&newpath, NULL,
2986					  bus->path_id,
2987					  target->target_id,
2988					  device->lun_id);
2989	else
2990		status = CAM_REQ_CMP_ERR;
2991
2992	if (status == CAM_REQ_CMP) {
2993
2994		/*
2995		 * Allow transfer negotiation to occur in a
2996		 * tag free environment and after settle delay.
2997		 */
2998		if (async_code == AC_SENT_BDR
2999		 || async_code == AC_BUS_RESET) {
3000			cam_freeze_devq(&newpath);
3001			cam_release_devq(&newpath,
3002				RELSIM_RELEASE_AFTER_TIMEOUT,
3003				/*reduction*/0,
3004				/*timeout*/scsi_delay,
3005				/*getcount_only*/0);
3006			scsi_toggle_tags(&newpath);
3007		}
3008
3009		if (async_code == AC_INQ_CHANGED) {
3010			/*
3011			 * We've sent a start unit command, or
3012			 * something similar to a device that
3013			 * may have caused its inquiry data to
3014			 * change. So we re-scan the device to
3015			 * refresh the inquiry data for it.
3016			 */
3017			scsi_scan_lun(newpath.periph, &newpath,
3018				     CAM_EXPECT_INQ_CHANGE, NULL);
3019		}
3020		xpt_release_path(&newpath);
3021	} else if (async_code == AC_LOST_DEVICE &&
3022	    (device->flags & CAM_DEV_UNCONFIGURED) == 0) {
3023		device->flags |= CAM_DEV_UNCONFIGURED;
3024		xpt_release_device(device);
3025	} else if (async_code == AC_TRANSFER_NEG) {
3026		struct ccb_trans_settings *settings;
3027		struct cam_path path;
3028
3029		settings = (struct ccb_trans_settings *)async_arg;
3030		xpt_compile_path(&path, NULL, bus->path_id, target->target_id,
3031				 device->lun_id);
3032		scsi_set_transfer_settings(settings, &path,
3033					  /*async_update*/TRUE);
3034		xpt_release_path(&path);
3035	}
3036}
3037
3038static void
3039_scsi_announce_periph(struct cam_periph *periph, u_int *speed, u_int *freq, struct ccb_trans_settings *cts)
3040{
3041	struct	ccb_pathinq cpi;
3042	struct	cam_path *path = periph->path;
3043
3044	cam_periph_assert(periph, MA_OWNED);
3045
3046	xpt_setup_ccb(&cts->ccb_h, path, CAM_PRIORITY_NORMAL);
3047	cts->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
3048	cts->type = CTS_TYPE_CURRENT_SETTINGS;
3049	xpt_action((union ccb*)cts);
3050	if (cam_ccb_status((union ccb *)cts) != CAM_REQ_CMP)
3051		return;
3052
3053	/* Ask the SIM for its base transfer speed */
3054	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NORMAL);
3055	cpi.ccb_h.func_code = XPT_PATH_INQ;
3056	xpt_action((union ccb *)&cpi);
3057
3058	/* Report connection speed */
3059	*speed = cpi.base_transfer_speed;
3060	*freq = 0;
3061
3062	if (cts->ccb_h.status == CAM_REQ_CMP && cts->transport == XPORT_SPI) {
3063		struct	ccb_trans_settings_spi *spi =
3064		    &cts->xport_specific.spi;
3065
3066		if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0
3067		  && spi->sync_offset != 0) {
3068			*freq = scsi_calc_syncsrate(spi->sync_period);
3069			*speed = *freq;
3070		}
3071		if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
3072			*speed *= (0x01 << spi->bus_width);
3073	}
3074	if (cts->ccb_h.status == CAM_REQ_CMP && cts->transport == XPORT_FC) {
3075		struct	ccb_trans_settings_fc *fc =
3076		    &cts->xport_specific.fc;
3077
3078		if (fc->valid & CTS_FC_VALID_SPEED)
3079			*speed = fc->bitrate;
3080	}
3081	if (cts->ccb_h.status == CAM_REQ_CMP && cts->transport == XPORT_SAS) {
3082		struct	ccb_trans_settings_sas *sas =
3083		    &cts->xport_specific.sas;
3084
3085		if (sas->valid & CTS_SAS_VALID_SPEED)
3086			*speed = sas->bitrate;
3087	}
3088}
3089
3090static void
3091scsi_announce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb)
3092{
3093	struct	ccb_trans_settings cts;
3094	u_int speed, freq, mb;
3095
3096	_scsi_announce_periph(periph, &speed, &freq, &cts);
3097	if (cam_ccb_status((union ccb *)&cts) != CAM_REQ_CMP)
3098		return;
3099
3100	mb = speed / 1000;
3101	if (mb > 0)
3102		sbuf_printf(sb, "%s%d: %d.%03dMB/s transfers",
3103		       periph->periph_name, periph->unit_number,
3104		       mb, speed % 1000);
3105	else
3106		sbuf_printf(sb, "%s%d: %dKB/s transfers", periph->periph_name,
3107		       periph->unit_number, speed);
3108	/* Report additional information about SPI connections */
3109	if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SPI) {
3110		struct	ccb_trans_settings_spi *spi;
3111
3112		spi = &cts.xport_specific.spi;
3113		if (freq != 0) {
3114			sbuf_printf(sb, " (%d.%03dMHz%s, offset %d", freq / 1000,
3115			       freq % 1000,
3116			       (spi->ppr_options & MSG_EXT_PPR_DT_REQ) != 0
3117			     ? " DT" : "",
3118			       spi->sync_offset);
3119		}
3120		if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0
3121		 && spi->bus_width > 0) {
3122			if (freq != 0) {
3123				sbuf_printf(sb, ", ");
3124			} else {
3125				sbuf_printf(sb, " (");
3126			}
3127			sbuf_printf(sb, "%dbit)", 8 * (0x01 << spi->bus_width));
3128		} else if (freq != 0) {
3129			sbuf_printf(sb, ")");
3130		}
3131	}
3132	if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_FC) {
3133		struct	ccb_trans_settings_fc *fc;
3134
3135		fc = &cts.xport_specific.fc;
3136		if (fc->valid & CTS_FC_VALID_WWNN)
3137			sbuf_printf(sb, " WWNN 0x%llx", (long long) fc->wwnn);
3138		if (fc->valid & CTS_FC_VALID_WWPN)
3139			sbuf_printf(sb, " WWPN 0x%llx", (long long) fc->wwpn);
3140		if (fc->valid & CTS_FC_VALID_PORT)
3141			sbuf_printf(sb, " PortID 0x%x", fc->port);
3142	}
3143	sbuf_printf(sb, "\n");
3144}
3145
3146static void
3147scsi_announce_periph(struct cam_periph *periph)
3148{
3149	struct	ccb_trans_settings cts;
3150	u_int speed, freq, mb;
3151
3152	_scsi_announce_periph(periph, &speed, &freq, &cts);
3153	if (cam_ccb_status((union ccb *)&cts) != CAM_REQ_CMP)
3154		return;
3155
3156	mb = speed / 1000;
3157	if (mb > 0)
3158		printf("%s%d: %d.%03dMB/s transfers",
3159		       periph->periph_name, periph->unit_number,
3160		       mb, speed % 1000);
3161	else
3162		printf("%s%d: %dKB/s transfers", periph->periph_name,
3163		       periph->unit_number, speed);
3164	/* Report additional information about SPI connections */
3165	if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_SPI) {
3166		struct	ccb_trans_settings_spi *spi;
3167
3168		spi = &cts.xport_specific.spi;
3169		if (freq != 0) {
3170			printf(" (%d.%03dMHz%s, offset %d", freq / 1000,
3171			       freq % 1000,
3172			       (spi->ppr_options & MSG_EXT_PPR_DT_REQ) != 0
3173			     ? " DT" : "",
3174			       spi->sync_offset);
3175		}
3176		if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0
3177		 && spi->bus_width > 0) {
3178			if (freq != 0) {
3179				printf(", ");
3180			} else {
3181				printf(" (");
3182			}
3183			printf("%dbit)", 8 * (0x01 << spi->bus_width));
3184		} else if (freq != 0) {
3185			printf(")");
3186		}
3187	}
3188	if (cts.ccb_h.status == CAM_REQ_CMP && cts.transport == XPORT_FC) {
3189		struct	ccb_trans_settings_fc *fc;
3190
3191		fc = &cts.xport_specific.fc;
3192		if (fc->valid & CTS_FC_VALID_WWNN)
3193			printf(" WWNN 0x%llx", (long long) fc->wwnn);
3194		if (fc->valid & CTS_FC_VALID_WWPN)
3195			printf(" WWPN 0x%llx", (long long) fc->wwpn);
3196		if (fc->valid & CTS_FC_VALID_PORT)
3197			printf(" PortID 0x%x", fc->port);
3198	}
3199	printf("\n");
3200}
3201
3202static void
3203scsi_proto_announce_sbuf(struct cam_ed *device, struct sbuf *sb)
3204{
3205	scsi_print_inquiry_sbuf(sb, &device->inq_data);
3206}
3207
3208static void
3209scsi_proto_announce(struct cam_ed *device)
3210{
3211	scsi_print_inquiry(&device->inq_data);
3212}
3213
3214static void
3215scsi_proto_denounce_sbuf(struct cam_ed *device, struct sbuf *sb)
3216{
3217	scsi_print_inquiry_short_sbuf(sb, &device->inq_data);
3218}
3219
3220static void
3221scsi_proto_denounce(struct cam_ed *device)
3222{
3223	scsi_print_inquiry_short(&device->inq_data);
3224}
3225
3226static void
3227scsi_proto_debug_out(union ccb *ccb)
3228{
3229	char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
3230	struct cam_ed *device;
3231
3232	if (ccb->ccb_h.func_code != XPT_SCSI_IO)
3233		return;
3234
3235	device = ccb->ccb_h.path->device;
3236	CAM_DEBUG(ccb->ccb_h.path,
3237	    CAM_DEBUG_CDB,("%s. CDB: %s\n",
3238		scsi_op_desc(scsiio_cdb_ptr(&ccb->csio)[0], &device->inq_data),
3239		scsi_cdb_string(scsiio_cdb_ptr(&ccb->csio), cdb_str, sizeof(cdb_str))));
3240}
3241