xref: /illumos-gate/usr/src/cmd/devfsadm/devfsadm.c (revision cb2bfa20)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2016 Toomas Soome <tsoome@me.com>
24  * Copyright 2016 Nexenta Systems, Inc.  All rights reserved.
25  * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
26  * Copyright 2019, Joyent, Inc.
27  */
28 
29 /*
30  * Devfsadm replaces drvconfig, audlinks, disks, tapes, ports, devlinks
31  * as a general purpose device administrative utility.	It creates
32  * devices special files in /devices and logical links in /dev, and
33  * coordinates updates to /etc/path_to_instance with the kernel.  It
34  * operates in both command line mode to handle user or script invoked
35  * reconfiguration updates, and operates in daemon mode to handle dynamic
36  * reconfiguration for hotplugging support.
37  */
38 
39 #include <string.h>
40 #include <deflt.h>
41 #include <tsol/label.h>
42 #include <bsm/devices.h>
43 #include <bsm/devalloc.h>
44 #include <utime.h>
45 #include <sys/param.h>
46 #include <bsm/libbsm.h>
47 #include <zone.h>
48 #include "devfsadm_impl.h"
49 
50 /* externs from devalloc.c */
51 extern void  _reset_devalloc(int);
52 extern void _update_devalloc_db(devlist_t *, int, int, char *, char *);
53 extern int _da_check_for_usb(char *, char *);
54 
55 /* create or remove nodes or links. unset with -n */
56 static int file_mods = TRUE;
57 
58 /* cleanup mode.  Set with -C */
59 static int cleanup = FALSE;
60 
61 /* devlinks -d compatibility */
62 static int devlinks_debug = FALSE;
63 
64 /* flag to check if system is labeled */
65 int system_labeled = FALSE;
66 
67 /* flag to enable/disable device allocation with -e/-d */
68 static int devalloc_flag = 0;
69 
70 /* flag that indicates if device allocation is on or not */
71 static int devalloc_is_on = 0;
72 
73 /* flag to update device allocation database for this device type */
74 static int update_devdb = 0;
75 
76 /*
77  * devices to be deallocated with -d :
78  *	audio, floppy, cd, floppy, tape, rmdisk.
79  */
80 static char *devalloc_list[10] = {DDI_NT_AUDIO, DDI_NT_CD, DDI_NT_CD_CHAN,
81 				    DDI_NT_FD, DDI_NT_TAPE, DDI_NT_BLOCK_CHAN,
82 				    DDI_NT_UGEN, DDI_NT_USB_ATTACHMENT_POINT,
83 				    DDI_NT_SCSI_NEXUS, NULL};
84 
85 /* list of allocatable devices */
86 static devlist_t devlist;
87 
88 /* load a single driver only.  set with -i */
89 static int single_drv = FALSE;
90 static char *driver = NULL;
91 
92 /* attempt to load drivers or defer attach nodes */
93 static int load_attach_drv = TRUE;
94 
95 /* reload all driver.conf files */
96 static int update_all_drivers = FALSE;
97 
98 /* set if invoked via /usr/lib/devfsadm/devfsadmd */
99 static int daemon_mode = FALSE;
100 
101 /* set if event_handler triggered */
102 int event_driven = FALSE;
103 
104 /* output directed to syslog during daemon mode if set */
105 static int logflag = FALSE;
106 
107 /* build links in /dev.  -x to turn off */
108 static int build_dev = TRUE;
109 
110 /* build nodes in /devices.  -y to turn off */
111 static int build_devices = TRUE;
112 
113 /* -z to turn off */
114 static int flush_path_to_inst_enable = TRUE;
115 
116 /* variables used for path_to_inst flushing */
117 static int inst_count = 0;
118 static mutex_t count_lock;
119 static cond_t cv;
120 
121 /* variables for minor_fini thread */
122 static mutex_t minor_fini_mutex;
123 static int minor_fini_canceled = TRUE;
124 static int minor_fini_delayed = FALSE;
125 static cond_t minor_fini_cv;
126 static int minor_fini_timeout = MINOR_FINI_TIMEOUT_DEFAULT;
127 
128 /* single-threads /dev modification */
129 static sema_t dev_sema;
130 
131 /* the program we were invoked as; ie argv[0] */
132 static char *prog;
133 
134 /* pointers to create/remove link lists */
135 static create_list_t *create_head = NULL;
136 static remove_list_t *remove_head = NULL;
137 
138 /*  supports the class -c option */
139 static char **classes = NULL;
140 static int num_classes = 0;
141 
142 /* used with verbose option -v or -V */
143 static int num_verbose = 0;
144 static char **verbose = NULL;
145 
146 static struct mperm *minor_perms = NULL;
147 static driver_alias_t *driver_aliases = NULL;
148 
149 /* set if -r alternate root given */
150 static char *root_dir = "";
151 
152 /* /devices or <rootdir>/devices */
153 static char *devices_dir  = DEVICES;
154 
155 /* /dev or <rootdir>/dev */
156 static char *dev_dir = DEV;
157 
158 /* /etc/dev or <rootdir>/etc/dev */
159 static char *etc_dev_dir = ETCDEV;
160 
161 /*
162  * writable root (for lock files and doors during install).
163  * This is also root dir for /dev attr dir during install.
164  */
165 static char *attr_root = NULL;
166 
167 /* /etc/path_to_inst unless -p used */
168 static char *inst_file = INSTANCE_FILE;
169 
170 /* /usr/lib/devfsadm/linkmods unless -l used */
171 static char *module_dirs = MODULE_DIRS;
172 
173 /* default uid/gid used if /etc/minor_perm entry not found */
174 static uid_t root_uid;
175 static gid_t sys_gid;
176 
177 /* /etc/devlink.tab unless devlinks -t used */
178 static char *devlinktab_file = NULL;
179 
180 /* File and data structure to reserve enumerate IDs */
181 static char *enumerate_file = ENUMERATE_RESERVED;
182 static enumerate_file_t *enumerate_reserved = NULL;
183 
184 /* set if /dev link is new. speeds up rm_stale_links */
185 static int linknew = TRUE;
186 
187 /* variables for devlink.tab compat processing */
188 static devlinktab_list_t *devlinktab_list = NULL;
189 static unsigned int devlinktab_line = 0;
190 
191 /* cache head for devfsadm_enumerate*() functions */
192 static numeral_set_t *head_numeral_set = NULL;
193 
194 /* list list of devfsadm modules */
195 static module_t *module_head = NULL;
196 
197 /* name_to_major list used in utility function */
198 static n2m_t *n2m_list = NULL;
199 
200 /* cache of some links used for performance */
201 static linkhead_t *headlinkhead = NULL;
202 
203 /* locking variables to prevent multiples writes to /dev */
204 static int hold_dev_lock = FALSE;
205 static int hold_daemon_lock = FALSE;
206 static int dev_lock_fd;
207 static int daemon_lock_fd;
208 static char dev_lockfile[PATH_MAX + 1];
209 static char daemon_lockfile[PATH_MAX + 1];
210 
211 /* last devinfo node/minor processed. used for performance */
212 static di_node_t lnode;
213 static di_minor_t lminor;
214 static char lphy_path[PATH_MAX + 1] = {""};
215 
216 /* Globals used by the link database */
217 static di_devlink_handle_t devlink_cache;
218 static int update_database = FALSE;
219 
220 /* Globals used to set logindev perms */
221 static struct login_dev *login_dev_cache = NULL;
222 static int login_dev_enable = FALSE;
223 
224 /* Global to use devinfo snapshot cache */
225 static int use_snapshot_cache = FALSE;
226 
227 /* Global for no-further-processing hash */
228 static item_t **nfp_hash;
229 static mutex_t  nfp_mutex = DEFAULTMUTEX;
230 
231 /*
232  * Directories not removed even when empty.  They are packaged, or may
233  * be referred to from a non-global zone.  The dirs must be listed in
234  * canonical form i.e. without leading "/dev/"
235  */
236 static char *sticky_dirs[] =
237 	{"dsk", "rdsk", "term", "lofi", "rlofi", NULL};
238 
239 /* Devname globals */
240 static int lookup_door_fd = -1;
241 static char *lookup_door_path;
242 
243 static void load_dev_acl(void);
244 static void update_drvconf(major_t, int);
245 static void check_reconfig_state(void);
246 static int s_stat(const char *, struct stat *);
247 
248 static int is_blank(char *);
249 
250 /* sysevent queue related globals */
251 static mutex_t  syseventq_mutex = DEFAULTMUTEX;
252 static syseventq_t *syseventq_front;
253 static syseventq_t *syseventq_back;
254 static void process_syseventq();
255 
256 static di_node_t devi_root_node = DI_NODE_NIL;
257 
258 int
main(int argc,char * argv[])259 main(int argc, char *argv[])
260 {
261 	struct passwd *pw;
262 	struct group *gp;
263 	pid_t pid;
264 
265 	(void) setlocale(LC_ALL, "");
266 	(void) textdomain(TEXT_DOMAIN);
267 
268 	if ((prog = strrchr(argv[0], '/')) == NULL) {
269 		prog = argv[0];
270 	} else {
271 		prog++;
272 	}
273 
274 	if (getuid() != 0) {
275 		err_print(MUST_BE_ROOT);
276 		devfsadm_exit(1);
277 		/*NOTREACHED*/
278 	}
279 
280 	if (getzoneid() != GLOBAL_ZONEID) {
281 		err_print(MUST_BE_GLOBAL_ZONE);
282 		devfsadm_exit(1);
283 	}
284 
285 	/*
286 	 * Close all files except stdin/stdout/stderr
287 	 */
288 	closefrom(3);
289 
290 	if ((pw = getpwnam(DEFAULT_DEV_USER)) != NULL) {
291 		root_uid = pw->pw_uid;
292 	} else {
293 		err_print(CANT_FIND_USER, DEFAULT_DEV_USER);
294 		root_uid = (uid_t)0;	/* assume 0 is root */
295 	}
296 
297 	/* the default group is sys */
298 
299 	if ((gp = getgrnam(DEFAULT_DEV_GROUP)) != NULL) {
300 		sys_gid = gp->gr_gid;
301 	} else {
302 		err_print(CANT_FIND_GROUP, DEFAULT_DEV_GROUP);
303 		sys_gid = (gid_t)3;	/* assume 3 is sys */
304 	}
305 
306 	(void) umask(0);
307 
308 	system_labeled = is_system_labeled();
309 	if (system_labeled == FALSE) {
310 		/*
311 		 * is_system_labeled() will return false in case we are
312 		 * starting before the first reboot after Trusted Extensions
313 		 * is enabled.  Check the setting in /etc/system to see if
314 		 * TX is enabled (even if not yet booted).
315 		 */
316 		if (defopen("/etc/system") == 0) {
317 			if (defread("set sys_labeling=1") != NULL)
318 				system_labeled = TRUE;
319 
320 			/* close defaults file */
321 			(void) defopen(NULL);
322 		}
323 	}
324 	/*
325 	 * Check if device allocation is enabled.
326 	 */
327 	devalloc_is_on = (da_is_on() == 1) ? 1 : 0;
328 
329 #ifdef DEBUG
330 	if (system_labeled == FALSE) {
331 		struct stat tx_stat;
332 
333 		/* test hook: see also mkdevalloc.c and allocate.c */
334 		system_labeled = is_system_labeled_debug(&tx_stat);
335 	}
336 #endif
337 
338 	parse_args(argc, argv);
339 
340 	(void) sema_init(&dev_sema, 1, USYNC_THREAD, NULL);
341 
342 	/* Initialize device allocation list */
343 	devlist.audio = devlist.cd = devlist.floppy = devlist.tape =
344 	    devlist.rmdisk = NULL;
345 
346 	if (daemon_mode == TRUE) {
347 		/*
348 		 * Build /dev and /devices before daemonizing if
349 		 * reconfig booting and daemon invoked with alternate
350 		 * root. This is to support install.
351 		 */
352 		if (getenv(RECONFIG_BOOT) != NULL && root_dir[0] != '\0') {
353 			vprint(INFO_MID, CONFIGURING);
354 			load_dev_acl();
355 			update_drvconf((major_t)-1, 0);
356 			process_devinfo_tree();
357 			(void) modctl(MODSETMINIROOT);
358 		}
359 
360 		/*
361 		 * fork before detaching from tty in order to print error
362 		 * message if unable to acquire file lock.  locks not preserved
363 		 * across forks.  Even under debug we want to fork so that
364 		 * when executed at boot we don't hang.
365 		 */
366 		if (fork() != 0) {
367 			devfsadm_exit(0);
368 			/*NOTREACHED*/
369 		}
370 
371 		/* set directory to / so it coredumps there */
372 		if (chdir("/") == -1) {
373 			err_print(CHROOT_FAILED, strerror(errno));
374 		}
375 
376 		/* only one daemon can run at a time */
377 		if ((pid = enter_daemon_lock()) == getpid()) {
378 			detachfromtty();
379 			(void) cond_init(&cv, USYNC_THREAD, 0);
380 			(void) mutex_init(&count_lock, USYNC_THREAD, 0);
381 			if (thr_create(NULL, 0,
382 			    (void *(*)(void *))instance_flush_thread,
383 			    NULL, THR_DETACHED, NULL) != 0) {
384 				err_print(CANT_CREATE_THREAD, "daemon",
385 				    strerror(errno));
386 				devfsadm_exit(1);
387 				/*NOTREACHED*/
388 			}
389 
390 			/* start the minor_fini_thread */
391 			(void) mutex_init(&minor_fini_mutex, USYNC_THREAD, 0);
392 			(void) cond_init(&minor_fini_cv, USYNC_THREAD, 0);
393 			if (thr_create(NULL, 0, minor_fini_thread,
394 			    NULL, THR_DETACHED, NULL)) {
395 				err_print(CANT_CREATE_THREAD, "minor_fini",
396 				    strerror(errno));
397 				devfsadm_exit(1);
398 				/*NOTREACHED*/
399 			}
400 
401 
402 			/*
403 			 * logindevperms need only be set
404 			 * in daemon mode and when root dir is "/".
405 			 */
406 			if (root_dir[0] == '\0')
407 				login_dev_enable = TRUE;
408 			daemon_update();
409 			devfsadm_exit(0);
410 			/*NOTREACHED*/
411 		} else {
412 			err_print(DAEMON_RUNNING, pid);
413 			devfsadm_exit(1);
414 			/*NOTREACHED*/
415 		}
416 	} else {
417 		/* not a daemon, so just build /dev and /devices */
418 
419 		/*
420 		 * If turning off device allocation, load the
421 		 * minor_perm file because process_devinfo_tree() will
422 		 * need this in order to reset the permissions of the
423 		 * device files.
424 		 */
425 		if (devalloc_flag == DA_OFF) {
426 			read_minor_perm_file();
427 		}
428 
429 		process_devinfo_tree();
430 		if (devalloc_flag != 0)
431 			/* Enable/disable device allocation */
432 			_reset_devalloc(devalloc_flag);
433 	}
434 	return (0);
435 }
436 
437 static void
update_drvconf(major_t major,int flags)438 update_drvconf(major_t major, int flags)
439 {
440 	if (modctl(MODLOADDRVCONF, major, flags) != 0)
441 		err_print(gettext("update_drvconf failed for major %d\n"),
442 		    major);
443 }
444 
445 static void
load_dev_acl()446 load_dev_acl()
447 {
448 	if (load_devpolicy() != 0)
449 		err_print(gettext("device policy load failed\n"));
450 	load_minor_perm_file();
451 }
452 
453 /*
454  * As devfsadm is run early in boot to provide the kernel with
455  * minor_perm info, we might as well check for reconfig at the
456  * same time to avoid running devfsadm twice.  This gets invoked
457  * earlier than the env variable RECONFIG_BOOT is set up.
458  */
459 static void
check_reconfig_state()460 check_reconfig_state()
461 {
462 	struct stat sb;
463 
464 	if (s_stat("/reconfigure", &sb) == 0) {
465 		(void) modctl(MODDEVNAME, MODDEVNAME_RECONFIG, 0);
466 	}
467 }
468 
469 static void
modctl_sysavail()470 modctl_sysavail()
471 {
472 	/*
473 	 * Inform /dev that system is available, that
474 	 * implicit reconfig can now be performed.
475 	 */
476 	(void) modctl(MODDEVNAME, MODDEVNAME_SYSAVAIL, 0);
477 }
478 
479 static void
set_lock_root(void)480 set_lock_root(void)
481 {
482 	struct stat sb;
483 	char *lock_root;
484 	size_t len;
485 
486 	lock_root = attr_root ? attr_root : root_dir;
487 
488 	len = strlen(lock_root) + strlen(ETCDEV) + 1;
489 	etc_dev_dir = s_malloc(len);
490 	(void) snprintf(etc_dev_dir, len, "%s%s", lock_root, ETCDEV);
491 
492 	if (s_stat(etc_dev_dir, &sb) != 0) {
493 		s_mkdirp(etc_dev_dir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
494 	} else if (!S_ISDIR(sb.st_mode)) {
495 		err_print(NOT_DIR, etc_dev_dir);
496 		devfsadm_exit(1);
497 		/*NOTREACHED*/
498 	}
499 }
500 
501 
502 /*
503  * Parse arguments for all 6 programs handled from devfsadm.
504  */
505 static void
parse_args(int argc,char * argv[])506 parse_args(int argc, char *argv[])
507 {
508 	char opt;
509 	char get_linkcompat_opts = FALSE;
510 	char *compat_class;
511 	int num_aliases = 0;
512 	int len;
513 	int retval;
514 	int config = TRUE;
515 	int bind = FALSE;
516 	int force_flag = FALSE;
517 	struct aliases *ap = NULL;
518 	struct aliases *a_head = NULL;
519 	struct aliases *a_tail = NULL;
520 	struct modconfig mc;
521 
522 	(void) bzero(&mc, sizeof (mc));
523 
524 	if (strcmp(prog, DISKS) == 0) {
525 		compat_class = "disk";
526 		get_linkcompat_opts = TRUE;
527 
528 	} else if (strcmp(prog, TAPES) == 0) {
529 		compat_class = "tape";
530 		get_linkcompat_opts = TRUE;
531 
532 	} else if (strcmp(prog, PORTS) == 0) {
533 		compat_class = "port";
534 		get_linkcompat_opts = TRUE;
535 
536 	} else if (strcmp(prog, AUDLINKS) == 0) {
537 		compat_class = "audio";
538 		get_linkcompat_opts = TRUE;
539 
540 	} else if (strcmp(prog, DEVLINKS) == 0) {
541 		devlinktab_file = DEVLINKTAB_FILE;
542 
543 		build_devices = FALSE;
544 		load_attach_drv = FALSE;
545 
546 		while ((opt = getopt(argc, argv, "dnr:st:vV:")) != EOF) {
547 			switch (opt) {
548 			case 'd':
549 				file_mods = FALSE;
550 				flush_path_to_inst_enable = FALSE;
551 				devlinks_debug = TRUE;
552 				break;
553 			case 'n':
554 				/* prevent driver loading and deferred attach */
555 				load_attach_drv = FALSE;
556 				break;
557 			case 'r':
558 				set_root_devices_dev_dir(optarg);
559 				if (zone_pathcheck(root_dir) !=
560 				    DEVFSADM_SUCCESS)
561 					devfsadm_exit(1);
562 					/*NOTREACHED*/
563 				break;
564 			case 's':
565 				/*
566 				 * suppress.  don't create/remove links/nodes
567 				 * useful with -v or -V
568 				 */
569 				file_mods = FALSE;
570 				flush_path_to_inst_enable = FALSE;
571 				break;
572 			case 't':
573 				/* supply a non-default table file */
574 				devlinktab_file = optarg;
575 				break;
576 			case 'v':
577 				/* documented verbose flag */
578 				add_verbose_id(VERBOSE_MID);
579 				break;
580 			case 'V':
581 				/* undocumented for extra verbose levels */
582 				add_verbose_id(optarg);
583 				break;
584 			default:
585 				usage();
586 				break;
587 			}
588 		}
589 
590 		if (optind < argc) {
591 			usage();
592 		}
593 
594 	} else if (strcmp(prog, DRVCONFIG) == 0) {
595 		int update_only = 0;
596 		build_dev = FALSE;
597 
598 		while ((opt =
599 		    getopt(argc, argv, "a:bc:dfi:m:np:R:r:suvV:x")) != EOF) {
600 			switch (opt) {
601 			case 'a':
602 				ap = calloc(sizeof (struct aliases), 1);
603 				ap->a_name = dequote(optarg);
604 				len = strlen(ap->a_name) + 1;
605 				if (len > MAXMODCONFNAME) {
606 					err_print(ALIAS_TOO_LONG,
607 					    MAXMODCONFNAME, ap->a_name);
608 					devfsadm_exit(1);
609 					/*NOTREACHED*/
610 				}
611 				ap->a_len = len;
612 				if (a_tail == NULL) {
613 					a_head = ap;
614 				} else {
615 					a_tail->a_next = ap;
616 				}
617 				a_tail = ap;
618 				num_aliases++;
619 				bind = TRUE;
620 				break;
621 			case 'b':
622 				bind = TRUE;
623 				break;
624 			case 'c':
625 				(void) strcpy(mc.drvclass, optarg);
626 				break;
627 			case 'd':
628 				/*
629 				 * need to keep for compatibility, but
630 				 * do nothing.
631 				 */
632 				break;
633 			case 'f':
634 				force_flag = TRUE;
635 				break;
636 			case 'i':
637 				single_drv = TRUE;
638 				(void) strcpy(mc.drvname, optarg);
639 				driver = s_strdup(optarg);
640 				break;
641 			case 'm':
642 				mc.major = atoi(optarg);
643 				break;
644 			case 'n':
645 				/* prevent driver loading and deferred attach */
646 				load_attach_drv = FALSE;
647 				break;
648 			case 'p':
649 				/* specify alternate path_to_inst file */
650 				inst_file = s_strdup(optarg);
651 				break;
652 			case 'R':
653 				/*
654 				 * Private flag for suninstall to populate
655 				 * device information on the installed root.
656 				 */
657 				root_dir = s_strdup(optarg);
658 				if (zone_pathcheck(root_dir) !=
659 				    DEVFSADM_SUCCESS)
660 				devfsadm_exit(devfsadm_copy());
661 				/*NOTREACHED*/
662 				break;
663 			case 'r':
664 				devices_dir = s_strdup(optarg);
665 				if (zone_pathcheck(devices_dir) !=
666 				    DEVFSADM_SUCCESS)
667 					devfsadm_exit(1);
668 					/*NOTREACHED*/
669 				break;
670 			case 's':
671 				/*
672 				 * suppress.  don't create nodes
673 				 * useful with -v or -V
674 				 */
675 				file_mods = FALSE;
676 				flush_path_to_inst_enable = FALSE;
677 				break;
678 			case 'u':
679 				/*
680 				 * Invoked via update_drv(1m) to update
681 				 * the kernel's driver/alias binding
682 				 * when removing one or more aliases.
683 				 */
684 				config = FALSE;
685 				break;
686 			case 'v':
687 				/* documented verbose flag */
688 				add_verbose_id(VERBOSE_MID);
689 				break;
690 			case 'V':
691 				/* undocumented for extra verbose levels */
692 				add_verbose_id(optarg);
693 				break;
694 			case 'x':
695 				update_only = 1;
696 				break;
697 			default:
698 				usage();
699 			}
700 		}
701 
702 		if (optind < argc) {
703 			usage();
704 		}
705 
706 		if (bind == TRUE) {
707 			if ((mc.major == -1) || (mc.drvname[0] == '\0')) {
708 				err_print(MAJOR_AND_B_FLAG);
709 				devfsadm_exit(1);
710 				/*NOTREACHED*/
711 			}
712 			mc.flags = 0;
713 			if (force_flag)
714 				mc.flags |= MOD_UNBIND_OVERRIDE;
715 			if (update_only)
716 				mc.flags |= MOD_ADDMAJBIND_UPDATE;
717 			mc.num_aliases = num_aliases;
718 			mc.ap = a_head;
719 			retval =  modctl((config == TRUE) ? MODADDMAJBIND :
720 			    MODREMDRVALIAS, NULL, (caddr_t)&mc);
721 			if (retval < 0) {
722 				err_print((config == TRUE) ? MODCTL_ADDMAJBIND :
723 				    MODCTL_REMMAJBIND);
724 			}
725 			devfsadm_exit(retval);
726 			/*NOTREACHED*/
727 		}
728 
729 	} else if ((strcmp(prog, DEVFSADM) == 0) ||
730 	    (strcmp(prog, DEVFSADMD) == 0)) {
731 		char *zonename = NULL;
732 		int init_drvconf = 0;
733 		int init_perm = 0;
734 		int public_mode = 0;
735 		int init_sysavail = 0;
736 
737 		if (strcmp(prog, DEVFSADMD) == 0) {
738 			daemon_mode = TRUE;
739 		}
740 
741 		devlinktab_file = DEVLINKTAB_FILE;
742 
743 		while ((opt = getopt(argc, argv,
744 		    "a:Cc:deIi:l:np:PR:r:sSt:uvV:x:")) != EOF) {
745 			if (opt == 'I' || opt == 'P' || opt == 'S') {
746 				if (public_mode)
747 					usage();
748 			} else {
749 				if (init_perm || init_drvconf || init_sysavail)
750 					usage();
751 				public_mode = 1;
752 			}
753 			switch (opt) {
754 			case 'a':
755 				attr_root = s_strdup(optarg);
756 				break;
757 			case 'C':
758 				cleanup = TRUE;
759 				break;
760 			case 'c':
761 				num_classes++;
762 				classes = s_realloc(classes,
763 				    num_classes * sizeof (char *));
764 				classes[num_classes - 1] = optarg;
765 				break;
766 			case 'd':
767 				if (daemon_mode == FALSE) {
768 					/*
769 					 * Device allocation to be disabled.
770 					 */
771 					devalloc_flag = DA_OFF;
772 					build_dev = FALSE;
773 				}
774 				break;
775 			case 'e':
776 				if (daemon_mode == FALSE) {
777 					/*
778 					 * Device allocation to be enabled.
779 					 */
780 					devalloc_flag = DA_ON;
781 					build_dev = FALSE;
782 				}
783 				break;
784 			case 'I':	/* update kernel driver.conf cache */
785 				if (daemon_mode == TRUE)
786 					usage();
787 				init_drvconf = 1;
788 				break;
789 			case 'i':
790 				single_drv = TRUE;
791 				driver = s_strdup(optarg);
792 				break;
793 			case 'l':
794 				/* specify an alternate module load path */
795 				module_dirs = s_strdup(optarg);
796 				break;
797 			case 'n':
798 				/* prevent driver loading and deferred attach */
799 				load_attach_drv = FALSE;
800 				break;
801 			case 'p':
802 				/* specify alternate path_to_inst file */
803 				inst_file = s_strdup(optarg);
804 				break;
805 			case 'P':
806 				if (daemon_mode == TRUE)
807 					usage();
808 				/* load minor_perm and device_policy */
809 				init_perm = 1;
810 				break;
811 			case 'R':
812 				/*
813 				 * Private flag for suninstall to populate
814 				 * device information on the installed root.
815 				 */
816 				root_dir = s_strdup(optarg);
817 				devfsadm_exit(devfsadm_copy());
818 				/*NOTREACHED*/
819 				break;
820 			case 'r':
821 				set_root_devices_dev_dir(optarg);
822 				break;
823 			case 's':
824 				/*
825 				 * suppress. don't create/remove links/nodes
826 				 * useful with -v or -V
827 				 */
828 				file_mods = FALSE;
829 				flush_path_to_inst_enable = FALSE;
830 				break;
831 			case 'S':
832 				if (daemon_mode == TRUE)
833 					usage();
834 				init_sysavail = 1;
835 				break;
836 			case 't':
837 				devlinktab_file = optarg;
838 				break;
839 			case 'u':	/* complete configuration after */
840 					/* adding a driver update-only */
841 				if (daemon_mode == TRUE)
842 					usage();
843 				update_all_drivers = TRUE;
844 				break;
845 			case 'v':
846 				/* documented verbose flag */
847 				add_verbose_id(VERBOSE_MID);
848 				break;
849 			case 'V':
850 				/* undocumented: specify verbose lvl */
851 				add_verbose_id(optarg);
852 				break;
853 			case 'x':
854 				/*
855 				 * x is the "private switch" option.  The
856 				 * goal is to not suck up all the other
857 				 * option letters.
858 				 */
859 				if (strcmp(optarg, "update_devlinksdb") == 0) {
860 					update_database = TRUE;
861 				} else if (strcmp(optarg, "no_dev") == 0) {
862 					/* don't build /dev */
863 					build_dev = FALSE;
864 				} else if (strcmp(optarg, "no_devices") == 0) {
865 					/* don't build /devices */
866 					build_devices = FALSE;
867 				} else if (strcmp(optarg, "no_p2i") == 0) {
868 					/* don't flush path_to_inst */
869 					flush_path_to_inst_enable = FALSE;
870 				} else if (strcmp(optarg, "use_dicache") == 0) {
871 					use_snapshot_cache = TRUE;
872 				} else {
873 					usage();
874 				}
875 				break;
876 			default:
877 				usage();
878 				break;
879 			}
880 		}
881 		if (optind < argc) {
882 			usage();
883 		}
884 
885 		/*
886 		 * We're not in zone mode; Check to see if the rootpath
887 		 * collides with any zonepaths.
888 		 */
889 		if (zonename == NULL) {
890 			if (zone_pathcheck(root_dir) != DEVFSADM_SUCCESS)
891 				devfsadm_exit(1);
892 				/*NOTREACHED*/
893 		}
894 
895 		if (init_drvconf || init_perm || init_sysavail) {
896 			/*
897 			 * Load minor perm before force-loading drivers
898 			 * so the correct permissions are picked up.
899 			 */
900 			if (init_perm) {
901 				check_reconfig_state();
902 				load_dev_acl();
903 			}
904 			if (init_drvconf)
905 				update_drvconf((major_t)-1, 0);
906 			if (init_sysavail)
907 				modctl_sysavail();
908 			devfsadm_exit(0);
909 			/*NOTREACHED*/
910 		}
911 	}
912 
913 
914 	if (get_linkcompat_opts == TRUE) {
915 
916 		build_devices = FALSE;
917 		load_attach_drv = FALSE;
918 		num_classes++;
919 		classes = s_realloc(classes, num_classes *
920 		    sizeof (char *));
921 		classes[num_classes - 1] = compat_class;
922 
923 		while ((opt = getopt(argc, argv, "Cnr:svV:")) != EOF) {
924 			switch (opt) {
925 			case 'C':
926 				cleanup = TRUE;
927 				break;
928 			case 'n':
929 				/* prevent driver loading or deferred attach */
930 				load_attach_drv = FALSE;
931 				break;
932 			case 'r':
933 				set_root_devices_dev_dir(optarg);
934 				if (zone_pathcheck(root_dir) !=
935 				    DEVFSADM_SUCCESS)
936 					devfsadm_exit(1);
937 					/*NOTREACHED*/
938 				break;
939 			case 's':
940 				/* suppress.  don't create/remove links/nodes */
941 				/* useful with -v or -V */
942 				file_mods = FALSE;
943 				flush_path_to_inst_enable = FALSE;
944 				break;
945 			case 'v':
946 				/* documented verbose flag */
947 				add_verbose_id(VERBOSE_MID);
948 				break;
949 			case 'V':
950 				/* undocumented for extra verbose levels */
951 				add_verbose_id(optarg);
952 				break;
953 			default:
954 				usage();
955 			}
956 		}
957 		if (optind < argc) {
958 			usage();
959 		}
960 	}
961 	set_lock_root();
962 }
963 
964 void
usage(void)965 usage(void)
966 {
967 	if (strcmp(prog, DEVLINKS) == 0) {
968 		err_print(DEVLINKS_USAGE);
969 	} else if (strcmp(prog, DRVCONFIG) == 0) {
970 		err_print(DRVCONFIG_USAGE);
971 	} else if ((strcmp(prog, DEVFSADM) == 0) ||
972 	    (strcmp(prog, DEVFSADMD) == 0)) {
973 		err_print(DEVFSADM_USAGE);
974 	} else {
975 		err_print(COMPAT_LINK_USAGE);
976 	}
977 
978 	devfsadm_exit(1);
979 	/*NOTREACHED*/
980 }
981 
982 static void
devi_tree_walk(struct dca_impl * dcip,int flags,char * ev_subclass)983 devi_tree_walk(struct dca_impl *dcip, int flags, char *ev_subclass)
984 {
985 	char *msg, *name;
986 	struct mlist	mlist = {0};
987 	di_node_t	node;
988 
989 	vprint(CHATTY_MID, "devi_tree_walk: root=%s, minor=%s, driver=%s,"
990 	    " error=%d, flags=%u\n", dcip->dci_root,
991 	    dcip->dci_minor ? dcip->dci_minor : "<NULL>",
992 	    dcip->dci_driver ? dcip->dci_driver : "<NULL>", dcip->dci_error,
993 	    dcip->dci_flags);
994 
995 	assert(dcip->dci_root);
996 
997 	if (dcip->dci_flags & DCA_LOAD_DRV) {
998 		node = di_init_driver(dcip->dci_driver, flags);
999 		msg = DRIVER_FAILURE;
1000 		name = dcip->dci_driver;
1001 	} else {
1002 		node = di_init(dcip->dci_root, flags);
1003 		msg = DI_INIT_FAILED;
1004 		name = dcip->dci_root;
1005 	}
1006 
1007 	if (node == DI_NODE_NIL) {
1008 		dcip->dci_error = errno;
1009 		/*
1010 		 * Rapid hotplugging (commonly seen during USB testing),
1011 		 * may remove a device before the create event for it
1012 		 * has been processed. To prevent alarming users with
1013 		 * a superfluous message, we suppress error messages
1014 		 * for ENXIO and hotplug.
1015 		 */
1016 		if (!(errno == ENXIO && (dcip->dci_flags & DCA_HOT_PLUG)))
1017 			err_print(msg, name, strerror(dcip->dci_error));
1018 		return;
1019 	}
1020 
1021 	if (dcip->dci_flags & DCA_FLUSH_PATHINST)
1022 		flush_path_to_inst();
1023 
1024 	dcip->dci_arg = &mlist;
1025 	devi_root_node = node;	/* protected by lock_dev() */
1026 
1027 	vprint(CHATTY_MID, "walking device tree\n");
1028 
1029 	(void) di_walk_minor(node, NULL, DI_CHECK_ALIAS, dcip,
1030 	    check_minor_type);
1031 
1032 	process_deferred_links(dcip, DCA_CREATE_LINK);
1033 
1034 	dcip->dci_arg = NULL;
1035 
1036 	/*
1037 	 * Finished creating devfs files and dev links.
1038 	 * Log sysevent.
1039 	 */
1040 	if (ev_subclass)
1041 		build_and_enq_event(EC_DEV_ADD, ev_subclass, dcip->dci_root,
1042 		    node, dcip->dci_minor);
1043 
1044 	/* Add new device to device allocation database */
1045 	if (system_labeled && update_devdb) {
1046 		_update_devalloc_db(&devlist, 0, DA_ADD, NULL, root_dir);
1047 		update_devdb = 0;
1048 	}
1049 
1050 	devi_root_node = DI_NODE_NIL;	/* protected by lock_dev() */
1051 	di_fini(node);
1052 }
1053 
1054 static void
process_deferred_links(struct dca_impl * dcip,int flags)1055 process_deferred_links(struct dca_impl *dcip, int flags)
1056 {
1057 	struct mlist	*dep;
1058 	struct minor	*mp, *smp;
1059 
1060 	vprint(CHATTY_MID, "processing deferred links\n");
1061 
1062 	dep = dcip->dci_arg;
1063 
1064 	/*
1065 	 * The list head is not used during the deferred create phase
1066 	 */
1067 	dcip->dci_arg = NULL;
1068 
1069 	assert(dep);
1070 	assert((dep->head == NULL) ^ (dep->tail != NULL));
1071 	assert(flags == DCA_FREE_LIST || flags == DCA_CREATE_LINK);
1072 
1073 	for (smp = NULL, mp = dep->head; mp; mp = mp->next) {
1074 		if (flags == DCA_CREATE_LINK)
1075 			(void) check_minor_type(mp->node, mp->minor, dcip);
1076 		free(smp);
1077 		smp = mp;
1078 	}
1079 
1080 	free(smp);
1081 }
1082 
1083 /*
1084  * Called in non-daemon mode to take a snap shot of the devinfo tree.
1085  * Then it calls the appropriate functions to build /devices and /dev.
1086  * It also flushes path_to_inst.
1087  * Except in the devfsadm -i (single driver case), the flags used by devfsadm
1088  * needs to match DI_CACHE_SNAPSHOT_FLAGS. That will make DINFOCACHE snapshot
1089  * updated.
1090  */
1091 void
process_devinfo_tree()1092 process_devinfo_tree()
1093 {
1094 	uint_t		flags;
1095 	struct dca_impl	dci;
1096 	char		name[MAXNAMELEN];
1097 	char		*fcn = "process_devinfo_tree: ";
1098 
1099 	vprint(CHATTY_MID, "%senter\n", fcn);
1100 
1101 	dca_impl_init("/", NULL, &dci);
1102 
1103 	lock_dev();
1104 
1105 	/*
1106 	 * Update kernel driver.conf cache when devfsadm/drvconfig
1107 	 * is invoked to build /devices and /dev.
1108 	 */
1109 	if (update_all_drivers || load_attach_drv) {
1110 		update_drvconf((major_t)-1,
1111 		    update_all_drivers ? MOD_LOADDRVCONF_RECONF : 0);
1112 	}
1113 
1114 	if (single_drv == TRUE) {
1115 		/*
1116 		 * load a single driver, but walk the entire devinfo tree
1117 		 */
1118 		if (load_attach_drv == FALSE)
1119 			err_print(DRV_LOAD_REQD);
1120 
1121 		vprint(CHATTY_MID, "%sattaching driver (%s)\n", fcn, driver);
1122 
1123 		dci.dci_flags |= DCA_LOAD_DRV;
1124 		(void) snprintf(name, sizeof (name), "%s", driver);
1125 		dci.dci_driver = name;
1126 		flags = DINFOCPYALL | DINFOPATH;
1127 
1128 	} else if (load_attach_drv == TRUE) {
1129 		/*
1130 		 * Load and attach all drivers, then walk the entire tree.
1131 		 * If the cache flag is set, use DINFOCACHE to get cached
1132 		 * data.
1133 		 */
1134 		if (use_snapshot_cache == TRUE) {
1135 			flags = DINFOCACHE;
1136 			vprint(CHATTY_MID, "%susing snapshot cache\n", fcn);
1137 		} else {
1138 			vprint(CHATTY_MID, "%sattaching all drivers\n", fcn);
1139 			flags = DI_CACHE_SNAPSHOT_FLAGS;
1140 			if (cleanup) {
1141 				/*
1142 				 * remove dangling entries from /etc/devices
1143 				 * files.
1144 				 */
1145 				flags |= DINFOCLEANUP;
1146 			}
1147 		}
1148 	} else {
1149 		/*
1150 		 * For devlinks, disks, ports, tapes and devfsadm -n,
1151 		 * just need to take a snapshot with active devices.
1152 		 */
1153 		vprint(CHATTY_MID, "%staking snapshot of active devices\n",
1154 		    fcn);
1155 		flags = DINFOCPYALL;
1156 	}
1157 
1158 	if (((load_attach_drv == TRUE) || (single_drv == TRUE)) &&
1159 	    (build_devices == TRUE)) {
1160 		dci.dci_flags |= DCA_FLUSH_PATHINST;
1161 	}
1162 
1163 	/* handle pre-cleanup operations desired by the modules. */
1164 	pre_and_post_cleanup(RM_PRE);
1165 
1166 	devi_tree_walk(&dci, flags, NULL);
1167 
1168 	if (dci.dci_error) {
1169 		devfsadm_exit(1);
1170 		/*NOTREACHED*/
1171 	}
1172 
1173 	/* handle post-cleanup operations desired by the modules. */
1174 	pre_and_post_cleanup(RM_POST);
1175 
1176 	unlock_dev(SYNC_STATE);
1177 }
1178 
1179 /*ARGSUSED*/
1180 static void
print_cache_signal(int signo)1181 print_cache_signal(int signo)
1182 {
1183 	if (signal(SIGUSR1, print_cache_signal) == SIG_ERR) {
1184 		err_print("signal SIGUSR1 failed: %s\n", strerror(errno));
1185 		devfsadm_exit(1);
1186 		/*NOTREACHED*/
1187 	}
1188 }
1189 
1190 static void
revoke_lookup_door(void)1191 revoke_lookup_door(void)
1192 {
1193 	if (lookup_door_fd != -1) {
1194 		if (door_revoke(lookup_door_fd) == -1) {
1195 			err_print("door_revoke of %s failed - %s\n",
1196 			    lookup_door_path, strerror(errno));
1197 		}
1198 	}
1199 }
1200 
1201 /*ARGSUSED*/
1202 static void
catch_exit(int signo)1203 catch_exit(int signo)
1204 {
1205 	revoke_lookup_door();
1206 }
1207 
1208 /*
1209  * Register with eventd for messages. Create doors for synchronous
1210  * link creation.
1211  */
1212 static void
daemon_update(void)1213 daemon_update(void)
1214 {
1215 	int fd;
1216 	char *fcn = "daemon_update: ";
1217 	char door_file[MAXPATHLEN];
1218 	const char *subclass_list;
1219 	sysevent_handle_t *sysevent_hp;
1220 	vprint(CHATTY_MID, "%senter\n", fcn);
1221 
1222 	if (signal(SIGUSR1, print_cache_signal) == SIG_ERR) {
1223 		err_print("signal SIGUSR1 failed: %s\n", strerror(errno));
1224 		devfsadm_exit(1);
1225 		/*NOTREACHED*/
1226 	}
1227 	if (signal(SIGTERM, catch_exit) == SIG_ERR) {
1228 		err_print("signal SIGTERM failed: %s\n", strerror(errno));
1229 		devfsadm_exit(1);
1230 		/*NOTREACHED*/
1231 	}
1232 
1233 	if (snprintf(door_file, sizeof (door_file),
1234 	    "%s%s", attr_root ? attr_root : root_dir, DEVFSADM_SERVICE_DOOR)
1235 	    >= sizeof (door_file)) {
1236 		err_print("update_daemon failed to open sysevent service "
1237 		    "door\n");
1238 		devfsadm_exit(1);
1239 		/*NOTREACHED*/
1240 	}
1241 	if ((sysevent_hp = sysevent_open_channel_alt(
1242 	    door_file)) == NULL) {
1243 		err_print(CANT_CREATE_DOOR,
1244 		    door_file, strerror(errno));
1245 		devfsadm_exit(1);
1246 		/*NOTREACHED*/
1247 	}
1248 	if (sysevent_bind_subscriber(sysevent_hp, event_handler) != 0) {
1249 		err_print(CANT_CREATE_DOOR,
1250 		    door_file, strerror(errno));
1251 		(void) sysevent_close_channel(sysevent_hp);
1252 		devfsadm_exit(1);
1253 		/*NOTREACHED*/
1254 	}
1255 	subclass_list = EC_SUB_ALL;
1256 	if (sysevent_register_event(sysevent_hp, EC_ALL, &subclass_list, 1)
1257 	    != 0) {
1258 		err_print(CANT_CREATE_DOOR,
1259 		    door_file, strerror(errno));
1260 		(void) sysevent_unbind_subscriber(sysevent_hp);
1261 		(void) sysevent_close_channel(sysevent_hp);
1262 		devfsadm_exit(1);
1263 		/*NOTREACHED*/
1264 	}
1265 	if (snprintf(door_file, sizeof (door_file), "%s/%s",
1266 	    etc_dev_dir, DEVFSADM_SYNCH_DOOR) >= sizeof (door_file)) {
1267 		err_print(CANT_CREATE_DOOR, DEVFSADM_SYNCH_DOOR,
1268 		    strerror(ENAMETOOLONG));
1269 		devfsadm_exit(1);
1270 		/*NOTREACHED*/
1271 	}
1272 
1273 	(void) s_unlink(door_file);
1274 	if ((fd = open(door_file, O_RDWR | O_CREAT, SYNCH_DOOR_PERMS)) == -1) {
1275 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1276 		devfsadm_exit(1);
1277 		/*NOTREACHED*/
1278 	}
1279 	(void) close(fd);
1280 
1281 	if ((fd = door_create(sync_handler, NULL,
1282 	    DOOR_REFUSE_DESC | DOOR_NO_CANCEL)) == -1) {
1283 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1284 		(void) s_unlink(door_file);
1285 		devfsadm_exit(1);
1286 		/*NOTREACHED*/
1287 	}
1288 
1289 	if (fattach(fd, door_file) == -1) {
1290 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1291 		(void) s_unlink(door_file);
1292 		devfsadm_exit(1);
1293 		/*NOTREACHED*/
1294 	}
1295 
1296 	/*
1297 	 * devname_lookup_door
1298 	 */
1299 	if (snprintf(door_file, sizeof (door_file), "%s/%s",
1300 	    etc_dev_dir, DEVNAME_LOOKUP_DOOR) >= sizeof (door_file)) {
1301 		err_print(CANT_CREATE_DOOR, DEVNAME_LOOKUP_DOOR,
1302 		    strerror(ENAMETOOLONG));
1303 		devfsadm_exit(1);
1304 		/*NOTREACHED*/
1305 	}
1306 
1307 	(void) s_unlink(door_file);
1308 	if ((fd = open(door_file, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR)) == -1) {
1309 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1310 		devfsadm_exit(1);
1311 		/*NOTREACHED*/
1312 	}
1313 	(void) close(fd);
1314 
1315 	if ((fd = door_create(devname_lookup_handler, NULL,
1316 	    DOOR_REFUSE_DESC)) == -1) {
1317 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1318 		(void) s_unlink(door_file);
1319 		devfsadm_exit(1);
1320 		/*NOTREACHED*/
1321 	}
1322 
1323 	(void) fdetach(door_file);
1324 	lookup_door_path = s_strdup(door_file);
1325 retry:
1326 	if (fattach(fd, door_file) == -1) {
1327 		if (errno == EBUSY)
1328 			goto retry;
1329 		err_print(CANT_CREATE_DOOR, door_file, strerror(errno));
1330 		(void) s_unlink(door_file);
1331 		devfsadm_exit(1);
1332 		/*NOTREACHED*/
1333 	}
1334 	lookup_door_fd = fd;
1335 
1336 	/* pass down the door name to kernel for door_ki_open */
1337 	if (devname_kcall(MODDEVNAME_LOOKUPDOOR, (void *)door_file) != 0)
1338 		err_print(DEVNAME_CONTACT_FAILED, strerror(errno));
1339 
1340 	vprint(CHATTY_MID, "%spausing\n", fcn);
1341 	for (;;) {
1342 		(void) pause();
1343 	}
1344 }
1345 
1346 /*ARGSUSED*/
1347 static void
sync_handler(void * cookie,char * ap,size_t asize,door_desc_t * dp,uint_t ndesc)1348 sync_handler(void *cookie, char *ap, size_t asize,
1349     door_desc_t *dp, uint_t ndesc)
1350 {
1351 	door_cred_t	dcred;
1352 	struct dca_off	*dcp, rdca;
1353 	struct dca_impl dci;
1354 
1355 	/*
1356 	 * Must be root to make this call
1357 	 * If caller is not root, don't touch its data.
1358 	 */
1359 	if (door_cred(&dcred) != 0 || dcred.dc_euid != 0) {
1360 		dcp = &rdca;
1361 		dcp->dca_error = EPERM;
1362 		goto out;
1363 	}
1364 
1365 	assert(ap);
1366 	assert(asize == sizeof (*dcp));
1367 
1368 	dcp = (void *)ap;
1369 
1370 	/*
1371 	 * Root is always present and is the first component of "name" member
1372 	 */
1373 	assert(dcp->dca_root == 0);
1374 
1375 	/*
1376 	 * The structure passed in by the door_client uses offsets
1377 	 * instead of pointers to work across address space boundaries.
1378 	 * Now copy the data into a structure (dca_impl) which uses
1379 	 * pointers.
1380 	 */
1381 	dci.dci_root = &dcp->dca_name[dcp->dca_root];
1382 	dci.dci_minor = dcp->dca_minor ? &dcp->dca_name[dcp->dca_minor] : NULL;
1383 	dci.dci_driver =
1384 	    dcp->dca_driver ? &dcp->dca_name[dcp->dca_driver] : NULL;
1385 	dci.dci_error = 0;
1386 	dci.dci_flags = dcp->dca_flags | (dci.dci_driver ? DCA_LOAD_DRV : 0);
1387 	dci.dci_arg = NULL;
1388 
1389 	lock_dev();
1390 	devi_tree_walk(&dci, DINFOCPYALL, NULL);
1391 	dcp->dca_error = dci.dci_error;
1392 
1393 	if (dcp->dca_flags & DCA_DEVLINK_SYNC)
1394 		unlock_dev(SYNC_STATE);
1395 	else
1396 		unlock_dev(CACHE_STATE);
1397 
1398 out:	(void) door_return((char *)dcp, sizeof (*dcp), NULL, 0);
1399 }
1400 
1401 static void
lock_dev(void)1402 lock_dev(void)
1403 {
1404 	vprint(CHATTY_MID, "lock_dev(): entered\n");
1405 
1406 	if (build_dev == FALSE)
1407 		return;
1408 
1409 	/* lockout other threads from /dev */
1410 	while (sema_wait(&dev_sema) != 0)
1411 		;
1412 
1413 	/*
1414 	 * Lock out other devfsadm processes from /dev.
1415 	 * If this wasn't the last process to run,
1416 	 * clear caches
1417 	 */
1418 	if (enter_dev_lock() != getpid()) {
1419 		invalidate_enumerate_cache();
1420 		rm_all_links_from_cache();
1421 		(void) di_devlink_close(&devlink_cache, DI_LINK_ERROR);
1422 
1423 		/* send any sysevents that were queued up. */
1424 		process_syseventq();
1425 	}
1426 
1427 	/*
1428 	 * (re)load the  reverse links database if not
1429 	 * already cached.
1430 	 */
1431 	if (devlink_cache == NULL)
1432 		devlink_cache = di_devlink_open(root_dir, 0);
1433 
1434 	/*
1435 	 * If modules were unloaded, reload them.  Also use module status
1436 	 * as an indication that we should check to see if other binding
1437 	 * files need to be reloaded.
1438 	 */
1439 	if (module_head == NULL) {
1440 		load_modules();
1441 		read_minor_perm_file();
1442 		read_driver_aliases_file();
1443 		read_devlinktab_file();
1444 		read_logindevperm_file();
1445 		read_enumerate_file();
1446 	}
1447 
1448 	if (module_head != NULL)
1449 		return;
1450 
1451 	if (strcmp(prog, DEVLINKS) == 0) {
1452 		if (devlinktab_list == NULL) {
1453 			err_print(NO_LINKTAB, devlinktab_file);
1454 			err_print(NO_MODULES, module_dirs);
1455 			err_print(ABORTING);
1456 			devfsadm_exit(1);
1457 			/*NOTREACHED*/
1458 		}
1459 	} else {
1460 		err_print(NO_MODULES, module_dirs);
1461 		if (strcmp(prog, DEVFSADM) == 0) {
1462 			err_print(MODIFY_PATH);
1463 		}
1464 	}
1465 }
1466 
1467 /*
1468  * Unlock the device.  If we are processing a CACHE_STATE call, we signal a
1469  * minor_fini_thread delayed SYNC_STATE at the end of the call.  If we are
1470  * processing a SYNC_STATE call, we cancel any minor_fini_thread SYNC_STATE
1471  * at both the start and end of the call since we will be doing the SYNC_STATE.
1472  */
1473 static void
unlock_dev(int flag)1474 unlock_dev(int flag)
1475 {
1476 	assert(flag == SYNC_STATE || flag == CACHE_STATE);
1477 
1478 	vprint(CHATTY_MID, "unlock_dev(): entered\n");
1479 
1480 	/* If we are starting a SYNC_STATE, cancel minor_fini_thread SYNC */
1481 	if (flag == SYNC_STATE) {
1482 		(void) mutex_lock(&minor_fini_mutex);
1483 		minor_fini_canceled = TRUE;
1484 		minor_fini_delayed = FALSE;
1485 		(void) mutex_unlock(&minor_fini_mutex);
1486 	}
1487 
1488 	if (build_dev == FALSE)
1489 		return;
1490 
1491 	if (devlink_cache == NULL) {
1492 		err_print(NO_DEVLINK_CACHE);
1493 	}
1494 	assert(devlink_cache);
1495 
1496 	if (flag == SYNC_STATE) {
1497 		unload_modules();
1498 		if (update_database)
1499 			(void) di_devlink_update(devlink_cache);
1500 		(void) di_devlink_close(&devlink_cache, 0);
1501 
1502 		/*
1503 		 * now that the devlinks db cache has been flushed, it is safe
1504 		 * to send any sysevents that were queued up.
1505 		 */
1506 		process_syseventq();
1507 	}
1508 
1509 	exit_dev_lock(0);
1510 
1511 	(void) mutex_lock(&minor_fini_mutex);
1512 	if (flag == SYNC_STATE) {
1513 		/* We did a SYNC_STATE, cancel minor_fini_thread SYNC */
1514 		minor_fini_canceled = TRUE;
1515 		minor_fini_delayed = FALSE;
1516 	} else {
1517 		/* We did a CACHE_STATE, start delayed minor_fini_thread SYNC */
1518 		minor_fini_canceled = FALSE;
1519 		minor_fini_delayed = TRUE;
1520 		(void) cond_signal(&minor_fini_cv);
1521 	}
1522 	(void) mutex_unlock(&minor_fini_mutex);
1523 
1524 	(void) sema_post(&dev_sema);
1525 }
1526 
1527 /*
1528  * Check that if -r is set, it is not any part of a zone--- that is, that
1529  * the zonepath is not a substring of the root path.
1530  */
1531 static int
zone_pathcheck(char * checkpath)1532 zone_pathcheck(char *checkpath)
1533 {
1534 	void		*dlhdl = NULL;
1535 	char		*name;
1536 	char		root[MAXPATHLEN]; /* resolved devfsadm root path */
1537 	char		zroot[MAXPATHLEN]; /* zone root path */
1538 	char		rzroot[MAXPATHLEN]; /* resolved zone root path */
1539 	char		tmp[MAXPATHLEN];
1540 	FILE		*cookie;
1541 	int		err = DEVFSADM_SUCCESS;
1542 
1543 	if (checkpath[0] == '\0')
1544 		return (DEVFSADM_SUCCESS);
1545 
1546 	/*
1547 	 * Check if zones is available on this system.
1548 	 */
1549 	if ((dlhdl = dlopen(LIBZONECFG_PATH, RTLD_LAZY)) == NULL) {
1550 		return (DEVFSADM_SUCCESS);
1551 	}
1552 
1553 	bzero(root, sizeof (root));
1554 	if (resolvepath(checkpath, root, sizeof (root) - 1) == -1) {
1555 		/*
1556 		 * In this case the user has done "devfsadm -r" on some path
1557 		 * which does not yet exist, or we got some other misc. error.
1558 		 * We punt and don't resolve the path in this case.
1559 		 */
1560 		(void) strlcpy(root, checkpath, sizeof (root));
1561 	}
1562 
1563 	if (strlen(root) > 0 && (root[strlen(root) - 1] != '/')) {
1564 		(void) snprintf(tmp, sizeof (tmp), "%s/", root);
1565 		(void) strlcpy(root, tmp, sizeof (root));
1566 	}
1567 
1568 	cookie = setzoneent();
1569 	while ((name = getzoneent(cookie)) != NULL) {
1570 		/* Skip the global zone */
1571 		if (strcmp(name, GLOBAL_ZONENAME) == 0) {
1572 			free(name);
1573 			continue;
1574 		}
1575 
1576 		if (zone_get_zonepath(name, zroot, sizeof (zroot)) != Z_OK) {
1577 			free(name);
1578 			continue;
1579 		}
1580 
1581 		bzero(rzroot, sizeof (rzroot));
1582 		if (resolvepath(zroot, rzroot, sizeof (rzroot) - 1) == -1) {
1583 			/*
1584 			 * Zone path doesn't exist, or other misc error,
1585 			 * so we try using the non-resolved pathname.
1586 			 */
1587 			(void) strlcpy(rzroot, zroot, sizeof (rzroot));
1588 		}
1589 		if (strlen(rzroot) > 0 && (rzroot[strlen(rzroot) - 1] != '/')) {
1590 			(void) snprintf(tmp, sizeof (tmp), "%s/", rzroot);
1591 			(void) strlcpy(rzroot, tmp, sizeof (rzroot));
1592 		}
1593 
1594 		/*
1595 		 * Finally, the comparison.  If the zone root path is a
1596 		 * leading substring of the root path, fail.
1597 		 */
1598 		if (strncmp(rzroot, root, strlen(rzroot)) == 0) {
1599 			err_print(ZONE_PATHCHECK, root, name);
1600 			err = DEVFSADM_FAILURE;
1601 			free(name);
1602 			break;
1603 		}
1604 		free(name);
1605 	}
1606 	endzoneent(cookie);
1607 	(void) dlclose(dlhdl);
1608 	return (err);
1609 }
1610 
1611 /*
1612  *  Called by the daemon when it receives an event from the devfsadm SLM
1613  *  to syseventd.
1614  *
1615  *  The devfsadm SLM uses a private event channel for communication to
1616  *  devfsadmd set-up via private libsysevent interfaces.  This handler is
1617  *  used to bind to the devfsadmd channel for event delivery.
1618  *  The devfsadmd SLM insures single calls to this routine as well as
1619  *  synchronized event delivery.
1620  *
1621  */
1622 static void
event_handler(sysevent_t * ev)1623 event_handler(sysevent_t *ev)
1624 {
1625 	char *path;
1626 	char *minor;
1627 	char *subclass;
1628 	char *dev_ev_subclass;
1629 	char *driver_name;
1630 	nvlist_t *attr_list = NULL;
1631 	int err = 0;
1632 	int instance;
1633 	int branch_event = 0;
1634 
1635 	/*
1636 	 * If this is event-driven, then we cannot trust the static devlist
1637 	 * to be correct.
1638 	 */
1639 
1640 	event_driven = TRUE;
1641 	subclass = sysevent_get_subclass_name(ev);
1642 	vprint(EVENT_MID, "event_handler: %s id:0X%llx\n",
1643 	    subclass, sysevent_get_seq(ev));
1644 
1645 	if (strcmp(subclass, ESC_DEVFS_START) == 0) {
1646 		return;
1647 	}
1648 
1649 	/* Check if event is an instance modification */
1650 	if (strcmp(subclass, ESC_DEVFS_INSTANCE_MOD) == 0) {
1651 		devfs_instance_mod();
1652 		return;
1653 	}
1654 	if (sysevent_get_attr_list(ev, &attr_list) != 0) {
1655 		vprint(EVENT_MID, "event_handler: can not get attr list\n");
1656 		return;
1657 	}
1658 
1659 	if (strcmp(subclass, ESC_DEVFS_DEVI_ADD) == 0 ||
1660 	    strcmp(subclass, ESC_DEVFS_DEVI_REMOVE) == 0 ||
1661 	    strcmp(subclass, ESC_DEVFS_MINOR_CREATE) == 0 ||
1662 	    strcmp(subclass, ESC_DEVFS_MINOR_REMOVE) == 0) {
1663 		if ((err = nvlist_lookup_string(attr_list, DEVFS_PATHNAME,
1664 		    &path)) != 0)
1665 			goto out;
1666 
1667 		if (nvlist_lookup_string(attr_list, DEVFS_DEVI_CLASS,
1668 		    &dev_ev_subclass) != 0)
1669 			dev_ev_subclass = NULL;
1670 
1671 		if (nvlist_lookup_string(attr_list, DEVFS_DRIVER_NAME,
1672 		    &driver_name) != 0)
1673 			driver_name = NULL;
1674 
1675 		if (nvlist_lookup_int32(attr_list, DEVFS_INSTANCE,
1676 		    &instance) != 0)
1677 			instance = -1;
1678 
1679 		if (nvlist_lookup_int32(attr_list, DEVFS_BRANCH_EVENT,
1680 		    &branch_event) != 0)
1681 			branch_event = 0;
1682 
1683 		if (nvlist_lookup_string(attr_list, DEVFS_MINOR_NAME,
1684 		    &minor) != 0)
1685 			minor = NULL;
1686 
1687 		lock_dev();
1688 
1689 		if (strcmp(ESC_DEVFS_DEVI_ADD, subclass) == 0) {
1690 			add_minor_pathname(path, NULL, dev_ev_subclass);
1691 			if (branch_event) {
1692 				build_and_enq_event(EC_DEV_BRANCH,
1693 				    ESC_DEV_BRANCH_ADD, path, DI_NODE_NIL,
1694 				    NULL);
1695 			}
1696 
1697 		} else if (strcmp(ESC_DEVFS_MINOR_CREATE, subclass) == 0) {
1698 			add_minor_pathname(path, minor, dev_ev_subclass);
1699 
1700 		} else if (strcmp(ESC_DEVFS_MINOR_REMOVE, subclass) == 0) {
1701 			hot_cleanup(path, minor, dev_ev_subclass, driver_name,
1702 			    instance);
1703 
1704 		} else { /* ESC_DEVFS_DEVI_REMOVE */
1705 			hot_cleanup(path, NULL, dev_ev_subclass,
1706 			    driver_name, instance);
1707 			if (branch_event) {
1708 				build_and_enq_event(EC_DEV_BRANCH,
1709 				    ESC_DEV_BRANCH_REMOVE, path, DI_NODE_NIL,
1710 				    NULL);
1711 			}
1712 		}
1713 
1714 		unlock_dev(CACHE_STATE);
1715 
1716 	} else if (strcmp(subclass, ESC_DEVFS_BRANCH_ADD) == 0 ||
1717 	    strcmp(subclass, ESC_DEVFS_BRANCH_REMOVE) == 0) {
1718 		if ((err = nvlist_lookup_string(attr_list,
1719 		    DEVFS_PATHNAME, &path)) != 0)
1720 			goto out;
1721 
1722 		/* just log ESC_DEV_BRANCH... event */
1723 		if (strcmp(subclass, ESC_DEVFS_BRANCH_ADD) == 0)
1724 			dev_ev_subclass = ESC_DEV_BRANCH_ADD;
1725 		else
1726 			dev_ev_subclass = ESC_DEV_BRANCH_REMOVE;
1727 
1728 		lock_dev();
1729 		build_and_enq_event(EC_DEV_BRANCH, dev_ev_subclass, path,
1730 		    DI_NODE_NIL, NULL);
1731 		unlock_dev(CACHE_STATE);
1732 	} else
1733 		err_print(UNKNOWN_EVENT, subclass);
1734 
1735 out:
1736 	if (err)
1737 		err_print(EVENT_ATTR_LOOKUP_FAILED, strerror(err));
1738 	nvlist_free(attr_list);
1739 }
1740 
1741 static void
dca_impl_init(char * root,char * minor,struct dca_impl * dcip)1742 dca_impl_init(char *root, char *minor, struct dca_impl *dcip)
1743 {
1744 	assert(root);
1745 
1746 	dcip->dci_root = root;
1747 	dcip->dci_minor = minor;
1748 	dcip->dci_driver = NULL;
1749 	dcip->dci_error = 0;
1750 	dcip->dci_flags = 0;
1751 	dcip->dci_arg = NULL;
1752 }
1753 
1754 /*
1755  *  Kernel logs a message when a devinfo node is attached.  Try to create
1756  *  /dev and /devices for each minor node.  minorname can be NULL.
1757  */
1758 void
add_minor_pathname(char * node,char * minor,char * ev_subclass)1759 add_minor_pathname(char *node, char *minor, char *ev_subclass)
1760 {
1761 	struct dca_impl	dci;
1762 
1763 	vprint(CHATTY_MID, "add_minor_pathname: node_path=%s minor=%s\n",
1764 	    node, minor ? minor : "NULL");
1765 
1766 	dca_impl_init(node, minor, &dci);
1767 
1768 	/*
1769 	 * Restrict hotplug link creation if daemon
1770 	 * started  with -i option.
1771 	 */
1772 	if (single_drv == TRUE) {
1773 		dci.dci_driver = driver;
1774 	}
1775 
1776 	/*
1777 	 * We are being invoked in response to a hotplug event.
1778 	 */
1779 	dci.dci_flags = DCA_HOT_PLUG | DCA_CHECK_TYPE;
1780 
1781 	devi_tree_walk(&dci, DINFOPROP|DINFOMINOR, ev_subclass);
1782 }
1783 
1784 static di_node_t
find_clone_node()1785 find_clone_node()
1786 {
1787 	static di_node_t clone_node = DI_NODE_NIL;
1788 
1789 	if (clone_node == DI_NODE_NIL)
1790 		clone_node = di_init("/pseudo/clone@0", DINFOPROP);
1791 	return (clone_node);
1792 }
1793 
1794 static int
is_descendent_of(di_node_t node,char * driver)1795 is_descendent_of(di_node_t node, char *driver)
1796 {
1797 	while (node != DI_NODE_NIL) {
1798 		char *drv = di_driver_name(node);
1799 		if (strcmp(drv, driver) == 0)
1800 			return (1);
1801 		node = di_parent_node(node);
1802 	}
1803 	return (0);
1804 }
1805 
1806 /*
1807  * Checks the minor type.  If it is an alias node, then lookup
1808  * the real node/minor first, then call minor_process() to
1809  * do the real work.
1810  */
1811 static int
check_minor_type(di_node_t node,di_minor_t minor,void * arg)1812 check_minor_type(di_node_t node, di_minor_t minor, void *arg)
1813 {
1814 	ddi_minor_type	minor_type;
1815 	di_node_t	clone_node;
1816 	char		*mn;
1817 	char		*nt;
1818 	struct mlist	*dep;
1819 	struct dca_impl	*dcip = arg;
1820 
1821 	assert(dcip);
1822 
1823 	dep = dcip->dci_arg;
1824 
1825 	mn = di_minor_name(minor);
1826 
1827 	/*
1828 	 * We match driver here instead of in minor_process
1829 	 * as we want the actual driver name. This check is
1830 	 * unnecessary during deferred processing.
1831 	 */
1832 	if (dep &&
1833 	    ((dcip->dci_driver && !is_descendent_of(node, dcip->dci_driver)) ||
1834 	    (dcip->dci_minor && strcmp(mn, dcip->dci_minor)))) {
1835 		return (DI_WALK_CONTINUE);
1836 	}
1837 
1838 	if ((dcip->dci_flags & DCA_CHECK_TYPE) &&
1839 	    (nt = di_minor_nodetype(minor)) &&
1840 	    (strcmp(nt, DDI_NT_NET) == 0)) {
1841 		dcip->dci_flags &= ~DCA_CHECK_TYPE;
1842 	}
1843 
1844 	minor_type = di_minor_type(minor);
1845 
1846 	if (minor_type == DDM_MINOR) {
1847 		minor_process(node, minor, dep);
1848 
1849 	} else if (minor_type == DDM_ALIAS) {
1850 		struct mlist *cdep, clone_del = {0};
1851 
1852 		clone_node = find_clone_node();
1853 		if (clone_node == DI_NODE_NIL) {
1854 			err_print(DI_INIT_FAILED, "clone", strerror(errno));
1855 			return (DI_WALK_CONTINUE);
1856 		}
1857 
1858 		cdep = dep ? &clone_del : NULL;
1859 
1860 		minor_process(clone_node, minor, cdep);
1861 
1862 		/*
1863 		 * cache "alias" minor node and free "clone" minor
1864 		 */
1865 		if (cdep != NULL && cdep->head != NULL) {
1866 			assert(cdep->tail != NULL);
1867 			cache_deferred_minor(dep, node, minor);
1868 			dcip->dci_arg = cdep;
1869 			process_deferred_links(dcip, DCA_FREE_LIST);
1870 			dcip->dci_arg = dep;
1871 		}
1872 	}
1873 
1874 	return (DI_WALK_CONTINUE);
1875 }
1876 
1877 
1878 /*
1879  *  This is the entry point for each minor node, whether walking
1880  *  the entire tree via di_walk_minor() or processing a hotplug event
1881  *  for a single devinfo node (via hotplug ndi_devi_online()).
1882  */
1883 /*ARGSUSED*/
1884 static void
minor_process(di_node_t node,di_minor_t minor,struct mlist * dep)1885 minor_process(di_node_t node, di_minor_t minor, struct mlist *dep)
1886 {
1887 	create_list_t	*create;
1888 	int		defer;
1889 
1890 	vprint(CHATTY_MID, "minor_process: node=%s, minor=%s\n",
1891 	    di_node_name(node), di_minor_name(minor));
1892 
1893 	if (dep != NULL) {
1894 
1895 		/*
1896 		 * Reset /devices node to minor_perm perm/ownership
1897 		 * if we are here to deactivate device allocation
1898 		 */
1899 		if (build_devices == TRUE) {
1900 			reset_node_permissions(node, minor);
1901 		}
1902 
1903 		if (build_dev == FALSE) {
1904 			return;
1905 		}
1906 
1907 		/*
1908 		 * This function will create any nodes for /etc/devlink.tab.
1909 		 * If devlink.tab handles link creation, we don't call any
1910 		 * devfsadm modules since that could cause duplicate caching
1911 		 * in the enumerate functions if different re strings are
1912 		 * passed that are logically identical.  I'm still not
1913 		 * convinced this would cause any harm, but better to be safe.
1914 		 *
1915 		 * Deferred processing is available only for devlinks
1916 		 * created through devfsadm modules.
1917 		 */
1918 		if (process_devlink_compat(minor, node) == TRUE) {
1919 			return;
1920 		}
1921 	} else {
1922 		vprint(CHATTY_MID, "minor_process: deferred processing\n");
1923 	}
1924 
1925 	/*
1926 	 * look for relevant link create rules in the modules, and
1927 	 * invoke the link create callback function to build a link
1928 	 * if there is a match.
1929 	 */
1930 	defer = 0;
1931 	for (create = create_head; create != NULL; create = create->next) {
1932 		if ((minor_matches_rule(node, minor, create) == TRUE) &&
1933 		    class_ok(create->create->device_class) ==
1934 		    DEVFSADM_SUCCESS) {
1935 			if (call_minor_init(create->modptr) ==
1936 			    DEVFSADM_FAILURE) {
1937 				continue;
1938 			}
1939 
1940 			/*
1941 			 * If NOT doing the deferred creates (i.e. 1st pass) and
1942 			 * rule requests deferred processing cache the minor
1943 			 * data.
1944 			 *
1945 			 * If deferred processing (2nd pass), create links
1946 			 * ONLY if rule requests deferred processing.
1947 			 */
1948 			if (dep && ((create->create->flags & CREATE_MASK) ==
1949 			    CREATE_DEFER)) {
1950 				defer = 1;
1951 				continue;
1952 			} else if (dep == NULL &&
1953 			    ((create->create->flags & CREATE_MASK) !=
1954 			    CREATE_DEFER)) {
1955 				continue;
1956 			}
1957 
1958 			if ((*(create->create->callback_fcn))
1959 			    (minor, node) == DEVFSADM_TERMINATE) {
1960 				break;
1961 			}
1962 		}
1963 	}
1964 
1965 	if (defer)
1966 		cache_deferred_minor(dep, node, minor);
1967 }
1968 
1969 
1970 /*
1971  * Cache node and minor in defer list.
1972  */
1973 static void
cache_deferred_minor(struct mlist * dep,di_node_t node,di_minor_t minor)1974 cache_deferred_minor(
1975 	struct mlist *dep,
1976 	di_node_t node,
1977 	di_minor_t minor)
1978 {
1979 	struct minor	*mp;
1980 	const char	*fcn = "cache_deferred_minor";
1981 
1982 	vprint(CHATTY_MID, "%s node=%s, minor=%s\n", fcn,
1983 	    di_node_name(node), di_minor_name(minor));
1984 
1985 	if (dep == NULL) {
1986 		vprint(CHATTY_MID, "%s: cannot cache during "
1987 		    "deferred processing. Ignoring minor\n", fcn);
1988 		return;
1989 	}
1990 
1991 	mp = (struct minor *)s_zalloc(sizeof (struct minor));
1992 	mp->node = node;
1993 	mp->minor = minor;
1994 	mp->next = NULL;
1995 
1996 	assert(dep->head == NULL || dep->tail != NULL);
1997 	if (dep->head == NULL) {
1998 		dep->head = mp;
1999 	} else {
2000 		dep->tail->next = mp;
2001 	}
2002 	dep->tail = mp;
2003 }
2004 
2005 /*
2006  *  Check to see if "create" link creation rule matches this node/minor.
2007  *  If it does, return TRUE.
2008  */
2009 static int
minor_matches_rule(di_node_t node,di_minor_t minor,create_list_t * create)2010 minor_matches_rule(di_node_t node, di_minor_t minor, create_list_t *create)
2011 {
2012 	char *m_nodetype, *m_drvname;
2013 
2014 	if (create->create->node_type != NULL) {
2015 
2016 		m_nodetype = di_minor_nodetype(minor);
2017 		assert(m_nodetype != NULL);
2018 
2019 		switch (create->create->flags & TYPE_MASK) {
2020 		case TYPE_EXACT:
2021 			if (strcmp(create->create->node_type, m_nodetype) !=
2022 			    0) {
2023 				return (FALSE);
2024 			}
2025 			break;
2026 		case TYPE_PARTIAL:
2027 			if (strncmp(create->create->node_type, m_nodetype,
2028 			    strlen(create->create->node_type)) != 0) {
2029 				return (FALSE);
2030 			}
2031 			break;
2032 		case TYPE_RE:
2033 			if (regexec(&(create->node_type_comp), m_nodetype,
2034 			    0, NULL, 0) != 0) {
2035 				return (FALSE);
2036 			}
2037 			break;
2038 		}
2039 	}
2040 
2041 	if (create->create->drv_name != NULL) {
2042 		m_drvname = di_driver_name(node);
2043 		switch (create->create->flags & DRV_MASK) {
2044 		case DRV_EXACT:
2045 			if (strcmp(create->create->drv_name, m_drvname) != 0) {
2046 				return (FALSE);
2047 			}
2048 			break;
2049 		case DRV_RE:
2050 			if (regexec(&(create->drv_name_comp), m_drvname,
2051 			    0, NULL, 0) != 0) {
2052 				return (FALSE);
2053 			}
2054 			break;
2055 		}
2056 	}
2057 
2058 	return (TRUE);
2059 }
2060 
2061 /*
2062  * If no classes were given on the command line, then return DEVFSADM_SUCCESS.
2063  * Otherwise, return DEVFSADM_SUCCESS if the device "class" from the module
2064  * matches one of the device classes given on the command line,
2065  * otherwise, return DEVFSADM_FAILURE.
2066  */
2067 static int
class_ok(char * class)2068 class_ok(char *class)
2069 {
2070 	int i;
2071 
2072 	if (num_classes == 0) {
2073 		return (DEVFSADM_SUCCESS);
2074 	}
2075 
2076 	/*
2077 	 * Some create tabs operate on multiple classes of devices because the
2078 	 * kernel doesn't have a good way for a driver to indicate that a
2079 	 * particular minor's class is different from that of the dev_info_t
2080 	 * it belongs to. As such, we'll always fail to match those here.
2081 	 */
2082 	if (class == NULL) {
2083 		return (DEVFSADM_FAILURE);
2084 	}
2085 
2086 	for (i = 0; i < num_classes; i++) {
2087 		if (strcmp(class, classes[i]) == 0) {
2088 			return (DEVFSADM_SUCCESS);
2089 		}
2090 	}
2091 	return (DEVFSADM_FAILURE);
2092 }
2093 
2094 /*
2095  * call minor_fini on active modules, then unload ALL modules
2096  */
2097 static void
unload_modules(void)2098 unload_modules(void)
2099 {
2100 	module_t *module_free;
2101 	create_list_t *create_free;
2102 	remove_list_t *remove_free;
2103 
2104 	while (create_head != NULL) {
2105 		create_free = create_head;
2106 		create_head = create_head->next;
2107 
2108 		if ((create_free->create->flags & TYPE_RE) == TYPE_RE) {
2109 			regfree(&(create_free->node_type_comp));
2110 		}
2111 		if ((create_free->create->flags & DRV_RE) == DRV_RE) {
2112 			regfree(&(create_free->drv_name_comp));
2113 		}
2114 		free(create_free);
2115 	}
2116 
2117 	while (remove_head != NULL) {
2118 		remove_free = remove_head;
2119 		remove_head = remove_head->next;
2120 		free(remove_free);
2121 	}
2122 
2123 	while (module_head != NULL) {
2124 
2125 		if ((module_head->minor_fini != NULL) &&
2126 		    ((module_head->flags & MODULE_ACTIVE) == MODULE_ACTIVE)) {
2127 			(void) (*(module_head->minor_fini))();
2128 		}
2129 
2130 		vprint(MODLOAD_MID, "unloading module %s\n", module_head->name);
2131 		free(module_head->name);
2132 		(void) dlclose(module_head->dlhandle);
2133 
2134 		module_free = module_head;
2135 		module_head = module_head->next;
2136 		free(module_free);
2137 	}
2138 }
2139 
2140 /*
2141  * Load devfsadm logical link processing modules.
2142  */
2143 static void
load_modules(void)2144 load_modules(void)
2145 {
2146 	DIR *mod_dir;
2147 	struct dirent *entp;
2148 	char cdir[PATH_MAX + 1];
2149 	char *last;
2150 	char *mdir = module_dirs;
2151 	char *fcn = "load_modules: ";
2152 
2153 	while (*mdir != '\0') {
2154 
2155 		while (*mdir == ':') {
2156 			mdir++;
2157 		}
2158 
2159 		if (*mdir == '\0') {
2160 			continue;
2161 		}
2162 
2163 		last = strchr(mdir, ':');
2164 
2165 		if (last == NULL) {
2166 			last = mdir + strlen(mdir);
2167 		}
2168 
2169 		(void) strncpy(cdir, mdir, last - mdir);
2170 		cdir[last - mdir] = '\0';
2171 		mdir += strlen(cdir);
2172 
2173 		if ((mod_dir = opendir(cdir)) == NULL) {
2174 			vprint(MODLOAD_MID, "%sopendir(%s): %s\n",
2175 			    fcn, cdir, strerror(errno));
2176 			continue;
2177 		}
2178 
2179 		while ((entp = readdir(mod_dir)) != NULL) {
2180 
2181 			if ((strcmp(entp->d_name, ".") == 0) ||
2182 			    (strcmp(entp->d_name, "..") == 0)) {
2183 				continue;
2184 			}
2185 
2186 			load_module(entp->d_name, cdir);
2187 		}
2188 		s_closedir(mod_dir);
2189 	}
2190 }
2191 
2192 static void
load_module(char * mname,char * cdir)2193 load_module(char *mname, char *cdir)
2194 {
2195 	_devfsadm_create_reg_t *create_reg;
2196 	_devfsadm_remove_reg_V1_t *remove_reg;
2197 	create_list_t *create_list_element;
2198 	create_list_t **create_list_next;
2199 	remove_list_t *remove_list_element;
2200 	remove_list_t **remove_list_next;
2201 	char epath[PATH_MAX + 1], *end;
2202 	char *fcn = "load_module: ";
2203 	char *dlerrstr;
2204 	void *dlhandle;
2205 	module_t *module;
2206 	int flags;
2207 	int n;
2208 	int i;
2209 
2210 	/* ignore any file which does not end in '.so' */
2211 	if ((end = strstr(mname, MODULE_SUFFIX)) != NULL) {
2212 		if (end[strlen(MODULE_SUFFIX)] != '\0') {
2213 			return;
2214 		}
2215 	} else {
2216 		return;
2217 	}
2218 
2219 	(void) snprintf(epath, sizeof (epath), "%s/%s", cdir, mname);
2220 
2221 	if ((dlhandle = dlopen(epath, RTLD_LAZY)) == NULL) {
2222 		dlerrstr = dlerror();
2223 		err_print(DLOPEN_FAILED, epath,
2224 		    dlerrstr ? dlerrstr : "unknown error");
2225 		return;
2226 	}
2227 
2228 	/* dlsym the _devfsadm_create_reg structure */
2229 	if (NULL == (create_reg = (_devfsadm_create_reg_t *)
2230 	    dlsym(dlhandle, _DEVFSADM_CREATE_REG))) {
2231 		vprint(MODLOAD_MID, "dlsym(%s, %s): symbol not found\n", epath,
2232 		    _DEVFSADM_CREATE_REG);
2233 	} else {
2234 		vprint(MODLOAD_MID, "%sdlsym(%s, %s) succeeded\n",
2235 		    fcn, epath, _DEVFSADM_CREATE_REG);
2236 	}
2237 
2238 	/* dlsym the _devfsadm_remove_reg structure */
2239 	if (NULL == (remove_reg = (_devfsadm_remove_reg_V1_t *)
2240 	    dlsym(dlhandle, _DEVFSADM_REMOVE_REG))) {
2241 		vprint(MODLOAD_MID, "dlsym(%s,\n\t%s): symbol not found\n",
2242 		    epath, _DEVFSADM_REMOVE_REG);
2243 	} else {
2244 		vprint(MODLOAD_MID, "dlsym(%s, %s): succeeded\n",
2245 		    epath, _DEVFSADM_REMOVE_REG);
2246 	}
2247 
2248 	vprint(MODLOAD_MID, "module %s loaded\n", epath);
2249 
2250 	module = (module_t *)s_malloc(sizeof (module_t));
2251 	module->name = s_strdup(epath);
2252 	module->dlhandle = dlhandle;
2253 
2254 	/* dlsym other module functions, to be called later */
2255 	module->minor_fini = (int (*)())dlsym(dlhandle, MINOR_FINI);
2256 	module->minor_init = (int (*)())dlsym(dlhandle, MINOR_INIT);
2257 	module->flags = 0;
2258 
2259 	/*
2260 	 *  put a ptr to each struct devfsadm_create on "create_head"
2261 	 *  list sorted in interpose_lvl.
2262 	 */
2263 	if (create_reg != NULL) {
2264 		for (i = 0; i < create_reg->count; i++) {
2265 			int flags = create_reg->tblp[i].flags;
2266 
2267 			create_list_element = (create_list_t *)
2268 			    s_malloc(sizeof (create_list_t));
2269 
2270 			create_list_element->create = &(create_reg->tblp[i]);
2271 			create_list_element->modptr = module;
2272 
2273 			if (((flags & CREATE_MASK) != 0) &&
2274 			    ((flags & CREATE_MASK) != CREATE_DEFER)) {
2275 				free(create_list_element);
2276 				err_print("illegal flag combination in "
2277 				    "module create\n");
2278 				err_print(IGNORING_ENTRY, i, epath);
2279 				continue;
2280 			}
2281 
2282 			if (((flags & TYPE_MASK) == 0) ^
2283 			    (create_reg->tblp[i].node_type == NULL)) {
2284 				free(create_list_element);
2285 				err_print("flags value incompatible with "
2286 				    "node_type value in module create\n");
2287 				err_print(IGNORING_ENTRY, i, epath);
2288 				continue;
2289 			}
2290 
2291 			if (((flags & TYPE_MASK) != 0) &&
2292 			    ((flags & TYPE_MASK) != TYPE_EXACT) &&
2293 			    ((flags & TYPE_MASK) != TYPE_RE) &&
2294 			    ((flags & TYPE_MASK) != TYPE_PARTIAL)) {
2295 				free(create_list_element);
2296 				err_print("illegal TYPE_* flag combination in "
2297 				    "module create\n");
2298 				err_print(IGNORING_ENTRY, i, epath);
2299 				continue;
2300 			}
2301 
2302 			/* precompile regular expression for efficiency */
2303 			if ((flags & TYPE_RE) == TYPE_RE) {
2304 				if ((n = regcomp(&(create_list_element->
2305 				    node_type_comp),
2306 				    create_reg->tblp[i].node_type,
2307 				    REG_EXTENDED)) != 0) {
2308 					free(create_list_element);
2309 					err_print(REGCOMP_FAILED,
2310 					    create_reg->tblp[i].node_type, n);
2311 					err_print(IGNORING_ENTRY, i, epath);
2312 					continue;
2313 				}
2314 			}
2315 
2316 			if (((flags & DRV_MASK) == 0) ^
2317 			    (create_reg->tblp[i].drv_name == NULL)) {
2318 				if ((flags & TYPE_RE) == TYPE_RE) {
2319 					regfree(&(create_list_element->
2320 					    node_type_comp));
2321 				}
2322 				free(create_list_element);
2323 				err_print("flags value incompatible with "
2324 				    "drv_name value in module create\n");
2325 				err_print(IGNORING_ENTRY, i, epath);
2326 				continue;
2327 			}
2328 
2329 			if (((flags & DRV_MASK) != 0) &&
2330 			    ((flags & DRV_MASK) != DRV_EXACT) &&
2331 			    ((flags & DRV_MASK) !=  DRV_RE)) {
2332 				if ((flags & TYPE_RE) == TYPE_RE) {
2333 					regfree(&(create_list_element->
2334 					    node_type_comp));
2335 				}
2336 				free(create_list_element);
2337 				err_print("illegal DRV_* flag combination in "
2338 				    "module create\n");
2339 				err_print(IGNORING_ENTRY, i, epath);
2340 				continue;
2341 			}
2342 
2343 			/* precompile regular expression for efficiency */
2344 			if ((create_reg->tblp[i].flags & DRV_RE) == DRV_RE) {
2345 				if ((n = regcomp(&(create_list_element->
2346 				    drv_name_comp),
2347 				    create_reg->tblp[i].drv_name,
2348 				    REG_EXTENDED)) != 0) {
2349 					if ((flags & TYPE_RE) == TYPE_RE) {
2350 						regfree(&(create_list_element->
2351 						    node_type_comp));
2352 					}
2353 					free(create_list_element);
2354 					err_print(REGCOMP_FAILED,
2355 					    create_reg->tblp[i].drv_name, n);
2356 					err_print(IGNORING_ENTRY, i, epath);
2357 					continue;
2358 				}
2359 			}
2360 
2361 
2362 			/* add to list sorted by interpose level */
2363 			for (create_list_next = &(create_head);
2364 			    (*create_list_next != NULL) &&
2365 			    (*create_list_next)->create->interpose_lvl >=
2366 			    create_list_element->create->interpose_lvl;
2367 			    create_list_next = &((*create_list_next)->next))
2368 				;
2369 			create_list_element->next = *create_list_next;
2370 			*create_list_next = create_list_element;
2371 		}
2372 	}
2373 
2374 	/*
2375 	 *  put a ptr to each struct devfsadm_remove on "remove_head"
2376 	 *  list sorted by interpose_lvl.
2377 	 */
2378 	flags = 0;
2379 	if (remove_reg != NULL) {
2380 		if (remove_reg->version < DEVFSADM_V1)
2381 			flags |= RM_NOINTERPOSE;
2382 		for (i = 0; i < remove_reg->count; i++) {
2383 
2384 			remove_list_element = (remove_list_t *)
2385 			    s_malloc(sizeof (remove_list_t));
2386 
2387 			remove_list_element->remove = &(remove_reg->tblp[i]);
2388 			remove_list_element->remove->flags |= flags;
2389 			remove_list_element->modptr = module;
2390 
2391 			for (remove_list_next = &(remove_head);
2392 			    (*remove_list_next != NULL) &&
2393 			    (*remove_list_next)->remove->interpose_lvl >=
2394 			    remove_list_element->remove->interpose_lvl;
2395 			    remove_list_next = &((*remove_list_next)->next))
2396 				;
2397 			remove_list_element->next = *remove_list_next;
2398 			*remove_list_next = remove_list_element;
2399 		}
2400 	}
2401 
2402 	module->next = module_head;
2403 	module_head = module;
2404 }
2405 
2406 /*
2407  * After we have completed a CACHE_STATE, if a SYNC_STATE does not occur
2408  * within 'timeout' secs the minor_fini_thread needs to do a SYNC_STATE
2409  * so that we still call the minor_fini routines.
2410  */
2411 static void *
minor_fini_thread(void * arg __unused)2412 minor_fini_thread(void *arg __unused)
2413 {
2414 	timestruc_t	abstime;
2415 
2416 	vprint(INITFINI_MID, "minor_fini_thread starting\n");
2417 
2418 	(void) mutex_lock(&minor_fini_mutex);
2419 	for (;;) {
2420 		/* wait the gather period, or until signaled */
2421 		abstime.tv_sec = time(NULL) + minor_fini_timeout;
2422 		abstime.tv_nsec = 0;
2423 		(void) cond_timedwait(&minor_fini_cv,
2424 		    &minor_fini_mutex, &abstime);
2425 
2426 		/* if minor_fini was canceled, go wait again */
2427 		if (minor_fini_canceled == TRUE)
2428 			continue;
2429 
2430 		/* if minor_fini was delayed, go wait again */
2431 		if (minor_fini_delayed == TRUE) {
2432 			minor_fini_delayed = FALSE;
2433 			continue;
2434 		}
2435 
2436 		/* done with cancellations and delays, do the SYNC_STATE */
2437 		(void) mutex_unlock(&minor_fini_mutex);
2438 
2439 		lock_dev();
2440 		unlock_dev(SYNC_STATE);
2441 		vprint(INITFINI_MID, "minor_fini sync done\n");
2442 
2443 		(void) mutex_lock(&minor_fini_mutex);
2444 	}
2445 	return (NULL);
2446 }
2447 
2448 
2449 /*
2450  * Attempt to initialize module, if a minor_init routine exists.  Set
2451  * the active flag if the routine exists and succeeds.	If it doesn't
2452  * exist, just set the active flag.
2453  */
2454 static int
call_minor_init(module_t * module)2455 call_minor_init(module_t *module)
2456 {
2457 	char *fcn = "call_minor_init: ";
2458 
2459 	if ((module->flags & MODULE_ACTIVE) == MODULE_ACTIVE) {
2460 		return (DEVFSADM_SUCCESS);
2461 	}
2462 
2463 	vprint(INITFINI_MID, "%smodule %s.  current state: inactive\n",
2464 	    fcn, module->name);
2465 
2466 	if (module->minor_init == NULL) {
2467 		module->flags |= MODULE_ACTIVE;
2468 		vprint(INITFINI_MID, "minor_init not defined\n");
2469 		return (DEVFSADM_SUCCESS);
2470 	}
2471 
2472 	if ((*(module->minor_init))() == DEVFSADM_FAILURE) {
2473 		err_print(FAILED_FOR_MODULE, MINOR_INIT, module->name);
2474 		return (DEVFSADM_FAILURE);
2475 	}
2476 
2477 	vprint(INITFINI_MID, "minor_init() returns DEVFSADM_SUCCESS. "
2478 	    "new state: active\n");
2479 
2480 	module->flags |= MODULE_ACTIVE;
2481 	return (DEVFSADM_SUCCESS);
2482 }
2483 
2484 /*
2485  * Creates a symlink 'link' to the physical path of node:minor.
2486  * Construct link contents, then call create_link_common().
2487  */
2488 /*ARGSUSED*/
2489 int
devfsadm_mklink(char * link,di_node_t node,di_minor_t minor,int flags)2490 devfsadm_mklink(char *link, di_node_t node, di_minor_t minor, int flags)
2491 {
2492 	char rcontents[PATH_MAX];
2493 	char devlink[PATH_MAX];
2494 	char phy_path[PATH_MAX];
2495 	char *acontents;
2496 	char *dev_path;
2497 	int numslashes;
2498 	int rv;
2499 	int i, link_exists;
2500 	int last_was_slash = FALSE;
2501 
2502 	/*
2503 	 * try to use devices path
2504 	 */
2505 	if ((node == lnode) && (minor == lminor)) {
2506 		acontents = lphy_path;
2507 	} else if (di_minor_type(minor) == DDM_ALIAS) {
2508 		/* use /pseudo/clone@0:<driver> as the phys path */
2509 		(void) snprintf(phy_path, sizeof (phy_path),
2510 		    "/pseudo/clone@0:%s",
2511 		    di_driver_name(di_minor_devinfo(minor)));
2512 		acontents = phy_path;
2513 	} else {
2514 		if ((dev_path = di_devfs_path(node)) == NULL) {
2515 			err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
2516 			devfsadm_exit(1);
2517 			/*NOTREACHED*/
2518 		}
2519 		(void) snprintf(phy_path, sizeof (phy_path), "%s:%s",
2520 		    dev_path, di_minor_name(minor));
2521 		di_devfs_path_free(dev_path);
2522 		acontents = phy_path;
2523 	}
2524 
2525 	/* prepend link with dev_dir contents */
2526 	(void) strlcpy(devlink, dev_dir, sizeof (devlink));
2527 	(void) strlcat(devlink, "/", sizeof (devlink));
2528 	(void) strlcat(devlink, link, sizeof (devlink));
2529 
2530 	/*
2531 	 * Calculate # of ../ to add.  Account for double '//' in path.
2532 	 * Ignore all leading slashes.
2533 	 */
2534 	for (i = 0; link[i] == '/'; i++)
2535 		;
2536 	for (numslashes = 0; link[i] != '\0'; i++) {
2537 		if (link[i] == '/') {
2538 			if (last_was_slash == FALSE) {
2539 				numslashes++;
2540 				last_was_slash = TRUE;
2541 			}
2542 		} else {
2543 			last_was_slash = FALSE;
2544 		}
2545 	}
2546 	/* Don't count any trailing '/' */
2547 	if (link[i-1] == '/') {
2548 		numslashes--;
2549 	}
2550 
2551 	rcontents[0] = '\0';
2552 	do {
2553 		(void) strlcat(rcontents, "../", sizeof (rcontents));
2554 	} while (numslashes-- != 0);
2555 
2556 	(void) strlcat(rcontents, "devices", sizeof (rcontents));
2557 	(void) strlcat(rcontents, acontents, sizeof (rcontents));
2558 
2559 	if (devlinks_debug == TRUE) {
2560 		vprint(INFO_MID, "adding link %s ==> %s\n", devlink, rcontents);
2561 	}
2562 
2563 	if ((rv = create_link_common(devlink, rcontents, &link_exists))
2564 	    == DEVFSADM_SUCCESS) {
2565 		linknew = TRUE;
2566 		add_link_to_cache(link, acontents);
2567 	} else {
2568 		linknew = FALSE;
2569 	}
2570 
2571 	if (link_exists == TRUE) {
2572 		/* Link exists or was just created */
2573 		(void) di_devlink_add_link(devlink_cache, link, rcontents,
2574 		    DI_PRIMARY_LINK);
2575 
2576 		if (system_labeled && (flags & DA_ADD)) {
2577 			/*
2578 			 * Add this to the list of allocatable devices. If this
2579 			 * is a hotplugged, removable disk, add it as rmdisk.
2580 			 */
2581 			int instance = di_instance(node);
2582 
2583 			if ((flags & DA_CD) &&
2584 			    (_da_check_for_usb(devlink, root_dir) == 1)) {
2585 				(void) da_add_list(&devlist, devlink, instance,
2586 				    DA_ADD|DA_RMDISK);
2587 				update_devdb = DA_RMDISK;
2588 			} else if (linknew == TRUE) {
2589 				(void) da_add_list(&devlist, devlink, instance,
2590 				    flags);
2591 				update_devdb = flags;
2592 			}
2593 		}
2594 	}
2595 
2596 	return (rv);
2597 }
2598 
2599 /*
2600  * Creates a symlink link to primary_link.  Calculates relative
2601  * directory offsets, then calls link_common().
2602  */
2603 /*ARGSUSED*/
2604 int
devfsadm_secondary_link(char * link,char * primary_link,int flags)2605 devfsadm_secondary_link(char *link, char *primary_link, int flags)
2606 {
2607 	char contents[PATH_MAX + 1];
2608 	char devlink[PATH_MAX + 1];
2609 	int rv, link_exists;
2610 	char *fpath;
2611 	char *tpath;
2612 	char *op;
2613 
2614 	/* prepend link with dev_dir contents */
2615 	(void) strcpy(devlink, dev_dir);
2616 	(void) strcat(devlink, "/");
2617 	(void) strcat(devlink, link);
2618 	/*
2619 	 * building extra link, so use first link as link contents, but first
2620 	 * make it relative.
2621 	 */
2622 	fpath = link;
2623 	tpath = primary_link;
2624 	op = contents;
2625 
2626 	while (*fpath == *tpath && *fpath != '\0') {
2627 		fpath++, tpath++;
2628 	}
2629 
2630 	/* Count directories to go up, if any, and add "../" */
2631 	while (*fpath != '\0') {
2632 		if (*fpath == '/') {
2633 			(void) strcpy(op, "../");
2634 			op += 3;
2635 		}
2636 		fpath++;
2637 	}
2638 
2639 	/*
2640 	 * Back up to the start of the current path component, in
2641 	 * case in the middle
2642 	 */
2643 	while (tpath != primary_link && *(tpath-1) != '/') {
2644 		tpath--;
2645 	}
2646 	(void) strcpy(op, tpath);
2647 
2648 	if (devlinks_debug == TRUE) {
2649 		vprint(INFO_MID, "adding extra link %s ==> %s\n",
2650 		    devlink, contents);
2651 	}
2652 
2653 	if ((rv = create_link_common(devlink, contents, &link_exists))
2654 	    == DEVFSADM_SUCCESS) {
2655 		/*
2656 		 * we need to save the ultimate /devices contents, and not the
2657 		 * secondary link, since hotcleanup only looks at /devices path.
2658 		 * Since we don't have devices path here, we can try to get it
2659 		 * by readlink'ing the secondary link.  This assumes the primary
2660 		 * link was created first.
2661 		 */
2662 		add_link_to_cache(link, lphy_path);
2663 		linknew = TRUE;
2664 		if (system_labeled &&
2665 		    ((flags & DA_AUDIO) && (flags & DA_ADD))) {
2666 			/*
2667 			 * Add this device to the list of allocatable devices.
2668 			 */
2669 			int	instance = 0;
2670 
2671 			op = strrchr(contents, '/');
2672 			op++;
2673 			(void) sscanf(op, "%d", &instance);
2674 			(void) da_add_list(&devlist, devlink, instance, flags);
2675 			update_devdb = flags;
2676 		}
2677 	} else {
2678 		linknew = FALSE;
2679 	}
2680 
2681 	/*
2682 	 * If link exists or was just created, add it to the database
2683 	 */
2684 	if (link_exists == TRUE) {
2685 		(void) di_devlink_add_link(devlink_cache, link, contents,
2686 		    DI_SECONDARY_LINK);
2687 	}
2688 
2689 	return (rv);
2690 }
2691 
2692 /* returns pointer to the devices directory */
2693 char *
devfsadm_get_devices_dir()2694 devfsadm_get_devices_dir()
2695 {
2696 	return (devices_dir);
2697 }
2698 
2699 /*
2700  * Does the actual link creation.  VERBOSE_MID only used if there is
2701  * a change.  CHATTY_MID used otherwise.
2702  */
2703 static int
create_link_common(char * devlink,char * contents,int * exists)2704 create_link_common(char *devlink, char *contents, int *exists)
2705 {
2706 	int try;
2707 	int linksize;
2708 	int max_tries = 0;
2709 	static int prev_link_existed = TRUE;
2710 	char checkcontents[PATH_MAX + 1];
2711 	char *hide;
2712 
2713 	*exists = FALSE;
2714 
2715 	/* Database is not updated when file_mods == FALSE */
2716 	if (file_mods == FALSE) {
2717 		/* we want *actual* link contents so no alias redirection */
2718 		linksize = readlink(devlink, checkcontents, PATH_MAX);
2719 		if (linksize > 0) {
2720 			checkcontents[linksize] = '\0';
2721 			if (strcmp(checkcontents, contents) != 0) {
2722 				vprint(CHATTY_MID, REMOVING_LINK,
2723 				    devlink, checkcontents);
2724 				return (DEVFSADM_SUCCESS);
2725 			} else {
2726 				vprint(CHATTY_MID, "link exists and is correct:"
2727 				    " %s -> %s\n", devlink, contents);
2728 				/* failure only in that the link existed */
2729 				return (DEVFSADM_FAILURE);
2730 			}
2731 		} else {
2732 			vprint(VERBOSE_MID, CREATING_LINK, devlink, contents);
2733 			return (DEVFSADM_SUCCESS);
2734 		}
2735 	}
2736 
2737 	/*
2738 	 * systems calls are expensive, so predict whether to readlink
2739 	 * or symlink first, based on previous attempt
2740 	 */
2741 	if (prev_link_existed == FALSE) {
2742 		try = CREATE_LINK;
2743 	} else {
2744 		try = READ_LINK;
2745 	}
2746 
2747 	while (++max_tries <= 3) {
2748 
2749 		switch (try) {
2750 		case  CREATE_LINK:
2751 
2752 			if (symlink(contents, devlink) == 0) {
2753 				vprint(VERBOSE_MID, CREATING_LINK, devlink,
2754 				    contents);
2755 				prev_link_existed = FALSE;
2756 				/* link successfully created */
2757 				*exists = TRUE;
2758 				set_logindev_perms(devlink);
2759 				return (DEVFSADM_SUCCESS);
2760 			} else {
2761 				switch (errno) {
2762 
2763 				case ENOENT:
2764 					/* dirpath to node doesn't exist */
2765 					hide = strrchr(devlink, '/');
2766 					*hide = '\0';
2767 					s_mkdirp(devlink, S_IRWXU|S_IRGRP|
2768 					    S_IXGRP|S_IROTH|S_IXOTH);
2769 					*hide = '/';
2770 					break;
2771 				case EEXIST:
2772 					try = READ_LINK;
2773 					break;
2774 				default:
2775 					err_print(SYMLINK_FAILED, devlink,
2776 					    contents, strerror(errno));
2777 					return (DEVFSADM_FAILURE);
2778 				}
2779 			}
2780 			break;
2781 
2782 		case READ_LINK:
2783 
2784 			/*
2785 			 * If there is redirection, new phys path
2786 			 * and old phys path will not match and the
2787 			 * link will be created with new phys path
2788 			 * which is what we want. So we want real
2789 			 * contents.
2790 			 */
2791 			linksize = readlink(devlink, checkcontents, PATH_MAX);
2792 			if (linksize >= 0) {
2793 				checkcontents[linksize] = '\0';
2794 				if (strcmp(checkcontents, contents) != 0) {
2795 					s_unlink(devlink);
2796 					vprint(VERBOSE_MID, REMOVING_LINK,
2797 					    devlink, checkcontents);
2798 					try = CREATE_LINK;
2799 				} else {
2800 					prev_link_existed = TRUE;
2801 					vprint(CHATTY_MID,
2802 					    "link exists and is correct:"
2803 					    " %s -> %s\n", devlink, contents);
2804 					*exists = TRUE;
2805 					/* failure in that the link existed */
2806 					return (DEVFSADM_FAILURE);
2807 				}
2808 			} else {
2809 				switch (errno) {
2810 				case EINVAL:
2811 					/* not a symlink, remove and create */
2812 					s_unlink(devlink);
2813 					/* FALLTHROUGH */
2814 				default:
2815 					/* maybe it didn't exist at all */
2816 					try = CREATE_LINK;
2817 					break;
2818 				}
2819 			}
2820 			break;
2821 		}
2822 	}
2823 	err_print(MAX_ATTEMPTS, devlink, contents);
2824 	return (DEVFSADM_FAILURE);
2825 }
2826 
2827 static void
set_logindev_perms(char * devlink)2828 set_logindev_perms(char *devlink)
2829 {
2830 	struct login_dev *newdev;
2831 	struct passwd pwd, *resp;
2832 	char pwd_buf[PATH_MAX];
2833 	int rv;
2834 	struct stat sb;
2835 	char *devfs_path = NULL;
2836 
2837 	/*
2838 	 * We only want logindev perms to be set when a device is
2839 	 * hotplugged or an application requests synchronous creates.
2840 	 * So we enable this only in daemon mode. In addition,
2841 	 * login(1) only fixes the std. /dev dir. So we don't
2842 	 * change perms if alternate root is set.
2843 	 * login_dev_enable is TRUE only in these cases.
2844 	 */
2845 	if (login_dev_enable != TRUE)
2846 		return;
2847 
2848 	/*
2849 	 * Normally, /etc/logindevperm has few (8 - 10 entries) which
2850 	 * may be regular expressions (globs were converted to RE).
2851 	 * So just do a linear search through the list.
2852 	 */
2853 	for (newdev = login_dev_cache; newdev; newdev = newdev->ldev_next) {
2854 		vprint(FILES_MID, "matching %s with %s\n", devlink,
2855 		    newdev->ldev_device);
2856 
2857 		if (regexec(&newdev->ldev_device_regex, devlink, 0,
2858 		    NULL, 0) == 0)  {
2859 			vprint(FILES_MID, "matched %s with %s\n", devlink,
2860 			    newdev->ldev_device);
2861 			break;
2862 		}
2863 	}
2864 
2865 	if (newdev == NULL)
2866 		return;
2867 
2868 	/*
2869 	 * we have a match, now find the driver associated with this
2870 	 * minor node using a snapshot on the physical path
2871 	 */
2872 	(void) resolve_link(devlink, NULL, NULL, &devfs_path, 0);
2873 	/*
2874 	 * We dont need redirection here - the actual link contents
2875 	 * whether "alias" or "current" are fine
2876 	 */
2877 	if (devfs_path) {
2878 		di_node_t node;
2879 		char *drv;
2880 		struct driver_list *list;
2881 		char *p;
2882 
2883 		/* truncate on : so we can take a snapshot */
2884 		(void) strcpy(pwd_buf, devfs_path);
2885 		p = strrchr(pwd_buf, ':');
2886 		if (p == NULL) {
2887 			free(devfs_path);
2888 			return;
2889 		}
2890 		*p = '\0';
2891 
2892 		vprint(FILES_MID, "link=%s->physpath=%s\n",
2893 		    devlink, pwd_buf);
2894 
2895 		node = di_init(pwd_buf, DINFOMINOR);
2896 
2897 		drv = NULL;
2898 		if (node) {
2899 			drv = di_driver_name(node);
2900 
2901 			if (drv) {
2902 				vprint(FILES_MID, "%s: driver is %s\n",
2903 				    devlink, drv);
2904 			}
2905 		}
2906 		/* search thru the driver list specified in logindevperm */
2907 		list = newdev->ldev_driver_list;
2908 		if ((drv != NULL) && (list != NULL)) {
2909 			while (list) {
2910 				if (strcmp(list->driver_name,
2911 				    drv) == 0) {
2912 					vprint(FILES_MID,
2913 					    "driver %s match!\n", drv);
2914 					break;
2915 				}
2916 				list = list->next;
2917 			}
2918 			if (list == NULL) {
2919 				vprint(FILES_MID, "no driver match!\n");
2920 				free(devfs_path);
2921 				return;
2922 			}
2923 		}
2924 		free(devfs_path);
2925 		di_fini(node);
2926 	} else {
2927 		return;
2928 	}
2929 
2930 	vprint(FILES_MID, "changing permissions of %s\n", devlink);
2931 
2932 	/*
2933 	 * We have a match. We now attempt to determine the
2934 	 * owner and group of the console user.
2935 	 *
2936 	 * stat() the console device newdev->ldev_console
2937 	 * which will always exist - it will have the right owner but
2938 	 * not the right group. Use getpwuid_r() to determine group for this
2939 	 * uid.
2940 	 * Note, it is safe to use name service here since if name services
2941 	 * are not available (during boot or in single-user mode), then
2942 	 * console owner will be root and its gid can be found in
2943 	 * local files.
2944 	 */
2945 	if (stat(newdev->ldev_console, &sb) == -1) {
2946 		vprint(VERBOSE_MID, STAT_FAILED, newdev->ldev_console,
2947 		    strerror(errno));
2948 		return;
2949 	}
2950 
2951 	resp = NULL;
2952 	rv = getpwuid_r(sb.st_uid, &pwd, pwd_buf, sizeof (pwd_buf), &resp);
2953 	if (rv || resp == NULL) {
2954 		rv = rv ? rv : EINVAL;
2955 		vprint(VERBOSE_MID, GID_FAILED, sb.st_uid,
2956 		    strerror(rv));
2957 		return;
2958 	}
2959 
2960 	assert(&pwd == resp);
2961 
2962 	sb.st_gid = resp->pw_gid;
2963 
2964 	if (chmod(devlink, newdev->ldev_perms) == -1) {
2965 		vprint(VERBOSE_MID, CHMOD_FAILED, devlink,
2966 		    strerror(errno));
2967 		return;
2968 	}
2969 
2970 	if (chown(devlink, sb.st_uid, sb.st_gid)  == -1) {
2971 		vprint(VERBOSE_MID, CHOWN_FAILED, devlink,
2972 		    strerror(errno));
2973 	}
2974 }
2975 
2976 /*
2977  * Reset /devices node with appropriate permissions and
2978  * ownership as specified in /etc/minor_perm.
2979  */
2980 static void
reset_node_permissions(di_node_t node,di_minor_t minor)2981 reset_node_permissions(di_node_t node, di_minor_t minor)
2982 {
2983 	int spectype;
2984 	char phy_path[PATH_MAX + 1];
2985 	mode_t mode;
2986 	dev_t dev;
2987 	uid_t uid;
2988 	gid_t gid;
2989 	struct stat sb;
2990 	char *dev_path, *aminor = NULL;
2991 
2992 	/* lphy_path starts with / */
2993 	if ((dev_path = di_devfs_path(node)) == NULL) {
2994 		err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
2995 		devfsadm_exit(1);
2996 		/*NOTREACHED*/
2997 	}
2998 	(void) strcpy(lphy_path, dev_path);
2999 	di_devfs_path_free(dev_path);
3000 
3001 	(void) strcat(lphy_path, ":");
3002 	if (di_minor_type(minor) == DDM_ALIAS) {
3003 		char *driver;
3004 		aminor = di_minor_name(minor);
3005 		driver = di_driver_name(di_minor_devinfo(minor));
3006 		(void) strcat(lphy_path, driver);
3007 	} else
3008 		(void) strcat(lphy_path, di_minor_name(minor));
3009 
3010 	(void) strcpy(phy_path, devices_dir);
3011 	(void) strcat(phy_path, lphy_path);
3012 
3013 	lnode = node;
3014 	lminor = minor;
3015 
3016 	vprint(CHATTY_MID, "reset_node_permissions: phy_path=%s lphy_path=%s\n",
3017 	    phy_path, lphy_path);
3018 
3019 	dev = di_minor_devt(minor);
3020 	spectype = di_minor_spectype(minor); /* block or char */
3021 
3022 	getattr(phy_path, aminor, spectype, dev, &mode, &uid, &gid);
3023 
3024 	/*
3025 	 * compare and set permissions and ownership
3026 	 *
3027 	 * Under devfs, a quick insertion and removal of USB devices
3028 	 * would cause stat of physical path to fail. In this case,
3029 	 * we emit a verbose message, but don't print errors.
3030 	 */
3031 	if ((stat(phy_path, &sb) == -1) || (sb.st_rdev != dev)) {
3032 		vprint(VERBOSE_MID, NO_DEVFS_NODE, phy_path);
3033 		return;
3034 	}
3035 
3036 	/*
3037 	 * If we are here for a new device
3038 	 *	If device allocation is on
3039 	 *	then
3040 	 *		set ownership to root:other and permissions to 0000
3041 	 *	else
3042 	 *		set ownership and permissions as specified in minor_perm
3043 	 * If we are here for an existing device
3044 	 *	If device allocation is to be turned on
3045 	 *	then
3046 	 *		reset ownership to root:other and permissions to 0000
3047 	 *	else if device allocation is to be turned off
3048 	 *		reset ownership and permissions to those specified in
3049 	 *		minor_perm
3050 	 *	else
3051 	 *		preserve existing/user-modified ownership and
3052 	 *		permissions
3053 	 *
3054 	 * devfs indicates a new device by faking access time to be zero.
3055 	 */
3056 	if (sb.st_atime != 0) {
3057 		int  i;
3058 		char *nt;
3059 
3060 		if ((devalloc_flag == 0) && (devalloc_is_on != 1))
3061 			/*
3062 			 * Leave existing devices as they are if we are not
3063 			 * turning device allocation on/off.
3064 			 */
3065 			return;
3066 
3067 		nt = di_minor_nodetype(minor);
3068 
3069 		if (nt == NULL)
3070 			return;
3071 
3072 		for (i = 0; devalloc_list[i]; i++) {
3073 			if (strcmp(nt, devalloc_list[i]) == 0)
3074 				/*
3075 				 * One of the types recognized by devalloc,
3076 				 * reset attrs.
3077 				 */
3078 				break;
3079 		}
3080 		if (devalloc_list[i] == NULL)
3081 			return;
3082 	}
3083 
3084 	if (file_mods == FALSE) {
3085 		/* Nothing more to do if simulating */
3086 		vprint(VERBOSE_MID, PERM_MSG, phy_path, uid, gid, mode);
3087 		return;
3088 	}
3089 
3090 	if ((devalloc_flag == DA_ON) ||
3091 	    ((devalloc_is_on == 1) && (devalloc_flag != DA_OFF))) {
3092 		/*
3093 		 * we are here either to turn device allocation on or
3094 		 * to add a new device while device allocation is on
3095 		 * (and we've confirmed that we're not turning it
3096 		 * off).
3097 		 */
3098 		mode = DEALLOC_MODE;
3099 		uid = DA_UID;
3100 		gid = DA_GID;
3101 	}
3102 
3103 	if ((devalloc_is_on == 1) || (devalloc_flag == DA_ON) ||
3104 	    (sb.st_mode != mode)) {
3105 		if (chmod(phy_path, mode) == -1)
3106 			vprint(VERBOSE_MID, CHMOD_FAILED,
3107 			    phy_path, strerror(errno));
3108 	}
3109 	if ((devalloc_is_on == 1) || (devalloc_flag == DA_ON) ||
3110 	    (sb.st_uid != uid || sb.st_gid != gid)) {
3111 		if (chown(phy_path, uid, gid) == -1)
3112 			vprint(VERBOSE_MID, CHOWN_FAILED,
3113 			    phy_path, strerror(errno));
3114 	}
3115 
3116 	/* Report that we actually did something */
3117 	vprint(VERBOSE_MID, PERM_MSG, phy_path, uid, gid, mode);
3118 }
3119 
3120 /*
3121  * Removes logical link and the minor node it refers to.  If file is a
3122  * link, we recurse and try to remove the minor node (or link if path is
3123  * a double link) that file's link contents refer to.
3124  */
3125 static void
devfsadm_rm_work(char * file,int recurse,int file_type)3126 devfsadm_rm_work(char *file, int recurse, int file_type)
3127 {
3128 	char *fcn = "devfsadm_rm_work: ";
3129 	int linksize;
3130 	char contents[PATH_MAX + 1];
3131 	char nextfile[PATH_MAX + 1];
3132 	char newfile[PATH_MAX + 1];
3133 	char *ptr;
3134 
3135 	vprint(REMOVE_MID, "%s%s\n", fcn, file);
3136 
3137 	/*
3138 	 * Note: we don't remove /devices (non-links) entries because they are
3139 	 *	covered by devfs.
3140 	 */
3141 	if (file_type != TYPE_LINK) {
3142 		return;
3143 	}
3144 
3145 	/* split into multiple if's due to excessive indentations */
3146 	(void) strcpy(newfile, dev_dir);
3147 	(void) strcat(newfile, "/");
3148 	(void) strcat(newfile, file);
3149 
3150 	/*
3151 	 * we dont care about the content of the symlink, so
3152 	 * redirection is not needed.
3153 	 */
3154 	if ((recurse == TRUE) &&
3155 	    ((linksize = readlink(newfile, contents, PATH_MAX)) > 0)) {
3156 		contents[linksize] = '\0';
3157 
3158 		/*
3159 		 * recurse if link points to another link
3160 		 */
3161 		if (is_minor_node(contents, &ptr) != DEVFSADM_TRUE) {
3162 			if (strncmp(contents, DEV "/", strlen(DEV) + 1) == 0) {
3163 				devfsadm_rm_work(&contents[strlen(DEV) + 1],
3164 				    TRUE, TYPE_LINK);
3165 			} else {
3166 				if ((ptr = strrchr(file, '/')) != NULL) {
3167 					*ptr = '\0';
3168 					(void) strcpy(nextfile, file);
3169 					*ptr = '/';
3170 					(void) strcat(nextfile, "/");
3171 				} else {
3172 					(void) strcpy(nextfile, "");
3173 				}
3174 				(void) strcat(nextfile, contents);
3175 				devfsadm_rm_work(nextfile, TRUE, TYPE_LINK);
3176 			}
3177 		}
3178 	}
3179 
3180 	vprint(VERBOSE_MID, DEVFSADM_UNLINK, newfile);
3181 	if (file_mods == TRUE) {
3182 		rm_link_from_cache(file);
3183 		s_unlink(newfile);
3184 		rm_parent_dir_if_empty(newfile);
3185 		invalidate_enumerate_cache();
3186 		(void) di_devlink_rm_link(devlink_cache, file);
3187 	}
3188 }
3189 
3190 void
devfsadm_rm_link(char * file)3191 devfsadm_rm_link(char *file)
3192 {
3193 	devfsadm_rm_work(file, FALSE, TYPE_LINK);
3194 }
3195 
3196 void
devfsadm_rm_all(char * file)3197 devfsadm_rm_all(char *file)
3198 {
3199 	devfsadm_rm_work(file, TRUE, TYPE_LINK);
3200 }
3201 
3202 static int
s_rmdir(char * path)3203 s_rmdir(char *path)
3204 {
3205 	int	i;
3206 	char	*rpath, *dir;
3207 	const char *fcn = "s_rmdir";
3208 
3209 	/*
3210 	 * Certain directories are created at install time by packages.
3211 	 * Some of them (listed in sticky_dirs[]) are required by apps
3212 	 * and need to be present even when empty.
3213 	 */
3214 	vprint(REMOVE_MID, "%s: checking if %s is sticky\n", fcn, path);
3215 
3216 	rpath = path + strlen(dev_dir) + 1;
3217 
3218 	for (i = 0; (dir = sticky_dirs[i]) != NULL; i++) {
3219 		if (*rpath == *dir) {
3220 			if (strcmp(rpath, dir) == 0) {
3221 				vprint(REMOVE_MID, "%s: skipping sticky dir: "
3222 				    "%s\n", fcn, path);
3223 				errno = EEXIST;
3224 				return (-1);
3225 			}
3226 		}
3227 	}
3228 
3229 	return (rmdir(path));
3230 }
3231 
3232 /*
3233  * Try to remove any empty directories up the tree.  It is assumed that
3234  * pathname is a file that was removed, so start with its parent, and
3235  * work up the tree.
3236  */
3237 static void
rm_parent_dir_if_empty(char * pathname)3238 rm_parent_dir_if_empty(char *pathname)
3239 {
3240 	char *ptr, path[PATH_MAX + 1];
3241 	char *fcn = "rm_parent_dir_if_empty: ";
3242 
3243 	vprint(REMOVE_MID, "%schecking %s if empty\n", fcn, pathname);
3244 
3245 	(void) strcpy(path, pathname);
3246 
3247 	/*
3248 	 * ascend up the dir tree, deleting all empty dirs.
3249 	 * Return immediately if a dir is not empty.
3250 	 */
3251 	for (;;) {
3252 
3253 		if ((ptr = strrchr(path, '/')) == NULL) {
3254 			return;
3255 		}
3256 
3257 		*ptr = '\0';
3258 
3259 		if (finddev_emptydir(path)) {
3260 			/* directory is empty */
3261 			if (s_rmdir(path) == 0) {
3262 				vprint(REMOVE_MID,
3263 				    "%sremoving empty dir %s\n", fcn, path);
3264 			} else if (errno == EEXIST) {
3265 				vprint(REMOVE_MID,
3266 				    "%sfailed to remove dir: %s\n", fcn, path);
3267 				return;
3268 			}
3269 		} else {
3270 			/* some other file is here, so return */
3271 			vprint(REMOVE_MID, "%sdir not empty: %s\n", fcn, path);
3272 			return;
3273 		}
3274 	}
3275 }
3276 
3277 /*
3278  * This function and all the functions it calls below were added to
3279  * handle the unique problem with world wide names (WWN).  The problem is
3280  * that if a WWN device is moved to another address on the same controller
3281  * its logical link will change, while the physical node remains the same.
3282  * The result is that two logical links will point to the same physical path
3283  * in /devices, the valid link and a stale link. This function will
3284  * find all the stale nodes, though at a significant performance cost.
3285  *
3286  * Caching is used to increase performance.
3287  * A cache will be built from disk if the cache tag doesn't already exist.
3288  * The cache tag is a regular expression "dir_re", which selects a
3289  * subset of disks to search from typically something like
3290  * "dev/cXt[0-9]+d[0-9]+s[0-9]+".  After the cache is built, consistency must
3291  * be maintained, so entries are added as new links are created, and removed
3292  * as old links are deleted.  The whole cache is flushed if we are a daemon,
3293  * and another devfsadm process ran in between.
3294  *
3295  * Once the cache is built, this function finds the cache which matches
3296  * dir_re, and then it searches all links in that cache looking for
3297  * any link whose contents match "valid_link_contents" with a corresponding link
3298  * which does not match "valid_link".  Any such matches are stale and removed.
3299  *
3300  * This happens outside the context of a "reparenting" so we dont need
3301  * redirection.
3302  */
3303 void
devfsadm_rm_stale_links(char * dir_re,char * valid_link,di_node_t node,di_minor_t minor)3304 devfsadm_rm_stale_links(char *dir_re, char *valid_link, di_node_t node,
3305     di_minor_t minor)
3306 {
3307 	link_t *link;
3308 	linkhead_t *head;
3309 	char phy_path[PATH_MAX + 1];
3310 	char *valid_link_contents;
3311 	char *dev_path;
3312 	char rmlink[PATH_MAX + 1];
3313 
3314 	/*
3315 	 * try to use devices path
3316 	 */
3317 	if ((node == lnode) && (minor == lminor)) {
3318 		valid_link_contents = lphy_path;
3319 	} else {
3320 		if ((dev_path = di_devfs_path(node)) == NULL) {
3321 			err_print(DI_DEVFS_PATH_FAILED, strerror(errno));
3322 			devfsadm_exit(1);
3323 			/*NOTREACHED*/
3324 		}
3325 		(void) strcpy(phy_path, dev_path);
3326 		di_devfs_path_free(dev_path);
3327 
3328 		(void) strcat(phy_path, ":");
3329 		(void) strcat(phy_path, di_minor_name(minor));
3330 		valid_link_contents = phy_path;
3331 	}
3332 
3333 	/*
3334 	 * As an optimization, check to make sure the corresponding
3335 	 * devlink was just created before continuing.
3336 	 */
3337 
3338 	if (linknew == FALSE) {
3339 		return;
3340 	}
3341 
3342 	head = get_cached_links(dir_re);
3343 
3344 	assert(head->nextlink == NULL);
3345 
3346 	for (link = head->link; link != NULL; link = head->nextlink) {
3347 		/*
3348 		 * See hot_cleanup() for why we do this
3349 		 */
3350 		head->nextlink = link->next;
3351 		if ((strcmp(link->contents, valid_link_contents) == 0) &&
3352 		    (strcmp(link->devlink, valid_link) != 0)) {
3353 			vprint(CHATTY_MID, "removing %s -> %s\n"
3354 			    "valid link is: %s -> %s\n",
3355 			    link->devlink, link->contents,
3356 			    valid_link, valid_link_contents);
3357 			/*
3358 			 * Use a copy of the cached link name as the
3359 			 * cache entry will go away during link removal
3360 			 */
3361 			(void) snprintf(rmlink, sizeof (rmlink), "%s",
3362 			    link->devlink);
3363 			devfsadm_rm_link(rmlink);
3364 		}
3365 	}
3366 }
3367 
3368 /*
3369  * Return previously created cache, or create cache.
3370  */
3371 static linkhead_t *
get_cached_links(char * dir_re)3372 get_cached_links(char *dir_re)
3373 {
3374 	recurse_dev_t rd;
3375 	linkhead_t *linkhead;
3376 	int n;
3377 
3378 	vprint(BUILDCACHE_MID, "get_cached_links: %s\n", dir_re);
3379 
3380 	for (linkhead = headlinkhead; linkhead != NULL;
3381 	    linkhead = linkhead->nexthead) {
3382 		if (strcmp(linkhead->dir_re, dir_re) == 0) {
3383 			return (linkhead);
3384 		}
3385 	}
3386 
3387 	/*
3388 	 * This tag is not in cache, so add it, along with all its
3389 	 * matching /dev entries.  This is the only time we go to disk.
3390 	 */
3391 	linkhead = s_malloc(sizeof (linkhead_t));
3392 	linkhead->nexthead = headlinkhead;
3393 	headlinkhead = linkhead;
3394 	linkhead->dir_re = s_strdup(dir_re);
3395 
3396 	if ((n = regcomp(&(linkhead->dir_re_compiled), dir_re,
3397 	    REG_EXTENDED)) != 0) {
3398 		err_print(REGCOMP_FAILED,  dir_re, n);
3399 	}
3400 
3401 	linkhead->nextlink = NULL;
3402 	linkhead->link = NULL;
3403 
3404 	rd.fcn = build_devlink_list;
3405 	rd.data = (void *)linkhead;
3406 
3407 	vprint(BUILDCACHE_MID, "get_cached_links: calling recurse_dev_re\n");
3408 
3409 	/* call build_devlink_list for each directory in the dir_re RE */
3410 	if (dir_re[0] == '/') {
3411 		recurse_dev_re("/", &dir_re[1], &rd);
3412 	} else {
3413 		recurse_dev_re(dev_dir, dir_re, &rd);
3414 	}
3415 
3416 	return (linkhead);
3417 }
3418 
3419 static void
build_devlink_list(char * devlink,void * data)3420 build_devlink_list(char *devlink, void *data)
3421 {
3422 	char *fcn = "build_devlink_list: ";
3423 	char *ptr;
3424 	char *r_contents;
3425 	char *r_devlink;
3426 	char contents[PATH_MAX + 1];
3427 	char newlink[PATH_MAX + 1];
3428 	char stage_link[PATH_MAX + 1];
3429 	int linksize;
3430 	linkhead_t *linkhead = (linkhead_t *)data;
3431 	link_t *link;
3432 	int i = 0;
3433 
3434 	vprint(BUILDCACHE_MID, "%scheck_link: %s\n", fcn, devlink);
3435 
3436 	(void) strcpy(newlink, devlink);
3437 
3438 	do {
3439 		/*
3440 		 * None of the consumers of this function need redirection
3441 		 * so this readlink gets the "current" contents
3442 		 */
3443 		linksize = readlink(newlink, contents, PATH_MAX);
3444 		if (linksize <= 0) {
3445 			/*
3446 			 * The first pass through the do loop we may readlink()
3447 			 * non-symlink files(EINVAL) from false regexec matches.
3448 			 * Suppress error messages in those cases or if the link
3449 			 * content is the empty string.
3450 			 */
3451 			if (linksize < 0 && (i || errno != EINVAL))
3452 				err_print(READLINK_FAILED, "build_devlink_list",
3453 				    newlink, strerror(errno));
3454 			return;
3455 		}
3456 		contents[linksize] = '\0';
3457 		i = 1;
3458 
3459 		if (is_minor_node(contents, &r_contents) == DEVFSADM_FALSE) {
3460 			/*
3461 			 * assume that link contents is really a pointer to
3462 			 * another link, so recurse and read its link contents.
3463 			 *
3464 			 * some link contents are absolute:
3465 			 *	/dev/audio -> /dev/sound/0
3466 			 */
3467 			if (strncmp(contents, DEV "/",
3468 			    strlen(DEV) + strlen("/")) != 0) {
3469 
3470 				if ((ptr = strrchr(newlink, '/')) == NULL) {
3471 					vprint(REMOVE_MID, "%s%s -> %s invalid "
3472 					    "link. missing '/'\n", fcn,
3473 					    newlink, contents);
3474 					return;
3475 				}
3476 				*ptr = '\0';
3477 				(void) strcpy(stage_link, newlink);
3478 				*ptr = '/';
3479 				(void) strcat(stage_link, "/");
3480 				(void) strcat(stage_link, contents);
3481 				(void) strcpy(newlink, stage_link);
3482 			} else {
3483 				(void) strcpy(newlink, dev_dir);
3484 				(void) strcat(newlink, "/");
3485 				(void) strcat(newlink,
3486 				    &contents[strlen(DEV) + strlen("/")]);
3487 			}
3488 
3489 		} else {
3490 			newlink[0] = '\0';
3491 		}
3492 	} while (newlink[0] != '\0');
3493 
3494 	if (strncmp(devlink, dev_dir, strlen(dev_dir)) != 0) {
3495 		vprint(BUILDCACHE_MID, "%sinvalid link: %s\n", fcn, devlink);
3496 		return;
3497 	}
3498 
3499 	r_devlink = devlink + strlen(dev_dir);
3500 
3501 	if (r_devlink[0] != '/')
3502 		return;
3503 
3504 	link = s_malloc(sizeof (link_t));
3505 
3506 	/* don't store the '/' after rootdir/dev */
3507 	r_devlink += 1;
3508 
3509 	vprint(BUILDCACHE_MID, "%scaching link: %s\n", fcn, r_devlink);
3510 	link->devlink = s_strdup(r_devlink);
3511 
3512 	link->contents = s_strdup(r_contents);
3513 
3514 	link->next = linkhead->link;
3515 	linkhead->link = link;
3516 }
3517 
3518 /*
3519  * to be consistent, devlink must not begin with / and must be
3520  * relative to /dev/, whereas physpath must contain / and be
3521  * relative to /devices.
3522  */
3523 static void
add_link_to_cache(char * devlink,char * physpath)3524 add_link_to_cache(char *devlink, char *physpath)
3525 {
3526 	linkhead_t *linkhead;
3527 	link_t *link;
3528 	int added = 0;
3529 
3530 	if (file_mods == FALSE) {
3531 		return;
3532 	}
3533 
3534 	vprint(CACHE_MID, "add_link_to_cache: %s -> %s ",
3535 	    devlink, physpath);
3536 
3537 	for (linkhead = headlinkhead; linkhead != NULL;
3538 	    linkhead = linkhead->nexthead) {
3539 		if (regexec(&(linkhead->dir_re_compiled), devlink, 0, NULL, 0)
3540 		    == 0) {
3541 			added++;
3542 			link = s_malloc(sizeof (link_t));
3543 			link->devlink = s_strdup(devlink);
3544 			link->contents = s_strdup(physpath);
3545 			link->next = linkhead->link;
3546 			linkhead->link = link;
3547 		}
3548 	}
3549 
3550 	vprint(CACHE_MID,
3551 	    " %d %s\n", added, added == 0 ? "NOT ADDED" : "ADDED");
3552 }
3553 
3554 /*
3555  * Remove devlink from cache.  Devlink must be relative to /dev/ and not start
3556  * with /.
3557  */
3558 static void
rm_link_from_cache(char * devlink)3559 rm_link_from_cache(char *devlink)
3560 {
3561 	linkhead_t *linkhead;
3562 	link_t **linkp;
3563 	link_t *save;
3564 
3565 	vprint(CACHE_MID, "rm_link_from_cache enter: %s\n", devlink);
3566 
3567 	for (linkhead = headlinkhead; linkhead != NULL;
3568 	    linkhead = linkhead->nexthead) {
3569 		if (regexec(&(linkhead->dir_re_compiled), devlink, 0, NULL, 0)
3570 		    == 0) {
3571 
3572 			for (linkp = &(linkhead->link); *linkp != NULL; ) {
3573 				if ((strcmp((*linkp)->devlink, devlink) == 0)) {
3574 					save = *linkp;
3575 					*linkp = (*linkp)->next;
3576 					/*
3577 					 * We are removing our caller's
3578 					 * "next" link. Update the nextlink
3579 					 * field in the head so that our
3580 					 * callers accesses the next valid
3581 					 * link
3582 					 */
3583 					if (linkhead->nextlink == save)
3584 						linkhead->nextlink = *linkp;
3585 					free(save->devlink);
3586 					free(save->contents);
3587 					free(save);
3588 					vprint(CACHE_MID, " %s FREED FROM "
3589 					    "CACHE\n", devlink);
3590 				} else {
3591 					linkp = &((*linkp)->next);
3592 				}
3593 			}
3594 		}
3595 	}
3596 }
3597 
3598 static void
rm_all_links_from_cache()3599 rm_all_links_from_cache()
3600 {
3601 	linkhead_t *linkhead;
3602 	linkhead_t *nextlinkhead;
3603 	link_t *link;
3604 	link_t *nextlink;
3605 
3606 	vprint(CACHE_MID, "rm_all_links_from_cache\n");
3607 
3608 	for (linkhead = headlinkhead; linkhead != NULL;
3609 	    linkhead = nextlinkhead) {
3610 
3611 		nextlinkhead = linkhead->nexthead;
3612 		assert(linkhead->nextlink == NULL);
3613 		for (link = linkhead->link; link != NULL; link = nextlink) {
3614 			nextlink = link->next;
3615 			free(link->devlink);
3616 			free(link->contents);
3617 			free(link);
3618 		}
3619 		regfree(&(linkhead->dir_re_compiled));
3620 		free(linkhead->dir_re);
3621 		free(linkhead);
3622 	}
3623 	headlinkhead = NULL;
3624 }
3625 
3626 /*
3627  * Called when the kernel has modified the incore path_to_inst data.  This
3628  * function will schedule a flush of the data to the filesystem.
3629  */
3630 static void
devfs_instance_mod(void)3631 devfs_instance_mod(void)
3632 {
3633 	char *fcn = "devfs_instance_mod: ";
3634 	vprint(PATH2INST_MID, "%senter\n", fcn);
3635 
3636 	/* signal instance thread */
3637 	(void) mutex_lock(&count_lock);
3638 	inst_count++;
3639 	(void) cond_signal(&cv);
3640 	(void) mutex_unlock(&count_lock);
3641 }
3642 
3643 static void
instance_flush_thread(void)3644 instance_flush_thread(void)
3645 {
3646 	int i;
3647 	int idle;
3648 
3649 	for (;;) {
3650 
3651 		(void) mutex_lock(&count_lock);
3652 		while (inst_count == 0) {
3653 			(void) cond_wait(&cv, &count_lock);
3654 		}
3655 		inst_count = 0;
3656 
3657 		vprint(PATH2INST_MID, "signaled to flush path_to_inst."
3658 		    " Enter delay loop\n");
3659 		/*
3660 		 * Wait MAX_IDLE_DELAY seconds after getting the last flush
3661 		 * path_to_inst event before invoking a flush, but never wait
3662 		 * more than MAX_DELAY seconds after getting the first event.
3663 		 */
3664 		for (idle = 0, i = 0; i < MAX_DELAY; i++) {
3665 
3666 			(void) mutex_unlock(&count_lock);
3667 			(void) sleep(1);
3668 			(void) mutex_lock(&count_lock);
3669 
3670 			/* shorten the delay if we are idle */
3671 			if (inst_count == 0) {
3672 				idle++;
3673 				if (idle > MAX_IDLE_DELAY) {
3674 					break;
3675 				}
3676 			} else {
3677 				inst_count = idle = 0;
3678 			}
3679 		}
3680 
3681 		(void) mutex_unlock(&count_lock);
3682 
3683 		flush_path_to_inst();
3684 	}
3685 }
3686 
3687 /*
3688  * Helper function for flush_path_to_inst() below; this routine calls the
3689  * inst_sync syscall to flush the path_to_inst database to the given file.
3690  */
3691 static int
do_inst_sync(char * filename,char * instfilename)3692 do_inst_sync(char *filename, char *instfilename)
3693 {
3694 	void (*sigsaved)(int);
3695 	int err = 0, flags = INST_SYNC_IF_REQUIRED;
3696 	struct stat sb;
3697 
3698 	if (stat(instfilename, &sb) == -1 && errno == ENOENT)
3699 		flags = INST_SYNC_ALWAYS;
3700 
3701 	vprint(INSTSYNC_MID, "do_inst_sync: about to flush %s\n", filename);
3702 	sigsaved = sigset(SIGSYS, SIG_IGN);
3703 	if (inst_sync(filename, flags) == -1)
3704 		err = errno;
3705 	(void) sigset(SIGSYS, sigsaved);
3706 
3707 	switch (err) {
3708 	case 0:
3709 		return (DEVFSADM_SUCCESS);
3710 	case EALREADY:	/* no-op, path_to_inst already up to date */
3711 		return (EALREADY);
3712 	case ENOSYS:
3713 		err_print(CANT_LOAD_SYSCALL);
3714 		break;
3715 	case EPERM:
3716 		err_print(SUPER_TO_SYNC);
3717 		break;
3718 	default:
3719 		err_print(INSTSYNC_FAILED, filename, strerror(err));
3720 		break;
3721 	}
3722 	return (DEVFSADM_FAILURE);
3723 }
3724 
3725 /*
3726  * Flush the kernel's path_to_inst database to /etc/path_to_inst.  To do so
3727  * safely, the database is flushed to a temporary file, then moved into place.
3728  *
3729  * The following files are used during this process:
3730  *	/etc/path_to_inst:	The path_to_inst file
3731  *	/etc/path_to_inst.<pid>: Contains data flushed from the kernel
3732  *	/etc/path_to_inst.old:  The backup file
3733  *	/etc/path_to_inst.old.<pid>: Temp file for creating backup
3734  *
3735  */
3736 static void
flush_path_to_inst(void)3737 flush_path_to_inst(void)
3738 {
3739 	char *new_inst_file = NULL;
3740 	char *old_inst_file = NULL;
3741 	char *old_inst_file_npid = NULL;
3742 	FILE *inst_file_fp = NULL;
3743 	FILE *old_inst_file_fp = NULL;
3744 	struct stat sb;
3745 	int err = 0;
3746 	int c;
3747 	int inst_strlen;
3748 
3749 	vprint(PATH2INST_MID, "flush_path_to_inst: %s\n",
3750 	    (flush_path_to_inst_enable == TRUE) ? "ENABLED" : "DISABLED");
3751 
3752 	if (flush_path_to_inst_enable == FALSE) {
3753 		return;
3754 	}
3755 
3756 	inst_strlen = strlen(inst_file);
3757 	new_inst_file = s_malloc(inst_strlen + PID_STR_LEN + 2);
3758 	old_inst_file = s_malloc(inst_strlen + PID_STR_LEN + 6);
3759 	old_inst_file_npid = s_malloc(inst_strlen +
3760 	    sizeof (INSTANCE_FILE_SUFFIX));
3761 
3762 	(void) snprintf(new_inst_file, inst_strlen + PID_STR_LEN + 2,
3763 	    "%s.%ld", inst_file, getpid());
3764 
3765 	if (stat(new_inst_file, &sb) == 0) {
3766 		s_unlink(new_inst_file);
3767 	}
3768 
3769 	err = do_inst_sync(new_inst_file, inst_file);
3770 	if (err != DEVFSADM_SUCCESS) {
3771 		goto out;
3772 		/*NOTREACHED*/
3773 	}
3774 
3775 	/*
3776 	 * Now we deal with the somewhat tricky updating and renaming
3777 	 * of this critical piece of kernel state.
3778 	 */
3779 
3780 	/*
3781 	 * Copy the current instance file into a temporary file.
3782 	 * Then rename the temporary file into the backup (.old)
3783 	 * file and rename the newly flushed kernel data into
3784 	 * the instance file.
3785 	 * Of course if 'inst_file' doesn't exist, there's much
3786 	 * less for us to do .. tee hee.
3787 	 */
3788 	if ((inst_file_fp = fopen(inst_file, "r")) == NULL) {
3789 		/*
3790 		 * No such file.  Rename the new onto the old
3791 		 */
3792 		if ((err = rename(new_inst_file, inst_file)) != 0)
3793 			err_print(RENAME_FAILED, inst_file, strerror(errno));
3794 		goto out;
3795 		/*NOTREACHED*/
3796 	}
3797 
3798 	(void) snprintf(old_inst_file, inst_strlen + PID_STR_LEN + 6,
3799 	    "%s.old.%ld", inst_file, getpid());
3800 
3801 	if (stat(old_inst_file, &sb) == 0) {
3802 		s_unlink(old_inst_file);
3803 	}
3804 
3805 	if ((old_inst_file_fp = fopen(old_inst_file, "w")) == NULL) {
3806 		/*
3807 		 * Can't open the 'old_inst_file' file for writing.
3808 		 * This is somewhat strange given that the syscall
3809 		 * just succeeded to write a file out.. hmm.. maybe
3810 		 * the fs just filled up or something nasty.
3811 		 *
3812 		 * Anyway, abort what we've done so far.
3813 		 */
3814 		err_print(CANT_UPDATE, old_inst_file);
3815 		err = DEVFSADM_FAILURE;
3816 		goto out;
3817 		/*NOTREACHED*/
3818 	}
3819 
3820 	/*
3821 	 * Copy current instance file into the temporary file
3822 	 */
3823 	err = 0;
3824 	while ((c = getc(inst_file_fp)) != EOF) {
3825 		if ((err = putc(c, old_inst_file_fp)) == EOF) {
3826 			break;
3827 		}
3828 	}
3829 
3830 	if (fclose(old_inst_file_fp) == EOF || err == EOF) {
3831 		vprint(INFO_MID, CANT_UPDATE, old_inst_file);
3832 		err = DEVFSADM_FAILURE;
3833 		goto out;
3834 		/* NOTREACHED */
3835 	}
3836 
3837 	/*
3838 	 * Set permissions to be the same on the backup as
3839 	 * /etc/path_to_inst.
3840 	 */
3841 	(void) chmod(old_inst_file, 0444);
3842 
3843 	/*
3844 	 * So far, everything we've done is more or less reversible.
3845 	 * But now we're going to commit ourselves.
3846 	 */
3847 
3848 	(void) snprintf(old_inst_file_npid,
3849 	    inst_strlen + sizeof (INSTANCE_FILE_SUFFIX),
3850 	    "%s%s", inst_file, INSTANCE_FILE_SUFFIX);
3851 
3852 	if ((err = rename(old_inst_file, old_inst_file_npid)) != 0) {
3853 		err_print(RENAME_FAILED, old_inst_file_npid,
3854 		    strerror(errno));
3855 	} else if ((err = rename(new_inst_file, inst_file)) != 0) {
3856 		err_print(RENAME_FAILED, inst_file, strerror(errno));
3857 	}
3858 
3859 out:
3860 	if (inst_file_fp != NULL) {
3861 		if (fclose(inst_file_fp) == EOF) {
3862 			err_print(FCLOSE_FAILED, inst_file, strerror(errno));
3863 		}
3864 	}
3865 
3866 	if (stat(new_inst_file, &sb) == 0) {
3867 		s_unlink(new_inst_file);
3868 	}
3869 	free(new_inst_file);
3870 
3871 	if (stat(old_inst_file, &sb) == 0) {
3872 		s_unlink(old_inst_file);
3873 	}
3874 	free(old_inst_file);
3875 
3876 	free(old_inst_file_npid);
3877 
3878 	if (err != 0 && err != EALREADY) {
3879 		err_print(FAILED_TO_UPDATE, inst_file);
3880 	}
3881 }
3882 
3883 /*
3884  * detach from tty.  For daemon mode.
3885 </