xref: /freebsd/sys/kern/uipc_shm.c (revision 5405b282e1f319b6f3597bb77f68be903e7f248c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2006, 2011, 2016-2017 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Portions of this software were developed by BAE Systems, the University of
8  * Cambridge Computer Laboratory, and Memorial University under DARPA/AFRL
9  * contract FA8650-15-C-7558 ("CADETS"), as part of the DARPA Transparent
10  * Computing (TC) research program.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Support for shared swap-backed anonymous memory objects via
36  * shm_open(2) and shm_unlink(2).  While most of the implementation is
37  * here, vm_mmap.c contains mapping logic changes.
38  *
39  * TODO:
40  *
41  * (1) Need to export data to a userland tool via a sysctl.  Should ipcs(1)
42  *     and ipcrm(1) be expanded or should new tools to manage both POSIX
43  *     kernel semaphores and POSIX shared memory be written?
44  *
45  * (2) Add support for this file type to fstat(1).
46  *
47  * (3) Resource limits?  Does this need its own resource limits or are the
48  *     existing limits in mmap(2) sufficient?
49  */
50 
51 #include <sys/cdefs.h>
52 __FBSDID("$FreeBSD$");
53 
54 #include "opt_capsicum.h"
55 #include "opt_ktrace.h"
56 
57 #include <sys/param.h>
58 #include <sys/capsicum.h>
59 #include <sys/conf.h>
60 #include <sys/fcntl.h>
61 #include <sys/file.h>
62 #include <sys/filedesc.h>
63 #include <sys/filio.h>
64 #include <sys/fnv_hash.h>
65 #include <sys/kernel.h>
66 #include <sys/uio.h>
67 #include <sys/signal.h>
68 #include <sys/jail.h>
69 #include <sys/ktrace.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/mman.h>
73 #include <sys/mutex.h>
74 #include <sys/priv.h>
75 #include <sys/proc.h>
76 #include <sys/refcount.h>
77 #include <sys/resourcevar.h>
78 #include <sys/rwlock.h>
79 #include <sys/sbuf.h>
80 #include <sys/stat.h>
81 #include <sys/syscallsubr.h>
82 #include <sys/sysctl.h>
83 #include <sys/sysproto.h>
84 #include <sys/systm.h>
85 #include <sys/sx.h>
86 #include <sys/time.h>
87 #include <sys/vnode.h>
88 #include <sys/unistd.h>
89 #include <sys/user.h>
90 
91 #include <security/audit/audit.h>
92 #include <security/mac/mac_framework.h>
93 
94 #include <vm/vm.h>
95 #include <vm/vm_param.h>
96 #include <vm/pmap.h>
97 #include <vm/vm_extern.h>
98 #include <vm/vm_map.h>
99 #include <vm/vm_kern.h>
100 #include <vm/vm_object.h>
101 #include <vm/vm_page.h>
102 #include <vm/vm_pageout.h>
103 #include <vm/vm_pager.h>
104 #include <vm/swap_pager.h>
105 
106 struct shm_mapping {
107 	char		*sm_path;
108 	Fnv32_t		sm_fnv;
109 	struct shmfd	*sm_shmfd;
110 	LIST_ENTRY(shm_mapping) sm_link;
111 };
112 
113 static MALLOC_DEFINE(M_SHMFD, "shmfd", "shared memory file descriptor");
114 static LIST_HEAD(, shm_mapping) *shm_dictionary;
115 static struct sx shm_dict_lock;
116 static struct mtx shm_timestamp_lock;
117 static u_long shm_hash;
118 static struct unrhdr64 shm_ino_unr;
119 static dev_t shm_dev_ino;
120 
121 #define	SHM_HASH(fnv)	(&shm_dictionary[(fnv) & shm_hash])
122 
123 static void	shm_init(void *arg);
124 static void	shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd);
125 static struct shmfd *shm_lookup(char *path, Fnv32_t fnv);
126 static int	shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred);
127 
128 static fo_rdwr_t	shm_read;
129 static fo_rdwr_t	shm_write;
130 static fo_truncate_t	shm_truncate;
131 static fo_ioctl_t	shm_ioctl;
132 static fo_stat_t	shm_stat;
133 static fo_close_t	shm_close;
134 static fo_chmod_t	shm_chmod;
135 static fo_chown_t	shm_chown;
136 static fo_seek_t	shm_seek;
137 static fo_fill_kinfo_t	shm_fill_kinfo;
138 static fo_mmap_t	shm_mmap;
139 
140 /* File descriptor operations. */
141 struct fileops shm_ops = {
142 	.fo_read = shm_read,
143 	.fo_write = shm_write,
144 	.fo_truncate = shm_truncate,
145 	.fo_ioctl = shm_ioctl,
146 	.fo_poll = invfo_poll,
147 	.fo_kqfilter = invfo_kqfilter,
148 	.fo_stat = shm_stat,
149 	.fo_close = shm_close,
150 	.fo_chmod = shm_chmod,
151 	.fo_chown = shm_chown,
152 	.fo_sendfile = vn_sendfile,
153 	.fo_seek = shm_seek,
154 	.fo_fill_kinfo = shm_fill_kinfo,
155 	.fo_mmap = shm_mmap,
156 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
157 };
158 
159 FEATURE(posix_shm, "POSIX shared memory");
160 
161 static int
162 uiomove_object_page(vm_object_t obj, size_t len, struct uio *uio)
163 {
164 	vm_page_t m;
165 	vm_pindex_t idx;
166 	size_t tlen;
167 	int error, offset, rv;
168 
169 	idx = OFF_TO_IDX(uio->uio_offset);
170 	offset = uio->uio_offset & PAGE_MASK;
171 	tlen = MIN(PAGE_SIZE - offset, len);
172 
173 	VM_OBJECT_WLOCK(obj);
174 
175 	/*
176 	 * Read I/O without either a corresponding resident page or swap
177 	 * page: use zero_region.  This is intended to avoid instantiating
178 	 * pages on read from a sparse region.
179 	 */
180 	if (uio->uio_rw == UIO_READ && vm_page_lookup(obj, idx) == NULL &&
181 	    !vm_pager_has_page(obj, idx, NULL, NULL)) {
182 		VM_OBJECT_WUNLOCK(obj);
183 		return (uiomove(__DECONST(void *, zero_region), tlen, uio));
184 	}
185 
186 	/*
187 	 * Parallel reads of the page content from disk are prevented
188 	 * by exclusive busy.
189 	 *
190 	 * Although the tmpfs vnode lock is held here, it is
191 	 * nonetheless safe to sleep waiting for a free page.  The
192 	 * pageout daemon does not need to acquire the tmpfs vnode
193 	 * lock to page out tobj's pages because tobj is a OBJT_SWAP
194 	 * type object.
195 	 */
196 	m = vm_page_grab(obj, idx, VM_ALLOC_NORMAL | VM_ALLOC_NOBUSY);
197 	if (m->valid != VM_PAGE_BITS_ALL) {
198 		vm_page_xbusy(m);
199 		if (vm_pager_has_page(obj, idx, NULL, NULL)) {
200 			rv = vm_pager_get_pages(obj, &m, 1, NULL, NULL);
201 			if (rv != VM_PAGER_OK) {
202 				printf(
203 	    "uiomove_object: vm_obj %p idx %jd valid %x pager error %d\n",
204 				    obj, idx, m->valid, rv);
205 				vm_page_lock(m);
206 				vm_page_free(m);
207 				vm_page_unlock(m);
208 				VM_OBJECT_WUNLOCK(obj);
209 				return (EIO);
210 			}
211 		} else
212 			vm_page_zero_invalid(m, TRUE);
213 		vm_page_xunbusy(m);
214 	}
215 	vm_page_lock(m);
216 	vm_page_hold(m);
217 	if (vm_page_active(m))
218 		vm_page_reference(m);
219 	else
220 		vm_page_activate(m);
221 	vm_page_unlock(m);
222 	VM_OBJECT_WUNLOCK(obj);
223 	error = uiomove_fromphys(&m, offset, tlen, uio);
224 	if (uio->uio_rw == UIO_WRITE && error == 0) {
225 		VM_OBJECT_WLOCK(obj);
226 		vm_page_dirty(m);
227 		vm_pager_page_unswapped(m);
228 		VM_OBJECT_WUNLOCK(obj);
229 	}
230 	vm_page_lock(m);
231 	vm_page_unhold(m);
232 	vm_page_unlock(m);
233 
234 	return (error);
235 }
236 
237 int
238 uiomove_object(vm_object_t obj, off_t obj_size, struct uio *uio)
239 {
240 	ssize_t resid;
241 	size_t len;
242 	int error;
243 
244 	error = 0;
245 	while ((resid = uio->uio_resid) > 0) {
246 		if (obj_size <= uio->uio_offset)
247 			break;
248 		len = MIN(obj_size - uio->uio_offset, resid);
249 		if (len == 0)
250 			break;
251 		error = uiomove_object_page(obj, len, uio);
252 		if (error != 0 || resid == uio->uio_resid)
253 			break;
254 	}
255 	return (error);
256 }
257 
258 static int
259 shm_seek(struct file *fp, off_t offset, int whence, struct thread *td)
260 {
261 	struct shmfd *shmfd;
262 	off_t foffset;
263 	int error;
264 
265 	shmfd = fp->f_data;
266 	foffset = foffset_lock(fp, 0);
267 	error = 0;
268 	switch (whence) {
269 	case L_INCR:
270 		if (foffset < 0 ||
271 		    (offset > 0 && foffset > OFF_MAX - offset)) {
272 			error = EOVERFLOW;
273 			break;
274 		}
275 		offset += foffset;
276 		break;
277 	case L_XTND:
278 		if (offset > 0 && shmfd->shm_size > OFF_MAX - offset) {
279 			error = EOVERFLOW;
280 			break;
281 		}
282 		offset += shmfd->shm_size;
283 		break;
284 	case L_SET:
285 		break;
286 	default:
287 		error = EINVAL;
288 	}
289 	if (error == 0) {
290 		if (offset < 0 || offset > shmfd->shm_size)
291 			error = EINVAL;
292 		else
293 			td->td_uretoff.tdu_off = offset;
294 	}
295 	foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
296 	return (error);
297 }
298 
299 static int
300 shm_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
301     int flags, struct thread *td)
302 {
303 	struct shmfd *shmfd;
304 	void *rl_cookie;
305 	int error;
306 
307 	shmfd = fp->f_data;
308 #ifdef MAC
309 	error = mac_posixshm_check_read(active_cred, fp->f_cred, shmfd);
310 	if (error)
311 		return (error);
312 #endif
313 	foffset_lock_uio(fp, uio, flags);
314 	rl_cookie = rangelock_rlock(&shmfd->shm_rl, uio->uio_offset,
315 	    uio->uio_offset + uio->uio_resid, &shmfd->shm_mtx);
316 	error = uiomove_object(shmfd->shm_object, shmfd->shm_size, uio);
317 	rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
318 	foffset_unlock_uio(fp, uio, flags);
319 	return (error);
320 }
321 
322 static int
323 shm_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
324     int flags, struct thread *td)
325 {
326 	struct shmfd *shmfd;
327 	void *rl_cookie;
328 	int error;
329 
330 	shmfd = fp->f_data;
331 #ifdef MAC
332 	error = mac_posixshm_check_write(active_cred, fp->f_cred, shmfd);
333 	if (error)
334 		return (error);
335 #endif
336 	foffset_lock_uio(fp, uio, flags);
337 	if ((flags & FOF_OFFSET) == 0) {
338 		rl_cookie = rangelock_wlock(&shmfd->shm_rl, 0, OFF_MAX,
339 		    &shmfd->shm_mtx);
340 	} else {
341 		rl_cookie = rangelock_wlock(&shmfd->shm_rl, uio->uio_offset,
342 		    uio->uio_offset + uio->uio_resid, &shmfd->shm_mtx);
343 	}
344 
345 	error = uiomove_object(shmfd->shm_object, shmfd->shm_size, uio);
346 	rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
347 	foffset_unlock_uio(fp, uio, flags);
348 	return (error);
349 }
350 
351 static int
352 shm_truncate(struct file *fp, off_t length, struct ucred *active_cred,
353     struct thread *td)
354 {
355 	struct shmfd *shmfd;
356 #ifdef MAC
357 	int error;
358 #endif
359 
360 	shmfd = fp->f_data;
361 #ifdef MAC
362 	error = mac_posixshm_check_truncate(active_cred, fp->f_cred, shmfd);
363 	if (error)
364 		return (error);
365 #endif
366 	return (shm_dotruncate(shmfd, length));
367 }
368 
369 int
370 shm_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
371     struct thread *td)
372 {
373 
374 	switch (com) {
375 	case FIONBIO:
376 	case FIOASYNC:
377 		/*
378 		 * Allow fcntl(fd, F_SETFL, O_NONBLOCK) to work,
379 		 * just like it would on an unlinked regular file
380 		 */
381 		return (0);
382 	default:
383 		return (ENOTTY);
384 	}
385 }
386 
387 static int
388 shm_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
389     struct thread *td)
390 {
391 	struct shmfd *shmfd;
392 #ifdef MAC
393 	int error;
394 #endif
395 
396 	shmfd = fp->f_data;
397 
398 #ifdef MAC
399 	error = mac_posixshm_check_stat(active_cred, fp->f_cred, shmfd);
400 	if (error)
401 		return (error);
402 #endif
403 
404 	/*
405 	 * Attempt to return sanish values for fstat() on a memory file
406 	 * descriptor.
407 	 */
408 	bzero(sb, sizeof(*sb));
409 	sb->st_blksize = PAGE_SIZE;
410 	sb->st_size = shmfd->shm_size;
411 	sb->st_blocks = howmany(sb->st_size, sb->st_blksize);
412 	mtx_lock(&shm_timestamp_lock);
413 	sb->st_atim = shmfd->shm_atime;
414 	sb->st_ctim = shmfd->shm_ctime;
415 	sb->st_mtim = shmfd->shm_mtime;
416 	sb->st_birthtim = shmfd->shm_birthtime;
417 	sb->st_mode = S_IFREG | shmfd->shm_mode;		/* XXX */
418 	sb->st_uid = shmfd->shm_uid;
419 	sb->st_gid = shmfd->shm_gid;
420 	mtx_unlock(&shm_timestamp_lock);
421 	sb->st_dev = shm_dev_ino;
422 	sb->st_ino = shmfd->shm_ino;
423 	sb->st_nlink = shmfd->shm_object->ref_count;
424 
425 	return (0);
426 }
427 
428 static int
429 shm_close(struct file *fp, struct thread *td)
430 {
431 	struct shmfd *shmfd;
432 
433 	shmfd = fp->f_data;
434 	fp->f_data = NULL;
435 	shm_drop(shmfd);
436 
437 	return (0);
438 }
439 
440 int
441 shm_dotruncate(struct shmfd *shmfd, off_t length)
442 {
443 	vm_object_t object;
444 	vm_page_t m;
445 	vm_pindex_t idx, nobjsize;
446 	vm_ooffset_t delta;
447 	int base, rv;
448 
449 	KASSERT(length >= 0, ("shm_dotruncate: length < 0"));
450 	object = shmfd->shm_object;
451 	VM_OBJECT_WLOCK(object);
452 	if (length == shmfd->shm_size) {
453 		VM_OBJECT_WUNLOCK(object);
454 		return (0);
455 	}
456 	nobjsize = OFF_TO_IDX(length + PAGE_MASK);
457 
458 	/* Are we shrinking?  If so, trim the end. */
459 	if (length < shmfd->shm_size) {
460 		/*
461 		 * Disallow any requests to shrink the size if this
462 		 * object is mapped into the kernel.
463 		 */
464 		if (shmfd->shm_kmappings > 0) {
465 			VM_OBJECT_WUNLOCK(object);
466 			return (EBUSY);
467 		}
468 
469 		/*
470 		 * Zero the truncated part of the last page.
471 		 */
472 		base = length & PAGE_MASK;
473 		if (base != 0) {
474 			idx = OFF_TO_IDX(length);
475 retry:
476 			m = vm_page_lookup(object, idx);
477 			if (m != NULL) {
478 				if (vm_page_sleep_if_busy(m, "shmtrc"))
479 					goto retry;
480 			} else if (vm_pager_has_page(object, idx, NULL, NULL)) {
481 				m = vm_page_alloc(object, idx,
482 				    VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
483 				if (m == NULL)
484 					goto retry;
485 				rv = vm_pager_get_pages(object, &m, 1, NULL,
486 				    NULL);
487 				vm_page_lock(m);
488 				if (rv == VM_PAGER_OK) {
489 					/*
490 					 * Since the page was not resident,
491 					 * and therefore not recently
492 					 * accessed, immediately enqueue it
493 					 * for asynchronous laundering.  The
494 					 * current operation is not regarded
495 					 * as an access.
496 					 */
497 					vm_page_launder(m);
498 					vm_page_unlock(m);
499 					vm_page_xunbusy(m);
500 				} else {
501 					vm_page_free(m);
502 					vm_page_unlock(m);
503 					VM_OBJECT_WUNLOCK(object);
504 					return (EIO);
505 				}
506 			}
507 			if (m != NULL) {
508 				pmap_zero_page_area(m, base, PAGE_SIZE - base);
509 				KASSERT(m->valid == VM_PAGE_BITS_ALL,
510 				    ("shm_dotruncate: page %p is invalid", m));
511 				vm_page_dirty(m);
512 				vm_pager_page_unswapped(m);
513 			}
514 		}
515 		delta = IDX_TO_OFF(object->size - nobjsize);
516 
517 		/* Toss in memory pages. */
518 		if (nobjsize < object->size)
519 			vm_object_page_remove(object, nobjsize, object->size,
520 			    0);
521 
522 		/* Toss pages from swap. */
523 		if (object->type == OBJT_SWAP)
524 			swap_pager_freespace(object, nobjsize, delta);
525 
526 		/* Free the swap accounted for shm */
527 		swap_release_by_cred(delta, object->cred);
528 		object->charge -= delta;
529 	} else {
530 		/* Try to reserve additional swap space. */
531 		delta = IDX_TO_OFF(nobjsize - object->size);
532 		if (!swap_reserve_by_cred(delta, object->cred)) {
533 			VM_OBJECT_WUNLOCK(object);
534 			return (ENOMEM);
535 		}
536 		object->charge += delta;
537 	}
538 	shmfd->shm_size = length;
539 	mtx_lock(&shm_timestamp_lock);
540 	vfs_timestamp(&shmfd->shm_ctime);
541 	shmfd->shm_mtime = shmfd->shm_ctime;
542 	mtx_unlock(&shm_timestamp_lock);
543 	object->size = nobjsize;
544 	VM_OBJECT_WUNLOCK(object);
545 	return (0);
546 }
547 
548 /*
549  * shmfd object management including creation and reference counting
550  * routines.
551  */
552 struct shmfd *
553 shm_alloc(struct ucred *ucred, mode_t mode)
554 {
555 	struct shmfd *shmfd;
556 
557 	shmfd = malloc(sizeof(*shmfd), M_SHMFD, M_WAITOK | M_ZERO);
558 	shmfd->shm_size = 0;
559 	shmfd->shm_uid = ucred->cr_uid;
560 	shmfd->shm_gid = ucred->cr_gid;
561 	shmfd->shm_mode = mode;
562 	shmfd->shm_object = vm_pager_allocate(OBJT_DEFAULT, NULL,
563 	    shmfd->shm_size, VM_PROT_DEFAULT, 0, ucred);
564 	KASSERT(shmfd->shm_object != NULL, ("shm_create: vm_pager_allocate"));
565 	shmfd->shm_object->pg_color = 0;
566 	VM_OBJECT_WLOCK(shmfd->shm_object);
567 	vm_object_clear_flag(shmfd->shm_object, OBJ_ONEMAPPING);
568 	vm_object_set_flag(shmfd->shm_object, OBJ_COLORED | OBJ_NOSPLIT);
569 	VM_OBJECT_WUNLOCK(shmfd->shm_object);
570 	vfs_timestamp(&shmfd->shm_birthtime);
571 	shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
572 	    shmfd->shm_birthtime;
573 	shmfd->shm_ino = alloc_unr64(&shm_ino_unr);
574 	refcount_init(&shmfd->shm_refs, 1);
575 	mtx_init(&shmfd->shm_mtx, "shmrl", NULL, MTX_DEF);
576 	rangelock_init(&shmfd->shm_rl);
577 #ifdef MAC
578 	mac_posixshm_init(shmfd);
579 	mac_posixshm_create(ucred, shmfd);
580 #endif
581 
582 	return (shmfd);
583 }
584 
585 struct shmfd *
586 shm_hold(struct shmfd *shmfd)
587 {
588 
589 	refcount_acquire(&shmfd->shm_refs);
590 	return (shmfd);
591 }
592 
593 void
594 shm_drop(struct shmfd *shmfd)
595 {
596 
597 	if (refcount_release(&shmfd->shm_refs)) {
598 #ifdef MAC
599 		mac_posixshm_destroy(shmfd);
600 #endif
601 		rangelock_destroy(&shmfd->shm_rl);
602 		mtx_destroy(&shmfd->shm_mtx);
603 		vm_object_deallocate(shmfd->shm_object);
604 		free(shmfd, M_SHMFD);
605 	}
606 }
607 
608 /*
609  * Determine if the credentials have sufficient permissions for a
610  * specified combination of FREAD and FWRITE.
611  */
612 int
613 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
614 {
615 	accmode_t accmode;
616 	int error;
617 
618 	accmode = 0;
619 	if (flags & FREAD)
620 		accmode |= VREAD;
621 	if (flags & FWRITE)
622 		accmode |= VWRITE;
623 	mtx_lock(&shm_timestamp_lock);
624 	error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
625 	    accmode, ucred, NULL);
626 	mtx_unlock(&shm_timestamp_lock);
627 	return (error);
628 }
629 
630 /*
631  * Dictionary management.  We maintain an in-kernel dictionary to map
632  * paths to shmfd objects.  We use the FNV hash on the path to store
633  * the mappings in a hash table.
634  */
635 static void
636 shm_init(void *arg)
637 {
638 
639 	mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
640 	sx_init(&shm_dict_lock, "shm dictionary");
641 	shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
642 	new_unrhdr64(&shm_ino_unr, 1);
643 	shm_dev_ino = devfs_alloc_cdp_inode();
644 	KASSERT(shm_dev_ino > 0, ("shm dev inode not initialized"));
645 }
646 SYSINIT(shm_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_init, NULL);
647 
648 static struct shmfd *
649 shm_lookup(char *path, Fnv32_t fnv)
650 {
651 	struct shm_mapping *map;
652 
653 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
654 		if (map->sm_fnv != fnv)
655 			continue;
656 		if (strcmp(map->sm_path, path) == 0)
657 			return (map->sm_shmfd);
658 	}
659 
660 	return (NULL);
661 }
662 
663 static void
664 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
665 {
666 	struct shm_mapping *map;
667 
668 	map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
669 	map->sm_path = path;
670 	map->sm_fnv = fnv;
671 	map->sm_shmfd = shm_hold(shmfd);
672 	shmfd->shm_path = path;
673 	LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
674 }
675 
676 static int
677 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
678 {
679 	struct shm_mapping *map;
680 	int error;
681 
682 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
683 		if (map->sm_fnv != fnv)
684 			continue;
685 		if (strcmp(map->sm_path, path) == 0) {
686 #ifdef MAC
687 			error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
688 			if (error)
689 				return (error);
690 #endif
691 			error = shm_access(map->sm_shmfd, ucred,
692 			    FREAD | FWRITE);
693 			if (error)
694 				return (error);
695 			map->sm_shmfd->shm_path = NULL;
696 			LIST_REMOVE(map, sm_link);
697 			shm_drop(map->sm_shmfd);
698 			free(map->sm_path, M_SHMFD);
699 			free(map, M_SHMFD);
700 			return (0);
701 		}
702 	}
703 
704 	return (ENOENT);
705 }
706 
707 int
708 kern_shm_open(struct thread *td, const char *userpath, int flags, mode_t mode,
709     struct filecaps *fcaps)
710 {
711 	struct filedesc *fdp;
712 	struct shmfd *shmfd;
713 	struct file *fp;
714 	char *path;
715 	const char *pr_path;
716 	size_t pr_pathlen;
717 	Fnv32_t fnv;
718 	mode_t cmode;
719 	int fd, error;
720 
721 #ifdef CAPABILITY_MODE
722 	/*
723 	 * shm_open(2) is only allowed for anonymous objects.
724 	 */
725 	if (IN_CAPABILITY_MODE(td) && (userpath != SHM_ANON))
726 		return (ECAPMODE);
727 #endif
728 
729 	AUDIT_ARG_FFLAGS(flags);
730 	AUDIT_ARG_MODE(mode);
731 
732 	if ((flags & O_ACCMODE) != O_RDONLY && (flags & O_ACCMODE) != O_RDWR)
733 		return (EINVAL);
734 
735 	if ((flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_CLOEXEC)) != 0)
736 		return (EINVAL);
737 
738 	fdp = td->td_proc->p_fd;
739 	cmode = (mode & ~fdp->fd_cmask) & ACCESSPERMS;
740 
741 	error = falloc_caps(td, &fp, &fd, O_CLOEXEC, fcaps);
742 	if (error)
743 		return (error);
744 
745 	/* A SHM_ANON path pointer creates an anonymous object. */
746 	if (userpath == SHM_ANON) {
747 		/* A read-only anonymous object is pointless. */
748 		if ((flags & O_ACCMODE) == O_RDONLY) {
749 			fdclose(td, fp, fd);
750 			fdrop(fp, td);
751 			return (EINVAL);
752 		}
753 		shmfd = shm_alloc(td->td_ucred, cmode);
754 	} else {
755 		path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
756 		pr_path = td->td_ucred->cr_prison->pr_path;
757 
758 		/* Construct a full pathname for jailed callers. */
759 		pr_pathlen = strcmp(pr_path, "/") == 0 ? 0
760 		    : strlcpy(path, pr_path, MAXPATHLEN);
761 		error = copyinstr(userpath, path + pr_pathlen,
762 		    MAXPATHLEN - pr_pathlen, NULL);
763 #ifdef KTRACE
764 		if (error == 0 && KTRPOINT(curthread, KTR_NAMEI))
765 			ktrnamei(path);
766 #endif
767 		/* Require paths to start with a '/' character. */
768 		if (error == 0 && path[pr_pathlen] != '/')
769 			error = EINVAL;
770 		if (error) {
771 			fdclose(td, fp, fd);
772 			fdrop(fp, td);
773 			free(path, M_SHMFD);
774 			return (error);
775 		}
776 
777 		AUDIT_ARG_UPATH1_CANON(path);
778 		fnv = fnv_32_str(path, FNV1_32_INIT);
779 		sx_xlock(&shm_dict_lock);
780 		shmfd = shm_lookup(path, fnv);
781 		if (shmfd == NULL) {
782 			/* Object does not yet exist, create it if requested. */
783 			if (flags & O_CREAT) {
784 #ifdef MAC
785 				error = mac_posixshm_check_create(td->td_ucred,
786 				    path);
787 				if (error == 0) {
788 #endif
789 					shmfd = shm_alloc(td->td_ucred, cmode);
790 					shm_insert(path, fnv, shmfd);
791 #ifdef MAC
792 				}
793 #endif
794 			} else {
795 				free(path, M_SHMFD);
796 				error = ENOENT;
797 			}
798 		} else {
799 			/*
800 			 * Object already exists, obtain a new
801 			 * reference if requested and permitted.
802 			 */
803 			free(path, M_SHMFD);
804 			if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
805 				error = EEXIST;
806 			else {
807 #ifdef MAC
808 				error = mac_posixshm_check_open(td->td_ucred,
809 				    shmfd, FFLAGS(flags & O_ACCMODE));
810 				if (error == 0)
811 #endif
812 				error = shm_access(shmfd, td->td_ucred,
813 				    FFLAGS(flags & O_ACCMODE));
814 			}
815 
816 			/*
817 			 * Truncate the file back to zero length if
818 			 * O_TRUNC was specified and the object was
819 			 * opened with read/write.
820 			 */
821 			if (error == 0 &&
822 			    (flags & (O_ACCMODE | O_TRUNC)) ==
823 			    (O_RDWR | O_TRUNC)) {
824 #ifdef MAC
825 				error = mac_posixshm_check_truncate(
826 					td->td_ucred, fp->f_cred, shmfd);
827 				if (error == 0)
828 #endif
829 					shm_dotruncate(shmfd, 0);
830 			}
831 			if (error == 0)
832 				shm_hold(shmfd);
833 		}
834 		sx_xunlock(&shm_dict_lock);
835 
836 		if (error) {
837 			fdclose(td, fp, fd);
838 			fdrop(fp, td);
839 			return (error);
840 		}
841 	}
842 
843 	finit(fp, FFLAGS(flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
844 
845 	td->td_retval[0] = fd;
846 	fdrop(fp, td);
847 
848 	return (0);
849 }
850 
851 /* System calls. */
852 int
853 sys_shm_open(struct thread *td, struct shm_open_args *uap)
854 {
855 
856 	return (kern_shm_open(td, uap->path, uap->flags, uap->mode, NULL));
857 }
858 
859 int
860 sys_shm_unlink(struct thread *td, struct shm_unlink_args *uap)
861 {
862 	char *path;
863 	const char *pr_path;
864 	size_t pr_pathlen;
865 	Fnv32_t fnv;
866 	int error;
867 
868 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
869 	pr_path = td->td_ucred->cr_prison->pr_path;
870 	pr_pathlen = strcmp(pr_path, "/") == 0 ? 0
871 	    : strlcpy(path, pr_path, MAXPATHLEN);
872 	error = copyinstr(uap->path, path + pr_pathlen, MAXPATHLEN - pr_pathlen,
873 	    NULL);
874 	if (error) {
875 		free(path, M_TEMP);
876 		return (error);
877 	}
878 #ifdef KTRACE
879 	if (KTRPOINT(curthread, KTR_NAMEI))
880 		ktrnamei(path);
881 #endif
882 	AUDIT_ARG_UPATH1_CANON(path);
883 	fnv = fnv_32_str(path, FNV1_32_INIT);
884 	sx_xlock(&shm_dict_lock);
885 	error = shm_remove(path, fnv, td->td_ucred);
886 	sx_xunlock(&shm_dict_lock);
887 	free(path, M_TEMP);
888 
889 	return (error);
890 }
891 
892 int
893 shm_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t objsize,
894     vm_prot_t prot, vm_prot_t cap_maxprot, int flags,
895     vm_ooffset_t foff, struct thread *td)
896 {
897 	struct shmfd *shmfd;
898 	vm_prot_t maxprot;
899 	int error;
900 
901 	shmfd = fp->f_data;
902 	maxprot = VM_PROT_NONE;
903 
904 	/* FREAD should always be set. */
905 	if ((fp->f_flag & FREAD) != 0)
906 		maxprot |= VM_PROT_EXECUTE | VM_PROT_READ;
907 	if ((fp->f_flag & FWRITE) != 0)
908 		maxprot |= VM_PROT_WRITE;
909 
910 	/* Don't permit shared writable mappings on read-only descriptors. */
911 	if ((flags & MAP_SHARED) != 0 &&
912 	    (maxprot & VM_PROT_WRITE) == 0 &&
913 	    (prot & VM_PROT_WRITE) != 0)
914 		return (EACCES);
915 	maxprot &= cap_maxprot;
916 
917 	/* See comment in vn_mmap(). */
918 	if (
919 #ifdef _LP64
920 	    objsize > OFF_MAX ||
921 #endif
922 	    foff < 0 || foff > OFF_MAX - objsize)
923 		return (EINVAL);
924 
925 #ifdef MAC
926 	error = mac_posixshm_check_mmap(td->td_ucred, shmfd, prot, flags);
927 	if (error != 0)
928 		return (error);
929 #endif
930 
931 	mtx_lock(&shm_timestamp_lock);
932 	vfs_timestamp(&shmfd->shm_atime);
933 	mtx_unlock(&shm_timestamp_lock);
934 	vm_object_reference(shmfd->shm_object);
935 
936 	error = vm_mmap_object(map, addr, objsize, prot, maxprot, flags,
937 	    shmfd->shm_object, foff, FALSE, td);
938 	if (error != 0)
939 		vm_object_deallocate(shmfd->shm_object);
940 	return (error);
941 }
942 
943 static int
944 shm_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
945     struct thread *td)
946 {
947 	struct shmfd *shmfd;
948 	int error;
949 
950 	error = 0;
951 	shmfd = fp->f_data;
952 	mtx_lock(&shm_timestamp_lock);
953 	/*
954 	 * SUSv4 says that x bits of permission need not be affected.
955 	 * Be consistent with our shm_open there.
956 	 */
957 #ifdef MAC
958 	error = mac_posixshm_check_setmode(active_cred, shmfd, mode);
959 	if (error != 0)
960 		goto out;
961 #endif
962 	error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid,
963 	    shmfd->shm_gid, VADMIN, active_cred, NULL);
964 	if (error != 0)
965 		goto out;
966 	shmfd->shm_mode = mode & ACCESSPERMS;
967 out:
968 	mtx_unlock(&shm_timestamp_lock);
969 	return (error);
970 }
971 
972 static int
973 shm_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
974     struct thread *td)
975 {
976 	struct shmfd *shmfd;
977 	int error;
978 
979 	error = 0;
980 	shmfd = fp->f_data;
981 	mtx_lock(&shm_timestamp_lock);
982 #ifdef MAC
983 	error = mac_posixshm_check_setowner(active_cred, shmfd, uid, gid);
984 	if (error != 0)
985 		goto out;
986 #endif
987 	if (uid == (uid_t)-1)
988 		uid = shmfd->shm_uid;
989 	if (gid == (gid_t)-1)
990                  gid = shmfd->shm_gid;
991 	if (((uid != shmfd->shm_uid && uid != active_cred->cr_uid) ||
992 	    (gid != shmfd->shm_gid && !groupmember(gid, active_cred))) &&
993 	    (error = priv_check_cred(active_cred, PRIV_VFS_CHOWN)))
994 		goto out;
995 	shmfd->shm_uid = uid;
996 	shmfd->shm_gid = gid;
997 out:
998 	mtx_unlock(&shm_timestamp_lock);
999 	return (error);
1000 }
1001 
1002 /*
1003  * Helper routines to allow the backing object of a shared memory file
1004  * descriptor to be mapped in the kernel.
1005  */
1006 int
1007 shm_map(struct file *fp, size_t size, off_t offset, void **memp)
1008 {
1009 	struct shmfd *shmfd;
1010 	vm_offset_t kva, ofs;
1011 	vm_object_t obj;
1012 	int rv;
1013 
1014 	if (fp->f_type != DTYPE_SHM)
1015 		return (EINVAL);
1016 	shmfd = fp->f_data;
1017 	obj = shmfd->shm_object;
1018 	VM_OBJECT_WLOCK(obj);
1019 	/*
1020 	 * XXXRW: This validation is probably insufficient, and subject to
1021 	 * sign errors.  It should be fixed.
1022 	 */
1023 	if (offset >= shmfd->shm_size ||
1024 	    offset + size > round_page(shmfd->shm_size)) {
1025 		VM_OBJECT_WUNLOCK(obj);
1026 		return (EINVAL);
1027 	}
1028 
1029 	shmfd->shm_kmappings++;
1030 	vm_object_reference_locked(obj);
1031 	VM_OBJECT_WUNLOCK(obj);
1032 
1033 	/* Map the object into the kernel_map and wire it. */
1034 	kva = vm_map_min(kernel_map);
1035 	ofs = offset & PAGE_MASK;
1036 	offset = trunc_page(offset);
1037 	size = round_page(size + ofs);
1038 	rv = vm_map_find(kernel_map, obj, offset, &kva, size, 0,
1039 	    VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
1040 	    VM_PROT_READ | VM_PROT_WRITE, 0);
1041 	if (rv == KERN_SUCCESS) {
1042 		rv = vm_map_wire(kernel_map, kva, kva + size,
1043 		    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
1044 		if (rv == KERN_SUCCESS) {
1045 			*memp = (void *)(kva + ofs);
1046 			return (0);
1047 		}
1048 		vm_map_remove(kernel_map, kva, kva + size);
1049 	} else
1050 		vm_object_deallocate(obj);
1051 
1052 	/* On failure, drop our mapping reference. */
1053 	VM_OBJECT_WLOCK(obj);
1054 	shmfd->shm_kmappings--;
1055 	VM_OBJECT_WUNLOCK(obj);
1056 
1057 	return (vm_mmap_to_errno(rv));
1058 }
1059 
1060 /*
1061  * We require the caller to unmap the entire entry.  This allows us to
1062  * safely decrement shm_kmappings when a mapping is removed.
1063  */
1064 int
1065 shm_unmap(struct file *fp, void *mem, size_t size)
1066 {
1067 	struct shmfd *shmfd;
1068 	vm_map_entry_t entry;
1069 	vm_offset_t kva, ofs;
1070 	vm_object_t obj;
1071 	vm_pindex_t pindex;
1072 	vm_prot_t prot;
1073 	boolean_t wired;
1074 	vm_map_t map;
1075 	int rv;
1076 
1077 	if (fp->f_type != DTYPE_SHM)
1078 		return (EINVAL);
1079 	shmfd = fp->f_data;
1080 	kva = (vm_offset_t)mem;
1081 	ofs = kva & PAGE_MASK;
1082 	kva = trunc_page(kva);
1083 	size = round_page(size + ofs);
1084 	map = kernel_map;
1085 	rv = vm_map_lookup(&map, kva, VM_PROT_READ | VM_PROT_WRITE, &entry,
1086 	    &obj, &pindex, &prot, &wired);
1087 	if (rv != KERN_SUCCESS)
1088 		return (EINVAL);
1089 	if (entry->start != kva || entry->end != kva + size) {
1090 		vm_map_lookup_done(map, entry);
1091 		return (EINVAL);
1092 	}
1093 	vm_map_lookup_done(map, entry);
1094 	if (obj != shmfd->shm_object)
1095 		return (EINVAL);
1096 	vm_map_remove(map, kva, kva + size);
1097 	VM_OBJECT_WLOCK(obj);
1098 	KASSERT(shmfd->shm_kmappings > 0, ("shm_unmap: object not mapped"));
1099 	shmfd->shm_kmappings--;
1100 	VM_OBJECT_WUNLOCK(obj);
1101 	return (0);
1102 }
1103 
1104 static int
1105 shm_fill_kinfo_locked(struct shmfd *shmfd, struct kinfo_file *kif, bool list)
1106 {
1107 	const char *path, *pr_path;
1108 	size_t pr_pathlen;
1109 	bool visible;
1110 
1111 	sx_assert(&shm_dict_lock, SA_LOCKED);
1112 	kif->kf_type = KF_TYPE_SHM;
1113 	kif->kf_un.kf_file.kf_file_mode = S_IFREG | shmfd->shm_mode;
1114 	kif->kf_un.kf_file.kf_file_size = shmfd->shm_size;
1115 	if (shmfd->shm_path != NULL) {
1116 		if (shmfd->shm_path != NULL) {
1117 			path = shmfd->shm_path;
1118 			pr_path = curthread->td_ucred->cr_prison->pr_path;
1119 			if (strcmp(pr_path, "/") != 0) {
1120 				/* Return the jail-rooted pathname. */
1121 				pr_pathlen = strlen(pr_path);
1122 				visible = strncmp(path, pr_path, pr_pathlen)
1123 				    == 0 && path[pr_pathlen] == '/';
1124 				if (list && !visible)
1125 					return (EPERM);
1126 				if (visible)
1127 					path += pr_pathlen;
1128 			}
1129 			strlcpy(kif->kf_path, path, sizeof(kif->kf_path));
1130 		}
1131 	}
1132 	return (0);
1133 }
1134 
1135 static int
1136 shm_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1137     struct filedesc *fdp __unused)
1138 {
1139 	int res;
1140 
1141 	sx_slock(&shm_dict_lock);
1142 	res = shm_fill_kinfo_locked(fp->f_data, kif, false);
1143 	sx_sunlock(&shm_dict_lock);
1144 	return (res);
1145 }
1146 
1147 static int
1148 sysctl_posix_shm_list(SYSCTL_HANDLER_ARGS)
1149 {
1150 	struct shm_mapping *shmm;
1151 	struct sbuf sb;
1152 	struct kinfo_file kif;
1153 	u_long i;
1154 	ssize_t curlen;
1155 	int error, error2;
1156 
1157 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file) * 5, req);
1158 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
1159 	curlen = 0;
1160 	error = 0;
1161 	sx_slock(&shm_dict_lock);
1162 	for (i = 0; i < shm_hash + 1; i++) {
1163 		LIST_FOREACH(shmm, &shm_dictionary[i], sm_link) {
1164 			error = shm_fill_kinfo_locked(shmm->sm_shmfd,
1165 			    &kif, true);
1166 			if (error == EPERM)
1167 				continue;
1168 			if (error != 0)
1169 				break;
1170 			pack_kinfo(&kif);
1171 			if (req->oldptr != NULL &&
1172 			    kif.kf_structsize + curlen > req->oldlen)
1173 				break;
1174 			error = sbuf_bcat(&sb, &kif, kif.kf_structsize) == 0 ?
1175 			    0 : ENOMEM;
1176 			if (error != 0)
1177 				break;
1178 			curlen += kif.kf_structsize;
1179 		}
1180 	}
1181 	sx_sunlock(&shm_dict_lock);
1182 	error2 = sbuf_finish(&sb);
1183 	sbuf_delete(&sb);
1184 	return (error != 0 ? error : error2);
1185 }
1186 
1187 SYSCTL_PROC(_kern_ipc, OID_AUTO, posix_shm_list,
1188     CTLFLAG_RD | CTLFLAG_MPSAFE | CTLTYPE_OPAQUE,
1189     NULL, 0, sysctl_posix_shm_list, "",
1190     "POSIX SHM list");
1191