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