1/* $NetBSD: kern_drvctl.c,v 1.32 2011/08/31 18:31:02 plunky 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.32 2011/08/31 18:31:02 plunky 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
51struct drvctl_event {
52	TAILQ_ENTRY(drvctl_event) dce_link;
53	prop_dictionary_t	dce_event;
54};
55
56TAILQ_HEAD(drvctl_queue, drvctl_event);
57
58static struct drvctl_queue	drvctl_eventq;		/* FIFO */
59static kcondvar_t		drvctl_cond;
60static kmutex_t			drvctl_lock;
61static int			drvctl_nopen = 0, drvctl_eventcnt = 0;
62static struct selinfo		drvctl_rdsel;
63
64#define DRVCTL_EVENTQ_DEPTH	64	/* arbitrary queue limit */
65
66dev_type_open(drvctlopen);
67
68const struct cdevsw drvctl_cdevsw = {
69	drvctlopen, nullclose, nullread, nullwrite, noioctl,
70	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER
71};
72
73void drvctlattach(int);
74
75static int	drvctl_read(struct file *, off_t *, struct uio *,
76			    kauth_cred_t, int);
77static int	drvctl_write(struct file *, off_t *, struct uio *,
78			     kauth_cred_t, int);
79static int	drvctl_ioctl(struct file *, u_long, void *);
80static int	drvctl_poll(struct file *, int);
81static int	drvctl_stat(struct file *, struct stat *);
82static int	drvctl_close(struct file *);
83
84static const struct fileops drvctl_fileops = {
85	.fo_read = drvctl_read,
86	.fo_write = drvctl_write,
87	.fo_ioctl = drvctl_ioctl,
88	.fo_fcntl = fnullop_fcntl,
89	.fo_poll = drvctl_poll,
90	.fo_stat = drvctl_stat,
91	.fo_close = drvctl_close,
92	.fo_kqfilter = fnullop_kqfilter,
93	.fo_restart = fnullop_restart,
94};
95
96#define MAXLOCATORS 100
97
98static int drvctl_command(struct lwp *, struct plistref *, u_long, int);
99static int drvctl_getevent(struct lwp *, struct plistref *, u_long, int);
100
101void
102drvctl_init(void)
103{
104	TAILQ_INIT(&drvctl_eventq);
105	mutex_init(&drvctl_lock, MUTEX_DEFAULT, IPL_NONE);
106	cv_init(&drvctl_cond, "devmon");
107	selinit(&drvctl_rdsel);
108}
109
110void
111devmon_insert(const char *event, prop_dictionary_t ev)
112{
113	struct drvctl_event *dce, *odce;
114
115	mutex_enter(&drvctl_lock);
116
117	if (drvctl_nopen == 0) {
118		prop_object_release(ev);
119		mutex_exit(&drvctl_lock);
120		return;
121	}
122
123	/* Fill in mandatory member */
124	if (!prop_dictionary_set_cstring_nocopy(ev, "event", event)) {
125		prop_object_release(ev);
126		mutex_exit(&drvctl_lock);
127		return;
128	}
129
130	dce = kmem_alloc(sizeof(*dce), KM_SLEEP);
131	if (dce == NULL) {
132		prop_object_release(ev);
133		mutex_exit(&drvctl_lock);
134		return;
135	}
136
137	dce->dce_event = ev;
138
139	if (drvctl_eventcnt == DRVCTL_EVENTQ_DEPTH) {
140		odce = TAILQ_FIRST(&drvctl_eventq);
141		TAILQ_REMOVE(&drvctl_eventq, odce, dce_link);
142		prop_object_release(odce->dce_event);
143		kmem_free(odce, sizeof(*odce));
144		--drvctl_eventcnt;
145	}
146
147	TAILQ_INSERT_TAIL(&drvctl_eventq, dce, dce_link);
148	++drvctl_eventcnt;
149	cv_broadcast(&drvctl_cond);
150	selnotify(&drvctl_rdsel, 0, 0);
151
152	mutex_exit(&drvctl_lock);
153}
154
155int
156drvctlopen(dev_t dev, int flags, int mode, struct lwp *l)
157{
158	struct file *fp;
159	int fd;
160	int ret;
161
162	ret = fd_allocfile(&fp, &fd);
163	if (ret)
164		return ret;
165
166	/* XXX setup context */
167	mutex_enter(&drvctl_lock);
168	ret = fd_clone(fp, fd, flags, &drvctl_fileops, /* context */NULL);
169	++drvctl_nopen;
170	mutex_exit(&drvctl_lock);
171
172	return ret;
173}
174
175static int
176pmdevbyname(u_long cmd, struct devpmargs *a)
177{
178	struct device *d;
179
180	if ((d = device_find_by_xname(a->devname)) == NULL)
181		return ENXIO;
182
183	switch (cmd) {
184	case DRVSUSPENDDEV:
185		return pmf_device_recursive_suspend(d, PMF_Q_DRVCTL) ? 0 : EBUSY;
186	case DRVRESUMEDEV:
187		if (a->flags & DEVPM_F_SUBTREE) {
188			return pmf_device_subtree_resume(d, PMF_Q_DRVCTL)
189			    ? 0 : EBUSY;
190		} else {
191			return pmf_device_recursive_resume(d, PMF_Q_DRVCTL)
192			    ? 0 : EBUSY;
193		}
194	default:
195		return EPASSTHROUGH;
196	}
197}
198
199static int
200listdevbyname(struct devlistargs *l)
201{
202	device_t d, child;
203	deviter_t di;
204	int cnt = 0, idx, error = 0;
205
206	if (*l->l_devname == '\0')
207		d = NULL;
208	else if (memchr(l->l_devname, 0, sizeof(l->l_devname)) == NULL)
209		return EINVAL;
210	else if ((d = device_find_by_xname(l->l_devname)) == NULL)
211		return ENXIO;
212
213	for (child = deviter_first(&di, 0); child != NULL;
214	     child = deviter_next(&di)) {
215		if (device_parent(child) != d)
216			continue;
217		idx = cnt++;
218		if (l->l_childname == NULL || idx >= l->l_children)
219			continue;
220		error = copyoutstr(device_xname(child), l->l_childname[idx],
221				sizeof(l->l_childname[idx]), NULL);
222		if (error != 0)
223			break;
224	}
225	deviter_release(&di);
226
227	l->l_children = cnt;
228	return error;
229}
230
231static int
232detachdevbyname(const char *devname)
233{
234	struct device *d;
235
236	if ((d = device_find_by_xname(devname)) == NULL)
237		return ENXIO;
238
239#ifndef XXXFULLRISK
240	/*
241	 * If the parent cannot be notified, it might keep
242	 * pointers to the detached device.
243	 * There might be a private notification mechanism,
244	 * but better play it safe here.
245	 */
246	if (d->dv_parent && !d->dv_parent->dv_cfattach->ca_childdetached)
247		return ENOTSUP;
248#endif
249	return config_detach(d, 0);
250}
251
252static int
253rescanbus(const char *busname, const char *ifattr,
254	  int numlocators, const int *locators)
255{
256	int i, rc;
257	struct device *d;
258	const struct cfiattrdata * const *ap;
259
260	/* XXX there should be a way to get limits and defaults (per device)
261	   from config generated data */
262	int locs[MAXLOCATORS];
263	for (i = 0; i < MAXLOCATORS; i++)
264		locs[i] = -1;
265
266	for (i = 0; i < numlocators;i++)
267		locs[i] = locators[i];
268
269	if ((d = device_find_by_xname(busname)) == NULL)
270		return ENXIO;
271
272	/*
273	 * must support rescan, and must have something
274	 * to attach to
275	 */
276	if (!d->dv_cfattach->ca_rescan ||
277	    !d->dv_cfdriver->cd_attrs)
278		return ENODEV;
279
280	/* allow to omit attribute if there is exactly one */
281	if (!ifattr) {
282		if (d->dv_cfdriver->cd_attrs[1])
283			return EINVAL;
284		ifattr = d->dv_cfdriver->cd_attrs[0]->ci_name;
285	} else {
286		/* check for valid attribute passed */
287		for (ap = d->dv_cfdriver->cd_attrs; *ap; ap++)
288			if (!strcmp((*ap)->ci_name, ifattr))
289				break;
290		if (!*ap)
291			return EINVAL;
292	}
293
294	rc = (*d->dv_cfattach->ca_rescan)(d, ifattr, locs);
295	config_deferred(NULL);
296	return rc;
297}
298
299static int
300drvctl_read(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
301    int flags)
302{
303	return ENODEV;
304}
305
306static int
307drvctl_write(struct file *fp, off_t *offp, struct uio *uio, kauth_cred_t cred,
308    int flags)
309{
310	return ENODEV;
311}
312
313static int
314drvctl_ioctl(struct file *fp, u_long cmd, void *data)
315{
316	int res;
317	char *ifattr;
318	int *locs;
319	size_t locs_sz = 0; /* XXXgcc */
320
321	switch (cmd) {
322	case DRVSUSPENDDEV:
323	case DRVRESUMEDEV:
324#define d ((struct devpmargs *)data)
325		res = pmdevbyname(cmd, d);
326#undef d
327		break;
328	case DRVLISTDEV:
329		res = listdevbyname((struct devlistargs *)data);
330		break;
331	case DRVDETACHDEV:
332#define d ((struct devdetachargs *)data)
333		res = detachdevbyname(d->devname);
334#undef d
335		break;
336	case DRVRESCANBUS:
337#define d ((struct devrescanargs *)data)
338		d->busname[sizeof(d->busname) - 1] = '\0';
339
340		/* XXX better copyin? */
341		if (d->ifattr[0]) {
342			d->ifattr[sizeof(d->ifattr) - 1] = '\0';
343			ifattr = d->ifattr;
344		} else
345			ifattr = 0;
346
347		if (d->numlocators) {
348			if (d->numlocators > MAXLOCATORS)
349				return EINVAL;
350			locs_sz = d->numlocators * sizeof(int);
351			locs = kmem_alloc(locs_sz, KM_SLEEP);
352			res = copyin(d->locators, locs, locs_sz);
353			if (res) {
354				kmem_free(locs, locs_sz);
355				return res;
356			}
357		} else
358			locs = NULL;
359		res = rescanbus(d->busname, ifattr, d->numlocators, locs);
360		if (locs)
361			kmem_free(locs, locs_sz);
362#undef d
363		break;
364	case DRVCTLCOMMAND:
365	    	res = drvctl_command(curlwp, (struct plistref *)data, cmd,
366		    fp->f_flag);
367	    	break;
368	case DRVGETEVENT:
369		res = drvctl_getevent(curlwp, (struct plistref *)data, cmd,
370		    fp->f_flag);
371		break;
372	default:
373		return EPASSTHROUGH;
374	}
375	return res;
376}
377
378static int
379drvctl_stat(struct file *fp, struct stat *st)
380{
381	(void)memset(st, 0, sizeof(*st));
382	st->st_uid = kauth_cred_geteuid(fp->f_cred);
383	st->st_gid = kauth_cred_getegid(fp->f_cred);
384	return 0;
385}
386
387static int
388drvctl_poll(struct file *fp, int events)
389{
390	int revents = 0;
391
392	if (!TAILQ_EMPTY(&drvctl_eventq))
393		revents |= events & (POLLIN | POLLRDNORM);
394	else
395		selrecord(curlwp, &drvctl_rdsel);
396
397	return revents;
398}
399
400static int
401drvctl_close(struct file *fp)
402{
403	struct drvctl_event *dce;
404
405	/* XXX free context */
406	mutex_enter(&drvctl_lock);
407	KASSERT(drvctl_nopen > 0);
408	--drvctl_nopen;
409	if (drvctl_nopen == 0) {
410		/* flush queue */
411		while ((dce = TAILQ_FIRST(&drvctl_eventq)) != NULL) {
412			TAILQ_REMOVE(&drvctl_eventq, dce, dce_link);
413			KASSERT(drvctl_eventcnt > 0);
414			--drvctl_eventcnt;
415			prop_object_release(dce->dce_event);
416			kmem_free(dce, sizeof(*dce));
417		}
418	}
419	mutex_exit(&drvctl_lock);
420
421	return 0;
422}
423
424void
425drvctlattach(int arg)
426{
427}
428
429/*****************************************************************************
430 * Driver control command processing engine
431 *****************************************************************************/
432
433static int
434drvctl_command_get_properties(struct lwp *l,
435			      prop_dictionary_t command_dict,
436			      prop_dictionary_t results_dict)
437{
438	prop_dictionary_t args_dict;
439	prop_string_t devname_string;
440	device_t dev;
441	deviter_t di;
442
443	args_dict = prop_dictionary_get(command_dict, "drvctl-arguments");
444	if (args_dict == NULL)
445		return EINVAL;
446
447	devname_string = prop_dictionary_get(args_dict, "device-name");
448	if (devname_string == NULL)
449		return EINVAL;
450
451	for (dev = deviter_first(&di, 0); dev != NULL;
452	     dev = deviter_next(&di)) {
453		if (prop_string_equals_cstring(devname_string,
454					       device_xname(dev))) {
455			prop_dictionary_set(results_dict, "drvctl-result-data",
456			    device_properties(dev));
457			break;
458		}
459	}
460
461	deviter_release(&di);
462
463	if (dev == NULL)
464		return ESRCH;
465
466	return 0;
467}
468
469struct drvctl_command_desc {
470	const char *dcd_name;		/* command name */
471	int (*dcd_func)(struct lwp *,	/* handler function */
472			prop_dictionary_t,
473			prop_dictionary_t);
474	int dcd_rw;			/* read or write required */
475};
476
477static const struct drvctl_command_desc drvctl_command_table[] = {
478	{ .dcd_name = "get-properties",
479	  .dcd_func = drvctl_command_get_properties,
480	  .dcd_rw   = FREAD,
481	},
482
483	{ .dcd_name = NULL }
484};
485
486static int
487drvctl_command(struct lwp *l, struct plistref *pref, u_long ioctl_cmd,
488	       int fflag)
489{
490	prop_dictionary_t command_dict, results_dict;
491	prop_string_t command_string;
492	const struct drvctl_command_desc *dcd;
493	int error;
494
495	error = prop_dictionary_copyin_ioctl(pref, ioctl_cmd, &command_dict);
496	if (error)
497		return error;
498
499	results_dict = prop_dictionary_create();
500	if (results_dict == NULL) {
501		prop_object_release(command_dict);
502		return ENOMEM;
503	}
504
505	command_string = prop_dictionary_get(command_dict, "drvctl-command");
506	if (command_string == NULL) {
507		error = EINVAL;
508		goto out;
509	}
510
511	for (dcd = drvctl_command_table; dcd->dcd_name != NULL; dcd++) {
512		if (prop_string_equals_cstring(command_string,
513					       dcd->dcd_name))
514			break;
515	}
516
517	if (dcd->dcd_name == NULL) {
518		error = EINVAL;
519		goto out;
520	}
521
522	if ((fflag & dcd->dcd_rw) == 0) {
523		error = EPERM;
524		goto out;
525	}
526
527	error = (*dcd->dcd_func)(l, command_dict, results_dict);
528
529	prop_dictionary_set_int32(results_dict, "drvctl-error", error);
530
531	error = prop_dictionary_copyout_ioctl(pref, ioctl_cmd, results_dict);
532 out:
533	prop_object_release(command_dict);
534	prop_object_release(results_dict);
535	return error;
536}
537
538static int
539drvctl_getevent(struct lwp *l, struct plistref *pref, u_long ioctl_cmd,
540	        int fflag)
541{
542	struct drvctl_event *dce;
543	int ret;
544
545	if ((fflag & (FREAD|FWRITE)) != (FREAD|FWRITE))
546		return EPERM;
547
548	mutex_enter(&drvctl_lock);
549	while ((dce = TAILQ_FIRST(&drvctl_eventq)) == NULL) {
550		if (fflag & O_NONBLOCK) {
551			mutex_exit(&drvctl_lock);
552			return EWOULDBLOCK;
553		}
554
555		ret = cv_wait_sig(&drvctl_cond, &drvctl_lock);
556		if (ret) {
557			mutex_exit(&drvctl_lock);
558			return ret;
559		}
560	}
561	TAILQ_REMOVE(&drvctl_eventq, dce, dce_link);
562	KASSERT(drvctl_eventcnt > 0);
563	--drvctl_eventcnt;
564	mutex_exit(&drvctl_lock);
565
566	ret = prop_dictionary_copyout_ioctl(pref, ioctl_cmd, dce->dce_event);
567
568	prop_object_release(dce->dce_event);
569	kmem_free(dce, sizeof(*dce));
570
571	return ret;
572}
573