xref: /illumos-gate/usr/src/lib/fm/topo/modules/common/ses/ses.c (revision 8808ac5dae118369991f158b6ab736cb2691ecde)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2012 Milan Jurik. All rights reserved.
25  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
26  * Copyright 2015 Joyent, Inc.
27  */
28 
29 #include <alloca.h>
30 #include <dirent.h>
31 #include <devid.h>
32 #include <fm/libdiskstatus.h>
33 #include <inttypes.h>
34 #include <pthread.h>
35 #include <strings.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <sys/dkio.h>
39 #include <sys/fm/protocol.h>
40 #include <sys/libdevid.h>
41 #include <sys/scsi/scsi_types.h>
42 #include <sys/byteorder.h>
43 #include <pthread.h>
44 #include <signal.h>
45 #include <fcntl.h>
46 #include <sys/ctfs.h>
47 #include <libcontract.h>
48 #include <poll.h>
49 #include <sys/contract/device.h>
50 #include <libsysevent.h>
51 #include <sys/sysevent/eventdefs.h>
52 #include <scsi/plugins/ses/vendor/sun.h>
53 
54 #include "disk.h"
55 #include "ses.h"
56 
57 #define	SES_VERSION	1
58 
59 #define	SES_STARTING_SUBCHASSIS 256	/* valid subchassis IDs are uint8_t */
60 #define	NO_SUBCHASSIS	((uint64_t)-1)
61 
62 static int ses_snap_freq = 250;		/* in milliseconds */
63 
64 #define	SES_STATUS_UNAVAIL(s)	\
65 	((s) == SES_ESC_UNSUPPORTED || (s) >= SES_ESC_NOT_INSTALLED)
66 
67 #define	HR_SECOND   1000000000
68 
69 /*
70  * Because multiple SES targets can be part of a single chassis, we construct
71  * our own hierarchy that takes this into account.  These SES targets may refer
72  * to the same devices (multiple paths) or to different devices (managing
73  * different portions of the space).  We arrange things into a
74  * ses_enum_enclosure_t, which contains a set of ses targets, and a list of all
75  * nodes found so far.
76  */
77 typedef struct ses_alt_node {
78 	topo_list_t		san_link;
79 	ses_node_t		*san_node;
80 } ses_alt_node_t;
81 
82 typedef struct ses_enum_node {
83 	topo_list_t		sen_link;
84 	ses_node_t		*sen_node;
85 	topo_list_t		sen_alt_nodes;
86 	uint64_t		sen_type;
87 	uint64_t		sen_instance;
88 	ses_enum_target_t	*sen_target;
89 } ses_enum_node_t;
90 
91 typedef struct ses_enum_chassis {
92 	topo_list_t		sec_link;
93 	topo_list_t		sec_subchassis;
94 	topo_list_t		sec_nodes;
95 	topo_list_t		sec_targets;
96 	const char		*sec_csn;
97 	ses_node_t		*sec_enclosure;
98 	ses_enum_target_t	*sec_target;
99 	topo_instance_t		sec_instance;
100 	topo_instance_t		sec_scinstance;
101 	topo_instance_t		sec_maxinstance;
102 	boolean_t		sec_hasdev;
103 	boolean_t		sec_internal;
104 } ses_enum_chassis_t;
105 
106 typedef struct ses_enum_data {
107 	topo_list_t		sed_devs;
108 	topo_list_t		sed_chassis;
109 	ses_enum_chassis_t	*sed_current;
110 	ses_enum_target_t	*sed_target;
111 	int			sed_errno;
112 	char			*sed_name;
113 	topo_mod_t		*sed_mod;
114 	topo_instance_t		sed_instance;
115 } ses_enum_data_t;
116 
117 typedef struct sas_connector_phy_data {
118 	uint64_t    scpd_index;
119 	uint64_t    scpd_pm;
120 } sas_connector_phy_data_t;
121 
122 typedef struct sas_connector_type {
123 	uint64_t    sct_type;
124 	char	    *sct_name;
125 } sas_connector_type_t;
126 
127 static const sas_connector_type_t sas_connector_type_list[] = {
128 	{   0x0, "Information unknown"  },
129 	{   0x1, "External SAS 4x receptacle (see SAS-2 and SFF-8470)"	},
130 	{   0x2, "Exteranl Mini SAS 4x receptacle (see SAS-2 and SFF-8088)" },
131 	{   0x3, "QSFP+ receptacle (see SAS-2.1 and SFF-8436)" },
132 	{   0x4, "Mini SAS 4x active receptacle (see SAS-2.1 and SFF-8088)" },
133 	{   0x5, "Mini SAS HD 4x receptacle (see SAS-2.1 and SFF-8644)" },
134 	{   0x6, "Mini SAS HD 8x receptacle (see SAS-2.1 and SFF-8644)" },
135 	{   0x7, "Mini SAS HD 16x receptacle (see SAS-2.1 and SFF-8644)" },
136 	{   0xF, "Vendor-specific external connector"	},
137 	{   0x10, "Internal wide SAS 4i plug (see SAS-2 and SFF-8484)"	},
138 	{   0x11,
139 	"Internal wide Mini SAS 4i receptacle (see SAS-2 and SFF-8087)"	},
140 	{   0x12, "Mini SAS HD 4i receptacle (see SAS-2.1 and SFF-8643)" },
141 	{   0x20, "Internal SAS Drive receptacle (see SAS-2 and SFF-8482)" },
142 	{   0x21, "Internal SATA host plug (see SAS-2 and SATA-2)"	},
143 	{   0x22, "Internal SAS Drive plug (see SAS-2 and SFF-8482)"	},
144 	{   0x23, "Internal SATA device plug (see SAS-2 and SATA-2)"	},
145 	{   0x24, "Micro SAS receptacle (see SAS-2.14)"	},
146 	{   0x25, "Micro SATA device plug (see SAS-2.1 and SATA)"	},
147 	{   0x26, "Micro SAS plug (see SAS-2.1 and SFF-8486)"	},
148 	{   0x27, "Micro SAS/SATA plug (see SAS-2.1 and SFF-8486)"	},
149 	{   0x28,
150 	"12 Gb/s SAS Drive backplane receptacle (see SAS-34 and SFF-8680)" },
151 	{   0x29, "12Gb/s SAS Drive Plug (see SAS-3 and SFF-8680)"	},
152 	{   0x2A, "Multifunction 12 Gb/s 6x Unshielded receptacle connector "
153 		"receptacle (see SAS-3 and SFF-8639)"	},
154 	{   0x2B, "Multifunction 12 Gb/s 6x Unshielded receptable connector "
155 		"plug (see SAS-3 and SFF-8639)"	},
156 	{   0x2F, "Internal SAS virtual connector"  },
157 	{   0x3F, "Vendor-specific internal connector"	},
158 	{   0x70, "Other Vendor-specific connector"	},
159 	{   0x71, "Other Vendor-specific connector"	},
160 	{   0x72, "Other Vendor-specific connector"	},
161 	{   0x73, "Other Vendor-specific connector"	},
162 	{   0x74, "Other Vendor-specific connector"	},
163 	{   0x75, "Other Vendor-specific connector"	},
164 	{   0x76, "Other Vendor-specific connector"	},
165 	{   0x77, "Other Vendor-specific connector"	},
166 	{   0x78, "Other Vendor-specific connector"	},
167 	{   0x79, "Other Vendor-specific connector"	},
168 	{   0x7A, "Other Vendor-specific connector"	},
169 	{   0x7B, "Other Vendor-specific connector"	},
170 	{   0x7C, "Other Vendor-specific connector"	},
171 	{   0x7D, "Other Vendor-specific connector"	},
172 	{   0x7E, "Other Vendor-specific connector"	},
173 	{   0x7F, "Other Vendor-specific connector"	},
174 	{   0x80, "Not Defined"	}
175 };
176 
177 #define	SAS_CONNECTOR_TYPE_CODE_NOT_DEFINED  0x80
178 #define	SAS_CONNECTOR_TYPE_NOT_DEFINED \
179 	"Connector type not defined by SES-2 standard"
180 #define	SAS_CONNECTOR_TYPE_RESERVED \
181 	"Connector type reserved by SES-2 standard"
182 
183 typedef struct phys_enum_type {
184 	uint64_t    pet_type;
185 	char	    *pet_nodename;
186 	char	    *pet_defaultlabel;
187 	boolean_t   pet_dorange;
188 } phys_enum_type_t;
189 
190 static const phys_enum_type_t phys_enum_type_list[] = {
191 	{   SES_ET_ARRAY_DEVICE, BAY, "BAY", B_TRUE  },
192 	{   SES_ET_COOLING, FAN, "FAN", B_TRUE  },
193 	{   SES_ET_DEVICE, BAY, "BAY", B_TRUE  },
194 	{   SES_ET_ESC_ELECTRONICS, CONTROLLER, "CONTROLLER", B_TRUE  },
195 	{   SES_ET_POWER_SUPPLY, PSU, "PSU", B_TRUE  },
196 	{   SES_ET_SUNW_FANBOARD, FANBOARD, "FANBOARD", B_TRUE  },
197 	{   SES_ET_SUNW_FANMODULE, FANMODULE, "FANMODULE", B_TRUE  },
198 	{   SES_ET_SUNW_POWERBOARD, POWERBOARD, "POWERBOARD", B_TRUE  },
199 	{   SES_ET_SUNW_POWERMODULE, POWERMODULE, "POWERMODULE", B_TRUE  }
200 };
201 
202 #define	N_PHYS_ENUM_TYPES (sizeof (phys_enum_type_list) / \
203 	sizeof (phys_enum_type_list[0]))
204 
205 /*
206  * Structure for the hierarchical tree for element nodes.
207  */
208 typedef struct ses_phys_tree {
209     ses_node_t	*spt_snode;
210     ses_enum_node_t	*spt_senumnode;
211     boolean_t	spt_isfru;
212     uint64_t	spt_eonlyindex;
213     uint64_t	spt_cindex;
214     uint64_t	spt_pindex;
215     uint64_t	spt_maxinst;
216     struct ses_phys_tree    *spt_parent;
217     struct ses_phys_tree    *spt_child;
218     struct ses_phys_tree    *spt_sibling;
219     tnode_t	*spt_tnode;
220 } ses_phys_tree_t;
221 
222 typedef enum {
223 	SES_NEW_CHASSIS		= 0x1,
224 	SES_NEW_SUBCHASSIS	= 0x2,
225 	SES_DUP_CHASSIS		= 0x4,
226 	SES_DUP_SUBCHASSIS	= 0x8
227 } ses_chassis_type_e;
228 
229 
230 static const topo_pgroup_info_t storage_pgroup = {
231 	TOPO_PGROUP_STORAGE,
232 	TOPO_STABILITY_PRIVATE,
233 	TOPO_STABILITY_PRIVATE,
234 	1
235 };
236 
237 static const topo_pgroup_info_t smp_pgroup = {
238 	TOPO_PGROUP_SMP,
239 	TOPO_STABILITY_PRIVATE,
240 	TOPO_STABILITY_PRIVATE,
241 	1
242 };
243 
244 static const topo_pgroup_info_t ses_pgroup = {
245 	TOPO_PGROUP_SES,
246 	TOPO_STABILITY_PRIVATE,
247 	TOPO_STABILITY_PRIVATE,
248 	1
249 };
250 
251 static int ses_present(topo_mod_t *, tnode_t *, topo_version_t, nvlist_t *,
252     nvlist_t **);
253 static int ses_contains(topo_mod_t *, tnode_t *, topo_version_t, nvlist_t *,
254     nvlist_t **);
255 
256 static const topo_method_t ses_component_methods[] = {
257 	{ TOPO_METH_PRESENT, TOPO_METH_PRESENT_DESC,
258 	    TOPO_METH_PRESENT_VERSION0, TOPO_STABILITY_INTERNAL, ses_present },
259 	{ TOPO_METH_FAC_ENUM, TOPO_METH_FAC_ENUM_DESC, 0,
260 	    TOPO_STABILITY_INTERNAL, ses_node_enum_facility },
261 	{ TOPO_METH_SENSOR_FAILURE, TOPO_METH_SENSOR_FAILURE_DESC,
262 	    TOPO_METH_SENSOR_FAILURE_VERSION, TOPO_STABILITY_INTERNAL,
263 	    topo_method_sensor_failure },
264 	{ NULL }
265 };
266 
267 static const topo_method_t ses_bay_methods[] = {
268 	{ TOPO_METH_FAC_ENUM, TOPO_METH_FAC_ENUM_DESC, 0,
269 	    TOPO_STABILITY_INTERNAL, ses_node_enum_facility },
270 	{ NULL }
271 };
272 
273 static const topo_method_t ses_enclosure_methods[] = {
274 	{ TOPO_METH_CONTAINS, TOPO_METH_CONTAINS_DESC,
275 	    TOPO_METH_CONTAINS_VERSION, TOPO_STABILITY_INTERNAL, ses_contains },
276 	{ TOPO_METH_FAC_ENUM, TOPO_METH_FAC_ENUM_DESC, 0,
277 	    TOPO_STABILITY_INTERNAL, ses_enc_enum_facility },
278 	{ NULL }
279 };
280 
281 /*
282  * Functions for tracking ses devices which we were unable to open. We retry
283  * these at regular intervals using ses_recheck_dir() and if we find that we
284  * can now open any of them then we send a sysevent to indicate that a new topo
285  * snapshot should be taken.
286  */
287 typedef struct ses_open_fail_list {
288 	struct ses_open_fail_list	*sof_next;
289 	char				*sof_path;
290 } ses_open_fail_list_t;
291 
292 static ses_open_fail_list_t *ses_sofh;
293 static pthread_mutex_t ses_sofmt;
294 static void ses_ct_print(char *ptr);
295 
296 static void
297 ses_recheck_dir()
298 {
299 	ses_target_t *target;
300 	sysevent_id_t eid;
301 	char buf[80];
302 	ses_open_fail_list_t *sof;
303 
304 	/*
305 	 * check list of "unable to open" devices
306 	 */
307 	(void) pthread_mutex_lock(&ses_sofmt);
308 	for (sof = ses_sofh; sof != NULL; sof = sof->sof_next) {
309 		/*
310 		 * see if we can open it now
311 		 */
312 		if ((target = ses_open(LIBSES_VERSION,
313 		    sof->sof_path)) == NULL) {
314 			(void) snprintf(buf, sizeof (buf),
315 			    "recheck_dir - still can't open %s", sof->sof_path);
316 			ses_ct_print(buf);
317 			continue;
318 		}
319 
320 		/*
321 		 * ok - better force a new snapshot
322 		 */
323 		(void) snprintf(buf, sizeof (buf),
324 		    "recheck_dir - can now open %s", sof->sof_path);
325 		ses_ct_print(buf);
326 		(void) sysevent_post_event(EC_PLATFORM, ESC_PLATFORM_SP_RESET,
327 		    SUNW_VENDOR, "fmd", NULL, &eid);
328 		ses_close(target);
329 		break;
330 	}
331 	(void) pthread_mutex_unlock(&ses_sofmt);
332 }
333 
334 static void
335 ses_sof_alloc(topo_mod_t *mod, char *path)
336 {
337 	ses_open_fail_list_t *sof;
338 
339 	(void) pthread_mutex_lock(&ses_sofmt);
340 	sof = topo_mod_zalloc(mod, sizeof (*sof));
341 	topo_mod_dprintf(mod, "sof_alloc %s", path);
342 	sof->sof_path = path;
343 	sof->sof_next = ses_sofh;
344 	ses_sofh = sof;
345 	(void) pthread_mutex_unlock(&ses_sofmt);
346 }
347 
348 static void
349 ses_sof_freeall(topo_mod_t *mod)
350 {
351 	ses_open_fail_list_t *sof, *next_sof;
352 
353 	(void) pthread_mutex_lock(&ses_sofmt);
354 	for (sof = ses_sofh; sof != NULL; sof = next_sof) {
355 		next_sof = sof->sof_next;
356 		topo_mod_dprintf(mod, "sof_freeall %s", sof->sof_path);
357 		topo_mod_strfree(mod, sof->sof_path);
358 		topo_mod_free(mod, sof, sizeof (*sof));
359 	}
360 	ses_sofh = NULL;
361 	(void) pthread_mutex_unlock(&ses_sofmt);
362 }
363 
364 /*
365  * functions for verifying that the ses_enum_target_t held in a device
366  * contract's cookie field is still valid (it may have been freed by
367  * ses_release()).
368  */
369 typedef struct ses_stp_list {
370 	struct ses_stp_list	*ssl_next;
371 	ses_enum_target_t	*ssl_tgt;
372 } ses_stp_list_t;
373 
374 static ses_stp_list_t *ses_sslh;
375 static pthread_mutex_t ses_sslmt;
376 
377 static void
378 ses_ssl_alloc(topo_mod_t *mod, ses_enum_target_t *stp)
379 {
380 	ses_stp_list_t *ssl;
381 
382 	(void) pthread_mutex_lock(&ses_sslmt);
383 	ssl = topo_mod_zalloc(mod, sizeof (*ssl));
384 	topo_mod_dprintf(mod, "ssl_alloc %p", stp);
385 	ssl->ssl_tgt = stp;
386 	ssl->ssl_next = ses_sslh;
387 	ses_sslh = ssl;
388 	(void) pthread_mutex_unlock(&ses_sslmt);
389 }
390 
391 static void
392 ses_ssl_free(topo_mod_t *mod, ses_enum_target_t *stp)
393 {
394 	ses_stp_list_t *ssl, *prev_ssl;
395 
396 	(void) pthread_mutex_lock(&ses_sslmt);
397 	prev_ssl = NULL;
398 	for (ssl = ses_sslh; ssl != NULL; ssl = ssl->ssl_next) {
399 		if (ssl->ssl_tgt == stp) {
400 			topo_mod_dprintf(mod, "ssl_free %p", ssl->ssl_tgt);
401 			if (prev_ssl == NULL)
402 				ses_sslh = ssl->ssl_next;
403 			else
404 				prev_ssl->ssl_next = ssl->ssl_next;
405 			topo_mod_free(mod, ssl, sizeof (*ssl));
406 			break;
407 		}
408 		prev_ssl = ssl;
409 	}
410 	(void) pthread_mutex_unlock(&ses_sslmt);
411 }
412 
413 static int
414 ses_ssl_valid(ses_enum_target_t *stp)
415 {
416 	ses_stp_list_t *ssl;
417 
418 	for (ssl = ses_sslh; ssl != NULL; ssl = ssl->ssl_next)
419 		if (ssl->ssl_tgt == stp)
420 			return (1);
421 	return (0);
422 }
423 
424 /*
425  * Functions for creating and destroying a background thread
426  * (ses_contract_thread) used for detecting when ses devices have been
427  * retired/unretired.
428  */
429 static struct ses_thread_s {
430 	pthread_mutex_t mt;
431 	pthread_t tid;
432 	int thr_sig;
433 	int doexit;
434 	int count;
435 } sesthread = {
436 	PTHREAD_MUTEX_INITIALIZER,
437 	0,
438 	SIGTERM,
439 	0,
440 	0
441 };
442 
443 typedef struct ses_mod_list {
444 	struct ses_mod_list	*smod_next;
445 	topo_mod_t		*smod_mod;
446 } ses_mod_list_t;
447 
448 static ses_mod_list_t *ses_smod;
449 
450 static void
451 ses_ct_print(char *ptr)
452 {
453 	(void) pthread_mutex_lock(&sesthread.mt);
454 	if (ses_smod != NULL && ses_smod->smod_mod != NULL)
455 		topo_mod_dprintf(ses_smod->smod_mod, ptr);
456 	(void) pthread_mutex_unlock(&sesthread.mt);
457 }
458 
459 /*ARGSUSED*/
460 static void *
461 ses_contract_thread(void *arg)
462 {
463 	int efd, ctlfd, statfd;
464 	ct_evthdl_t ev;
465 	ctevid_t evid;
466 	uint_t event;
467 	char path[PATH_MAX];
468 	char buf[80];
469 	ses_enum_target_t *stp;
470 	ct_stathdl_t stathdl;
471 	ctid_t ctid;
472 	struct pollfd fds;
473 	int pollret;
474 	sigset_t sigset;
475 
476 	ses_ct_print("start contract event thread");
477 	efd = open64(CTFS_ROOT "/device/pbundle", O_RDONLY);
478 	fds.fd = efd;
479 	fds.events = POLLIN;
480 	fds.revents = 0;
481 	sigaddset(&sigset, sesthread.thr_sig);
482 	pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
483 	for (;;) {
484 		/* check if we've been asked to exit */
485 		(void) pthread_mutex_lock(&sesthread.mt);
486 		if (sesthread.doexit) {
487 			(void) pthread_mutex_unlock(&sesthread.mt);
488 			break;
489 		}
490 		(void) pthread_mutex_unlock(&sesthread.mt);
491 
492 		/* poll until an event arrives */
493 		if ((pollret = poll(&fds, 1, 10000)) <= 0) {
494 			if (pollret == 0)
495 				ses_recheck_dir();
496 			continue;
497 		}
498 
499 		/* read the event */
500 		(void) pthread_mutex_lock(&ses_sslmt);
501 		ses_ct_print("read contract event");
502 		if (ct_event_read(efd, &ev) != 0) {
503 			(void) pthread_mutex_unlock(&ses_sslmt);
504 			continue;
505 		}
506 
507 		/* see if it is an event we are expecting */
508 		ctid = ct_event_get_ctid(ev);
509 		(void) snprintf(buf, sizeof (buf),
510 		    "got contract event ctid=%d", ctid);
511 		ses_ct_print(buf);
512 		event = ct_event_get_type(ev);
513 		if (event != CT_DEV_EV_OFFLINE && event != CT_EV_NEGEND) {
514 			(void) snprintf(buf, sizeof (buf),
515 			    "bad contract event %x", event);
516 			ses_ct_print(buf);
517 			ct_event_free(ev);
518 			(void) pthread_mutex_unlock(&ses_sslmt);
519 			continue;
520 		}
521 
522 		/* find target pointer saved in cookie */
523 		evid = ct_event_get_evid(ev);
524 		(void) snprintf(path, PATH_MAX, CTFS_ROOT "/device/%ld/status",
525 		    ctid);
526 		statfd = open64(path, O_RDONLY);
527 		(void) ct_status_read(statfd, CTD_COMMON, &stathdl);
528 		stp = (ses_enum_target_t *)(uintptr_t)
529 		    ct_status_get_cookie(stathdl);
530 		ct_status_free(stathdl);
531 		(void) close(statfd);
532 
533 		/* check if target pointer is still valid */
534 		if (ses_ssl_valid(stp) == 0) {
535 			(void) snprintf(buf, sizeof (buf),
536 			    "contract already abandoned %x", event);
537 			ses_ct_print(buf);
538 			(void) snprintf(path, PATH_MAX,
539 			    CTFS_ROOT "/device/%ld/ctl", ctid);
540 			ctlfd = open64(path, O_WRONLY);
541 			if (event != CT_EV_NEGEND)
542 				(void) ct_ctl_ack(ctlfd, evid);
543 			else
544 				(void) ct_ctl_abandon(ctlfd);
545 			(void) close(ctlfd);
546 			ct_event_free(ev);
547 			(void) pthread_mutex_unlock(&ses_sslmt);
548 			continue;
549 		}
550 
551 		/* find control device for ack/abandon */
552 		(void) pthread_mutex_lock(&stp->set_lock);
553 		(void) snprintf(path, PATH_MAX, CTFS_ROOT "/device/%ld/ctl",
554 		    ctid);
555 		ctlfd = open64(path, O_WRONLY);
556 		if (event != CT_EV_NEGEND) {
557 			/* if this is an offline event, do the offline */
558 			ses_ct_print("got contract offline event");
559 			if (stp->set_target) {
560 				ses_ct_print("contract thread rele");
561 				ses_snap_rele(stp->set_snap);
562 				ses_close(stp->set_target);
563 				stp->set_target = NULL;
564 			}
565 			(void) ct_ctl_ack(ctlfd, evid);
566 		} else {
567 			/* if this is the negend, then abandon the contract */
568 			ses_ct_print("got contract negend");
569 			if (stp->set_ctid) {
570 				(void) snprintf(buf, sizeof (buf),
571 				    "abandon old contract %d", stp->set_ctid);
572 				ses_ct_print(buf);
573 				stp->set_ctid = NULL;
574 			}
575 			(void) ct_ctl_abandon(ctlfd);
576 		}
577 		(void) close(ctlfd);
578 		(void) pthread_mutex_unlock(&stp->set_lock);
579 		ct_event_free(ev);
580 		(void) pthread_mutex_unlock(&ses_sslmt);
581 	}
582 	(void) close(efd);
583 	return (NULL);
584 }
585 
586 int
587 find_thr_sig(void)
588 {
589 	int i;
590 	sigset_t oset, rset;
591 	int sig[] = {SIGTERM, SIGUSR1, SIGUSR2};
592 	int sig_sz = sizeof (sig) / sizeof (int);
593 	int rc = SIGTERM;
594 
595 	/* prefered set of signals that are likely used to terminate threads */
596 	(void) sigemptyset(&oset);
597 	(void) pthread_sigmask(SIG_SETMASK, NULL, &oset);
598 	for (i = 0; i < sig_sz; i++) {
599 		if (sigismember(&oset, sig[i]) == 0) {
600 			return (sig[i]);
601 		}
602 	}
603 
604 	/* reserved set of signals that are not allowed to terminate thread */
605 	(void) sigemptyset(&rset);
606 	(void) sigaddset(&rset, SIGABRT);
607 	(void) sigaddset(&rset, SIGKILL);
608 	(void) sigaddset(&rset, SIGSTOP);
609 	(void) sigaddset(&rset, SIGCANCEL);
610 
611 	/* Find signal that is not masked and not in the reserved list. */
612 	for (i = 1; i < MAXSIG; i++) {
613 		if (sigismember(&rset, i) == 1) {
614 			continue;
615 		}
616 		if (sigismember(&oset, i) == 0) {
617 			return (i);
618 		}
619 	}
620 
621 	return (rc);
622 }
623 
624 /*ARGSUSED*/
625 static void
626 ses_handler(int sig)
627 {
628 }
629 
630 static void
631 ses_thread_init(topo_mod_t *mod)
632 {
633 	pthread_attr_t *attr = NULL;
634 	struct sigaction act;
635 	ses_mod_list_t *smod;
636 
637 	(void) pthread_mutex_lock(&sesthread.mt);
638 	sesthread.count++;
639 	smod = topo_mod_zalloc(mod, sizeof (*smod));
640 	smod->smod_mod = mod;
641 	smod->smod_next = ses_smod;
642 	ses_smod = smod;
643 	if (sesthread.tid == 0) {
644 		/* find a suitable signal to use for killing the thread below */
645 		sesthread.thr_sig = find_thr_sig();
646 
647 		/* if don't have a handler for this signal, create one */
648 		(void) sigaction(sesthread.thr_sig, NULL, &act);
649 		if (act.sa_handler == SIG_DFL || act.sa_handler == SIG_IGN)
650 			act.sa_handler = ses_handler;
651 		(void) sigaction(sesthread.thr_sig, &act, NULL);
652 
653 		/* create a thread to listen for offline events */
654 		(void) pthread_create(&sesthread.tid,
655 		    attr, ses_contract_thread, NULL);
656 	}
657 	(void) pthread_mutex_unlock(&sesthread.mt);
658 }
659 
660 static void
661 ses_thread_fini(topo_mod_t *mod)
662 {
663 	ses_mod_list_t *smod, *prev_smod;
664 
665 	(void) pthread_mutex_lock(&sesthread.mt);
666 	prev_smod = NULL;
667 	for (smod = ses_smod; smod != NULL; smod = smod->smod_next) {
668 		if (smod->smod_mod == mod) {
669 			if (prev_smod == NULL)
670 				ses_smod = smod->smod_next;
671 			else
672 				prev_smod->smod_next = smod->smod_next;
673 			topo_mod_free(mod, smod, sizeof (*smod));
674 			break;
675 		}
676 		prev_smod = smod;
677 	}
678 	if (--sesthread.count > 0) {
679 		(void) pthread_mutex_unlock(&sesthread.mt);
680 		return;
681 	}
682 	sesthread.doexit = 1;
683 	(void) pthread_mutex_unlock(&sesthread.mt);
684 	(void) pthread_kill(sesthread.tid, sesthread.thr_sig);
685 	(void) pthread_join(sesthread.tid, NULL);
686 	sesthread.tid = 0;
687 }
688 
689 static void
690 ses_create_contract(topo_mod_t *mod, ses_enum_target_t *stp)
691 {
692 	int tfd, len, rval;
693 	char link_path[PATH_MAX];
694 
695 	stp->set_ctid = NULL;
696 
697 	/* convert "/dev" path into "/devices" path */
698 	if ((len = readlink(stp->set_devpath, link_path, PATH_MAX)) < 0) {
699 		topo_mod_dprintf(mod, "readlink failed");
700 		return;
701 	}
702 	link_path[len] = '\0';
703 
704 	/* set up template to create new contract */
705 	tfd = open64(CTFS_ROOT "/device/template", O_RDWR);
706 	(void) ct_tmpl_set_critical(tfd, CT_DEV_EV_OFFLINE);
707 	(void) ct_tmpl_set_cookie(tfd, (uint64_t)(uintptr_t)stp);
708 
709 	/* strip "../../devices" off the front and create the contract */
710 	if ((rval = ct_dev_tmpl_set_minor(tfd, &link_path[13])) != 0)
711 		topo_mod_dprintf(mod, "failed to set minor %s rval = %d",
712 		    &link_path[13], rval);
713 	else if ((rval = ct_tmpl_create(tfd, &stp->set_ctid)) != 0)
714 		topo_mod_dprintf(mod, "failed to create ctid rval = %d", rval);
715 	else
716 		topo_mod_dprintf(mod, "created ctid=%d", stp->set_ctid);
717 	(void) close(tfd);
718 }
719 
720 static void
721 ses_target_free(topo_mod_t *mod, ses_enum_target_t *stp)
722 {
723 	if (--stp->set_refcount == 0) {
724 		/* check if already closed due to contract offline request */
725 		(void) pthread_mutex_lock(&stp->set_lock);
726 		if (stp->set_target) {
727 			ses_snap_rele(stp->set_snap);
728 			ses_close(stp->set_target);
729 			stp->set_target = NULL;
730 		}
731 		if (stp->set_ctid) {
732 			int ctlfd;
733 			char path[PATH_MAX];
734 
735 			topo_mod_dprintf(mod, "abandon old contract %d",
736 			    stp->set_ctid);
737 			(void) snprintf(path, PATH_MAX,
738 			    CTFS_ROOT "/device/%ld/ctl", stp->set_ctid);
739 			ctlfd = open64(path, O_WRONLY);
740 			(void) ct_ctl_abandon(ctlfd);
741 			(void) close(ctlfd);
742 			stp->set_ctid = NULL;
743 		}
744 		(void) pthread_mutex_unlock(&stp->set_lock);
745 		ses_ssl_free(mod, stp);
746 		topo_mod_strfree(mod, stp->set_devpath);
747 		topo_mod_free(mod, stp, sizeof (ses_enum_target_t));
748 	}
749 }
750 
751 static void
752 ses_data_free(ses_enum_data_t *sdp, ses_enum_chassis_t *pcp)
753 {
754 	topo_mod_t *mod = sdp->sed_mod;
755 	ses_enum_chassis_t *cp;
756 	ses_enum_node_t *np;
757 	ses_enum_target_t *tp;
758 	ses_alt_node_t *ap;
759 	topo_list_t *cpl;
760 
761 
762 	if (pcp != NULL)
763 		cpl = &pcp->sec_subchassis;
764 	else
765 		cpl = &sdp->sed_chassis;
766 
767 	while ((cp = topo_list_next(cpl)) != NULL) {
768 		topo_list_delete(cpl, cp);
769 
770 		while ((np = topo_list_next(&cp->sec_nodes)) != NULL) {
771 			while ((ap = topo_list_next(&np->sen_alt_nodes)) !=
772 			    NULL) {
773 				topo_list_delete(&np->sen_alt_nodes, ap);
774 				topo_mod_free(mod, ap, sizeof (ses_alt_node_t));
775 			}
776 			topo_list_delete(&cp->sec_nodes, np);
777 			topo_mod_free(mod, np, sizeof (ses_enum_node_t));
778 		}
779 
780 		while ((tp = topo_list_next(&cp->sec_targets)) != NULL) {
781 			topo_list_delete(&cp->sec_targets, tp);
782 			ses_target_free(mod, tp);
783 		}
784 
785 		topo_mod_free(mod, cp, sizeof (ses_enum_chassis_t));
786 	}
787 
788 	if (pcp == NULL) {
789 		dev_list_free(mod, &sdp->sed_devs);
790 		topo_mod_free(mod, sdp, sizeof (ses_enum_data_t));
791 	}
792 }
793 
794 /*
795  * For enclosure nodes, we have a special contains method.  By default, the hc
796  * walker will compare the node name and instance number to determine if an
797  * FMRI matches.  For enclosures where the enumeration order is impossible to
798  * predict, we instead use the chassis-id as a unique identifier, and ignore
799  * the instance number.
800  */
801 static int
802 fmri_contains(topo_mod_t *mod, nvlist_t *nv1, nvlist_t *nv2)
803 {
804 	uint8_t v1, v2;
805 	nvlist_t **hcp1, **hcp2;
806 	int err, i;
807 	uint_t nhcp1, nhcp2;
808 	nvlist_t *a1, *a2;
809 	char *c1, *c2;
810 	int mindepth;
811 
812 	if (nvlist_lookup_uint8(nv1, FM_VERSION, &v1) != 0 ||
813 	    nvlist_lookup_uint8(nv2, FM_VERSION, &v2) != 0 ||
814 	    v1 > FM_HC_SCHEME_VERSION || v2 > FM_HC_SCHEME_VERSION)
815 		return (topo_mod_seterrno(mod, EMOD_FMRI_VERSION));
816 
817 	err = nvlist_lookup_nvlist_array(nv1, FM_FMRI_HC_LIST, &hcp1, &nhcp1);
818 	err |= nvlist_lookup_nvlist_array(nv2, FM_FMRI_HC_LIST, &hcp2, &nhcp2);
819 	if (err != 0)
820 		return (topo_mod_seterrno(mod, EMOD_FMRI_NVL));
821 
822 	/*
823 	 * If the chassis-id doesn't match, then these FMRIs are not
824 	 * equivalent.  If one of the FMRIs doesn't have a chassis ID, then we
825 	 * have no choice but to fall back to the instance ID.
826 	 */
827 	if (nvlist_lookup_nvlist(nv1, FM_FMRI_AUTHORITY, &a1) == 0 &&
828 	    nvlist_lookup_nvlist(nv2, FM_FMRI_AUTHORITY, &a2) == 0 &&
829 	    nvlist_lookup_string(a1, FM_FMRI_AUTH_CHASSIS, &c1) == 0 &&
830 	    nvlist_lookup_string(a2, FM_FMRI_AUTH_CHASSIS, &c2) == 0) {
831 		if (strcmp(c1, c2) != 0)
832 			return (0);
833 
834 		mindepth = 1;
835 	} else {
836 		mindepth = 0;
837 	}
838 
839 	if (nhcp2 < nhcp1)
840 		return (0);
841 
842 	for (i = 0; i < nhcp1; i++) {
843 		char *nm1 = NULL;
844 		char *nm2 = NULL;
845 		char *id1 = NULL;
846 		char *id2 = NULL;
847 
848 		(void) nvlist_lookup_string(hcp1[i], FM_FMRI_HC_NAME, &nm1);
849 		(void) nvlist_lookup_string(hcp2[i], FM_FMRI_HC_NAME, &nm2);
850 		(void) nvlist_lookup_string(hcp1[i], FM_FMRI_HC_ID, &id1);
851 		(void) nvlist_lookup_string(hcp2[i], FM_FMRI_HC_ID, &id2);
852 		if (nm1 == NULL || nm2 == NULL || id1 == NULL || id2 == NULL)
853 			return (topo_mod_seterrno(mod, EMOD_FMRI_NVL));
854 
855 		if (strcmp(nm1, nm2) == 0 &&
856 		    (i < mindepth || strcmp(id1, id2) == 0))
857 			continue;
858 
859 		return (0);
860 	}
861 
862 	return (1);
863 }
864 
865 /*ARGSUSED*/
866 static int
867 ses_contains(topo_mod_t *mod, tnode_t *tn, topo_version_t version,
868     nvlist_t *in, nvlist_t **out)
869 {
870 	int ret;
871 	nvlist_t *nv1, *nv2;
872 
873 	if (version > TOPO_METH_CONTAINS_VERSION)
874 		return (topo_mod_seterrno(mod, EMOD_VER_NEW));
875 
876 	if (nvlist_lookup_nvlist(in, TOPO_METH_FMRI_ARG_FMRI, &nv1) != 0 ||
877 	    nvlist_lookup_nvlist(in, TOPO_METH_FMRI_ARG_SUBFMRI, &nv2) != 0)
878 		return (topo_mod_seterrno(mod, EMOD_METHOD_INVAL));
879 
880 	ret = fmri_contains(mod, nv1, nv2);
881 	if (ret < 0)
882 		return (-1);
883 
884 	if (topo_mod_nvalloc(mod, out, NV_UNIQUE_NAME) == 0) {
885 		if (nvlist_add_uint32(*out, TOPO_METH_CONTAINS_RET,
886 		    ret) == 0)
887 			return (0);
888 		else
889 			nvlist_free(*out);
890 	}
891 
892 	return (-1);
893 
894 }
895 
896 /*
897  * Return a current instance of the node.  This is somewhat complicated because
898  * we need to take a new snapshot in order to get the new data, but we don't
899  * want to be constantly taking SES snapshots if the consumer is going to do a
900  * series of queries.  So we adopt the strategy of assuming that the SES state
901  * is not going to be rapidly changing, and limit our snapshot frequency to
902  * some defined bounds.
903  */
904 ses_node_t *
905 ses_node_lock(topo_mod_t *mod, tnode_t *tn)
906 {
907 	ses_enum_target_t *tp = topo_node_getspecific(tn);
908 	hrtime_t now;
909 	ses_snap_t *snap;
910 	int err;
911 	uint64_t nodeid;
912 	ses_node_t *np;
913 
914 	if (tp == NULL) {
915 		(void) topo_mod_seterrno(mod, EMOD_METHOD_NOTSUP);
916 		return (NULL);
917 	}
918 
919 	(void) pthread_mutex_lock(&tp->set_lock);
920 
921 	/*
922 	 * Determine if we need to take a new snapshot.
923 	 */
924 	now = gethrtime();
925 
926 	if (tp->set_target == NULL) {
927 		/*
928 		 * We may have closed the device but not yet abandoned the
929 		 * contract (ie we've had the offline event but not yet the
930 		 * negend). If so, just return failure.
931 		 */
932 		if (tp->set_ctid != NULL) {
933 			(void) topo_mod_seterrno(mod, EMOD_METHOD_NOTSUP);
934 			(void) pthread_mutex_unlock(&tp->set_lock);
935 			return (NULL);
936 		}
937 
938 		/*
939 		 * The device has been closed due to a contract offline
940 		 * request, then we need to reopen it and create a new contract.
941 		 */
942 		if ((tp->set_target =
943 		    ses_open(LIBSES_VERSION, tp->set_devpath)) == NULL) {
944 			sysevent_id_t eid;
945 
946 			(void) topo_mod_seterrno(mod, EMOD_METHOD_NOTSUP);
947 			(void) pthread_mutex_unlock(&tp->set_lock);
948 			topo_mod_dprintf(mod, "recheck_dir - "
949 			    "can no longer open %s", tp->set_devpath);
950 			(void) sysevent_post_event(EC_PLATFORM,
951 			    ESC_PLATFORM_SP_RESET, SUNW_VENDOR, "fmd", NULL,
952 			    &eid);
953 			return (NULL);
954 		}
955 		topo_mod_dprintf(mod, "reopen contract");
956 		ses_create_contract(mod, tp);
957 		tp->set_snap = ses_snap_hold(tp->set_target);
958 		tp->set_snaptime = gethrtime();
959 	} else if (now - tp->set_snaptime > (ses_snap_freq * 1000 * 1000) &&
960 	    (snap = ses_snap_new(tp->set_target)) != NULL) {
961 		if (ses_snap_generation(snap) !=
962 		    ses_snap_generation(tp->set_snap)) {
963 			/*
964 			 * If we find ourselves in this situation, we're in
965 			 * trouble.  The generation count has changed, which
966 			 * indicates that our current topology is out of date.
967 			 * But we need to consult the new topology in order to
968 			 * determine presence at this moment in time.  We can't
969 			 * go back and change the topo snapshot in situ, so
970 			 * we'll just have to fail the call in this unlikely
971 			 * scenario.
972 			 */
973 			ses_snap_rele(snap);
974 			(void) topo_mod_seterrno(mod, EMOD_METHOD_NOTSUP);
975 			(void) pthread_mutex_unlock(&tp->set_lock);
976 			return (NULL);
977 		} else {
978 			ses_snap_rele(tp->set_snap);
979 			tp->set_snap = snap;
980 		}
981 		tp->set_snaptime = gethrtime();
982 	}
983 
984 	snap = tp->set_snap;
985 
986 	verify(topo_prop_get_uint64(tn, TOPO_PGROUP_SES,
987 	    TOPO_PROP_NODE_ID, &nodeid, &err) == 0);
988 	verify((np = ses_node_lookup(snap, nodeid)) != NULL);
989 
990 	return (np);
991 }
992 
993 /*ARGSUSED*/
994 void
995 ses_node_unlock(topo_mod_t *mod, tnode_t *tn)
996 {
997 	ses_enum_target_t *tp = topo_node_getspecific(tn);
998 
999 	verify(tp != NULL);
1000 
1001 	(void) pthread_mutex_unlock(&tp->set_lock);
1002 }
1003 
1004 /*
1005  * Determine if the element is present.
1006  */
1007 /*ARGSUSED*/
1008 static int
1009 ses_present(topo_mod_t *mod, tnode_t *tn, topo_version_t version,
1010     nvlist_t *in, nvlist_t **out)
1011 {
1012 	boolean_t present;
1013 	ses_node_t *np;
1014 	nvlist_t *props, *nvl;
1015 	uint64_t status;
1016 
1017 	if ((np = ses_node_lock(mod, tn)) == NULL)
1018 		return (-1);
1019 
1020 	verify((props = ses_node_props(np)) != NULL);
1021 	verify(nvlist_lookup_uint64(props,
1022 	    SES_PROP_STATUS_CODE, &status) == 0);
1023 
1024 	ses_node_unlock(mod, tn);
1025 
1026 	present = (status != SES_ESC_NOT_INSTALLED);
1027 
1028 	if (topo_mod_nvalloc(mod, &nvl, NV_UNIQUE_NAME) != 0)
1029 		return (topo_mod_seterrno(mod, EMOD_FMRI_NVL));
1030 
1031 	if (nvlist_add_uint32(nvl, TOPO_METH_PRESENT_RET,
1032 	    present) != 0) {
1033 		nvlist_free(nvl);
1034 		return (topo_mod_seterrno(mod, EMOD_FMRI_NVL));
1035 	}
1036 
1037 	*out = nvl;
1038 
1039 	return (0);
1040 }
1041 
1042 /*
1043  * Sets standard properties for a ses node (enclosure, bay, controller
1044  * or expander).
1045  * This includes setting the FRU, as well as setting the
1046  * authority information.  When  the fru topo node(frutn) is not NULL
1047  * its resouce should be used as FRU.
1048  */
1049 static int
1050 ses_set_standard_props(topo_mod_t *mod, tnode_t *frutn, tnode_t *tn,
1051     nvlist_t *auth, uint64_t nodeid, const char *path)
1052 {
1053 	int err;
1054 	char *product, *chassis;
1055 	nvlist_t *fmri;
1056 
1057 	/*
1058 	 * Set the authority explicitly if specified.
1059 	 */
1060 	if (auth) {
1061 		verify(nvlist_lookup_string(auth, FM_FMRI_AUTH_PRODUCT,
1062 		    &product) == 0);
1063 		verify(nvlist_lookup_string(auth, FM_FMRI_AUTH_CHASSIS,
1064 		    &chassis) == 0);
1065 		if (topo_prop_set_string(tn, FM_FMRI_AUTHORITY,
1066 		    FM_FMRI_AUTH_PRODUCT, TOPO_PROP_IMMUTABLE, product,
1067 		    &err) != 0 ||
1068 		    topo_prop_set_string(tn, FM_FMRI_AUTHORITY,
1069 		    FM_FMRI_AUTH_CHASSIS, TOPO_PROP_IMMUTABLE, chassis,
1070 		    &err) != 0 ||
1071 		    topo_prop_set_string(tn, FM_FMRI_AUTHORITY,
1072 		    FM_FMRI_AUTH_SERVER, TOPO_PROP_IMMUTABLE, "",
1073 		    &err) != 0) {
1074 			topo_mod_dprintf(mod, "failed to add authority "
1075 			    "properties: %s\n", topo_strerror(err));
1076 			return (topo_mod_seterrno(mod, err));
1077 		}
1078 	}
1079 
1080 	/*
1081 	 * Copy the resource and set that as the FRU.
1082 	 */
1083 	if (frutn != NULL) {
1084 		if (topo_node_resource(frutn, &fmri, &err) != 0) {
1085 			topo_mod_dprintf(mod,
1086 			    "topo_node_resource() failed : %s\n",
1087 			    topo_strerror(err));
1088 			return (topo_mod_seterrno(mod, err));
1089 		}
1090 	} else {
1091 		if (topo_node_resource(tn, &fmri, &err) != 0) {
1092 			topo_mod_dprintf(mod,
1093 			    "topo_node_resource() failed : %s\n",
1094 			    topo_strerror(err));
1095 			return (topo_mod_seterrno(mod, err));
1096 		}
1097 	}
1098 
1099 	if (topo_node_fru_set(tn, fmri, 0, &err) != 0) {
1100 		topo_mod_dprintf(mod,
1101 		    "topo_node_fru_set() failed : %s\n",
1102 		    topo_strerror(err));
1103 		nvlist_free(fmri);
1104 		return (topo_mod_seterrno(mod, err));
1105 	}
1106 
1107 	nvlist_free(fmri);
1108 
1109 	/*
1110 	 * Set the SES-specific properties so that consumers can query
1111 	 * additional information about the particular SES element.
1112 	 */
1113 	if (topo_pgroup_create(tn, &ses_pgroup, &err) != 0) {
1114 		topo_mod_dprintf(mod, "failed to create propgroup "
1115 		    "%s: %s\n", TOPO_PGROUP_SES, topo_strerror(err));
1116 		return (-1);
1117 	}
1118 
1119 	if (topo_prop_set_uint64(tn, TOPO_PGROUP_SES,
1120 	    TOPO_PROP_NODE_ID, TOPO_PROP_IMMUTABLE,
1121 	    nodeid, &err) != 0) {
1122 		topo_mod_dprintf(mod,
1123 		    "failed to create property %s: %s\n",
1124 		    TOPO_PROP_NODE_ID, topo_strerror(err));
1125 		return (-1);
1126 	}
1127 
1128 	if (topo_prop_set_string(tn, TOPO_PGROUP_SES,
1129 	    TOPO_PROP_TARGET_PATH, TOPO_PROP_IMMUTABLE,
1130 	    path, &err) != 0) {
1131 		topo_mod_dprintf(mod,
1132 		    "failed to create property %s: %s\n",
1133 		    TOPO_PROP_TARGET_PATH, topo_strerror(err));
1134 		return (-1);
1135 	}
1136 
1137 	return (0);
1138 }
1139 
1140 /*
1141  * Callback to add a disk to a given bay.  We first check the status-code to
1142  * determine if a disk is present, ignoring those that aren't in an appropriate
1143  * state.  We then scan the parent bay node's SAS address array to determine
1144  * possible attached SAS addresses.  We create a disk node if the disk is not
1145  * SAS or the SES target does not support the necessary pages for this; if we
1146  * find the SAS address, we create a disk node and also correlate it with
1147  * the corresponding Solaris device node to fill in the rest of the data.
1148  */
1149 static int
1150 ses_create_disk(ses_enum_data_t *sdp, tnode_t *pnode, nvlist_t *props)
1151 {
1152 	topo_mod_t *mod = sdp->sed_mod;
1153 	uint64_t status;
1154 	uint_t s, nsas;
1155 	char **paths;
1156 	int err, ret;
1157 	tnode_t *child = NULL;
1158 
1159 	/*
1160 	 * Skip devices that are not in a present (and possibly damaged) state.
1161 	 */
1162 	if (nvlist_lookup_uint64(props, SES_PROP_STATUS_CODE, &status) != 0)
1163 		return (0);
1164 
1165 	if (status != SES_ESC_UNSUPPORTED &&
1166 	    status != SES_ESC_OK &&
1167 	    status != SES_ESC_CRITICAL &&
1168 	    status != SES_ESC_NONCRITICAL &&
1169 	    status != SES_ESC_UNRECOVERABLE &&
1170 	    status != SES_ESC_NO_ACCESS &&
1171 	    status != SES_ESC_UNKNOWN)
1172 		return (0);
1173 
1174 	topo_mod_dprintf(mod, "found attached disk");
1175 
1176 	/*
1177 	 * Create the disk range.
1178 	 */
1179 	if (topo_node_range_create(mod, pnode, DISK, 0, 0) != 0) {
1180 		topo_mod_dprintf(mod,
1181 		    "topo_node_create_range() failed: %s",
1182 		    topo_mod_errmsg(mod));
1183 		return (-1);
1184 	}
1185 
1186 	/*
1187 	 * Look through all SAS addresses and attempt to correlate them to a
1188 	 * known Solaris device.  If we don't find a matching node, then we
1189 	 * don't enumerate the disk node.
1190 	 * Note that TOPO_PROP_SAS_ADDR prop includes SAS address from
1191 	 * alternate elements that represent the same device.
1192 	 */
1193 	if (topo_prop_get_string_array(pnode, TOPO_PGROUP_SES,
1194 	    TOPO_PROP_SAS_ADDR, &paths, &nsas, &err) != 0)
1195 		return (0);
1196 
1197 	err = 0;
1198 
1199 	for (s = 0; s < nsas; s++) {
1200 		ret = disk_declare_addr(mod, pnode, &sdp->sed_devs, paths[s],
1201 		    &child);
1202 		if (ret == 0) {
1203 			break;
1204 		} else if (ret < 0) {
1205 			err = -1;
1206 			break;
1207 		}
1208 	}
1209 
1210 	if (s == nsas)
1211 		(void) disk_declare_non_enumerated(mod, pnode, &child);
1212 
1213 	/* copy sas_addresses (target-ports) from parent (with 'w'added) */
1214 	if (child != NULL) {
1215 		int i;
1216 		char **tports;
1217 		uint64_t wwn;
1218 
1219 		tports = topo_mod_zalloc(mod, sizeof (char *) * nsas);
1220 		if (tports != NULL) {
1221 			for (i = 0; i < nsas; i++) {
1222 				if (scsi_wwnstr_to_wwn(paths[i], &wwn) !=
1223 				    DDI_SUCCESS)
1224 					break;
1225 				tports[i] = scsi_wwn_to_wwnstr(wwn, 1, NULL);
1226 				if (tports[i] == NULL)
1227 					break;
1228 			}
1229 			/* if they all worked then create the property */
1230 			if (i == nsas)
1231 				(void) topo_prop_set_string_array(child,
1232 				    TOPO_PGROUP_STORAGE,
1233 				    TOPO_STORAGE_TARGET_PORT_L0IDS,
1234 				    TOPO_PROP_IMMUTABLE, (const char **)tports,
1235 				    nsas, &err);
1236 
1237 			for (i = 0; i < nsas; i++)
1238 				if (tports[i] != NULL)
1239 					scsi_free_wwnstr(tports[i]);
1240 			topo_mod_free(mod, tports, sizeof (char *) * nsas);
1241 		}
1242 	}
1243 
1244 	for (s = 0; s < nsas; s++)
1245 		topo_mod_free(mod, paths[s], strlen(paths[s]) + 1);
1246 	topo_mod_free(mod, paths, nsas * sizeof (char *));
1247 
1248 	return (err);
1249 }
1250 
1251 static int
1252 ses_add_bay_props(topo_mod_t *mod, tnode_t *tn, ses_enum_node_t *snp)
1253 {
1254 	ses_alt_node_t *ap;
1255 	ses_node_t *np;
1256 	nvlist_t *props;
1257 
1258 	nvlist_t **phys;
1259 	uint_t i, j, n_phys, all_phys = 0;
1260 	char **paths;
1261 	uint64_t addr;
1262 	size_t len;
1263 	int terr, err = -1;
1264 
1265 	for (ap = topo_list_next(&snp->sen_alt_nodes); ap != NULL;
1266 	    ap = topo_list_next(ap)) {
1267 		np = ap->san_node;
1268 		props = ses_node_props(np);
1269 
1270 		if (nvlist_lookup_nvlist_array(props, SES_SAS_PROP_PHYS,
1271 		    &phys, &n_phys) != 0)
1272 			continue;
1273 
1274 		all_phys += n_phys;
1275 	}
1276 
1277 	if (all_phys == 0)
1278 		return (0);
1279 
1280 	if ((paths = topo_mod_zalloc(mod, all_phys * sizeof (char *))) == NULL)
1281 		return (-1);
1282 
1283 	for (i = 0, ap = topo_list_next(&snp->sen_alt_nodes); ap != NULL;
1284 	    ap = topo_list_next(ap)) {
1285 		np = ap->san_node;
1286 		props = ses_node_props(np);
1287 
1288 		if (nvlist_lookup_nvlist_array(props, SES_SAS_PROP_PHYS,
1289 		    &phys, &n_phys) != 0)
1290 			continue;
1291 
1292 		for (j = 0; j < n_phys; j++) {
1293 			if (nvlist_lookup_uint64(phys[j], SES_SAS_PROP_ADDR,
1294 			    &addr) != 0)
1295 				continue;
1296 
1297 			len = snprintf(NULL, 0, "%016llx", addr) + 1;
1298 			if ((paths[i] = topo_mod_alloc(mod, len)) == NULL)
1299 				goto error;
1300 
1301 			(void) snprintf(paths[i], len, "%016llx", addr);
1302 
1303 			++i;
1304 		}
1305 	}
1306 
1307 	err = topo_prop_set_string_array(tn, TOPO_PGROUP_SES,
1308 	    TOPO_PROP_SAS_ADDR, TOPO_PROP_IMMUTABLE,
1309 	    (const char **)paths, i, &terr);
1310 	if (err != 0)
1311 		err = topo_mod_seterrno(mod, terr);
1312 
1313 error:
1314 	for (i = 0; i < all_phys && paths[i] != NULL; i++)
1315 		topo_mod_free(mod, paths[i], strlen(paths[i]) + 1);
1316 	topo_mod_free(mod, paths, all_phys * sizeof (char *));
1317 
1318 	return (err);
1319 }
1320 
1321 /*
1322  * Callback to create a basic node (bay, psu, fan, or controller and expander).
1323  */
1324 static int
1325 ses_create_generic(ses_enum_data_t *sdp, ses_enum_node_t *snp, tnode_t *pnode,
1326     tnode_t *frutn, const char *nodename, const char *labelname,
1327     tnode_t **node)
1328 {
1329 	ses_node_t *np = snp->sen_node;
1330 	ses_node_t *parent;
1331 	uint64_t instance = snp->sen_instance;
1332 	topo_mod_t *mod = sdp->sed_mod;
1333 	nvlist_t *props, *aprops;
1334 	nvlist_t *auth = NULL, *fmri = NULL;
1335 	tnode_t *tn = NULL;
1336 	char label[128];
1337 	int err;
1338 	char *part = NULL, *serial = NULL, *revision = NULL;
1339 	char *desc;
1340 	boolean_t report;
1341 
1342 	props = ses_node_props(np);
1343 
1344 	(void) nvlist_lookup_string(props, LIBSES_PROP_PART, &part);
1345 	(void) nvlist_lookup_string(props, LIBSES_PROP_SERIAL, &serial);
1346 
1347 	topo_mod_dprintf(mod, "adding %s %llu", nodename, instance);
1348 
1349 	/*
1350 	 * Create the node.  The interesting information is all copied from the
1351 	 * parent enclosure node, so there is not much to do.
1352 	 */
1353 	if ((auth = topo_mod_auth(mod, pnode)) == NULL)
1354 		goto error;
1355 
1356 	/*
1357 	 * We want to report revision information for the controller nodes, but
1358 	 * we do not get per-element revision information.  However, we do have
1359 	 * revision information for the entire enclosure, and we can use the
1360 	 * 'reported-via' property to know that this controller corresponds to
1361 	 * the given revision information.  This means we cannot get revision
1362 	 * information for targets we are not explicitly connected to, but
1363 	 * there is little we can do about the situation.
1364 	 */
1365 	if (strcmp(nodename, CONTROLLER) == 0 &&
1366 	    nvlist_lookup_boolean_value(props, SES_PROP_REPORT, &report) == 0 &&
1367 	    report) {
1368 		for (parent = ses_node_parent(np); parent != NULL;
1369 		    parent = ses_node_parent(parent)) {
1370 			if (ses_node_type(parent) == SES_NODE_ENCLOSURE) {
1371 				(void) nvlist_lookup_string(
1372 				    ses_node_props(parent),
1373 				    SES_EN_PROP_REV, &revision);
1374 				break;
1375 			}
1376 		}
1377 	}
1378 
1379 	if ((fmri = topo_mod_hcfmri(mod, pnode, FM_HC_SCHEME_VERSION,
1380 	    nodename, (topo_instance_t)instance, NULL, auth, part, revision,
1381 	    serial)) == NULL) {
1382 		topo_mod_dprintf(mod, "topo_mod_hcfmri() failed: %s",
1383 		    topo_mod_errmsg(mod));
1384 		goto error;
1385 	}
1386 
1387 	if ((tn = topo_node_bind(mod, pnode, nodename,
1388 	    instance, fmri)) == NULL) {
1389 		topo_mod_dprintf(mod, "topo_node_bind() failed: %s",
1390 		    topo_mod_errmsg(mod));
1391 		goto error;
1392 	}
1393 
1394 	/*
1395 	 * For the node label, we look for the following in order:
1396 	 *
1397 	 * 	<ses-description>
1398 	 * 	<ses-class-description> <instance>
1399 	 * 	<default-type-label> <instance>
1400 	 */
1401 	if (nvlist_lookup_string(props, SES_PROP_DESCRIPTION, &desc) != 0 ||
1402 	    desc[0] == '\0') {
1403 		parent = ses_node_parent(np);
1404 		aprops = ses_node_props(parent);
1405 		if (nvlist_lookup_string(aprops, SES_PROP_CLASS_DESCRIPTION,
1406 		    &desc) != 0 || desc[0] == '\0')
1407 			desc = (char *)labelname;
1408 		(void) snprintf(label, sizeof (label), "%s %llu", desc,
1409 		    instance);
1410 		desc = label;
1411 	}
1412 
1413 	if (topo_node_label_set(tn, desc, &err) != 0)
1414 		goto error;
1415 
1416 	if (ses_set_standard_props(mod, frutn, tn, NULL, ses_node_id(np),
1417 	    snp->sen_target->set_devpath) != 0)
1418 		goto error;
1419 
1420 	if (strcmp(nodename, BAY) == 0) {
1421 		if (ses_add_bay_props(mod, tn, snp) != 0)
1422 			goto error;
1423 
1424 		if (ses_create_disk(sdp, tn, props) != 0)
1425 			goto error;
1426 
1427 		if (topo_method_register(mod, tn, ses_bay_methods) != 0) {
1428 			topo_mod_dprintf(mod,
1429 			    "topo_method_register() failed: %s",
1430 			    topo_mod_errmsg(mod));
1431 			goto error;
1432 		}
1433 	} else if ((strcmp(nodename, FAN) == 0) ||
1434 	    (strcmp(nodename, PSU) == 0) ||
1435 	    (strcmp(nodename, CONTROLLER) == 0)) {
1436 		/*
1437 		 * Only fan, psu, and controller nodes have a 'present' method.
1438 		 * Bay nodes are always present, and disk nodes are present by
1439 		 * virtue of being enumerated and SAS expander nodes and
1440 		 * SAS connector nodes are also always present once
1441 		 * the parent controller is found.
1442 		 */
1443 		if (topo_method_register(mod, tn, ses_component_methods) != 0) {
1444 			topo_mod_dprintf(mod,
1445 			    "topo_method_register() failed: %s",
1446 			    topo_mod_errmsg(mod));
1447 			goto error;
1448 		}
1449 
1450 	}
1451 
1452 	snp->sen_target->set_refcount++;
1453 	topo_node_setspecific(tn, snp->sen_target);
1454 
1455 	nvlist_free(auth);
1456 	nvlist_free(fmri);
1457 	if (node != NULL) *node = tn;
1458 	return (0);
1459 
1460 error:
1461 	nvlist_free(auth);
1462 	nvlist_free(fmri);
1463 	return (-1);
1464 }
1465 
1466 /*
1467  * Create SAS expander specific props.
1468  */
1469 /*ARGSUSED*/
1470 static int
1471 ses_set_expander_props(ses_enum_data_t *sdp, ses_enum_node_t *snp,
1472     tnode_t *ptnode, tnode_t *tnode, int *phycount, int64_t *connlist)
1473 {
1474 	ses_node_t *np = snp->sen_node;
1475 	topo_mod_t *mod = sdp->sed_mod;
1476 	nvlist_t *auth = NULL, *fmri = NULL;
1477 	nvlist_t *props, **phylist;
1478 	int err, i;
1479 	uint_t pcount;
1480 	uint64_t sasaddr, connidx;
1481 	char sasaddr_str[17];
1482 	boolean_t found = B_FALSE, ses_found = B_FALSE;
1483 	dev_di_node_t *dnode, *sesdnode;
1484 
1485 	props = ses_node_props(np);
1486 
1487 	/*
1488 	 * the uninstalled expander is not enumerated by checking
1489 	 * the element status code.  No present present' method provided.
1490 	 */
1491 	/*
1492 	 * Get the Expander SAS address.  It should exist.
1493 	 */
1494 	if (nvlist_lookup_uint64(props, SES_EXP_PROP_SAS_ADDR,
1495 	    &sasaddr) != 0) {
1496 		topo_mod_dprintf(mod,
1497 		    "Failed to get prop %s.", SES_EXP_PROP_SAS_ADDR);
1498 		goto error;
1499 	}
1500 
1501 	(void) sprintf(sasaddr_str, "%llx", sasaddr);
1502 
1503 	/* search matching dev_di_node. */
1504 	for (dnode = topo_list_next(&sdp->sed_devs); dnode != NULL;
1505 	    dnode = topo_list_next(dnode)) {
1506 		for (i = 0; i < dnode->ddn_ppath_count; i++) {
1507 			if ((dnode->ddn_target_port[i] != NULL) &&
1508 			    (strstr(dnode->ddn_target_port[i],
1509 			    sasaddr_str) != NULL)) {
1510 				found = B_TRUE;
1511 				break;
1512 			}
1513 		}
1514 		if (found)
1515 			break;
1516 	}
1517 
1518 	if (!found) {
1519 		topo_mod_dprintf(mod,
1520 		    "ses_set_expander_props: Failed to find matching "
1521 		    "devinfo node for Exapnder SAS address %s",
1522 		    SES_EXP_PROP_SAS_ADDR);
1523 		/* continue on to get storage group props. */
1524 	} else {
1525 		/* create/set the devfs-path and devid in the smp group */
1526 		if (topo_pgroup_create(tnode, &smp_pgroup, &err) != 0) {
1527 			topo_mod_dprintf(mod, "ses_set_expander_props: "
1528 			    "failed to create smp property group %s\n",
1529 			    topo_strerror(err));
1530 			goto error;
1531 		} else {
1532 			if (topo_prop_set_string(tnode, TOPO_PGROUP_SMP,
1533 			    TOPO_PROP_SMP_TARGET_PORT, TOPO_PROP_IMMUTABLE,
1534 			    dnode->ddn_target_port[i], &err) != 0) {
1535 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1536 				    "set %S error %s\n", TOPO_PROP_SAS_ADDR,
1537 				    topo_strerror(err));
1538 			}
1539 			if (topo_prop_set_string(tnode, TOPO_PGROUP_SMP,
1540 			    TOPO_PROP_SMP_DEV_PATH, TOPO_PROP_IMMUTABLE,
1541 			    dnode->ddn_dpath, &err) != 0) {
1542 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1543 				    "set dev error %s\n", topo_strerror(err));
1544 			}
1545 			if (topo_prop_set_string(tnode, TOPO_PGROUP_SMP,
1546 			    TOPO_PROP_SMP_DEVID, TOPO_PROP_IMMUTABLE,
1547 			    dnode->ddn_devid, &err) != 0) {
1548 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1549 				    "set devid error %s\n", topo_strerror(err));
1550 			}
1551 			if (dnode->ddn_ppath_count != 0 &&
1552 			    topo_prop_set_string_array(tnode, TOPO_PGROUP_SMP,
1553 			    TOPO_PROP_SMP_PHYS_PATH, TOPO_PROP_IMMUTABLE,
1554 			    (const char **)dnode->ddn_ppath,
1555 			    dnode->ddn_ppath_count, &err) != 0) {
1556 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1557 				    "set phys-path error %s\n",
1558 				    topo_strerror(err));
1559 			}
1560 		}
1561 	}
1562 
1563 	/* update the ses property group with SES target info */
1564 	if ((topo_pgroup_create(tnode, &ses_pgroup, &err) != 0) &&
1565 	    (err != ETOPO_PROP_DEFD)) {
1566 		/* SES prop group doesn't exist but failed to be created. */
1567 		topo_mod_dprintf(mod, "ses_set_expander_props: "
1568 		    "ses pgroup create error %s\n", topo_strerror(err));
1569 		goto error;
1570 	} else {
1571 		/* locate assciated enclosure dev_di_node. */
1572 		for (sesdnode = topo_list_next(&sdp->sed_devs);
1573 		    sesdnode != NULL; sesdnode = topo_list_next(sesdnode)) {
1574 			for (i = 0; i < sesdnode->ddn_ppath_count; i++) {
1575 				/*
1576 				 * check if attached port exists and
1577 				 * its node type is enclosure and
1578 				 * attached port is same as sas address of
1579 				 * the expander and
1580 				 * bridge port for virtual phy indication
1581 				 * exist.
1582 				 */
1583 				if ((sesdnode->ddn_attached_port[i] != NULL) &&
1584 				    (sesdnode->ddn_dtype == DTYPE_ESI) &&
1585 				    (strstr(sesdnode->ddn_attached_port[i],
1586 				    sasaddr_str) != NULL) &&
1587 				    (sesdnode->ddn_bridge_port[i] != NULL)) {
1588 					ses_found = B_TRUE;
1589 					break;
1590 				}
1591 			}
1592 			if (ses_found) break;
1593 		}
1594 
1595 		if (ses_found) {
1596 			if (topo_prop_set_string(tnode, TOPO_PGROUP_SES,
1597 			    TOPO_PROP_SES_TARGET_PORT, TOPO_PROP_IMMUTABLE,
1598 			    sesdnode->ddn_target_port[i], &err) != 0) {
1599 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1600 				    "set ses %S error %s\n", TOPO_PROP_SAS_ADDR,
1601 				    topo_strerror(err));
1602 			}
1603 			if (topo_prop_set_string(tnode, TOPO_PGROUP_SES,
1604 			    TOPO_PROP_SES_DEV_PATH, TOPO_PROP_IMMUTABLE,
1605 			    sesdnode->ddn_dpath, &err) != 0) {
1606 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1607 				    "set ses dev error %s\n",
1608 				    topo_strerror(err));
1609 			}
1610 			if (topo_prop_set_string(tnode, TOPO_PGROUP_SES,
1611 			    TOPO_PROP_SES_DEVID, TOPO_PROP_IMMUTABLE,
1612 			    sesdnode->ddn_devid, &err) != 0) {
1613 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1614 				    "set ses devid error %s\n",
1615 				    topo_strerror(err));
1616 			}
1617 			if (sesdnode->ddn_ppath_count != 0 &&
1618 			    topo_prop_set_string_array(tnode, TOPO_PGROUP_SES,
1619 			    TOPO_PROP_SES_PHYS_PATH, TOPO_PROP_IMMUTABLE,
1620 			    (const char **)sesdnode->ddn_ppath,
1621 			    sesdnode->ddn_ppath_count, &err) != 0) {
1622 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1623 				    "set ses phys-path error %s\n",
1624 				    topo_strerror(err));
1625 			}
1626 
1627 		}
1628 	}
1629 
1630 	/* create the storage group */
1631 	if (topo_pgroup_create(tnode, &storage_pgroup, &err) != 0) {
1632 		topo_mod_dprintf(mod, "ses_set_expander_props: "
1633 		    "create storage error %s\n", topo_strerror(err));
1634 		goto error;
1635 	} else {
1636 		/* set the SAS address prop out of expander element status. */
1637 		if (topo_prop_set_string(tnode, TOPO_PGROUP_STORAGE,
1638 		    TOPO_PROP_SAS_ADDR, TOPO_PROP_IMMUTABLE, sasaddr_str,
1639 		    &err) != 0) {
1640 			topo_mod_dprintf(mod, "ses_set_expander_props: "
1641 			    "set %S error %s\n", TOPO_PROP_SAS_ADDR,
1642 			    topo_strerror(err));
1643 		}
1644 
1645 		/* Get the phy information for the expander */
1646 		if (nvlist_lookup_nvlist_array(props, SES_SAS_PROP_PHYS,
1647 		    &phylist, &pcount) != 0) {
1648 			topo_mod_dprintf(mod,
1649 			    "Failed to get prop %s.", SES_SAS_PROP_PHYS);
1650 		} else {
1651 			/*
1652 			 * For each phy, get the connector element index and
1653 			 * stores into connector element index array.
1654 			 */
1655 			*phycount = pcount;
1656 			for (i = 0; i < pcount; i++) {
1657 				if (nvlist_lookup_uint64(phylist[i],
1658 				    SES_PROP_CE_IDX, &connidx) == 0) {
1659 					if (connidx != 0xff) {
1660 						connlist[i] = connidx;
1661 					} else {
1662 						connlist[i] = -1;
1663 					}
1664 				} else {
1665 					/* Fail to get the index. set to -1. */
1666 					connlist[i] = -1;
1667 				}
1668 			}
1669 
1670 			/* set the phy count prop of the expander. */
1671 			if (topo_prop_set_uint64(tnode, TOPO_PGROUP_STORAGE,
1672 			    TOPO_PROP_PHY_COUNT, TOPO_PROP_IMMUTABLE, pcount,
1673 			    &err) != 0) {
1674 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1675 				    "set %S error %s\n", TOPO_PROP_PHY_COUNT,
1676 				    topo_strerror(err));
1677 			}
1678 
1679 			/*
1680 			 * set the connector element index of
1681 			 * the expander phys.
1682 			 */
1683 		}
1684 
1685 		/* populate other misc storage group properties */
1686 		if (found) {
1687 			if (dnode->ddn_mfg && (topo_prop_set_string(tnode,
1688 			    TOPO_PGROUP_STORAGE, TOPO_STORAGE_MANUFACTURER,
1689 			    TOPO_PROP_IMMUTABLE, dnode->ddn_mfg, &err) != 0)) {
1690 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1691 				    "set mfg error %s\n", topo_strerror(err));
1692 			}
1693 
1694 			if (dnode->ddn_model && (topo_prop_set_string(tnode,
1695 			    TOPO_PGROUP_STORAGE, TOPO_STORAGE_MODEL,
1696 			    TOPO_PROP_IMMUTABLE,
1697 			    dnode->ddn_model, &err) != 0)) {
1698 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1699 				    "set model error %s\n", topo_strerror(err));
1700 			}
1701 
1702 			if (dnode->ddn_serial && (topo_prop_set_string(tnode,
1703 			    TOPO_PGROUP_STORAGE, TOPO_STORAGE_SERIAL_NUM,
1704 			    TOPO_PROP_IMMUTABLE,
1705 			    dnode->ddn_serial, &err) != 0)) {
1706 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1707 				    "set serial error %s\n",
1708 				    topo_strerror(err));
1709 			}
1710 
1711 			if (dnode->ddn_firm && (topo_prop_set_string(tnode,
1712 			    TOPO_PGROUP_STORAGE,
1713 			    TOPO_STORAGE_FIRMWARE_REV, TOPO_PROP_IMMUTABLE,
1714 			    dnode->ddn_firm, &err) != 0)) {
1715 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1716 				    "set firm error %s\n", topo_strerror(err));
1717 			}
1718 		}
1719 	}
1720 
1721 	return (0);
1722 
1723 error:
1724 	nvlist_free(auth);
1725 	nvlist_free(fmri);
1726 	return (-1);
1727 }
1728 
1729 /*
1730  * Create SAS expander specific props.
1731  */
1732 /*ARGSUSED*/
1733 static int
1734 ses_set_connector_props(ses_enum_data_t *sdp, ses_enum_node_t *snp,
1735     tnode_t *tnode, int64_t phy_mask)
1736 {
1737 	ses_node_t *np = snp->sen_node;
1738 	topo_mod_t *mod = sdp->sed_mod;
1739 	nvlist_t *props;
1740 	int err, i;
1741 	uint64_t conntype;
1742 	char phymask_str[17], *conntype_str;
1743 	boolean_t   found;
1744 
1745 	props = ses_node_props(np);
1746 
1747 	/*
1748 	 * convert phy mask to string.
1749 	 */
1750 	(void) snprintf(phymask_str, 17, "%llx", phy_mask);
1751 
1752 	/* create the storage group */
1753 	if (topo_pgroup_create(tnode, &storage_pgroup, &err) != 0) {
1754 		topo_mod_dprintf(mod, "ses_set_expander_props: "
1755 		    "create storage error %s\n", topo_strerror(err));
1756 		return (-1);
1757 	} else {
1758 		/* set the SAS address prop of the expander. */
1759 		if (topo_prop_set_string(tnode, TOPO_PGROUP_STORAGE,
1760 		    TOPO_STORAGE_SAS_PHY_MASK, TOPO_PROP_IMMUTABLE,
1761 		    phymask_str, &err) != 0) {
1762 			topo_mod_dprintf(mod, "ses_set_expander_props: "
1763 			    "set %S error %s\n", TOPO_STORAGE_SAS_PHY_MASK,
1764 			    topo_strerror(err));
1765 		}
1766 
1767 		/* Get the connector type information for the expander */
1768 		if (nvlist_lookup_uint64(props,
1769 		    SES_SC_PROP_CONNECTOR_TYPE, &conntype) != 0) {
1770 			topo_mod_dprintf(mod, "Failed to get prop %s.",
1771 			    TOPO_STORAGE_SAS_PHY_MASK);
1772 		} else {
1773 			found = B_FALSE;
1774 			for (i = 0; ; i++) {
1775 				if (sas_connector_type_list[i].sct_type ==
1776 				    SAS_CONNECTOR_TYPE_CODE_NOT_DEFINED) {
1777 					break;
1778 				}
1779 				if (sas_connector_type_list[i].sct_type ==
1780 				    conntype) {
1781 					conntype_str =
1782 					    sas_connector_type_list[i].sct_name;
1783 					found = B_TRUE;
1784 					break;
1785 				}
1786 			}
1787 
1788 			if (!found) {
1789 				if (conntype <
1790 				    SAS_CONNECTOR_TYPE_CODE_NOT_DEFINED) {
1791 					conntype_str =
1792 					    SAS_CONNECTOR_TYPE_RESERVED;
1793 				} else {
1794 					conntype_str =
1795 					    SAS_CONNECTOR_TYPE_NOT_DEFINED;
1796 				}
1797 			}
1798 
1799 			/* set the phy count prop of the expander. */
1800 			if (topo_prop_set_string(tnode, TOPO_PGROUP_STORAGE,
1801 			    TOPO_STORAGE_SAS_CONNECTOR_TYPE,
1802 			    TOPO_PROP_IMMUTABLE, conntype_str, &err) != 0) {
1803 				topo_mod_dprintf(mod, "ses_set_expander_props: "
1804 				    "set %S error %s\n", TOPO_PROP_PHY_COUNT,
1805 				    topo_strerror(err));
1806 			}
1807 		}
1808 	}
1809 
1810 	return (0);
1811 }
1812 
1813 /*
1814  * Instantiate SAS expander nodes for a given ESC Electronics node(controller)
1815  * nodes.
1816  */
1817 /*ARGSUSED*/
1818 static int
1819 ses_create_esc_sasspecific(ses_enum_data_t *sdp, ses_enum_node_t *snp,
1820     tnode_t *pnode, ses_enum_chassis_t *cp,
1821     boolean_t dorange)
1822 {
1823 	topo_mod_t *mod = sdp->sed_mod;
1824 	tnode_t	*exptn, *contn;
1825 	boolean_t found;
1826 	sas_connector_phy_data_t connectors[64] = {NULL};
1827 	uint64_t max;
1828 	ses_enum_node_t *ctlsnp, *xsnp, *consnp;
1829 	ses_node_t *np = snp->sen_node;
1830 	nvlist_t *props, *psprops;
1831 	uint64_t index, psindex, conindex, psstatus, i, j, count;
1832 	int64_t cidxlist[256] = {NULL};
1833 	int phycount;
1834 
1835 	props = ses_node_props(np);
1836 
1837 	if (nvlist_lookup_uint64(props, SES_PROP_ELEMENT_ONLY_INDEX,
1838 	    &index) != 0)
1839 		return (-1);
1840 
1841 	/*
1842 	 * For SES constroller node, check to see if there are
1843 	 * associated SAS expanders.
1844 	 */
1845 	found = B_FALSE;
1846 	max = 0;
1847 	for (ctlsnp = topo_list_next(&cp->sec_nodes); ctlsnp != NULL;
1848 	    ctlsnp = topo_list_next(ctlsnp)) {
1849 		if (ctlsnp->sen_type == SES_ET_SAS_EXPANDER) {
1850 			found = B_TRUE;
1851 			if (ctlsnp->sen_instance > max)
1852 				max = ctlsnp->sen_instance;
1853 		}
1854 	}
1855 
1856 	/*
1857 	 * No SAS expander found notthing to process.
1858 	 */
1859 	if (!found)
1860 		return (0);
1861 
1862 	topo_mod_dprintf(mod, "%s Controller %d: creating "
1863 	    "%llu %s nodes", cp->sec_csn, index, max + 1, SASEXPANDER);
1864 
1865 	/*
1866 	 * The max number represent the number of elements
1867 	 * deducted from the highest SES_PROP_ELEMENT_CLASS_INDEX
1868 	 * of SET_ET_SAS_EXPANDER type element.
1869 	 *
1870 	 * There may be multiple ESC Electronics element(controllers)
1871 	 * within JBOD(typicall two for redundancy) and SAS expander
1872 	 * elements are associated with only one of them.  We are
1873 	 * still creating the range based max number here.
1874 	 * That will cover the case that all expanders are associated
1875 	 * with one SES controller.
1876 	 */
1877 	if (dorange && topo_node_range_create(mod, pnode,
1878 	    SASEXPANDER, 0, max) != 0) {
1879 		topo_mod_dprintf(mod,
1880 		    "topo_node_create_range() failed: %s",
1881 		    topo_mod_errmsg(mod));
1882 		return (-1);
1883 	}
1884 
1885 	/*
1886 	 * Search exapnders with the parent index matching with
1887 	 * ESC Electronics element index.
1888 	 * Note the index used here is a global index across
1889 	 * SES elements.
1890 	 */
1891 	for (xsnp = topo_list_next(&cp->sec_nodes); xsnp != NULL;
1892 	    xsnp = topo_list_next(xsnp)) {
1893 		if (xsnp->sen_type == SES_ET_SAS_EXPANDER) {
1894 			/*
1895 			 * get the parent ESC controller.
1896 			 */
1897 			psprops = ses_node_props(xsnp->sen_node);
1898 			if (nvlist_lookup_uint64(psprops,
1899 			    SES_PROP_STATUS_CODE, &psstatus) == 0) {
1900 				if (psstatus == SES_ESC_NOT_INSTALLED) {
1901 					/*
1902 					 * Not installed.
1903 					 * Don't create a ndoe.
1904 					 */
1905 					continue;
1906 				}
1907 			} else {
1908 				/*
1909 				 * The element should have status code.
1910 				 * If not there is no way to find
1911 				 * out if the expander element exist or
1912 				 * not.
1913 				 */
1914 				continue;
1915 			}
1916 
1917 			/* Get the physical parent index to compare. */
1918 			if (nvlist_lookup_uint64(psprops,
1919 			    LIBSES_PROP_PHYS_PARENT, &psindex) == 0) {
1920 				if (index == psindex) {
1921 		/* indentation moved forward */
1922 		/*
1923 		 * Handle basic node information of SAS expander
1924 		 * element - binding to parent node and
1925 		 * allocating FMRI...
1926 		 */
1927 		if (ses_create_generic(sdp, xsnp, pnode, pnode, SASEXPANDER,
1928 		    "SAS-EXPANDER", &exptn) != 0)
1929 			continue;
1930 		/*
1931 		 * Now handle SAS expander unique portion of node creation.
1932 		 * The max nubmer of the phy count is 256 since SES-2
1933 		 * defines as 1 byte field.  The cidxlist has the same
1934 		 * number of elements.
1935 		 *
1936 		 * We use size 64 array to store the connectors.
1937 		 * Typically a connectors associated with 4 phys so that
1938 		 * matches with the max number of connecters associated
1939 		 * with an expander.
1940 		 * The phy count goes up to 38 for Sun supported
1941 		 * JBOD.
1942 		 */
1943 		(void) memset(cidxlist, 0, sizeof (int64_t) * 64);
1944 		if (ses_set_expander_props(sdp, xsnp, pnode, exptn, &phycount,
1945 		    cidxlist) != 0) {
1946 			/*
1947 			 * error on getting specific prop failed.
1948 			 * continue on.  Note that the node is
1949 			 * left bound.
1950 			 */
1951 			continue;
1952 		}
1953 
1954 		/*
1955 		 * count represetns the number of connectors discovered so far.
1956 		 */
1957 		count = 0;
1958 		(void) memset(connectors, 0,
1959 		    sizeof (sas_connector_phy_data_t) * 64);
1960 		for (i = 0; i < phycount; i++) {
1961 			if (cidxlist[i] != -1) {
1962 				/* connector index is valid. */
1963 				for (j = 0; j < count; j++) {
1964 					if (connectors[j].scpd_index ==
1965 					    cidxlist[i]) {
1966 						/*
1967 						 * Just update phy mask.
1968 						 * The postion for connector
1969 						 * index lists(cidxlist index)
1970 						 * is set.
1971 						 */
1972 						connectors[j].scpd_pm =
1973 						    connectors[j].scpd_pm |
1974 						    (1ULL << i);
1975 						break;
1976 					}
1977 				}
1978 				/*
1979 				 * If j and count matche a  new connector
1980 				 * index is found.
1981 				 */
1982 				if (j == count) {
1983 					/* add a new index and phy mask. */
1984 					connectors[count].scpd_index =
1985 					    cidxlist[i];
1986 					connectors[count].scpd_pm =
1987 					    connectors[count].scpd_pm |
1988 					    (1ULL << i);
1989 					count++;
1990 				}
1991 			}
1992 		}
1993 
1994 		/*
1995 		 * create range for the connector nodes.
1996 		 * The class index of the ses connector element
1997 		 * is set as the instance nubmer for the node.
1998 		 * Even though one expander may not have all connectors
1999 		 * are associated with we are creating the range with
2000 		 * max possible instance number.
2001 		 */
2002 		found = B_FALSE;
2003 		max = 0;
2004 		for (consnp = topo_list_next(&cp->sec_nodes);
2005 		    consnp != NULL; consnp = topo_list_next(consnp)) {
2006 			if (consnp->sen_type == SES_ET_SAS_CONNECTOR) {
2007 				psprops = ses_node_props(consnp->sen_node);
2008 				found = B_TRUE;
2009 				if (consnp->sen_instance > max)
2010 					max = consnp->sen_instance;
2011 			}
2012 		}
2013 
2014 		/*
2015 		 * No SAS connector found nothing to process.
2016 		 */
2017 		if (!found)
2018 			return (0);
2019 
2020 		if (dorange && topo_node_range_create(mod, exptn,
2021 		    RECEPTACLE, 0, max) != 0) {
2022 			topo_mod_dprintf(mod,
2023 			    "topo_node_create_range() failed: %s",
2024 			    topo_mod_errmsg(mod));
2025 			return (-1);
2026 		}
2027 
2028 		/* search matching connector element using the index. */
2029 		for (i = 0; i < count; i++) {
2030 			found = B_FALSE;
2031 			for (consnp = topo_list_next(&cp->sec_nodes);
2032 			    consnp != NULL; consnp = topo_list_next(consnp)) {
2033 				if (consnp->sen_type == SES_ET_SAS_CONNECTOR) {
2034 					psprops = ses_node_props(
2035 					    consnp->sen_node);
2036 					/*
2037 					 * Get the physical parent index to
2038 					 * compare.
2039 					 * The connector elements are children
2040 					 * of ESC Electronics element even
2041 					 * though we enumerate them under
2042 					 * an expander in libtopo.
2043 					 */
2044 					if (nvlist_lookup_uint64(psprops,
2045 					    SES_PROP_ELEMENT_ONLY_INDEX,
2046 					    &conindex) == 0) {
2047 						if (conindex ==
2048 						    connectors[i].scpd_index) {
2049 							found = B_TRUE;
2050 							break;
2051 						}
2052 					}
2053 				}
2054 			}
2055 
2056 			/* now create a libtopo node. */
2057 			if (found) {
2058 				/* Create generic props. */
2059 				if (ses_create_generic(sdp, consnp, exptn,
2060 				    topo_node_parent(exptn),
2061 				    RECEPTACLE, "RECEPTACLE", &contn) !=
2062 				    0) {
2063 					continue;
2064 				}
2065 				/* Create connector specific props. */
2066 				if (ses_set_connector_props(sdp, consnp,
2067 				    contn, connectors[i].scpd_pm) != 0) {
2068 					continue;
2069 				}
2070 			}
2071 		}
2072 		/* end indentation change */
2073 				}
2074 			}
2075 		}
2076 	}
2077 
2078 	return (0);
2079 }
2080 
2081 /*
2082  * Instantiate any protocol specific portion of a node.
2083  */
2084 /*ARGSUSED*/
2085 static int
2086 ses_create_protocol_specific(ses_enum_data_t *sdp, ses_enum_node_t *snp,
2087     tnode_t *pnode, uint64_t type, ses_enum_chassis_t *cp,
2088     boolean_t dorange)
2089 {
2090 
2091 	if (type == SES_ET_ESC_ELECTRONICS) {
2092 		/* create SAS specific children(expanders and connectors. */
2093 		return (ses_create_esc_sasspecific(sdp, snp, pnode, cp,
2094 		    dorange));
2095 	}
2096 
2097 	return (0);
2098 }
2099 
2100 /*
2101  * Instantiate any children of a given type.
2102  */
2103 static int
2104 ses_create_children(ses_enum_data_t *sdp, tnode_t *pnode, uint64_t type,
2105     const char *nodename, const char *defaultlabel, ses_enum_chassis_t *cp,
2106     boolean_t dorange)
2107 {
2108 	topo_mod_t *mod = sdp->sed_mod;
2109 	boolean_t found;
2110 	uint64_t max;
2111 	ses_enum_node_t *snp;
2112 	tnode_t	*tn;
2113 
2114 	/*
2115 	 * First go through and count how many matching nodes we have.
2116 	 */
2117 	max = 0;
2118 	found = B_FALSE;
2119 	for (snp = topo_list_next(&cp->sec_nodes); snp != NULL;
2120 	    snp = topo_list_next(snp)) {
2121 		if (snp->sen_type == type) {
2122 			found = B_TRUE;
2123 			if (snp->sen_instance > max)
2124 				max = snp->sen_instance;
2125 		}
2126 	}
2127 
2128 	/*
2129 	 * No enclosure should export both DEVICE and ARRAY_DEVICE elements.
2130 	 * Since we map both of these to 'disk', if an enclosure does this, we
2131 	 * just ignore the array elements.
2132 	 */
2133 	if (!found ||
2134 	    (type == SES_ET_ARRAY_DEVICE && cp->sec_hasdev))
2135 		return (0);
2136 
2137 	topo_mod_dprintf(mod, "%s: creating %llu %s nodes",
2138 	    cp->sec_csn, max + 1, nodename);
2139 
2140 	if (dorange && topo_node_range_create(mod, pnode,
2141 	    nodename, 0, max) != 0) {
2142 		topo_mod_dprintf(mod,
2143 		    "topo_node_create_range() failed: %s",
2144 		    topo_mod_errmsg(mod));
2145 		return (-1);
2146 	}
2147 
2148 	for (snp = topo_list_next(&cp->sec_nodes); snp != NULL;
2149 	    snp = topo_list_next(snp)) {
2150 		if (snp->sen_type == type) {
2151 			/*
2152 			 * With flat layout of ses nodes there is no
2153 			 * way to find out the direct FRU for a node.
2154 			 * Passing NULL for fru topo node.  Note that
2155 			 * ses_create_children_from_phys_tree() provides
2156 			 * the actual direct FRU for a node.
2157 			 */
2158 			if (ses_create_generic(sdp, snp, pnode, NULL,
2159 			    nodename, defaultlabel, &tn) != 0)
2160 				return (-1);
2161 			/*
2162 			 * For some SES element there may be protocol specific
2163 			 * information to process.   Here we are processing
2164 			 * the association between enclosure controller and
2165 			 * SAS expanders.
2166 			 */
2167 			if (type == SES_ET_ESC_ELECTRONICS) {
2168 				/* create SAS expander node */
2169 				if (ses_create_protocol_specific(sdp, snp,
2170 				    tn, type, cp, dorange) != 0) {
2171 					return (-1);
2172 				}
2173 			}
2174 
2175 		}
2176 	}
2177 
2178 	return (0);
2179 }
2180 
2181 /*
2182  * Instantiate a new subchassis instance in the topology.
2183  */
2184 static int
2185 ses_create_subchassis(ses_enum_data_t *sdp, tnode_t *pnode,
2186     ses_enum_chassis_t *scp)
2187 {
2188 	topo_mod_t *mod = sdp->sed_mod;
2189 	tnode_t *tn;
2190 	nvlist_t *props;
2191 	nvlist_t *auth = NULL, *fmri = NULL;
2192 	uint64_t instance = scp->sec_instance;
2193 	char *desc;
2194 	char label[128];
2195 	char **paths;
2196 	int i, err;
2197 	ses_enum_target_t *stp;
2198 	int ret = -1;
2199 
2200 	/*
2201 	 * Copy authority information from parent enclosure node
2202 	 */
2203 	if ((auth = topo_mod_auth(mod, pnode)) == NULL)
2204 		goto error;
2205 
2206 	/*
2207 	 * Record the subchassis serial number in the FMRI.
2208 	 * For now, we assume that logical id is the subchassis serial number.
2209 	 * If this assumption changes in future, then the following
2210 	 * piece of code will need to be updated via an RFE.
2211 	 */
2212 	if ((fmri = topo_mod_hcfmri(mod, pnode, FM_HC_SCHEME_VERSION,
2213 	    SUBCHASSIS, (topo_instance_t)instance, NULL, auth, NULL, NULL,
2214 	    NULL)) == NULL) {
2215 		topo_mod_dprintf(mod, "topo_mod_hcfmri() failed: %s",
2216 		    topo_mod_errmsg(mod));
2217 		goto error;
2218 	}
2219 
2220 	if ((tn = topo_node_bind(mod, pnode, SUBCHASSIS,
2221 	    instance, fmri)) == NULL) {
2222 		topo_mod_dprintf(mod, "topo_node_bind() failed: %s",
2223 		    topo_mod_errmsg(mod));
2224 		goto error;
2225 	}
2226 
2227 	props = ses_node_props(scp->sec_enclosure);
2228 
2229 	/*
2230 	 * Look for the subchassis label in the following order:
2231 	 *	<ses-description>
2232 	 *	<ses-class-description> <instance>
2233 	 *	<default-type-label> <instance>
2234 	 *
2235 	 * For subchassis, the default label is "SUBCHASSIS"
2236 	 */
2237 	if (nvlist_lookup_string(props, SES_PROP_DESCRIPTION, &desc) != 0 ||
2238 	    desc[0] == '\0') {
2239 		if (nvlist_lookup_string(props, SES_PROP_CLASS_DESCRIPTION,
2240 		    &desc) == 0 && desc[0] != '\0')
2241 			(void) snprintf(label, sizeof (label), "%s %llu", desc,
2242 			    instance);
2243 		else
2244 			(void) snprintf(label, sizeof (label),
2245 			    "SUBCHASSIS %llu", instance);
2246 		desc = label;
2247 	}
2248 
2249 	if (topo_node_label_set(tn, desc, &err) != 0)
2250 		goto error;
2251 
2252 	if (ses_set_standard_props(mod, NULL, tn, NULL,
2253 	    ses_node_id(scp->sec_enclosure), scp->sec_target->set_devpath) != 0)
2254 		goto error;
2255 
2256 	/*
2257 	 * Set the 'chassis-type' property for this subchassis.  This is either
2258 	 * 'ses-class-description' or 'subchassis'.
2259 	 */
2260 	if (nvlist_lookup_string(props, SES_PROP_CLASS_DESCRIPTION, &desc) != 0)
2261 		desc = "subchassis";
2262 
2263 	if (topo_prop_set_string(tn, TOPO_PGROUP_SES,
2264 	    TOPO_PROP_CHASSIS_TYPE, TOPO_PROP_IMMUTABLE, desc, &err) != 0) {
2265 		topo_mod_dprintf(mod, "failed to create property %s: %s\n",
2266 		    TOPO_PROP_CHASSIS_TYPE, topo_strerror(err));
2267 		goto error;
2268 	}
2269 
2270 	/*
2271 	 * For enclosures, we want to include all possible targets (for upgrade
2272 	 * purposes).
2273 	 */
2274 	for (i = 0, stp = topo_list_next(&scp->sec_targets); stp != NULL;
2275 	    stp = topo_list_next(stp), i++)
2276 		;
2277 
2278 	verify(i != 0);
2279 	paths = alloca(i * sizeof (char *));
2280 
2281 	for (i = 0, stp = topo_list_next(&scp->sec_targets); stp != NULL;
2282 	    stp = topo_list_next(stp), i++)
2283 		paths[i] = stp->set_devpath;
2284 
2285 	if (topo_prop_set_string_array(tn, TOPO_PGROUP_SES,
2286 	    TOPO_PROP_PATHS, TOPO_PROP_IMMUTABLE, (const char **)paths,
2287 	    i, &err) != 0) {
2288 		topo_mod_dprintf(mod, "failed to create property %s: %s\n",
2289 		    TOPO_PROP_PATHS, topo_strerror(err));
2290 		goto error;
2291 	}
2292 
2293 	if (topo_method_register(mod, tn, ses_enclosure_methods) != 0) {
2294 		topo_mod_dprintf(mod, "topo_method_register() failed: %s",
2295 		    topo_mod_errmsg(mod));
2296 		goto error;
2297 	}
2298 
2299 	/*
2300 	 * Create the nodes for controllers and bays.
2301 	 */
2302 	if (ses_create_children(sdp, tn, SES_ET_ESC_ELECTRONICS,
2303 	    CONTROLLER, "CONTROLLER", scp, B_TRUE) != 0 ||
2304 	    ses_create_children(sdp, tn, SES_ET_DEVICE,
2305 	    BAY, "BAY", scp, B_TRUE) != 0 ||
2306 	    ses_create_children(sdp, tn, SES_ET_ARRAY_DEVICE,
2307 	    BAY, "BAY", scp, B_TRUE) != 0)
2308 		goto error;
2309 
2310 	ret = 0;
2311 
2312 error:
2313 	nvlist_free(auth);
2314 	nvlist_free(fmri);
2315 	return (ret);
2316 }
2317 
2318 /*
2319  * Function we use to insert a node.
2320  */
2321 static int
2322 ses_phys_tree_insert(topo_mod_t *mod, ses_phys_tree_t **sproot,
2323     ses_phys_tree_t *child)
2324 {
2325 	uint64_t ppindex, eindex, pindex;
2326 	ses_phys_tree_t *node_ptr;
2327 	int ret = 0;
2328 
2329 	assert(sproot != NULL);
2330 	assert(child != NULL);
2331 
2332 	if (*sproot == NULL) {
2333 		*sproot = child;
2334 		return (0);
2335 	}
2336 
2337 	pindex = child->spt_pindex;
2338 	ppindex = (*sproot)->spt_pindex;
2339 	eindex = (*sproot)->spt_eonlyindex;
2340 
2341 	/*
2342 	 * If the element only index of the root is same as the physical
2343 	 * parent index of a node to be added, add the node as a child of
2344 	 * the current root.
2345 	 */
2346 	if (eindex == pindex) {
2347 		(void) ses_phys_tree_insert(mod, &(*sproot)->spt_child, child);
2348 		child->spt_parent = *sproot;
2349 	} else if (ppindex == pindex) {
2350 		/*
2351 		 * if the physical parent of the current root and the child
2352 		 * is same, then this should be a sibling node.
2353 		 * Siblings can be different element types and arrange
2354 		 * them by group.
2355 		 */
2356 		if ((*sproot)->spt_senumnode->sen_type ==
2357 		    child->spt_senumnode->sen_type) {
2358 			child->spt_sibling = *sproot;
2359 			*sproot = child;
2360 		} else {
2361 			/* add a node in front of matching element type. */
2362 			node_ptr = *sproot;
2363 			while (node_ptr->spt_sibling != NULL) {
2364 				if (node_ptr->spt_sibling->
2365 				    spt_senumnode->sen_type ==
2366 				    child->spt_senumnode->sen_type) {
2367 					child->spt_sibling =
2368 					    node_ptr->spt_sibling;
2369 					node_ptr->spt_sibling = child;
2370 					break;
2371 				}
2372 				node_ptr = node_ptr->spt_sibling;
2373 			}
2374 			/* no matching.  Add the child at the end. */
2375 			if (node_ptr->spt_sibling == NULL) {
2376 				node_ptr->spt_sibling = child;
2377 			}
2378 		}
2379 		child->spt_parent = (*sproot)->spt_parent;
2380 	} else {
2381 		/*
2382 		 * The root and the node is not directly related.
2383 		 * Try to insert to the child sub-tree first and then try to
2384 		 * insert to the sibling sub-trees.  If fails for both
2385 		 * the caller will retry insertion later.
2386 		 */
2387 		if ((*sproot)->spt_child) {
2388 			ret = ses_phys_tree_insert(mod, &(*sproot)->spt_child,
2389 			    child);
2390 		}
2391 		if ((*sproot)->spt_child == NULL || ret != 0) {
2392 			if ((*sproot)->spt_sibling) {
2393 				ret = ses_phys_tree_insert(mod,
2394 				    &(*sproot)->spt_sibling, child);
2395 			} else {
2396 				ret = 1;
2397 			}
2398 		}
2399 		return (ret);
2400 	}
2401 	return (0);
2402 }
2403 
2404 /*
2405  * Construct tree view of ses elements through parent phyiscal element index.
2406  * The root of tree is already constructed using the enclosure element.
2407  */
2408 static int
2409 ses_construct_phys_tree(ses_enum_data_t *sdp, ses_enum_chassis_t *cp,
2410     ses_phys_tree_t *sproot)
2411 {
2412 	ses_enum_node_t *snp;
2413 	ses_phys_tree_t	*child;
2414 	ses_phys_tree_t	*u_watch = NULL;
2415 	ses_phys_tree_t	*u_head = NULL;
2416 	ses_phys_tree_t	*u_tail = NULL;
2417 	int u_inserted = 0, u_left = 0;
2418 	nvlist_t *props;
2419 	topo_mod_t *mod = sdp->sed_mod;
2420 
2421 	for (snp = topo_list_next(&cp->sec_nodes); snp != NULL;
2422 	    snp = topo_list_next(snp)) {
2423 		if ((child = topo_mod_zalloc(mod,
2424 		    sizeof (ses_phys_tree_t))) == NULL) {
2425 			topo_mod_dprintf(mod,
2426 			    "failed to allocate root.");
2427 			return (-1);
2428 		}
2429 		child->spt_snode = snp->sen_node;
2430 		props = ses_node_props(snp->sen_node);
2431 		if (nvlist_lookup_uint64(props,
2432 		    LIBSES_PROP_PHYS_PARENT, &child->spt_pindex) != 0) {
2433 			/*
2434 			 * the prop should exist. continue to see if
2435 			 * we can build a partial tree with other elements.
2436 			 */
2437 			topo_mod_dprintf(mod,
2438 			    "ses_construct_phys_tree(): Failed to find prop %s "
2439 			    "on ses element type %d and instance %d "
2440 			    "(CSN %s).", LIBSES_PROP_PHYS_PARENT,
2441 			    snp->sen_type, snp->sen_instance, cp->sec_csn);
2442 			topo_mod_free(mod, child, sizeof (ses_phys_tree_t));
2443 			continue;
2444 		} else {
2445 			if (nvlist_lookup_boolean_value(props,
2446 			    LIBSES_PROP_FRU, &child->spt_isfru) != 0) {
2447 				topo_mod_dprintf(mod,
2448 				    "ses_construct_phys_tree(): Failed to "
2449 				    "find prop %s on ses element type %d "
2450 				    "and instance %d (CSN %s).",
2451 				    LIBSES_PROP_FRU,
2452 				    snp->sen_type, snp->sen_instance,
2453 				    cp->sec_csn);
2454 				/*
2455 				 * Ignore if the prop doesn't exist.
2456 				 * Note that the enclosure itself should be
2457 				 * a FRU so if no FRU found the enclosure FRU
2458 				 * can be a direct FRU.
2459 				 */
2460 			}
2461 			verify(nvlist_lookup_uint64(props,
2462 			    SES_PROP_ELEMENT_ONLY_INDEX,
2463 			    &child->spt_eonlyindex) == 0);
2464 			verify(nvlist_lookup_uint64(props,
2465 			    SES_PROP_ELEMENT_CLASS_INDEX,
2466 			    &child->spt_cindex) == 0);
2467 		}
2468 		child->spt_senumnode = snp;
2469 		if (ses_phys_tree_insert(mod, &sproot, child) != 0) {
2470 			/* collect unresolved element to process later. */
2471 			if (u_head == NULL) {
2472 				u_head = child;
2473 				u_tail = child;
2474 			} else {
2475 				child->spt_sibling = u_head;
2476 				u_head = child;
2477 			}
2478 		}
2479 	}
2480 
2481 	/*
2482 	 * The parent of a child node may not be inserted yet.
2483 	 * Trying to insert the child until no child is left or
2484 	 * no child is not added further.  For the latter
2485 	 * the hierarchical relationship between elements
2486 	 * should be checked through SUNW,FRUID page.
2487 	 * u_watch is a watch dog to check the prgress of unresolved
2488 	 * node.
2489 	 */
2490 	u_watch = u_tail;
2491 	while (u_head) {
2492 		child = u_head;
2493 		u_head = u_head->spt_sibling;
2494 		if (u_head == NULL)
2495 			u_tail = NULL;
2496 		child->spt_sibling = NULL;
2497 		if (ses_phys_tree_insert(mod, &sproot, child) != 0) {
2498 			u_tail->spt_sibling = child;
2499 			u_tail = child;
2500 			if (child == u_watch) {
2501 				/*
2502 				 * We just scanned one round for the
2503 				 * unresolved list. Check to see whether we
2504 				 * have nodes inserted, if none, we should
2505 				 * break in case of an indefinite loop.
2506 				 */
2507 				if (u_inserted == 0) {
2508 					/*
2509 					 * Indicate there is unhandled node.
2510 					 * Chain free the whole unsolved
2511 					 * list here.
2512 					 */
2513 					u_left++;
2514 					break;
2515 				} else {
2516 					u_inserted = 0;
2517 					u_watch = u_tail;
2518 				}
2519 			}
2520 		} else {
2521 			/*
2522 			 * We just inserted one rpnode, increment the
2523 			 * unsolved_inserted counter. We will utilize this
2524 			 * counter to detect an indefinite insertion loop.
2525 			 */
2526 			u_inserted++;
2527 			if (child == u_watch) {
2528 				/*
2529 				 * watch dog node itself is inserted.
2530 				 * Set it to the tail and refresh the watching.
2531 				 */
2532 				u_watch = u_tail;
2533 				u_inserted = 0;
2534 				u_left = 0;
2535 			}
2536 		}
2537 	}
2538 
2539 	/* check if there is left out unresolved nodes. */
2540 	if (u_left) {
2541 		topo_mod_dprintf(mod, "ses_construct_phys_tree(): "
2542 		    "Failed to construct physical view of the following "
2543 		    "ses elements of Chassis CSN %s.", cp->sec_csn);
2544 		while (u_head) {
2545 			u_tail = u_head->spt_sibling;
2546 			topo_mod_dprintf(mod,
2547 			    "\telement type (%d) and instance (%d)",
2548 			    u_head->spt_senumnode->sen_type,
2549 			    u_head->spt_senumnode->sen_instance);
2550 			topo_mod_free(mod, u_head, sizeof (ses_phys_tree_t));
2551 			u_head = u_tail;
2552 		}
2553 		return (-1);
2554 	}
2555 
2556 	return (0);
2557 }
2558 
2559 /*
2560  * Free the whole phys tree.
2561  */
2562 static void ses_phys_tree_free(topo_mod_t *mod, ses_phys_tree_t *sproot)
2563 {
2564 	if (sproot == NULL)
2565 		return;
2566 
2567 	/* Free child tree. */
2568 	if (sproot->spt_child) {
2569 		ses_phys_tree_free(mod, sproot->spt_child);
2570 	}
2571 
2572 	/* Free sibling trees. */
2573 	if (sproot->spt_sibling) {
2574 		ses_phys_tree_free(mod, sproot->spt_sibling);
2575 	}
2576 
2577 	/* Free root node itself. */
2578 	topo_mod_free(mod, sproot, sizeof (ses_phys_tree_t));
2579 }
2580 
2581 /*
2582  * Parses phys_enum_type table to get the index of the given type.
2583  */
2584 static boolean_t
2585 is_type_enumerated(ses_phys_tree_t *node, int *index)
2586 {
2587 	int i;
2588 
2589 	for (i = 0; i < N_PHYS_ENUM_TYPES; i++) {
2590 		if (node->spt_senumnode->sen_type ==
2591 		    phys_enum_type_list[i].pet_type) {
2592 			*index = i;
2593 			return (B_TRUE);
2594 		}
2595 	}
2596 	return (B_FALSE);
2597 }
2598 
2599 /*
2600  * Recusrive routine for top-down enumeration of the tree.
2601  */
2602 static int
2603 ses_enumerate_node(ses_enum_data_t *sdp, tnode_t *pnode, ses_enum_chassis_t *cp,
2604     ses_phys_tree_t *parent, int mrange[])
2605 {
2606 	topo_mod_t *mod = sdp->sed_mod;
2607 	ses_phys_tree_t *child = NULL;
2608 	int i, ret = 0, ret_ch;
2609 	uint64_t prevtype = SES_ET_UNSPECIFIED;
2610 	ses_phys_tree_t *dirfru = NULL;
2611 	tnode_t *tn = NULL, *frutn = NULL;
2612 
2613 	if (parent == NULL) {
2614 		return (0);
2615 	}
2616 
2617 	for (child = parent->spt_child; child != NULL;
2618 	    child = child->spt_sibling) {
2619 		if (is_type_enumerated(child, &i)) {
2620 			if (prevtype != phys_enum_type_list[i].pet_type) {
2621 				/* check if range needs to be created. */
2622 				if (phys_enum_type_list[i].pet_dorange &&
2623 				    topo_node_range_create(mod, pnode,
2624 				    phys_enum_type_list[i].pet_nodename, 0,
2625 				    mrange[i]) != 0) {
2626 					topo_mod_dprintf(mod,
2627 					    "topo_node_create_range() failed: "
2628 					    "%s", topo_mod_errmsg(mod));
2629 					return (-1);
2630 				}
2631 				prevtype = phys_enum_type_list[i].pet_type;
2632 			}
2633 
2634 			if (!(child->spt_isfru)) {
2635 				for (dirfru = parent; dirfru != NULL;
2636 				    dirfru = dirfru->spt_parent) {
2637 					if (dirfru->spt_isfru) {
2638 						break;
2639 					}
2640 				}
2641 				/* found direct FRU node. */
2642 				if (dirfru) {
2643 					frutn = dirfru->spt_tnode;
2644 				} else {
2645 					frutn = NULL;
2646 				}
2647 			} else {
2648 				frutn = NULL;
2649 			}
2650 
2651 			if (ses_create_generic(sdp, child->spt_senumnode,
2652 			    pnode, frutn, phys_enum_type_list[i].pet_nodename,
2653 			    phys_enum_type_list[i].pet_defaultlabel, &tn) != 0)
2654 				return (-1);
2655 
2656 			child->spt_tnode = tn;
2657 			/*
2658 			 * For some SES element there may be protocol specific
2659 			 * information to process.   Here we are processing
2660 			 * the association between enclosure controller and
2661 			 * SAS expanders.
2662 			 */
2663 			if (phys_enum_type_list[i].pet_type ==
2664 			    SES_ET_ESC_ELECTRONICS) {
2665 				/* create SAS expander node */
2666 				if (ses_create_protocol_specific(sdp,
2667 				    child->spt_senumnode, tn,
2668 				    phys_enum_type_list[i].pet_type,
2669 				    cp, phys_enum_type_list[i].pet_dorange) !=
2670 				    0) {
2671 					return (-1);
2672 				}
2673 			}
2674 		} else {
2675 			continue;
2676 		}
2677 		ret_ch = ses_enumerate_node(sdp, tn, cp, child, mrange);
2678 		if (ret_ch)
2679 			ret = ret_ch; /* there was an error and set the ret. */
2680 	}
2681 
2682 	return (ret);
2683 }
2684 
2685 /*
2686  * Instantiate types of nodes that are specified in the hierarchy
2687  * element type list.
2688  */
2689 static int
2690 ses_create_children_from_phys_tree(ses_enum_data_t *sdp, tnode_t *pnode,
2691     ses_enum_chassis_t *cp, ses_phys_tree_t *phys_tree)
2692 {
2693 	topo_mod_t *mod = sdp->sed_mod;
2694 	int mrange[N_PHYS_ENUM_TYPES] = { 0 };
2695 	ses_enum_node_t *snp;
2696 	int i, ret;
2697 
2698 	/*
2699 	 * First get max range for each type of element to be enumerated.
2700 	 */
2701 	for (i = 0; i < N_PHYS_ENUM_TYPES; i++) {
2702 		if (phys_enum_type_list[i].pet_dorange) {
2703 			for (snp = topo_list_next(&cp->sec_nodes); snp != NULL;
2704 			    snp = topo_list_next(snp)) {
2705 				if (snp->sen_type ==
2706 				    phys_enum_type_list[i].pet_type) {
2707 					if (snp->sen_instance > mrange[i])
2708 						mrange[i] =
2709 						    snp->sen_instance;
2710 				}
2711 			}
2712 		}
2713 	}
2714 
2715 	topo_mod_dprintf(mod, "%s: creating nodes from FRU hierarchy tree.",
2716 	    cp->sec_csn);
2717 
2718 	if ((ret = ses_enumerate_node(sdp, pnode, cp, phys_tree, mrange)) !=
2719 	    0) {
2720 		topo_mod_dprintf(mod,
2721 		    "ses_create_children_from_phys_tree() failed: ");
2722 		return (ret);
2723 	}
2724 
2725 	return (0);
2726 }
2727 
2728 /*
2729  * Instantiate a new chassis instance in the topology.
2730  */
2731 static int
2732 ses_create_chassis(ses_enum_data_t *sdp, tnode_t *pnode, ses_enum_chassis_t *cp)
2733 {
2734 	topo_mod_t *mod = sdp->sed_mod;
2735 	nvlist_t *props;
2736 	char *raw_manufacturer, *raw_model, *raw_revision;
2737 	char *manufacturer = NULL, *model = NULL, *product = NULL;
2738 	char *revision = NULL;
2739 	char *serial;
2740 	char **paths;
2741 	size_t prodlen;
2742 	tnode_t *tn;
2743 	nvlist_t *fmri = NULL, *auth = NULL;
2744 	int ret = -1;
2745 	ses_enum_node_t *snp;
2746 	ses_enum_target_t *stp;
2747 	ses_enum_chassis_t *scp;
2748 	int i, err;
2749 	uint64_t sc_count = 0, pindex;
2750 	ses_phys_tree_t	*sproot = NULL;
2751 	hrtime_t start;
2752 	hrtime_t end;
2753 	double duration;
2754 
2755 	/*
2756 	 * Ignore any internal enclosures.
2757 	 */
2758 	if (cp->sec_internal)
2759 		return (0);
2760 
2761 	/*
2762 	 * Check to see if there are any devices presennt in the chassis.  If
2763 	 * not, ignore the chassis alltogether.  This is most useful for
2764 	 * ignoring internal HBAs that present a SES target but don't actually
2765 	 * manage any of the devices.
2766 	 */
2767 	for (snp = topo_list_next(&cp->sec_nodes); snp != NULL;
2768 	    snp = topo_list_next(snp)) {
2769 		if (snp->sen_type == SES_ET_DEVICE ||
2770 		    snp->sen_type == SES_ET_ARRAY_DEVICE)
2771 			break;
2772 	}
2773 
2774 	if (snp == NULL)
2775 		return (0);
2776 
2777 	props = ses_node_props(cp->sec_enclosure);
2778 
2779 	/*
2780 	 * We use the following property mappings:
2781 	 *
2782 	 * 	manufacturer		vendor-id
2783 	 * 	model			product-id
2784 	 * 	serial-number		libses-chassis-serial
2785 	 */
2786 	verify(nvlist_lookup_string(props, SES_EN_PROP_VID,
2787 	    &raw_manufacturer) == 0);
2788 	verify(nvlist_lookup_string(props, SES_EN_PROP_PID, &raw_model) == 0);
2789 	verify(nvlist_lookup_string(props, SES_EN_PROP_REV,
2790 	    &raw_revision) == 0);
2791 	verify(nvlist_lookup_string(props, LIBSES_EN_PROP_CSN, &serial) == 0);
2792 
2793 	/*
2794 	 * To construct the authority information, we 'clean' each string by
2795 	 * removing any offensive characters and trimmming whitespace.  For the
2796 	 * 'product-id', we use a concatenation of 'manufacturer-model'.  We
2797 	 * also take the numerical serial number and convert it to a string.
2798 	 */
2799 	if ((manufacturer = disk_auth_clean(mod, raw_manufacturer)) == NULL ||
2800 	    (model = disk_auth_clean(mod, raw_model)) == NULL ||
2801 	    (revision = disk_auth_clean(mod, raw_revision)) == NULL) {
2802 		goto error;
2803 	}
2804 
2805 	prodlen = strlen(manufacturer) + strlen(model) + 2;
2806 	if ((product = topo_mod_alloc(mod, prodlen)) == NULL)
2807 		goto error;
2808 
2809 	(void) snprintf(product, prodlen, "%s-%s", manufacturer, model);
2810 
2811 	/*
2812 	 * Construct the topo node and bind it to our parent.
2813 	 */
2814 	if (topo_mod_nvalloc(mod, &auth, NV_UNIQUE_NAME) != 0)
2815 		goto error;
2816 
2817 	if (nvlist_add_string(auth, FM_FMRI_AUTH_PRODUCT, product) != 0 ||
2818 	    nvlist_add_string(auth, FM_FMRI_AUTH_CHASSIS, serial) != 0) {
2819 		(void) topo_mod_seterrno(mod, EMOD_NVL_INVAL);
2820 		goto error;
2821 	}
2822 
2823 	/*
2824 	 * We pass NULL for the parent FMRI because there is no resource
2825 	 * associated with it.  For the toplevel enclosure, we leave the
2826 	 * serial/part/revision portions empty, which are reserved for
2827 	 * individual components within the chassis.
2828 	 */
2829 	if ((fmri = topo_mod_hcfmri(mod, NULL, FM_HC_SCHEME_VERSION,
2830 	    SES_ENCLOSURE, cp->sec_instance, NULL, auth,
2831 	    model, revision, serial)) == NULL) {
2832 		topo_mod_dprintf(mod, "topo_mod_hcfmri() failed: %s",
2833 		    topo_mod_errmsg(mod));
2834 		goto error;
2835 	}
2836 
2837 	if ((tn = topo_node_bind(mod, pnode, SES_ENCLOSURE,
2838 	    cp->sec_instance, fmri)) == NULL) {
2839 		topo_mod_dprintf(mod, "topo_node_bind() failed: %s",
2840 		    topo_mod_errmsg(mod));
2841 		goto error;
2842 	}
2843 
2844 	if (topo_method_register(mod, tn, ses_enclosure_methods) != 0) {
2845 		topo_mod_dprintf(mod,
2846 		    "topo_method_register() failed: %s",
2847 		    topo_mod_errmsg(mod));
2848 		goto error;
2849 	}
2850 
2851 	if (ses_set_standard_props(mod, NULL, tn, auth,
2852 	    ses_node_id(cp->sec_enclosure), cp->sec_target->set_devpath) != 0)
2853 		goto error;
2854 
2855 	/*
2856 	 * For enclosures, we want to include all possible targets (for upgrade
2857 	 * purposes).
2858 	 */
2859 	for (i = 0, stp = topo_list_next(&cp->sec_targets); stp != NULL;
2860 	    stp = topo_list_next(stp), i++)
2861 		;
2862 
2863 	verify(i != 0);
2864 	paths = alloca(i * sizeof (char *));
2865 
2866 	for (i = 0, stp = topo_list_next(&cp->sec_targets); stp != NULL;
2867 	    stp = topo_list_next(stp), i++)
2868 		paths[i] = stp->set_devpath;
2869 
2870 
2871 	if (topo_prop_set_string_array(tn, TOPO_PGROUP_SES,
2872 	    TOPO_PROP_PATHS, TOPO_PROP_IMMUTABLE, (const char **)paths,
2873 	    i, &err) != 0) {
2874 		topo_mod_dprintf(mod,
2875 		    "failed to create property %s: %s\n",
2876 		    TOPO_PROP_PATHS, topo_strerror(err));
2877 		goto error;
2878 	}
2879 
2880 	if (nvlist_lookup_uint64(props,
2881 	    LIBSES_PROP_PHYS_PARENT, &pindex) == 0) {
2882 		start = gethrtime(); /* to mearusre performance */
2883 		/*
2884 		 * The enclosure is supported through SUNW,FRUID.
2885 		 * Need to enumerate the nodes through hierarchical order.
2886 		 */
2887 		if ((sproot = topo_mod_zalloc(mod,
2888 		    sizeof (ses_phys_tree_t))) == NULL) {
2889 			topo_mod_dprintf(mod,
2890 			    "failed to allocate root: %s\n",
2891 			    topo_strerror(err));
2892 			goto error;
2893 		}
2894 		sproot->spt_pindex = pindex;
2895 		if (nvlist_lookup_boolean_value(props,
2896 		    LIBSES_PROP_FRU, &sproot->spt_isfru) != 0) {
2897 			topo_mod_dprintf(mod,
2898 			    "ses_create_chassis(): Failed to find prop %s "
2899 			    "on enclosure element (CSN %s).",
2900 			    LIBSES_PROP_FRU, cp->sec_csn);
2901 			/* an enclosure should be a FRU. continue to process. */
2902 			sproot->spt_isfru = B_TRUE;
2903 		}
2904 		if (nvlist_lookup_uint64(props,
2905 		    SES_PROP_ELEMENT_ONLY_INDEX,
2906 		    &sproot->spt_eonlyindex) != 0) {
2907 			topo_mod_dprintf(mod,
2908 			    "ses_create_chassis(): Failed to find prop %s "
2909 			    "on enclosure element (CSN %s).",
2910 			    LIBSES_PROP_PHYS_PARENT, cp->sec_csn);
2911 			topo_mod_free(mod, sproot, sizeof (ses_phys_tree_t));
2912 			goto error;
2913 		}
2914 		if (sproot->spt_pindex != sproot->spt_eonlyindex) {
2915 			topo_mod_dprintf(mod, "ses_create_chassis(): "
2916 			    "Enclosure element(CSN %s) should have "
2917 			    "itself as the parent to be the root node "
2918 			    "of FRU hierarchical tree.)", cp->sec_csn);
2919 			topo_mod_free(mod, sproot, sizeof (ses_phys_tree_t));
2920 			goto error;
2921 		} else {
2922 			sproot->spt_snode = cp->sec_enclosure;
2923 			sproot->spt_tnode = tn;
2924 			/* construct a tree. */
2925 			if (ses_construct_phys_tree(sdp, cp, sproot) != 0) {
2926 				topo_mod_dprintf(mod, "ses_create_chassis(): "
2927 				    "Failed to construct FRU hierarchical "
2928 				    "tree on enclosure (CSN %s.)",
2929 				    cp->sec_csn);
2930 			}
2931 
2932 			/* enumerate elements from the tree. */
2933 			if (ses_create_children_from_phys_tree(sdp, tn, cp,
2934 			    sproot) != 0) {
2935 				topo_mod_dprintf(mod, "ses_create_chassis(): "
2936 				    "Failed to create children topo nodes out "
2937 				    "of FRU hierarchical tree on enclosure "
2938 				    "(CSN %s).", cp->sec_csn);
2939 			}
2940 			/* destroy the phys tree. */
2941 			ses_phys_tree_free(mod, sproot);
2942 		}
2943 
2944 		end = gethrtime();
2945 		duration = end - start;
2946 		duration /= HR_SECOND;
2947 		topo_mod_dprintf(mod,
2948 		    "FRU boundary tree based enumeration: %.6f seconds",
2949 		    duration);
2950 	} else {
2951 		/*
2952 		 * Create the nodes for power supplies, fans, controllers and
2953 		 * devices.  Note that SAS exopander nodes and connector nodes
2954 		 * are handled through protocol specific processing of
2955 		 * controllers.
2956 		 */
2957 		if (ses_create_children(sdp, tn, SES_ET_POWER_SUPPLY,
2958 		    PSU, "PSU", cp, B_TRUE) != 0 ||
2959 		    ses_create_children(sdp, tn, SES_ET_COOLING,
2960 		    FAN, "FAN", cp, B_TRUE) != 0 ||
2961 		    ses_create_children(sdp, tn, SES_ET_ESC_ELECTRONICS,
2962 		    CONTROLLER, "CONTROLLER", cp, B_TRUE) != 0 ||
2963 		    ses_create_children(sdp, tn, SES_ET_DEVICE,
2964 		    BAY, "BAY", cp, B_TRUE) != 0 ||
2965 		    ses_create_children(sdp, tn, SES_ET_ARRAY_DEVICE,
2966 		    BAY, "BAY", cp, B_TRUE) != 0)
2967 			goto error;
2968 	}
2969 
2970 	if (cp->sec_maxinstance >= 0 &&
2971 	    (topo_node_range_create(mod, tn, SUBCHASSIS, 0,
2972 	    cp->sec_maxinstance) != 0)) {
2973 		topo_mod_dprintf(mod, "topo_node_create_range() failed: %s",
2974 		    topo_mod_errmsg(mod));
2975 		goto error;
2976 	}
2977 
2978 	for (scp = topo_list_next(&cp->sec_subchassis); scp != NULL;
2979 	    scp = topo_list_next(scp)) {
2980 
2981 		if (ses_create_subchassis(sdp, tn, scp) != 0)
2982 			goto error;
2983 
2984 		topo_mod_dprintf(mod, "created Subchassis node with "
2985 		    "instance %u\nand target (%s) under Chassis with CSN %s",
2986 		    scp->sec_instance, scp->sec_target->set_devpath,
2987 		    cp->sec_csn);
2988 
2989 		sc_count++;
2990 	}
2991 
2992 	topo_mod_dprintf(mod, "%s: created %llu %s nodes",
2993 	    cp->sec_csn, sc_count, SUBCHASSIS);
2994 
2995 	cp->sec_target->set_refcount++;
2996 	topo_node_setspecific(tn, cp->sec_target);
2997 
2998 	ret = 0;
2999 error:
3000 	topo_mod_strfree(mod, manufacturer);
3001 	topo_mod_strfree(mod, model);
3002 	topo_mod_strfree(mod, revision);
3003 	topo_mod_strfree(mod, product);
3004 
3005 	nvlist_free(fmri);
3006 	nvlist_free(auth);
3007 	return (ret);
3008 }
3009 
3010 /*
3011  * Create a bay node explicitly enumerated via XML.
3012  */
3013 static int
3014 ses_create_bays(ses_enum_data_t *sdp, tnode_t *pnode)
3015 {
3016 	topo_mod_t *mod = sdp->sed_mod;
3017 	ses_enum_chassis_t *cp;
3018 
3019 	/*
3020 	 * Iterate over chassis looking for an internal enclosure.  This
3021 	 * property is set via a vendor-specific plugin, and there should only
3022 	 * ever be a single internal chassis in a system.
3023 	 */
3024 	for (cp = topo_list_next(&sdp->sed_chassis); cp != NULL;
3025 	    cp = topo_list_next(cp)) {
3026 		if (cp->sec_internal)
3027 			break;
3028 	}
3029 
3030 	if (cp == NULL) {
3031 		topo_mod_dprintf(mod, "failed to find internal chassis\n");
3032 		return (-1);
3033 	}
3034 
3035 	if (ses_create_children(sdp, pnode, SES_ET_DEVICE,
3036 	    BAY, "BAY", cp, B_FALSE) != 0 ||
3037 	    ses_create_children(sdp, pnode, SES_ET_ARRAY_DEVICE,
3038 	    BAY, "BAY", cp, B_FALSE) != 0)
3039 		return (-1);
3040 
3041 	return (0);
3042 }
3043 
3044 /*
3045  * Initialize chassis or subchassis.
3046  */
3047 static int
3048 ses_init_chassis(topo_mod_t *mod, ses_enum_data_t *sdp, ses_enum_chassis_t *pcp,
3049     ses_enum_chassis_t *cp, ses_node_t *np, nvlist_t *props,
3050     uint64_t subchassis, ses_chassis_type_e flags)
3051 {
3052 	boolean_t internal, ident;
3053 
3054 	assert((flags & (SES_NEW_CHASSIS | SES_NEW_SUBCHASSIS |
3055 	    SES_DUP_CHASSIS | SES_DUP_SUBCHASSIS)) != 0);
3056 
3057 	assert(cp != NULL);
3058 	assert(np != NULL);
3059 	assert(props != NULL);
3060 
3061 	if (flags & (SES_NEW_SUBCHASSIS | SES_DUP_SUBCHASSIS))
3062 		assert(pcp != NULL);
3063 
3064 	topo_mod_dprintf(mod, "ses_init_chassis: %s: index %llu, flags (%d)",
3065 	    sdp->sed_name, subchassis, flags);
3066 
3067 	if (flags & (SES_NEW_CHASSIS | SES_NEW_SUBCHASSIS)) {
3068 
3069 		topo_mod_dprintf(mod, "new chassis/subchassis");
3070 		if (nvlist_lookup_boolean_value(props,
3071 		    LIBSES_EN_PROP_INTERNAL, &internal) == 0)
3072 			cp->sec_internal = internal;
3073 
3074 		cp->sec_enclosure = np;
3075 		cp->sec_target = sdp->sed_target;
3076 
3077 		if (flags & SES_NEW_CHASSIS) {
3078 			if (!cp->sec_internal)
3079 				cp->sec_instance = sdp->sed_instance++;
3080 			topo_list_append(&sdp->sed_chassis, cp);
3081 		} else {
3082 			if (subchassis != NO_SUBCHASSIS)
3083 				cp->sec_instance = subchassis;
3084 			else
3085 				cp->sec_instance = pcp->sec_scinstance++;
3086 
3087 			if (cp->sec_instance > pcp->sec_maxinstance)
3088 				pcp->sec_maxinstance = cp->sec_instance;
3089 
3090 			topo_list_append(&pcp->sec_subchassis, cp);
3091 		}
3092 
3093 	} else {
3094 		topo_mod_dprintf(mod, "dup chassis/subchassis");
3095 		if (nvlist_lookup_boolean_value(props,
3096 		    SES_PROP_IDENT, &ident) == 0) {
3097 			topo_mod_dprintf(mod,  "overriding enclosure node");
3098 
3099 			cp->sec_enclosure = np;
3100 			cp->sec_target = sdp->sed_target;
3101 		}
3102 	}
3103 
3104 	topo_list_append(&cp->sec_targets, sdp->sed_target);
3105 	sdp->sed_current = cp;
3106 
3107 	return (0);
3108 }
3109 
3110 /*
3111  * Gather nodes from the current SES target into our chassis list, merging the
3112  * results if necessary.
3113  */
3114 static ses_walk_action_t
3115 ses_enum_gather(ses_node_t *np, void *data)
3116 {
3117 	nvlist_t *props = ses_node_props(np);
3118 	ses_enum_data_t *sdp = data;
3119 	topo_mod_t *mod = sdp->sed_mod;
3120 	ses_enum_chassis_t *cp, *scp;
3121 	ses_enum_node_t *snp;
3122 	ses_alt_node_t *sap;
3123 	char *csn;
3124 	uint64_t instance, type;
3125 	uint64_t prevstatus, status;
3126 	boolean_t report;
3127 	uint64_t subchassis = NO_SUBCHASSIS;
3128 
3129 	if (ses_node_type(np) == SES_NODE_ENCLOSURE) {
3130 		/*
3131 		 * If we have already identified the chassis for this target,
3132 		 * then this is a secondary enclosure and we should ignore it,
3133 		 * along with the rest of the tree (since this is depth-first).
3134 		 */
3135 		if (sdp->sed_current != NULL)
3136 			return (SES_WALK_ACTION_TERMINATE);
3137 
3138 		/*
3139 		 * Go through the list of chassis we have seen so far and see
3140 		 * if this serial number matches one of the known values.
3141 		 * If so, check whether this enclosure is a subchassis.
3142 		 */
3143 		if (nvlist_lookup_string(props, LIBSES_EN_PROP_CSN,
3144 		    &csn) != 0)
3145 			return (SES_WALK_ACTION_TERMINATE);
3146 
3147 		(void) nvlist_lookup_uint64(props, LIBSES_EN_PROP_SUBCHASSIS_ID,
3148 		    &subchassis);
3149 
3150 		topo_mod_dprintf(mod, "ses_enum_gather: Enclosure Node (%s) "
3151 		    "CSN (%s), subchassis (%llu)", sdp->sed_name, csn,
3152 		    subchassis);
3153 
3154 		/*
3155 		 * We need to determine whether this enclosure node
3156 		 * represents a chassis or a subchassis. Since we may
3157 		 * receive the enclosure nodes in a non-deterministic
3158 		 * manner, we need to account for all possible combinations:
3159 		 *	1. Chassis for the current CSN has not yet been
3160 		 *	   allocated
3161 		 *		1.1 This is a new chassis:
3162 		 *			allocate and instantiate the chassis
3163 		 *		1.2 This is a new subchassis:
3164 		 *			allocate a placeholder chassis
3165 		 *			allocate and instantiate the subchassis
3166 		 *			link the subchassis to the chassis
3167 		 *	2. Chassis for the current CSN has been allocated
3168 		 *		2.1 This is a duplicate chassis enclosure
3169 		 *			check whether to override old chassis
3170 		 *			append to chassis' target list
3171 		 *		2.2 Only placeholder chassis exists
3172 		 *			fill in the chassis fields
3173 		 *		2.3 This is a new subchassis
3174 		 *			allocate and instantiate the subchassis
3175 		 *			link the subchassis to the chassis
3176 		 *		2.4 This is a duplicate subchassis enclosure
3177 		 *			 check whether to override old chassis
3178 		 *			 append to chassis' target list
3179 		 */
3180 
3181 		for (cp = topo_list_next(&sdp->sed_chassis); cp != NULL;
3182 		    cp = topo_list_next(cp))
3183 			if (strcmp(cp->sec_csn, csn) == 0)
3184 				break;
3185 
3186 		if (cp == NULL) {
3187 			/* 1. Haven't seen a chassis with this CSN before */
3188 
3189 			if ((cp = topo_mod_zalloc(mod,
3190 			    sizeof (ses_enum_chassis_t))) == NULL)
3191 				goto error;
3192 
3193 			cp->sec_scinstance = SES_STARTING_SUBCHASSIS;
3194 			cp->sec_maxinstance = -1;
3195 			cp->sec_csn = csn;
3196 
3197 			if (subchassis == NO_SUBCHASSIS) {
3198 				/* 1.1 This is a new chassis */
3199 
3200 				topo_mod_dprintf(mod, "%s: Initialize new "
3201 				    "chassis with CSN %s", sdp->sed_name, csn);
3202 
3203 				if (ses_init_chassis(mod, sdp, NULL, cp,
3204 				    np, props, NO_SUBCHASSIS,
3205 				    SES_NEW_CHASSIS) < 0)
3206 					goto error;
3207 			} else {
3208 				/* 1.2 This is a new subchassis */
3209 
3210 				topo_mod_dprintf(mod, "%s: Initialize new "
3211 				    "subchassis with CSN %s and index %llu",
3212 				    sdp->sed_name, csn, subchassis);
3213 
3214 				if ((scp = topo_mod_zalloc(mod,
3215 				    sizeof (ses_enum_chassis_t))) == NULL)
3216 					goto error;
3217 
3218 				scp->sec_csn = csn;
3219 
3220 				if (ses_init_chassis(mod, sdp, cp, scp, np,
3221 				    props, subchassis, SES_NEW_SUBCHASSIS) < 0)
3222 					goto error;
3223 			}
3224 		} else {
3225 			/*
3226 			 * We have a chassis or subchassis with this CSN.  If
3227 			 * it's a chassis, we must check to see whether it is
3228 			 * a placeholder previously created because we found a
3229 			 * subchassis with this CSN.  We will know that because
3230 			 * the sec_target value will not be set; it is set only
3231 			 * in ses_init_chassis().  In that case, initialise it
3232 			 * as a new chassis; otherwise, it's a duplicate and we
3233 			 * need to append only.
3234 			 */
3235 			if (subchassis == NO_SUBCHASSIS) {
3236 				if (cp->sec_target != NULL) {
3237 					/* 2.1 This is a duplicate chassis */
3238 
3239 					topo_mod_dprintf(mod, "%s: Append "
3240 					    "duplicate chassis with CSN (%s)",
3241 					    sdp->sed_name, csn);
3242 
3243 					if (ses_init_chassis(mod, sdp, NULL, cp,
3244 					    np, props, NO_SUBCHASSIS,
3245 					    SES_DUP_CHASSIS) < 0)
3246 						goto error;
3247 				} else {
3248 					/* Placeholder chassis - init it up */
3249 					topo_mod_dprintf(mod, "%s: Initialize"
3250 					    "placeholder chassis with CSN %s",
3251 					    sdp->sed_name, csn);
3252 
3253 					if (ses_init_chassis(mod, sdp, NULL,
3254 					    cp, np, props, NO_SUBCHASSIS,
3255 					    SES_NEW_CHASSIS) < 0)
3256 						goto error;
3257 
3258 				}
3259 			} else {
3260 				/* This is a subchassis */
3261 
3262 				for (scp = topo_list_next(&cp->sec_subchassis);
3263 				    scp != NULL; scp = topo_list_next(scp))
3264 					if (scp->sec_instance == subchassis)
3265 						break;
3266 
3267 				if (scp == NULL) {
3268 					/* 2.3 This is a new subchassis */
3269 
3270 					topo_mod_dprintf(mod, "%s: Initialize "
3271 					    "new subchassis with CSN (%s) "
3272 					    "and LID (%s)",
3273 					    sdp->sed_name, csn);
3274 
3275 					if ((scp = topo_mod_zalloc(mod,
3276 					    sizeof (ses_enum_chassis_t)))
3277 					    == NULL)
3278 						goto error;
3279 
3280 					scp->sec_csn = csn;
3281 
3282 					if (ses_init_chassis(mod, sdp, cp, scp,
3283 					    np, props, subchassis,
3284 					    SES_NEW_SUBCHASSIS) < 0)
3285 						goto error;
3286 				} else {
3287 					/* 2.4 This is a duplicate subchassis */
3288 
3289 					topo_mod_dprintf(mod, "%s: Append "
3290 					    "duplicate subchassis with "
3291 					    "CSN (%s)", sdp->sed_name, csn);
3292 
3293 					if (ses_init_chassis(mod, sdp, cp, scp,
3294 					    np, props, subchassis,
3295 					    SES_DUP_SUBCHASSIS) < 0)
3296 						goto error;
3297 				}
3298 			}
3299 		}
3300 	} else if (ses_node_type(np) == SES_NODE_ELEMENT) {
3301 		/*
3302 		 * If we haven't yet seen an enclosure node and identified the
3303 		 * current chassis, something is very wrong; bail out.
3304 		 */
3305 		if (sdp->sed_current == NULL)
3306 			return (SES_WALK_ACTION_TERMINATE);
3307 
3308 		/*
3309 		 * If this isn't one of the element types we care about, then
3310 		 * ignore it.
3311 		 */
3312 		verify(nvlist_lookup_uint64(props, SES_PROP_ELEMENT_TYPE,
3313 		    &type) == 0);
3314 		if (type != SES_ET_DEVICE &&
3315 		    type != SES_ET_ARRAY_DEVICE &&
3316 		    type != SES_ET_SUNW_FANBOARD &&
3317 		    type != SES_ET_SUNW_FANMODULE &&
3318 		    type != SES_ET_COOLING &&
3319 		    type != SES_ET_SUNW_POWERBOARD &&
3320 		    type != SES_ET_SUNW_POWERMODULE &&
3321 		    type != SES_ET_POWER_SUPPLY &&
3322 		    type != SES_ET_ESC_ELECTRONICS &&
3323 		    type != SES_ET_SAS_EXPANDER &&
3324 		    type != SES_ET_SAS_CONNECTOR)
3325 			return (SES_WALK_ACTION_CONTINUE);
3326 
3327 		/*
3328 		 * Get the current instance number and see if we already know
3329 		 * about this element.  If so, it means we have multiple paths
3330 		 * to the same elements, and we should ignore the current path.
3331 		 */
3332 		verify(nvlist_lookup_uint64(props, SES_PROP_ELEMENT_CLASS_INDEX,
3333 		    &instance) == 0);
3334 		if (type == SES_ET_DEVICE || type == SES_ET_ARRAY_DEVICE)
3335 			(void) nvlist_lookup_uint64(props, SES_PROP_BAY_NUMBER,
3336 			    &instance);
3337 
3338 		cp = sdp->sed_current;
3339 
3340 		for (snp = topo_list_next(&cp->sec_nodes); snp != NULL;
3341 		    snp = topo_list_next(snp)) {
3342 			if (snp->sen_type == type &&
3343 			    snp->sen_instance == instance)
3344 				break;
3345 		}
3346 
3347 		/*
3348 		 * We prefer the new element under the following circumstances:
3349 		 *
3350 		 * - The currently known element's status is unknown or not
3351 		 *   available, but the new element has a known status.  This
3352 		 *   occurs if a given element is only available through a
3353 		 *   particular target.
3354 		 *
3355 		 * - This is an ESC_ELECTRONICS element, and the 'reported-via'
3356 		 *   property is set.  This allows us to get reliable firmware
3357 		 *   revision information from the enclosure node.
3358 		 */
3359 		if (snp != NULL) {
3360 			if (nvlist_lookup_uint64(
3361 			    ses_node_props(snp->sen_node),
3362 			    SES_PROP_STATUS_CODE, &prevstatus) != 0)
3363 				prevstatus = SES_ESC_UNSUPPORTED;
3364 			if (nvlist_lookup_uint64(
3365 			    props, SES_PROP_STATUS_CODE, &status) != 0)
3366 				status = SES_ESC_UNSUPPORTED;
3367 			if (nvlist_lookup_boolean_value(
3368 			    props, SES_PROP_REPORT, &report) != 0)
3369 				report = B_FALSE;
3370 
3371 			if ((SES_STATUS_UNAVAIL(prevstatus) &&
3372 			    !SES_STATUS_UNAVAIL(status)) ||
3373 			    (type == SES_ET_ESC_ELECTRONICS &&
3374 			    report)) {
3375 				snp->sen_node = np;
3376 				snp->sen_target = sdp->sed_target;
3377 			}
3378 
3379 			if ((sap = topo_mod_zalloc(mod,
3380 			    sizeof (ses_alt_node_t))) == NULL)
3381 				goto error;
3382 
3383 			sap->san_node = np;
3384 			topo_list_append(&snp->sen_alt_nodes, sap);
3385 
3386 			return (SES_WALK_ACTION_CONTINUE);
3387 		}
3388 
3389 		if ((snp = topo_mod_zalloc(mod,
3390 		    sizeof (ses_enum_node_t))) == NULL)
3391 			goto error;
3392 
3393 		if ((sap = topo_mod_zalloc(mod,
3394 		    sizeof (ses_alt_node_t))) == NULL) {
3395 			topo_mod_free(mod, snp, sizeof (ses_enum_node_t));
3396 			goto error;
3397 		}
3398 
3399 		topo_mod_dprintf(mod, "%s: adding node (%llu, %llu)",
3400 		    sdp->sed_name, type, instance);
3401 		snp->sen_node = np;
3402 		snp->sen_type = type;
3403 		snp->sen_instance = instance;
3404 		snp->sen_target = sdp->sed_target;
3405 		sap->san_node = np;
3406 		topo_list_append(&snp->sen_alt_nodes, sap);
3407 		topo_list_append(&cp->sec_nodes, snp);
3408 
3409 		if (type == SES_ET_DEVICE)
3410 			cp->sec_hasdev = B_TRUE;
3411 	}
3412 
3413 	return (SES_WALK_ACTION_CONTINUE);
3414 
3415 error:
3416 	sdp->sed_errno = -1;
3417 	return (SES_WALK_ACTION_TERMINATE);
3418 }
3419 
3420 static int
3421 ses_process_dir(const char *dirpath, ses_enum_data_t *sdp)
3422 {
3423 	topo_mod_t *mod = sdp->sed_mod;
3424 	DIR *dir;
3425 	struct dirent *dp;
3426 	char path[PATH_MAX];
3427 	ses_enum_target_t *stp;
3428 	int err = -1;
3429 
3430 	/*
3431 	 * Open the SES target directory and iterate over any available
3432 	 * targets.
3433 	 */
3434 	if ((dir = opendir(dirpath)) == NULL) {
3435 		/*
3436 		 * If the SES target directory does not exist, then return as if
3437 		 * there are no active targets.
3438 		 */
3439 		topo_mod_dprintf(mod, "failed to open ses "
3440 		    "directory '%s'", dirpath);
3441 		return (0);
3442 	}
3443 
3444 	while ((dp = readdir(dir)) != NULL) {
3445 		if (strcmp(dp->d_name, ".") == 0 ||
3446 		    strcmp(dp->d_name, "..") == 0)
3447 			continue;
3448 
3449 		/*
3450 		 * Create a new target instance and take a snapshot.
3451 		 */
3452 		if ((stp = topo_mod_zalloc(mod,
3453 		    sizeof (ses_enum_target_t))) == NULL)
3454 			goto error;
3455 
3456 		(void) pthread_mutex_init(&stp->set_lock, NULL);
3457 
3458 		(void) snprintf(path, sizeof (path), "%s/%s", dirpath,
3459 		    dp->d_name);
3460 
3461 		/*
3462 		 * We keep track of the SES device path and export it on a
3463 		 * per-node basis to allow higher level software to get to the
3464 		 * corresponding SES state.
3465 		 */
3466 		if ((stp->set_devpath = topo_mod_strdup(mod, path)) == NULL) {
3467 			topo_mod_free(mod, stp, sizeof (ses_enum_target_t));
3468 			goto error;
3469 		}
3470 
3471 		if ((stp->set_target =
3472 		    ses_open(LIBSES_VERSION, path)) == NULL) {
3473 			topo_mod_dprintf(mod, "failed to open ses target "
3474 			    "'%s': %s", dp->d_name, ses_errmsg());
3475 			ses_sof_alloc(mod, stp->set_devpath);
3476 			topo_mod_free(mod, stp, sizeof (ses_enum_target_t));
3477 			continue;
3478 		}
3479 		topo_mod_dprintf(mod, "open contract");
3480 		ses_ssl_alloc(mod, stp);
3481 		ses_create_contract(mod, stp);
3482 
3483 		stp->set_refcount = 1;
3484 		sdp->sed_target = stp;
3485 		stp->set_snap = ses_snap_hold(stp->set_target);
3486 		stp->set_snaptime = gethrtime();
3487 
3488 		/*
3489 		 * Enumerate over all SES elements and merge them into the
3490 		 * correct ses_enum_chassis_t.
3491 		 */
3492 		sdp->sed_current = NULL;
3493 		sdp->sed_errno = 0;
3494 		sdp->sed_name = dp->d_name;
3495 		(void) ses_walk(stp->set_snap, ses_enum_gather, sdp);
3496 
3497 		if (sdp->sed_errno != 0)
3498 			goto error;
3499 	}
3500 
3501 	err = 0;
3502 error:
3503 	(void) closedir(dir);
3504 	return (err);
3505 }
3506 
3507 static void
3508 ses_release(topo_mod_t *mod, tnode_t *tn)
3509 {
3510 	ses_enum_target_t *stp;
3511 
3512 	if ((stp = topo_node_getspecific(tn)) != NULL) {
3513 		topo_node_setspecific(tn, NULL);
3514 		ses_target_free(mod, stp);
3515 	}
3516 }
3517 
3518 /*ARGSUSED*/
3519 static int
3520 ses_enum(topo_mod_t *mod, tnode_t *rnode, const char *name,
3521     topo_instance_t min, topo_instance_t max, void *arg, void *notused)
3522 {
3523 	ses_enum_chassis_t *cp;
3524 	ses_enum_data_t *data;
3525 
3526 	/*
3527 	 * Check to make sure we're being invoked sensibly, and that we're not
3528 	 * being invoked as part of a post-processing step.
3529 	 */
3530 	if (strcmp(name, SES_ENCLOSURE) != 0 && strcmp(name, BAY) != 0)
3531 		return (0);
3532 
3533 	/*
3534 	 * If this is the first time we've called our enumeration method, then
3535 	 * gather information about any available enclosures.
3536 	 */
3537 	if ((data = topo_mod_getspecific(mod)) == NULL) {
3538 		ses_sof_freeall(mod);
3539 		if ((data = topo_mod_zalloc(mod, sizeof (ses_enum_data_t))) ==
3540 		    NULL)
3541 			return (-1);
3542 
3543 		data->sed_mod = mod;
3544 		topo_mod_setspecific(mod, data);
3545 
3546 		if (dev_list_gather(mod, &data->sed_devs) != 0)
3547 			goto error;
3548 
3549 		/*
3550 		 * We search both the ses(7D) and sgen(7D) locations, so we are
3551 		 * independent of any particular driver class bindings.
3552 		 */
3553 		if (ses_process_dir("/dev/es", data) != 0 ||
3554 		    ses_process_dir("/dev/scsi/ses", data) != 0)
3555 			goto error;
3556 	}
3557 
3558 	if (strcmp(name, SES_ENCLOSURE) == 0) {
3559 		/*
3560 		 * This is a request to enumerate external enclosures.  Go
3561 		 * through all the targets and create chassis nodes where
3562 		 * necessary.
3563 		 */
3564 		for (cp = topo_list_next(&data->sed_chassis); cp != NULL;
3565 		    cp = topo_list_next(cp)) {
3566 			if (ses_create_chassis(data, rnode, cp) != 0)
3567 				goto error;
3568 		}
3569 	} else {
3570 		/*
3571 		 * This is a request to enumerate a specific bay underneath the
3572 		 * root chassis (for internal disks).
3573 		 */
3574 		if (ses_create_bays(data, rnode) != 0)
3575 			goto error;
3576 	}
3577 
3578 	/*
3579 	 * This is a bit of a kludge.  In order to allow internal disks to be
3580 	 * enumerated and share snapshot-specific information with the external
3581 	 * enclosure enumeration, we rely on the fact that we will be invoked
3582 	 * for the 'ses-enclosure' node last.
3583 	 */
3584 	if (strcmp(name, SES_ENCLOSURE) == 0) {
3585 		for (cp = topo_list_next(&data->sed_chassis); cp != NULL;
3586 		    cp = topo_list_next(cp))
3587 			ses_data_free(data, cp);
3588 		ses_data_free(data, NULL);
3589 		topo_mod_setspecific(mod, NULL);
3590 	}
3591 	return (0);
3592 
3593 error:
3594 	for (cp = topo_list_next(&data->sed_chassis); cp != NULL;
3595 	    cp = topo_list_next(cp))
3596 		ses_data_free(data, cp);
3597 	ses_data_free(data, NULL);
3598 	topo_mod_setspecific(mod, NULL);
3599 	return (-1);
3600 }
3601 
3602 static const topo_modops_t ses_ops =
3603 	{ ses_enum, ses_release };
3604 
3605 static topo_modinfo_t ses_info =
3606 	{ SES_ENCLOSURE, FM_FMRI_SCHEME_HC, SES_VERSION, &ses_ops };
3607 
3608 /*ARGSUSED*/
3609 int
3610 _topo_init(topo_mod_t *mod, topo_version_t version)
3611 {
3612 	int rval;
3613 
3614 	if (getenv("TOPOSESDEBUG") != NULL)
3615 		topo_mod_setdebug(mod);
3616 
3617 	topo_mod_dprintf(mod, "initializing %s enumerator\n",
3618 	    SES_ENCLOSURE);
3619 
3620 	if ((rval = topo_mod_register(mod, &ses_info, TOPO_VERSION)) == 0)
3621 		ses_thread_init(mod);
3622 
3623 	return (rval);
3624 }
3625 
3626 void
3627 _topo_fini(topo_mod_t *mod)
3628 {
3629 	ses_thread_fini(mod);
3630 	ses_sof_freeall(mod);
3631 	topo_mod_unregister(mod);
3632 }
3633