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