xref: /titanic_52/usr/src/cmd/devfsadm/devfsadm.c (revision 4bc0a2ef2b7ba50a7a717e7ddbf31472ad28e358)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * Devfsadm replaces drvconfig, audlinks, disks, tapes, ports, devlinks
31  * as a general purpose device administrative utility.	It creates
32  * devices special files in /devices and logical links in /dev, and
33  * coordinates updates to /etc/path_to_instance with the kernel.  It
34  * operates in both command line mode to handle user or script invoked
35  * reconfiguration updates, and operates in daemon mode to handle dynamic
36  * reconfiguration for hotplugging support.
37  */
38 
39 #include "devfsadm_impl.h"
40 #include <utime.h>
41 
42 /* globals */
43 
44 /* create or remove nodes or links. unset with -n */
45 static int file_mods = TRUE;
46 
47 /* cleanup mode.  Set with -C */
48 static int cleanup = FALSE;
49 
50 /* devlinks -d compatibility */
51 static int devlinks_debug = FALSE;
52 
53 /* turn off device allocation with devfsadm -d */
54 static int devalloc_off = FALSE;
55 
56 /* devices to be deallocated with -d */
57 static char *devalloc[5] =
58 	{DDI_NT_AUDIO, DDI_NT_CD, DDI_NT_FD, DDI_NT_TAPE, NULL};
59 
60 /* load a single driver only.  set with -i */
61 static int single_drv = FALSE;
62 static char *driver = NULL;
63 
64 /* attempt to load drivers or defer attach nodes */
65 static int load_attach_drv = TRUE;
66 
67 /* set if invoked via /usr/lib/devfsadm/devfsadmd */
68 static int daemon_mode = FALSE;
69 
70 /* output directed to syslog during daemon mode if set */
71 static int logflag = FALSE;
72 
73 /* build links in /dev.  -x to turn off */
74 static int build_dev = TRUE;
75 
76 /* build nodes in /devices.  -y to turn off */
77 static int build_devices = TRUE;
78 
79 /* -z to turn off */
80 static int flush_path_to_inst_enable = TRUE;
81 
82 /* variables used for path_to_inst flushing */
83 static int inst_count = 0;
84 static mutex_t count_lock;
85 static cond_t cv;
86 
87 /* variables for minor_fini calling system */
88 static int minor_fini_timeout = MINOR_FINI_TIMEOUT_DEFAULT;
89 static mutex_t minor_fini_mutex;
90 static int minor_fini_thread_created = FALSE;
91 static int minor_fini_delay_restart = FALSE;
92 
93 /* single-threads /dev modification */
94 static sema_t dev_sema;
95 
96 /* the program we were invoked as; ie argv[0] */
97 static char *prog;
98 
99 /* pointers to create/remove link lists */
100 static create_list_t *create_head = NULL;
101 static remove_list_t *remove_head = NULL;
102 
103 /*  supports the class -c option */
104 static char **classes = NULL;
105 static int num_classes = 0;
106 
107 /* used with verbose option -v or -V */
108 static int num_verbose = 0;
109 static char **verbose = NULL;
110 
111 static struct mperm *minor_perms = NULL;
112 static driver_alias_t *driver_aliases = NULL;
113 
114 /* set if -r alternate root given */
115 static char *root_dir = "";
116 
117 /* /devices or <rootdir>/devices */
118 static char *devices_dir  = DEVICES;
119 
120 /* /dev or <rootdir>/dev */
121 static char *dev_dir = DEV;
122 
123 /* /dev for the global zone */
124 static char *global_dev_dir = DEV;
125 
126 /* /etc/path_to_inst unless -p used */
127 static char *inst_file = INSTANCE_FILE;
128 
129 /* /usr/lib/devfsadm/linkmods unless -l used */
130 static char *module_dirs = MODULE_DIRS;
131 
132 /* default uid/gid used if /etc/minor_perm entry not found */
133 static uid_t root_uid;
134 static gid_t sys_gid;
135 
136 /* /etc/devlink.tab unless devlinks -t used */
137 static char *devlinktab_file = NULL;
138 
139 /* set if /dev link is new. speeds up rm_stale_links */
140 static int linknew = TRUE;
141 
142 /* variables for devlink.tab compat processing */
143 static devlinktab_list_t *devlinktab_list = NULL;
144 static unsigned int devlinktab_line = 0;
145 
146 /* cache head for devfsadm_enumerate*() functions */
147 static numeral_set_t *head_numeral_set = NULL;
148 
149 /* list list of devfsadm modules */
150 static module_t *module_head = NULL;
151 
152 /* name_to_major list used in utility function */
153 static n2m_t *n2m_list = NULL;
154 
155 /* cache of some links used for performance */
156 static linkhead_t *headlinkhead = NULL;
157 
158 /* locking variables to prevent multiples writes to /dev */
159 static int hold_dev_lock = FALSE;
160 static int hold_daemon_lock = FALSE;
161 static int dev_lock_fd;
162 static int daemon_lock_fd;
163 static char dev_lockfile[PATH_MAX + 1];
164 static char daemon_lockfile[PATH_MAX + 1];
165 
166 /* last devinfo node/minor processed. used for performance */
167 static di_node_t lnode;
168 static di_minor_t lminor;
169 static char lphy_path[PATH_MAX + 1] = {""};
170 
171 /* Globals used by the link database */
172 static di_devlink_handle_t devlink_cache;
173 static int update_database = FALSE;
174 static int devlink_door_fd = -1; /* fd of devlink handler door */
175 
176 /* Globals used to set logindev perms */
177 static struct login_dev *login_dev_cache = NULL;
178 static int login_dev_enable = FALSE;
179 
180 /* Global to use devinfo snapshot cache */
181 static int use_snapshot_cache = FALSE;
182 
183 /* Zone-related information */
184 static int zone_cmd_mode = 0;
185 static mutex_t zone_mutex; /* protects zone registration/unregistration ops */
186 static struct zone_devinfo *zone_head;	/* linked list of zones */
187 
188 /*
189  * Packaged directories - not removed even when empty.
190  * The dirs must be listed in canonical form
191  * i.e. without leading "/dev/"
192  */
193 static char *packaged_dirs[] =
194 	{"dsk", "rdsk", "term", NULL};
195 
196 /* RCM related globals */
197 static void *librcm_hdl;
198 static rcm_handle_t *rcm_hdl = NULL;
199 static thread_t process_rcm_events_tid;
200 static struct rcm_eventq *volatile rcm_eventq_head = NULL;
201 static struct rcm_eventq *rcm_eventq_tail = NULL;
202 static mutex_t rcm_eventq_lock;
203 static cond_t rcm_eventq_cv;
204 static volatile int need_to_exit_rcm_event_thread = 0;
205 
206 static void load_dev_acl(void);
207 static void update_drvconf(major_t);
208 
209 
210 int
211 main(int argc, char *argv[])
212 {
213 	struct passwd *pw;
214 	struct group *gp;
215 	pid_t pid;
216 
217 	(void) setlocale(LC_ALL, "");
218 	(void) textdomain(TEXT_DOMAIN);
219 
220 	if ((prog = strrchr(argv[0], '/')) == NULL) {
221 		prog = argv[0];
222 	} else {
223 		prog++;
224 	}
225 
226 	if (getuid() != 0) {
227 		err_print(MUST_BE_ROOT);
228 		devfsadm_exit(1);
229 	}
230 
231 	/*
232 	 * Close all files except stdin/stdout/stderr
233 	 */
234 	closefrom(3);
235 
236 	if ((pw = getpwnam(DEFAULT_DEV_USER)) != NULL) {
237 		root_uid = pw->pw_uid;
238 	} else {
239 		err_print(CANT_FIND_USER, DEFAULT_DEV_USER);
240 		root_uid = (uid_t)0;	/* assume 0 is root */
241 	}
242 
243 	/* the default group is sys */
244 
245 	if ((gp = getgrnam(DEFAULT_DEV_GROUP)) != NULL) {
246 		sys_gid = gp->gr_gid;
247 	} else {
248 		err_print(CANT_FIND_GROUP, DEFAULT_DEV_GROUP);
249 		sys_gid = (gid_t)3;	/* assume 3 is sys */
250 	}
251 
252 	(void) umask(0);
253 
254 	parse_args(argc, argv);
255 
256 	(void) sema_init(&dev_sema, 1, USYNC_THREAD, NULL);
257 
258 	if (daemon_mode == TRUE) {
259 		/*
260 		 * Build /dev and /devices before daemonizing if
261 		 * reconfig booting and daemon invoked with alternate
262 		 * root. This is to support install.
263 		 */
264 		if (getenv(RECONFIG_BOOT) != NULL && root_dir[0] != '\0') {
265 			vprint(INFO_MID, CONFIGURING);
266 			load_dev_acl();
267 			update_drvconf((major_t)-1);
268 			process_devinfo_tree();
269 			(void) modctl(MODSETMINIROOT);
270 		}
271 
272 		/*
273 		 * fork before detaching from tty in order to print error
274 		 * message if unable to acquire file lock.  locks not preserved
275 		 * across forks.  Even under debug we want to fork so that
276 		 * when executed at boot we don't hang.
277 		 */
278 		if (fork() != 0) {
279 			devfsadm_exit(0);
280 		}
281 
282 		/* set directory to / so it coredumps there */
283 		if (chdir("/") == -1) {
284 			err_print(CHROOT_FAILED, strerror(errno));
285 		}
286 
287 		/* only one daemon can run at a time */
288 		if ((pid = enter_daemon_lock()) == getpid()) {
289 			thread_t thread;
290 			detachfromtty();
291 			(void) cond_init(&cv, USYNC_THREAD, 0);
292 			(void) mutex_init(&count_lock, USYNC_THREAD, 0);
293 			if (thr_create(NULL, NULL,
294 				(void *(*)(void *))instance_flush_thread,
295 				    NULL,
296 				    THR_DETACHED,
297 				    &thread) != 0) {
298 				err_print(CANT_CREATE_THREAD, "daemon",
299 					strerror(errno));
300 				devfsadm_exit(1);
301 			}
302 
303 			/*
304 			 * No need for rcm notifications when running
305 			 * with an alternate root. So initialize rcm only
306 			 * when devfsadm is running with root dir "/".
307 			 * Similarly, logindevperms need only be set
308 			 * in daemon mode and when root dir is "/".
309 			 */
310 			if (root_dir[0] == '\0') {
311 				(void) rcm_init();
312 				login_dev_enable = TRUE;
313 			}
314 
315 			daemon_update();
316 		} else {
317 			err_print(DAEMON_RUNNING, pid);
318 			devfsadm_exit(1);
319 		}
320 		exit_daemon_lock();
321 
322 	} else {
323 		/* not a daemon, so just build /dev and /devices */
324 		process_devinfo_tree();
325 	}
326 	return (0);
327 }
328 
329 static void
330 update_drvconf(major_t major)
331 {
332 	if (modctl(MODLOADDRVCONF, major) != 0)
333 		err_print(gettext("update_drvconf failed for major %d\n"),
334 		    major);
335 }
336 
337 
338 static void
339 load_dev_acl()
340 {
341 	if (load_devpolicy() != 0)
342 		err_print(gettext("device policy load failed\n"));
343 	load_minor_perm_file();
344 }
345 
346 /*
347  * set_zone_params sets us up to run against a specific zone.  It should
348  * only be called from parse_args.
349  */
350 static int
351 set_zone_params(char *zone_name)
352 {
353 	char zpath[MAXPATHLEN];
354 	zone_dochandle_t hdl;
355 	void *dlhdl;
356 
357 	assert(daemon_mode == FALSE);
358 
359 	if (strcmp(zone_name, GLOBAL_ZONENAME) == 0) {
360 		err_print(INVALID_ZONE, zone_name);
361 		return (DEVFSADM_FAILURE);
362 	}
363 
364 	if ((dlhdl = dlopen(LIBZONECFG_PATH, RTLD_LAZY)) == NULL) {
365 		err_print(ZONE_LIB_MISSING);
366 		return (DEVFSADM_FAILURE);
367 	}
368 
369 	if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
370 		err_print(ZONE_ROOTPATH_FAILED, zone_name, strerror(errno));
371 		(void) dlclose(dlhdl);
372 		return (DEVFSADM_FAILURE);
373 	}
374 	set_root_devices_dev_dir(zpath, 1);
375 
376 	if ((hdl = zonecfg_init_handle()) == NULL) {
377 		err_print(ZONE_REP_FAILED, zone_name, strerror(errno));
378 		(void) dlclose(dlhdl);
379 		return (DEVFSADM_FAILURE);
380 	}
381 
382 	if ((zonecfg_get_snapshot_handle(zone_name, hdl)) != Z_OK) {
383 		err_print(ZONE_REP_FAILED, zone_name, strerror(errno));
384 		zonecfg_fini_handle(hdl);
385 		(void) dlclose(dlhdl);
386 		return (DEVFSADM_FAILURE);
387 	}
388 	(void) dlclose(dlhdl);
389 
390 	zone_head = s_malloc(sizeof (struct zone_devinfo));
391 	zone_head->zone_path = s_strdup(zpath);
392 	zone_head->zone_name = s_strdup(zone_name);
393 	zone_head->zone_dochdl = hdl;
394 	zone_head->zone_next = NULL;
395 	zone_cmd_mode = 1;
396 	return (DEVFSADM_SUCCESS);
397 }
398 
399 /*
400  * Parse arguments for all 6 programs handled from devfsadm.
401  */
402 static void
403 parse_args(int argc, char *argv[])
404 {
405 	char opt;
406 	char get_linkcompat_opts = FALSE;
407 	char *compat_class;
408 	int num_aliases = 0;
409 	int len;
410 	int retval;
411 	int add_bind = FALSE;
412 	struct aliases *ap = NULL;
413 	struct aliases *a_head = NULL;
414 	struct aliases *a_tail = NULL;
415 	struct modconfig mc;
416 
417 	if (strcmp(prog, DISKS) == 0) {
418 		compat_class = "disk";
419 		get_linkcompat_opts = TRUE;
420 
421 	} else if (strcmp(prog, TAPES) == 0) {
422 		compat_class = "tape";
423 		get_linkcompat_opts = TRUE;
424 
425 	} else if (strcmp(prog, PORTS) == 0) {
426 		compat_class = "port";
427 		get_linkcompat_opts = TRUE;
428 
429 	} else if (strcmp(prog, AUDLINKS) == 0) {
430 		compat_class = "audio";
431 		get_linkcompat_opts = TRUE;
432 
433 	} else if (strcmp(prog, DEVLINKS) == 0) {
434 		devlinktab_file = DEVLINKTAB_FILE;
435 
436 		build_devices = FALSE;
437 		load_attach_drv = FALSE;
438 
439 		while ((opt = getopt(argc, argv, "dnr:st:vV:")) != EOF) {
440 			switch (opt) {
441 			case 'd':
442 				file_mods = FALSE;
443 				flush_path_to_inst_enable = FALSE;
444 				devlinks_debug = TRUE;
445 				break;
446 			case 'n':
447 				/* prevent driver loading and deferred attach */
448 				load_attach_drv = FALSE;
449 				break;
450 			case 'r':
451 				set_root_devices_dev_dir(optarg, 0);
452 				if (zone_pathcheck(root_dir) !=
453 				    DEVFSADM_SUCCESS)
454 					devfsadm_exit(1);
455 				break;
456 			case 's':
457 				/*
458 				 * suppress.  don't create/remove links/nodes
459 				 * useful with -v or -V
460 				 */
461 				file_mods = FALSE;
462 				flush_path_to_inst_enable = FALSE;
463 				break;
464 			case 't':
465 				/* supply a non-default table file */
466 				devlinktab_file = optarg;
467 				break;
468 			case 'v':
469 				/* documented verbose flag */
470 				add_verbose_id(VERBOSE_MID);
471 				break;
472 			case 'V':
473 				/* undocumented for extra verbose levels */
474 				add_verbose_id(optarg);
475 				break;
476 			default:
477 				usage();
478 				break;
479 			}
480 		}
481 
482 		if (optind < argc) {
483 			usage();
484 		}
485 
486 	} else if (strcmp(prog, DRVCONFIG) == 0) {
487 		build_dev = FALSE;
488 
489 		while ((opt =
490 			getopt(argc, argv, "a:bdc:i:m:np:R:r:svV:")) != EOF) {
491 			switch (opt) {
492 			case 'a':
493 				ap = calloc(sizeof (struct aliases), 1);
494 				ap->a_name = dequote(optarg);
495 				len = strlen(ap->a_name) + 1;
496 				if (len > MAXMODCONFNAME) {
497 					err_print(ALIAS_TOO_LONG,
498 					    MAXMODCONFNAME, ap->a_name);
499 					devfsadm_exit(1);
500 				}
501 				ap->a_len = len;
502 				if (a_tail == NULL) {
503 					a_head = ap;
504 				} else {
505 					a_tail->a_next = ap;
506 				}
507 				a_tail = ap;
508 				num_aliases++;
509 				add_bind = TRUE;
510 				break;
511 			case 'b':
512 				add_bind = TRUE;
513 				break;
514 			case 'c':
515 				(void) strcpy(mc.drvclass, optarg);
516 				break;
517 			case 'd':
518 				/*
519 				 * need to keep for compatibility, but
520 				 * do nothing.
521 				 */
522 				break;
523 			case 'i':
524 				single_drv = TRUE;
525 				(void) strcpy(mc.drvname, optarg);
526 				driver = s_strdup(optarg);
527 				break;
528 			case 'm':
529 				mc.major = atoi(optarg);
530 				break;
531 			case 'n':
532 				/* prevent driver loading and deferred attach */
533 				load_attach_drv = FALSE;
534 				break;
535 			case 'p':
536 				/* specify alternate path_to_inst file */
537 				inst_file = s_strdup(optarg);
538 				break;
539 			case 'R':
540 				/*
541 				 * Private flag for suninstall to populate
542 				 * device information on the installed root.
543 				 */
544 				root_dir = s_strdup(optarg);
545 				if (zone_pathcheck(root_dir) !=
546 				    DEVFSADM_SUCCESS)
547 				devfsadm_exit(devfsadm_copy());
548 				break;
549 			case 'r':
550 				devices_dir = s_strdup(optarg);
551 				if (zone_pathcheck(devices_dir) !=
552 				    DEVFSADM_SUCCESS)
553 					devfsadm_exit(1);
554 				break;
555 			case 's':
556 				/*
557 				 * suppress.  don't create nodes
558 				 * useful with -v or -V
559 				 */
560 				file_mods = FALSE;
561 				flush_path_to_inst_enable = FALSE;
562 				break;
563 			case 'v':
564 				/* documented verbose flag */
565 				add_verbose_id(VERBOSE_MID);
566 				break;
567 			case 'V':
568 				/* undocumented for extra verbose levels */
569 				add_verbose_id(optarg);
570 				break;
571 			default:
572 				usage();
573 			}
574 		}
575 
576 		if (optind < argc) {
577 			usage();
578 		}
579 
580 		if ((add_bind == TRUE) && (mc.major == -1 ||
581 		    mc.drvname[0] == NULL)) {
582 			err_print(MAJOR_AND_B_FLAG);
583 			devfsadm_exit(1);
584 		}
585 		if (add_bind == TRUE) {
586 			mc.num_aliases = num_aliases;
587 			mc.ap = a_head;
588 			retval =  modctl(MODADDMAJBIND, NULL, (caddr_t)&mc);
589 			if (retval < 0) {
590 				err_print(MODCTL_ADDMAJBIND);
591 			}
592 			devfsadm_exit(retval);
593 		}
594 
595 	} else if ((strcmp(prog, DEVFSADM) == 0) ||
596 	    (strcmp(prog, DEVFSADMD) == 0)) {
597 		char *zonename = NULL;
598 		enum zreg_op zoneop;
599 		int init_drvconf = 0;
600 		int init_perm = 0;
601 		int public_mode = 0;
602 
603 		if (strcmp(prog, DEVFSADMD) == 0) {
604 			daemon_mode = TRUE;
605 		}
606 
607 		devlinktab_file = DEVLINKTAB_FILE;
608 
609 		while ((opt = getopt(argc, argv,
610 		    "Cc:dIi:l:np:PR:r:st:vV:x:z:Z:")) != EOF) {
611 			if (opt == 'I' || opt == 'P') {
612 				if (public_mode)
613 					usage();
614 			} else {
615 				if (init_perm || init_drvconf)
616 					usage();
617 				public_mode = 1;
618 			}
619 			switch (opt) {
620 			case 'C':
621 				cleanup = TRUE;
622 				break;
623 			case 'c':
624 				num_classes++;
625 				classes = s_realloc(classes, num_classes *
626 						    sizeof (char *));
627 				classes[num_classes - 1] = optarg;
628 				break;
629 			case  'd':
630 				if (daemon_mode == FALSE) {
631 					devalloc_off = TRUE;
632 					build_dev = FALSE;
633 				}
634 				break;
635 			case 'I':	/* update kernel driver.conf cache */
636 				if (daemon_mode == TRUE)
637 					usage();
638 				init_drvconf = 1;
639 				break;
640 			case 'i':
641 				single_drv = TRUE;
642 				driver = s_strdup(optarg);
643 				break;
644 			case 'l':
645 				/* specify an alternate module load path */
646 				module_dirs = s_strdup(optarg);
647 				break;
648 			case 'n':
649 				/* prevent driver loading and deferred attach */
650 				load_attach_drv = FALSE;
651 				break;
652 			case 'p':
653 				/* specify alternate path_to_inst file */
654 				inst_file = s_strdup(optarg);
655 				break;
656 			case 'P':
657 				if (daemon_mode == TRUE)
658 					usage();
659 				/* load minor_perm and device_policy */
660 				init_perm = 1;
661 				break;
662 			case 'R':
663 				/*
664 				 * Private flag for suninstall to populate
665 				 * device information on the installed root.
666 				 */
667 				root_dir = s_strdup(optarg);
668 				devfsadm_exit(devfsadm_copy());
669 				break;
670 			case 'r':
671 				set_root_devices_dev_dir(optarg, 0);
672 				break;
673 			case 's':
674 				/*
675 				 * suppress. don't create/remove links/nodes
676 				 * useful with -v or -V
677 				 */
678 				file_mods = FALSE;
679 				flush_path_to_inst_enable = FALSE;
680 				break;
681 			case 't':
682 				devlinktab_file = optarg;
683 				break;
684 			case 'v':
685 				/* documented verbose flag */
686 				add_verbose_id(VERBOSE_MID);
687 				break;
688 			case 'V':
689 				/* undocumented: specify verbose lvl */
690 				add_verbose_id(optarg);
691 				break;
692 			case 'x':
693 				/*
694 				 * x is the "private switch" option.  The
695 				 * goal is to not suck up all the other
696 				 * option letters.
697 				 */
698 				if (strcmp(optarg, "update_devlinksdb") == 0) {
699 					update_database = TRUE;
700 				} else if (strcmp(optarg, "no_dev") == 0) {
701 					/* don't build /dev */
702 					build_dev = FALSE;
703 				} else if (strcmp(optarg, "no_devices") == 0) {
704 					/* don't build /devices */
705 					build_devices = FALSE;
706 				} else if (strcmp(optarg, "no_p2i") == 0) {
707 					/* don't flush path_to_inst */
708 					flush_path_to_inst_enable = FALSE;
709 				} else if (strcmp(optarg, "use_dicache") == 0) {
710 					use_snapshot_cache = TRUE;
711 				} else {
712 					usage();
713 				}
714 				break;
715 			case 'z':
716 				zonename = optarg;
717 				zoneop = ZONE_REG;
718 				break;
719 			case 'Z':
720 				zonename = optarg;
721 				zoneop = ZONE_UNREG;
722 				break;
723 			default:
724 				usage();
725 				break;
726 			}
727 
728 		}
729 		if (optind < argc) {
730 			usage();
731 		}
732 
733 		/*
734 		 * We're not in zone mode; Check to see if the rootpath
735 		 * collides with any zonepaths.
736 		 */
737 		if (zonename == NULL) {
738 			if (zone_pathcheck(root_dir) != DEVFSADM_SUCCESS)
739 				devfsadm_exit(1);
740 		}
741 
742 		if (zonename != NULL) {
743 			/*
744 			 * -z and -Z cannot be used if we're the daemon.  The
745 			 * daemon always manages all zones.
746 			 */
747 			if (daemon_mode == TRUE)
748 				usage();
749 
750 			/*
751 			 * -z and -Z are private flags, but to be paranoid we
752 			 * check whether they have been combined with -r.
753 			 */
754 			if (*root_dir != '\0')
755 				usage();
756 
757 			if (set_zone_params(optarg) != DEVFSADM_SUCCESS)
758 				devfsadm_exit(1);
759 
760 			call_zone_register(zonename, zoneop);
761 			if (zoneop == ZONE_UNREG)
762 				devfsadm_exit(0);
763 			/*
764 			 * If we are in ZONE_REG mode we plow on, laying out
765 			 * devices for this zone.
766 			 */
767 		}
768 		if (init_drvconf || init_perm) {
769 			/*
770 			 * Load minor perm before force-loading drivers
771 			 * so the correct permissions are picked up.
772 			 */
773 			if (init_perm)
774 				load_dev_acl();
775 			if (init_drvconf)
776 				update_drvconf((major_t)-1);
777 			devfsadm_exit(0);
778 			/* NOTREACHED */
779 		}
780 	}
781 
782 
783 	if (get_linkcompat_opts == TRUE) {
784 
785 		build_devices = FALSE;
786 		load_attach_drv = FALSE;
787 		num_classes++;
788 		classes = s_realloc(classes, num_classes *
789 		    sizeof (char *));
790 		classes[num_classes - 1] = compat_class;
791 
792 		while ((opt = getopt(argc, argv, "Cnr:svV:")) != EOF) {
793 			switch (opt) {
794 			case 'C':
795 				cleanup = TRUE;
796 				break;
797 			case 'n':
798 				/* prevent driver loading or deferred attach */
799 				load_attach_drv = FALSE;
800 				break;
801 			case 'r':
802 				set_root_devices_dev_dir(optarg, 0);
803 				if (zone_pathcheck(root_dir) !=
804 				    DEVFSADM_SUCCESS)
805 					devfsadm_exit(1);
806 				break;
807 			case 's':
808 				/* suppress.  don't create/remove links/nodes */
809 				/* useful with -v or -V */
810 				file_mods = FALSE;
811 				flush_path_to_inst_enable = FALSE;
812 				break;
813 			case 'v':
814 				/* documented verbose flag */
815 				add_verbose_id(VERBOSE_MID);
816 				break;
817 			case 'V':
818 				/* undocumented for extra verbose levels */
819 				add_verbose_id(optarg);
820 				break;
821 			default:
822 				usage();
823 			}
824 		}
825 		if (optind < argc) {
826 			usage();
827 		}
828 	}
829 }
830 
831 void
832 usage(void)
833 {
834 	if (strcmp(prog, DEVLINKS) == 0) {
835 		err_print(DEVLINKS_USAGE);
836 	} else if (strcmp(prog, DRVCONFIG) == 0) {
837 		err_print(DRVCONFIG_USAGE);
838 	} else if ((strcmp(prog, DEVFSADM) == 0) ||
839 			(strcmp(prog, DEVFSADMD) == 0)) {
840 		err_print(DEVFSADM_USAGE);
841 	} else {
842 		err_print(COMPAT_LINK_USAGE);
843 	}
844 
845 	devfsadm_exit(1);
846 }
847 
848 static void
849 devi_tree_walk(struct dca_impl *dcip, int flags, char *ev_subclass)
850 {
851 	char *msg, *name;
852 	struct mlist	mlist = {0};
853 	di_node_t	node;
854 
855 	vprint(CHATTY_MID, "devi_tree_walk: root=%s, minor=%s, driver=%s,"
856 	    " error=%d, flags=%u\n", dcip->dci_root,
857 	    dcip->dci_minor ? dcip->dci_minor : "<NULL>",
858 	    dcip->dci_driver ? dcip->dci_driver : "<NULL>", dcip->dci_error,
859 	    dcip->dci_flags);
860 
861 	assert(dcip->dci_root);
862 
863 	if (dcip->dci_flags & DCA_LOAD_DRV) {
864 		node = di_init_driver(dcip->dci_driver, flags);
865 		msg = DRIVER_FAILURE;
866 		name = dcip->dci_driver;
867 	} else {
868 		node = di_init(dcip->dci_root, flags);
869 		msg = DI_INIT_FAILED;
870 		name = dcip->dci_root;
871 	}
872 
873 	if (node == DI_NODE_NIL) {
874 		dcip->dci_error = errno;
875 		/*
876 		 * Rapid hotplugging (commonly seen during USB testing),
877 		 * may remove a device before the create event for it
878 		 * has been processed. To prevent alarming users with
879 		 * a superfluous message, we suppress error messages
880 		 * for ENXIO and hotplug.
881 		 */
882 		if (!(errno == ENXIO && (dcip->dci_flags & DCA_HOT_PLUG)))
883 			err_print(msg, name, strerror(dcip->dci_error));
884 		return;
885 	}
886 
887 	if (dcip->dci_flags & DCA_FLUSH_PATHINST)
888 		flush_path_to_inst();
889 
890 	dcip->dci_arg = &mlist;
891 
892 	vprint(CHATTY_MID, "walking device tree\n");
893 
894 	(void) di_walk_minor(node, NULL, DI_CHECK_ALIAS, dcip,
895 	    check_minor_type);
896 
897 	process_deferred_links(dcip, DCA_CREATE_LINK);
898 
899 	dcip->dci_arg = NULL;
900 
901 	/*
902 	 * Finished creating devfs files and dev links.
903 	 * Log sysevent and notify RCM.
904 	 */
905 	if (ev_subclass)
906 		build_and_log_event(EC_DEV_ADD, ev_subclass, dcip->dci_root,
907 		    node);
908 
909 	if ((dcip->dci_flags & DCA_NOTIFY_RCM) && rcm_hdl)
910 		(void) notify_rcm(node, dcip->dci_minor);
911 
912 	di_fini(node);
913 }
914 
915 static void
916 process_deferred_links(struct dca_impl *dcip, int flags)
917 {
918 	struct mlist	*dep;
919 	struct minor	*mp, *smp;
920 
921 	vprint(CHATTY_MID, "processing deferred links\n");
922 
923 	dep = dcip->dci_arg;
924 
925 	/*
926 	 * The list head is not used during the deferred create phase
927 	 */
928 	dcip->dci_arg = NULL;
929 
930 	assert(dep);
931 	assert((dep->head == NULL) ^ (dep->tail != NULL));
932 	assert(flags == DCA_FREE_LIST || flags == DCA_CREATE_LINK);
933 
934 	for (smp = NULL, mp = dep->head; mp; mp = mp->next) {
935 		if (flags == DCA_CREATE_LINK)
936 			(void) check_minor_type(mp->node, mp->minor, dcip);
937 		free(smp);
938 		smp = mp;
939 	}
940 
941 	free(smp);
942 }
943 
944 /*
945  * Called in non-daemon mode to take a snap shot of the devinfo tree.
946  * Then it calls the appropriate functions to build /devices and /dev.
947  * It also flushes path_to_inst.
948  */
949 void
950 process_devinfo_tree()
951 {
952 	uint_t		flags = DINFOCPYALL;
953 	struct dca_impl	dci;
954 	char		name[MAXNAMELEN];
955 	char		*fcn = "process_devinfo_tree: ";
956 
957 	vprint(CHATTY_MID, "%senter\n", fcn);
958 
959 	dca_impl_init("/", NULL, &dci);
960 
961 	lock_dev();
962 
963 	/*
964 	 * Update kernel driver.conf cache when devfsadm/drvconfig
965 	 * is invoked to build /devices and /dev.
966 	 */
967 	if (load_attach_drv == TRUE)
968 		update_drvconf((major_t)-1);
969 
970 	if (single_drv == TRUE) {
971 		/*
972 		 * load a single driver, but walk the entire devinfo tree
973 		 */
974 		if (load_attach_drv == FALSE)
975 			err_print(DRV_LOAD_REQD);
976 
977 		vprint(CHATTY_MID, "%sattaching driver (%s)\n", fcn, driver);
978 
979 		dci.dci_flags |= DCA_LOAD_DRV;
980 		(void) snprintf(name, sizeof (name), "%s", driver);
981 		dci.dci_driver = name;
982 
983 	} else if (load_attach_drv == TRUE) {
984 		/*
985 		 * load and attach all drivers, then walk the entire tree.
986 		 * If the cache flag is set, use DINFOCACHE to get cached
987 		 * data.
988 		 */
989 		if (use_snapshot_cache == TRUE) {
990 			flags = DINFOCACHE;
991 			vprint(CHATTY_MID, "%susing snapshot cache\n", fcn);
992 		} else {
993 			vprint(CHATTY_MID, "%sattaching all drivers\n", fcn);
994 			flags |= DINFOFORCE;
995 		}
996 	}
997 
998 	if (((load_attach_drv == TRUE) || (single_drv == TRUE)) &&
999 	    (build_devices == TRUE)) {
1000 		dci.dci_flags |= DCA_FLUSH_PATHINST;
1001 	}
1002 
1003 	/* handle pre-cleanup operations desired by the modules. */
1004 	pre_and_post_cleanup(RM_PRE);
1005 
1006 	devi_tree_walk(&dci, flags, NULL);
1007 
1008 	if (dci.dci_error) {
1009 		devfsadm_exit(1);
1010 	}
1011 
1012 	/* handle post-cleanup operations desired by the modules. */
1013 	pre_and_post_cleanup(RM_POST);
1014 
1015 	/*
1016 	 * Remove dangling entries from /etc/devices/devid_cache
1017 	 * if we forceloaded the entire device tree.
1018 	 */
1019 	if (cleanup && (flags & DINFOFORCE) == 0)
1020 		(void) modctl(MODCLEANUP, NULL, 0, NULL);
1021 
1022 	unlock_dev(SYNC_STATE);
1023 }
1024 
1025 /*ARGSUSED*/
1026 static void
1027 print_cache_signal(int signo)
1028 {
1029 
1030 	if (signal(SIGUSR1, print_cache_signal) == SIG_ERR) {
1031 		err_print("signal SIGUSR1 failed: %s\n", strerror(errno));
1032 		devfsadm_exit(1);
1033 	}
1034 }
1035 
1036 /*
1037  * Register with eventd for messages. Create doors for synchronous
1038  * link creation.
1039  */
1040 static void
1041 daemon_update(void)
1042 {
1043 	int fd;
1044 	char *fcn = "daemon_update: ";
1045 	char door_file[MAXPATHLEN];
1046 	const char *subclass_list;
1047 	sysevent_handle_t *sysevent_hp;
1048 	vprint(CHATTY_MID, "%senter\n", fcn);
1049 
1050 	if (signal(SIGUSR1, print_cache_signal) == SIG_ERR) {
1051 		err_print("signal SIGUSR1 failed: %s\n", strerror(errno));
1052 		devfsadm_exit(1);
1053 	}
1054 
1055 	if (snprintf(door_file, sizeof (door_file),
1056 	    "%s%s", root_dir, DEVFSADM_SERVICE_DOOR) >= sizeof (door_file)) {
1057 		err_print("update_daemon failed to open sysevent service "
1058 		    "door\n");
1059 		devfsadm_exit(1);
1060 	}
1061 	if ((sysevent_hp = sysevent_open_channel_alt(
1062 	    door_file)) == NULL) {
1063 		err_print(CANT_CREATE_DOOR,
1064 			door_file, strerror(errno));
1065 		devfsadm_exit(1);
1066 	}
1067 	if (sysevent_bind_subscriber(sysevent_hp, event_handler) != 0) {
1068 		err_print(CANT_CREATE_DOOR,
1069 		    door_file, strerror(errno));
1070 		(void) sysevent_close_channel(sysevent_hp);
1071 		devfsadm_exit(1);
1072 	}
1073 	subclass_list = EC_SUB_ALL;
1074 	if (sysevent_register_event(sysevent_hp, EC_ALL, &subclass_list, 1)
1075 	    != 0) {
1076 		err_print(CANT_CREATE_DOOR,
1077 		    door_file, strerror(errno));
1078 		(void) sysevent_unbind_subscriber(sysevent_hp);
1079 		(void) sysevent_close_channel(sysevent_hp);
1080 		devfsadm_exit(1);
1081 	}
1082 
1083 	if (snprintf(door_file, sizeof (door_file),
1084 	    "%s/%s", dev_dir, ZONE_REG_DOOR) >= sizeof (door_file)) {
1085 		err_print(CANT_CREATE_ZONE_DOOR, door_file,
1086 		    strerror(ENAMETOOLONG));
1087 		devfsadm_exit(1);
1088 	}
1089 	(void) s_unlink(door_file);
1090 	if ((fd = open(door_file, O_RDWR | O_CREAT, ZONE_DOOR_PERMS)) == -1) {
1091 		err_print(CANT_CREATE_ZONE_DOOR, door_file, strerror(errno));
1092 		devfsadm_exit(1);
1093 	}
1094 	(void) close(fd);
1095 	if ((fd = door_create(zone_reg_handler, NULL,
1096 	    DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) == -1) {
1097 		err_print(CANT_CREATE_ZONE_DOOR, door_file, strerror(errno));
1098 		(void) s_unlink(door_file);
1099 		devfsadm_exit(1);
1100 	}
1101 	if (fattach(fd, door_file) == -1) {
1102 		err_print(CANT_CREATE_ZONE_DOOR, door_file, strerror(errno));
1103 		(void) s_unlink(door_file);
1104 		devfsadm_exit(1);
1105 	}
1106 
1107 	(void) snprintf(door_file, sizeof (door_file), "%s/%s", dev_dir,
1108 	    DEVFSADM_SYNCH_DOOR);
1109 
1110 	(void) s_unlink(door_file);
1111 	if ((fd = open(door_file, O_RDWR | O_CREAT, SYNCH_DOOR_PERMS)) == -1) {
1112 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1113 		devfsadm_exit(1);
1114 	}
1115 	(void) close(fd);
1116 
1117 	if ((fd = door_create(sync_handler, NULL,
1118 	    DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) == -1) {
1119 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1120 		(void) s_unlink(door_file);
1121 		devfsadm_exit(1);
1122 	}
1123 
1124 	if (fattach(fd, door_file) == -1) {
1125 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1126 		(void) s_unlink(door_file);
1127 		devfsadm_exit(1);
1128 	}
1129 	devlink_door_fd = fd;
1130 
1131 	/*
1132 	 * Make sure devfsadm is managing any and all configured system zones.
1133 	 */
1134 	if (register_all_zones() != DEVFSADM_SUCCESS) {
1135 		err_print(ZONE_LIST_FAILED, strerror(errno));
1136 	}
1137 
1138 	vprint(CHATTY_MID, "%spausing\n", fcn);
1139 	for (;;) {
1140 		(void) pause();
1141 	}
1142 }
1143 
1144 /*ARGSUSED*/
1145 static void
1146 sync_handler(void *cookie, char *ap, size_t asize,
1147     door_desc_t *dp, uint_t ndesc)
1148 {
1149 	door_cred_t	dcred;
1150 	struct dca_off	*dcp, rdca;
1151 	struct dca_impl dci;
1152 
1153 	/*
1154 	 * Must be root to make this call
1155 	 * If caller is not root, don't touch its data.
1156 	 */
1157 	if (door_cred(&dcred) != 0 || dcred.dc_euid != 0) {
1158 		dcp = &rdca;
1159 		dcp->dca_error = EPERM;
1160 		goto out;
1161 	}
1162 
1163 	assert(ap);
1164 	assert(asize == sizeof (*dcp));
1165 
1166 	dcp = (void *)ap;
1167 
1168 	/*
1169 	 * Root is always present and is the first component of "name" member
1170 	 */
1171 	assert(dcp->dca_root == 0);
1172 
1173 	/*
1174 	 * The structure passed in by the door_client uses offsets
1175 	 * instead of pointers to work across address space boundaries.
1176 	 * Now copy the data into a structure (dca_impl) which uses
1177 	 * pointers.
1178 	 */
1179 	dci.dci_root = &dcp->dca_name[dcp->dca_root];
1180 	dci.dci_minor = dcp->dca_minor ? &dcp->dca_name[dcp->dca_minor] : NULL;
1181 	dci.dci_driver =
1182 	    dcp->dca_driver ? &dcp->dca_name[dcp->dca_driver] : NULL;
1183 	dci.dci_error = 0;
1184 	dci.dci_flags = dcp->dca_flags | (dci.dci_driver ? DCA_LOAD_DRV : 0);
1185 	dci.dci_arg = NULL;
1186 
1187 	lock_dev();
1188 
1189 	devi_tree_walk(&dci, DINFOCPYALL, NULL);
1190 
1191 	unlock_dev(CACHE_STATE);
1192 
1193 	dcp->dca_error = dci.dci_error;
1194 
1195 	startup_cache_sync_thread();
1196 
1197 out:
1198 	(void) door_return((char *)dcp, sizeof (*dcp), NULL, 0);
1199 }
1200 
1201 static void
1202 lock_dev(void)
1203 {
1204 	vprint(CHATTY_MID, "lock_dev(): entered\n");
1205 
1206 	if (build_dev == FALSE)
1207 		return;
1208 
1209 	/* lockout other threads from /dev */
1210 	while (sema_wait(&dev_sema) != 0);
1211 
1212 	/*
1213 	 * Lock out other devfsadm processes from /dev.
1214 	 * If this wasn't the last process to run,
1215 	 * clear caches
1216 	 */
1217 	if (enter_dev_lock() != getpid()) {
1218 		invalidate_enumerate_cache();
1219 		rm_all_links_from_cache();
1220 		(void) di_devlink_close(&devlink_cache, DI_LINK_ERROR);
1221 		devlink_cache = NULL;
1222 	}
1223 
1224 	/*
1225 	 * (re)load the  reverse links database if not
1226 	 * already cached.
1227 	 */
1228 	if (devlink_cache == NULL)
1229 		devlink_cache = di_devlink_open(root_dir, 0);
1230 
1231 
1232 	/*
1233 	 * If modules were unloaded, reload them.  Also use module status
1234 	 * as an indication that we should check to see if other binding
1235 	 * files need to be reloaded.
1236 	 */
1237 	if (module_head == NULL) {
1238 		load_modules();
1239 		read_minor_perm_file();
1240 		read_driver_aliases_file();
1241 		read_devlinktab_file();
1242 		read_logindevperm_file();
1243 	}
1244 
1245 	if (module_head != NULL)
1246 		return;
1247 
1248 	if (strcmp(prog, DEVLINKS) == 0) {
1249 		if (devlinktab_list == NULL) {
1250 			err_print(NO_LINKTAB, devlinktab_file);
1251 			err_print(NO_MODULES, module_dirs);
1252 			err_print(ABORTING);
1253 			devfsadm_exit(1);
1254 		}
1255 	} else {
1256 		err_print(NO_MODULES, module_dirs);
1257 		if (strcmp(prog, DEVFSADM) == 0) {
1258 			err_print(MODIFY_PATH);
1259 		}
1260 	}
1261 }
1262 
1263 static void
1264 unlock_dev(int flag)
1265 {
1266 	vprint(CHATTY_MID, "unlock_dev(): entered\n");
1267 
1268 	if (build_dev == FALSE)
1269 		return;
1270 
1271 	assert(devlink_cache);
1272 	assert(flag == SYNC_STATE || flag == CACHE_STATE);
1273 
1274 
1275 	if (flag == SYNC_STATE) {
1276 		unload_modules();
1277 		if (update_database)
1278 			(void) di_devlink_update(devlink_cache);
1279 		(void) di_devlink_close(&devlink_cache, 0);
1280 		devlink_cache = NULL;
1281 	}
1282 
1283 	exit_dev_lock();
1284 
1285 	(void) sema_post(&dev_sema);
1286 }
1287 
1288 /*
1289  * Contact the daemon to register the identified zone.  We do everything with
1290  * zone names, for simplicity.
1291  */
1292 static void
1293 call_zone_register(char *zone_name, int regop)
1294 {
1295 	int doorfd, ret, retries = 0;
1296 	door_arg_t arg;
1297 	struct zreg z;
1298 	char path[MAXPATHLEN];
1299 
1300 	assert(regop == ZONE_REG || regop == ZONE_UNREG);
1301 
1302 	if (strcmp(zone_name, GLOBAL_ZONENAME) == 0) {
1303 		err_print(INVALID_ZONE, zone_name);
1304 		return;
1305 	}
1306 
1307 	z.zreg_error = 0;
1308 	z.zreg_op = regop;
1309 	(void) strlcpy(z.zreg_zonename, zone_name, ZONENAME_MAX);
1310 
1311 	(void) snprintf(path, sizeof (path), "/dev/%s", ZONE_REG_DOOR);
1312 	if ((doorfd = open(path, O_RDWR)) == -1) {
1313 		return;
1314 	}
1315 
1316 	bzero(&arg, sizeof (arg));
1317 	arg.data_ptr = (char *)&z;
1318 	arg.data_size = sizeof (z);
1319 	arg.rbuf = (char *)&z;
1320 	arg.rsize = sizeof (z);
1321 
1322 	/*
1323 	 * If the daemon is running, tell it about the zone.  If not, it's
1324 	 * ok.  When it next gets run by the system (because there is
1325 	 * device-related work to do), it will load the list of zones from
1326 	 * the kernel.
1327 	 */
1328 	while (((ret = door_call(doorfd, &arg)) == -1) && retries++ < 3) {
1329 		(void) sleep(retries);
1330 	}
1331 	(void) close(doorfd);
1332 
1333 	if (ret != 0) {
1334 		return;
1335 	}
1336 
1337 	switch (z.zreg_error) {
1338 	case ZONE_SUCCESS:
1339 		break;
1340 	case ZONE_ERR_NOZONE:
1341 		err_print(ZONE_REG_FAILED, zone_name, strerror(z.zreg_errno));
1342 		break;
1343 	case ZONE_ERR_DOOR:
1344 		err_print(ZONE_DOOR_MKFAIL, zone_name, strerror(z.zreg_errno));
1345 		break;
1346 	case ZONE_ERR_REPOSITORY:
1347 		err_print(ZONE_REP_FAILED, zone_name, strerror(z.zreg_errno));
1348 		break;
1349 	case ZONE_ERR_NOLIB:
1350 		err_print(ZONE_LIB_MISSING);
1351 		break;
1352 	default:
1353 		err_print(ZONE_REG_FAILED, zone_name, strerror(z.zreg_errno));
1354 		break;
1355 	}
1356 }
1357 
1358 /*
1359  * The following routines are the daemon-side code for managing the set of
1360  * currently registered zones.
1361  *
1362  * TODO: improve brain-dead list performance--- use libuutil avl tree or hash?
1363  */
1364 static void
1365 zlist_insert(struct zone_devinfo *newzone)
1366 {
1367 	struct zone_devinfo *z;
1368 	assert(MUTEX_HELD(&zone_mutex));
1369 
1370 	if (zone_head == NULL) {
1371 		zone_head = newzone;
1372 		return;
1373 	}
1374 	z = zlist_remove(newzone->zone_name);
1375 	if (z != NULL)
1376 		delete_zone(z);
1377 	newzone->zone_next = zone_head;
1378 	zone_head = newzone;
1379 }
1380 
1381 static void
1382 delete_zone(struct zone_devinfo *z) {
1383 	char door_file[PATH_MAX];
1384 
1385 	/*
1386 	 * Tidy up by withdrawing our door from the zone.
1387 	 */
1388 	(void) snprintf(door_file, sizeof (door_file), "%s/dev/%s",
1389 	    z->zone_path, DEVFSADM_SYNCH_DOOR);
1390 	(void) s_unlink(door_file);
1391 
1392 	zonecfg_fini_handle(z->zone_dochdl);
1393 	free(z->zone_path);
1394 	free(z->zone_name);
1395 	free(z);
1396 }
1397 
1398 static struct zone_devinfo *
1399 zlist_remove(char *zone_name)
1400 {
1401 	struct zone_devinfo *z, *unlinked = NULL, **prevnextp;
1402 	assert(MUTEX_HELD(&zone_mutex));
1403 
1404 	prevnextp = &zone_head;
1405 	for (z = zone_head; z != NULL; z = z->zone_next) {
1406 		if (strcmp(zone_name, z->zone_name) == 0) {
1407 			unlinked = z;
1408 			*prevnextp = z->zone_next;
1409 			return (unlinked);
1410 		}
1411 		prevnextp = &(z->zone_next);
1412 	}
1413 	return (NULL);
1414 }
1415 
1416 /*
1417  * Delete all zones.  Note that this should *only* be called in the exit
1418  * path of the daemon, as it does not take the zone_mutex-- this is because
1419  * we could wind up calling devfsadm_exit() with that zone_mutex_held.
1420  */
1421 static void
1422 zlist_deleteall_unlocked(void)
1423 {
1424 	struct zone_devinfo *tofree;
1425 
1426 	while (zone_head != NULL) {
1427 		tofree = zone_head;
1428 		zone_head = zone_head->zone_next;
1429 		delete_zone(tofree);
1430 	}
1431 	assert(zone_head == NULL);
1432 }
1433 
1434 static int
1435 zone_register(char *zone_name)
1436 {
1437 	char		door_file[MAXPATHLEN], zpath[MAXPATHLEN];
1438 	int		fd;
1439 	int 		need_unlink = 0, error = ZONE_SUCCESS, myerrno = 0;
1440 	zone_dochandle_t hdl = NULL;
1441 	void		*dlhdl = NULL;
1442 	struct zone_devinfo *newzone = NULL;
1443 
1444 	assert(MUTEX_HELD(&zone_mutex));
1445 
1446 	if ((dlhdl = dlopen(LIBZONECFG_PATH, RTLD_LAZY)) == NULL) {
1447 		error = ZONE_ERR_NOLIB;
1448 		goto bad;
1449 	}
1450 
1451 	if (zone_get_zonepath(zone_name, zpath, sizeof (zpath)) != Z_OK) {
1452 		error = ZONE_ERR_NOZONE;
1453 		myerrno = errno;
1454 		goto bad;
1455 	}
1456 
1457 	if (snprintf(door_file, sizeof (door_file), "%s/dev/%s",
1458 	    zpath, DEVFSADM_SYNCH_DOOR) >= sizeof (door_file)) {
1459 		myerrno = ENAMETOOLONG;	/* synthesize a reasonable errno */
1460 		error = ZONE_ERR_DOOR;
1461 		goto bad;
1462 	}
1463 
1464 	(void) s_unlink(door_file);
1465 	if ((fd = open(door_file, O_RDWR | O_CREAT, ZONE_DOOR_PERMS)) == -1) {
1466 		myerrno = errno;
1467 		error = ZONE_ERR_DOOR;
1468 		goto bad;
1469 	}
1470 	need_unlink = 1;
1471 	(void) close(fd);
1472 
1473 	if (fattach(devlink_door_fd, door_file) == -1) {
1474 		error = ZONE_ERR_DOOR;
1475 		myerrno = errno;
1476 		goto bad;
1477 	}
1478 
1479 	if ((hdl = zonecfg_init_handle()) == NULL) {
1480 		error = ZONE_ERR_REPOSITORY;
1481 		myerrno = errno;
1482 		goto bad;
1483 	}
1484 
1485 	if ((zonecfg_get_snapshot_handle(zone_name, hdl)) != Z_OK) {
1486 		error = ZONE_ERR_REPOSITORY;
1487 		myerrno = errno;
1488 		goto bad;
1489 	}
1490 
1491 	newzone = s_malloc(sizeof (struct zone_devinfo));
1492 	newzone->zone_path = s_strdup(zpath);
1493 	newzone->zone_name = s_strdup(zone_name);
1494 	newzone->zone_next = NULL;
1495 	newzone->zone_dochdl = hdl;
1496 	zlist_insert(newzone);
1497 	(void) dlclose(dlhdl);
1498 
1499 	return (ZONE_SUCCESS);
1500 
1501 bad:
1502 	(void) devfsadm_errprint("%s[%ld]: failed to register zone %s: %s",
1503 	    prog, getpid(), zone_name, strerror(myerrno));
1504 
1505 	assert(newzone == NULL);
1506 	if (need_unlink)
1507 		(void) s_unlink(door_file);
1508 	if (hdl)
1509 		zonecfg_fini_handle(hdl);
1510 	if (dlhdl)
1511 		(void) dlclose(dlhdl);
1512 	errno = myerrno;
1513 	return (error);
1514 }
1515 
1516 static int
1517 zone_unregister(char *zone_name)
1518 {
1519 	struct zone_devinfo *z;
1520 
1521 	assert(MUTEX_HELD(&zone_mutex));
1522 
1523 	if ((z = zlist_remove(zone_name)) == NULL)
1524 		return (ZONE_ERR_NOZONE);
1525 
1526 	delete_zone(z);
1527 	return (ZONE_SUCCESS);
1528 }
1529 
1530 /*
1531  *  Called by the daemon when it receives a door call to the zone registration
1532  *  door.
1533  */
1534 /*ARGSUSED*/
1535 static void
1536 zone_reg_handler(void *cookie, char *ap, size_t asize, door_desc_t *dp,
1537     uint_t ndesc)
1538 {
1539 	door_cred_t	dcred;
1540 	struct zreg 	*zregp, rzreg;
1541 
1542 	/*
1543 	 * We coarsely lock the whole registration process.
1544 	 */
1545 	(void) mutex_lock(&zone_mutex);
1546 
1547 	/*
1548 	 * Must be root to make this call
1549 	 * If caller is not root, don't touch its data.
1550 	 */
1551 	if (door_cred(&dcred) != 0 || dcred.dc_euid != 0) {
1552 		zregp = &rzreg;
1553 		zregp->zreg_error = ZONE_ERR_REPOSITORY;
1554 		zregp->zreg_errno = EPERM;
1555 		goto out;
1556 	}
1557 
1558 	assert(ap);
1559 	assert(asize == sizeof (*zregp));
1560 
1561 	zregp = (struct zreg *)(void *)ap;
1562 
1563 	/*
1564 	 * Kernel must know about this zone; one way of discovering this
1565 	 * is by looking up the zone id.
1566 	 */
1567 	if (getzoneidbyname(zregp->zreg_zonename) == -1) {
1568 		zregp->zreg_error = ZONE_ERR_REPOSITORY;
1569 		zregp->zreg_errno = errno;
1570 		goto out;
1571 	}
1572 
1573 	if (zregp->zreg_op == ZONE_REG) {
1574 		zregp->zreg_error = zone_register(zregp->zreg_zonename);
1575 		zregp->zreg_errno = errno;
1576 	} else {
1577 		zregp->zreg_error = zone_unregister(zregp->zreg_zonename);
1578 		zregp->zreg_errno = errno;
1579 	}
1580 
1581 out:
1582 	(void) mutex_unlock(&zone_mutex);
1583 	(void) door_return((char *)zregp, sizeof (*zregp), NULL, 0);
1584 }
1585 
1586 static int
1587 register_all_zones(void)
1588 {
1589 	zoneid_t *zids = NULL;
1590 	uint_t nzents, nzents_saved;
1591 	int i;
1592 
1593 	(void) mutex_lock(&zone_mutex);
1594 	if (zone_list(NULL, &nzents) != 0)
1595 		return (DEVFSADM_FAILURE);
1596 
1597 again:
1598 	assert(zids == NULL);
1599 	assert(MUTEX_HELD(&zone_mutex));
1600 	if (nzents == 0) {
1601 		(void) mutex_unlock(&zone_mutex);
1602 		return (DEVFSADM_SUCCESS);
1603 	}
1604 	zids = s_zalloc(nzents * sizeof (zoneid_t));
1605 	nzents_saved = nzents;
1606 	if (zone_list(zids, &nzents) != 0) {
1607 		(void) mutex_unlock(&zone_mutex);
1608 		free(zids);
1609 		return (DEVFSADM_FAILURE);
1610 	}
1611 	if (nzents != nzents_saved) {
1612 		/* list changed, try again */
1613 		free(zids);
1614 		zids = NULL;
1615 		goto again;
1616 	}
1617 
1618 	assert(zids != NULL);
1619 	for (i = 0; i < nzents; i++) {
1620 		char name[ZONENAME_MAX];
1621 
1622 		if (zids[i] == GLOBAL_ZONEID)
1623 			continue;
1624 		if (getzonenamebyid(zids[i], name, sizeof (name)) >= 0)
1625 			(void) zone_register(name);
1626 	}
1627 
1628 	(void) mutex_unlock(&zone_mutex);
1629 	free(zids);
1630 	return (DEVFSADM_SUCCESS);
1631 }
1632 
1633 /*
1634  * Check that if -r is set, it is not any part of a zone--- that is, that
1635  * the zonepath is not a substring of the root path.
1636  */
1637 static int
1638 zone_pathcheck(char *checkpath)
1639 {
1640 	void		*dlhdl = NULL;
1641 	char		*name;
1642 	char		root[MAXPATHLEN]; /* resolved devfsadm root path */
1643 	char		zroot[MAXPATHLEN]; /* zone root path */
1644 	char		rzroot[MAXPATHLEN]; /* resolved zone root path */
1645 	char 		tmp[MAXPATHLEN];
1646 	FILE		*cookie;
1647 	int		err = DEVFSADM_SUCCESS;
1648 
1649 	if (checkpath[0] == '\0')
1650 		return (DEVFSADM_SUCCESS);
1651 
1652 	/*
1653 	 * Check if zones is available on this system.
1654 	 */
1655 	if ((dlhdl = dlopen(LIBZONECFG_PATH, RTLD_LAZY)) == NULL) {
1656 		return (DEVFSADM_SUCCESS);
1657 	}
1658 
1659 	bzero(root, sizeof (root));
1660 	if (resolvepath(checkpath, root, sizeof (root) - 1) == -1) {
1661 		/*
1662 		 * In this case the user has done 'devfsadm -r' on some path
1663 		 * which does not yet exist, or we got some other misc. error.
1664 		 * We punt and don't resolve the path in this case.
1665 		 */
1666 		(void) strlcpy(root, checkpath, sizeof (root));
1667 	}
1668 
1669 	if (strlen(root) > 0 && (root[strlen(root) - 1] != '/')) {
1670 		(void) snprintf(tmp, sizeof (tmp), "%s/", root);
1671 		(void) strlcpy(root, tmp, sizeof (root));
1672 	}
1673 
1674 	cookie = setzoneent();
1675 	while ((name = getzoneent(cookie)) != NULL) {
1676 		/* Skip the global zone */
1677 		if (strcmp(name, GLOBAL_ZONENAME) == 0) {
1678 			free(name);
1679 			continue;
1680 		}
1681 
1682 		if (zone_get_zonepath(name, zroot, sizeof (zroot)) != Z_OK) {
1683 			free(name);
1684 			continue;
1685 		}
1686 
1687 		bzero(rzroot, sizeof (rzroot));
1688 		if (resolvepath(zroot, rzroot, sizeof (rzroot) - 1) == -1) {
1689 			/*
1690 			 * Zone path doesn't exist, or other misc error,
1691 			 * so we try using the non-resolved pathname.
1692 			 */
1693 			(void) strlcpy(rzroot, zroot, sizeof (rzroot));
1694 		}
1695 		if (strlen(rzroot) > 0 && (rzroot[strlen(rzroot) - 1] != '/')) {
1696 			(void) snprintf(tmp, sizeof (tmp), "%s/", rzroot);
1697 			(void) strlcpy(rzroot, tmp, sizeof (rzroot));
1698 		}
1699 
1700 		/*
1701 		 * Finally, the comparison.  If the zone root path is a
1702 		 * leading substring of the root path, fail.
1703 		 */
1704 		if (strncmp(rzroot, root, strlen(rzroot)) == 0) {
1705 			err_print(ZONE_PATHCHECK, root, name);
1706 			err = DEVFSADM_FAILURE;
1707 			free(name);
1708 			break;
1709 		}
1710 		free(name);
1711 	}
1712 	endzoneent(cookie);
1713 	(void) dlclose(dlhdl);
1714 	return (err);
1715 }
1716 
1717 /*
1718  *  Called by the daemon when it receives an event from the devfsadm SLM
1719  *  to syseventd.
1720  *
1721  *  The devfsadm SLM uses a private event channel for communication to
1722  *  devfsadmd set-up via private libsysevent interfaces.  This handler is
1723  *  used to bind to the devfsadmd channel for event delivery.
1724  *  The devfsadmd SLM insures single calls to this routine as well as
1725  *  synchronized event delivery.
1726  *
1727  */
1728 static void
1729 event_handler(sysevent_t *ev)
1730 {
1731 	char *path;
1732 	char *minor;
1733 	char *subclass;
1734 	char *dev_ev_subclass;
1735 	char *driver_name;
1736 	nvlist_t *attr_list = NULL;
1737 	int err = 0;
1738 	int instance;
1739 	int branch_event = 0;
1740 
1741 	subclass = sysevent_get_subclass_name(ev);
1742 	vprint(EVENT_MID, "event_handler: %s id:0X%llx\n",
1743 	    subclass, sysevent_get_seq(ev));
1744 
1745 	/* Check if event is an instance modification */
1746 	if (strcmp(subclass, ESC_DEVFS_INSTANCE_MOD) == 0) {
1747 		devfs_instance_mod();
1748 		return;
1749 	}
1750 	if (sysevent_get_attr_list(ev, &attr_list) != 0) {
1751 		vprint(EVENT_MID, "event_handler: can not get attr list\n");
1752 		return;
1753 	}
1754 
1755 	if (strcmp(subclass, ESC_DEVFS_DEVI_ADD) == 0 ||
1756 	    strcmp(subclass, ESC_DEVFS_DEVI_REMOVE) == 0 ||
1757 	    strcmp(subclass, ESC_DEVFS_MINOR_CREATE) == 0 ||
1758 	    strcmp(subclass, ESC_DEVFS_MINOR_REMOVE) == 0) {
1759 		if ((err = nvlist_lookup_string(attr_list, DEVFS_PATHNAME,
1760 		    &path)) != 0)
1761 			goto out;
1762 
1763 		if (strcmp(subclass, ESC_DEVFS_DEVI_ADD) == 0 ||
1764 		    strcmp(subclass, ESC_DEVFS_DEVI_REMOVE) == 0) {
1765 			if (nvlist_lookup_string(attr_list, DEVFS_DEVI_CLASS,
1766 			    &dev_ev_subclass) != 0)
1767 				dev_ev_subclass = NULL;
1768 
1769 			if (nvlist_lookup_string(attr_list, DEVFS_DRIVER_NAME,
1770 			    &driver_name) != 0)
1771 				driver_name = NULL;
1772 
1773 			if (nvlist_lookup_int32(attr_list, DEVFS_INSTANCE,
1774 			    &instance) != 0)
1775 				instance = -1;
1776 
1777 			if (nvlist_lookup_int32(attr_list, DEVFS_BRANCH_EVENT,
1778 			    &branch_event) != 0)
1779 				branch_event = 0;
1780 
1781 		} else {
1782 			if (nvlist_lookup_string(attr_list, DEVFS_MINOR_NAME,
1783 			    &minor) != 0)
1784 				minor = NULL;
1785 		}
1786 
1787 		lock_dev();
1788 
1789 		if (strcmp(ESC_DEVFS_DEVI_ADD, subclass) == 0) {
1790 			add_minor_pathname(path, NULL, dev_ev_subclass);
1791 			if (branch_event) {
1792 				build_and_log_event(EC_DEV_BRANCH,
1793 				    ESC_DEV_BRANCH_ADD, path, DI_NODE_NIL);
1794 			}
1795 
1796 		} else if (strcmp(ESC_DEVFS_MINOR_CREATE, subclass) == 0) {
1797 			add_minor_pathname(path, minor, NULL);
1798 
1799 		} else if (strcmp(ESC_DEVFS_MINOR_REMOVE, subclass) == 0) {
1800 			hot_cleanup(path, minor, NULL, NULL, -1);
1801 
1802 		} else { /* ESC_DEVFS_DEVI_REMOVE */
1803 			hot_cleanup(path, NULL, dev_ev_subclass,
1804 			    driver_name, instance);
1805 			if (branch_event) {
1806 				build_and_log_event(EC_DEV_BRANCH,
1807 				    ESC_DEV_BRANCH_REMOVE, path, DI_NODE_NIL);
1808 			}
1809 		}
1810 
1811 		unlock_dev(CACHE_STATE);
1812 		startup_cache_sync_thread();
1813 
1814 	} else if (strcmp(subclass, ESC_DEVFS_BRANCH_ADD) == 0 ||
1815 	    strcmp(subclass, ESC_DEVFS_BRANCH_REMOVE) == 0) {
1816 		if ((err = nvlist_lookup_string(attr_list,
1817 		    DEVFS_PATHNAME, &path)) != 0)
1818 			goto out;
1819 
1820 		/* just log ESC_DEV_BRANCH... event */
1821 		if (strcmp(subclass, ESC_DEVFS_BRANCH_ADD) == 0)
1822 			dev_ev_subclass = ESC_DEV_BRANCH_ADD;
1823 		else
1824 			dev_ev_subclass = ESC_DEV_BRANCH_REMOVE;
1825 
1826 		lock_dev();
1827 		build_and_log_event(EC_DEV_BRANCH, dev_ev_subclass, path,
1828 		    DI_NODE_NIL);
1829 		unlock_dev(CACHE_STATE);
1830 		startup_cache_sync_thread();
1831 
1832 	} else
1833 		err_print(UNKNOWN_EVENT, subclass);
1834 
1835 out:
1836 	if (err)
1837 		err_print(EVENT_ATTR_LOOKUP_FAILED, strerror(err));
1838 	nvlist_free(attr_list);
1839 }
1840 
1841 static void
1842 dca_impl_init(char *root, char *minor, struct dca_impl *dcip)
1843 {
1844 	assert(root);
1845 
1846 	dcip->dci_root = root;
1847 	dcip->dci_minor = minor;
1848 	dcip->dci_driver = NULL;
1849 	dcip->dci_error = 0;
1850 	dcip->dci_flags = 0;
1851 	dcip->dci_arg = NULL;
1852 }
1853 
1854 /*
1855  *  Kernel logs a message when a devinfo node is attached.  Try to create
1856  *  /dev and /devices for each minor node.  minorname can be NULL.
1857  */
1858 void
1859 add_minor_pathname(char *node, char *minor, char *ev_subclass)
1860 {
1861 	struct dca_impl	dci;
1862 
1863 	vprint(CHATTY_MID, "add_minor_pathname: node_path=%s minor=%s\n",
1864 	    node, minor ? minor : "NULL");
1865 
1866 	dca_impl_init(node, minor, &dci);
1867 
1868 	/*
1869 	 * Restrict hotplug link creation if daemon
1870 	 * started  with -i option.
1871 	 */
1872 	if (single_drv == TRUE) {
1873 		dci.dci_driver = driver;
1874 	}
1875 
1876 	/*
1877 	 * We are being invoked in response to a hotplug
1878 	 * event. Also, notify RCM if nodetype indicates
1879 	 * a network device has been hotplugged.
1880 	 */
1881 	dci.dci_flags = DCA_HOT_PLUG | DCA_CHECK_TYPE;
1882 
1883 	devi_tree_walk(&dci, DINFOPROP|DINFOMINOR, ev_subclass);
1884 }
1885 
1886 static di_node_t
1887 find_clone_node()
1888 {
1889 	static di_node_t clone_node = DI_NODE_NIL;
1890 
1891 	if (clone_node == DI_NODE_NIL)
1892 		clone_node = di_init("/pseudo/clone@0", DINFOPROP);
1893 	return (clone_node);
1894 }
1895 
1896 static int
1897 is_descendent_of(di_node_t node, char *driver)
1898 {
1899 	while (node != DI_NODE_NIL) {
1900 		char *drv = di_driver_name(node);
1901 		if (strcmp(drv, driver) == 0)
1902 			return (1);
1903 		node = di_parent_node(node);
1904 	}
1905 	return (0);
1906 }
1907 
1908 /*
1909  * Checks the minor type.  If it is an alias node, then lookup
1910  * the real node/minor first, then call minor_process() to
1911  * do the real work.
1912  */
1913 static int
1914 check_minor_type(di_node_t node, di_minor_t minor, void *arg)
1915 {
1916 	ddi_minor_type	minor_type;
1917 	di_node_t	clone_node;
1918 	char		*mn;
1919 	char		*nt;
1920 	struct mlist	*dep;
1921 	struct dca_impl	*dcip = arg;
1922 
1923 	assert(dcip);
1924 
1925 	dep = dcip->dci_arg;
1926 
1927 	mn = di_minor_name(minor);
1928 
1929 	/*
1930 	 * We match driver here instead of in minor_process
1931 	 * as we want the actual driver name. This check is
1932 	 * unnecessary during deferred processing.
1933 	 */
1934 	if (dep &&
1935 	    ((dcip->dci_driver && !is_descendent_of(node, dcip->dci_driver)) ||
1936 	    (dcip->dci_minor && strcmp(mn, dcip->dci_minor)))) {
1937 		return (DI_WALK_CONTINUE);
1938 	}
1939 
1940 	if ((dcip->dci_flags & DCA_CHECK_TYPE) &&
1941 	    (nt = di_minor_nodetype(minor)) &&
1942 	    (strcmp(nt, DDI_NT_NET) == 0)) {
1943 		dcip->dci_flags |= DCA_NOTIFY_RCM;
1944 		dcip->dci_flags &= ~DCA_CHECK_TYPE;
1945 	}
1946 
1947 	minor_type = di_minor_type(minor);
1948 
1949 	if (minor_type == DDM_MINOR) {
1950 		minor_process(node, minor, dep);
1951 
1952 	} else if (minor_type == DDM_ALIAS) {
1953 		struct mlist *cdep, clone_del = {0};
1954 
1955 		clone_node = find_clone_node();
1956 		if (clone_node == DI_NODE_NIL) {
1957 			err_print(DI_INIT_FAILED, "clone", strerror(errno));
1958 			return (DI_WALK_CONTINUE);
1959 		}
1960 
1961 		cdep = dep ? &clone_del : NULL;
1962 
1963 		minor_process(clone_node, minor, cdep);
1964 
1965 		/*
1966 		 * cache "alias" minor node and free "clone" minor
1967 		 */
1968 		if (cdep != NULL && cdep->head != NULL) {
1969 			assert(cdep->tail != NULL);
1970 			cache_deferred_minor(dep, node, minor);
1971 			dcip->dci_arg = cdep;
1972 			process_deferred_links(dcip, DCA_FREE_LIST);
1973 			dcip->dci_arg = dep;
1974 		}
1975 	}
1976 
1977 	return (DI_WALK_CONTINUE);
1978 }
1979 
1980 
1981 /*
1982  *  This is the entry point for each minor node, whether walking
1983  *  the entire tree via di_walk_minor() or processing a hotplug event
1984  *  for a single devinfo node (via hotplug ndi_devi_online()).
1985  */
1986 /*ARGSUSED*/
1987 static void
1988 minor_process(di_node_t node, di_minor_t minor, struct mlist *dep)
1989 {
1990 	create_list_t	*create;
1991 	int		defer;
1992 
1993 	vprint(CHATTY_MID, "minor_process: node=%s, minor=%s\n",
1994 		di_node_name(node), di_minor_name(minor));
1995 
1996 	if (dep != NULL) {
1997 
1998 		/*
1999 		 * Reset /devices node to minor_perm perm/ownership
2000 		 * if we are here to deactivate device allocation
2001 		 */
2002 		if (build_devices == TRUE) {
2003 			reset_node_permissions(node, minor);
2004 		}
2005 
2006 		if (build_dev == FALSE) {
2007 			return;
2008 		}
2009 
2010 		/*
2011 		 * This function will create any nodes for /etc/devlink.tab.
2012 		 * If devlink.tab handles link creation, we don't call any
2013 		 * devfsadm modules since that could cause duplicate caching
2014 		 * in the enumerate functions if different re strings are
2015 		 * passed that are logically identical.  I'm still not
2016 		 * convinced this would cause any harm, but better to be safe.
2017 		 *
2018 		 * Deferred processing is available only for devlinks
2019 		 * created through devfsadm modules.
2020 		 */
2021 		if (process_devlink_compat(minor, node) == TRUE) {
2022 			return;
2023 		}
2024 	} else {
2025 		vprint(CHATTY_MID, "minor_process: deferred processing\n");
2026 	}
2027 
2028 	/*
2029 	 * look for relevant link create rules in the modules, and
2030 	 * invoke the link create callback function to build a link
2031 	 * if there is a match.
2032 	 */
2033 	defer = 0;
2034 	for (create = create_head; create != NULL; create = create->next) {
2035 		if ((minor_matches_rule(node, minor, create) == TRUE) &&
2036 		    class_ok(create->create->device_class) ==
2037 		    DEVFSADM_SUCCESS) {
2038 			if (call_minor_init(create->modptr) ==
2039 			    DEVFSADM_FAILURE) {
2040 				continue;
2041 			}
2042 
2043 			/*
2044 			 * If NOT doing the deferred creates (i.e. 1st pass) and
2045 			 * rule requests deferred processing cache the minor
2046 			 * data.
2047 			 *
2048 			 * If deferred processing (2nd pass), create links
2049 			 * ONLY if rule requests deferred processing.
2050 			 */
2051 			if (dep && ((create->create->flags & CREATE_MASK) ==
2052 			    CREATE_DEFER)) {
2053 				defer = 1;
2054 				continue;
2055 			} else if (dep == NULL &&
2056 			    ((create->create->flags & CREATE_MASK) !=
2057 			    CREATE_DEFER)) {
2058 				continue;
2059 			}
2060 
2061 			if ((*(create->create->callback_fcn))
2062 			    (minor, node) == DEVFSADM_TERMINATE) {
2063 				break;
2064 			}
2065 		}
2066 	}
2067 
2068 	if (defer)
2069 		cache_deferred_minor(dep, node, minor);
2070 }
2071 
2072 
2073 /*
2074  * Cache node and minor in defer list.
2075  */
2076 static void
2077 cache_deferred_minor(
2078 	struct mlist *dep,
2079 	di_node_t node,
2080 	di_minor_t minor)
2081 {
2082 	struct minor	*mp;
2083 	const char	*fcn = "cache_deferred_minor";
2084 
2085 	vprint(CHATTY_MID, "%s node=%s, minor=%s\n", fcn,
2086 	    di_node_name(node), di_minor_name(minor));
2087 
2088 	if (dep == NULL) {
2089 		vprint(CHATTY_MID, "%s: cannot cache during "
2090 		    "deferred processing. Ignoring minor\n", fcn);
2091 		return;
2092 	}
2093 
2094 	mp = (struct minor *)s_zalloc(sizeof (struct minor));
2095 	mp->node = node;
2096 	mp->minor = minor;
2097 	mp->next = NULL;
2098 
2099 	assert(dep->head == NULL || dep->tail != NULL);
2100 	if (dep->head == NULL) {
2101 		dep->head = mp;
2102 	} else {
2103 		dep->tail->next = mp;
2104 	}
2105 	dep->tail = mp;
2106 }
2107 
2108 /*
2109  *  Check to see if "create" link creation rule matches this node/minor.
2110  *  If it does, return TRUE.
2111  */
2112 static int
2113 minor_matches_rule(di_node_t node, di_minor_t minor, create_list_t *create)
2114 {
2115 	char *m_nodetype, *m_drvname;
2116 
2117 	if (create->create->node_type != NULL) {
2118 
2119 		m_nodetype = di_minor_nodetype(minor);
2120 		assert(m_nodetype != NULL);
2121 
2122 		switch (create->create->flags & TYPE_MASK) {
2123 		case TYPE_EXACT:
2124 			if (strcmp(create->create->node_type, m_nodetype) !=
2125 			    0) {
2126 				return (FALSE);
2127 			}
2128 			break;
2129 		case TYPE_PARTIAL:
2130 			if (strncmp(create->create->node_type, m_nodetype,
2131 			    strlen(create->create->node_type)) != 0) {
2132 				return (FALSE);
2133 			}
2134 			break;
2135 		case TYPE_RE:
2136 			if (regexec(&(create->node_type_comp), m_nodetype,
2137 			    0, NULL, 0) != 0) {
2138 				return (FALSE);
2139 			}
2140 			break;
2141 		}
2142 	}
2143 
2144 	if (create->create->drv_name != NULL) {
2145 		m_drvname = di_driver_name(node);
2146 		switch (create->create->flags & DRV_MASK) {
2147 		case DRV_EXACT:
2148 			if (strcmp(create->create->drv_name, m_drvname) != 0) {
2149 				return (FALSE);
2150 			}
2151 			break;
2152 		case DRV_RE:
2153 			if (regexec(&(create->drv_name_comp), m_drvname,
2154 			    0, NULL, 0) != 0) {
2155 				return (FALSE);
2156 			}
2157 			break;
2158 		}
2159 	}
2160 
2161 	return (TRUE);
2162 }
2163 
2164 /*
2165  * If no classes were given on the command line, then return DEVFSADM_SUCCESS.
2166  * Otherwise, return DEVFSADM_SUCCESS if the device "class" from the module
2167  * matches one of the device classes given on the command line,
2168  * otherwise, return DEVFSADM_FAILURE.
2169  */
2170 static int
2171 class_ok(char *class)
2172 {
2173 	int i;
2174 
2175 	if (num_classes == 0) {
2176 		return (DEVFSADM_SUCCESS);
2177 	}
2178 
2179 	for (i = 0; i < num_classes; i++) {
2180 		if (strcmp(class, classes[i]) == 0) {
2181 			return (DEVFSADM_SUCCESS);
2182 		}
2183 	}
2184 	return (DEVFSADM_FAILURE);
2185 }
2186 
2187 /*
2188  * call minor_fini on active modules, then unload ALL modules
2189  */
2190 static void
2191 unload_modules(void)
2192 {
2193 	module_t *module_free;
2194 	create_list_t *create_free;
2195 	remove_list_t *remove_free;
2196 
2197 	while (create_head != NULL) {
2198 		create_free = create_head;
2199 		create_head = create_head->next;
2200 
2201 		if ((create_free->create->flags & TYPE_RE) == TYPE_RE) {
2202 			regfree(&(create_free->node_type_comp));
2203 		}
2204 		if ((create_free->create->flags & DRV_RE) == DRV_RE) {
2205 			regfree(&(create_free->drv_name_comp));
2206 		}
2207 		free(create_free);
2208 	}
2209 
2210 	while (remove_head != NULL) {
2211 		remove_free = remove_head;
2212 		remove_head = remove_head->next;
2213 		free(remove_free);
2214 	}
2215 
2216 	while (module_head != NULL) {
2217 
2218 		if ((module_head->minor_fini != NULL) &&
2219 		    ((module_head->flags & MODULE_ACTIVE) == MODULE_ACTIVE)) {
2220 			(void) (*(module_head->minor_fini))();
2221 		}
2222 
2223 		vprint(MODLOAD_MID, "unloading module %s\n", module_head->name);
2224 		free(module_head->name);
2225 		(void) dlclose(module_head->dlhandle);
2226 
2227 		module_free = module_head;
2228 		module_head = module_head->next;
2229 		free(module_free);
2230 	}
2231 }
2232 
2233 /*
2234  * Load devfsadm logical link processing modules.
2235  */
2236 static void
2237 load_modules(void)
2238 {
2239 	DIR *mod_dir;
2240 	struct dirent *entp;
2241 	char cdir[PATH_MAX + 1];
2242 	char *last;
2243 	char *mdir = module_dirs;
2244 	char *fcn = "load_modules: ";
2245 
2246 	while (*mdir != '\0') {
2247 
2248 		while (*mdir == ':') {
2249 			mdir++;
2250 		}
2251 
2252 		if (*mdir == '\0') {
2253 			continue;
2254 		}
2255 
2256 		last = strchr(mdir, ':');
2257 
2258 		if (last == NULL) {
2259 			last = mdir + strlen(mdir);
2260 		}
2261 
2262 		(void) strncpy(cdir, mdir, last - mdir);
2263 		cdir[last - mdir] = '\0';
2264 		mdir += strlen(cdir);
2265 
2266 		if ((mod_dir = opendir(cdir)) == NULL) {
2267 			vprint(MODLOAD_MID, "%sopendir(%s): %s\n",
2268 				fcn, cdir, strerror(errno));
2269 			continue;
2270 		}
2271 
2272 		while ((entp = readdir(mod_dir)) != NULL) {
2273 
2274 			if ((strcmp(entp->d_name, ".") == 0) ||
2275 			    (strcmp(entp->d_name, "..") == 0)) {
2276 				continue;
2277 			}
2278 
2279 			load_module(entp->d_name, cdir);
2280 		}
2281 		s_closedir(mod_dir);
2282 	}
2283 }
2284 
2285 static void
2286 load_module(char *mname, char *cdir)
2287 {
2288 	_devfsadm_create_reg_t *create_reg;
2289 	_devfsadm_remove_reg_t *remove_reg;
2290 	create_list_t *create_list_element;
2291 	create_list_t **create_list_next;
2292 	remove_list_t *remove_list_element;
2293 	remove_list_t **remove_list_next;
2294 	char epath[PATH_MAX + 1], *end;
2295 	char *fcn = "load_module: ";
2296 	char *dlerrstr;
2297 	void *dlhandle;
2298 	module_t *module;
2299 	int n;
2300 	int i;
2301 
2302 	/* ignore any file which does not end in '.so' */
2303 	if ((end = strstr(mname, MODULE_SUFFIX)) != NULL) {
2304 		if (end[strlen(MODULE_SUFFIX)] != '\0') {
2305 			return;
2306 		}
2307 	} else {
2308 		return;
2309 	}
2310 
2311 	(void) snprintf(epath, sizeof (epath), "%s/%s", cdir, mname);
2312 
2313 	if ((dlhandle = dlopen(epath, RTLD_LAZY)) == NULL) {
2314 		dlerrstr = dlerror();
2315 		err_print(DLOPEN_FAILED, epath,
2316 			dlerrstr ? dlerrstr : "unknown error");
2317 		return;
2318 	}
2319 
2320 	/* dlsym the _devfsadm_create_reg structure */
2321 	if (NULL == (create_reg = (_devfsadm_create_reg_t *)
2322 		    dlsym(dlhandle, _DEVFSADM_CREATE_REG))) {
2323 		vprint(MODLOAD_MID, "dlsym(%s, %s): symbol not found\n", epath,
2324 			_DEVFSADM_CREATE_REG);
2325 	} else {
2326 		vprint(MODLOAD_MID, "%sdlsym(%s, %s) succeeded\n",
2327 			    fcn, epath, _DEVFSADM_CREATE_REG);
2328 	}
2329 
2330 	/* dlsym the _devfsadm_remove_reg structure */
2331 	if (NULL == (remove_reg = (_devfsadm_remove_reg_t *)
2332 	    dlsym(dlhandle, _DEVFSADM_REMOVE_REG))) {
2333 		vprint(MODLOAD_MID, "dlsym(%s,\n\t%s): symbol not found\n",
2334 			epath, _DEVFSADM_REMOVE_REG);
2335 	} else {
2336 		vprint(MODLOAD_MID, "dlsym(%s, %s): succeeded\n",
2337 			    epath, _DEVFSADM_REMOVE_REG);
2338 	}
2339 
2340 	vprint(MODLOAD_MID, "module %s loaded\n", epath);
2341 
2342 	module = (module_t *)s_malloc(sizeof (module_t));
2343 	module->name = s_strdup(epath);
2344 	module->dlhandle = dlhandle;
2345 
2346 	/* dlsym other module functions, to be called later */
2347 	module->minor_fini = (int (*)())dlsym(dlhandle, MINOR_FINI);
2348 	module->minor_init = (int (*)())dlsym(dlhandle, MINOR_INIT);
2349 	module->flags = 0;
2350 
2351 	/*
2352 	 *  put a ptr to each struct devfsadm_create on "create_head"
2353 	 *  list sorted in interpose_lvl.
2354 	 */
2355 	if (create_reg != NULL) {
2356 		for (i = 0; i < create_reg->count; i++) {
2357 			int flags = create_reg->tblp[i].flags;
2358 
2359 			create_list_element = (create_list_t *)
2360 				s_malloc(sizeof (create_list_t));
2361 
2362 			create_list_element->create = &(create_reg->tblp[i]);
2363 			create_list_element->modptr = module;
2364 
2365 			if (((flags & CREATE_MASK) != 0) &&
2366 			    ((flags & CREATE_MASK) != CREATE_DEFER)) {
2367 				free(create_list_element);
2368 				err_print("illegal flag combination in "
2369 						"module create\n");
2370 				err_print(IGNORING_ENTRY, i, epath);
2371 				continue;
2372 			}
2373 
2374 			if (((flags & TYPE_MASK) == 0) ^
2375 			    (create_reg->tblp[i].node_type == NULL)) {
2376 				free(create_list_element);
2377 				err_print("flags value incompatible with "
2378 					"node_type value in module create\n");
2379 				err_print(IGNORING_ENTRY, i, epath);
2380 				continue;
2381 			}
2382 
2383 			if (((flags & TYPE_MASK) != 0) &&
2384 			    ((flags & TYPE_MASK) != TYPE_EXACT) &&
2385 			    ((flags & TYPE_MASK) != TYPE_RE) &&
2386 			    ((flags & TYPE_MASK) != TYPE_PARTIAL)) {
2387 				free(create_list_element);
2388 				err_print("illegal TYPE_* flag combination in "
2389 						"module create\n");
2390 				err_print(IGNORING_ENTRY, i, epath);
2391 				continue;
2392 			}
2393 
2394 			/* precompile regular expression for efficiency */
2395 			if ((flags & TYPE_RE) == TYPE_RE) {
2396 				if ((n = regcomp(&(create_list_element->
2397 				    node_type_comp),
2398 				    create_reg->tblp[i].node_type,
2399 				    REG_EXTENDED)) != 0) {
2400 					free(create_list_element);
2401 					err_print(REGCOMP_FAILED,
2402 						create_reg->tblp[i].node_type,
2403 						n);
2404 					err_print(IGNORING_ENTRY, i, epath);
2405 					continue;
2406 				}
2407 			}
2408 
2409 			if (((flags & DRV_MASK) == 0) ^
2410 			    (create_reg->tblp[i].drv_name == NULL)) {
2411 				if ((flags & TYPE_RE) == TYPE_RE) {
2412 					regfree(&(create_list_element->
2413 					    node_type_comp));
2414 				}
2415 				free(create_list_element);
2416 				err_print("flags value incompatible with "
2417 					"drv_name value in module create\n");
2418 				err_print(IGNORING_ENTRY, i, epath);
2419 				continue;
2420 			}
2421 
2422 			if (((flags & DRV_MASK) != 0) &&
2423 			    ((flags & DRV_MASK) != DRV_EXACT) &&
2424 			    ((flags & DRV_MASK) !=  DRV_RE)) {
2425 				if ((flags & TYPE_RE) == TYPE_RE) {
2426 					regfree(&(create_list_element->
2427 					    node_type_comp));
2428 				}
2429 				free(create_list_element);
2430 				err_print("illegal DRV_* flag combination in "
2431 					"module create\n");
2432 				err_print(IGNORING_ENTRY, i, epath);
2433 				continue;
2434 			}
2435 
2436 			/* precompile regular expression for efficiency */
2437 			if ((create_reg->tblp[i].flags & DRV_RE) == DRV_RE) {
2438 				if ((n = regcomp(&(create_list_element->
2439 				    drv_name_comp),
2440 				    create_reg->tblp[i].drv_name,
2441 				    REG_EXTENDED)) != 0) {
2442 					if ((flags & TYPE_RE) == TYPE_RE) {
2443 						regfree(&(create_list_element->
2444 						    node_type_comp));
2445 					}
2446 					free(create_list_element);
2447 					err_print(REGCOMP_FAILED,
2448 						create_reg->tblp[i].drv_name,
2449 						n);
2450 					err_print(IGNORING_ENTRY, i, epath);
2451 					continue;
2452 				}
2453 			}
2454 
2455 
2456 			/* add to list sorted by interpose level */
2457 			for (create_list_next = &(create_head);
2458 				(*create_list_next != NULL) &&
2459 				(*create_list_next)->create->interpose_lvl >=
2460 				create_list_element->create->interpose_lvl;
2461 				create_list_next =
2462 					&((*create_list_next)->next));
2463 			create_list_element->next = *create_list_next;
2464 			*create_list_next = create_list_element;
2465 		}
2466 	}
2467 
2468 	/*
2469 	 *  put a ptr to each struct devfsadm_remove on "remove_head"
2470 	 *  list sorted by interpose_lvl.
2471 	 */
2472 	if (remove_reg != NULL) {
2473 		for (i = 0; i < remove_reg->count; i++) {
2474 
2475 			remove_list_element = (remove_list_t *)
2476 				s_malloc(sizeof (remove_list_t));
2477 
2478 			remove_list_element->remove = &(remove_reg->tblp[i]);
2479 			remove_list_element->modptr = module;
2480 
2481 			for (remove_list_next = &(remove_head);
2482 				(*remove_list_next != NULL) &&
2483 				(*remove_list_next)->remove->interpose_lvl >=
2484 				remove_list_element->remove->interpose_lvl;
2485 				remove_list_next =
2486 					&((*remove_list_next)->next));
2487 			remove_list_element->next = *remove_list_next;
2488 			*remove_list_next = remove_list_element;
2489 		}
2490 	}
2491 
2492 	module->next = module_head;
2493 	module_head = module;
2494 }
2495 
2496 /*
2497  * Create a thread to call minor_fini after some delay
2498  */
2499 static void
2500 startup_cache_sync_thread()
2501 {
2502 	vprint(INITFINI_MID, "startup_cache_sync_thread\n");
2503 
2504 	(void) mutex_lock(&minor_fini_mutex);
2505 
2506 	minor_fini_delay_restart = TRUE;
2507 
2508 	if (minor_fini_thread_created == FALSE) {
2509 
2510 		if (thr_create(NULL, NULL,
2511 		    (void *(*)(void *))call_minor_fini_thread, NULL,
2512 		    THR_DETACHED, NULL)) {
2513 			err_print(CANT_CREATE_THREAD, "minor_fini",
2514 					strerror(errno));
2515 
2516 			(void) mutex_unlock(&minor_fini_mutex);
2517 
2518 			/*
2519 			 * just sync state here instead of
2520 			 * giving up
2521 			 */
2522 			lock_dev();
2523 			unlock_dev(SYNC_STATE);
2524 
2525 			return;
2526 		}
2527 		minor_fini_thread_created = TRUE;
2528 	} else {
2529 		vprint(INITFINI_MID, "restarting delay\n");
2530 	}
2531 
2532 	(void) mutex_unlock(&minor_fini_mutex);
2533 }
2534 
2535 /*
2536  * after not receiving an event for minor_fini_timeout secs, we need
2537  * to call the minor_fini routines
2538  */
2539 /*ARGSUSED*/
2540 static void
2541 call_minor_fini_thread(void *arg)
2542 {
2543 	int count = 0;
2544 
2545 	(void) mutex_lock(&minor_fini_mutex);
2546 
2547 	vprint(INITFINI_MID, "call_minor_fini_thread starting\n");
2548 
2549 	do {
2550 		minor_fini_delay_restart = FALSE;
2551 
2552 		(void) mutex_unlock(&minor_fini_mutex);
2553 		(void) sleep(minor_fini_timeout);
2554 		(void) mutex_lock(&minor_fini_mutex);
2555 
2556 		/*
2557 		 * if minor_fini_delay_restart is still false then
2558 		 * we can call minor fini routines.
2559 		 * ensure that at least periodically minor_fini gets
2560 		 * called satisfying link generators depending on fini
2561 		 * being eventually called
2562 		 */
2563 		if ((count++ >= FORCE_CALL_MINOR_FINI) ||
2564 		    (minor_fini_delay_restart == FALSE)) {
2565 			vprint(INITFINI_MID,
2566 			    "call_minor_fini starting (%d)\n", count);
2567 			(void) mutex_unlock(&minor_fini_mutex);
2568 
2569 			lock_dev();
2570 			unlock_dev(SYNC_STATE);
2571 
2572 			vprint(INITFINI_MID, "call_minor_fini done\n");
2573 
2574 			/*
2575 			 * hang around before exiting just in case
2576 			 * minor_fini_delay_restart is set again
2577 			 */
2578 			(void) sleep(1);
2579 
2580 			count = 0;
2581 
2582 			(void) mutex_lock(&minor_fini_mutex);
2583 		}
2584 	} while (minor_fini_delay_restart);
2585 
2586 	minor_fini_thread_created = FALSE;
2587 	(void) mutex_unlock(&minor_fini_mutex);
2588 	vprint(INITFINI_MID, "call_minor_fini_thread exiting\n");
2589 }
2590 
2591 /*
2592  * Attempt to initialize module, if a minor_init routine exists.  Set
2593  * the active flag if the routine exists and succeeds.	If it doesn't
2594  * exist, just set the active flag.
2595  */
2596 static int
2597 call_minor_init(module_t *module)
2598 {
2599 	char *fcn = "call_minor_init: ";
2600 
2601 	if ((module->flags & MODULE_ACTIVE) == MODULE_ACTIVE) {
2602 		return (DEVFSADM_SUCCESS);
2603 	}
2604 
2605 	vprint(INITFINI_MID, "%smodule %s.  current state: inactive\n",
2606 		fcn, module->name);
2607 
2608 	if (module->minor_init == NULL) {
2609 		module->flags |= MODULE_ACTIVE;
2610 		vprint(INITFINI_MID, "minor_init not defined\n");
2611 		return (DEVFSADM_SUCCESS);
2612 	}
2613 
2614 	if ((*(module->minor_init))() == DEVFSADM_FAILURE) {
2615 		err_print(FAILED_FOR_MODULE, MINOR_INIT, module->name);
2616 		return (DEVFSADM_FAILURE);
2617 	}
2618 
2619 	vprint(INITFINI_MID, "minor_init() returns DEVFSADM_SUCCESS. "
2620 		"new state: active\n");
2621 
2622 	module->flags |= MODULE_ACTIVE;
2623 	return (DEVFSADM_SUCCESS);
2624 }
2625 
2626 /*ARGSUSED*/
2627 int
2628 devfsadm_mklink_zone(struct zone_devinfo *z, char *link, di_node_t node,
2629     di_minor_t minor, int flags)
2630 {
2631 	char path[PATH_MAX];
2632 	char phy_path[PATH_MAX];
2633 	char *dev_pathp;
2634 	char *acontents, *aminor = NULL;
2635 	mode_t mode;
2636 	uid_t uid;
2637 	gid_t gid;
2638 	dev_t dev;
2639 	struct zone_devtab out_match;
2640 
2641 	if (zonecfg_match_dev(z->zone_dochdl, link, &out_match) != Z_OK) {
2642 		return (DEVFSADM_FAILURE);
2643 	}
2644 
2645 	vprint(ZONE_MID, "zone device match: <device match=\"%s\"> "
2646 	    "matches /dev/%s\n", out_match.zone_dev_match, link);
2647 
2648 	/*
2649 	 * In daemon mode, zone_path will be non-empty.  In non-daemon mode
2650 	 * it will be empty since we've already stuck the zone into dev_dir,
2651 	 * etc.
2652 	 */
2653 	(void) snprintf(path, sizeof (path), "%s/dev/%s", z->zone_path, link);
2654 	dev = di_minor_devt(minor);
2655 
2656 	/*
2657 	 * If this is an alias node (i.e. a clone node), we have to figure
2658 	 * out the minor name.
2659 	 */
2660 	if (di_minor_type(minor) == DDM_ALIAS) {
2661 		/* use /pseudo/clone@0:<driver> as the phys path */
2662 		(void) snprintf(phy_path, sizeof (phy_path),
2663 		    "/pseudo/clone@0:%s",
2664 		    di_driver_name(di_minor_devinfo(minor)));
2665 		aminor = di_minor_name(minor);
2666 		acontents = phy_path;
2667 	} else {
2668 		if ((dev_pathp = di_devfs_path(node)) == NULL) {
2669 			err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
2670 			devfsadm_exit(1);
2671 		}
2672 		(void) snprintf(phy_path, sizeof (phy_path), "%s:%s",
2673 		    dev_pathp, di_minor_name(minor));
2674 		di_devfs_path_free(dev_pathp);
2675 		acontents = phy_path;
2676 	}
2677 
2678 
2679 	getattr(acontents, aminor, di_minor_spectype(minor), dev,
2680 	    &mode, &uid, &gid);
2681 	vprint(ZONE_MID, "zone getattr(%s, %s, %d, %lu, 0%lo, %lu, %lu)\n",
2682 	    acontents, aminor ? aminor : "<NULL>", di_minor_spectype(minor),
2683 	    dev, mode, uid, gid);
2684 
2685 	/*
2686 	 * Create the node; if the enclosing directory doesn't exist,
2687 	 * make it too.
2688 	 */
2689 top:
2690 	if (mknod(path, di_minor_spectype(minor) | mode, dev) == -1) {
2691 		if (errno == ENOENT) {
2692 			/* dirpath to node doesn't exist */
2693 			char *hide = strrchr(path, '/');
2694 			*hide = '\0';
2695 			s_mkdirp(path,
2696 			    S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
2697 			*hide = '/';
2698 			goto top;
2699 		} else if (errno == EEXIST) {
2700 			return (DEVFSADM_SUCCESS);
2701 		}
2702 		err_print(MKNOD_FAILED, path, strerror(errno));
2703 		return (DEVFSADM_FAILURE);
2704 	} else {
2705 		/*
2706 		 * If we successfully made the node, then set its owner
2707 		 * and group.  Existing nodes will be unaffected.
2708 		 */
2709 		(void) chown(path, uid, gid);
2710 	}
2711 
2712 	return (DEVFSADM_SUCCESS);
2713 }
2714 
2715 /*
2716  * Creates a symlink 'link' to the physical path of node:minor.
2717  * Construct link contents, then call create_link_common().
2718  */
2719 /*ARGSUSED*/
2720 int
2721 devfsadm_mklink_default(char *link, di_node_t node, di_minor_t minor, int flags)
2722 {
2723 	char rcontents[PATH_MAX];
2724 	char devlink[PATH_MAX];
2725 	char phy_path[PATH_MAX];
2726 	char *acontents;
2727 	char *dev_path;
2728 	int numslashes;
2729 	int rv;
2730 	int i, link_exists;
2731 	int last_was_slash = FALSE;
2732 
2733 	/*
2734 	 * try to use devices path
2735 	 */
2736 	if ((node == lnode) && (minor == lminor)) {
2737 		acontents = lphy_path;
2738 	} else if (di_minor_type(minor) == DDM_ALIAS) {
2739 		/* use /pseudo/clone@0:<driver> as the phys path */
2740 		(void) snprintf(phy_path, sizeof (phy_path),
2741 		    "/pseudo/clone@0:%s",
2742 		    di_driver_name(di_minor_devinfo(minor)));
2743 		acontents = phy_path;
2744 	} else {
2745 		if ((dev_path = di_devfs_path(node)) == NULL) {
2746 			err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
2747 			devfsadm_exit(1);
2748 		}
2749 		(void) snprintf(phy_path, sizeof (phy_path), "%s:%s",
2750 		    dev_path, di_minor_name(minor));
2751 		di_devfs_path_free(dev_path);
2752 		acontents = phy_path;
2753 	}
2754 
2755 	/* prepend link with dev_dir contents */
2756 	(void) strlcpy(devlink, dev_dir, sizeof (devlink));
2757 	(void) strlcat(devlink, "/", sizeof (devlink));
2758 	(void) strlcat(devlink, link, sizeof (devlink));
2759 
2760 	/*
2761 	 * Calculate # of ../ to add.  Account for double '//' in path.
2762 	 * Ignore all leading slashes.
2763 	 */
2764 	for (i = 0; link[i] == '/'; i++)
2765 		;
2766 	for (numslashes = 0; link[i] != '\0'; i++) {
2767 		if (link[i] == '/') {
2768 			if (last_was_slash == FALSE) {
2769 				numslashes++;
2770 				last_was_slash = TRUE;
2771 			}
2772 		} else {
2773 			last_was_slash = FALSE;
2774 		}
2775 	}
2776 	/* Don't count any trailing '/' */
2777 	if (link[i-1] == '/') {
2778 		numslashes--;
2779 	}
2780 
2781 	rcontents[0] = '\0';
2782 	do {
2783 		(void) strlcat(rcontents, "../", sizeof (rcontents));
2784 	} while (numslashes-- != 0);
2785 
2786 	(void) strlcat(rcontents, "devices", sizeof (rcontents));
2787 	(void) strlcat(rcontents, acontents, sizeof (rcontents));
2788 
2789 	if (devlinks_debug == TRUE) {
2790 		vprint(INFO_MID, "adding link %s ==> %s\n", devlink, rcontents);
2791 	}
2792 
2793 	if ((rv = create_link_common(devlink, rcontents, &link_exists))
2794 	    == DEVFSADM_SUCCESS) {
2795 		linknew = TRUE;
2796 		add_link_to_cache(link, acontents);
2797 	} else {
2798 		linknew = FALSE;
2799 	}
2800 
2801 	if (link_exists == TRUE) {
2802 		/* Link exists or was just created */
2803 		(void) di_devlink_add_link(devlink_cache, link, rcontents,
2804 		    DI_PRIMARY_LINK);
2805 	}
2806 
2807 	return (rv);
2808 }
2809 
2810 int
2811 devfsadm_mklink(char *link, di_node_t node, di_minor_t minor, int flags)
2812 {
2813 	struct zone_devinfo *z;
2814 	int error;
2815 
2816 	/*
2817 	 * If we're in zone mode (also implies !daemon_mode), then the
2818 	 * zone devinfo list has only one element, the zone we're configuring,
2819 	 * and we can just use zone_head.
2820 	 */
2821 	if (zone_cmd_mode)
2822 		return (devfsadm_mklink_zone(zone_head, link, node,
2823 		    minor, flags));
2824 	else if (!daemon_mode)
2825 		return (devfsadm_mklink_default(link, node, minor, flags));
2826 
2827 	/*
2828 	 * We're in daemon mode, so we need to make the link in the global
2829 	 * zone; then, walk the list of zones, creating the corresponding
2830 	 * mknod'd nodes in each.
2831 	 */
2832 	error = devfsadm_mklink_default(link, node, minor, flags);
2833 
2834 	(void) mutex_lock(&zone_mutex);
2835 	for (z = zone_head; z != NULL; z = z->zone_next) {
2836 		(void) devfsadm_mklink_zone(z, link, node, minor, flags);
2837 	}
2838 	(void) mutex_unlock(&zone_mutex);
2839 	return (error);
2840 }
2841 
2842 /*
2843  * Creates a symlink link to primary_link.  Calculates relative
2844  * directory offsets, then calls link_common().
2845  */
2846 /*ARGSUSED*/
2847 int
2848 devfsadm_secondary_link(char *link, char *primary_link, int flags)
2849 {
2850 	char contents[PATH_MAX + 1];
2851 	char devlink[PATH_MAX + 1];
2852 	int rv, link_exists;
2853 	char *fpath;
2854 	char *tpath;
2855 	char *op;
2856 
2857 	/* prepend link with dev_dir contents */
2858 	(void) strcpy(devlink, dev_dir);
2859 	(void) strcat(devlink, "/");
2860 	(void) strcat(devlink, link);
2861 	/*
2862 	 * building extra link, so use first link as link contents, but first
2863 	 * make it relative.
2864 	 */
2865 	fpath = link;
2866 	tpath = primary_link;
2867 	op = contents;
2868 
2869 	while (*fpath == *tpath && *fpath != '\0') {
2870 		fpath++, tpath++;
2871 	}
2872 
2873 	/* Count directories to go up, if any, and add "../" */
2874 	while (*fpath != '\0') {
2875 		if (*fpath == '/') {
2876 			(void) strcpy(op, "../");
2877 			op += 3;
2878 		}
2879 		fpath++;
2880 	}
2881 
2882 	/*
2883 	 * Back up to the start of the current path component, in
2884 	 * case in the middle
2885 	 */
2886 	while (tpath != primary_link && *(tpath-1) != '/') {
2887 		tpath--;
2888 	}
2889 	(void) strcpy(op, tpath);
2890 
2891 	if (devlinks_debug == TRUE) {
2892 		vprint(INFO_MID, "adding extra link %s ==> %s\n",
2893 				devlink, contents);
2894 	}
2895 
2896 	if ((rv = create_link_common(devlink, contents, &link_exists))
2897 	    == DEVFSADM_SUCCESS) {
2898 		/*
2899 		 * we need to save the ultimate /devices contents, and not the
2900 		 * secondary link, since hotcleanup only looks at /devices path.
2901 		 * Since we don't have devices path here, we can try to get it
2902 		 * by readlink'ing the secondary link.  This assumes the primary
2903 		 * link was created first.
2904 		 */
2905 		add_link_to_cache(link, lphy_path);
2906 		linknew = TRUE;
2907 	} else {
2908 		linknew = FALSE;
2909 	}
2910 
2911 	/*
2912 	 * If link exists or was just created, add it to the database
2913 	 */
2914 	if (link_exists == TRUE) {
2915 		(void) di_devlink_add_link(devlink_cache, link, contents,
2916 		    DI_SECONDARY_LINK);
2917 	}
2918 
2919 	return (rv);
2920 }
2921 
2922 /* returns pointer to the devices directory */
2923 char *
2924 devfsadm_get_devices_dir()
2925 {
2926 	return (devices_dir);
2927 }
2928 
2929 /*
2930  * Does the actual link creation.  VERBOSE_MID only used if there is
2931  * a change.  CHATTY_MID used otherwise.
2932  */
2933 static int
2934 create_link_common(char *devlink, char *contents, int *exists)
2935 {
2936 	int try;
2937 	int linksize;
2938 	int max_tries = 0;
2939 	static int prev_link_existed = TRUE;
2940 	char checkcontents[PATH_MAX + 1];
2941 	char *hide;
2942 
2943 	*exists = FALSE;
2944 
2945 	/* Database is not updated when file_mods == FALSE */
2946 	if (file_mods == FALSE) {
2947 		linksize = readlink(devlink, checkcontents, PATH_MAX);
2948 		if (linksize > 0) {
2949 			checkcontents[linksize] = '\0';
2950 			if (strcmp(checkcontents, contents) != 0) {
2951 				vprint(CHATTY_MID, REMOVING_LINK,
2952 						devlink, checkcontents);
2953 				return (DEVFSADM_SUCCESS);
2954 			} else {
2955 				vprint(CHATTY_MID, "link exists and is correct:"
2956 					" %s -> %s\n", devlink, contents);
2957 				/* failure only in that the link existed */
2958 				return (DEVFSADM_FAILURE);
2959 			}
2960 		} else {
2961 			vprint(VERBOSE_MID, CREATING_LINK, devlink, contents);
2962 			return (DEVFSADM_SUCCESS);
2963 		}
2964 	}
2965 
2966 	/*
2967 	 * systems calls are expensive, so predict whether to readlink
2968 	 * or symlink first, based on previous attempt
2969 	 */
2970 	if (prev_link_existed == FALSE) {
2971 		try = CREATE_LINK;
2972 	} else {
2973 		try = READ_LINK;
2974 	}
2975 
2976 	while (++max_tries <= 3) {
2977 
2978 		switch (try) {
2979 		case  CREATE_LINK:
2980 
2981 			if (symlink(contents, devlink) == 0) {
2982 				vprint(VERBOSE_MID, CREATING_LINK, devlink,
2983 						contents);
2984 				prev_link_existed = FALSE;
2985 				/* link successfully created */
2986 				*exists = TRUE;
2987 				set_logindev_perms(devlink);
2988 				return (DEVFSADM_SUCCESS);
2989 			} else {
2990 				switch (errno) {
2991 
2992 				case ENOENT:
2993 					/* dirpath to node doesn't exist */
2994 					hide = strrchr(devlink, '/');
2995 					*hide = '\0';
2996 					s_mkdirp(devlink, S_IRWXU|S_IRGRP|
2997 						S_IXGRP|S_IROTH|S_IXOTH);
2998 					*hide = '/';
2999 					break;
3000 				case EEXIST:
3001 					try = READ_LINK;
3002 					break;
3003 				default:
3004 					err_print(SYMLINK_FAILED, devlink,
3005 						contents, strerror(errno));
3006 					return (DEVFSADM_FAILURE);
3007 				}
3008 			}
3009 			break;
3010 
3011 		case READ_LINK:
3012 
3013 			linksize = readlink(devlink, checkcontents, PATH_MAX);
3014 			if (linksize >= 0) {
3015 				checkcontents[linksize] = '\0';
3016 				if (strcmp(checkcontents, contents) != 0) {
3017 					s_unlink(devlink);
3018 					vprint(VERBOSE_MID, REMOVING_LINK,
3019 						devlink, checkcontents);
3020 					try = CREATE_LINK;
3021 				} else {
3022 					prev_link_existed = TRUE;
3023 					vprint(CHATTY_MID,
3024 						"link exists and is correct:"
3025 						" %s -> %s\n", devlink,
3026 						contents);
3027 					*exists = TRUE;
3028 					/* failure in that the link existed */
3029 					return (DEVFSADM_FAILURE);
3030 				}
3031 			} else {
3032 				switch (errno) {
3033 				case EINVAL:
3034 					/* not a symlink, remove and create */
3035 					s_unlink(devlink);
3036 				default:
3037 					/* maybe it didn't exist at all */
3038 					try = CREATE_LINK;
3039 					break;
3040 				}
3041 			}
3042 			break;
3043 		}
3044 	}
3045 	err_print(MAX_ATTEMPTS, devlink, contents);
3046 	return (DEVFSADM_FAILURE);
3047 }
3048 
3049 static void
3050 set_logindev_perms(char *devlink)
3051 {
3052 	struct login_dev *newdev;
3053 	struct passwd pwd, *resp;
3054 	char pwd_buf[PATH_MAX];
3055 	int rv;
3056 	struct stat sb;
3057 	char *devfs_path = NULL;
3058 
3059 	/*
3060 	 * We only want logindev perms to be set when a device is
3061 	 * hotplugged or an application requests synchronous creates.
3062 	 * So we enable this only in daemon mode. In addition,
3063 	 * login(1) only fixes the std. /dev dir. So we don't
3064 	 * change perms if alternate root is set.
3065 	 * login_dev_enable is TRUE only in these cases.
3066 	 */
3067 	if (login_dev_enable != TRUE)
3068 		return;
3069 
3070 	/*
3071 	 * Normally, /etc/logindevperm has few (8 - 10 entries) which
3072 	 * may be regular expressions (globs were converted to RE).
3073 	 * So just do a linear search through the list.
3074 	 */
3075 	for (newdev = login_dev_cache; newdev; newdev = newdev->ldev_next) {
3076 		vprint(FILES_MID, "matching %s with %s\n", devlink,
3077 		    newdev->ldev_device);
3078 
3079 		if (regexec(&newdev->ldev_device_regex, devlink, 0,
3080 		    NULL, 0) == 0)  {
3081 			vprint(FILES_MID, "matched %s with %s\n", devlink,
3082 			    newdev->ldev_device);
3083 			break;
3084 		}
3085 	}
3086 
3087 	if (newdev == NULL)
3088 		return;
3089 
3090 	/*
3091 	 * we have a match, now find the driver associated with this
3092 	 * minor node using a snapshot on the physical path
3093 	 */
3094 	(void) resolve_link(devlink, NULL, NULL, &devfs_path, 0);
3095 	if (devfs_path) {
3096 		di_node_t node;
3097 		char *drv = NULL;
3098 		struct driver_list *list;
3099 		char *p;
3100 
3101 		/* truncate on : so we can take a snapshot */
3102 		(void) strcpy(pwd_buf, devfs_path);
3103 		p = strrchr(pwd_buf, ':');
3104 		if (p == NULL) {
3105 			free(devfs_path);
3106 			return;
3107 		}
3108 		*p = '\0';
3109 
3110 		vprint(FILES_MID, "link=%s->physpath=%s\n",
3111 		    devlink, pwd_buf);
3112 
3113 		node = di_init(pwd_buf, DINFOMINOR);
3114 
3115 		if (node) {
3116 			drv = di_driver_name(node);
3117 
3118 			if (drv) {
3119 				vprint(FILES_MID, "%s: driver is %s\n",
3120 				    devlink, drv);
3121 			}
3122 			di_fini(node);
3123 		}
3124 		/* search thru the driver list specified in logindevperm */
3125 		list = newdev->ldev_driver_list;
3126 		if ((drv != NULL) && (list != NULL)) {
3127 			while (list) {
3128 				if (strcmp(list->driver_name,
3129 				    drv) == 0) {
3130 					vprint(FILES_MID,
3131 					    "driver %s match!\n", drv);
3132 					break;
3133 				}
3134 				list = list->next;
3135 			}
3136 			if (list == NULL) {
3137 				vprint(FILES_MID, "no driver match!\n");
3138 				free(devfs_path);
3139 				return;
3140 			}
3141 		}
3142 		free(devfs_path);
3143 	} else {
3144 		return;
3145 	}
3146 
3147 	vprint(FILES_MID, "changing permissions of %s\n", devlink);
3148 
3149 	/*
3150 	 * We have a match. We now attempt to determine the
3151 	 * owner and group of the console user.
3152 	 *
3153 	 * stat() the console device newdev->ldev_console
3154 	 * which will always exist - it will have the right owner but
3155 	 * not the right group. Use getpwuid_r() to determine group for this
3156 	 * uid.
3157 	 * Note, it is safe to use name service here since if name services
3158 	 * are not available (during boot or in single-user mode), then
3159 	 * console owner will be root and its gid can be found in
3160 	 * local files.
3161 	 */
3162 	if (stat(newdev->ldev_console, &sb) == -1) {
3163 		vprint(VERBOSE_MID, STAT_FAILED, newdev->ldev_console,
3164 		    strerror(errno));
3165 		return;
3166 	}
3167 
3168 	resp = NULL;
3169 	rv = getpwuid_r(sb.st_uid, &pwd, pwd_buf, sizeof (pwd_buf), &resp);
3170 	if (rv || resp == NULL) {
3171 		rv = rv ? rv : EINVAL;
3172 		vprint(VERBOSE_MID, GID_FAILED, sb.st_uid,
3173 		    strerror(rv));
3174 		return;
3175 	}
3176 
3177 	assert(&pwd == resp);
3178 
3179 	sb.st_gid = resp->pw_gid;
3180 
3181 	if (chmod(devlink, newdev->ldev_perms) == -1) {
3182 		vprint(VERBOSE_MID, CHMOD_FAILED, devlink,
3183 		    strerror(errno));
3184 		return;
3185 	}
3186 
3187 	if (chown(devlink, sb.st_uid, sb.st_gid)  == -1) {
3188 		vprint(VERBOSE_MID, CHOWN_FAILED, devlink,
3189 		    strerror(errno));
3190 	}
3191 }
3192 
3193 /*
3194  * Reset /devices node with appropriate permissions and
3195  * ownership as specified in /etc/minor_perm.
3196  */
3197 static void
3198 reset_node_permissions(di_node_t node, di_minor_t minor)
3199 {
3200 	int spectype;
3201 	char phy_path[PATH_MAX + 1];
3202 	mode_t mode;
3203 	dev_t dev;
3204 	uid_t uid;
3205 	gid_t gid;
3206 	struct stat sb;
3207 	char *dev_path, *aminor = NULL;
3208 
3209 	/* lphy_path starts with / */
3210 	if ((dev_path = di_devfs_path(node)) == NULL) {
3211 		err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
3212 		devfsadm_exit(1);
3213 	}
3214 	(void) strcpy(lphy_path, dev_path);
3215 	di_devfs_path_free(dev_path);
3216 
3217 	(void) strcat(lphy_path, ":");
3218 	if (di_minor_type(minor) == DDM_ALIAS) {
3219 		char *driver;
3220 		aminor = di_minor_name(minor);
3221 		driver = di_driver_name(di_minor_devinfo(minor));
3222 		(void) strcat(lphy_path, driver);
3223 	} else
3224 		(void) strcat(lphy_path, di_minor_name(minor));
3225 
3226 	(void) strcpy(phy_path, devices_dir);
3227 	(void) strcat(phy_path, lphy_path);
3228 
3229 	lnode = node;
3230 	lminor = minor;
3231 
3232 	vprint(CHATTY_MID, "reset_node_permissions: phy_path=%s lphy_path=%s\n",
3233 			phy_path, lphy_path);
3234 
3235 	dev = di_minor_devt(minor);
3236 	spectype = di_minor_spectype(minor); /* block or char */
3237 
3238 	getattr(phy_path, aminor, spectype, dev, &mode, &uid, &gid);
3239 
3240 	/*
3241 	 * compare and set permissions and ownership
3242 	 *
3243 	 * Under devfs, a quick insertion and removal of USB devices
3244 	 * would cause stat of physical path to fail. In this case,
3245 	 * we emit a verbose message, but don't print errors.
3246 	 */
3247 	if ((stat(phy_path, &sb) == -1) || (sb.st_rdev != dev)) {
3248 		vprint(VERBOSE_MID, NO_DEVFS_NODE, phy_path);
3249 		return;
3250 	}
3251 
3252 	/*
3253 	 * If we are here for deactivating device allocation, set
3254 	 * default permissions. Otherwise, set default permissions
3255 	 * only if this is a new device because we want to preserve
3256 	 * modified user permissions.
3257 	 * Devfs indicates a new device by faking an access time
3258 	 * of zero.
3259 	 */
3260 	if (sb.st_atime != 0) {
3261 		int  i;
3262 		char *nt;
3263 
3264 		if (devalloc_off == FALSE)
3265 			return;
3266 
3267 		nt = di_minor_nodetype(minor);
3268 		if (nt == NULL)
3269 			return;
3270 		for (i = 0; devalloc[i]; i++) {
3271 			if (strcmp(nt, devalloc[i]) == 0)
3272 				break;
3273 		}
3274 
3275 		if (devalloc[i] == NULL)
3276 			return;
3277 
3278 		/* One of the types recognized by devalloc, reset perms */
3279 	}
3280 
3281 	if (file_mods == FALSE) {
3282 		/* Nothing more to do if simulating */
3283 		vprint(VERBOSE_MID, PERM_MSG, phy_path, uid, gid, mode);
3284 		return;
3285 	}
3286 
3287 	if (sb.st_mode != mode) {
3288 		if (chmod(phy_path, mode) == -1)
3289 			vprint(VERBOSE_MID, CHMOD_FAILED,
3290 			    phy_path, strerror(errno));
3291 	}
3292 	if (sb.st_uid != uid || sb.st_gid != gid) {
3293 		if (chown(phy_path, uid, gid) == -1)
3294 			vprint(VERBOSE_MID, CHOWN_FAILED,
3295 			    phy_path, strerror(errno));
3296 	}
3297 
3298 	/* Report that we actually did something */
3299 	vprint(VERBOSE_MID, PERM_MSG, phy_path, uid, gid, mode);
3300 }
3301 
3302 /*
3303  * Removes logical link and the minor node it refers to.  If file is a
3304  * link, we recurse and try to remove the minor node (or link if path is
3305  * a double link) that file's link contents refer to.
3306  */
3307 static void
3308 devfsadm_rm_work(char *file, int recurse, int file_type)
3309 {
3310 	char *fcn = "devfsadm_rm_work: ";
3311 	int linksize;
3312 	char contents[PATH_MAX + 1];
3313 	char nextfile[PATH_MAX + 1];
3314 	char newfile[PATH_MAX + 1];
3315 	char *ptr;
3316 
3317 	vprint(REMOVE_MID, "%s%s\n", fcn, file);
3318 
3319 	/* TYPE_LINK split into multiple if's due to excessive indentations */
3320 	if (file_type == TYPE_LINK) {
3321 		(void) strcpy(newfile, dev_dir);
3322 		(void) strcat(newfile, "/");
3323 		(void) strcat(newfile, file);
3324 	}
3325 
3326 	if ((file_type == TYPE_LINK) && (recurse == TRUE) &&
3327 	    ((linksize = readlink(newfile, contents, PATH_MAX)) > 0)) {
3328 		contents[linksize] = '\0';
3329 
3330 		if (is_minor_node(contents, &ptr) == DEVFSADM_TRUE) {
3331 			devfsadm_rm_work(++ptr, FALSE, TYPE_DEVICES);
3332 		} else {
3333 			if (strncmp(contents, DEV "/", strlen(DEV) + 1) == 0) {
3334 				devfsadm_rm_work(&contents[strlen(DEV) + 1],
3335 							TRUE, TYPE_LINK);
3336 			} else {
3337 				if ((ptr = strrchr(file, '/')) != NULL) {
3338 					*ptr = '\0';
3339 					(void) strcpy(nextfile, file);
3340 					*ptr = '/';
3341 					(void) strcat(nextfile, "/");
3342 				} else {
3343 					(void) strcpy(nextfile, "");
3344 				}
3345 				(void) strcat(nextfile, contents);
3346 				devfsadm_rm_work(nextfile, TRUE, TYPE_LINK);
3347 			}
3348 		}
3349 	}
3350 
3351 	if (file_type == TYPE_LINK) {
3352 		vprint(VERBOSE_MID, DEVFSADM_UNLINK, newfile);
3353 		if (file_mods == TRUE) {
3354 			rm_link_from_cache(file);
3355 			s_unlink(newfile);
3356 			rm_parent_dir_if_empty(newfile);
3357 			invalidate_enumerate_cache();
3358 			(void) di_devlink_rm_link(devlink_cache, file);
3359 		}
3360 	}
3361 
3362 	/*
3363 	 * Note: we don't remove /devices entries because they are
3364 	 *	covered by devfs.
3365 	 */
3366 }
3367 
3368 void
3369 devfsadm_rm_link(char *file)
3370 {
3371 	devfsadm_rm_work(file, FALSE, TYPE_LINK);
3372 }
3373 
3374 void
3375 devfsadm_rm_all(char *file)
3376 {
3377 	devfsadm_rm_work(file, TRUE, TYPE_LINK);
3378 }
3379 
3380 static int
3381 s_rmdir(char *path)
3382 {
3383 	int	i;
3384 	char	*rpath, *dir;
3385 	const char *fcn = "s_rmdir";
3386 
3387 	/*
3388 	 * Certain directories are created at install time by packages.
3389 	 * Some of them (listed in packaged_dirs[]) are required by apps
3390 	 * and need to be present even when empty.
3391 	 */
3392 	vprint(REMOVE_MID, "%s: checking if %s is packaged\n", fcn, path);
3393 
3394 	rpath = path + strlen(dev_dir) + 1;
3395 
3396 	for (i = 0; (dir = packaged_dirs[i]) != NULL; i++) {
3397 		if (*rpath == *dir) {
3398 			if (strcmp(rpath, dir) == 0) {
3399 				vprint(REMOVE_MID, "%s: skipping packaged dir: "
3400 				    "%s\n", fcn, path);
3401 				errno = EEXIST;
3402 				return (-1);
3403 			}
3404 		}
3405 	}
3406 
3407 	return (rmdir(path));
3408 }
3409 
3410 /*
3411  * Try to remove any empty directories up the tree.  It is assumed that
3412  * pathname is a file that was removed, so start with its parent, and
3413  * work up the tree.
3414  */
3415 static void
3416 rm_parent_dir_if_empty(char *pathname)
3417 {
3418 	char *ptr, path[PATH_MAX + 1];
3419 	char *fcn = "rm_parent_dir_if_empty: ";
3420 
3421 	vprint(REMOVE_MID, "%schecking %s if empty\n", fcn, pathname);
3422 
3423 	(void) strcpy(path, pathname);
3424 
3425 	/*
3426 	 * ascend up the dir tree, deleting all empty dirs.
3427 	 * Return immediately if a dir is not empty.
3428 	 */
3429 	for (;;) {
3430 
3431 		if ((ptr = strrchr(path, '/')) == NULL) {
3432 			return;
3433 		}
3434 
3435 		*ptr = '\0';
3436 
3437 		if (s_rmdir(path) == 0) {
3438 			vprint(REMOVE_MID, "%sremoving empty dir %s\n",
3439 			    fcn, path);
3440 			continue;
3441 		}
3442 		if (errno == EEXIST) {
3443 			vprint(REMOVE_MID, "%sdir not empty: %s\n", fcn, path);
3444 			return;
3445 		}
3446 		vprint(REMOVE_MID, "%s can't remove %s: %s\n", fcn, path,
3447 		    strerror(errno));
3448 		return;
3449 	}
3450 }
3451 
3452 /*
3453  * This function and all the functions it calls below were added to
3454  * handle the unique problem with world wide names (WWN).  The problem is
3455  * that if a WWN device is moved to another address on the same controller
3456  * its logical link will change, while the physical node remains the same.
3457  * The result is that two logical links will point to the same physical path
3458  * in /devices, the valid link and a stale link. This function will
3459  * find all the stale nodes, though at a significant performance cost.
3460  *
3461  * Caching is used to increase performance.
3462  * A cache will be built from disk if the cache tag doesn't already exist.
3463  * The cache tag is a regular expression "dir_re", which selects a
3464  * subset of disks to search from typically something like
3465  * "dev/cXt[0-9]+d[0-9]+s[0-9]+".  After the cache is built, consistency must
3466  * be maintained, so entries are added as new links are created, and removed
3467  * as old links are deleted.  The whole cache is flushed if we are a daemon,
3468  * and another devfsadm process ran in between.
3469  *
3470  * Once the cache is built, this function finds the cache which matches
3471  * dir_re, and then it searches all links in that cache looking for
3472  * any link whose contents match "valid_link_contents" with a corresponding link
3473  * which does not match "valid_link".  Any such matches are stale and removed.
3474  */
3475 void
3476 devfsadm_rm_stale_links(char *dir_re, char *valid_link, di_node_t node,
3477 			di_minor_t minor)
3478 {
3479 	link_t *link;
3480 	linkhead_t *head;
3481 	char phy_path[PATH_MAX + 1];
3482 	char *valid_link_contents;
3483 	char *dev_path;
3484 	char rmlink[PATH_MAX + 1];
3485 
3486 	/*
3487 	 * try to use devices path
3488 	 */
3489 	if ((node == lnode) && (minor == lminor)) {
3490 		valid_link_contents = lphy_path;
3491 	} else {
3492 		if ((dev_path = di_devfs_path(node)) == NULL) {
3493 			err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
3494 			devfsadm_exit(1);
3495 		}
3496 		(void) strcpy(phy_path, dev_path);
3497 		di_devfs_path_free(dev_path);
3498 
3499 		(void) strcat(phy_path, ":");
3500 		(void) strcat(phy_path, di_minor_name(minor));
3501 		valid_link_contents = phy_path;
3502 	}
3503 
3504 	/*
3505 	 * As an optimization, check to make sure the corresponding
3506 	 * devlink was just created before continuing.
3507 	 */
3508 
3509 	if (linknew == FALSE) {
3510 		return;
3511 	}
3512 
3513 	head = get_cached_links(dir_re);
3514 
3515 	assert(head->nextlink == NULL);
3516 
3517 	for (link = head->link; link != NULL; link = head->nextlink) {
3518 		/*
3519 		 * See hot_cleanup() for why we do this
3520 		 */
3521 		head->nextlink = link->next;
3522 		if ((strcmp(link->contents, valid_link_contents) == 0) &&
3523 		    (strcmp(link->devlink, valid_link) != 0)) {
3524 			vprint(CHATTY_MID, "removing %s -> %s\n"
3525 				"valid link is: %s -> %s\n",
3526 				link->devlink, link->contents,
3527 				valid_link, valid_link_contents);
3528 			/*
3529 			 * Use a copy of the cached link name as the
3530 			 * cache entry will go away during link removal
3531 			 */
3532 			(void) snprintf(rmlink, sizeof (rmlink), "%s",
3533 			    link->devlink);
3534 			devfsadm_rm_link(rmlink);
3535 		}
3536 	}
3537 }
3538 
3539 /*
3540  * Return previously created cache, or create cache.
3541  */
3542 static linkhead_t *
3543 get_cached_links(char *dir_re)
3544 {
3545 	recurse_dev_t rd;
3546 	linkhead_t *linkhead;
3547 	int n;
3548 
3549 	vprint(BUILDCACHE_MID, "get_cached_links: %s\n", dir_re);
3550 
3551 	for (linkhead = headlinkhead; linkhead != NULL;
3552 		linkhead = linkhead->nexthead) {
3553 		if (strcmp(linkhead->dir_re, dir_re) == 0) {
3554 			return (linkhead);
3555 		}
3556 	}
3557 
3558 	/*
3559 	 * This tag is not in cache, so add it, along with all its
3560 	 * matching /dev entries.  This is the only time we go to disk.
3561 	 */
3562 	linkhead = s_malloc(sizeof (linkhead_t));
3563 	linkhead->nexthead = headlinkhead;
3564 	headlinkhead = linkhead;
3565 	linkhead->dir_re = s_strdup(dir_re);
3566 
3567 	if ((n = regcomp(&(linkhead->dir_re_compiled), dir_re,
3568 				REG_EXTENDED)) != 0) {
3569 		err_print(REGCOMP_FAILED,  dir_re, n);
3570 	}
3571 
3572 	linkhead->nextlink = NULL;
3573 	linkhead->link = NULL;
3574 
3575 	rd.fcn = build_devlink_list;
3576 	rd.data = (void *)linkhead;
3577 
3578 	vprint(BUILDCACHE_MID, "get_cached_links: calling recurse_dev_re\n");
3579 
3580 	/* call build_devlink_list for each directory in the dir_re RE */
3581 	if (dir_re[0] == '/') {
3582 		recurse_dev_re("/", &dir_re[1], &rd);
3583 	} else {
3584 		recurse_dev_re(dev_dir, dir_re, &rd);
3585 	}
3586 
3587 	return (linkhead);
3588 }
3589 
3590 static void
3591 build_devlink_list(char *devlink, void *data)
3592 {
3593 	char *fcn = "build_devlink_list: ";
3594 	char *ptr;
3595 	char *r_contents;
3596 	char *r_devlink;
3597 	char contents[PATH_MAX + 1];
3598 	char newlink[PATH_MAX + 1];
3599 	char stage_link[PATH_MAX + 1];
3600 	int linksize;
3601 	linkhead_t *linkhead = (linkhead_t *)data;
3602 	link_t *link;
3603 	int i = 0;
3604 
3605 	vprint(BUILDCACHE_MID, "%scheck_link: %s\n", fcn, devlink);
3606 
3607 	(void) strcpy(newlink, devlink);
3608 
3609 	do {
3610 		linksize = readlink(newlink, contents, PATH_MAX);
3611 		if (linksize <= 0) {
3612 			/*
3613 			 * The first pass through the do loop we may readlink()
3614 			 * non-symlink files(EINVAL) from false regexec matches.
3615 			 * Suppress error messages in those cases or if the link
3616 			 * content is the empty string.
3617 			 */
3618 			if (linksize < 0 && (i || errno != EINVAL))
3619 				err_print(READLINK_FAILED, "build_devlink_list",
3620 				    newlink, strerror(errno));
3621 			return;
3622 		}
3623 		contents[linksize] = '\0';
3624 		i = 1;
3625 
3626 		if (is_minor_node(contents, &r_contents) == DEVFSADM_FALSE) {
3627 			/*
3628 			 * assume that link contents is really a pointer to
3629 			 * another link, so recurse and read its link contents.
3630 			 *
3631 			 * some link contents are absolute:
3632 			 *	/dev/audio -> /dev/sound/0
3633 			 */
3634 			if (strncmp(contents, DEV "/",
3635 				strlen(DEV) + strlen("/")) != 0) {
3636 
3637 				if ((ptr = strrchr(newlink, '/')) == NULL) {
3638 					vprint(REMOVE_MID, "%s%s -> %s invalid "
3639 						"link. missing '/'\n", fcn,
3640 						newlink, contents);
3641 						return;
3642 				}
3643 				*ptr = '\0';
3644 				(void) strcpy(stage_link, newlink);
3645 				*ptr = '/';
3646 				(void) strcat(stage_link, "/");
3647 				(void) strcat(stage_link, contents);
3648 				(void) strcpy(newlink, stage_link);
3649 			} else {
3650 				(void) strcpy(newlink, dev_dir);
3651 				(void) strcat(newlink, "/");
3652 				(void) strcat(newlink,
3653 					&contents[strlen(DEV) + strlen("/")]);
3654 			}
3655 
3656 		} else {
3657 			newlink[0] = '\0';
3658 		}
3659 	} while (newlink[0] != '\0');
3660 
3661 	if (strncmp(devlink, dev_dir, strlen(dev_dir)) != 0) {
3662 		vprint(BUILDCACHE_MID, "%sinvalid link: %s\n", fcn, devlink);
3663 		return;
3664 	}
3665 
3666 	r_devlink = devlink + strlen(dev_dir);
3667 
3668 	if (r_devlink[0] != '/')
3669 		return;
3670 
3671 	link = s_malloc(sizeof (link_t));
3672 
3673 	/* don't store the '/' after rootdir/dev */
3674 	r_devlink += 1;
3675 
3676 	vprint(BUILDCACHE_MID, "%scaching link: %s\n", fcn, r_devlink);
3677 	link->devlink = s_strdup(r_devlink);
3678 
3679 	link->contents = s_strdup(r_contents);
3680 
3681 	link->next = linkhead->link;
3682 	linkhead->link = link;
3683 }
3684 
3685 /*
3686  * to be consistent, devlink must not begin with / and must be
3687  * relative to /dev/, whereas physpath must contain / and be
3688  * relative to /devices.
3689  */
3690 static void
3691 add_link_to_cache(char *devlink, char *physpath)
3692 {
3693 	linkhead_t *linkhead;
3694 	link_t *link;
3695 	int added = 0;
3696 
3697 	if (file_mods == FALSE) {
3698 		return;
3699 	}
3700 
3701 	vprint(CACHE_MID, "add_link_to_cache: %s -> %s ",
3702 				devlink, physpath);
3703 
3704 	for (linkhead = headlinkhead; linkhead != NULL;
3705 		linkhead = linkhead->nexthead) {
3706 		if (regexec(&(linkhead->dir_re_compiled), devlink, 0, NULL,
3707 			0) == 0) {
3708 			added++;
3709 			link = s_malloc(sizeof (link_t));
3710 			link->devlink = s_strdup(devlink);
3711 			link->contents = s_strdup(physpath);
3712 			link->next = linkhead->link;
3713 			linkhead->link = link;
3714 		}
3715 	}
3716 
3717 	vprint(CACHE_MID,
3718 		" %d %s\n", added, added == 0 ? "NOT ADDED" : "ADDED");
3719 }
3720 
3721 /*
3722  * Remove devlink from cache.  Devlink must be relative to /dev/ and not start
3723  * with /.
3724  */
3725 static void
3726 rm_link_from_cache(char *devlink)
3727 {
3728 	linkhead_t *linkhead;
3729 	link_t **linkp;
3730 	link_t *save;
3731 
3732 	vprint(CACHE_MID, "rm_link_from_cache enter: %s\n", devlink);
3733 
3734 	for (linkhead = headlinkhead; linkhead != NULL;
3735 	    linkhead = linkhead->nexthead) {
3736 		if (regexec(&(linkhead->dir_re_compiled), devlink, 0, NULL,
3737 			0) == 0) {
3738 
3739 			for (linkp = &(linkhead->link); *linkp != NULL; ) {
3740 				if ((strcmp((*linkp)->devlink, devlink) == 0)) {
3741 					save = *linkp;
3742 					*linkp = (*linkp)->next;
3743 					/*
3744 					 * We are removing our caller's
3745 					 * "next" link. Update the nextlink
3746 					 * field in the head so that our
3747 					 * callers accesses the next valid
3748 					 * link
3749 					 */
3750 					if (linkhead->nextlink == save)
3751 						linkhead->nextlink = *linkp;
3752 					free(save->devlink);
3753 					free(save->contents);
3754 					free(save);
3755 					vprint(CACHE_MID, " %s FREED FROM "
3756 						"CACHE\n", devlink);
3757 				} else {
3758 					linkp = &((*linkp)->next);
3759 				}
3760 			}
3761 		}
3762 	}
3763 }
3764 
3765 static void
3766 rm_all_links_from_cache()
3767 {
3768 	linkhead_t *linkhead;
3769 	linkhead_t *nextlinkhead;
3770 	link_t *link;
3771 	link_t *nextlink;
3772 
3773 	vprint(CACHE_MID, "rm_all_links_from_cache\n");
3774 
3775 	for (linkhead = headlinkhead; linkhead != NULL;
3776 		linkhead = nextlinkhead) {
3777 
3778 		nextlinkhead = linkhead->nexthead;
3779 		assert(linkhead->nextlink == NULL);
3780 		for (link = linkhead->link; link != NULL; link = nextlink) {
3781 			nextlink = link->next;
3782 			free(link->devlink);
3783 			free(link->contents);
3784 			free(link);
3785 		}
3786 		regfree(&(linkhead->dir_re_compiled));
3787 		free(linkhead->dir_re);
3788 		free(linkhead);
3789 	}
3790 	headlinkhead = NULL;
3791 }
3792 
3793 /*
3794  * Called when the kernel has modified the incore path_to_inst data.  This
3795  * function will schedule a flush of the data to the filesystem.
3796  */
3797 static void
3798 devfs_instance_mod(void)
3799 {
3800 	char *fcn = "devfs_instance_mod: ";
3801 	vprint(PATH2INST_MID, "%senter\n", fcn);
3802 
3803 	/* signal instance thread */
3804 	(void) mutex_lock(&count_lock);
3805 	inst_count++;
3806 	(void) cond_signal(&cv);
3807 	(void) mutex_unlock(&count_lock);
3808 }
3809 
3810 static void
3811 instance_flush_thread(void)
3812 {
3813 	int i;
3814 	int idle;
3815 
3816 	for (;;) {
3817 
3818 		(void) mutex_lock(&count_lock);
3819 		while (inst_count == 0) {
3820 			(void) cond_wait(&cv, &count_lock);
3821 		}
3822 		inst_count = 0;
3823 
3824 		vprint(PATH2INST_MID, "signaled to flush path_to_inst."
3825 			" Enter delay loop\n");
3826 		/*
3827 		 * Wait MAX_IDLE_DELAY seconds after getting the last flush
3828 		 * path_to_inst event before invoking a flush, but never wait
3829 		 * more than MAX_DELAY seconds after getting the first event.
3830 		 */
3831 		for (idle = 0, i = 0; i < MAX_DELAY; i++) {
3832 
3833 			(void) mutex_unlock(&count_lock);
3834 			(void) sleep(1);
3835 			(void) mutex_lock(&count_lock);
3836 
3837 			/* shorten the delay if we are idle */
3838 			if (inst_count == 0) {
3839 				idle++;
3840 				if (idle > MAX_IDLE_DELAY) {
3841 					break;
3842 				}
3843 			} else {
3844 				inst_count = idle = 0;
3845 			}
3846 		}
3847 
3848 		(void) mutex_unlock(&count_lock);
3849 
3850 		flush_path_to_inst();
3851 	}
3852 }
3853 
3854 /*
3855  * Helper function for flush_path_to_inst() below; this routine calls the
3856  * inst_sync syscall to flush the path_to_inst database to the given file.
3857  */
3858 static int
3859 do_inst_sync(char *filename)
3860 {
3861 	void (*sigsaved)(int);
3862 	int err = 0;
3863 
3864 	vprint(INSTSYNC_MID, "do_inst_sync: about to flush %s\n", filename);
3865 	sigsaved = sigset(SIGSYS, SIG_IGN);
3866 	if (inst_sync(filename, 0) == -1)
3867 		err = errno;
3868 	(void) sigset(SIGSYS, sigsaved);
3869 
3870 	switch (err) {
3871 	case 0:
3872 		return (DEVFSADM_SUCCESS);
3873 	case EALREADY:	/* no-op, path_to_inst already up to date */
3874 		return (EALREADY);
3875 	case ENOSYS:
3876 		err_print(CANT_LOAD_SYSCALL);
3877 		break;
3878 	case EPERM:
3879 		err_print(SUPER_TO_SYNC);
3880 		break;
3881 	default:
3882 		err_print(INSTSYNC_FAILED, filename, strerror(err));
3883 		break;
3884 	}
3885 	return (DEVFSADM_FAILURE);
3886 }
3887 
3888 /*
3889  * Flush the kernel's path_to_inst database to /etc/path_to_inst.  To do so
3890  * safely, the database is flushed to a temporary file, then moved into place.
3891  *
3892  * The following files are used during this process:
3893  * 	/etc/path_to_inst:	The path_to_inst file
3894  * 	/etc/path_to_inst.<pid>: Contains data flushed from the kernel
3895  * 	/etc/path_to_inst.old:  The backup file
3896  * 	/etc/path_to_inst.old.<pid>: Temp file for creating backup
3897  *
3898  */
3899 static void
3900 flush_path_to_inst(void)
3901 {
3902 	char *new_inst_file = NULL;
3903 	char *old_inst_file = NULL;
3904 	char *old_inst_file_npid = NULL;
3905 	FILE *inst_file_fp = NULL;
3906 	FILE *old_inst_file_fp = NULL;
3907 	struct stat sb;
3908 	int err = 0;
3909 	int c;
3910 	int inst_strlen;
3911 
3912 	vprint(PATH2INST_MID, "flush_path_to_inst: %s\n",
3913 	    (flush_path_to_inst_enable == TRUE) ? "ENABLED" : "DISABLED");
3914 
3915 	if (flush_path_to_inst_enable == FALSE) {
3916 		return;
3917 	}
3918 
3919 	inst_strlen = strlen(inst_file);
3920 	new_inst_file = s_malloc(inst_strlen + PID_STR_LEN + 2);
3921 	old_inst_file = s_malloc(inst_strlen + PID_STR_LEN + 6);
3922 	old_inst_file_npid = s_malloc(inst_strlen +
3923 	    sizeof (INSTANCE_FILE_SUFFIX));
3924 
3925 	(void) snprintf(new_inst_file, inst_strlen + PID_STR_LEN + 2,
3926 		"%s.%ld", inst_file, getpid());
3927 
3928 	if (stat(new_inst_file, &sb) == 0) {
3929 		s_unlink(new_inst_file);
3930 	}
3931 
3932 	if ((err = do_inst_sync(new_inst_file)) != DEVFSADM_SUCCESS) {
3933 		goto out;
3934 		/*NOTREACHED*/
3935 	}
3936 
3937 	/*
3938 	 * Now we deal with the somewhat tricky updating and renaming
3939 	 * of this critical piece of kernel state.
3940 	 */
3941 
3942 	/*
3943 	 * Copy the current instance file into a temporary file.
3944 	 * Then rename the temporary file into the backup (.old)
3945 	 * file and rename the newly flushed kernel data into
3946 	 * the instance file.
3947 	 * Of course if 'inst_file' doesn't exist, there's much
3948 	 * less for us to do .. tee hee.
3949 	 */
3950 	if ((inst_file_fp = fopen(inst_file, "r")) == NULL) {
3951 		/*
3952 		 * No such file.  Rename the new onto the old
3953 		 */
3954 		if ((err = rename(new_inst_file, inst_file)) != 0)
3955 			err_print(RENAME_FAILED, inst_file, strerror(errno));
3956 		goto out;
3957 		/*NOTREACHED*/
3958 	}
3959 
3960 	(void) snprintf(old_inst_file, inst_strlen + PID_STR_LEN + 6,
3961 		"%s.old.%ld", inst_file, getpid());
3962 
3963 	if (stat(old_inst_file, &sb) == 0) {
3964 		s_unlink(old_inst_file);
3965 	}
3966 
3967 	if ((old_inst_file_fp = fopen(old_inst_file, "w")) == NULL) {
3968 		/*
3969 		 * Can't open the 'old_inst_file' file for writing.
3970 		 * This is somewhat strange given that the syscall
3971 		 * just succeeded to write a file out.. hmm.. maybe
3972 		 * the fs just filled up or something nasty.
3973 		 *
3974 		 * Anyway, abort what we've done so far.
3975 		 */
3976 		err_print(CANT_UPDATE, old_inst_file);
3977 		err = DEVFSADM_FAILURE;
3978 		goto out;
3979 		/*NOTREACHED*/
3980 	}
3981 
3982 	/*
3983 	 * Copy current instance file into the temporary file
3984 	 */
3985 	err = 0;
3986 	while ((c = getc(inst_file_fp)) != EOF) {
3987 		if ((err = putc(c, old_inst_file_fp)) == EOF) {
3988 			break;
3989 		}
3990 	}
3991 
3992 	if (fclose(old_inst_file_fp) == EOF || err == EOF) {
3993 		vprint(INFO_MID, CANT_UPDATE, old_inst_file);
3994 		err = DEVFSADM_FAILURE;
3995 		goto out;
3996 		/* NOTREACHED */
3997 	}
3998 
3999 	/*
4000 	 * Set permissions to be the same on the backup as
4001 	 * /etc/path_to_inst.
4002 	 */
4003 	(void) chmod(old_inst_file, 0444);
4004 
4005 	/*
4006 	 * So far, everything we've done is more or less reversible.
4007 	 * But now we're going to commit ourselves.
4008 	 */
4009 
4010 	(void) snprintf(old_inst_file_npid,
4011 	    inst_strlen + sizeof (INSTANCE_FILE_SUFFIX),
4012 	    "%s%s", inst_file, INSTANCE_FILE_SUFFIX);
4013 
4014 	if ((err = rename(old_inst_file, old_inst_file_npid)) != 0) {
4015 		err_print(RENAME_FAILED, old_inst_file_npid,
4016 				strerror(errno));
4017 	} else if ((err = rename(new_inst_file, inst_file)) != 0) {
4018 		err_print(RENAME_FAILED, inst_file, strerror(errno));
4019 	}
4020 
4021 out:
4022 	if (inst_file_fp != NULL) {
4023 		if (fclose(inst_file_fp) == EOF) {
4024 			err_print(FCLOSE_FAILED, inst_file, strerror(errno));
4025 		}
4026 	}
4027 
4028 	if (stat(new_inst_file, &sb) == 0) {
4029 		s_unlink(new_inst_file);
4030 	}
4031 	free(new_inst_file);
4032 
4033 	if (stat(old_inst_file, &sb) == 0) {
4034 		s_unlink(old_inst_file);
4035 	}
4036 	free(old_inst_file);
4037 
4038 	free(old_inst_file_npid);
4039 
4040 	if (err != 0 && err != EALREADY) {
4041 		err_print(FAILED_TO_UPDATE, inst_file);
4042 	}
4043 }
4044 
4045 /*
4046  * detach from tty.  For daemon mode.
4047  */
4048 void
4049 detachfromtty()
4050 {
4051 	(void) setsid();
4052 	if (DEVFSADM_DEBUG_ON == TRUE) {
4053 		return;
4054 	}
4055 
4056 	(void) close(0);
4057 	(void) close(1);
4058 	(void) close(2);
4059 	(void) open("/dev/null", O_RDWR, 0);
4060 	(void) dup(0);
4061 	(void) dup(0);
4062 	openlog(DEVFSADMD, LOG_PID, LOG_DAEMON);
4063 	(void) setlogmask(LOG_UPTO(LOG_INFO));
4064 	logflag = TRUE;
4065 }
4066 
4067 /*
4068  * Use an advisory lock to synchronize updates to /dev.  If the lock is
4069  * held by another process, block in the fcntl() system call until that
4070  * process drops the lock or exits.  The lock file itself is
4071  * DEV_LOCK_FILE.  The process id of the current and last process owning
4072  * the lock is kept in the lock file.  After acquiring the lock, read the
4073  * process id and return it.  It is the process ID which last owned the
4074  * lock, and will be used to determine if caches need to be flushed.
4075  *
4076  * NOTE: if the devlink database is held open by the caller, it may
4077  * be closed by this routine. This is to enforce the following lock ordering:
4078  *	1) /dev lock 2) database open
4079  */
4080 pid_t
4081 enter_dev_lock()
4082 {
4083 	struct flock lock;
4084 	int n;
4085 	pid_t pid;
4086 	pid_t last_owner_pid;
4087 
4088 	if (file_mods == FALSE) {
4089 		return (0);
4090 	}
4091 
4092 	s_mkdirp(dev_dir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
4093 	(void) snprintf(dev_lockfile, sizeof (dev_lockfile),
4094 	    "%s/%s", dev_dir, DEV_LOCK_FILE);
4095 
4096 	vprint(LOCK_MID, "enter_dev_lock: lock file %s\n", dev_lockfile);
4097 
4098 	dev_lock_fd = open(dev_lockfile, O_CREAT|O_RDWR, 0644);
4099 	if (dev_lock_fd < 0) {
4100 		err_print(OPEN_FAILED, dev_lockfile, strerror(errno));
4101 		devfsadm_exit(1);
4102 	}
4103 
4104 	lock.l_type = F_WRLCK;
4105 	lock.l_whence = SEEK_SET;
4106 	lock.l_start = 0;
4107 	lock.l_len = 0;
4108 
4109 	/* try for the lock, but don't wait */
4110 	if (fcntl(dev_lock_fd, F_SETLK, &lock) == -1) {
4111 		if ((errno == EACCES) || (errno == EAGAIN)) {
4112 			pid = 0;
4113 			n = read(dev_lock_fd, &pid, sizeof (pid_t));
4114 			vprint(LOCK_MID, "waiting for PID %d to complete\n",
4115 				(int)pid);
4116 			if (lseek(dev_lock_fd, 0, SEEK_SET) == (off_t)-1) {
4117 				err_print(LSEEK_FAILED, dev_lockfile,
4118 						strerror(errno));
4119 				devfsadm_exit(1);
4120 			}
4121 			/*
4122 			 * wait for the dev lock. If we have the database open,
4123 			 * close it first - the order of lock acquisition should
4124 			 * always be:  1) dev_lock 2) database
4125 			 * This is to prevent deadlocks with any locks the
4126 			 * database code may hold.
4127 			 */
4128 			(void) di_devlink_close(&devlink_cache, 0);
4129 			if (fcntl(dev_lock_fd, F_SETLKW, &lock) == -1) {
4130 				err_print(LOCK_FAILED, dev_lockfile,
4131 						strerror(errno));
4132 				devfsadm_exit(1);
4133 			}
4134 		}
4135 	}
4136 
4137 	hold_dev_lock = TRUE;
4138 	pid = 0;
4139 	n = read(dev_lock_fd, &pid, sizeof (pid_t));
4140 	if (n == sizeof (pid_t) && pid == getpid()) {
4141 		return (pid);
4142 	}
4143 
4144 	last_owner_pid = pid;
4145 
4146 	if (lseek(dev_lock_fd, 0, SEEK_SET) == (off_t)-1) {
4147 		err_print(LSEEK_FAILED, dev_lockfile, strerror(errno));
4148 		devfsadm_exit(1);
4149 	}
4150 	pid = getpid();
4151 	n = write(dev_lock_fd, &pid, sizeof (pid_t));
4152 	if (n != sizeof (pid_t)) {
4153 		err_print(WRITE_FAILED, dev_lockfile, strerror(errno));
4154 		devfsadm_exit(1);
4155 	}
4156 
4157 	return (last_owner_pid);
4158 }
4159 
4160 /*
4161  * Drop the advisory /dev lock, close lock file.  Close and re-open the
4162  * file every time so to ensure a resync if for some reason the lock file
4163  * gets removed.
4164  */
4165 void
4166 exit_dev_lock()
4167 {
4168 	struct flock unlock;
4169 
4170 	if (hold_dev_lock == FALSE) {
4171 		return;
4172 	}
4173 
4174 	vprint(LOCK_MID, "exit_dev_lock: lock file %s\n", dev_lockfile);
4175 
4176 	unlock.l_type = F_UNLCK;
4177 	unlock.l_whence = SEEK_SET;
4178 	unlock.l_start = 0;
4179 	unlock.l_len = 0;
4180 
4181 	if (fcntl(dev_lock_fd, F_SETLK, &unlock) == -1) {
4182 		err_print(UNLOCK_FAILED, dev_lockfile, strerror(errno));
4183 	}
4184 
4185 	hold_dev_lock = FALSE;
4186 
4187 	if (close(dev_lock_fd) == -1) {
4188 		err_print(CLOSE_FAILED, dev_lockfile, strerror(errno));
4189 		devfsadm_exit(1);
4190 	}
4191 }
4192 
4193 /*
4194  *
4195  * Use an advisory lock to ensure that only one daemon process is active
4196  * in the system at any point in time.	If the lock is held by another
4197  * process, do not block but return the pid owner of the lock to the
4198  * caller immediately.	The lock is cleared if the holding daemon process
4199  * exits for any reason even if the lock file remains, so the daemon can
4200  * be restarted if necessary.  The lock file is DAEMON_LOCK_FILE.
4201  */
4202 pid_t
4203 enter_daemon_lock(void)
4204 {
4205 	struct flock lock;
4206 
4207 	s_mkdirp(dev_dir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
4208 	(void) snprintf(daemon_lockfile, sizeof (daemon_lockfile),
4209 	    "%s/%s", dev_dir, DAEMON_LOCK_FILE);
4210 
4211 	vprint(LOCK_MID, "enter_daemon_lock: lock file %s\n", daemon_lockfile);
4212 
4213 	daemon_lock_fd = open(daemon_lockfile, O_CREAT|O_RDWR, 0644);
4214 	if (daemon_lock_fd < 0) {
4215 		err_print(OPEN_FAILED, daemon_lockfile, strerror(errno));
4216 		devfsadm_exit(1);
4217 	}
4218 
4219 	lock.l_type = F_WRLCK;
4220 	lock.l_whence = SEEK_SET;
4221 	lock.l_start = 0;
4222 	lock.l_len = 0;
4223 
4224 	if (fcntl(daemon_lock_fd, F_SETLK, &lock) == -1) {
4225 
4226 		if (errno == EAGAIN || errno == EDEADLK) {
4227 			if (fcntl(daemon_lock_fd, F_GETLK, &lock) == -1) {
4228 				err_print(LOCK_FAILED, daemon_lockfile,
4229 						strerror(errno));
4230 				devfsadm_exit(1);
4231 			}
4232 			return (lock.l_pid);
4233 		}
4234 	}
4235 	hold_daemon_lock = TRUE;
4236 	return (getpid());
4237 }
4238 
4239 /*
4240  * Drop the advisory daemon lock, close lock file
4241  */
4242 void
4243 exit_daemon_lock(void)
4244 {
4245 	struct flock lock;
4246 
4247 	if (hold_daemon_lock == FALSE) {
4248 		return;
4249 	}
4250 
4251 	vprint(LOCK_MID, "exit_daemon_lock: lock file %s\n", daemon_lockfile);
4252 
4253 	lock.l_type = F_UNLCK;
4254 	lock.l_whence = SEEK_SET;
4255 	lock.l_start = 0;
4256 	lock.l_len = 0;
4257 
4258 	if (fcntl(daemon_lock_fd, F_SETLK, &lock) == -1) {
4259 		err_print(UNLOCK_FAILED, daemon_lockfile, strerror(errno));
4260 	}
4261 
4262 	if (close(daemon_lock_fd) == -1) {
4263 		err_print(CLOSE_FAILED, daemon_lockfile, strerror(errno));
4264 		devfsadm_exit(1);
4265 	}
4266 }
4267 
4268 /*
4269  * Called to removed danging nodes in two different modes: RM_PRE, RM_POST.
4270  * RM_PRE mode is called before processing the entire devinfo tree, and RM_POST
4271  * is called after processing the entire devinfo tree.
4272  */
4273 static void
4274 pre_and_post_cleanup(int flags)
4275 {
4276 	remove_list_t *rm;
4277 	recurse_dev_t rd;
4278 	cleanup_data_t cleanup_data;
4279 	char *fcn = "pre_and_post_cleanup: ";
4280 
4281 	if (build_dev == FALSE)
4282 		return;
4283 
4284 	vprint(CHATTY_MID, "attempting %s-cleanup\n",
4285 	    flags == RM_PRE ? "pre" : "post");
4286 	vprint(REMOVE_MID, "%sflags = %d\n", fcn, flags);
4287 
4288 	/*
4289 	 * the generic function recurse_dev_re is shared among different
4290 	 * functions, so set the method and data that it should use for
4291 	 * matches.
4292 	 */
4293 	rd.fcn = matching_dev;
4294 	rd.data = (void *)&cleanup_data;
4295 	cleanup_data.flags = flags;
4296 
4297 	for (rm = remove_head; rm != NULL; rm = rm->next) {
4298 		if ((flags & rm->remove->flags) == flags) {
4299 			cleanup_data.rm = rm;
4300 			/*
4301 			 * If reached this point, RM_PRE or RM_POST cleanup is
4302 			 * desired.  clean_ok() decides whether to clean
4303 			 * under the given circumstances.
4304 			 */
4305 			vprint(REMOVE_MID, "%scleanup: PRE or POST\n", fcn);
4306 			if (clean_ok(rm->remove) == DEVFSADM_SUCCESS) {
4307 				vprint(REMOVE_MID, "cleanup: cleanup OK\n");
4308 				recurse_dev_re(dev_dir, rm->remove->
4309 					dev_dirs_re, &rd);
4310 			}
4311 		}
4312 	}
4313 }
4314 
4315 /*
4316  * clean_ok() determines whether cleanup should be done according
4317  * to the following matrix:
4318  *
4319  * command line arguments RM_PRE    RM_POST	  RM_PRE &&    RM_POST &&
4320  *						  RM_ALWAYS    RM_ALWAYS
4321  * ---------------------- ------     -----	  ---------    ----------
4322  *
4323  * <neither -c nor -C>	  -	    -		  pre-clean    post-clean
4324  *
4325  * -C			  pre-clean  post-clean   pre-clean    post-clean
4326  *
4327  * -C -c class		  pre-clean  post-clean   pre-clean    post-clean
4328  *			  if class  if class	  if class     if class
4329  *			  matches   matches	  matches      matches
4330  *
4331  * -c class		   -	       -	  pre-clean    post-clean
4332  *						  if class     if class
4333  *						  matches      matches
4334  *
4335  */
4336 static int
4337 clean_ok(devfsadm_remove_t *remove)
4338 {
4339 	int i;
4340 
4341 	if (single_drv == TRUE) {
4342 		/* no cleanup at all when using -i option */
4343 		return (DEVFSADM_FAILURE);
4344 	}
4345 
4346 	/*
4347 	 * no cleanup if drivers are not loaded. We make an exception
4348 	 * for the "disks" program however, since disks has a public
4349 	 * cleanup flag (-C) and disk drivers are usually never
4350 	 * unloaded.
4351 	 */
4352 	if (load_attach_drv == FALSE && strcmp(prog, DISKS) != 0) {
4353 		return (DEVFSADM_FAILURE);
4354 	}
4355 
4356 	/* if the cleanup flag was not specified, return false */
4357 	if ((cleanup == FALSE) && ((remove->flags & RM_ALWAYS) == 0)) {
4358 		return (DEVFSADM_FAILURE);
4359 	}
4360 
4361 	if (num_classes == 0) {
4362 		return (DEVFSADM_SUCCESS);
4363 	}
4364 
4365 	/*
4366 	 * if reached this point, check to see if the class in the given
4367 	 * remove structure matches a class given on the command line
4368 	 */
4369 
4370 	for (i = 0; i < num_classes; i++) {
4371 		if (strcmp(remove->device_class, classes[i]) == 0) {
4372 			return (DEVFSADM_SUCCESS);
4373 		}
4374 	}
4375 
4376 	return (DEVFSADM_FAILURE);
4377 }
4378 
4379 /*
4380  * Called to remove dangling nodes after receiving a hotplug event
4381  * containing the physical node pathname to be removed.
4382  */
4383 void
4384 hot_cleanup(char *node_path, char *minor_name, char *ev_subclass,
4385     char *driver_name, int instance)
4386 {
4387 	link_t *link;
4388 	linkhead_t *head;
4389 	remove_list_t *rm;
4390 	char *fcn = "hot_cleanup: ";
4391 	char path[PATH_MAX + 1];
4392 	int path_len;
4393 	char rmlink[PATH_MAX + 1];
4394 	nvlist_t *nvl = NULL;
4395 	int skip;
4396 
4397 	/*
4398 	 * dev links can go away as part of hot cleanup.
4399 	 * So first build event attributes in order capture dev links.
4400 	 */
4401 	if (ev_subclass != NULL)
4402 		nvl = build_event_attributes(EC_DEV_REMOVE, ev_subclass,
4403 		    node_path, DI_NODE_NIL, driver_name, instance);
4404 
4405 	(void) strcpy(path, node_path);
4406 	(void) strcat(path, ":");
4407 	(void) strcat(path, minor_name == NULL ? "" : minor_name);
4408 
4409 	path_len = strlen(path);
4410 
4411 	vprint(REMOVE_MID, "%spath=%s\n", fcn, path);
4412 
4413 	for (rm = remove_head; rm != NULL; rm = rm->next) {
4414 		if ((RM_HOT & rm->remove->flags) == RM_HOT) {
4415 			head = get_cached_links(rm->remove->dev_dirs_re);
4416 			assert(head->nextlink == NULL);
4417 			for (link = head->link;
4418 			    link != NULL; link = head->nextlink) {
4419 				/*
4420 				 * The remove callback below may remove
4421 				 * the current and/or any or all of the
4422 				 * subsequent links in the list.
4423 				 * Save the next link in the head. If
4424 				 * the callback removes the next link
4425 				 * the saved pointer in the head will be
4426 				 * updated by the callback to point at
4427 				 * the next valid link.
4428 				 */
4429 				head->nextlink = link->next;
4430 				if (minor_name)
4431 					skip = strcmp(link->contents, path);
4432 				else
4433 					skip = strncmp(link->contents, path,
4434 					    path_len);
4435 				if (skip ||
4436 				    (call_minor_init(rm->modptr) ==
4437 				    DEVFSADM_FAILURE))
4438 					continue;
4439 
4440 				vprint(REMOVE_MID,
4441 					"%sremoving %s -> %s\n", fcn,
4442 					link->devlink, link->contents);
4443 				/*
4444 				 * Use a copy of the cached link name
4445 				 * as the cache entry will go away
4446 				 * during link removal
4447 				 */
4448 				(void) snprintf(rmlink, sizeof (rmlink),
4449 				    "%s", link->devlink);
4450 				(*(rm->remove->callback_fcn))(rmlink);
4451 			}
4452 		}
4453 	}
4454 
4455 	/* now log an event */
4456 	if (nvl) {
4457 		log_event(EC_DEV_REMOVE, ev_subclass, nvl);
4458 		free(nvl);
4459 	}
4460 }
4461 
4462 /*
4463  * Open the dir current_dir.  For every file which matches the first dir
4464  * component of path_re, recurse.  If there are no more *dir* path
4465  * components left in path_re (ie no more /), then call function rd->fcn.
4466  */
4467 static void
4468 recurse_dev_re(char *current_dir, char *path_re, recurse_dev_t *rd)
4469 {
4470 	regex_t re1;
4471 	char *slash;
4472 	char new_path[PATH_MAX + 1];
4473 	char *anchored_path_re;
4474 	struct dirent *entp;
4475 	DIR *dp;
4476 	size_t len;
4477 
4478 	vprint(RECURSEDEV_MID, "recurse_dev_re: curr = %s path=%s\n",
4479 		current_dir, path_re);
4480 
4481 	if ((dp = opendir(current_dir)) == NULL) {
4482 		return;
4483 	}
4484 
4485 	len = strlen(path_re);
4486 	if ((slash = strchr(path_re, '/')) != NULL) {
4487 		len = (slash - path_re);
4488 	}
4489 
4490 	anchored_path_re = s_malloc(len + 3);
4491 	(void) sprintf(anchored_path_re, "^%.*s$", len, path_re);
4492 
4493 	if (regcomp(&re1, anchored_path_re, REG_EXTENDED) != 0) {
4494 		free(anchored_path_re);
4495 		goto out;
4496 	}
4497 
4498 	free(anchored_path_re);
4499 
4500 	while ((entp = readdir(dp)) != NULL) {
4501 
4502 		if (strcmp(entp->d_name, ".") == 0 ||
4503 		    strcmp(entp->d_name, "..") == 0) {
4504 			continue;
4505 		}
4506 
4507 		if (regexec(&re1, entp->d_name, 0, NULL, 0) == 0) {
4508 			/* match */
4509 			(void) strcpy(new_path, current_dir);
4510 			(void) strcat(new_path, "/");
4511 			(void) strcat(new_path, entp->d_name);
4512 
4513 			vprint(RECURSEDEV_MID, "recurse_dev_re: match, new "
4514 				"path = %s\n", new_path);
4515 
4516 			if (slash != NULL) {
4517 				recurse_dev_re(new_path, slash + 1, rd);
4518 			} else {
4519 				/* reached the leaf component of path_re */
4520 				vprint(RECURSEDEV_MID,
4521 					"recurse_dev_re: calling fcn\n");
4522 				(*(rd->fcn))(new_path, rd->data);
4523 			}
4524 		}
4525 	}
4526 
4527 	regfree(&re1);
4528 
4529 out:
4530 	s_closedir(dp);
4531 }
4532 
4533 /*
4534  *  Found a devpath which matches a RE in the remove structure.
4535  *  Now check to see if it is dangling.
4536  */
4537 static void
4538 matching_dev(char *devpath, void *data)
4539 {
4540 	cleanup_data_t *cleanup_data = data;
4541 	char *fcn = "matching_dev: ";
4542 
4543 	vprint(RECURSEDEV_MID, "%sexamining devpath = '%s'\n", fcn,
4544 			devpath);
4545 
4546 	if (resolve_link(devpath, NULL, NULL, NULL, 1) == TRUE) {
4547 		if (call_minor_init(cleanup_data->rm->modptr) ==
4548 				DEVFSADM_FAILURE) {
4549 			return;
4550 		}
4551 
4552 		devpath += strlen(dev_dir) + strlen("/");
4553 
4554 		vprint(RECURSEDEV_MID, "%scalling"
4555 			" callback %s\n", fcn, devpath);
4556 		(*(cleanup_data->rm->remove->callback_fcn))(devpath);
4557 	}
4558 }
4559 
4560 int
4561 devfsadm_read_link(char *link, char **devfs_path)
4562 {
4563 	char devlink[PATH_MAX];
4564 
4565 	*devfs_path = NULL;
4566 
4567 	/* prepend link with dev_dir contents */
4568 	(void) strcpy(devlink, dev_dir);
4569 	(void) strcat(devlink, "/");
4570 	(void) strcat(devlink, link);
4571 
4572 	/* We *don't* want a stat of the /devices node */
4573 	(void) resolve_link(devlink, NULL, NULL, devfs_path, 0);
4574 
4575 	return (*devfs_path ? DEVFSADM_SUCCESS : DEVFSADM_FAILURE);
4576 }
4577 
4578 int
4579 devfsadm_link_valid(char *link)
4580 {
4581 	struct stat sb;
4582 	char devlink[PATH_MAX + 1], *contents;
4583 	int rv, type;
4584 
4585 	/* prepend link with dev_dir contents */
4586 	(void) strcpy(devlink, dev_dir);
4587 	(void) strcat(devlink, "/");
4588 	(void) strcat(devlink, link);
4589 
4590 	if (lstat(devlink, &sb) != 0) {
4591 		return (DEVFSADM_FALSE);
4592 	}
4593 
4594 	contents = NULL;
4595 	type = 0;
4596 	if (resolve_link(devlink, &contents, &type, NULL, 1) == TRUE) {
4597 		rv = DEVFSADM_FALSE;
4598 	} else {
4599 		rv = DEVFSADM_TRUE;
4600 	}
4601 
4602 	/*
4603 	 * The link exists. Add it to the database
4604 	 */
4605 	(void) di_devlink_add_link(devlink_cache, link, contents, type);
4606 	free(contents);
4607 
4608 	return (rv);
4609 }
4610 
4611 /*
4612  * devpath: Absolute path to /dev link
4613  * content_p: Returns malloced string (link content)
4614  * type_p: Returns link type: primary or secondary
4615  * devfs_path: Returns malloced string: /devices path w/out "/devices"
4616  * dangle: if set, check if link is dangling
4617  * Returns:
4618  *	TRUE if dangling
4619  *	FALSE if not or if caller doesn't care
4620  * Caller is assumed to have initialized pointer contents to NULL
4621  */
4622 static int
4623 resolve_link(char *devpath, char **content_p, int *type_p, char **devfs_path,
4624     int dangle)
4625 {
4626 	char contents[PATH_MAX + 1];
4627 	char stage_link[PATH_MAX + 1];
4628 	char *fcn = "resolve_link: ";
4629 	char *ptr;
4630 	int linksize;
4631 	int rv = TRUE;
4632 	struct stat sb;
4633 
4634 	linksize = readlink(devpath, contents, PATH_MAX);
4635 
4636 	if (linksize <= 0) {
4637 		return (FALSE);
4638 	} else {
4639 		contents[linksize] = '\0';
4640 	}
4641 	vprint(REMOVE_MID, "%s %s -> %s\n", fcn, devpath, contents);
4642 
4643 	if (content_p) {
4644 		*content_p = s_strdup(contents);
4645 	}
4646 
4647 	/*
4648 	 * Check to see if this is a link pointing to another link in /dev.  The
4649 	 * cheap way to do this is to look for a lack of ../devices/.
4650 	 */
4651 
4652 	if (is_minor_node(contents, &ptr) == DEVFSADM_FALSE) {
4653 
4654 		if (type_p) {
4655 			*type_p = DI_SECONDARY_LINK;
4656 		}
4657 
4658 		/*
4659 		 * assume that linkcontents is really a pointer to another
4660 		 * link, and if so recurse and read its link contents.
4661 		 */
4662 		if (strncmp(contents, DEV "/", strlen(DEV) + 1) == 0)  {
4663 			(void) strcpy(stage_link, dev_dir);
4664 			(void) strcat(stage_link, "/");
4665 			(void) strcpy(stage_link,
4666 					&contents[strlen(DEV) + strlen("/")]);
4667 		} else {
4668 			if ((ptr = strrchr(devpath, '/')) == NULL) {
4669 				vprint(REMOVE_MID, "%s%s -> %s invalid link. "
4670 					"missing '/'\n", fcn, devpath,
4671 					contents);
4672 				return (TRUE);
4673 			}
4674 			*ptr = '\0';
4675 			(void) strcpy(stage_link, devpath);
4676 			*ptr = '/';
4677 			(void) strcat(stage_link, "/");
4678 			(void) strcat(stage_link, contents);
4679 		}
4680 		return (resolve_link(stage_link, NULL, NULL, devfs_path,
4681 		    dangle));
4682 	}
4683 
4684 	/* Current link points at a /devices minor node */
4685 	if (type_p) {
4686 		*type_p = DI_PRIMARY_LINK;
4687 	}
4688 
4689 	if (devfs_path)
4690 		*devfs_path = s_strdup(ptr);
4691 
4692 	rv = FALSE;
4693 	if (dangle)
4694 		rv = (stat(ptr - strlen(DEVICES), &sb) == -1);
4695 
4696 	vprint(REMOVE_MID, "%slink=%s, returning %s\n", fcn,
4697 			devpath, ((rv == TRUE) ? "TRUE" : "FALSE"));
4698 
4699 	return (rv);
4700 }
4701 
4702 /*
4703  * Returns the substring of interest, given a path.
4704  */
4705 static char *
4706 alloc_cmp_str(const char *path, devfsadm_enumerate_t *dep)
4707 {
4708 	uint_t match;
4709 	char *np, *ap, *mp;
4710 	char *cmp_str = NULL;
4711 	char at[] = "@";
4712 	char *fcn = "alloc_cmp_str";
4713 
4714 	np = ap = mp = NULL;
4715 
4716 	/*
4717 	 * extract match flags from the flags argument.
4718 	 */
4719 	match = (dep->flags & MATCH_MASK);
4720 
4721 	vprint(ENUM_MID, "%s: enumeration match type: 0x%x"
4722 	    " path: %s\n", fcn, match, path);
4723 
4724 	/*
4725 	 * MATCH_CALLBACK and MATCH_ALL are the only flags
4726 	 * which may be used if "path" is a /dev path
4727 	 */
4728 	if (match == MATCH_CALLBACK) {
4729 		if (dep->sel_fcn == NULL) {
4730 			vprint(ENUM_MID, "%s: invalid enumerate"
4731 			    " callback: path: %s\n", fcn, path);
4732 			return (NULL);
4733 		}
4734 		cmp_str = dep->sel_fcn(path, dep->cb_arg);
4735 		return (cmp_str);
4736 	}
4737 
4738 	cmp_str = s_strdup(path);
4739 
4740 	if (match == MATCH_ALL) {
4741 		return (cmp_str);
4742 	}
4743 
4744 	/*
4745 	 * The remaining flags make sense only for /devices
4746 	 * paths
4747 	 */
4748 	if ((mp = strrchr(cmp_str, ':')) == NULL) {
4749 		vprint(ENUM_MID, "%s: invalid path: %s\n",
4750 		    fcn, path);
4751 		goto err;
4752 	}
4753 
4754 	if (match == MATCH_MINOR) {
4755 		/* A NULL "match_arg" values implies entire minor */
4756 		if (get_component(mp + 1, dep->match_arg) == NULL) {
4757 			vprint(ENUM_MID, "%s: invalid minor component:"
4758 			    " path: %s\n", fcn, path);
4759 			goto err;
4760 		}
4761 		return (cmp_str);
4762 	}
4763 
4764 	if ((np = strrchr(cmp_str, '/')) == NULL) {
4765 		vprint(ENUM_MID, "%s: invalid path: %s\n", fcn, path);
4766 		goto err;
4767 	}
4768 
4769 	if (match == MATCH_PARENT) {
4770 		if (strcmp(cmp_str, "/") == 0) {
4771 			vprint(ENUM_MID, "%s: invalid path: %s\n",
4772 			    fcn, path);
4773 			goto err;
4774 		}
4775 
4776 		if (np == cmp_str) {
4777 			*(np + 1) = '\0';
4778 		} else {
4779 			*np = '\0';
4780 		}
4781 		return (cmp_str);
4782 	}
4783 
4784 	/* ap can be NULL - Leaf address may not exist or be empty string */
4785 	ap = strchr(np+1, '@');
4786 
4787 	/* minor is no longer of interest */
4788 	*mp = '\0';
4789 
4790 	if (match == MATCH_NODE) {
4791 		if (ap)
4792 			*ap = '\0';
4793 		return (cmp_str);
4794 	} else if (match == MATCH_ADDR) {
4795 		/*
4796 		 * The empty string is a valid address. The only MATCH_ADDR
4797 		 * allowed in this case is against the whole address or
4798 		 * the first component of the address (match_arg=NULL/"0"/"1")
4799 		 * Note that in this case, the path won't have an "@"
4800 		 * As a result ap will be NULL. We fake up an ap = @'\0'
4801 		 * so that get_component() will work correctly.
4802 		 */
4803 		if (ap == NULL) {
4804 			ap = at;
4805 		}
4806 
4807 		if (get_component(ap + 1, dep->match_arg) == NULL) {
4808 			vprint(ENUM_MID, "%s: invalid leaf addr. component:"
4809 			    " path: %s\n", fcn, path);
4810 			goto err;
4811 		}
4812 		return (cmp_str);
4813 	}
4814 
4815 	vprint(ENUM_MID, "%s: invalid enumeration flags: 0x%x"
4816 		" path: %s\n", fcn, dep->flags, path);
4817 
4818 	/*FALLTHRU*/
4819 err:
4820 	free(cmp_str);
4821 	return (NULL);
4822 }
4823 
4824 
4825 /*
4826  * "str" is expected to be a string with components separated by ','
4827  * The terminating null char is considered a separator.
4828  * get_component() will remove the portion of the string beyond
4829  * the component indicated.
4830  * If comp_str is NULL, the entire "str" is returned.
4831  */
4832 static char *
4833 get_component(char *str, const char *comp_str)
4834 {
4835 	long comp;
4836 	char *cp;
4837 
4838 	if (str == NULL) {
4839 		return (NULL);
4840 	}
4841 
4842 	if (comp_str == NULL) {
4843 		return (str);
4844 	}
4845 
4846 	errno = 0;
4847 	comp = strtol(comp_str, &cp, 10);
4848 	if (errno != 0 || *cp != '\0' || comp < 0) {
4849 		return (NULL);
4850 	}
4851 
4852 	if (comp == 0)
4853 		return (str);
4854 
4855 	for (cp = str; ; cp++) {
4856 		if (*cp == ',' || *cp == '\0')
4857 			comp--;
4858 		if (*cp == '\0' || comp <= 0) {
4859 			break;
4860 		}
4861 	}
4862 
4863 	if (comp == 0) {
4864 		*cp = '\0';
4865 	} else {
4866 		str = NULL;
4867 	}
4868 
4869 	return (str);
4870 }
4871 
4872 
4873 /*
4874  * Enumerate serves as a generic counter as well as a means to determine
4875  * logical unit/controller numbers for such items as disk and tape
4876  * drives.
4877  *
4878  * rules[] is an array of  devfsadm_enumerate_t structures which defines
4879  * the enumeration rules to be used for a specified set of links in /dev.
4880  * The set of links is specified through regular expressions (of the flavor
4881  * described in regex(5)). These regular expressions are used to determine
4882  * the set of links in /dev to examine. The last path component in these
4883  * regular expressions MUST contain a parenthesized subexpression surrounding
4884  * the RE which is to be considered the enumerating component. The subexp
4885  * member in a rule is the subexpression number of the enumerating
4886  * component. Subexpressions in the last path component are numbered starting
4887  * from 1.
4888  *
4889  * A cache of current id assignments is built up from existing symlinks and
4890  * new assignments use the lowest unused id. Assignments are based on a
4891  * match of a specified substring of a symlink's contents. If the specified
4892  * component for the devfs_path argument matches the corresponding substring
4893  * for a existing symlink's contents, the cached id is returned. Else, a new
4894  * id is created and returned in *buf. *buf must be freed by the caller.
4895  *
4896  * An id assignment may be governed by a combination of rules, each rule
4897  * applicable to a different subset of links in /dev. For example, controller
4898  * numbers may be determined by a combination of disk symlinks in /dev/[r]dsk
4899  * and controller symlinks in /dev/cfg, with the two sets requiring different
4900  * rules to derive the "substring of interest". In such cases, the rules
4901  * array will have more than one element.
4902  */
4903 int
4904 devfsadm_enumerate_int(char *devfs_path, int index, char **buf,
4905 			devfsadm_enumerate_t rules[], int nrules)
4906 {
4907 	return (find_enum_id(rules, nrules,
4908 	    devfs_path, index, "0", INTEGER, buf, 0));
4909 }
4910 
4911 int
4912 disk_enumerate_int(char *devfs_path, int index, char **buf,
4913     devfsadm_enumerate_t rules[], int nrules)
4914 {
4915 	return (find_enum_id(rules, nrules,
4916 	    devfs_path, index, "0", INTEGER, buf, 1));
4917 }
4918 
4919 /*
4920  * Same as above, but allows a starting value to be specified.
4921  * Private to devfsadm.... used by devlinks.
4922  */
4923 static int
4924 devfsadm_enumerate_int_start(char *devfs_path, int index, char **buf,
4925 		devfsadm_enumerate_t rules[], int nrules, char *start)
4926 {
4927 	return (find_enum_id(rules, nrules,
4928 	    devfs_path, index, start, INTEGER, buf, 0));
4929 }
4930 
4931 /*
4932  *  devfsadm_enumerate_char serves as a generic counter returning
4933  *  a single letter.
4934  */
4935 int
4936 devfsadm_enumerate_char(char *devfs_path, int index, char **buf,
4937 			devfsadm_enumerate_t rules[], int nrules)
4938 {
4939 	return (find_enum_id(rules, nrules,
4940 	    devfs_path, index, "a", LETTER, buf, 0));
4941 }
4942 
4943 /*
4944  * Same as above, but allows a starting char to be specified.
4945  * Private to devfsadm - used by ports module (port_link.c)
4946  */
4947 int
4948 devfsadm_enumerate_char_start(char *devfs_path, int index, char **buf,
4949 	devfsadm_enumerate_t rules[], int nrules, char *start)
4950 {
4951 	return (find_enum_id(rules, nrules,
4952 	    devfs_path, index, start, LETTER, buf, 0));
4953 }
4954 
4955 
4956 /*
4957  * For a given numeral_set (see get_cached_set for desc of numeral_set),
4958  * search all cached entries looking for matches on a specified substring
4959  * of devfs_path. The substring is derived from devfs_path based on the
4960  * rule specified by "index". If a match is found on a cached entry,
4961  * return the enumerated id in buf. Otherwise, create a new id by calling
4962  * new_id, then cache and return that entry.
4963  */
4964 static int
4965 find_enum_id(devfsadm_enumerate_t rules[], int nrules,
4966 	char *devfs_path, int index, char *min, int type, char **buf,
4967 	int multiple)
4968 {
4969 	numeral_t *matchnp;
4970 	numeral_t *numeral;
4971 	int matchcount = 0;
4972 	char *cmp_str;
4973 	char *fcn = "find_enum_id";
4974 	numeral_set_t *set;
4975 
4976 	if (rules == NULL) {
4977 		vprint(ENUM_MID, "%s: no rules. path: %s\n",
4978 		    fcn, devfs_path ? devfs_path : "<NULL path>");
4979 		return (DEVFSADM_FAILURE);
4980 	}
4981 
4982 	if (devfs_path == NULL) {
4983 		vprint(ENUM_MID, "%s: NULL path\n", fcn);
4984 		return (DEVFSADM_FAILURE);
4985 	}
4986 
4987 	if (nrules <= 0 || index < 0 || index >= nrules || buf == NULL) {
4988 		vprint(ENUM_MID, "%s: invalid arguments. path: %s\n",
4989 		    fcn, devfs_path);
4990 		return (DEVFSADM_FAILURE);
4991 	}
4992 
4993 	*buf = NULL;
4994 
4995 
4996 	cmp_str = alloc_cmp_str(devfs_path, &rules[index]);
4997 	if (cmp_str == NULL) {
4998 		return (DEVFSADM_FAILURE);
4999 	}
5000 
5001 	if ((set = get_enum_cache(rules, nrules)) == NULL) {
5002 		free(cmp_str);
5003 		return (DEVFSADM_FAILURE);
5004 	}
5005 
5006 	assert(nrules == set->re_count);
5007 
5008 	/*
5009 	 * Check and see if a matching entry is already cached.
5010 	 */
5011 	matchcount = lookup_enum_cache(set, cmp_str, rules, index,
5012 	    &matchnp);
5013 
5014 	if (matchcount < 0 || matchcount > 1) {
5015 		free(cmp_str);
5016 		if (multiple && matchcount > 1)
5017 			return (DEVFSADM_MULTIPLE);
5018 		else
5019 			return (DEVFSADM_FAILURE);
5020 	}
5021 
5022 	/* if matching entry already cached, return it */
5023 	if (matchcount == 1) {
5024 		*buf = s_strdup(matchnp->id);
5025 		free(cmp_str);
5026 		return (DEVFSADM_SUCCESS);
5027 	}
5028 
5029 	/*
5030 	 * no cached entry, initialize a numeral struct
5031 	 * by calling new_id() and cache onto the numeral_set
5032 	 */
5033 	numeral = s_malloc(sizeof (numeral_t));
5034 	numeral->id = new_id(set->headnumeral, type, min);
5035 	numeral->full_path = s_strdup(devfs_path);
5036 	numeral->rule_index = index;
5037 	numeral->cmp_str = cmp_str;
5038 	cmp_str = NULL;
5039 
5040 	/* insert to head of list for fast lookups */
5041 	numeral->next = set->headnumeral;
5042 	set->headnumeral = numeral;
5043 
5044 	*buf = s_strdup(numeral->id);
5045 	return (DEVFSADM_SUCCESS);
5046 }
5047 
5048 
5049 /*
5050  * Looks up the specified cache for a match with a specified string
5051  * Returns:
5052  *	-1	: on error.
5053  *	0/1/2	: Number of matches.
5054  * Returns the matching element only if there is a single match.
5055  * If the "uncached" flag is set, derives the "cmp_str" afresh
5056  * for the match instead of using cached values.
5057  */
5058 static int
5059 lookup_enum_cache(numeral_set_t *set, char *cmp_str,
5060 	devfsadm_enumerate_t rules[], int index, numeral_t **matchnpp)
5061 {
5062 	int matchcount = 0, rv = -1;
5063 	int uncached;
5064 	numeral_t *np;
5065 	char *fcn = "lookup_enum_cache";
5066 	char *cp;
5067 
5068 	*matchnpp = NULL;
5069 
5070 	assert(index < set->re_count);
5071 
5072 	if (cmp_str == NULL) {
5073 		return (-1);
5074 	}
5075 
5076 	uncached = 0;
5077 	if ((rules[index].flags & MATCH_UNCACHED) == MATCH_UNCACHED) {
5078 		uncached = 1;
5079 	}
5080 
5081 	/*
5082 	 * Check and see if a matching entry is already cached.
5083 	 */
5084 	for (np = set->headnumeral; np != NULL; np = np->next) {
5085 		if (np->cmp_str == NULL) {
5086 			vprint(ENUM_MID, "%s: invalid entry in enumerate"
5087 			    " cache. path: %s\n", fcn, np->full_path);
5088 			return (-1);
5089 		}
5090 
5091 		if (uncached) {
5092 			vprint(CHATTY_MID, "%s: bypassing enumerate cache."
5093 			    " path: %s\n", fcn, cmp_str);
5094 			cp = alloc_cmp_str(np->full_path,
5095 			    &rules[np->rule_index]);
5096 			if (cp == NULL)
5097 				return (-1);
5098 			rv = strcmp(cmp_str, cp);
5099 			free(cp);
5100 		} else {
5101 			rv = strcmp(cmp_str, np->cmp_str);
5102 		}
5103 
5104 		if (rv == 0) {
5105 			if (matchcount++ != 0) {
5106 				break; /* more than 1 match. */
5107 			}
5108 			*matchnpp = np;
5109 		}
5110 	}
5111 
5112 	return (matchcount);
5113 }
5114 
5115 #ifdef	DEBUG
5116 static void
5117 dump_enum_cache(numeral_set_t *setp)
5118 {
5119 	int i;
5120 	numeral_t *np;
5121 	char *fcn = "dump_enum_cache";
5122 
5123 	vprint(ENUM_MID, "%s: re_count = %d\n", fcn, setp->re_count);
5124 	for (i = 0; i < setp->re_count; i++) {
5125 		vprint(ENUM_MID, "%s: re[%d] = %s\n", fcn, i, setp->re[i]);
5126 	}
5127 
5128 	for (np = setp->headnumeral; np != NULL; np = np->next) {
5129 		vprint(ENUM_MID, "%s: id: %s\n", fcn, np->id);
5130 		vprint(ENUM_MID, "%s: full_path: %s\n", fcn, np->full_path);
5131 		vprint(ENUM_MID, "%s: rule_index: %d\n", fcn, np->rule_index);
5132 		vprint(ENUM_MID, "%s: cmp_str: %s\n", fcn, np->cmp_str);
5133 	}
5134 }
5135 #endif
5136 
5137 /*
5138  * For a given set of regular expressions in rules[], this function returns
5139  * either a previously cached struct numeral_set or it will create and
5140  * cache a new struct numeral_set.  There is only one struct numeral_set
5141  * for the combination of REs present in rules[].  Each numeral_set contains
5142  * the regular expressions in rules[] used for cache selection AND a linked
5143  * list of struct numerals, ONE FOR EACH *UNIQUE* numeral or character ID
5144  * selected by the grouping parenthesized subexpression found in the last
5145  * path component of each rules[].re.  For example, the RE: "rmt/([0-9]+)"
5146  * selects all the logical nodes of the correct form in dev/rmt/.
5147  * Each rmt/X will store a *single* struct numeral... ie 0, 1, 2 each get a
5148  * single struct numeral. There is no need to store more than a single logical
5149  * node matching X since the information desired in the devfspath would be
5150  * identical for the portion of the devfspath of interest. (the part up to,
5151  * but not including the minor name in this example.)
5152  *
5153  * If the given numeral_set is not yet cached, call enumerate_recurse to
5154  * create it.
5155  */
5156 static numeral_set_t *
5157 get_enum_cache(devfsadm_enumerate_t rules[], int nrules)
5158 {
5159 	/* linked list of numeral sets */
5160 	numeral_set_t *setp;
5161 	int i;
5162 	char *path_left;
5163 	char *fcn = "get_enum_cache";
5164 
5165 	/*
5166 	 * See if we've already cached this numeral set.
5167 	 */
5168 	for (setp = head_numeral_set; setp != NULL; setp = setp->next) {
5169 		/*
5170 		 *  check all regexp's passed in function against
5171 		 *  those in cached set.
5172 		 */
5173 		if (nrules != setp->re_count) {
5174 			continue;
5175 		}
5176 
5177 		for (i = 0; i < nrules; i++) {
5178 			if (strcmp(setp->re[i], rules[i].re) != 0) {
5179 				break;
5180 			}
5181 		}
5182 
5183 		if (i == nrules) {
5184 			return (setp);
5185 		}
5186 	}
5187 
5188 	/*
5189 	 * If the MATCH_UNCACHED flag is set, we should not  be here.
5190 	 */
5191 	for (i = 0; i < nrules; i++) {
5192 		if ((rules[i].flags & MATCH_UNCACHED) == MATCH_UNCACHED) {
5193 			vprint(ENUM_MID, "%s: invalid enumeration flags: "
5194 			    "0x%x\n", fcn, rules[i].flags);
5195 			return (NULL);
5196 		}
5197 	}
5198 
5199 	/*
5200 	 *  Since we made it here, we have not yet cached the given set of
5201 	 *  logical nodes matching the passed re.  Create a cached entry
5202 	 *  struct numeral_set and populate it with a minimal set of
5203 	 *  logical nodes from /dev.
5204 	 */
5205 
5206 	setp = s_malloc(sizeof (numeral_set_t));
5207 	setp->re = s_malloc(sizeof (char *) * nrules);
5208 	for (i = 0; i < nrules; i++) {
5209 		setp->re[i] = s_strdup(rules[i].re);
5210 	}
5211 	setp->re_count = nrules;
5212 	setp->headnumeral = NULL;
5213 
5214 	/* put this new cached set on the cached set list */
5215 	setp->next = head_numeral_set;
5216 	head_numeral_set = setp;
5217 
5218 	/*
5219 	 * For each RE, search disk and cache any matches on the
5220 	 * numeral list.  We are careful to use global_dev_dir here since
5221 	 * for zones, we want to use the global zone's enumeration as the
5222 	 * source for enumeration within the zone.  Otherwise, for example,
5223 	 * controller numbering would be wrong within the zone.
5224 	 */
5225 	for (i = 0; i < nrules; i++) {
5226 		path_left = s_strdup(setp->re[i]);
5227 		enumerate_recurse(global_dev_dir, path_left, setp, rules, i);
5228 		free(path_left);
5229 	}
5230 
5231 #ifdef	DEBUG
5232 	dump_enum_cache(setp);
5233 #endif
5234 
5235 	return (setp);
5236 }
5237 
5238 
5239 /*
5240  * This function stats the pathname namebuf.  If this is a directory
5241  * entry, we recurse down dname/fname until we find the first symbolic
5242  * link, and then stat and return it.  This is valid for the same reason
5243  * that we only need to read a single pathname for multiple matching
5244  * logical ID's... ie, all the logical nodes should contain identical
5245  * physical paths for the parts we are interested.
5246  */
5247 int
5248 get_stat_info(char *namebuf, struct stat *sb)
5249 {
5250 	struct dirent *entp;
5251 	DIR *dp;
5252 	char *cp;
5253 
5254 	if (lstat(namebuf, sb) < 0) {
5255 		(void) err_print(LSTAT_FAILED, namebuf, strerror(errno));
5256 		return (DEVFSADM_FAILURE);
5257 	}
5258 
5259 	if ((sb->st_mode & S_IFMT) == S_IFLNK) {
5260 		return (DEVFSADM_SUCCESS);
5261 	}
5262 
5263 	/*
5264 	 * If it is a dir, recurse down until we find a link and
5265 	 * then use the link.
5266 	 */
5267 	if ((sb->st_mode & S_IFMT) == S_IFDIR) {
5268 
5269 		if ((dp = opendir(namebuf)) == NULL) {
5270 			return (DEVFSADM_FAILURE);
5271 		}
5272 
5273 		/*
5274 		 *  Search each dir entry looking for a symlink.  Return
5275 		 *  the first symlink found in namebuf.  Recurse dirs.
5276 		 */
5277 		while ((entp = readdir(dp)) != NULL) {
5278 			if (strcmp(entp->d_name, ".") == 0 ||
5279 			    strcmp(entp->d_name, "..") == 0) {
5280 				continue;
5281 			}
5282 
5283 			cp = namebuf + strlen(namebuf);
5284 			(void) strcat(namebuf, "/");
5285 			(void) strcat(namebuf, entp->d_name);
5286 			if (get_stat_info(namebuf, sb) == DEVFSADM_SUCCESS) {
5287 				s_closedir(dp);
5288 				return (DEVFSADM_SUCCESS);
5289 			}
5290 			*cp = '\0';
5291 		}
5292 		s_closedir(dp);
5293 	}
5294 
5295 	/* no symlink found, so return error */
5296 	return (DEVFSADM_FAILURE);
5297 }
5298 
5299 /*
5300  * An existing matching ID was not found, so this function is called to
5301  * create the next lowest ID.  In the INTEGER case, return the next
5302  * lowest unused integer.  In the case of LETTER, return the next lowest
5303  * unused letter.  Return empty string if all 26 are used.
5304  * Only IDs >= min will be returned.
5305  */
5306 char *
5307 new_id(numeral_t *numeral, int type, char *min)
5308 {
5309 	int imin;
5310 	temp_t *temp;
5311 	temp_t *ptr;
5312 	temp_t **previous;
5313 	temp_t *head = NULL;
5314 	char *retval;
5315 	static char tempbuff[8];
5316 	numeral_t *np;
5317 
5318 	if (type == LETTER) {
5319 
5320 		char letter[26], i;
5321 
5322 		if (numeral == NULL) {
5323 			return (s_strdup(min));
5324 		}
5325 
5326 		for (i = 0; i < 26; i++) {
5327 			letter[i] = 0;
5328 		}
5329 
5330 		for (np = numeral; np != NULL; np = np->next) {
5331 			letter[*np->id - 'a']++;
5332 		}
5333 
5334 		imin = *min - 'a';
5335 
5336 		for (i = imin; i < 26; i++) {
5337 			if (letter[i] == 0) {
5338 				retval = s_malloc(2);
5339 				retval[0] = 'a' + i;
5340 				retval[1] = '\0';
5341 				return (retval);
5342 			}
5343 		}
5344 
5345 		return (s_strdup(""));
5346 	}
5347 
5348 	if (type == INTEGER) {
5349 
5350 		if (numeral == NULL) {
5351 			return (s_strdup(min));
5352 		}
5353 
5354 		imin = atoi(min);
5355 
5356 		/* sort list */
5357 		for (np = numeral; np != NULL; np = np->next) {
5358 			temp = s_malloc(sizeof (temp_t));
5359 			temp->integer = atoi(np->id);
5360 			temp->next = NULL;
5361 
5362 			previous = &head;
5363 			for (ptr = head; ptr != NULL; ptr = ptr->next) {
5364 				if (temp->integer < ptr->integer) {
5365 					temp->next = ptr;
5366 					*previous = temp;
5367 					break;
5368 				}
5369 				previous = &(ptr->next);
5370 			}
5371 			if (ptr == NULL) {
5372 				*previous = temp;
5373 			}
5374 		}
5375 
5376 		/* now search sorted list for first hole >= imin */
5377 		for (ptr = head; ptr != NULL; ptr = ptr->next) {
5378 			if (imin == ptr->integer) {
5379 				imin++;
5380 			} else {
5381 				if (imin < ptr->integer) {
5382 					break;
5383 				}
5384 			}
5385 
5386 		}
5387 
5388 		/* free temp list */
5389 		for (ptr = head; ptr != NULL; ) {
5390 			temp = ptr;
5391 			ptr = ptr->next;
5392 			free(temp);
5393 		}
5394 
5395 		(void) sprintf(tempbuff, "%d", imin);
5396 		return (s_strdup(tempbuff));
5397 	}
5398 
5399 	return (s_strdup(""));
5400 }
5401 
5402 /*
5403  * Search current_dir for all files which match the first path component
5404  * of path_left, which is an RE.  If a match is found, but there are more
5405  * components of path_left, then recurse, otherwise, if we have reached
5406  * the last component of path_left, call create_cached_numerals for each
5407  * file.   At some point, recurse_dev_re() should be rewritten so that this
5408  * function can be eliminated.
5409  */
5410 static void
5411 enumerate_recurse(char *current_dir, char *path_left, numeral_set_t *setp,
5412 	    devfsadm_enumerate_t rules[], int index)
5413 {
5414 	char *slash;
5415 	char *new_path;
5416 	char *numeral_id;
5417 	struct dirent *entp;
5418 	DIR *dp;
5419 
5420 	if ((dp = opendir(current_dir)) == NULL) {
5421 		return;
5422 	}
5423 
5424 	/* get rid of any extra '/' */
5425 	while (*path_left == '/') {
5426 		path_left++;
5427 	}
5428 
5429 	if (slash = strchr(path_left, '/')) {
5430 		*slash = '\0';
5431 	}
5432 
5433 	while ((entp = readdir(dp)) != NULL) {
5434 
5435 		if (strcmp(entp->d_name, ".") == 0 ||
5436 		    strcmp(entp->d_name, "..") == 0) {
5437 			continue;
5438 		}
5439 
5440 		/*
5441 		 *  Returns true if path_left matches entp->d_name
5442 		 *  If it is the last path component, pass subexp
5443 		 *  so that it will return the corresponding ID in
5444 		 *  numeral_id.
5445 		 */
5446 		numeral_id = NULL;
5447 		if (match_path_component(path_left, entp->d_name, &numeral_id,
5448 				    slash ? 0 : rules[index].subexp)) {
5449 
5450 			new_path = s_malloc(strlen(current_dir) +
5451 					    strlen(entp->d_name) + 2);
5452 
5453 			(void) strcpy(new_path, current_dir);
5454 			(void) strcat(new_path, "/");
5455 			(void) strcat(new_path, entp->d_name);
5456 
5457 			if (slash != NULL) {
5458 				enumerate_recurse(new_path, slash + 1,
5459 				    setp, rules, index);
5460 			} else {
5461 				create_cached_numeral(new_path, setp,
5462 				    numeral_id, rules, index);
5463 				if (numeral_id != NULL) {
5464 					free(numeral_id);
5465 				}
5466 			}
5467 			free(new_path);
5468 		}
5469 	}
5470 
5471 	if (slash != NULL) {
5472 		*slash = '/';
5473 	}
5474 	s_closedir(dp);
5475 }
5476 
5477 
5478 /*
5479  * Returns true if file matches file_re.  If subexp is non-zero, it means
5480  * we are searching the last path component and need to return the
5481  * parenthesized subexpression subexp in id.
5482  *
5483  */
5484 static int
5485 match_path_component(char *file_re,  char *file,  char **id, int subexp)
5486 {
5487 	regex_t re1;
5488 	int match = 0;
5489 	int nelements;
5490 	regmatch_t *pmatch;
5491 
5492 	if (subexp != 0) {
5493 		nelements = subexp + 1;
5494 		pmatch = (regmatch_t *)
5495 			s_malloc(sizeof (regmatch_t) * nelements);
5496 	} else {
5497 		pmatch = NULL;
5498 		nelements = 0;
5499 	}
5500 
5501 	if (regcomp(&re1, file_re, REG_EXTENDED) != 0) {
5502 		if (pmatch != NULL) {
5503 			free(pmatch);
5504 		}
5505 		return (0);
5506 	}
5507 
5508 	if (regexec(&re1, file, nelements, pmatch, 0) == 0) {
5509 		match = 1;
5510 	}
5511 
5512 	if ((match != 0) && (subexp != 0)) {
5513 		int size = pmatch[subexp].rm_eo - pmatch[subexp].rm_so;
5514 		*id = s_malloc(size + 1);
5515 		(void) strncpy(*id, &file[pmatch[subexp].rm_so], size);
5516 		(*id)[size] = '\0';
5517 	}
5518 
5519 	if (pmatch != NULL) {
5520 		free(pmatch);
5521 	}
5522 	regfree(&re1);
5523 	return (match);
5524 }
5525 
5526 /*
5527  * This function is called for every file which matched the leaf
5528  * component of the RE.  If the "numeral_id" is not already on the
5529  * numeral set's numeral list, add it and its physical path.
5530  */
5531 static void
5532 create_cached_numeral(char *path, numeral_set_t *setp, char *numeral_id,
5533 	devfsadm_enumerate_t rules[], int index)
5534 {
5535 	char linkbuf[PATH_MAX + 1];
5536 	char lpath[PATH_MAX + 1];
5537 	char *linkptr, *cmp_str;
5538 	numeral_t *np;
5539 	int linksize;
5540 	struct stat sb;
5541 	const char *fcn = "create_cached_numeral";
5542 
5543 	assert(index >= 0 && index < setp->re_count);
5544 	assert(strcmp(rules[index].re, setp->re[index]) == 0);
5545 
5546 	/*
5547 	 *  We found a numeral_id from an entry in /dev which matched
5548 	 *  the re passed in from devfsadm_enumerate.  We only need to make sure
5549 	 *  ONE copy of numeral_id exists on the numeral list.  We only need
5550 	 *  to store /dev/dsk/cNtod0s0 and no other entries hanging off
5551 	 *  of controller N.
5552 	 */
5553 	for (np = setp->headnumeral; np != NULL; np = np->next) {
5554 		if (strcmp(numeral_id, np->id) == 0) {
5555 			return;
5556 		}
5557 	}
5558 
5559 	/* NOT on list, so add it */
5560 
5561 	(void) strcpy(lpath, path);
5562 	/*
5563 	 * If path is a dir, it is changed to the first symbolic link it find
5564 	 * if it finds one.
5565 	 */
5566 	if (get_stat_info(lpath, &sb) == DEVFSADM_FAILURE) {
5567 		return;
5568 	}
5569 
5570 	/* If we get here, we found a symlink */
5571 	linksize = readlink(lpath, linkbuf, PATH_MAX);
5572 
5573 	if (linksize <= 0) {
5574 		err_print(READLINK_FAILED, fcn, lpath, strerror(errno));
5575 		return;
5576 	}
5577 
5578 	linkbuf[linksize] = '\0';
5579 
5580 	/*
5581 	 * the following just points linkptr to the root of the /devices
5582 	 * node if it is a minor node, otherwise, to the first char of
5583 	 * linkbuf if it is a link.
5584 	 */
5585 	(void) is_minor_node(linkbuf, &linkptr);
5586 
5587 	cmp_str = alloc_cmp_str(linkptr, &rules[index]);
5588 	if (cmp_str == NULL) {
5589 		return;
5590 	}
5591 
5592 	np = s_malloc(sizeof (numeral_t));
5593 
5594 	np->id = s_strdup(numeral_id);
5595 	np->full_path = s_strdup(linkptr);
5596 	np->rule_index = index;
5597 	np->cmp_str = cmp_str;
5598 
5599 	np->next = setp->headnumeral;
5600 	setp->headnumeral = np;
5601 }
5602 
5603 
5604 /*
5605  * This should be called either before or after granting access to a
5606  * command line version of devfsadm running, since it may have changed
5607  * the state of /dev.  It forces future enumerate calls to re-build
5608  * cached information from /dev.
5609  */
5610 void
5611 invalidate_enumerate_cache(void)
5612 {
5613 	numeral_set_t *setp;
5614 	numeral_set_t *savedsetp;
5615 	numeral_t *savednumset;
5616 	numeral_t *numset;
5617 	int i;
5618 
5619 	for (setp = head_numeral_set; setp != NULL; ) {
5620 		/*
5621 		 *  check all regexp's passed in function against
5622 		 *  those in cached set.
5623 		 */
5624 
5625 		savedsetp = setp;
5626 		setp = setp->next;
5627 
5628 		for (i = 0; i < savedsetp->re_count; i++) {
5629 			free(savedsetp->re[i]);
5630 		}
5631 		free(savedsetp->re);
5632 
5633 		for (numset = savedsetp->headnumeral; numset != NULL; ) {
5634 			savednumset = numset;
5635 			numset = numset->next;
5636 			assert(savednumset->rule_index < savedsetp->re_count);
5637 			free(savednumset->id);
5638 			free(savednumset->full_path);
5639 			free(savednumset->cmp_str);
5640 			free(savednumset);
5641 		}
5642 		free(savedsetp);
5643 	}
5644 	head_numeral_set = NULL;
5645 }
5646 
5647 /*
5648  * Copies over links from /dev to <root>/dev and device special files in
5649  * /devices to <root>/devices, preserving the existing file modes.  If
5650  * the link or special file already exists on <root>, skip the copy.  (it
5651  * would exist only if a package hard coded it there, so assume package
5652  * knows best?).  Use /etc/name_to_major and <root>/etc/name_to_major to
5653  * make translations for major numbers on device special files.	No need to
5654  * make a translation on minor_perm since if the file was created in the
5655  * miniroot then it would presumably have the same minor_perm entry in
5656  *  <root>/etc/minor_perm.  To be used only by install.
5657  */
5658 int
5659 devfsadm_copy(void)
5660 {
5661 	char filename[PATH_MAX + 1];
5662 
5663 	/* load the installed root's name_to_major for translations */
5664 	(void) snprintf(filename, sizeof (filename), "%s%s", root_dir,
5665 	    NAME_TO_MAJOR);
5666 	if (load_n2m_table(filename) == DEVFSADM_FAILURE) {
5667 		return (DEVFSADM_FAILURE);
5668 	}
5669 
5670 	/* Copy /dev to target disk. No need to copy /devices with devfs */
5671 	(void) nftw(DEV, devfsadm_copy_file, 20, FTW_PHYS);
5672 
5673 	/* Let install handle copying over path_to_inst */
5674 
5675 	return (DEVFSADM_SUCCESS);
5676 }
5677 
5678 /*
5679  * This function copies links, dirs, and device special files.
5680  * Note that it always returns DEVFSADM_SUCCESS, so that nftw doesn't
5681  * abort.
5682  */
5683 /*ARGSUSED*/
5684 static int
5685 devfsadm_copy_file(const char *file, const struct stat *stat,
5686 		    int flags, struct FTW *ftw)
5687 {
5688 	struct stat sp;
5689 	dev_t newdev;
5690 	char newfile[PATH_MAX + 1];
5691 	char linkcontents[PATH_MAX + 1];
5692 	int bytes;
5693 	const char *fcn = "devfsadm_copy_file";
5694 
5695 	(void) strcpy(newfile, root_dir);
5696 	(void) strcat(newfile, "/");
5697 	(void) strcat(newfile, file);
5698 
5699 	if (lstat(newfile, &sp) == 0) {
5700 		/* newfile already exists, so no need to continue */
5701 		return (DEVFSADM_SUCCESS);
5702 	}
5703 
5704 	if (((stat->st_mode & S_IFMT) == S_IFBLK) ||
5705 	    ((stat->st_mode & S_IFMT) == S_IFCHR)) {
5706 		if (translate_major(stat->st_rdev, &newdev) ==
5707 		    DEVFSADM_FAILURE) {
5708 			return (DEVFSADM_SUCCESS);
5709 		}
5710 		if (mknod(newfile, stat->st_mode, newdev) == -1) {
5711 			err_print(MKNOD_FAILED, newfile, strerror(errno));
5712 			return (DEVFSADM_SUCCESS);
5713 		}
5714 	} else if ((stat->st_mode & S_IFMT) == S_IFDIR) {
5715 		if (mknod(newfile, stat->st_mode, 0) == -1) {
5716 			err_print(MKNOD_FAILED, newfile, strerror(errno));
5717 			return (DEVFSADM_SUCCESS);
5718 		}
5719 	} else if ((stat->st_mode & S_IFMT) == S_IFLNK)  {
5720 		if ((bytes = readlink(file, linkcontents, PATH_MAX)) == -1)  {
5721 			err_print(READLINK_FAILED, fcn, file, strerror(errno));
5722 			return (DEVFSADM_SUCCESS);
5723 		}
5724 		linkcontents[bytes] = '\0';
5725 		if (symlink(linkcontents, newfile) == -1) {
5726 			err_print(SYMLINK_FAILED, newfile, newfile,
5727 					strerror(errno));
5728 			return (DEVFSADM_SUCCESS);
5729 		}
5730 	}
5731 
5732 	(void) lchown(newfile, stat->st_uid, stat->st_gid);
5733 	return (DEVFSADM_SUCCESS);
5734 }
5735 
5736 /*
5737  *  Given a dev_t from the running kernel, return the new_dev_t
5738  *  by translating to the major number found on the installed
5739  *  target's root name_to_major file.
5740  */
5741 static int
5742 translate_major(dev_t old_dev, dev_t *new_dev)
5743 {
5744 	major_t oldmajor;
5745 	major_t newmajor;
5746 	minor_t oldminor;
5747 	minor_t newminor;
5748 	char cdriver[FILENAME_MAX + 1];
5749 	char driver[FILENAME_MAX + 1];
5750 	char *fcn = "translate_major: ";
5751 
5752 	oldmajor = major(old_dev);
5753 	if (modctl(MODGETNAME, driver, sizeof (driver),
5754 			    &oldmajor) != 0) {
5755 		return (DEVFSADM_FAILURE);
5756 	}
5757 
5758 	if (strcmp(driver, "clone") != 0) {
5759 		/* non-clone case */
5760 
5761 		/* look up major number is target's name2major */
5762 		if (get_major_no(driver, &newmajor) == DEVFSADM_FAILURE) {
5763 			return (DEVFSADM_FAILURE);
5764 		}
5765 
5766 		*new_dev = makedev(newmajor, minor(old_dev));
5767 		if (old_dev != *new_dev) {
5768 			vprint(CHATTY_MID, "%sdriver: %s old: %lu,%lu "
5769 				"new: %lu,%lu\n", fcn, driver, major(old_dev),
5770 				minor(old_dev), major(*new_dev),
5771 				minor(*new_dev));
5772 		}
5773 		return (DEVFSADM_SUCCESS);
5774 	} else {
5775 		/*
5776 		 *  The clone is a special case.  Look at its minor
5777 		 *  number since it is the major number of the real driver.
5778 		 */
5779 		if (get_major_no(driver, &newmajor) == DEVFSADM_FAILURE) {
5780 			return (DEVFSADM_FAILURE);
5781 		}
5782 
5783 		oldminor = minor(old_dev);
5784 		if (modctl(MODGETNAME, cdriver, sizeof (cdriver),
5785 					&oldminor) != 0) {
5786 			err_print(MODGETNAME_FAILED, oldminor);
5787 			return (DEVFSADM_FAILURE);
5788 		}
5789 
5790 		if (get_major_no(cdriver, &newminor) == DEVFSADM_FAILURE) {
5791 			return (DEVFSADM_FAILURE);
5792 		}
5793 
5794 		*new_dev = makedev(newmajor, newminor);
5795 		if (old_dev != *new_dev) {
5796 			vprint(CHATTY_MID, "%sdriver: %s old: "
5797 				"%lu,%lu  new: %lu,%lu\n", fcn, driver,
5798 				major(old_dev), minor(old_dev),
5799 				major(*new_dev), minor(*new_dev));
5800 		}
5801 		return (DEVFSADM_SUCCESS);
5802 	}
5803 }
5804 
5805 /*
5806  *
5807  * Find the major number for driver, searching the n2m_list that was
5808  * built in load_n2m_table().
5809  */
5810 static int
5811 get_major_no(char *driver, major_t *major)
5812 {
5813 	n2m_t *ptr;
5814 
5815 	for (ptr = n2m_list; ptr != NULL; ptr = ptr->next) {
5816 		if (strcmp(ptr->driver, driver) == 0) {
5817 			*major = ptr->major;
5818 			return (DEVFSADM_SUCCESS);
5819 		}
5820 	}
5821 	err_print(FIND_MAJOR_FAILED, driver);
5822 	return (DEVFSADM_FAILURE);
5823 }
5824 
5825 /*
5826  * Loads a name_to_major table into memory.  Used only for suninstall's
5827  * private -R option to devfsadm, to translate major numbers from the
5828  * running to the installed target disk.
5829  */
5830 static int
5831 load_n2m_table(char *file)
5832 {
5833 	FILE *fp;
5834 	char line[1024];
5835 	char driver[PATH_MAX + 1];
5836 	major_t major;
5837 	n2m_t *ptr;
5838 	int ln = 0;
5839 
5840 	if ((fp = fopen(file, "r")) == NULL) {
5841 		err_print(FOPEN_FAILED, file, strerror(errno));
5842 		return (DEVFSADM_FAILURE);
5843 	}
5844 
5845 	while (fgets(line, sizeof (line), fp) != NULL) {
5846 		ln++;
5847 		if (line[0] == '#') {
5848 			continue;
5849 		}
5850 		if (sscanf(line, "%1024s%lu", driver, &major) != 2) {
5851 			err_print(IGNORING_LINE_IN, ln, file);
5852 			continue;
5853 		}
5854 		ptr = (n2m_t *)s_malloc(sizeof (n2m_t));
5855 		ptr->major = major;
5856 		ptr->driver = s_strdup(driver);
5857 		ptr->next = n2m_list;
5858 		n2m_list = ptr;
5859 	}
5860 	if (fclose(fp) == EOF) {
5861 		err_print(FCLOSE_FAILED, file, strerror(errno));
5862 	}
5863 	return (DEVFSADM_SUCCESS);
5864 }
5865 
5866 /*
5867  * Called at devfsadm startup to read in the devlink.tab file.	Creates
5868  * a linked list of devlinktab_list structures which will be
5869  * searched for every minor node.
5870  */
5871 static void
5872 read_devlinktab_file(void)
5873 {
5874 	devlinktab_list_t *headp = NULL;
5875 	devlinktab_list_t *entryp;
5876 	devlinktab_list_t **previous;
5877 	devlinktab_list_t *save;
5878 	char line[MAX_DEVLINK_LINE];
5879 	char *selector;
5880 	char *p_link;
5881 	char *s_link;
5882 	FILE *fp;
5883 	int i;
5884 	static struct stat cached_sb;
5885 	struct stat current_sb;
5886 	static int cached = FALSE;
5887 
5888 	if (devlinktab_file == NULL) {
5889 		return;
5890 	}
5891 
5892 	(void) stat(devlinktab_file, &current_sb);
5893 
5894 	/* if already cached, check to see if it is still valid */
5895 	if (cached == TRUE) {
5896 
5897 		if (current_sb.st_mtime == cached_sb.st_mtime) {
5898 			vprint(FILES_MID, "%s cache valid\n", devlinktab_file);
5899 			return;
5900 		}
5901 
5902 		vprint(FILES_MID, "invalidating %s cache\n", devlinktab_file);
5903 
5904 		while (devlinktab_list != NULL) {
5905 			free_link_list(devlinktab_list->p_link);
5906 			free_link_list(devlinktab_list->s_link);
5907 			free_selector_list(devlinktab_list->selector);
5908 			free(devlinktab_list->selector_pattern);
5909 			free(devlinktab_list->p_link_pattern);
5910 			if (devlinktab_list->s_link_pattern != NULL) {
5911 				free(devlinktab_list->s_link_pattern);
5912 			}
5913 			save = devlinktab_list;
5914 			devlinktab_list = devlinktab_list->next;
5915 			free(save);
5916 		}
5917 	} else {
5918 		cached = TRUE;
5919 	}
5920 
5921 	(void) stat(devlinktab_file, &cached_sb);
5922 
5923 	if ((fp = fopen(devlinktab_file, "r")) == NULL) {
5924 		err_print(FOPEN_FAILED, devlinktab_file, strerror(errno));
5925 		return;
5926 	}
5927 
5928 	previous = &headp;
5929 
5930 	while (fgets(line, sizeof (line), fp) != NULL) {
5931 		devlinktab_line++;
5932 		i = strlen(line);
5933 		if (line[i-1] == NEWLINE) {
5934 			line[i-1] = '\0';
5935 		} else if (i == sizeof (line-1)) {
5936 			err_print(LINE_TOO_LONG, devlinktab_line,
5937 			    devlinktab_file, sizeof (line)-1);
5938 			while (((i = getc(fp)) != '\n') && (i != EOF));
5939 			continue;
5940 		}
5941 
5942 		if ((line[0] == '#') || (line[0] == '\0')) {
5943 			/* Ignore comments and blank lines */
5944 			continue;
5945 		}
5946 
5947 		vprint(DEVLINK_MID, "table: %s line %d: '%s'\n",
5948 			devlinktab_file, devlinktab_line, line);
5949 
5950 		/* break each entry into fields.  s_link may be NULL */
5951 		if (split_devlinktab_entry(line, &selector, &p_link,
5952 		    &s_link) == DEVFSADM_FAILURE) {
5953 			vprint(DEVLINK_MID, "split_entry returns failure\n");
5954 			continue;
5955 		} else {
5956 			vprint(DEVLINK_MID, "split_entry selector='%s' "
5957 				"p_link='%s' s_link='%s'\n\n", selector,
5958 				p_link, (s_link == NULL) ? "" : s_link);
5959 		}
5960 
5961 		entryp = (devlinktab_list_t *)
5962 			s_malloc(sizeof (devlinktab_list_t));
5963 
5964 		entryp->line_number = devlinktab_line;
5965 
5966 		if ((entryp->selector =
5967 			create_selector_list(selector)) == NULL) {
5968 			free(entryp);
5969 			continue;
5970 		}
5971 		entryp->selector_pattern = s_strdup(selector);
5972 
5973 		if ((entryp->p_link = create_link_list(p_link)) == NULL) {
5974 			free_selector_list(entryp->selector);
5975 			free(entryp->selector_pattern);
5976 			free(entryp);
5977 			continue;
5978 		}
5979 
5980 		entryp->p_link_pattern = s_strdup(p_link);
5981 
5982 		if (s_link != NULL) {
5983 			if ((entryp->s_link =
5984 			    create_link_list(s_link)) == NULL) {
5985 				free_selector_list(entryp->selector);
5986 				free_link_list(entryp->p_link);
5987 				free(entryp->selector_pattern);
5988 				free(entryp->p_link_pattern);
5989 				free(entryp);
5990 				continue;
5991 			}
5992 			    entryp->s_link_pattern = s_strdup(s_link);
5993 		} else {
5994 			entryp->s_link = NULL;
5995 			entryp->s_link_pattern = NULL;
5996 
5997 		}
5998 
5999 		/* append to end of list */
6000 
6001 		entryp->next = NULL;
6002 		*previous = entryp;
6003 		previous = &(entryp->next);
6004 	}
6005 	if (fclose(fp) == EOF) {
6006 		err_print(FCLOSE_FAILED, devlinktab_file, strerror(errno));
6007 	}
6008 	devlinktab_list = headp;
6009 }
6010 
6011 /*
6012  *
6013  * For a single line entry in devlink.tab, split the line into fields
6014  * selector, p_link, and an optionally s_link.	If s_link field is not
6015  * present, then return NULL in s_link (not NULL string).
6016  */
6017 static int
6018 split_devlinktab_entry(char *entry, char **selector, char **p_link,
6019 			char **s_link)
6020 {
6021 	char *tab;
6022 
6023 	*selector = entry;
6024 
6025 	if ((tab = strchr(entry, TAB)) != NULL) {
6026 		*tab = '\0';
6027 		*p_link = ++tab;
6028 	} else {
6029 		err_print(MISSING_TAB, devlinktab_line, devlinktab_file);
6030 		return (DEVFSADM_FAILURE);
6031 	}
6032 
6033 	if (*p_link == '\0') {
6034 		err_print(MISSING_DEVNAME, devlinktab_line, devlinktab_file);
6035 		return (DEVFSADM_FAILURE);
6036 	}
6037 
6038 	if ((tab = strchr(*p_link, TAB)) != NULL) {
6039 		*tab = '\0';
6040 		*s_link = ++tab;
6041 		if (strchr(*s_link, TAB) != NULL) {
6042 			err_print(TOO_MANY_FIELDS, devlinktab_line,
6043 					devlinktab_file);
6044 			return (DEVFSADM_FAILURE);
6045 		}
6046 	} else {
6047 		*s_link = NULL;
6048 	}
6049 
6050 	return (DEVFSADM_SUCCESS);
6051 }
6052 
6053 /*
6054  * For a given devfs_spec field, for each element in the field, add it to
6055  * a linked list of devfs_spec structures.  Return the linked list in
6056  * devfs_spec_list.
6057  */
6058 static selector_list_t *
6059 create_selector_list(char *selector)
6060 {
6061 	    char *key;
6062 	    char *val;
6063 	    int error = FALSE;
6064 	    selector_list_t *head_selector_list = NULL;
6065 	    selector_list_t *selector_list;
6066 
6067 	    /* parse_devfs_spec splits the next field into keyword & value */
6068 	    while ((*selector != NULL) && (error == FALSE)) {
6069 		    if (parse_selector(&selector, &key,
6070 				&val) == DEVFSADM_FAILURE) {
6071 			    error = TRUE;
6072 			    break;
6073 		    } else {
6074 			    selector_list = (selector_list_t *)
6075 				    s_malloc(sizeof (selector_list_t));
6076 			    if (strcmp(NAME_S, key) == 0) {
6077 				    selector_list->key = NAME;
6078 			    } else if (strcmp(TYPE_S, key) == 0) {
6079 				    selector_list->key = TYPE;
6080 			    } else if (strncmp(ADDR_S, key, ADDR_S_LEN) == 0) {
6081 				    selector_list->key = ADDR;
6082 				    if (key[ADDR_S_LEN] == '\0') {
6083 					    selector_list->arg = 0;
6084 				    } else if (isdigit(key[ADDR_S_LEN]) !=
6085 						FALSE) {
6086 					    selector_list->arg =
6087 							atoi(&key[ADDR_S_LEN]);
6088 				    } else {
6089 					    error = TRUE;
6090 					    free(selector_list);
6091 					    err_print(BADKEYWORD, key,
6092 						devlinktab_line,
6093 						devlinktab_file);
6094 					    break;
6095 				    }
6096 			    } else if (strncmp(MINOR_S, key,
6097 						MINOR_S_LEN) == 0) {
6098 				    selector_list->key = MINOR;
6099 				    if (key[MINOR_S_LEN] == '\0') {
6100 					    selector_list->arg = 0;
6101 				    } else if (isdigit(key[MINOR_S_LEN]) !=
6102 						FALSE) {
6103 					    selector_list->arg =
6104 						atoi(&key[MINOR_S_LEN]);
6105 				    } else {
6106 					    error = TRUE;
6107 					    free(selector_list);
6108 					    err_print(BADKEYWORD, key,
6109 						devlinktab_line,
6110 						devlinktab_file);
6111 					    break;
6112 				    }
6113 				    vprint(DEVLINK_MID, "MINOR = %s\n", val);
6114 			    } else {
6115 				    err_print(UNRECOGNIZED_KEY, key,
6116 					devlinktab_line, devlinktab_file);
6117 				    error = TRUE;
6118 				    free(selector_list);
6119 				    break;
6120 			    }
6121 			    selector_list->val = s_strdup(val);
6122 			    selector_list->next = head_selector_list;
6123 			    head_selector_list = selector_list;
6124 			    vprint(DEVLINK_MID, "key='%s' val='%s' arg=%d\n",
6125 					key, val, selector_list->arg);
6126 		    }
6127 	    }
6128 
6129 	    if ((error == FALSE) && (head_selector_list != NULL)) {
6130 		    return (head_selector_list);
6131 	    } else {
6132 		    /* parse failed.  Free any allocated structs */
6133 		    free_selector_list(head_selector_list);
6134 		    return (NULL);
6135 	    }
6136 }
6137 
6138 /*
6139  * Takes a semicolon separated list of selector elements and breaks up
6140  * into a keyword-value pair.	semicolon and equal characters are
6141  * replaced with NULL's.  On success, selector is updated to point to the
6142  * terminating NULL character terminating the keyword-value pair, and the
6143  * function returns DEVFSADM_SUCCESS.	If there is a syntax error,
6144  * devfs_spec is not modified and function returns DEVFSADM_FAILURE.
6145  */
6146 static int
6147 parse_selector(char **selector, char **key, char **val)
6148 {
6149 	char *equal;
6150 	char *semi_colon;
6151 
6152 	*key = *selector;
6153 
6154 	if ((equal = strchr(*key, '=')) != NULL) {
6155 		*equal = '\0';
6156 	} else {
6157 		err_print(MISSING_EQUAL, devlinktab_line, devlinktab_file);
6158 		return (DEVFSADM_FAILURE);
6159 	}
6160 
6161 	*val = ++equal;
6162 	if ((semi_colon = strchr(equal, ';')) != NULL) {
6163 		*semi_colon = '\0';
6164 		*selector = semi_colon + 1;
6165 	} else {
6166 		*selector = equal + strlen(equal);
6167 	}
6168 	return (DEVFSADM_SUCCESS);
6169 }
6170 
6171 /*
6172  * link is either the second or third field of devlink.tab.  Parse link
6173  * into a linked list of devlink structures and return ptr to list.  Each
6174  * list element is either a constant string, or one of the following
6175  * escape sequences: \M, \A, \N, or \D.  The first three escape sequences
6176  * take a numerical argument.
6177  */
6178 static link_list_t *
6179 create_link_list(char *link)
6180 {
6181 	int x = 0;
6182 	int error = FALSE;
6183 	int counter_found = FALSE;
6184 	link_list_t *head = NULL;
6185 	link_list_t **ptr;
6186 	link_list_t *link_list;
6187 	char constant[MAX_DEVLINK_LINE];
6188 	char *error_str;
6189 
6190 	if (link == NULL) {
6191 		return (NULL);
6192 	}
6193 
6194 	while ((*link != '\0') && (error == FALSE)) {
6195 		link_list = (link_list_t *)s_malloc(sizeof (link_list_t));
6196 		link_list->next = NULL;
6197 
6198 		while ((*link != '\0') && (*link != '\\')) {
6199 			/* a non-escaped string */
6200 			constant[x++] = *(link++);
6201 		}
6202 		if (x != 0) {
6203 			constant[x] = '\0';
6204 			link_list->type = CONSTANT;
6205 			link_list->constant = s_strdup(constant);
6206 			x = 0;
6207 			vprint(DEVLINK_MID, "CONSTANT FOUND %s\n", constant);
6208 		} else {
6209 			switch (*(++link)) {
6210 			case 'M':
6211 				link_list->type = MINOR;
6212 				break;
6213 			case 'A':
6214 				link_list->type = ADDR;
6215 				break;
6216 			case 'N':
6217 				if (counter_found == TRUE) {
6218 					error = TRUE;
6219 					error_str = "multiple counters "
6220 						"not permitted";
6221 					free(link_list);
6222 				} else {
6223 					counter_found = TRUE;
6224 					link_list->type = COUNTER;
6225 				}
6226 				break;
6227 			case 'D':
6228 				link_list->type = NAME;
6229 				break;
6230 			default:
6231 				error = TRUE;
6232 				free(link_list);
6233 				error_str = "unrecognized escape sequence";
6234 				break;
6235 			}
6236 			if (*(link++) != 'D') {
6237 				if (isdigit(*link) == FALSE) {
6238 					error_str = "escape sequence must be "
6239 						"followed by a digit\n";
6240 					error = TRUE;
6241 					free(link_list);
6242 				} else {
6243 					link_list->arg =
6244 						(int)strtoul(link, &link, 10);
6245 					vprint(DEVLINK_MID, "link_list->arg = "
6246 						"%d\n", link_list->arg);
6247 				}
6248 			}
6249 		}
6250 		/* append link_list struct to end of list */
6251 		if (error == FALSE) {
6252 			for (ptr = &head; *ptr != NULL; ptr = &((*ptr)->next));
6253 			*ptr = link_list;
6254 		}
6255 	}
6256 
6257 	if (error == FALSE) {
6258 		return (head);
6259 	} else {
6260 		err_print(CONFIG_INCORRECT, devlinktab_line, devlinktab_file,
6261 		    error_str);
6262 		free_link_list(head);
6263 		return (NULL);
6264 	}
6265 }
6266 
6267 /*
6268  * Called for each minor node devfsadm processes; for each minor node,
6269  * look for matches in the devlinktab_list list which was created on
6270  * startup read_devlinktab_file().  If there is a match, call build_links()
6271  * to build a logical devlink and a possible extra devlink.
6272  */
6273 static int
6274 process_devlink_compat(di_minor_t minor, di_node_t node)
6275 {
6276 	int link_built = FALSE;
6277 	devlinktab_list_t *entry;
6278 	char *nodetype;
6279 	char *dev_path;
6280 
6281 	if (devlinks_debug == TRUE) {
6282 		nodetype =  di_minor_nodetype(minor);
6283 		assert(nodetype != NULL);
6284 		if ((dev_path = di_devfs_path(node)) != NULL) {
6285 			vprint(INFO_MID, "'%s' entry: %s:%s\n", nodetype,
6286 				dev_path,
6287 				di_minor_name(minor) ? di_minor_name(minor) :
6288 				"");
6289 			di_devfs_path_free(dev_path);
6290 		}
6291 
6292 	}
6293 
6294 
6295 	/* don't process devlink.tab if devfsadm invoked with -c <class> */
6296 	if (num_classes > 0) {
6297 		return (FALSE);
6298 	}
6299 
6300 	for (entry = devlinktab_list; entry != NULL; entry = entry->next) {
6301 		if (devlink_matches(entry, minor, node) == DEVFSADM_SUCCESS) {
6302 			link_built = TRUE;
6303 			(void) build_links(entry, minor, node);
6304 		}
6305 	}
6306 	return (link_built);
6307 }
6308 
6309 /*
6310  * For a given devlink.tab devlinktab_list entry, see if the selector
6311  * field matches this minor node.  If it does, return DEVFSADM_SUCCESS,
6312  * otherwise DEVFSADM_FAILURE.
6313  */
6314 static int
6315 devlink_matches(devlinktab_list_t *entry, di_minor_t minor, di_node_t node)
6316 {
6317 	selector_list_t *selector = entry->selector;
6318 	char *addr;
6319 	char *minor_name;
6320 	char *node_type;
6321 
6322 	for (; selector != NULL; selector = selector->next) {
6323 		switch (selector->key) {
6324 		case NAME:
6325 			if (strcmp(di_node_name(node), selector->val) != 0) {
6326 				return (DEVFSADM_FAILURE);
6327 			}
6328 			break;
6329 		case TYPE:
6330 			node_type = di_minor_nodetype(minor);
6331 			assert(node_type != NULL);
6332 			if (strcmp(node_type, selector->val) != 0) {
6333 				return (DEVFSADM_FAILURE);
6334 			}
6335 			break;
6336 		case ADDR:
6337 			if ((addr = di_bus_addr(node)) == NULL) {
6338 				return (DEVFSADM_FAILURE);
6339 			}
6340 			if (selector->arg == 0) {
6341 				if (strcmp(addr, selector->val) != 0) {
6342 					return (DEVFSADM_FAILURE);
6343 				}
6344 			} else {
6345 				if (compare_field(addr, selector->val,
6346 				    selector->arg) == DEVFSADM_FAILURE) {
6347 					return (DEVFSADM_FAILURE);
6348 				}
6349 			}
6350 			break;
6351 		case MINOR:
6352 			if ((minor_name = di_minor_name(minor)) == NULL) {
6353 				return (DEVFSADM_FAILURE);
6354 			}
6355 			if (selector->arg == 0) {
6356 				if (strcmp(minor_name, selector->val) != 0) {
6357 					return (DEVFSADM_FAILURE);
6358 				}
6359 			} else {
6360 				if (compare_field(minor_name, selector->val,
6361 					selector->arg) == DEVFSADM_FAILURE) {
6362 					return (DEVFSADM_FAILURE);
6363 				}
6364 			}
6365 			break;
6366 		default:
6367 			return (DEVFSADM_FAILURE);
6368 		}
6369 	}
6370 
6371 	return (DEVFSADM_SUCCESS);
6372 }
6373 
6374 /*
6375  * For the given minor node and devlinktab_list entry from devlink.tab,
6376  * build a logical dev link and a possible extra devlink.
6377  * Return DEVFSADM_SUCCESS if link is created, otherwise DEVFSADM_FAILURE.
6378  */
6379 static int
6380 build_links(devlinktab_list_t *entry, di_minor_t minor, di_node_t node)
6381 {
6382 	char secondary_link[PATH_MAX + 1];
6383 	char primary_link[PATH_MAX + 1];
6384 	char contents[PATH_MAX + 1];
6385 	char *dev_path;
6386 
6387 	if ((dev_path = di_devfs_path(node)) == NULL) {
6388 		err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
6389 		devfsadm_exit(1);
6390 	}
6391 	(void) strcpy(contents, dev_path);
6392 	di_devfs_path_free(dev_path);
6393 
6394 	(void) strcat(contents, ":");
6395 	(void) strcat(contents, di_minor_name(minor));
6396 
6397 	if (construct_devlink(primary_link, entry->p_link, contents,
6398 				minor, node,
6399 			    entry->p_link_pattern) == DEVFSADM_FAILURE) {
6400 		return (DEVFSADM_FAILURE);
6401 	}
6402 	(void) devfsadm_mklink(primary_link, node, minor, 0);
6403 
6404 	if (entry->s_link == NULL) {
6405 		return (DEVFSADM_SUCCESS);
6406 	}
6407 
6408 	if (construct_devlink(secondary_link, entry->s_link,
6409 			primary_link, minor, node,
6410 				entry->s_link_pattern) == DEVFSADM_FAILURE) {
6411 		return (DEVFSADM_FAILURE);
6412 	}
6413 
6414 	(void) devfsadm_secondary_link(secondary_link, primary_link, 0);
6415 
6416 	return (DEVFSADM_SUCCESS);
6417 }
6418 
6419 /*
6420  * The counter rule for devlink.tab entries is implemented via
6421  * devfsadm_enumerate_int_start(). One of the arguments to this function
6422  * is a path, where each path component is treated as a regular expression.
6423  * For devlink.tab entries, this path regular expression is derived from
6424  * the devlink spec. get_anchored_re() accepts path regular expressions derived
6425  * from devlink.tab entries and inserts the anchors '^' and '$' at the beginning
6426  * and end respectively of each path component. This is done to prevent
6427  * false matches. For example, without anchors, "a/([0-9]+)" will match "ab/c9"
6428  * and incorrect links will be generated.
6429  */
6430 static int
6431 get_anchored_re(char *link, char *anchored_re, char *pattern)
6432 {
6433 	if (*link == '/' || *link == '\0') {
6434 		err_print(INVALID_DEVLINK_SPEC, pattern);
6435 		return (DEVFSADM_FAILURE);
6436 	}
6437 
6438 	*anchored_re++ = '^';
6439 	for (; *link != '\0'; ) {
6440 		if (*link == '/') {
6441 			while (*link == '/')
6442 				link++;
6443 			*anchored_re++ = '$';
6444 			*anchored_re++ = '/';
6445 			if (*link != '\0') {
6446 				*anchored_re++ = '^';
6447 			}
6448 		} else {
6449 			*anchored_re++ = *link++;
6450 			if (*link == '\0') {
6451 				*anchored_re++ = '$';
6452 			}
6453 		}
6454 	}
6455 	*anchored_re = '\0';
6456 
6457 	return (DEVFSADM_SUCCESS);
6458 }
6459 
6460 static int
6461 construct_devlink(char *link, link_list_t *link_build, char *contents,
6462 			di_minor_t minor, di_node_t node, char *pattern)
6463 {
6464 	int counter_offset = -1;
6465 	devfsadm_enumerate_t rules[1] = {NULL};
6466 	char templink[PATH_MAX + 1];
6467 	char *buff;
6468 	char start[10];
6469 	char *node_path;
6470 	char anchored_re[PATH_MAX + 1];
6471 
6472 	link[0] = '\0';
6473 
6474 	for (; link_build != NULL; link_build = link_build->next) {
6475 		switch (link_build->type) {
6476 		case NAME:
6477 			(void) strcat(link, di_node_name(node));
6478 			break;
6479 		case CONSTANT:
6480 			(void) strcat(link, link_build->constant);
6481 			break;
6482 		case ADDR:
6483 			if (component_cat(link, di_bus_addr(node),
6484 				    link_build->arg) == DEVFSADM_FAILURE) {
6485 				node_path = di_devfs_path(node);
6486 				err_print(CANNOT_BE_USED, pattern, node_path,
6487 					    di_minor_name(minor));
6488 				di_devfs_path_free(node_path);
6489 				return (DEVFSADM_FAILURE);
6490 			}
6491 			break;
6492 		case MINOR:
6493 			if (component_cat(link, di_minor_name(minor),
6494 				    link_build->arg) == DEVFSADM_FAILURE) {
6495 				node_path = di_devfs_path(node);
6496 				err_print(CANNOT_BE_USED, pattern, node_path,
6497 					    di_minor_name(minor));
6498 				di_devfs_path_free(node_path);
6499 				return (DEVFSADM_FAILURE);
6500 			}
6501 			break;
6502 		case COUNTER:
6503 			counter_offset = strlen(link);
6504 			(void) strcat(link, "([0-9]+)");
6505 			(void) sprintf(start, "%d", link_build->arg);
6506 			break;
6507 		default:
6508 			return (DEVFSADM_FAILURE);
6509 		}
6510 	}
6511 
6512 	if (counter_offset != -1) {
6513 		/*
6514 		 * copy anything appended after "([0-9]+)" into
6515 		 * templink
6516 		 */
6517 
6518 		(void) strcpy(templink,
6519 			    &link[counter_offset + strlen("([0-9]+)")]);
6520 		if (get_anchored_re(link, anchored_re, pattern)
6521 		    != DEVFSADM_SUCCESS) {
6522 			return (DEVFSADM_FAILURE);
6523 		}
6524 		rules[0].re = anchored_re;
6525 		rules[0].subexp = 1;
6526 		rules[0].flags = MATCH_ALL;
6527 		if (devfsadm_enumerate_int_start(contents, 0, &buff,
6528 		    rules, 1, start) == DEVFSADM_FAILURE) {
6529 			return (DEVFSADM_FAILURE);
6530 		}
6531 		(void) strcpy(&link[counter_offset], buff);
6532 		free(buff);
6533 		(void) strcat(link, templink);
6534 		vprint(DEVLINK_MID, "COUNTER is	%s\n", link);
6535 	}
6536 	return (DEVFSADM_SUCCESS);
6537 }
6538 
6539 /*
6540  * Compares "field" number of the comma separated list "full_name" with
6541  * field_item.	Returns DEVFSADM_SUCCESS for match,
6542  * DEVFSADM_FAILURE for no match.
6543  */
6544 static int
6545 compare_field(char *full_name, char *field_item, int field)
6546 {
6547 	--field;
6548 	while ((*full_name != '\0') && (field != 0)) {
6549 		if (*(full_name++) == ',') {
6550 			field--;
6551 		}
6552 	}
6553 
6554 	if (field != 0) {
6555 		return (DEVFSADM_FAILURE);
6556 	}
6557 
6558 	while ((*full_name != '\0') && (*field_item != '\0') &&
6559 			(*full_name != ',')) {
6560 		if (*(full_name++) != *(field_item++)) {
6561 			return (DEVFSADM_FAILURE);
6562 		}
6563 	}
6564 
6565 	if (*field_item != '\0') {
6566 		return (DEVFSADM_FAILURE);
6567 	}
6568 
6569 	if ((*full_name == '\0') || (*full_name == ','))
6570 		return (DEVFSADM_SUCCESS);
6571 
6572 	return (DEVFSADM_FAILURE);
6573 }
6574 
6575 /*
6576  * strcat() field # "field" of comma separated list "name" to "link".
6577  * Field 0 is the entire name.
6578  * Return DEVFSADM_SUCCESS or DEVFSADM_FAILURE.
6579  */
6580 static int
6581 component_cat(char *link, char *name, int field)
6582 {
6583 
6584 	if (name == NULL) {
6585 		return (DEVFSADM_FAILURE);
6586 	}
6587 
6588 	if (field == 0) {
6589 		(void) strcat(link, name);
6590 		return (DEVFSADM_SUCCESS);
6591 	}
6592 
6593 	while (*link != '\0') {
6594 		link++;
6595 	}
6596 
6597 	--field;
6598 	while ((*name != '\0') && (field != 0)) {
6599 		if (*(name++) == ',') {
6600 			--field;
6601 		}
6602 	}
6603 
6604 	if (field != 0) {
6605 		return (DEVFSADM_FAILURE);
6606 	}
6607 
6608 	while ((*name != '\0') && (*name != ',')) {
6609 		*(link++) = *(name++);
6610 	}
6611 
6612 	*link = '\0';
6613 	return (DEVFSADM_SUCCESS);
6614 }
6615 
6616 static void
6617 free_selector_list(selector_list_t *head)
6618 {
6619 	selector_list_t *temp;
6620 
6621 	while (head != NULL) {
6622 		temp = head;
6623 		head = head->next;
6624 		free(temp->val);
6625 		free(temp);
6626 	}
6627 }
6628 
6629 static void
6630 free_link_list(link_list_t *head)
6631 {
6632 	link_list_t *temp;
6633 
6634 	while (head != NULL) {
6635 		temp = head;
6636 		head = head->next;
6637 		if (temp->type == CONSTANT) {
6638 			free(temp->constant);
6639 		}
6640 		free(temp);
6641 	}
6642 }
6643 
6644 /*
6645  * Prints only if level matches one of the debug levels
6646  * given on command line.  INFO_MID is always printed.
6647  *
6648  * See devfsadm.h for a listing of globally defined levels and
6649  * meanings.  Modules should prefix the level with their
6650  * module name to prevent collisions.
6651  */
6652 /*PRINTFLIKE2*/
6653 void
6654 devfsadm_print(char *msgid, char *message, ...)
6655 {
6656 	va_list ap;
6657 	static int newline = TRUE;
6658 	int x;
6659 
6660 	if (msgid != NULL) {
6661 		for (x = 0; x < num_verbose; x++) {
6662 			if (strcmp(verbose[x], msgid) == 0) {
6663 				break;
6664 			}
6665 			if (strcmp(verbose[x], ALL_MID) == 0) {
6666 				break;
6667 			}
6668 		}
6669 		if (x == num_verbose) {
6670 			return;
6671 		}
6672 	}
6673 
6674 	va_start(ap, message);
6675 
6676 	if (msgid == NULL) {
6677 		if (logflag == TRUE) {
6678 			(void) vsyslog(LOG_NOTICE, message, ap);
6679 		} else {
6680 			(void) vfprintf(stdout, message, ap);
6681 		}
6682 
6683 	} else {
6684 		if (logflag == TRUE) {
6685 			(void) syslog(LOG_DEBUG, "%s[%ld]: %s: ",
6686 				    prog, getpid(), msgid);
6687 			(void) vsyslog(LOG_DEBUG, message, ap);
6688 		} else {
6689 			if (newline == TRUE) {
6690 				(void) fprintf(stdout, "%s[%ld]: %s: ",
6691 					prog, getpid(), msgid);
6692 			}
6693 			(void) vfprintf(stdout, message, ap);
6694 		}
6695 	}
6696 
6697 	if (message[strlen(message) - 1] == '\n') {
6698 		newline = TRUE;
6699 	} else {
6700 		newline = FALSE;
6701 	}
6702 	va_end(ap);
6703 }
6704 
6705 /*
6706  * print error messages to the terminal or to syslog
6707  */
6708 /*PRINTFLIKE1*/
6709 void
6710 devfsadm_errprint(char *message, ...)
6711 {
6712 	va_list ap;
6713 
6714 	va_start(ap, message);
6715 
6716 	if (logflag == TRUE) {
6717 		(void) vsyslog(LOG_ERR, message, ap);
6718 	} else {
6719 		(void) fprintf(stderr, "%s: ", prog);
6720 		(void) vfprintf(stderr, message, ap);
6721 	}
6722 	va_end(ap);
6723 }
6724 
6725 /*
6726  * return noupdate state (-s)
6727  */
6728 int
6729 devfsadm_noupdate(void)
6730 {
6731 	return (file_mods == TRUE ? DEVFSADM_TRUE : DEVFSADM_FALSE);
6732 }
6733 
6734 /*
6735  * return current root update path (-r)
6736  */
6737 const char *
6738 devfsadm_root_path(void)
6739 {
6740 	if (root_dir[0] == '\0') {
6741 		return ("/");
6742 	} else {
6743 		return ((const char *)root_dir);
6744 	}
6745 }
6746 
6747 /* common exit function which ensures releasing locks */
6748 static void
6749 devfsadm_exit(int status)
6750 {
6751 	if (DEVFSADM_DEBUG_ON) {
6752 		vprint(INFO_MID, "exit status = %d\n", status);
6753 	}
6754 
6755 	if (rcm_hdl) {
6756 		if (thr_self() != process_rcm_events_tid) {
6757 			(void) mutex_lock(&rcm_eventq_lock);
6758 			need_to_exit_rcm_event_thread = 1;
6759 			(void) cond_broadcast(&rcm_eventq_cv);
6760 			(void) mutex_unlock(&rcm_eventq_lock);
6761 
6762 			/* wait until process_rcm_events() thread exits */
6763 			(void) thr_join(process_rcm_events_tid, NULL, NULL);
6764 		}
6765 		librcm_free_handle(rcm_hdl);
6766 		(void) dlclose(librcm_hdl);
6767 	}
6768 
6769 	zlist_deleteall_unlocked();		/* dispose of all zones */
6770 
6771 	exit_dev_lock();
6772 	exit_daemon_lock();
6773 
6774 	if (logflag == TRUE) {
6775 		closelog();
6776 	}
6777 
6778 	exit(status);
6779 }
6780 
6781 /*
6782  * set root_dir, devices_dir, dev_dir using optarg.  zone_mode determines
6783  * whether we're operating on behalf of a zone; in this case, we need to
6784  * reference some things from the global zone.  Note that zone mode and
6785  * -R don't get along, but that should be OK since zone mode is not
6786  * a public interface.
6787  */
6788 static void
6789 set_root_devices_dev_dir(char *dir, int zone_mode)
6790 {
6791 	size_t len;
6792 
6793 	root_dir = s_strdup(dir);
6794 	len = strlen(dir) + strlen(DEVICES) + 1;
6795 	devices_dir = s_malloc(len);
6796 	(void) snprintf(devices_dir, len, "%s%s", root_dir, DEVICES);
6797 	len = strlen(root_dir) + strlen(DEV) + 1;
6798 	dev_dir = s_malloc(len);
6799 	(void) snprintf(dev_dir, len, "%s%s", root_dir, DEV);
6800 	if (zone_mode) {
6801 		len = strlen(DEV) + 1;
6802 		global_dev_dir = s_malloc(len);
6803 		(void) snprintf(global_dev_dir, len, "%s", DEV);
6804 	} else {
6805 		global_dev_dir = s_malloc(len);
6806 		(void) snprintf(global_dev_dir, len, "%s%s", root_dir, DEV);
6807 	}
6808 }
6809 
6810 /*
6811  * Removes quotes.
6812  */
6813 static char *
6814 dequote(char *src)
6815 {
6816 	char	*dst;
6817 	int	len;
6818 
6819 	len = strlen(src);
6820 	dst = s_malloc(len + 1);
6821 	if (src[0] == '\"' && src[len - 1] == '\"') {
6822 		len -= 2;
6823 		(void) strncpy(dst, &src[1], len);
6824 		dst[len] = '\0';
6825 	} else {
6826 		(void) strcpy(dst, src);
6827 	}
6828 	return (dst);
6829 }
6830 
6831 /*
6832  * For a given physical device pathname and spectype, return the
6833  * ownership and permissions attributes by looking in data from
6834  * /etc/minor_perm.  If currently in installation mode, check for
6835  * possible major number translations from the miniroot to the installed
6836  * root's name_to_major table. Note that there can be multiple matches,
6837  * but the last match takes effect.  pts seems to rely on this
6838  * implementation behavior.
6839  */
6840 static void
6841 getattr(char *phy_path, char *aminor, int spectype, dev_t dev, mode_t *mode,
6842 	uid_t *uid, gid_t *gid)
6843 {
6844 	char devname[PATH_MAX + 1];
6845 	char *node_name;
6846 	char *minor_name;
6847 	int match = FALSE;
6848 	int is_clone;
6849 	int mp_drvname_matches_node_name;
6850 	int mp_drvname_matches_minor_name;
6851 	int mp_drvname_is_clone;
6852 	int mp_drvname_matches_drvname;
6853 	struct mperm *mp;
6854 	major_t major_no;
6855 	char driver[PATH_MAX + 1];
6856 
6857 	/*
6858 	 * Get the driver name based on the major number since the name
6859 	 * in /devices may be generic.  Could be running with more major
6860 	 * numbers than are in /etc/name_to_major, so get it from the kernel
6861 	 */
6862 	major_no = major(dev);
6863 
6864 	if (modctl(MODGETNAME, driver, sizeof (driver), &major_no) != 0) {
6865 		/* return default values */
6866 		goto use_defaults;
6867 	}
6868 
6869 	(void) strcpy(devname, phy_path);
6870 
6871 	node_name = strrchr(devname, '/'); /* node name is the last */
6872 					/* component */
6873 	if (node_name == NULL) {
6874 		err_print(NO_NODE, devname);
6875 		goto use_defaults;
6876 	}
6877 
6878 	minor_name = strchr(++node_name, '@'); /* see if it has address part */
6879 
6880 	if (minor_name != NULL) {
6881 		*minor_name++ = '\0';
6882 	} else {
6883 		minor_name = node_name;
6884 	}
6885 
6886 	minor_name = strchr(minor_name, ':'); /* look for minor name */
6887 
6888 	if (minor_name == NULL) {
6889 		err_print(NO_MINOR, devname);
6890 		goto use_defaults;
6891 	}
6892 	*minor_name++ = '\0';
6893 
6894 	/*
6895 	 * mp->mp_drvname = device name from minor_perm
6896 	 * mp->mp_minorname = minor part of device name from
6897 	 * minor_perm
6898 	 * drvname = name of driver for this device
6899 	 */
6900 
6901 	is_clone = (strcmp(node_name, "clone") == 0 ? TRUE : FALSE);
6902 	for (mp = minor_perms; mp != NULL; mp = mp->mp_next) {
6903 		mp_drvname_matches_node_name =
6904 			(strcmp(mp->mp_drvname, node_name) == 0 ? TRUE : FALSE);
6905 		mp_drvname_matches_minor_name =
6906 			(strcmp(mp->mp_drvname, minor_name) == 0  ? TRUE:FALSE);
6907 		mp_drvname_is_clone =
6908 			(strcmp(mp->mp_drvname, "clone") == 0  ? TRUE : FALSE);
6909 		mp_drvname_matches_drvname =
6910 			(strcmp(mp->mp_drvname, driver) == 0  ? TRUE : FALSE);
6911 
6912 		/*
6913 		 * If one of the following cases is true, then we try to change
6914 		 * the permissions if a "shell global pattern match" of
6915 		 * mp_>mp_minorname matches minor_name.
6916 		 *
6917 		 * 1.  mp->mp_drvname matches driver.
6918 		 *
6919 		 * OR
6920 		 *
6921 		 * 2.  mp->mp_drvname matches node_name and this
6922 		 *	name is an alias of the driver name
6923 		 *
6924 		 * OR
6925 		 *
6926 		 * 3.  /devices entry is the clone device and either
6927 		 *	minor_perm entry is the clone device or matches
6928 		 *	the minor part of the clone device.
6929 		 */
6930 
6931 		if ((mp_drvname_matches_drvname == TRUE)||
6932 		    ((mp_drvname_matches_node_name == TRUE) &&
6933 		    (alias(driver, node_name) == TRUE)) ||
6934 		    ((is_clone == TRUE) &&
6935 		    ((mp_drvname_is_clone == TRUE) ||
6936 		    (mp_drvname_matches_minor_name == TRUE)))) {
6937 			/*
6938 			 * Check that the minor part of the
6939 			 * device name from the minor_perm
6940 			 * entry matches and if so, set the
6941 			 * permissions.
6942 			 *
6943 			 * Under real devfs, clone minor name is changed
6944 			 * to match the driver name, but minor_perm may
6945 			 * not match. We reconcile it here.
6946 			 */
6947 			if (aminor != NULL)
6948 				minor_name = aminor;
6949 
6950 			if (gmatch(minor_name, mp->mp_minorname) != 0) {
6951 				*uid = mp->mp_uid;
6952 				*gid = mp->mp_gid;
6953 				*mode = spectype | mp->mp_mode;
6954 				match = TRUE;
6955 			}
6956 		}
6957 	}
6958 
6959 	if (match == TRUE) {
6960 		return;
6961 	}
6962 
6963 	use_defaults:
6964 	/* not found in minor_perm, so just use default values */
6965 	*uid = root_uid;
6966 	*gid = sys_gid;
6967 	*mode = (spectype | 0600);
6968 }
6969 
6970 /*
6971  * Called by devfs_read_minor_perm() to report errors
6972  * key is:
6973  *	line number: ignoring line number error
6974  *	errno: open/close errors
6975  *	size: alloc errors
6976  */
6977 static void
6978 minorperm_err_cb(minorperm_err_t mp_err, int key)
6979 {
6980 	switch (mp_err) {
6981 	case MP_FOPEN_ERR:
6982 		err_print(FOPEN_FAILED, MINOR_PERM_FILE, strerror(key));
6983 		break;
6984 	case MP_FCLOSE_ERR:
6985 		err_print(FCLOSE_FAILED, MINOR_PERM_FILE, strerror(key));
6986 		break;
6987 	case MP_IGNORING_LINE_ERR:
6988 		err_print(IGNORING_LINE_IN, key, MINOR_PERM_FILE);
6989 		break;
6990 	case MP_ALLOC_ERR:
6991 		err_print(MALLOC_FAILED, key);
6992 		break;
6993 	case MP_NVLIST_ERR:
6994 		err_print(NVLIST_ERROR, MINOR_PERM_FILE, strerror(key));
6995 		break;
6996 	case MP_CANT_FIND_USER_ERR:
6997 		err_print(CANT_FIND_USER, DEFAULT_DEV_USER);
6998 		break;
6999 	case MP_CANT_FIND_GROUP_ERR:
7000 		err_print(CANT_FIND_GROUP, DEFAULT_DEV_GROUP);
7001 		break;
7002 	}
7003 }
7004 
7005 static void
7006 read_minor_perm_file(void)
7007 {
7008 	static int cached = FALSE;
7009 	static struct stat cached_sb;
7010 	struct stat current_sb;
7011 
7012 	(void) stat(MINOR_PERM_FILE, &current_sb);
7013 
7014 	/* If already cached, check to see if it is still valid */
7015 	if (cached == TRUE) {
7016 
7017 		if (current_sb.st_mtime == cached_sb.st_mtime) {
7018 			vprint(FILES_MID, "%s cache valid\n", MINOR_PERM_FILE);
7019 			return;
7020 		}
7021 		devfs_free_minor_perm(minor_perms);
7022 		minor_perms = NULL;
7023 	} else {
7024 		cached = TRUE;
7025 	}
7026 
7027 	(void) stat(MINOR_PERM_FILE, &cached_sb);
7028 
7029 	vprint(FILES_MID, "loading binding file: %s\n", MINOR_PERM_FILE);
7030 
7031 	minor_perms = devfs_read_minor_perm(minorperm_err_cb);
7032 }
7033 
7034 static void
7035 load_minor_perm_file(void)
7036 {
7037 	read_minor_perm_file();
7038 	if (devfs_load_minor_perm(minor_perms, minorperm_err_cb) != 0)
7039 		err_print(gettext("minor_perm load failed\n"));
7040 }
7041 
7042 static char *
7043 convert_to_re(char *dev)
7044 {
7045 	char *p, *l, *out;
7046 	int i;
7047 
7048 	out = s_malloc(PATH_MAX);
7049 
7050 	for (l = p = dev, i = 0; (*p != '\0') && (i < (PATH_MAX - 1));
7051 	    ++p, i++) {
7052 		if ((*p == '*') && ((l != p) && (*l == '/'))) {
7053 			out[i++] = '.';
7054 			out[i] = '+';
7055 		} else {
7056 			out[i] = *p;
7057 		}
7058 		l = p;
7059 	}
7060 	out[i] = '\0';
7061 	p = (char *)s_malloc(strlen(out) + 1);
7062 	(void) strlcpy(p, out, strlen(out) + 1);
7063 	free(out);
7064 
7065 	vprint(FILES_MID, "converted %s -> %s\n", dev, p);
7066 
7067 	return (p);
7068 }
7069 
7070 static void
7071 read_logindevperm_file(void)
7072 {
7073 	static int cached = FALSE;
7074 	static struct stat cached_sb;
7075 	struct stat current_sb;
7076 	struct login_dev *ldev;
7077 	FILE *fp;
7078 	char line[MAX_LDEV_LINE];
7079 	int ln, perm, rv;
7080 	char *cp, *console, *devlist, *dev;
7081 	char *lasts, *devlasts, *permstr, *drv;
7082 	struct driver_list *list, *next;
7083 
7084 	/* Read logindevperm only when enabled */
7085 	if (login_dev_enable != TRUE)
7086 		return;
7087 
7088 	if (cached == TRUE) {
7089 		if (stat(LDEV_FILE, &current_sb) == 0 &&
7090 		    current_sb.st_mtime == cached_sb.st_mtime) {
7091 			vprint(FILES_MID, "%s cache valid\n", LDEV_FILE);
7092 			return;
7093 		}
7094 		vprint(FILES_MID, "invalidating %s cache\n", LDEV_FILE);
7095 		while (login_dev_cache != NULL) {
7096 
7097 			ldev = login_dev_cache;
7098 			login_dev_cache = ldev->ldev_next;
7099 			free(ldev->ldev_console);
7100 			free(ldev->ldev_device);
7101 			regfree(&ldev->ldev_device_regex);
7102 			list = ldev->ldev_driver_list;
7103 			while (list) {
7104 				next = list->next;
7105 				free(list);
7106 				list = next;
7107 			}
7108 			free(ldev);
7109 		}
7110 	} else {
7111 		cached = TRUE;
7112 	}
7113 
7114 	assert(login_dev_cache == NULL);
7115 
7116 	if (stat(LDEV_FILE, &cached_sb) != 0) {
7117 		cached = FALSE;
7118 		return;
7119 	}
7120 
7121 	vprint(FILES_MID, "loading file: %s\n", LDEV_FILE);
7122 
7123 	if ((fp = fopen(LDEV_FILE, "r")) == NULL) {
7124 		/* Not fatal to devfsadm */
7125 		cached = FALSE;
7126 		err_print(FOPEN_FAILED, LDEV_FILE, strerror(errno));
7127 		return;
7128 	}
7129 
7130 	ln = 0;
7131 	while (fgets(line, MAX_LDEV_LINE, fp) != NULL) {
7132 		ln++;
7133 
7134 		/* Remove comments */
7135 		if ((cp = strchr(line, '#')) != NULL)
7136 			*cp = '\0';
7137 
7138 		if ((console = strtok_r(line, LDEV_DELIMS, &lasts)) == NULL)
7139 			continue;	/* Blank line */
7140 
7141 		if ((permstr =  strtok_r(NULL, LDEV_DELIMS, &lasts)) == NULL) {
7142 			err_print(IGNORING_LINE_IN, ln, LDEV_FILE);
7143 			continue;	/* Malformed line */
7144 		}
7145 
7146 		/*
7147 		 * permstr is string in octal format. Convert to int
7148 		 */
7149 		cp = NULL;
7150 		errno = 0;
7151 		perm = strtol(permstr, &cp, 8);
7152 		if (errno || perm < 0 || perm > 0777 || *cp != '\0') {
7153 			err_print(IGNORING_LINE_IN, ln, LDEV_FILE);
7154 			continue;
7155 		}
7156 
7157 		if ((devlist = strtok_r(NULL, LDEV_DELIMS, &lasts)) == NULL) {
7158 			err_print(IGNORING_LINE_IN, ln, LDEV_FILE);
7159 			continue;
7160 		}
7161 
7162 		dev = strtok_r(devlist, LDEV_DEV_DELIM, &devlasts);
7163 		while (dev) {
7164 
7165 			ldev = (struct login_dev *)s_zalloc(
7166 			    sizeof (struct login_dev));
7167 			ldev->ldev_console = s_strdup(console);
7168 			ldev->ldev_perms = perm;
7169 
7170 			/*
7171 			 * the logical device name may contain '*' which
7172 			 * we convert to a regular expression
7173 			 */
7174 			ldev->ldev_device = convert_to_re(dev);
7175 			if (ldev->ldev_device &&
7176 			    (rv = regcomp(&ldev->ldev_device_regex,
7177 			    ldev->ldev_device, REG_EXTENDED))) {
7178 				bzero(&ldev->ldev_device_regex,
7179 				    sizeof (ldev->ldev_device_regex));
7180 				err_print(REGCOMP_FAILED,
7181 				    ldev->ldev_device, rv);
7182 			}
7183 			ldev->ldev_next = login_dev_cache;
7184 			login_dev_cache = ldev;
7185 			dev = strtok_r(NULL, LDEV_DEV_DELIM, &devlasts);
7186 		}
7187 
7188 		drv = strtok_r(NULL, LDEV_DRVLIST_DELIMS, &lasts);
7189 		if (drv) {
7190 			if (strcmp(drv, LDEV_DRVLIST_NAME) == 0) {
7191 
7192 				drv = strtok_r(NULL, LDEV_DRV_DELIMS,
7193 					&lasts);
7194 
7195 				while (drv) {
7196 					vprint(FILES_MID,
7197 					    "logindevperm driver=%s\n",
7198 					    drv);
7199 
7200 					/*
7201 					 * create a linked list of driver
7202 					 * names
7203 					 */
7204 					list = (struct driver_list *)
7205 					    s_zalloc(
7206 					    sizeof (struct driver_list));
7207 					(void) strlcpy(list->driver_name, drv,
7208 					    sizeof (list->driver_name));
7209 					list->next = ldev->ldev_driver_list;
7210 					ldev->ldev_driver_list = list;
7211 					drv = strtok_r(NULL, LDEV_DRV_DELIMS,
7212 					    &lasts);
7213 				}
7214 			}
7215 		}
7216 	}
7217 	(void) fclose(fp);
7218 }
7219 
7220 /*
7221  * Tokens are separated by ' ', '\t', ':', '=', '&', '|', ';', '\n', or '\0'
7222  *
7223  * Returns DEVFSADM_SUCCESS if token found, DEVFSADM_FAILURE otherwise.
7224  */
7225 static int
7226 getnexttoken(char *next, char **nextp, char **tokenpp, char *tchar)
7227 {
7228 	char *cp;
7229 	char *cp1;
7230 	char *tokenp;
7231 
7232 	cp = next;
7233 	while (*cp == ' ' || *cp == '\t') {
7234 		cp++;			/* skip leading spaces */
7235 	}
7236 	tokenp = cp;			/* start of token */
7237 	while (*cp != '\0' && *cp != '\n' && *cp != ' ' && *cp != '\t' &&
7238 		*cp != ':' && *cp != '=' && *cp != '&' &&
7239 		*cp != '|' && *cp != ';') {
7240 		cp++;			/* point to next character */
7241 	}
7242 	/*
7243 	 * If terminating character is a space or tab, look ahead to see if
7244 	 * there's another terminator that's not a space or a tab.
7245 	 * (This code handles trailing spaces.)
7246 	 */
7247 	if (*cp == ' ' || *cp == '\t') {
7248 		cp1 = cp;
7249 		while (*++cp1 == ' ' || *cp1 == '\t')
7250 			;
7251 		if (*cp1 == '=' || *cp1 == ':' || *cp1 == '&' || *cp1 == '|' ||
7252 			*cp1 == ';' || *cp1 == '\n' || *cp1 == '\0') {
7253 			*cp = NULL;	/* terminate token */
7254 			cp = cp1;
7255 		}
7256 	}
7257 	if (tchar != NULL) {
7258 		*tchar = *cp;		/* save terminating character */
7259 		if (*tchar == '\0') {
7260 			*tchar = '\n';
7261 		}
7262 	}
7263 	*cp++ = '\0';			/* terminate token, point to next */
7264 	*nextp = cp;			/* set pointer to next character */
7265 	if (cp - tokenp - 1 == 0) {
7266 		return (DEVFSADM_FAILURE);
7267 	}
7268 	*tokenpp = tokenp;
7269 	return (DEVFSADM_SUCCESS);
7270 }
7271 
7272 /*
7273  * read or reread the driver aliases file
7274  */
7275 static void
7276 read_driver_aliases_file(void)
7277 {
7278 
7279 	driver_alias_t *save;
7280 	driver_alias_t *lst_tail;
7281 	driver_alias_t *ap;
7282 	static int cached = FALSE;
7283 	FILE *afd;
7284 	char line[256];
7285 	char *cp;
7286 	char *p;
7287 	char t;
7288 	int ln = 0;
7289 	static struct stat cached_sb;
7290 	struct stat current_sb;
7291 
7292 	(void) stat(ALIASFILE, &current_sb);
7293 
7294 	/* If already cached, check to see if it is still valid */
7295 	if (cached == TRUE) {
7296 
7297 		if (current_sb.st_mtime == cached_sb.st_mtime) {
7298 			vprint(FILES_MID, "%s cache valid\n", ALIASFILE);
7299 			return;
7300 		}
7301 
7302 		vprint(FILES_MID, "invalidating %s cache\n", ALIASFILE);
7303 		while (driver_aliases != NULL) {
7304 			free(driver_aliases->alias_name);
7305 			free(driver_aliases->driver_name);
7306 			save = driver_aliases;
7307 			driver_aliases = driver_aliases->next;
7308 			free(save);
7309 		}
7310 	} else {
7311 		cached = TRUE;
7312 	}
7313 
7314 	(void) stat(ALIASFILE, &cached_sb);
7315 
7316 	vprint(FILES_MID, "loading binding file: %s\n", ALIASFILE);
7317 
7318 	if ((afd = fopen(ALIASFILE, "r")) == NULL) {
7319 		err_print(FOPEN_FAILED, ALIASFILE, strerror(errno));
7320 		devfsadm_exit(1);
7321 	}
7322 
7323 	while (fgets(line, sizeof (line) - 1, afd) != NULL) {
7324 		ln++;
7325 		cp = line;
7326 		if (getnexttoken(cp, &cp, &p, &t) == DEVFSADM_FAILURE) {
7327 			err_print(IGNORING_LINE_IN, ln, ALIASFILE);
7328 			continue;
7329 		}
7330 		if (t == '\n' || t == '\0') {
7331 			err_print(DRV_BUT_NO_ALIAS, ln, ALIASFILE);
7332 			continue;
7333 		}
7334 		ap = (struct driver_alias *)
7335 				s_zalloc(sizeof (struct driver_alias));
7336 		ap->driver_name = s_strdup(p);
7337 		if (getnexttoken(cp, &cp, &p, &t) == DEVFSADM_FAILURE) {
7338 			err_print(DRV_BUT_NO_ALIAS, ln, ALIASFILE);
7339 			free(ap->driver_name);
7340 			free(ap);
7341 			continue;
7342 		}
7343 		if (*p == '"') {
7344 			if (p[strlen(p) - 1] == '"') {
7345 				p[strlen(p) - 1] = '\0';
7346 				p++;
7347 			}
7348 		}
7349 		ap->alias_name = s_strdup(p);
7350 		if (driver_aliases == NULL) {
7351 			driver_aliases = ap;
7352 			lst_tail = ap;
7353 		} else {
7354 			lst_tail->next = ap;
7355 			lst_tail = ap;
7356 		}
7357 	}
7358 	if (fclose(afd) == EOF) {
7359 		err_print(FCLOSE_FAILED, ALIASFILE, strerror(errno));
7360 	}
7361 }
7362 
7363 /*
7364  * return TRUE if alias_name is an alias for driver_name, otherwise
7365  * return FALSE.
7366  */
7367 static int
7368 alias(char *driver_name, char *alias_name)
7369 {
7370 	driver_alias_t *alias;
7371 
7372 	/*
7373 	 * check for a match
7374 	 */
7375 	for (alias = driver_aliases; alias != NULL; alias = alias->next) {
7376 		if ((strcmp(alias->driver_name, driver_name) == 0) &&
7377 		    (strcmp(alias->alias_name, alias_name) == 0)) {
7378 			return (TRUE);
7379 		}
7380 	}
7381 	return (FALSE);
7382 }
7383 
7384 /*
7385  * convenience functions
7386  */
7387 static void *
7388 s_malloc(const size_t size)
7389 {
7390 	void *rp;
7391 
7392 	rp = malloc(size);
7393 	if (rp == NULL) {
7394 		err_print(MALLOC_FAILED, size);
7395 		devfsadm_exit(1);
7396 	}
7397 	return (rp);
7398 }
7399 
7400 /*
7401  * convenience functions
7402  */
7403 static void *
7404 s_realloc(void *ptr, const size_t size)
7405 {
7406 	ptr = realloc(ptr, size);
7407 	if (ptr == NULL) {
7408 		err_print(REALLOC_FAILED, size);
7409 		devfsadm_exit(1);
7410 	}
7411 	return (ptr);
7412 }
7413 
7414 static void *
7415 s_zalloc(const size_t size)
7416 {
7417 	void *rp;
7418 
7419 	rp = calloc(1, size);
7420 	if (rp == NULL) {
7421 		err_print(CALLOC_FAILED, size);
7422 		devfsadm_exit(1);
7423 	}
7424 	return (rp);
7425 }
7426 
7427 char *
7428 s_strdup(const char *ptr)
7429 {
7430 	void *rp;
7431 
7432 	rp = strdup(ptr);
7433 	if (rp == NULL) {
7434 		err_print(STRDUP_FAILED, ptr);
7435 		devfsadm_exit(1);
7436 	}
7437 	return (rp);
7438 }
7439 
7440 static void
7441 s_closedir(DIR *dirp)
7442 {
7443 retry:
7444 	if (closedir(dirp) != 0) {
7445 		if (errno == EINTR)
7446 			goto retry;
7447 		err_print(CLOSEDIR_FAILED, strerror(errno));
7448 	}
7449 }
7450 
7451 static void
7452 s_mkdirp(const char *path, const mode_t mode)
7453 {
7454 	vprint(CHATTY_MID, "mkdirp(%s, 0x%lx)\n", path, mode);
7455 	if (mkdirp(path, mode) == -1) {
7456 		if (errno != EEXIST) {
7457 			err_print(MKDIR_FAILED, path, mode, strerror(errno));
7458 		}
7459 	}
7460 }
7461 
7462 static void
7463 s_unlink(const char *file)
7464 {
7465 retry:
7466 	if (unlink(file) == -1) {
7467 		if (errno == EINTR || errno == EAGAIN)
7468 			goto retry;
7469 		if (errno != ENOENT) {
7470 			err_print(UNLINK_FAILED, file, strerror(errno));
7471 		}
7472 	}
7473 }
7474 
7475 static void
7476 add_verbose_id(char *mid)
7477 {
7478 	num_verbose++;
7479 	verbose = s_realloc(verbose, num_verbose * sizeof (char *));
7480 	verbose[num_verbose - 1] = mid;
7481 }
7482 
7483 /*
7484  * returns DEVFSADM_TRUE if contents is a minor node in /devices.
7485  * If mn_root is not NULL, mn_root is set to:
7486  *	if contents is a /dev node, mn_root = contents
7487  * 			OR
7488  *	if contents is a /devices node, mn_root set to the '/'
7489  *	following /devices.
7490  */
7491 static int
7492 is_minor_node(char *contents, char **mn_root)
7493 {
7494 	char *ptr;
7495 	char device_prefix[100];
7496 
7497 	(void) snprintf(device_prefix, sizeof (device_prefix), "../devices/");
7498 
7499 	if ((ptr = strstr(contents, device_prefix)) != NULL) {
7500 		if (mn_root != NULL) {
7501 			/* mn_root should point to the / following /devices */
7502 			*mn_root = ptr += strlen(device_prefix) - 1;
7503 		}
7504 		return (DEVFSADM_TRUE);
7505 	}
7506 
7507 	(void) snprintf(device_prefix, sizeof (device_prefix), "/devices/");
7508 
7509 	if (strncmp(contents, device_prefix, strlen(device_prefix)) == 0) {
7510 		if (mn_root != NULL) {
7511 			/* mn_root should point to the / following /devices */
7512 			*mn_root = contents + strlen(device_prefix) - 1;
7513 		}
7514 		return (DEVFSADM_TRUE);
7515 	}
7516 
7517 	if (mn_root != NULL) {
7518 		*mn_root = contents;
7519 	}
7520 	return (DEVFSADM_FALSE);
7521 }
7522 
7523 /*
7524  * Lookup nvpair corresponding to the given name and type:
7525  *
7526  * The standard nvlist_lookup functions in libnvpair don't work as our
7527  * nvlist is not allocated with NV_UNIQUE_NAME or NV_UNIQUE_NAME_TYPE.
7528  */
7529 static nvpair_t *
7530 lookup_nvpair(nvlist_t *nvl, char *name, data_type_t type)
7531 {
7532 	nvpair_t *nvp;
7533 
7534 	for (nvp = nvlist_next_nvpair(nvl, NULL); nvp != NULL;
7535 	    nvp = nvlist_next_nvpair(nvl, nvp)) {
7536 		if (strcmp(name, nvpair_name(nvp)) == 0 &&
7537 		    nvpair_type(nvp) == type)
7538 			return (nvp);
7539 	}
7540 
7541 	return (NULL);
7542 }
7543 
7544 /*ARGSUSED*/
7545 static void
7546 process_rcm_events(void *arg)
7547 {
7548 	struct rcm_eventq *ev, *ev_next;
7549 	nvpair_t *nvp;
7550 	char *path, *driver;
7551 	int instance;
7552 	int err;
7553 	int need_to_exit;
7554 
7555 	for (;;) {
7556 		(void) mutex_lock(&rcm_eventq_lock);
7557 		while (rcm_eventq_head == NULL &&
7558 		    need_to_exit_rcm_event_thread == 0)
7559 			(void) cond_wait(&rcm_eventq_cv, &rcm_eventq_lock);
7560 
7561 		need_to_exit = need_to_exit_rcm_event_thread;
7562 		ev = rcm_eventq_head;
7563 		rcm_eventq_head = rcm_eventq_tail = NULL;
7564 		(void) mutex_unlock(&rcm_eventq_lock);
7565 
7566 		for (; ev != NULL; ev = ev_next) {
7567 			/*
7568 			 * Private notification interface to RCM:
7569 			 * Do not retry the RCM notification on an error since
7570 			 * we do not know whether the failure occurred in
7571 			 * librcm, rcm_daemon or rcm modules or scripts.
7572 			 */
7573 			if (librcm_notify_event(rcm_hdl,
7574 			    RCM_RESOURCE_NETWORK_NEW, 0, ev->nvl, NULL)
7575 			    != RCM_SUCCESS) {
7576 
7577 				err = errno;
7578 
7579 				if (((nvp = lookup_nvpair(ev->nvl,
7580 				    RCM_NV_DEVFS_PATH, DATA_TYPE_STRING))
7581 				    == NULL) ||
7582 				    (nvpair_value_string(nvp, &path) != 0))
7583 					    path = "unknown";
7584 
7585 				if (((nvp = lookup_nvpair(ev->nvl,
7586 				    RCM_NV_DRIVER_NAME, DATA_TYPE_STRING))
7587 				    == NULL) ||
7588 				    (nvpair_value_string(nvp, &driver) != 0))
7589 					    driver = "unknown";
7590 				if (((nvp = lookup_nvpair(ev->nvl,
7591 				    RCM_NV_INSTANCE, DATA_TYPE_INT32))
7592 				    == NULL) ||
7593 				    (nvpair_value_int32(nvp, &instance) != 0))
7594 					    instance = -1;
7595 
7596 				err_print(RCM_NOTIFY_FAILED, path, driver,
7597 				    instance, strerror(err));
7598 			}
7599 
7600 			ev_next = ev->next;
7601 			nvlist_free(ev->nvl);
7602 			free(ev);
7603 		}
7604 
7605 		if (need_to_exit)
7606 			return;
7607 	}
7608 }
7609 
7610 /*
7611  * Initialize rcm related handles and function pointers.
7612  * Since RCM need not present in miniroot, we dlopen librcm.
7613  */
7614 static int
7615 rcm_init(void)
7616 {
7617 #define	LIBRCM_PATH	"/usr/lib/librcm.so"
7618 	rcm_handle_t *hdl = NULL;
7619 	int err;
7620 
7621 	if ((librcm_hdl = dlopen(LIBRCM_PATH, RTLD_LAZY)) == NULL) {
7622 		/*
7623 		 * don't log an error here, since librcm may not be present
7624 		 * in miniroot.
7625 		 */
7626 		return (-1);
7627 	}
7628 
7629 	librcm_alloc_handle = (int (*)())dlsym(librcm_hdl, "rcm_alloc_handle");
7630 	librcm_free_handle = (void (*)())dlsym(librcm_hdl, "rcm_free_handle");
7631 	librcm_notify_event = (int (*)())dlsym(librcm_hdl, "rcm_notify_event");
7632 
7633 	if (librcm_alloc_handle == NULL || librcm_notify_event == NULL ||
7634 	    librcm_free_handle == NULL) {
7635 		err_print(MISSING_SYMBOLS, LIBRCM_PATH);
7636 		goto out;
7637 	}
7638 
7639 	/* Initialize the rcm handle */
7640 	if (librcm_alloc_handle(NULL, 0, NULL, &hdl) != RCM_SUCCESS) {
7641 		err_print(RCM_ALLOC_HANDLE_ERROR);
7642 		goto out;
7643 	}
7644 
7645 	(void) cond_init(&rcm_eventq_cv, USYNC_THREAD, 0);
7646 	(void) mutex_init(&rcm_eventq_lock, USYNC_THREAD, 0);
7647 
7648 	/* create a thread to notify RCM of events */
7649 	if ((err = thr_create(NULL, 0, (void *(*)(void *))process_rcm_events,
7650 	    NULL, 0, &process_rcm_events_tid)) != 0) {
7651 		err_print(CANT_CREATE_THREAD, "process_rcm_events",
7652 		    strerror(err));
7653 		goto out;
7654 	}
7655 
7656 	rcm_hdl = hdl;
7657 	return (0);
7658 
7659 out:
7660 	if (hdl)
7661 		librcm_free_handle(hdl);
7662 	(void) dlclose(librcm_hdl);
7663 	return (-1);
7664 }
7665 
7666 /*
7667  * Build an nvlist using the minor data. Pack it and add the packed nvlist
7668  * as a byte array to nv_list parameter.
7669  * Return 0 on success, errno on failure.
7670  */
7671 static int
7672 add_minor_data_to_nvl(nvlist_t *nv_list, di_minor_t minor)
7673 {
7674 	nvlist_t *nvl = NULL;
7675 	int32_t minor_type;
7676 	char *minor_name, *minor_node_type;
7677 	int err;
7678 	char *buf = NULL;
7679 	size_t buflen = 0;
7680 
7681 	if ((err = nvlist_alloc(&nvl, 0, 0)) != 0)
7682 		return (err);
7683 
7684 	minor_type = (int32_t)di_minor_type(minor);
7685 	if ((err = nvlist_add_int32(nvl, RCM_NV_MINOR_TYPE, minor_type)) != 0)
7686 		goto error;
7687 
7688 	minor_name = di_minor_name(minor);
7689 	if ((err = nvlist_add_string(nvl, RCM_NV_MINOR_NAME, minor_name)) != 0)
7690 		goto error;
7691 
7692 	if ((minor_node_type = di_minor_nodetype(minor)) == NULL)
7693 		minor_node_type = "";
7694 	if ((err = nvlist_add_string(nvl, RCM_NV_MINOR_NODE_TYPE,
7695 	    minor_node_type)) != 0)
7696 		goto error;
7697 
7698 	if ((err = nvlist_pack(nvl, &buf, &buflen, NV_ENCODE_NATIVE, 0)) != 0)
7699 		goto error;
7700 
7701 	err = nvlist_add_byte_array(nv_list, RCM_NV_MINOR_DATA,
7702 	    (uchar_t *)(buf), (uint_t)(buflen));
7703 
7704 error:
7705 	nvlist_free(nvl);
7706 	if (buf)
7707 		free(buf);
7708 	return (err);
7709 }
7710 
7711 static void
7712 enqueue_rcm_event(nvlist_t *nvl)
7713 {
7714 	struct rcm_eventq *ev;
7715 
7716 	ev = (struct rcm_eventq *)s_zalloc(sizeof (struct rcm_eventq));
7717 	ev->nvl = nvl;
7718 
7719 	(void) mutex_lock(&rcm_eventq_lock);
7720 	if (rcm_eventq_head == NULL)
7721 		rcm_eventq_head = ev;
7722 	else
7723 		rcm_eventq_tail->next = ev;
7724 	rcm_eventq_tail = ev;
7725 	(void) cond_broadcast(&rcm_eventq_cv);
7726 	(void) mutex_unlock(&rcm_eventq_lock);
7727 }
7728 
7729 /*
7730  * Generate an nvlist using the information given in node and minor_name.
7731  * If minor_name is NULL the nvlist will contain information on
7732  * all minor nodes. Otherwise the nvlist will contain information
7733  * only on the given minor_name. Notify RCM passing the nvlist.
7734  *
7735  * Return 0 upon successfully notifying RCM, errno on failure.
7736  */
7737 static int
7738 notify_rcm(di_node_t node, char *minor_name)
7739 {
7740 	nvlist_t *nvl = NULL;
7741 	char *path, *driver_name;
7742 	char *node_name;
7743 	int err;
7744 	int32_t instance;
7745 	di_minor_t minor;
7746 
7747 	if ((driver_name = di_driver_name(node)) == NULL)
7748 		driver_name = "";
7749 
7750 	instance = (int32_t)di_instance(node);
7751 
7752 	if ((path = di_devfs_path(node)) == NULL) {
7753 		err = errno;
7754 		goto error;
7755 	}
7756 
7757 	if ((err = nvlist_alloc(&nvl, 0, 0)) != 0)
7758 		goto error;
7759 
7760 	if ((err = nvlist_add_string(nvl, RCM_NV_DRIVER_NAME, driver_name))
7761 	    != 0)
7762 		goto error;
7763 
7764 	if ((err = nvlist_add_int32(nvl, RCM_NV_INSTANCE, instance)) != 0)
7765 		goto error;
7766 
7767 	if ((node_name = di_node_name(node)) == NULL)
7768 		node_name = "";
7769 	if ((err = nvlist_add_string(nvl, RCM_NV_NODE_NAME, node_name)) != 0)
7770 		goto error;
7771 
7772 	if ((err = nvlist_add_string(nvl, RCM_NV_DEVFS_PATH, path)) != 0)
7773 		goto error;
7774 
7775 	minor = di_minor_next(node, DI_MINOR_NIL);
7776 	while (minor != DI_MINOR_NIL) {
7777 		if ((minor_name == NULL) ||
7778 		    (strcmp(minor_name, di_minor_name(minor)) == 0)) {
7779 			if ((err = add_minor_data_to_nvl(nvl, minor)) != 0)
7780 				goto error;
7781 		}
7782 		minor = di_minor_next(node, minor);
7783 	}
7784 
7785 	enqueue_rcm_event(nvl);
7786 	di_devfs_path_free(path);
7787 	return (0);
7788 
7789 error:
7790 	err_print(RCM_NVLIST_BUILD_ERROR, ((path != NULL) ? path : "unknown"),
7791 	    driver_name, instance, strerror(err));
7792 
7793 	if (path)
7794 		di_devfs_path_free(path);
7795 	if (nvl)
7796 		nvlist_free(nvl);
7797 	return (err);
7798 }
7799 
7800 /*
7801  * Add the specified property to nvl.
7802  * Returns:
7803  *   0	successfully added
7804  *   -1	an error occurred
7805  *   1	could not add the property for reasons not due to errors.
7806  */
7807 static int
7808 add_property(nvlist_t *nvl, di_prop_t prop)
7809 {
7810 	char *name;
7811 	char *attr_name;
7812 	int n, len;
7813 	int32_t *int32p;
7814 	int64_t *int64p;
7815 	char *str;
7816 	char **strarray;
7817 	uchar_t *bytep;
7818 	int rv = 0;
7819 	int i;
7820 
7821 	if ((name = di_prop_name(prop)) == NULL)
7822 		return (-1);
7823 
7824 	len = sizeof (DEV_PROP_PREFIX) + strlen(name);
7825 	if ((attr_name = malloc(len)) == NULL)
7826 		return (-1);
7827 
7828 	(void) strlcpy(attr_name, DEV_PROP_PREFIX, len);
7829 	(void) strlcat(attr_name, name, len);
7830 
7831 	switch (di_prop_type(prop)) {
7832 	case DI_PROP_TYPE_BOOLEAN:
7833 		if (nvlist_add_boolean(nvl, attr_name) != 0)
7834 			goto out;
7835 		break;
7836 
7837 	case DI_PROP_TYPE_INT:
7838 		if ((n = di_prop_ints(prop, &int32p)) < 1)
7839 			goto out;
7840 
7841 		if (n <= (PROP_LEN_LIMIT / sizeof (int32_t))) {
7842 			if (nvlist_add_int32_array(nvl, attr_name, int32p,
7843 			    n) != 0)
7844 				goto out;
7845 		} else
7846 			rv = 1;
7847 		break;
7848 
7849 	case DI_PROP_TYPE_INT64:
7850 		if ((n = di_prop_int64(prop, &int64p)) < 1)
7851 			goto out;
7852 
7853 		if (n <= (PROP_LEN_LIMIT / sizeof (int64_t))) {
7854 			if (nvlist_add_int64_array(nvl, attr_name, int64p,
7855 			    n) != 0)
7856 				goto out;
7857 		} else
7858 			rv = 1;
7859 		break;
7860 
7861 	case DI_PROP_TYPE_BYTE:
7862 	case DI_PROP_TYPE_UNKNOWN:
7863 		if ((n = di_prop_bytes(prop, &bytep)) < 1)
7864 			goto out;
7865 
7866 		if (n <= PROP_LEN_LIMIT) {
7867 			if (nvlist_add_byte_array(nvl, attr_name, bytep, n)
7868 			    != 0)
7869 				goto out;
7870 		} else
7871 			rv = 1;
7872 		break;
7873 
7874 	case DI_PROP_TYPE_STRING:
7875 		if ((n = di_prop_strings(prop, &str)) < 1)
7876 			goto out;
7877 
7878 		if ((strarray = malloc(n * sizeof (char *))) == NULL)
7879 			goto out;
7880 
7881 		len = 0;
7882 		for (i = 0; i < n; i++) {
7883 			strarray[i] = str + len;
7884 			len += strlen(strarray[i]) + 1;
7885 		}
7886 
7887 		if (len <= PROP_LEN_LIMIT) {
7888 			if (nvlist_add_string_array(nvl, attr_name, strarray,
7889 			    n) != 0) {
7890 				free(strarray);
7891 				goto out;
7892 			}
7893 		} else
7894 			rv = 1;
7895 		free(strarray);
7896 		break;
7897 
7898 	default:
7899 		rv = 1;
7900 		break;
7901 	}
7902 
7903 	free(attr_name);
7904 	return (rv);
7905 
7906 out:
7907 	free(attr_name);
7908 	return (-1);
7909 }
7910 
7911 static void
7912 free_dev_names(struct devlink_cb_arg *x)
7913 {
7914 	int i;
7915 
7916 	for (i = 0; i < x->count; i++) {
7917 		free(x->dev_names[i]);
7918 		free(x->link_contents[i]);
7919 	}
7920 }
7921 
7922 /* callback function for di_devlink_cache_walk */
7923 static int
7924 devlink_cb(di_devlink_t dl, void *arg)
7925 {
7926 	struct devlink_cb_arg *x = (struct devlink_cb_arg *)arg;
7927 	const char *path;
7928 	const char *content;
7929 
7930 	if ((path = di_devlink_path(dl)) == NULL ||
7931 	    (content = di_devlink_content(dl)) == NULL ||
7932 	    (x->dev_names[x->count] = strdup(path)) == NULL)
7933 		goto out;
7934 
7935 	if ((x->link_contents[x->count] = strdup(content)) == NULL) {
7936 		free(x->dev_names[x->count]);
7937 		goto out;
7938 	}
7939 
7940 	x->count++;
7941 	if (x->count >= MAX_DEV_NAME_COUNT)
7942 		return (DI_WALK_TERMINATE);
7943 
7944 	return (DI_WALK_CONTINUE);
7945 
7946 out:
7947 	x->rv = -1;
7948 	free_dev_names(x);
7949 	return (DI_WALK_TERMINATE);
7950 }
7951 
7952 /*
7953  * Lookup dev name corresponding to the phys_path.
7954  * phys_path is path to a node or minor node.
7955  * Returns:
7956  *	0 with *dev_name set to the dev name
7957  *		Lookup succeeded and dev_name found
7958  *	0 with *dev_name set to NULL
7959  *		Lookup encountered no errors but dev name not found
7960  *	-1
7961  *		Lookup failed
7962  */
7963 static int
7964 lookup_dev_name(char *phys_path, char **dev_name)
7965 {
7966 	struct devlink_cb_arg cb_arg;
7967 
7968 	*dev_name = NULL;
7969 
7970 	cb_arg.count = 0;
7971 	cb_arg.rv = 0;
7972 	(void) di_devlink_cache_walk(devlink_cache, NULL, phys_path,
7973 	    DI_PRIMARY_LINK, &cb_arg, devlink_cb);
7974 
7975 	if (cb_arg.rv == -1)
7976 		return (-1);
7977 
7978 	if (cb_arg.count > 0) {
7979 		*dev_name = strdup(cb_arg.dev_names[0]);
7980 		free_dev_names(&cb_arg);
7981 		if (*dev_name == NULL)
7982 			return (-1);
7983 	}
7984 
7985 	return (0);
7986 }
7987 
7988 static char *
7989 lookup_disk_dev_name(char *node_path)
7990 {
7991 	struct devlink_cb_arg cb_arg;
7992 	char *dev_name = NULL;
7993 	int i;
7994 	char *p;
7995 	int len1, len2;
7996 
7997 #define	DEV_RDSK	"/dev/rdsk/"
7998 #define	DISK_RAW_MINOR	",raw"
7999 
8000 	cb_arg.count = 0;
8001 	cb_arg.rv = 0;
8002 	(void) di_devlink_cache_walk(devlink_cache, NULL, node_path,
8003 	    DI_PRIMARY_LINK, &cb_arg, devlink_cb);
8004 
8005 	if (cb_arg.rv == -1 || cb_arg.count == 0)
8006 		return (NULL);
8007 
8008 	/* first try lookup based on /dev/rdsk name */
8009 	for (i = 0; i < cb_arg.count; i++) {
8010 		if (strncmp(cb_arg.dev_names[i], DEV_RDSK,
8011 		    sizeof (DEV_RDSK) - 1) == 0) {
8012 			dev_name = strdup(cb_arg.dev_names[i]);
8013 			break;
8014 		}
8015 	}
8016 
8017 	if (dev_name == NULL) {
8018 		/* now try lookup based on a minor name ending with ",raw" */
8019 		len1 = sizeof (DISK_RAW_MINOR) - 1;
8020 		for (i = 0; i < cb_arg.count; i++) {
8021 			len2 = strlen(cb_arg.link_contents[i]);
8022 			if (len2 >= len1 &&
8023 			    strcmp(cb_arg.link_contents[i] + len2 - len1,
8024 			    DISK_RAW_MINOR) == 0) {
8025 				dev_name = strdup(cb_arg.dev_names[i]);
8026 				break;
8027 			}
8028 		}
8029 	}
8030 
8031 	free_dev_names(&cb_arg);
8032 
8033 	if (strlen(dev_name) == 0) {
8034 		free(dev_name);
8035 		return (NULL);
8036 	}
8037 
8038 	/* if the name contains slice or partition number strip it */
8039 	p = dev_name + strlen(dev_name) - 1;
8040 	if (isdigit(*p)) {
8041 		while (p != dev_name && isdigit(*p))
8042 			p--;
8043 		if (*p == 's' || *p == 'p')
8044 			*p = '\0';
8045 	}
8046 
8047 	return (dev_name);
8048 }
8049 
8050 static char *
8051 lookup_network_dev_name(char *node_path, char *driver_name)
8052 {
8053 	char *dev_name = NULL;
8054 	char phys_path[MAXPATHLEN];
8055 
8056 	if (lookup_dev_name(node_path, &dev_name) == -1)
8057 		return (NULL);
8058 
8059 	if (dev_name == NULL) {
8060 		/* dlpi style-2 only interface */
8061 		(void) snprintf(phys_path, sizeof (phys_path),
8062 		    "/pseudo/clone@0:%s", driver_name);
8063 		if (lookup_dev_name(phys_path, &dev_name) == -1 ||
8064 		    dev_name == NULL)
8065 			return (NULL);
8066 	}
8067 
8068 	return (dev_name);
8069 }
8070 
8071 /*
8072  * Build an nvlist containing all attributes for devfs events.
8073  * Returns nvlist pointer on success, NULL on failure.
8074  */
8075 static nvlist_t *
8076 build_event_attributes(char *class, char *subclass, char *node_path,
8077     di_node_t node, char *driver_name, int instance)
8078 {
8079 	nvlist_t *nvl;
8080 	int err = 0;
8081 	di_prop_t prop;
8082 	int count;
8083 	char *prop_name;
8084 	int x;
8085 	char *dev_name = NULL;
8086 	int dev_name_lookup_err = 0;
8087 
8088 	if ((err = nvlist_alloc(&nvl, NV_UNIQUE_NAME_TYPE, 0)) != 0) {
8089 		nvl = NULL;
8090 		goto out;
8091 	}
8092 
8093 	if ((err = nvlist_add_int32(nvl, EV_VERSION, EV_V1)) != 0)
8094 		goto out;
8095 
8096 	if ((err = nvlist_add_string(nvl, DEV_PHYS_PATH, node_path)) != 0)
8097 		goto out;
8098 
8099 	if (strcmp(class, EC_DEV_ADD) != 0 &&
8100 	    strcmp(class, EC_DEV_REMOVE) != 0)
8101 		return (nvl);
8102 
8103 	if (driver_name == NULL || instance == -1)
8104 		goto out;
8105 
8106 	if (strcmp(subclass, ESC_DISK) == 0) {
8107 		if ((dev_name = lookup_disk_dev_name(node_path)) == NULL) {
8108 			dev_name_lookup_err = 1;
8109 			goto out;
8110 		}
8111 	} else if (strcmp(subclass, ESC_NETWORK) == 0) {
8112 		if ((dev_name = lookup_network_dev_name(node_path, driver_name))
8113 		    == NULL) {
8114 			dev_name_lookup_err = 1;
8115 			goto out;
8116 		}
8117 	}
8118 
8119 	if (dev_name) {
8120 		if ((err = nvlist_add_string(nvl, DEV_NAME, dev_name)) != 0)
8121 			goto out;
8122 		free(dev_name);
8123 		dev_name = NULL;
8124 	}
8125 
8126 	if ((err = nvlist_add_string(nvl, DEV_DRIVER_NAME, driver_name)) != 0)
8127 		goto out;
8128 
8129 	if ((err = nvlist_add_int32(nvl, DEV_INSTANCE, instance)) != 0)
8130 		goto out;
8131 
8132 	if (strcmp(class, EC_DEV_ADD) == 0) {
8133 		/* add properties */
8134 		count = 0;
8135 		for (prop = di_prop_next(node, DI_PROP_NIL);
8136 		    prop != DI_PROP_NIL && count < MAX_PROP_COUNT;
8137 		    prop = di_prop_next(node, prop)) {
8138 
8139 			if (di_prop_devt(prop) != DDI_DEV_T_NONE)
8140 				continue;
8141 
8142 			if ((x = add_property(nvl, prop)) == 0)
8143 				count++;
8144 			else if (x == -1) {
8145 				if ((prop_name = di_prop_name(prop)) == NULL)
8146 					prop_name = "";
8147 				err_print(PROP_ADD_FAILED, prop_name);
8148 				goto out;
8149 			}
8150 		}
8151 	}
8152 
8153 	return (nvl);
8154 
8155 out:
8156 	if (nvl)
8157 		nvlist_free(nvl);
8158 
8159 	if (dev_name)
8160 		free(dev_name);
8161 
8162 	if (dev_name_lookup_err)
8163 		err_print(DEV_NAME_LOOKUP_FAILED, node_path);
8164 	else
8165 		err_print(BUILD_EVENT_ATTR_FAILED, (err) ? strerror(err) : "");
8166 	return (NULL);
8167 }
8168 
8169 static void
8170 log_event(char *class, char *subclass, nvlist_t *nvl)
8171 {
8172 	sysevent_id_t eid;
8173 
8174 	if (sysevent_post_event(class, subclass, "SUNW", DEVFSADMD,
8175 	    nvl, &eid) != 0) {
8176 		err_print(LOG_EVENT_FAILED, strerror(errno));
8177 	}
8178 }
8179 
8180 static void
8181 build_and_log_event(char *class, char *subclass, char *node_path,
8182     di_node_t node)
8183 {
8184 	nvlist_t *nvl;
8185 
8186 	if (node != DI_NODE_NIL)
8187 		nvl = build_event_attributes(class, subclass, node_path, node,
8188 		    di_driver_name(node), di_instance(node));
8189 	else
8190 		nvl = build_event_attributes(class, subclass, node_path, node,
8191 		    NULL, -1);
8192 
8193 	if (nvl) {
8194 		log_event(class, subclass, nvl);
8195 		nvlist_free(nvl);
8196 	}
8197 }
8198