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