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