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