xref: /dragonfly/sys/kern/kern_memio.c (revision bcb3e04d)
1 /*-
2  * Copyright (c) 1988 University of Utah.
3  * Copyright (c) 1982, 1986, 1990 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * the Systems Programming Group of the University of Utah Computer
8  * Science Department, and code derived from software contributed to
9  * Berkeley by William Jolitz.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the University of
22  *	California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  *	from: Utah $Hdr: mem.c 1.13 89/10/08$
40  *	from: @(#)mem.c	7.2 (Berkeley) 5/9/91
41  * $FreeBSD: src/sys/i386/i386/mem.c,v 1.79.2.9 2003/01/04 22:58:01 njl Exp $
42  */
43 
44 /*
45  * Memory special file
46  */
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/buf.h>
51 #include <sys/conf.h>
52 #include <sys/fcntl.h>
53 #include <sys/filio.h>
54 #include <sys/kernel.h>
55 #include <sys/malloc.h>
56 #include <sys/memrange.h>
57 #include <sys/proc.h>
58 #include <sys/priv.h>
59 #include <sys/random.h>
60 #include <sys/signalvar.h>
61 #include <sys/uio.h>
62 #include <sys/vnode.h>
63 
64 #include <sys/signal2.h>
65 #include <sys/mplock2.h>
66 
67 #include <vm/vm.h>
68 #include <vm/pmap.h>
69 #include <vm/vm_extern.h>
70 
71 
72 static	d_open_t	mmopen;
73 static	d_close_t	mmclose;
74 static	d_read_t	mmread;
75 static	d_write_t	mmwrite;
76 static	d_ioctl_t	mmioctl;
77 static	d_mmap_t	memmmap;
78 static	d_kqfilter_t	mmkqfilter;
79 
80 #define CDEV_MAJOR 2
81 static struct dev_ops mem_ops = {
82 	{ "mem", 0, D_MPSAFE },
83 	.d_open =	mmopen,
84 	.d_close =	mmclose,
85 	.d_read =	mmread,
86 	.d_write =	mmwrite,
87 	.d_ioctl =	mmioctl,
88 	.d_kqfilter =	mmkqfilter,
89 	.d_mmap =	memmmap,
90 };
91 
92 static int rand_bolt;
93 static caddr_t	zbuf;
94 static cdev_t	zerodev = NULL;
95 
96 MALLOC_DEFINE(M_MEMDESC, "memdesc", "memory range descriptors");
97 static int mem_ioctl (cdev_t, u_long, caddr_t, int, struct ucred *);
98 static int random_ioctl (cdev_t, u_long, caddr_t, int, struct ucred *);
99 
100 struct mem_range_softc mem_range_softc;
101 
102 
103 static int
104 mmopen(struct dev_open_args *ap)
105 {
106 	cdev_t dev = ap->a_head.a_dev;
107 	int error;
108 
109 	switch (minor(dev)) {
110 	case 0:
111 	case 1:
112 		if (ap->a_oflags & FWRITE) {
113 			if (securelevel > 0 || kernel_mem_readonly)
114 				return (EPERM);
115 		}
116 		error = 0;
117 		break;
118 	case 14:
119 		error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0);
120 		if (error != 0)
121 			break;
122 		if (securelevel > 0 || kernel_mem_readonly) {
123 			error = EPERM;
124 			break;
125 		}
126 		error = cpu_set_iopl();
127 		break;
128 	default:
129 		error = 0;
130 		break;
131 	}
132 	return (error);
133 }
134 
135 static int
136 mmclose(struct dev_close_args *ap)
137 {
138 	cdev_t dev = ap->a_head.a_dev;
139 	int error;
140 
141 	switch (minor(dev)) {
142 	case 14:
143 		error = cpu_clr_iopl();
144 		break;
145 	default:
146 		error = 0;
147 		break;
148 	}
149 	return (error);
150 }
151 
152 
153 static int
154 mmrw(cdev_t dev, struct uio *uio, int flags)
155 {
156 	int o;
157 	u_int c, v;
158 	u_int poolsize;
159 	struct iovec *iov;
160 	int error = 0;
161 	caddr_t buf = NULL;
162 
163 	while (uio->uio_resid > 0 && error == 0) {
164 		iov = uio->uio_iov;
165 		if (iov->iov_len == 0) {
166 			uio->uio_iov++;
167 			uio->uio_iovcnt--;
168 			if (uio->uio_iovcnt < 0)
169 				panic("mmrw");
170 			continue;
171 		}
172 		switch (minor(dev)) {
173 		case 0:
174 			/*
175 			 * minor device 0 is physical memory, /dev/mem
176 			 */
177 			v = uio->uio_offset;
178 			v &= ~PAGE_MASK;
179 			pmap_kenter((vm_offset_t)ptvmmap, v);
180 			o = (int)uio->uio_offset & PAGE_MASK;
181 			c = (u_int)(PAGE_SIZE - ((uintptr_t)iov->iov_base & PAGE_MASK));
182 			c = min(c, (u_int)(PAGE_SIZE - o));
183 			c = min(c, (u_int)iov->iov_len);
184 			error = uiomove((caddr_t)&ptvmmap[o], (int)c, uio);
185 			pmap_kremove((vm_offset_t)ptvmmap);
186 			continue;
187 
188 		case 1: {
189 			/*
190 			 * minor device 1 is kernel memory, /dev/kmem
191 			 */
192 			vm_offset_t saddr, eaddr;
193 			int prot;
194 
195 			c = iov->iov_len;
196 
197 			/*
198 			 * Make sure that all of the pages are currently
199 			 * resident so that we don't create any zero-fill
200 			 * pages.
201 			 */
202 			saddr = trunc_page(uio->uio_offset);
203 			eaddr = round_page(uio->uio_offset + c);
204 			if (saddr > eaddr)
205 				return EFAULT;
206 
207 			/*
208 			 * Make sure the kernel addresses are mapped.
209 			 * platform_direct_mapped() can be used to bypass
210 			 * default mapping via the page table (virtual kernels
211 			 * contain a lot of out-of-band data).
212 			 */
213 			prot = VM_PROT_READ;
214 			if (uio->uio_rw != UIO_READ)
215 				prot |= VM_PROT_WRITE;
216 			error = kvm_access_check(saddr, eaddr, prot);
217 			if (error)
218 				return (error);
219 			error = uiomove((caddr_t)(vm_offset_t)uio->uio_offset,
220 					(int)c, uio);
221 			continue;
222 		}
223 		case 2:
224 			/*
225 			 * minor device 2 (/dev/null) is EOF/RATHOLE
226 			 */
227 			if (uio->uio_rw == UIO_READ)
228 				return (0);
229 			c = iov->iov_len;
230 			break;
231 		case 3:
232 			/*
233 			 * minor device 3 (/dev/random) is source of filth
234 			 * on read, seeder on write
235 			 */
236 			if (buf == NULL)
237 				buf = kmalloc(PAGE_SIZE, M_TEMP, M_WAITOK);
238 			c = min(iov->iov_len, PAGE_SIZE);
239 			if (uio->uio_rw == UIO_WRITE) {
240 				error = uiomove(buf, (int)c, uio);
241 				if (error == 0)
242 					error = add_buffer_randomness(buf, c);
243 			} else {
244 				poolsize = read_random(buf, c);
245 				if (poolsize == 0) {
246 					if (buf)
247 						kfree(buf, M_TEMP);
248 					if ((flags & IO_NDELAY) != 0)
249 						return (EWOULDBLOCK);
250 					return (0);
251 				}
252 				c = min(c, poolsize);
253 				error = uiomove(buf, (int)c, uio);
254 			}
255 			continue;
256 		case 4:
257 			/*
258 			 * minor device 4 (/dev/urandom) is source of muck
259 			 * on read, writes are disallowed.
260 			 */
261 			c = min(iov->iov_len, PAGE_SIZE);
262 			if (uio->uio_rw == UIO_WRITE) {
263 				error = EPERM;
264 				break;
265 			}
266 			if (CURSIG(curthread->td_lwp) != 0) {
267 				/*
268 				 * Use tsleep() to get the error code right.
269 				 * It should return immediately.
270 				 */
271 				error = tsleep(&rand_bolt, PCATCH, "urand", 1);
272 				if (error != 0 && error != EWOULDBLOCK)
273 					continue;
274 			}
275 			if (buf == NULL)
276 				buf = kmalloc(PAGE_SIZE, M_TEMP, M_WAITOK);
277 			poolsize = read_random_unlimited(buf, c);
278 			c = min(c, poolsize);
279 			error = uiomove(buf, (int)c, uio);
280 			continue;
281 		case 12:
282 			/*
283 			 * minor device 12 (/dev/zero) is source of nulls
284 			 * on read, write are disallowed.
285 			 */
286 			if (uio->uio_rw == UIO_WRITE) {
287 				c = iov->iov_len;
288 				break;
289 			}
290 			if (zbuf == NULL) {
291 				zbuf = (caddr_t)kmalloc(PAGE_SIZE, M_TEMP,
292 				    M_WAITOK | M_ZERO);
293 			}
294 			c = min(iov->iov_len, PAGE_SIZE);
295 			error = uiomove(zbuf, (int)c, uio);
296 			continue;
297 		default:
298 			return (ENODEV);
299 		}
300 		if (error)
301 			break;
302 		iov->iov_base = (char *)iov->iov_base + c;
303 		iov->iov_len -= c;
304 		uio->uio_offset += c;
305 		uio->uio_resid -= c;
306 	}
307 	if (buf)
308 		kfree(buf, M_TEMP);
309 	return (error);
310 }
311 
312 static int
313 mmread(struct dev_read_args *ap)
314 {
315 	return(mmrw(ap->a_head.a_dev, ap->a_uio, ap->a_ioflag));
316 }
317 
318 static int
319 mmwrite(struct dev_write_args *ap)
320 {
321 	return(mmrw(ap->a_head.a_dev, ap->a_uio, ap->a_ioflag));
322 }
323 
324 
325 
326 
327 
328 /*******************************************************\
329 * allow user processes to MMAP some memory sections	*
330 * instead of going through read/write			*
331 \*******************************************************/
332 
333 static int
334 memmmap(struct dev_mmap_args *ap)
335 {
336 	cdev_t dev = ap->a_head.a_dev;
337 
338 	switch (minor(dev)) {
339 	case 0:
340 		/*
341 		 * minor device 0 is physical memory
342 		 */
343 #if defined(__i386__)
344         	ap->a_result = i386_btop(ap->a_offset);
345 #elif defined(__x86_64__)
346 		ap->a_result = x86_64_btop(ap->a_offset);
347 #endif
348 		return 0;
349 	case 1:
350 		/*
351 		 * minor device 1 is kernel memory
352 		 */
353 #if defined(__i386__)
354         	ap->a_result = i386_btop(vtophys(ap->a_offset));
355 #elif defined(__x86_64__)
356         	ap->a_result = x86_64_btop(vtophys(ap->a_offset));
357 #endif
358 		return 0;
359 
360 	default:
361 		return EINVAL;
362 	}
363 }
364 
365 static int
366 mmioctl(struct dev_ioctl_args *ap)
367 {
368 	cdev_t dev = ap->a_head.a_dev;
369 	int error;
370 
371 	get_mplock();
372 
373 	switch (minor(dev)) {
374 	case 0:
375 		error = mem_ioctl(dev, ap->a_cmd, ap->a_data,
376 				  ap->a_fflag, ap->a_cred);
377 		break;
378 	case 3:
379 	case 4:
380 		error = random_ioctl(dev, ap->a_cmd, ap->a_data,
381 				     ap->a_fflag, ap->a_cred);
382 		break;
383 	default:
384 		error = ENODEV;
385 		break;
386 	}
387 
388 	rel_mplock();
389 	return (error);
390 }
391 
392 /*
393  * Operations for changing memory attributes.
394  *
395  * This is basically just an ioctl shim for mem_range_attr_get
396  * and mem_range_attr_set.
397  */
398 static int
399 mem_ioctl(cdev_t dev, u_long cmd, caddr_t data, int flags, struct ucred *cred)
400 {
401 	int nd, error = 0;
402 	struct mem_range_op *mo = (struct mem_range_op *)data;
403 	struct mem_range_desc *md;
404 
405 	/* is this for us? */
406 	if ((cmd != MEMRANGE_GET) &&
407 	    (cmd != MEMRANGE_SET))
408 		return (ENOTTY);
409 
410 	/* any chance we can handle this? */
411 	if (mem_range_softc.mr_op == NULL)
412 		return (EOPNOTSUPP);
413 
414 	/* do we have any descriptors? */
415 	if (mem_range_softc.mr_ndesc == 0)
416 		return (ENXIO);
417 
418 	switch (cmd) {
419 	case MEMRANGE_GET:
420 		nd = imin(mo->mo_arg[0], mem_range_softc.mr_ndesc);
421 		if (nd > 0) {
422 			md = (struct mem_range_desc *)
423 				kmalloc(nd * sizeof(struct mem_range_desc),
424 				       M_MEMDESC, M_WAITOK);
425 			error = mem_range_attr_get(md, &nd);
426 			if (!error)
427 				error = copyout(md, mo->mo_desc,
428 					nd * sizeof(struct mem_range_desc));
429 			kfree(md, M_MEMDESC);
430 		} else {
431 			nd = mem_range_softc.mr_ndesc;
432 		}
433 		mo->mo_arg[0] = nd;
434 		break;
435 
436 	case MEMRANGE_SET:
437 		md = (struct mem_range_desc *)kmalloc(sizeof(struct mem_range_desc),
438 						    M_MEMDESC, M_WAITOK);
439 		error = copyin(mo->mo_desc, md, sizeof(struct mem_range_desc));
440 		/* clamp description string */
441 		md->mr_owner[sizeof(md->mr_owner) - 1] = 0;
442 		if (error == 0)
443 			error = mem_range_attr_set(md, &mo->mo_arg[0]);
444 		kfree(md, M_MEMDESC);
445 		break;
446 	}
447 	return (error);
448 }
449 
450 /*
451  * Implementation-neutral, kernel-callable functions for manipulating
452  * memory range attributes.
453  */
454 int
455 mem_range_attr_get(struct mem_range_desc *mrd, int *arg)
456 {
457 	/* can we handle this? */
458 	if (mem_range_softc.mr_op == NULL)
459 		return (EOPNOTSUPP);
460 
461 	if (*arg == 0) {
462 		*arg = mem_range_softc.mr_ndesc;
463 	} else {
464 		bcopy(mem_range_softc.mr_desc, mrd, (*arg) * sizeof(struct mem_range_desc));
465 	}
466 	return (0);
467 }
468 
469 int
470 mem_range_attr_set(struct mem_range_desc *mrd, int *arg)
471 {
472 	/* can we handle this? */
473 	if (mem_range_softc.mr_op == NULL)
474 		return (EOPNOTSUPP);
475 
476 	return (mem_range_softc.mr_op->set(&mem_range_softc, mrd, arg));
477 }
478 
479 #ifdef SMP
480 void
481 mem_range_AP_init(void)
482 {
483 	if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
484 		return (mem_range_softc.mr_op->initAP(&mem_range_softc));
485 }
486 #endif
487 
488 static int
489 random_ioctl(cdev_t dev, u_long cmd, caddr_t data, int flags, struct ucred *cred)
490 {
491 	int error;
492 	int intr;
493 
494 	/*
495 	 * Even inspecting the state is privileged, since it gives a hint
496 	 * about how easily the randomness might be guessed.
497 	 */
498 	error = 0;
499 
500 	switch (cmd) {
501 	/* Really handled in upper layer */
502 	case FIOASYNC:
503 		break;
504 	case MEM_SETIRQ:
505 		intr = *(int16_t *)data;
506 		if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
507 			break;
508 		if (intr < 0 || intr >= MAX_INTS)
509 			return (EINVAL);
510 		register_randintr(intr);
511 		break;
512 	case MEM_CLEARIRQ:
513 		intr = *(int16_t *)data;
514 		if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
515 			break;
516 		if (intr < 0 || intr >= MAX_INTS)
517 			return (EINVAL);
518 		unregister_randintr(intr);
519 		break;
520 	case MEM_RETURNIRQ:
521 		error = ENOTSUP;
522 		break;
523 	case MEM_FINDIRQ:
524 		intr = *(int16_t *)data;
525 		if ((error = priv_check_cred(cred, PRIV_ROOT, 0)) != 0)
526 			break;
527 		if (intr < 0 || intr >= MAX_INTS)
528 			return (EINVAL);
529 		intr = next_registered_randintr(intr);
530 		if (intr == MAX_INTS)
531 			return (ENOENT);
532 		*(u_int16_t *)data = intr;
533 		break;
534 	default:
535 		error = ENOTSUP;
536 		break;
537 	}
538 	return (error);
539 }
540 
541 static int
542 mm_filter_read(struct knote *kn, long hint)
543 {
544 	return (1);
545 }
546 
547 static int
548 mm_filter_write(struct knote *kn, long hint)
549 {
550 	return (1);
551 }
552 
553 static void
554 dummy_filter_detach(struct knote *kn) {}
555 
556 static struct filterops random_read_filtops =
557         { FILTEROP_ISFD, NULL, dummy_filter_detach, random_filter_read };
558 
559 static struct filterops mm_read_filtops =
560         { FILTEROP_ISFD, NULL, dummy_filter_detach, mm_filter_read };
561 
562 static struct filterops mm_write_filtops =
563         { FILTEROP_ISFD, NULL, dummy_filter_detach, mm_filter_write };
564 
565 int
566 mmkqfilter(struct dev_kqfilter_args *ap)
567 {
568 	struct knote *kn = ap->a_kn;
569 	cdev_t dev = ap->a_head.a_dev;
570 
571 	ap->a_result = 0;
572 	switch (kn->kn_filter) {
573 	case EVFILT_READ:
574 		switch (minor(dev)) {
575 		case 3:
576 			kn->kn_fop = &random_read_filtops;
577 			break;
578 		default:
579 			kn->kn_fop = &mm_read_filtops;
580 			break;
581 		}
582 		break;
583 	case EVFILT_WRITE:
584 		kn->kn_fop = &mm_write_filtops;
585 		break;
586 	default:
587 		ap->a_result = EOPNOTSUPP;
588 		return (0);
589 	}
590 
591 	return (0);
592 }
593 
594 int
595 iszerodev(cdev_t dev)
596 {
597 	return (zerodev == dev);
598 }
599 
600 static void
601 mem_drvinit(void *unused)
602 {
603 
604 	/* Initialise memory range handling */
605 	if (mem_range_softc.mr_op != NULL)
606 		mem_range_softc.mr_op->init(&mem_range_softc);
607 
608 	make_dev(&mem_ops, 0, UID_ROOT, GID_KMEM, 0640, "mem");
609 	make_dev(&mem_ops, 1, UID_ROOT, GID_KMEM, 0640, "kmem");
610 	make_dev(&mem_ops, 2, UID_ROOT, GID_WHEEL, 0666, "null");
611 	make_dev(&mem_ops, 3, UID_ROOT, GID_WHEEL, 0644, "random");
612 	make_dev(&mem_ops, 4, UID_ROOT, GID_WHEEL, 0644, "urandom");
613 	zerodev = make_dev(&mem_ops, 12, UID_ROOT, GID_WHEEL, 0666, "zero");
614 	make_dev(&mem_ops, 14, UID_ROOT, GID_WHEEL, 0600, "io");
615 }
616 
617 SYSINIT(memdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,mem_drvinit,NULL)
618 
619