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