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