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