xref: /netbsd-src/sys/kern/kern_drvctl.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /* $NetBSD: kern_drvctl.c,v 1.49 2021/06/16 00:19:46 riastradh Exp $ */
2 
3 /*
4  * Copyright (c) 2004
5  * 	Matthias Drochner.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __KERNEL_RCSID(0, "$NetBSD: kern_drvctl.c,v 1.49 2021/06/16 00:19:46 riastradh Exp $");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/conf.h>
36 #include <sys/device.h>
37 #include <sys/event.h>
38 #include <sys/kmem.h>
39 #include <sys/ioctl.h>
40 #include <sys/fcntl.h>
41 #include <sys/file.h>
42 #include <sys/filedesc.h>
43 #include <sys/select.h>
44 #include <sys/poll.h>
45 #include <sys/drvctlio.h>
46 #include <sys/devmon.h>
47 #include <sys/stat.h>
48 #include <sys/kauth.h>
49 #include <sys/lwp.h>
50 #include <sys/module.h>
51 
52 #include "ioconf.h"
53 
54 struct drvctl_event {
55 	TAILQ_ENTRY(drvctl_event) dce_link;
56 	prop_dictionary_t	dce_event;
57 };
58 
59 TAILQ_HEAD(drvctl_queue, drvctl_event);
60 
61 static struct drvctl_queue	drvctl_eventq;		/* FIFO */
62 static kcondvar_t		drvctl_cond;
63 static kmutex_t			drvctl_lock;
64 static int			drvctl_nopen = 0, drvctl_eventcnt = 0;
65 static struct selinfo		drvctl_rdsel;
66 
67 #define DRVCTL_EVENTQ_DEPTH	64	/* arbitrary queue limit */
68 
69 dev_type_open(drvctlopen);
70 
71 const struct cdevsw drvctl_cdevsw = {
72 	.d_open = drvctlopen,
73 	.d_close = nullclose,
74 	.d_read = nullread,
75 	.d_write = nullwrite,
76 	.d_ioctl = noioctl,
77 	.d_stop = nostop,
78 	.d_tty = notty,
79 	.d_poll = nopoll,
80 	.d_mmap = nommap,
81 	.d_kqfilter = nokqfilter,
82 	.d_discard = nodiscard,
83 	.d_flag = D_OTHER
84 };
85 
86 static int	drvctl_read(struct file *, off_t *, struct uio *,
87 			    kauth_cred_t, int);
88 static int	drvctl_write(struct file *, off_t *, struct uio *,
89 			     kauth_cred_t, int);
90 static int	drvctl_ioctl(struct file *, u_long, void *);
91 static int	drvctl_poll(struct file *, int);
92 static int	drvctl_stat(struct file *, struct stat *);
93 static int	drvctl_close(struct file *);
94 
95 static const struct fileops drvctl_fileops = {
96 	.fo_name = "drvctl",
97 	.fo_read = drvctl_read,
98 	.fo_write = drvctl_write,
99 	.fo_ioctl = drvctl_ioctl,
100 	.fo_fcntl = fnullop_fcntl,
101 	.fo_poll = drvctl_poll,
102 	.fo_stat = drvctl_stat,
103 	.fo_close = drvctl_close,
104 	.fo_kqfilter = fnullop_kqfilter,
105 	.fo_restart = fnullop_restart,
106 };
107 
108 #define MAXLOCATORS 100
109 
110 static int (*saved_insert_vec)(const char *, prop_dictionary_t) = NULL;
111 
112 static int drvctl_command(struct lwp *, struct plistref *, u_long, int);
113 static int drvctl_getevent(struct lwp *, struct plistref *, u_long, int);
114 
115 void
116 drvctl_init(void)
117 {
118 	TAILQ_INIT(&drvctl_eventq);
119 	mutex_init(&drvctl_lock, MUTEX_DEFAULT, IPL_NONE);
120 	cv_init(&drvctl_cond, "devmon");
121 	selinit(&drvctl_rdsel);
122 }
123 
124 void
125 drvctl_fini(void)
126 {
127 
128 	seldestroy(&drvctl_rdsel);
129 	cv_destroy(&drvctl_cond);
130 	mutex_destroy(&drvctl_lock);
131 }
132 
133 int
134 devmon_insert(const char *event, prop_dictionary_t ev)
135 {
136 	struct drvctl_event *dce, *odce;
137 
138 	mutex_enter(&drvctl_lock);
139 
140 	if (drvctl_nopen == 0) {
141 		prop_object_release(ev);
142 		mutex_exit(&drvctl_lock);
143 		return 0;
144 	}
145 
146 	/* Fill in mandatory member */
147 	if (!prop_dictionary_set_string_nocopy(ev, "event", event)) {
148 		prop_object_release(ev);
149 		mutex_exit(&drvctl_lock);
150 		return 0;
151 	}
152 
153 	dce = kmem_alloc(sizeof(*dce), KM_SLEEP);
154 	dce->dce_event = ev;
155 
156 	if (drvctl_eventcnt == DRVCTL_EVENTQ_DEPTH) {
157 		odce = TAILQ_FIRST(&drvctl_eventq);
158 		TAILQ_REMOVE(&drvctl_eventq, odce, dce_link);
159 		prop_object_release(odce->dce_event);
160 		kmem_free(odce, sizeof(*odce));
161 		--drvctl_eventcnt;
162 	}
163 
164 	TAILQ_INSERT_TAIL(&drvctl_eventq, dce, dce_link);
165 	++drvctl_eventcnt;
166 	cv_broadcast(&drvctl_cond);
167 	selnotify(&drvctl_rdsel, 0, 0);
168 
169 	mutex_exit(&drvctl_lock);
170 	return 0;
171 }
172 
173 int
174 drvctlopen(dev_t dev, int flags, int mode, struct lwp *l)
175 {
176 	struct file *fp;
177 	int fd;
178 	int ret;
179 
180 	ret = fd_allocfile(&fp, &fd);
181 	if (ret)
182 		return ret;
183 
184 	/* XXX setup context */
185 	mutex_enter(&drvctl_lock);
186 	ret = fd_clone(fp, fd, flags, &drvctl_fileops, /* context */NULL);
187 	++drvctl_nopen;
188 	mutex_exit(&drvctl_lock);
189 
190 	return ret;
191 }
192 
193 static int
194 pmdevbyname(u_long cmd, struct devpmargs *a)
195 {
196 	device_t d;
197 
198 	KASSERT(KERNEL_LOCKED_P());
199 
200 	if ((d = device_find_by_xname(a->devname)) == NULL)
201 		return ENXIO;
202 
203 	switch (cmd) {
204 	case DRVSUSPENDDEV:
205 		return pmf_device_recursive_suspend(d, PMF_Q_DRVCTL) ? 0 : EBUSY;
206 	case DRVRESUMEDEV:
207 		if (a->flags & DEVPM_F_SUBTREE) {
208 			return pmf_device_subtree_resume(d, PMF_Q_DRVCTL)
209 			    ? 0 : EBUSY;
210 		} else {
211 			return pmf_device_recursive_resume(d, PMF_Q_DRVCTL)
212 			    ? 0 : EBUSY;
213 		}
214 	default:
215 		return EPASSTHROUGH;
216 	}
217 }
218 
219 static int
220 listdevbyname(struct devlistargs *l)
221 {
222 	device_t d, child;
223 	deviter_t di;
224 	int cnt = 0, idx, error = 0;
225 
226 	KASSERT(KERNEL_LOCKED_P());
227 
228 	if (*l->l_devname == '\0')
229 		d = NULL;
230 	else if (memchr(l->l_devname, 0, sizeof(l->l_devname)) == NULL)
231 		return EINVAL;
232 	else if ((d = device_find_by_xname(l->l_devname)) == NULL)
233 		return ENXIO;
234 
235 	for (child = deviter_first(&di, 0); child != NULL;
236 	     child = deviter_next(&di)) {
237 		if (device_parent(child) != d)
238 			continue;
239 		idx = cnt++;
240 		if (l->l_childname == NULL || idx >= l->l_children)
241 			continue;
242 		error = copyoutstr(device_xname(child), l->l_childname[idx],
243 				sizeof(l->l_childname[idx]), NULL);
244 		if (error != 0)
245 			break;
246 	}
247 	deviter_release(&di);
248 
249 	l->l_children = cnt;
250 	return error;
251 }
252 
253 static int
254 detachdevbyname(const char *devname)
255 {
256 	device_t d;
257 	deviter_t di;
258 	int error;
259 
260 	KASSERT(KERNEL_LOCKED_P());
261 
262 	for (d = deviter_first(&di, DEVITER_F_RW);
263 	     d != NULL;
264 	     d = deviter_next(&di)) {
265 		if (strcmp(device_xname(d), devname) == 0)
266 			break;
267 	}
268 	if (d == NULL) {
269 		error = ENXIO;
270 		goto out;
271 	}
272 
273 #ifndef XXXFULLRISK
274 	/*
275 	 * If the parent cannot be notified, it might keep
276 	 * pointers to the detached device.
277 	 * There might be a private notification mechanism,
278 	 * but better play it safe here.
279 	 */
280 	if (d->dv_parent && !d->dv_parent->dv_cfattach->ca_childdetached) {
281 		error = ENOTSUP;
282 		goto out;
283 	}
284 #endif
285 
286 	error = config_detach(d, 0);
287 out:	deviter_release(&di);
288 	return error;
289 }
290 
291 static int
292 rescanbus(const char *busname, const char *ifattr,
293 	  int numlocators, const int *locators)
294 {
295 	int i, rc;
296 	device_t d;
297 	const struct cfiattrdata * const *ap;
298 
299 	KASSERT(KERNEL_LOCKED_P());
300 
301 	/* XXX there should be a way to get limits and defaults (per device)
302 	   from config generated data */
303 	int locs[MAXLOCATORS];
304 	for (i = 0; i < MAXLOCATORS; i++)
305 		locs[i] = -1;
306 
307 	for (i = 0; i < numlocators;i++)
308 		locs[i] = locators[i];
309 
310 	if ((d = device_find_by_xname(busname)) == NULL)
311 		return ENXIO;
312 
313 	/*
314 	 * must support rescan, and must have something
315 	 * to attach to
316 	 */
317 	if (!d->dv_cfattach->ca_rescan ||
318 	    !d->dv_cfdriver->cd_attrs)
319 		return ENODEV;
320 
321 	/* rescan all ifattrs if none is specified */
322 	if (!ifattr) {
323 		rc = 0;
324 		for (ap = d->dv_cfdriver->cd_attrs; *ap; ap++) {
325 			rc = (*d->dv_cfattach->ca_rescan)(d, (*ap)->ci_name,
326 			    locs);
327 			if (rc)
328 				break;
329 		}
330 	} else {
331 		/* check for valid attribute passed */
332 		for (ap = d->dv_cfdriver->cd_attrs; *ap; ap++)
333 			if (!strcmp((*ap)->ci_name, ifattr))
334 				break;
335 		if (!*ap)
336 			return EINVAL;
337 		rc = (*d->dv_cfattach->ca_rescan)(d, ifattr, locs);
338 	}
339 
340 	config_deferred(NULL);
341 	return rc;
342 }
343 
344 static int
345 drvctl_read(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
346     int flags)
347 {
348 	return ENODEV;
349 }
350 
351 static int
352 drvctl_write(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
353     int flags)
354 {
355 	return ENODEV;
356 }
357 
358 static int
359 drvctl_ioctl(struct file *fp, u_long cmd, void *data)
360 {
361 	int res;
362 	char *ifattr;
363 	int *locs;
364 	size_t locs_sz = 0; /* XXXgcc */
365 
366 	KERNEL_LOCK(1, NULL);
367 	switch (cmd) {
368 	case DRVSUSPENDDEV:
369 	case DRVRESUMEDEV:
370 #define d ((struct devpmargs *)data)
371 		res = pmdevbyname(cmd, d);
372 #undef d
373 		break;
374 	case DRVLISTDEV:
375 		res = listdevbyname((struct devlistargs *)data);
376 		break;
377 	case DRVDETACHDEV:
378 #define d ((struct devdetachargs *)data)
379 		res = detachdevbyname(d->devname);
380 #undef d
381 		break;
382 	case DRVRESCANBUS:
383 #define d ((struct devrescanargs *)data)
384 		d->busname[sizeof(d->busname) - 1] = '\0';
385 
386 		/* XXX better copyin? */
387 		if (d->ifattr[0]) {
388 			d->ifattr[sizeof(d->ifattr) - 1] = '\0';
389 			ifattr = d->ifattr;
390 		} else
391 			ifattr = 0;
392 
393 		if (d->numlocators) {
394 			if (d->numlocators > MAXLOCATORS) {
395 				res = EINVAL;
396 				goto out;
397 			}
398 			locs_sz = d->numlocators * sizeof(int);
399 			locs = kmem_alloc(locs_sz, KM_SLEEP);
400 			res = copyin(d->locators, locs, locs_sz);
401 			if (res) {
402 				kmem_free(locs, locs_sz);
403 				goto out;
404 			}
405 		} else
406 			locs = NULL;
407 		res = rescanbus(d->busname, ifattr, d->numlocators, locs);
408 		if (locs)
409 			kmem_free(locs, locs_sz);
410 #undef d
411 		break;
412 	case DRVCTLCOMMAND:
413 	    	res = drvctl_command(curlwp, (struct plistref *)data, cmd,
414 		    fp->f_flag);
415 	    	break;
416 	case DRVGETEVENT:
417 		res = drvctl_getevent(curlwp, (struct plistref *)data, cmd,
418 		    fp->f_flag);
419 		break;
420 	default:
421 		res = EPASSTHROUGH;
422 		break;
423 	}
424 out:	KERNEL_UNLOCK_ONE(NULL);
425 	return res;
426 }
427 
428 static int
429 drvctl_stat(struct file *fp, struct stat *st)
430 {
431 	(void)memset(st, 0, sizeof(*st));
432 	st->st_uid = kauth_cred_geteuid(fp->f_cred);
433 	st->st_gid = kauth_cred_getegid(fp->f_cred);
434 	return 0;
435 }
436 
437 static int
438 drvctl_poll(struct file *fp, int events)
439 {
440 	int revents = 0;
441 
442 	if (!TAILQ_EMPTY(&drvctl_eventq))
443 		revents |= events & (POLLIN | POLLRDNORM);
444 	else
445 		selrecord(curlwp, &drvctl_rdsel);
446 
447 	return revents;
448 }
449 
450 static int
451 drvctl_close(struct file *fp)
452 {
453 	struct drvctl_event *dce;
454 
455 	/* XXX free context */
456 	mutex_enter(&drvctl_lock);
457 	KASSERT(drvctl_nopen > 0);
458 	--drvctl_nopen;
459 	if (drvctl_nopen == 0) {
460 		/* flush queue */
461 		while ((dce = TAILQ_FIRST(&drvctl_eventq)) != NULL) {
462 			TAILQ_REMOVE(&drvctl_eventq, dce, dce_link);
463 			KASSERT(drvctl_eventcnt > 0);
464 			--drvctl_eventcnt;
465 			prop_object_release(dce->dce_event);
466 			kmem_free(dce, sizeof(*dce));
467 		}
468 	}
469 	mutex_exit(&drvctl_lock);
470 
471 	return 0;
472 }
473 
474 void
475 drvctlattach(int arg __unused)
476 {
477 }
478 
479 /*****************************************************************************
480  * Driver control command processing engine
481  *****************************************************************************/
482 
483 static int
484 drvctl_command_get_properties(struct lwp *l,
485 			      prop_dictionary_t command_dict,
486 			      prop_dictionary_t results_dict)
487 {
488 	prop_dictionary_t args_dict;
489 	prop_string_t devname_string;
490 	device_t dev;
491 	deviter_t di;
492 
493 	args_dict = prop_dictionary_get(command_dict, "drvctl-arguments");
494 	if (args_dict == NULL)
495 		return EINVAL;
496 
497 	devname_string = prop_dictionary_get(args_dict, "device-name");
498 	if (devname_string == NULL)
499 		return EINVAL;
500 
501 	for (dev = deviter_first(&di, 0); dev != NULL;
502 	     dev = deviter_next(&di)) {
503 		if (prop_string_equals_string(devname_string,
504 					       device_xname(dev))) {
505 			prop_dictionary_set(results_dict, "drvctl-result-data",
506 			    device_properties(dev));
507 			break;
508 		}
509 	}
510 
511 	deviter_release(&di);
512 
513 	if (dev == NULL)
514 		return ESRCH;
515 
516 	return 0;
517 }
518 
519 struct drvctl_command_desc {
520 	const char *dcd_name;		/* command name */
521 	int (*dcd_func)(struct lwp *,	/* handler function */
522 			prop_dictionary_t,
523 			prop_dictionary_t);
524 	int dcd_rw;			/* read or write required */
525 };
526 
527 static const struct drvctl_command_desc drvctl_command_table[] = {
528 	{ .dcd_name = "get-properties",
529 	  .dcd_func = drvctl_command_get_properties,
530 	  .dcd_rw   = FREAD,
531 	},
532 
533 	{ .dcd_name = NULL }
534 };
535 
536 static int
537 drvctl_command(struct lwp *l, struct plistref *pref, u_long ioctl_cmd,
538 	       int fflag)
539 {
540 	prop_dictionary_t command_dict, results_dict;
541 	prop_string_t command_string;
542 	const struct drvctl_command_desc *dcd;
543 	int error;
544 
545 	error = prop_dictionary_copyin_ioctl(pref, ioctl_cmd, &command_dict);
546 	if (error)
547 		return error;
548 
549 	results_dict = prop_dictionary_create();
550 	if (results_dict == NULL) {
551 		prop_object_release(command_dict);
552 		return ENOMEM;
553 	}
554 
555 	command_string = prop_dictionary_get(command_dict, "drvctl-command");
556 	if (command_string == NULL) {
557 		error = EINVAL;
558 		goto out;
559 	}
560 
561 	for (dcd = drvctl_command_table; dcd->dcd_name != NULL; dcd++) {
562 		if (prop_string_equals_string(command_string,
563 					      dcd->dcd_name))
564 			break;
565 	}
566 
567 	if (dcd->dcd_name == NULL) {
568 		error = EINVAL;
569 		goto out;
570 	}
571 
572 	if ((fflag & dcd->dcd_rw) == 0) {
573 		error = EPERM;
574 		goto out;
575 	}
576 
577 	error = (*dcd->dcd_func)(l, command_dict, results_dict);
578 
579 	prop_dictionary_set_int32(results_dict, "drvctl-error", error);
580 
581 	error = prop_dictionary_copyout_ioctl(pref, ioctl_cmd, results_dict);
582  out:
583 	prop_object_release(command_dict);
584 	prop_object_release(results_dict);
585 	return error;
586 }
587 
588 static int
589 drvctl_getevent(struct lwp *l, struct plistref *pref, u_long ioctl_cmd,
590 	        int fflag)
591 {
592 	struct drvctl_event *dce;
593 	int ret;
594 
595 	if ((fflag & (FREAD|FWRITE)) != (FREAD|FWRITE))
596 		return EPERM;
597 
598 	mutex_enter(&drvctl_lock);
599 	while ((dce = TAILQ_FIRST(&drvctl_eventq)) == NULL) {
600 		if (fflag & O_NONBLOCK) {
601 			mutex_exit(&drvctl_lock);
602 			return EWOULDBLOCK;
603 		}
604 
605 		ret = cv_wait_sig(&drvctl_cond, &drvctl_lock);
606 		if (ret) {
607 			mutex_exit(&drvctl_lock);
608 			return ret;
609 		}
610 	}
611 	TAILQ_REMOVE(&drvctl_eventq, dce, dce_link);
612 	KASSERT(drvctl_eventcnt > 0);
613 	--drvctl_eventcnt;
614 	mutex_exit(&drvctl_lock);
615 
616 	ret = prop_dictionary_copyout_ioctl(pref, ioctl_cmd, dce->dce_event);
617 
618 	prop_object_release(dce->dce_event);
619 	kmem_free(dce, sizeof(*dce));
620 
621 	return ret;
622 }
623 
624 /*
625  * Module glue
626  */
627 
628 MODULE(MODULE_CLASS_DRIVER, drvctl, NULL);
629 
630 int
631 drvctl_modcmd(modcmd_t cmd, void *arg)
632 {
633 	int error;
634 #ifdef _MODULE
635 	int bmajor, cmajor;
636 #endif
637 
638 	error = 0;
639 	switch (cmd) {
640 	case MODULE_CMD_INIT:
641 		drvctl_init();
642 
643 		mutex_enter(&drvctl_lock);
644 #ifdef _MODULE
645 		bmajor = cmajor = -1;
646 		error = devsw_attach("drvctl", NULL, &bmajor,
647 		    &drvctl_cdevsw, &cmajor);
648 #endif
649 		if (error == 0) {
650 			KASSERT(saved_insert_vec == NULL);
651 			saved_insert_vec = devmon_insert_vec;
652 			devmon_insert_vec = devmon_insert;
653 		}
654 
655 		mutex_exit(&drvctl_lock);
656 		break;
657 
658 	case MODULE_CMD_FINI:
659 		mutex_enter(&drvctl_lock);
660 		if (drvctl_nopen != 0 || drvctl_eventcnt != 0 ) {
661 			mutex_exit(&drvctl_lock);
662 			return EBUSY;
663 		}
664 		KASSERT(saved_insert_vec != NULL);
665 		devmon_insert_vec = saved_insert_vec;
666 		saved_insert_vec = NULL;
667 #ifdef _MODULE
668 		error = devsw_detach(NULL, &drvctl_cdevsw);
669 		if (error != 0) {
670 			saved_insert_vec = devmon_insert_vec;
671 			devmon_insert_vec = devmon_insert;
672 		}
673 #endif
674 		mutex_exit(&drvctl_lock);
675 		if (error == 0)
676 			drvctl_fini();
677 
678 		break;
679 	default:
680 		error = ENOTTY;
681 		break;
682 	}
683 
684 	return error;
685 }
686