xref: /freebsd/sys/kern/uipc_shm.c (revision d8dfbeb5701769832e84e5bb52f2e8b4e3ab902b)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2006, 2011, 2016-2017 Robert N. M. Watson
5  * Copyright 2020 The FreeBSD Foundation
6  * All rights reserved.
7  *
8  * Portions of this software were developed by BAE Systems, the University of
9  * Cambridge Computer Laboratory, and Memorial University under DARPA/AFRL
10  * contract FA8650-15-C-7558 ("CADETS"), as part of the DARPA Transparent
11  * Computing (TC) research program.
12  *
13  * Portions of this software were developed by Konstantin Belousov
14  * under sponsorship from the FreeBSD Foundation.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 /*
39  * Support for shared swap-backed anonymous memory objects via
40  * shm_open(2), shm_rename(2), and shm_unlink(2).
41  * While most of the implementation is here, vm_mmap.c contains
42  * mapping logic changes.
43  *
44  * posixshmcontrol(1) allows users to inspect the state of the memory
45  * objects.  Per-uid swap resource limit controls total amount of
46  * memory that user can consume for anonymous objects, including
47  * shared.
48  */
49 
50 #include <sys/cdefs.h>
51 #include "opt_capsicum.h"
52 #include "opt_ktrace.h"
53 
54 #include <sys/param.h>
55 #include <sys/capsicum.h>
56 #include <sys/conf.h>
57 #include <sys/fcntl.h>
58 #include <sys/file.h>
59 #include <sys/filedesc.h>
60 #include <sys/filio.h>
61 #include <sys/fnv_hash.h>
62 #include <sys/kernel.h>
63 #include <sys/limits.h>
64 #include <sys/uio.h>
65 #include <sys/signal.h>
66 #include <sys/jail.h>
67 #include <sys/ktrace.h>
68 #include <sys/lock.h>
69 #include <sys/malloc.h>
70 #include <sys/mman.h>
71 #include <sys/mutex.h>
72 #include <sys/priv.h>
73 #include <sys/proc.h>
74 #include <sys/refcount.h>
75 #include <sys/resourcevar.h>
76 #include <sys/rwlock.h>
77 #include <sys/sbuf.h>
78 #include <sys/stat.h>
79 #include <sys/syscallsubr.h>
80 #include <sys/sysctl.h>
81 #include <sys/sysproto.h>
82 #include <sys/systm.h>
83 #include <sys/sx.h>
84 #include <sys/time.h>
85 #include <sys/vmmeter.h>
86 #include <sys/vnode.h>
87 #include <sys/unistd.h>
88 #include <sys/user.h>
89 
90 #include <security/audit/audit.h>
91 #include <security/mac/mac_framework.h>
92 
93 #include <vm/vm.h>
94 #include <vm/vm_param.h>
95 #include <vm/pmap.h>
96 #include <vm/vm_extern.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_kern.h>
99 #include <vm/vm_object.h>
100 #include <vm/vm_page.h>
101 #include <vm/vm_pageout.h>
102 #include <vm/vm_pager.h>
103 #include <vm/vm_radix.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 static void	shm_doremove(struct shm_mapping *map);
128 static int	shm_dotruncate_cookie(struct shmfd *shmfd, off_t length,
129     void *rl_cookie);
130 static int	shm_dotruncate_locked(struct shmfd *shmfd, off_t length,
131     void *rl_cookie);
132 static int	shm_copyin_path(struct thread *td, const char *userpath_in,
133     char **path_out);
134 static int	shm_deallocate(struct shmfd *shmfd, off_t *offset,
135     off_t *length, int flags);
136 
137 static fo_rdwr_t	shm_read;
138 static fo_rdwr_t	shm_write;
139 static fo_truncate_t	shm_truncate;
140 static fo_ioctl_t	shm_ioctl;
141 static fo_stat_t	shm_stat;
142 static fo_close_t	shm_close;
143 static fo_chmod_t	shm_chmod;
144 static fo_chown_t	shm_chown;
145 static fo_seek_t	shm_seek;
146 static fo_fill_kinfo_t	shm_fill_kinfo;
147 static fo_mmap_t	shm_mmap;
148 static fo_get_seals_t	shm_get_seals;
149 static fo_add_seals_t	shm_add_seals;
150 static fo_fallocate_t	shm_fallocate;
151 static fo_fspacectl_t	shm_fspacectl;
152 
153 /* File descriptor operations. */
154 const struct fileops shm_ops = {
155 	.fo_read = shm_read,
156 	.fo_write = shm_write,
157 	.fo_truncate = shm_truncate,
158 	.fo_ioctl = shm_ioctl,
159 	.fo_poll = invfo_poll,
160 	.fo_kqfilter = invfo_kqfilter,
161 	.fo_stat = shm_stat,
162 	.fo_close = shm_close,
163 	.fo_chmod = shm_chmod,
164 	.fo_chown = shm_chown,
165 	.fo_sendfile = vn_sendfile,
166 	.fo_seek = shm_seek,
167 	.fo_fill_kinfo = shm_fill_kinfo,
168 	.fo_mmap = shm_mmap,
169 	.fo_get_seals = shm_get_seals,
170 	.fo_add_seals = shm_add_seals,
171 	.fo_fallocate = shm_fallocate,
172 	.fo_fspacectl = shm_fspacectl,
173 	.fo_cmp = file_kcmp_generic,
174 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE,
175 };
176 
177 FEATURE(posix_shm, "POSIX shared memory");
178 
179 static SYSCTL_NODE(_vm, OID_AUTO, largepages, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
180     "");
181 
182 static int largepage_reclaim_tries = 1;
183 SYSCTL_INT(_vm_largepages, OID_AUTO, reclaim_tries,
184     CTLFLAG_RWTUN, &largepage_reclaim_tries, 0,
185     "Number of contig reclaims before giving up for default alloc policy");
186 
187 #define	shm_rangelock_unlock(shmfd, cookie)				\
188 	rangelock_unlock(&(shmfd)->shm_rl, (cookie))
189 #define	shm_rangelock_rlock(shmfd, start, end)				\
190 	rangelock_rlock(&(shmfd)->shm_rl, (start), (end))
191 #define	shm_rangelock_tryrlock(shmfd, start, end)			\
192 	rangelock_tryrlock(&(shmfd)->shm_rl, (start), (end))
193 #define	shm_rangelock_wlock(shmfd, start, end)				\
194 	rangelock_wlock(&(shmfd)->shm_rl, (start), (end))
195 
196 static int
197 uiomove_object_page(vm_object_t obj, size_t len, struct uio *uio)
198 {
199 	struct pctrie_iter pages;
200 	vm_page_t m;
201 	vm_pindex_t idx;
202 	size_t tlen;
203 	int error, offset, rv;
204 
205 	idx = OFF_TO_IDX(uio->uio_offset);
206 	offset = uio->uio_offset & PAGE_MASK;
207 	tlen = MIN(PAGE_SIZE - offset, len);
208 
209 	rv = vm_page_grab_valid_unlocked(&m, obj, idx,
210 	    VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY | VM_ALLOC_NOCREAT);
211 	if (rv == VM_PAGER_OK)
212 		goto found;
213 
214 	/*
215 	 * Read I/O without either a corresponding resident page or swap
216 	 * page: use zero_region.  This is intended to avoid instantiating
217 	 * pages on read from a sparse region.
218 	 */
219 	vm_page_iter_init(&pages, obj);
220 	VM_OBJECT_WLOCK(obj);
221 	m = vm_radix_iter_lookup(&pages, idx);
222 	if (uio->uio_rw == UIO_READ && m == NULL &&
223 	    !vm_pager_has_page(obj, idx, NULL, NULL)) {
224 		VM_OBJECT_WUNLOCK(obj);
225 		return (uiomove(__DECONST(void *, zero_region), tlen, uio));
226 	}
227 
228 	/*
229 	 * Although the tmpfs vnode lock is held here, it is
230 	 * nonetheless safe to sleep waiting for a free page.  The
231 	 * pageout daemon does not need to acquire the tmpfs vnode
232 	 * lock to page out tobj's pages because tobj is a OBJT_SWAP
233 	 * type object.
234 	 */
235 	rv = vm_page_grab_valid_iter(&m, obj, idx,
236 	    VM_ALLOC_NORMAL | VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY, &pages);
237 	if (rv != VM_PAGER_OK) {
238 		VM_OBJECT_WUNLOCK(obj);
239 		if (bootverbose) {
240 			printf("uiomove_object: vm_obj %p idx %jd "
241 			    "pager error %d\n", obj, idx, rv);
242 		}
243 		return (rv == VM_PAGER_AGAIN ? ENOSPC : EIO);
244 	}
245 	VM_OBJECT_WUNLOCK(obj);
246 
247 found:
248 	error = uiomove_fromphys(&m, offset, tlen, uio);
249 	if (uio->uio_rw == UIO_WRITE) {
250 		/*
251 		 * Even a failed copy may have changed the page's contents,
252 		 * because uiomove_fromphys() can copy part of the data before
253 		 * it fails.
254 		 */
255 		vm_page_set_dirty(m);
256 	}
257 	vm_page_activate(m);
258 	vm_page_sunbusy(m);
259 
260 	return (error);
261 }
262 
263 int
264 uiomove_object(vm_object_t obj, off_t obj_size, struct uio *uio)
265 {
266 	ssize_t resid;
267 	size_t len;
268 	int error;
269 
270 	error = 0;
271 	while ((resid = uio->uio_resid) > 0) {
272 		if (obj_size <= uio->uio_offset)
273 			break;
274 		len = MIN(obj_size - uio->uio_offset, resid);
275 		if (len == 0)
276 			break;
277 		error = uiomove_object_page(obj, len, uio);
278 		if (error != 0 || resid == uio->uio_resid)
279 			break;
280 	}
281 	return (error);
282 }
283 
284 static u_long count_largepages[MAXPAGESIZES];
285 
286 static int
287 shm_largepage_phys_populate(vm_object_t object, vm_pindex_t pidx,
288     int fault_type, vm_prot_t max_prot, vm_pindex_t *first, vm_pindex_t *last)
289 {
290 	vm_page_t m __diagused;
291 	int psind;
292 
293 	psind = object->un_pager.phys.data_val;
294 	if (psind == 0 || pidx >= object->size)
295 		return (VM_PAGER_FAIL);
296 	*first = rounddown2(pidx, pagesizes[psind] / PAGE_SIZE);
297 
298 	/*
299 	 * We only busy the first page in the superpage run.  It is
300 	 * useless to busy whole run since we only remove full
301 	 * superpage, and it takes too long to busy e.g. 512 * 512 ==
302 	 * 262144 pages constituing 1G amd64 superage.
303 	 */
304 	m = vm_page_grab(object, *first, VM_ALLOC_NORMAL | VM_ALLOC_NOCREAT);
305 	MPASS(m != NULL);
306 
307 	*last = *first + atop(pagesizes[psind]) - 1;
308 	return (VM_PAGER_OK);
309 }
310 
311 static boolean_t
312 shm_largepage_phys_haspage(vm_object_t object, vm_pindex_t pindex,
313     int *before, int *after)
314 {
315 	int psind;
316 
317 	psind = object->un_pager.phys.data_val;
318 	if (psind == 0 || pindex >= object->size)
319 		return (FALSE);
320 	if (before != NULL) {
321 		*before = pindex - rounddown2(pindex, pagesizes[psind] /
322 		    PAGE_SIZE);
323 	}
324 	if (after != NULL) {
325 		*after = roundup2(pindex, pagesizes[psind] / PAGE_SIZE) -
326 		    pindex;
327 	}
328 	return (TRUE);
329 }
330 
331 static void
332 shm_largepage_phys_ctor(vm_object_t object, vm_prot_t prot,
333     vm_ooffset_t foff, struct ucred *cred)
334 {
335 	object->flags |= OBJ_PG_DTOR;
336 }
337 
338 static void
339 shm_largepage_phys_dtor(vm_object_t object)
340 {
341 	int psind;
342 
343 	VM_OBJECT_ASSERT_WLOCKED(object);
344 
345 	psind = object->un_pager.phys.data_val;
346 	if (psind != 0) {
347 		struct pctrie_iter pages;
348 		vm_page_t m;
349 		bool removed __diagused;
350 
351 		vm_page_iter_init(&pages, object);
352 restart:
353 		VM_RADIX_FOREACH(m, &pages) {
354 			if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL)) {
355 				pctrie_iter_reset(&pages);
356 				goto restart;
357 			}
358 			removed = vm_page_iter_remove(&pages, m);
359 			KASSERT(!removed, ("%s: page %p not wired", __func__, m));
360 			vm_page_unwire(m, PQ_NONE);
361 		}
362 		atomic_subtract_long(&count_largepages[psind],
363 		    object->size / (pagesizes[psind] / PAGE_SIZE));
364 	} else {
365 		KASSERT(object->size == 0,
366 		    ("largepage phys obj %p not initialized bit size %#jx > 0",
367 		    object, (uintmax_t)object->size));
368 	}
369 }
370 
371 static const struct phys_pager_ops shm_largepage_phys_ops = {
372 	.phys_pg_populate =	shm_largepage_phys_populate,
373 	.phys_pg_haspage =	shm_largepage_phys_haspage,
374 	.phys_pg_ctor =		shm_largepage_phys_ctor,
375 	.phys_pg_dtor =		shm_largepage_phys_dtor,
376 };
377 
378 bool
379 shm_largepage(struct shmfd *shmfd)
380 {
381 	return (shmfd->shm_object->type == OBJT_PHYS);
382 }
383 
384 static void
385 shm_pager_freespace(vm_object_t obj, vm_pindex_t start, vm_size_t size)
386 {
387 	struct shmfd *shm;
388 	vm_size_t c;
389 
390 	swap_pager_freespace(obj, start, size, &c);
391 	if (c == 0)
392 		return;
393 
394 	shm = obj->un_pager.swp.swp_priv;
395 	if (shm == NULL)
396 		return;
397 	KASSERT(shm->shm_pages >= c,
398 	    ("shm %p pages %jd free %jd", shm,
399 	    (uintmax_t)shm->shm_pages, (uintmax_t)c));
400 	shm->shm_pages -= c;
401 }
402 
403 static void
404 shm_page_inserted(vm_object_t obj, vm_page_t m)
405 {
406 	struct shmfd *shm;
407 
408 	shm = obj->un_pager.swp.swp_priv;
409 	if (shm == NULL)
410 		return;
411 	if (!vm_pager_has_page(obj, m->pindex, NULL, NULL))
412 		shm->shm_pages += 1;
413 }
414 
415 static void
416 shm_page_removed(vm_object_t obj, vm_page_t m)
417 {
418 	struct shmfd *shm;
419 
420 	shm = obj->un_pager.swp.swp_priv;
421 	if (shm == NULL)
422 		return;
423 	if (!vm_pager_has_page(obj, m->pindex, NULL, NULL)) {
424 		KASSERT(shm->shm_pages >= 1,
425 		    ("shm %p pages %jd free 1", shm,
426 		    (uintmax_t)shm->shm_pages));
427 		shm->shm_pages -= 1;
428 	}
429 }
430 
431 static struct pagerops shm_swap_pager_ops = {
432 	.pgo_kvme_type = KVME_TYPE_SWAP,
433 	.pgo_freespace = shm_pager_freespace,
434 	.pgo_page_inserted = shm_page_inserted,
435 	.pgo_page_removed = shm_page_removed,
436 };
437 static int shmfd_pager_type = -1;
438 
439 static int
440 shm_seek(struct file *fp, off_t offset, int whence, struct thread *td)
441 {
442 	struct shmfd *shmfd;
443 	off_t foffset;
444 	int error;
445 
446 	shmfd = fp->f_data;
447 	foffset = foffset_lock(fp, 0);
448 	error = 0;
449 	switch (whence) {
450 	case L_INCR:
451 		if (foffset < 0 ||
452 		    (offset > 0 && foffset > OFF_MAX - offset)) {
453 			error = EOVERFLOW;
454 			break;
455 		}
456 		offset += foffset;
457 		break;
458 	case L_XTND:
459 		if (offset > 0 && shmfd->shm_size > OFF_MAX - offset) {
460 			error = EOVERFLOW;
461 			break;
462 		}
463 		offset += shmfd->shm_size;
464 		break;
465 	case L_SET:
466 		break;
467 	default:
468 		error = EINVAL;
469 	}
470 	if (error == 0) {
471 		if (offset < 0 || offset > shmfd->shm_size)
472 			error = EINVAL;
473 		else
474 			td->td_uretoff.tdu_off = offset;
475 	}
476 	foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
477 	return (error);
478 }
479 
480 static int
481 shm_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
482     int flags, struct thread *td)
483 {
484 	struct shmfd *shmfd;
485 	void *rl_cookie;
486 	int error;
487 
488 	shmfd = fp->f_data;
489 #ifdef MAC
490 	error = mac_posixshm_check_read(active_cred, fp->f_cred, shmfd);
491 	if (error)
492 		return (error);
493 #endif
494 	foffset_lock_uio(fp, uio, flags);
495 	rl_cookie = shm_rangelock_rlock(shmfd, uio->uio_offset,
496 	    uio->uio_offset + uio->uio_resid);
497 	error = uiomove_object(shmfd->shm_object, shmfd->shm_size, uio);
498 	shm_rangelock_unlock(shmfd, rl_cookie);
499 	foffset_unlock_uio(fp, uio, flags);
500 	return (error);
501 }
502 
503 static int
504 shm_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
505     int flags, struct thread *td)
506 {
507 	struct shmfd *shmfd;
508 	void *rl_cookie;
509 	int error;
510 	off_t newsize;
511 
512 	KASSERT((flags & FOF_OFFSET) == 0 || uio->uio_offset >= 0,
513 	    ("%s: negative offset", __func__));
514 
515 	shmfd = fp->f_data;
516 #ifdef MAC
517 	error = mac_posixshm_check_write(active_cred, fp->f_cred, shmfd);
518 	if (error)
519 		return (error);
520 #endif
521 	foffset_lock_uio(fp, uio, flags);
522 	if (uio->uio_resid > OFF_MAX - uio->uio_offset) {
523 		/*
524 		 * Overflow is only an error if we're supposed to expand on
525 		 * write.  Otherwise, we'll just truncate the write to the
526 		 * size of the file, which can only grow up to OFF_MAX.
527 		 */
528 		if ((shmfd->shm_flags & SHM_GROW_ON_WRITE) != 0) {
529 			foffset_unlock_uio(fp, uio, flags);
530 			return (EFBIG);
531 		}
532 
533 		newsize = atomic_load_64(&shmfd->shm_size);
534 	} else {
535 		newsize = uio->uio_offset + uio->uio_resid;
536 	}
537 	if ((flags & FOF_OFFSET) == 0)
538 		rl_cookie = shm_rangelock_wlock(shmfd, 0, OFF_MAX);
539 	else
540 		rl_cookie = shm_rangelock_wlock(shmfd, uio->uio_offset,
541 		    MAX(newsize, uio->uio_offset));
542 	if (shm_largepage(shmfd) && shmfd->shm_lp_psind == 0) {
543 		error = EINVAL;
544 	} else if ((shmfd->shm_seals & F_SEAL_WRITE) != 0) {
545 		error = EPERM;
546 	} else {
547 		error = 0;
548 		if ((shmfd->shm_flags & SHM_GROW_ON_WRITE) != 0 &&
549 		    newsize > shmfd->shm_size) {
550 			error = shm_dotruncate_cookie(shmfd, newsize,
551 			    rl_cookie);
552 		}
553 		if (error == 0)
554 			error = uiomove_object(shmfd->shm_object,
555 			    shmfd->shm_size, uio);
556 	}
557 	shm_rangelock_unlock(shmfd, rl_cookie);
558 	foffset_unlock_uio(fp, uio, flags);
559 	return (error);
560 }
561 
562 static int
563 shm_truncate(struct file *fp, off_t length, struct ucred *active_cred,
564     struct thread *td)
565 {
566 	struct shmfd *shmfd;
567 #ifdef MAC
568 	int error;
569 #endif
570 
571 	shmfd = fp->f_data;
572 #ifdef MAC
573 	error = mac_posixshm_check_truncate(active_cred, fp->f_cred, shmfd);
574 	if (error)
575 		return (error);
576 #endif
577 	return (shm_dotruncate(shmfd, length));
578 }
579 
580 int
581 shm_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
582     struct thread *td)
583 {
584 	struct shmfd *shmfd;
585 	struct shm_largepage_conf *conf;
586 	void *rl_cookie;
587 
588 	shmfd = fp->f_data;
589 	switch (com) {
590 	case FIONBIO:
591 	case FIOASYNC:
592 		/*
593 		 * Allow fcntl(fd, F_SETFL, O_NONBLOCK) to work,
594 		 * just like it would on an unlinked regular file
595 		 */
596 		return (0);
597 	case FIOSSHMLPGCNF:
598 		if (!shm_largepage(shmfd))
599 			return (ENOTTY);
600 		conf = data;
601 		rl_cookie = shm_rangelock_wlock(shmfd, 0, OFF_MAX);
602 		if (shmfd->shm_lp_psind != 0 &&
603 		    conf->psind != shmfd->shm_lp_psind) {
604 			shm_rangelock_unlock(shmfd, rl_cookie);
605 			return (EINVAL);
606 		}
607 		if (conf->psind <= 0 || conf->psind >= MAXPAGESIZES ||
608 		    pagesizes[conf->psind] == 0) {
609 			shm_rangelock_unlock(shmfd, rl_cookie);
610 			return (EINVAL);
611 		}
612 		if (conf->alloc_policy != SHM_LARGEPAGE_ALLOC_DEFAULT &&
613 		    conf->alloc_policy != SHM_LARGEPAGE_ALLOC_NOWAIT &&
614 		    conf->alloc_policy != SHM_LARGEPAGE_ALLOC_HARD) {
615 			shm_rangelock_unlock(shmfd, rl_cookie);
616 			return (EINVAL);
617 		}
618 		shmfd->shm_lp_psind = conf->psind;
619 		shmfd->shm_lp_alloc_policy = conf->alloc_policy;
620 		shmfd->shm_object->un_pager.phys.data_val = conf->psind;
621 		shm_rangelock_unlock(shmfd, rl_cookie);
622 		return (0);
623 	case FIOGSHMLPGCNF:
624 		if (!shm_largepage(shmfd))
625 			return (ENOTTY);
626 		conf = data;
627 		rl_cookie = shm_rangelock_rlock(shmfd, 0, OFF_MAX);
628 		conf->psind = shmfd->shm_lp_psind;
629 		conf->alloc_policy = shmfd->shm_lp_alloc_policy;
630 		shm_rangelock_unlock(shmfd, rl_cookie);
631 		return (0);
632 	default:
633 		return (ENOTTY);
634 	}
635 }
636 
637 static int
638 shm_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
639 {
640 	struct shmfd *shmfd;
641 #ifdef MAC
642 	int error;
643 #endif
644 
645 	shmfd = fp->f_data;
646 
647 #ifdef MAC
648 	error = mac_posixshm_check_stat(active_cred, fp->f_cred, shmfd);
649 	if (error)
650 		return (error);
651 #endif
652 
653 	/*
654 	 * Attempt to return sanish values for fstat() on a memory file
655 	 * descriptor.
656 	 */
657 	bzero(sb, sizeof(*sb));
658 	sb->st_blksize = PAGE_SIZE;
659 	sb->st_size = shmfd->shm_size;
660 	mtx_lock(&shm_timestamp_lock);
661 	sb->st_atim = shmfd->shm_atime;
662 	sb->st_ctim = shmfd->shm_ctime;
663 	sb->st_mtim = shmfd->shm_mtime;
664 	sb->st_birthtim = shmfd->shm_birthtime;
665 	sb->st_mode = S_IFREG | shmfd->shm_mode;		/* XXX */
666 	sb->st_uid = shmfd->shm_uid;
667 	sb->st_gid = shmfd->shm_gid;
668 	mtx_unlock(&shm_timestamp_lock);
669 	sb->st_dev = shm_dev_ino;
670 	sb->st_ino = shmfd->shm_ino;
671 	sb->st_nlink = shmfd->shm_object->ref_count;
672 	sb->st_blocks = ptoa(shm_largepage(shmfd) ? shmfd->shm_object->size :
673 	    shmfd->shm_pages) / DEV_BSIZE;
674 
675 	return (0);
676 }
677 
678 static int
679 shm_close(struct file *fp, struct thread *td)
680 {
681 	struct shmfd *shmfd;
682 
683 	shmfd = fp->f_data;
684 	fp->f_data = NULL;
685 	shm_drop(shmfd);
686 
687 	return (0);
688 }
689 
690 static int
691 shm_copyin_path(struct thread *td, const char *userpath_in, char **path_out) {
692 	int error;
693 	char *path;
694 	const char *pr_path;
695 	size_t pr_pathlen;
696 
697 	path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
698 	pr_path = td->td_ucred->cr_prison->pr_path;
699 
700 	/* Construct a full pathname for jailed callers. */
701 	pr_pathlen = strcmp(pr_path, "/") ==
702 	    0 ? 0 : strlcpy(path, pr_path, MAXPATHLEN);
703 	error = copyinstr(userpath_in, path + pr_pathlen,
704 	    MAXPATHLEN - pr_pathlen, NULL);
705 	if (error != 0)
706 		goto out;
707 
708 #ifdef KTRACE
709 	if (KTRPOINT(curthread, KTR_NAMEI))
710 		ktrnamei(path);
711 #endif
712 
713 	/* Require paths to start with a '/' character. */
714 	if (path[pr_pathlen] != '/') {
715 		error = EINVAL;
716 		goto out;
717 	}
718 
719 	*path_out = path;
720 
721 out:
722 	if (error != 0)
723 		free(path, M_SHMFD);
724 
725 	return (error);
726 }
727 
728 static int
729 shm_partial_page_invalidate(vm_object_t object, vm_pindex_t idx, int base,
730     int end)
731 {
732 	return (vm_page_grab_zero_partial(object, idx, base, end));
733 }
734 
735 static int
736 shm_dotruncate_locked(struct shmfd *shmfd, off_t length, void *rl_cookie)
737 {
738 	vm_object_t object;
739 	vm_pindex_t nobjsize;
740 	vm_ooffset_t delta;
741 	int base, error;
742 
743 	KASSERT(length >= 0, ("shm_dotruncate: length < 0"));
744 	object = shmfd->shm_object;
745 	VM_OBJECT_ASSERT_WLOCKED(object);
746 	rangelock_cookie_assert(rl_cookie, RCA_WLOCKED);
747 	if (length == shmfd->shm_size)
748 		return (0);
749 	nobjsize = OFF_TO_IDX(length + PAGE_MASK);
750 
751 	/* Are we shrinking?  If so, trim the end. */
752 	if (length < shmfd->shm_size) {
753 		if ((shmfd->shm_seals & F_SEAL_SHRINK) != 0)
754 			return (EPERM);
755 
756 		/*
757 		 * Disallow any requests to shrink the size if this
758 		 * object is mapped into the kernel.
759 		 */
760 		if (shmfd->shm_kmappings > 0)
761 			return (EBUSY);
762 
763 		/*
764 		 * Zero the truncated part of the last page.
765 		 */
766 		base = length & PAGE_MASK;
767 		if (base != 0) {
768 			error = shm_partial_page_invalidate(object,
769 			    OFF_TO_IDX(length), base, PAGE_SIZE);
770 			if (error)
771 				return (error);
772 		}
773 		delta = IDX_TO_OFF(object->size - nobjsize);
774 
775 		if (nobjsize < object->size)
776 			vm_object_page_remove(object, nobjsize, object->size,
777 			    0);
778 
779 		/* Free the swap accounted for shm */
780 		swap_release_by_cred(delta, object->cred);
781 	} else {
782 		if ((shmfd->shm_seals & F_SEAL_GROW) != 0)
783 			return (EPERM);
784 
785 		/* Try to reserve additional swap space. */
786 		delta = IDX_TO_OFF(nobjsize - object->size);
787 		if (!swap_reserve_by_cred(delta, object->cred))
788 			return (ENOMEM);
789 	}
790 	shmfd->shm_size = length;
791 	mtx_lock(&shm_timestamp_lock);
792 	vfs_timestamp(&shmfd->shm_ctime);
793 	shmfd->shm_mtime = shmfd->shm_ctime;
794 	mtx_unlock(&shm_timestamp_lock);
795 	object->size = nobjsize;
796 	return (0);
797 }
798 
799 static int
800 shm_dotruncate_largepage(struct shmfd *shmfd, off_t length, void *rl_cookie)
801 {
802 	vm_object_t object;
803 	vm_page_t m;
804 	vm_pindex_t newobjsz;
805 	vm_pindex_t oldobjsz __unused;
806 	int aflags, error, i, psind, try;
807 
808 	KASSERT(length >= 0, ("shm_dotruncate_largepage: length < 0"));
809 	object = shmfd->shm_object;
810 	VM_OBJECT_ASSERT_WLOCKED(object);
811 	rangelock_cookie_assert(rl_cookie, RCA_WLOCKED);
812 
813 	oldobjsz = object->size;
814 	newobjsz = OFF_TO_IDX(length);
815 	if (length == shmfd->shm_size)
816 		return (0);
817 	psind = shmfd->shm_lp_psind;
818 	if (psind == 0 && length != 0)
819 		return (EINVAL);
820 	if ((length & (pagesizes[psind] - 1)) != 0)
821 		return (EINVAL);
822 
823 	if (length < shmfd->shm_size) {
824 		if ((shmfd->shm_seals & F_SEAL_SHRINK) != 0)
825 			return (EPERM);
826 		if (shmfd->shm_kmappings > 0)
827 			return (EBUSY);
828 		return (ENOTSUP);	/* Pages are unmanaged. */
829 #if 0
830 		vm_object_page_remove(object, newobjsz, oldobjsz, 0);
831 		object->size = newobjsz;
832 		shmfd->shm_size = length;
833 		return (0);
834 #endif
835 	}
836 
837 	if ((shmfd->shm_seals & F_SEAL_GROW) != 0)
838 		return (EPERM);
839 
840 	aflags = VM_ALLOC_NORMAL | VM_ALLOC_ZERO | VM_ALLOC_WIRED;
841 	if (shmfd->shm_lp_alloc_policy == SHM_LARGEPAGE_ALLOC_NOWAIT)
842 		aflags |= VM_ALLOC_WAITFAIL;
843 	try = 0;
844 
845 	/*
846 	 * Extend shmfd and object, keeping all already fully
847 	 * allocated large pages intact even on error, because dropped
848 	 * object lock might allowed mapping of them.
849 	 */
850 	while (object->size < newobjsz) {
851 		error = sig_intr();
852 		if (error != 0)
853 			return (error);
854 		m = vm_page_alloc_contig(object, object->size, aflags,
855 		    pagesizes[psind] / PAGE_SIZE, 0, ~0,
856 		    pagesizes[psind], 0,
857 		    VM_MEMATTR_DEFAULT);
858 		if (m == NULL) {
859 			VM_OBJECT_WUNLOCK(object);
860 			error = sig_intr();
861 			if (error != 0) {
862 				VM_OBJECT_WLOCK(object);
863 				return (error);
864 			}
865 			if (shmfd->shm_lp_alloc_policy ==
866 			    SHM_LARGEPAGE_ALLOC_NOWAIT ||
867 			    (shmfd->shm_lp_alloc_policy ==
868 			    SHM_LARGEPAGE_ALLOC_DEFAULT &&
869 			    try >= largepage_reclaim_tries)) {
870 				VM_OBJECT_WLOCK(object);
871 				return (ENOMEM);
872 			}
873 			error = vm_page_reclaim_contig(aflags,
874 			    pagesizes[psind] / PAGE_SIZE, 0, ~0,
875 			    pagesizes[psind], 0);
876 			if (error == ENOMEM)
877 				error = vm_wait_intr(object);
878 			if (error != 0) {
879 				VM_OBJECT_WLOCK(object);
880 				return (error);
881 			}
882 			try++;
883 			VM_OBJECT_WLOCK(object);
884 			continue;
885 		}
886 		try = 0;
887 		for (i = 0; i < pagesizes[psind] / PAGE_SIZE; i++) {
888 			if ((m[i].flags & PG_ZERO) == 0)
889 				pmap_zero_page(&m[i]);
890 			vm_page_valid(&m[i]);
891 			vm_page_xunbusy(&m[i]);
892 		}
893 		object->size += OFF_TO_IDX(pagesizes[psind]);
894 		shmfd->shm_size += pagesizes[psind];
895 		atomic_add_long(&count_largepages[psind], 1);
896 	}
897 	return (0);
898 }
899 
900 static int
901 shm_dotruncate_cookie(struct shmfd *shmfd, off_t length, void *rl_cookie)
902 {
903 	int error;
904 
905 	VM_OBJECT_WLOCK(shmfd->shm_object);
906 	error = shm_largepage(shmfd) ? shm_dotruncate_largepage(shmfd,
907 	    length, rl_cookie) : shm_dotruncate_locked(shmfd, length,
908 	    rl_cookie);
909 	VM_OBJECT_WUNLOCK(shmfd->shm_object);
910 	return (error);
911 }
912 
913 int
914 shm_dotruncate(struct shmfd *shmfd, off_t length)
915 {
916 	void *rl_cookie;
917 	int error;
918 
919 	rl_cookie = shm_rangelock_wlock(shmfd, 0, OFF_MAX);
920 	error = shm_dotruncate_cookie(shmfd, length, rl_cookie);
921 	shm_rangelock_unlock(shmfd, rl_cookie);
922 	return (error);
923 }
924 
925 /*
926  * shmfd object management including creation and reference counting
927  * routines.
928  */
929 struct shmfd *
930 shm_alloc(struct ucred *ucred, mode_t mode, bool largepage)
931 {
932 	struct shmfd *shmfd;
933 	vm_object_t obj;
934 
935 	if (largepage) {
936 		obj = phys_pager_allocate(NULL, &shm_largepage_phys_ops,
937 		    NULL, 0, VM_PROT_DEFAULT, 0, ucred);
938 	} else {
939 		obj = vm_pager_allocate(shmfd_pager_type, NULL, 0,
940 		    VM_PROT_DEFAULT, 0, ucred);
941 	}
942 	if (obj == NULL) {
943 		/*
944 		 * swap reservation limits can cause object allocation
945 		 * to fail.
946 		 */
947 		return (NULL);
948 	}
949 
950 	shmfd = malloc(sizeof(*shmfd), M_SHMFD, M_WAITOK | M_ZERO);
951 	shmfd->shm_uid = ucred->cr_uid;
952 	shmfd->shm_gid = ucred->cr_gid;
953 	shmfd->shm_mode = mode;
954 	if (largepage) {
955 		obj->un_pager.phys.phys_priv = shmfd;
956 		shmfd->shm_lp_alloc_policy = SHM_LARGEPAGE_ALLOC_DEFAULT;
957 	} else {
958 		obj->un_pager.swp.swp_priv = shmfd;
959 	}
960 
961 	VM_OBJECT_WLOCK(obj);
962 	vm_object_set_flag(obj, OBJ_POSIXSHM);
963 	VM_OBJECT_WUNLOCK(obj);
964 	shmfd->shm_object = obj;
965 	vfs_timestamp(&shmfd->shm_birthtime);
966 	shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
967 	    shmfd->shm_birthtime;
968 	shmfd->shm_ino = alloc_unr64(&shm_ino_unr);
969 	refcount_init(&shmfd->shm_refs, 1);
970 	mtx_init(&shmfd->shm_mtx, "shmrl", NULL, MTX_DEF);
971 	rangelock_init(&shmfd->shm_rl);
972 #ifdef MAC
973 	mac_posixshm_init(shmfd);
974 	mac_posixshm_create(ucred, shmfd);
975 #endif
976 
977 	return (shmfd);
978 }
979 
980 struct shmfd *
981 shm_hold(struct shmfd *shmfd)
982 {
983 
984 	refcount_acquire(&shmfd->shm_refs);
985 	return (shmfd);
986 }
987 
988 void
989 shm_drop(struct shmfd *shmfd)
990 {
991 	vm_object_t obj;
992 
993 	if (refcount_release(&shmfd->shm_refs)) {
994 #ifdef MAC
995 		mac_posixshm_destroy(shmfd);
996 #endif
997 		rangelock_destroy(&shmfd->shm_rl);
998 		mtx_destroy(&shmfd->shm_mtx);
999 		obj = shmfd->shm_object;
1000 		VM_OBJECT_WLOCK(obj);
1001 		if (shm_largepage(shmfd))
1002 			obj->un_pager.phys.phys_priv = NULL;
1003 		else
1004 			obj->un_pager.swp.swp_priv = NULL;
1005 		VM_OBJECT_WUNLOCK(obj);
1006 		vm_object_deallocate(obj);
1007 		free(shmfd, M_SHMFD);
1008 	}
1009 }
1010 
1011 /*
1012  * Determine if the credentials have sufficient permissions for a
1013  * specified combination of FREAD and FWRITE.
1014  */
1015 int
1016 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
1017 {
1018 	accmode_t accmode;
1019 	int error;
1020 
1021 	accmode = 0;
1022 	if (flags & FREAD)
1023 		accmode |= VREAD;
1024 	if (flags & FWRITE)
1025 		accmode |= VWRITE;
1026 	mtx_lock(&shm_timestamp_lock);
1027 	error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
1028 	    accmode, ucred);
1029 	mtx_unlock(&shm_timestamp_lock);
1030 	return (error);
1031 }
1032 
1033 static void
1034 shm_init(void *arg)
1035 {
1036 	char name[32];
1037 	int i;
1038 
1039 	mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
1040 	sx_init(&shm_dict_lock, "shm dictionary");
1041 	shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
1042 	new_unrhdr64(&shm_ino_unr, 1);
1043 	shm_dev_ino = devfs_alloc_cdp_inode();
1044 	KASSERT(shm_dev_ino > 0, ("shm dev inode not initialized"));
1045 	shmfd_pager_type = vm_pager_alloc_dyn_type(&shm_swap_pager_ops,
1046 	    OBJT_SWAP);
1047 	MPASS(shmfd_pager_type != -1);
1048 
1049 	for (i = 1; i < MAXPAGESIZES; i++) {
1050 		if (pagesizes[i] == 0)
1051 			break;
1052 #define	M	(1024 * 1024)
1053 #define	G	(1024 * M)
1054 		if (pagesizes[i] >= G)
1055 			snprintf(name, sizeof(name), "%luG", pagesizes[i] / G);
1056 		else if (pagesizes[i] >= M)
1057 			snprintf(name, sizeof(name), "%luM", pagesizes[i] / M);
1058 		else
1059 			snprintf(name, sizeof(name), "%lu", pagesizes[i]);
1060 #undef G
1061 #undef M
1062 		SYSCTL_ADD_ULONG(NULL, SYSCTL_STATIC_CHILDREN(_vm_largepages),
1063 		    OID_AUTO, name, CTLFLAG_RD, &count_largepages[i],
1064 		    "number of non-transient largepages allocated");
1065 	}
1066 }
1067 SYSINIT(shm_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_init, NULL);
1068 
1069 /*
1070  * Remove all shared memory objects that belong to a prison.
1071  */
1072 void
1073 shm_remove_prison(struct prison *pr)
1074 {
1075 	struct shm_mapping *shmm, *tshmm;
1076 	u_long i;
1077 
1078 	sx_xlock(&shm_dict_lock);
1079 	for (i = 0; i < shm_hash + 1; i++) {
1080 		LIST_FOREACH_SAFE(shmm, &shm_dictionary[i], sm_link, tshmm) {
1081 			if (shmm->sm_shmfd->shm_object->cred &&
1082 			    shmm->sm_shmfd->shm_object->cred->cr_prison == pr)
1083 				shm_doremove(shmm);
1084 		}
1085 	}
1086 	sx_xunlock(&shm_dict_lock);
1087 }
1088 
1089 /*
1090  * Dictionary management.  We maintain an in-kernel dictionary to map
1091  * paths to shmfd objects.  We use the FNV hash on the path to store
1092  * the mappings in a hash table.
1093  */
1094 static struct shmfd *
1095 shm_lookup(char *path, Fnv32_t fnv)
1096 {
1097 	struct shm_mapping *map;
1098 
1099 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
1100 		if (map->sm_fnv != fnv)
1101 			continue;
1102 		if (strcmp(map->sm_path, path) == 0)
1103 			return (map->sm_shmfd);
1104 	}
1105 
1106 	return (NULL);
1107 }
1108 
1109 static void
1110 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
1111 {
1112 	struct shm_mapping *map;
1113 
1114 	map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
1115 	map->sm_path = path;
1116 	map->sm_fnv = fnv;
1117 	map->sm_shmfd = shm_hold(shmfd);
1118 	shmfd->shm_path = path;
1119 	LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
1120 }
1121 
1122 static int
1123 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
1124 {
1125 	struct shm_mapping *map;
1126 	int error;
1127 
1128 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
1129 		if (map->sm_fnv != fnv)
1130 			continue;
1131 		if (strcmp(map->sm_path, path) == 0) {
1132 #ifdef MAC
1133 			error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
1134 			if (error)
1135 				return (error);
1136 #endif
1137 			error = shm_access(map->sm_shmfd, ucred,
1138 			    FREAD | FWRITE);
1139 			if (error)
1140 				return (error);
1141 			shm_doremove(map);
1142 			return (0);
1143 		}
1144 	}
1145 
1146 	return (ENOENT);
1147 }
1148 
1149 static void
1150 shm_doremove(struct shm_mapping *map)
1151 {
1152 	map->sm_shmfd->shm_path = NULL;
1153 	LIST_REMOVE(map, sm_link);
1154 	shm_drop(map->sm_shmfd);
1155 	free(map->sm_path, M_SHMFD);
1156 	free(map, M_SHMFD);
1157 }
1158 
1159 int
1160 kern_shm_open2(struct thread *td, const char *userpath, int flags, mode_t mode,
1161     int shmflags, struct filecaps *fcaps, const char *name __unused,
1162     struct shmfd *shmfd)
1163 {
1164 	struct pwddesc *pdp;
1165 	struct file *fp;
1166 	char *path;
1167 	void *rl_cookie;
1168 	Fnv32_t fnv;
1169 	mode_t cmode;
1170 	int error, fd, initial_seals;
1171 	bool largepage;
1172 
1173 	if ((shmflags & ~(SHM_ALLOW_SEALING | SHM_GROW_ON_WRITE |
1174 	    SHM_LARGEPAGE)) != 0)
1175 		return (EINVAL);
1176 
1177 	initial_seals = F_SEAL_SEAL;
1178 	if ((shmflags & SHM_ALLOW_SEALING) != 0)
1179 		initial_seals &= ~F_SEAL_SEAL;
1180 
1181 	AUDIT_ARG_FFLAGS(flags);
1182 	AUDIT_ARG_MODE(mode);
1183 
1184 	if ((flags & O_ACCMODE) != O_RDONLY && (flags & O_ACCMODE) != O_RDWR)
1185 		return (EINVAL);
1186 
1187 	if ((flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_CLOEXEC |
1188 	    O_CLOFORK)) != 0)
1189 		return (EINVAL);
1190 
1191 	largepage = (shmflags & SHM_LARGEPAGE) != 0;
1192 	if (largepage && !PMAP_HAS_LARGEPAGES)
1193 		return (ENOTTY);
1194 
1195 	/*
1196 	 * Currently only F_SEAL_SEAL may be set when creating or opening shmfd.
1197 	 * If the decision is made later to allow additional seals, care must be
1198 	 * taken below to ensure that the seals are properly set if the shmfd
1199 	 * already existed -- this currently assumes that only F_SEAL_SEAL can
1200 	 * be set and doesn't take further precautions to ensure the validity of
1201 	 * the seals being added with respect to current mappings.
1202 	 */
1203 	if ((initial_seals & ~F_SEAL_SEAL) != 0)
1204 		return (EINVAL);
1205 
1206 	if (userpath != SHM_ANON) {
1207 		error = shm_copyin_path(td, userpath, &path);
1208 		if (error != 0)
1209 			return (error);
1210 
1211 #ifdef CAPABILITY_MODE
1212 		/*
1213 		 * shm_open(2) is only allowed for anonymous objects.
1214 		 */
1215 		if (CAP_TRACING(td))
1216 			ktrcapfail(CAPFAIL_NAMEI, path);
1217 		if (IN_CAPABILITY_MODE(td)) {
1218 			error = ECAPMODE;
1219 			goto outnofp;
1220 		}
1221 #endif
1222 
1223 		AUDIT_ARG_UPATH1_CANON(path);
1224 	} else {
1225 		path = NULL;
1226 	}
1227 
1228 	pdp = td->td_proc->p_pd;
1229 	cmode = (mode & ~pdp->pd_cmask) & ACCESSPERMS;
1230 
1231 	/*
1232 	 * shm_open(2) created shm should always have O_CLOEXEC set, as mandated
1233 	 * by POSIX.  We allow it to be unset here so that an in-kernel
1234 	 * interface may be written as a thin layer around shm, optionally not
1235 	 * setting CLOEXEC.  For shm_open(2), O_CLOEXEC is set unconditionally
1236 	 * in sys_shm_open() to keep this implementation compliant.
1237 	 */
1238 	error = falloc_caps(td, &fp, &fd, flags & O_CLOEXEC, fcaps);
1239 	if (error != 0)
1240 		goto outnofp;
1241 
1242 	/*
1243 	 * A SHM_ANON path pointer creates an anonymous object.  We allow other
1244 	 * parts of the kernel to pre-populate a shmfd and then materialize an
1245 	 * fd for it here as a means to pass data back up to userland.  This
1246 	 * doesn't really make sense for named shm objects, but it makes plenty
1247 	 * of sense for anonymous objects.
1248 	 */
1249 	if (userpath == SHM_ANON) {
1250 		if (shmfd != NULL) {
1251 			shm_hold(shmfd);
1252 		} else {
1253 			/*
1254 			 * A read-only anonymous object is pointless, unless it
1255 			 * was pre-populated by the kernel with the expectation
1256 			 * that a shmfd would later be created for userland to
1257 			 * access it through.
1258 			 */
1259 			if ((flags & O_ACCMODE) == O_RDONLY) {
1260 				error = EINVAL;
1261 				goto out;
1262 			}
1263 			shmfd = shm_alloc(td->td_ucred, cmode, largepage);
1264 			if (shmfd == NULL) {
1265 				error = ENOMEM;
1266 				goto out;
1267 			}
1268 
1269 			shmfd->shm_seals = initial_seals;
1270 			shmfd->shm_flags = shmflags;
1271 		}
1272 	} else {
1273 		fnv = fnv_32_str(path, FNV1_32_INIT);
1274 		sx_xlock(&shm_dict_lock);
1275 
1276 		MPASS(shmfd == NULL);
1277 		shmfd = shm_lookup(path, fnv);
1278 		if (shmfd == NULL) {
1279 			/* Object does not yet exist, create it if requested. */
1280 			if (flags & O_CREAT) {
1281 #ifdef MAC
1282 				error = mac_posixshm_check_create(td->td_ucred,
1283 				    path);
1284 				if (error == 0) {
1285 #endif
1286 					shmfd = shm_alloc(td->td_ucred, cmode,
1287 					    largepage);
1288 					if (shmfd == NULL) {
1289 						error = ENOMEM;
1290 					} else {
1291 						shmfd->shm_seals =
1292 						    initial_seals;
1293 						shmfd->shm_flags = shmflags;
1294 						shm_insert(path, fnv, shmfd);
1295 						path = NULL;
1296 					}
1297 #ifdef MAC
1298 				}
1299 #endif
1300 			} else {
1301 				error = ENOENT;
1302 			}
1303 		} else {
1304 			/*
1305 			 * Object already exists, obtain a new reference if
1306 			 * requested and permitted.
1307 			 */
1308 			rl_cookie = shm_rangelock_wlock(shmfd, 0, OFF_MAX);
1309 
1310 			/*
1311 			 * kern_shm_open() likely shouldn't ever error out on
1312 			 * trying to set a seal that already exists, unlike
1313 			 * F_ADD_SEALS.  This would break terribly as
1314 			 * shm_open(2) actually sets F_SEAL_SEAL to maintain
1315 			 * historical behavior where the underlying file could
1316 			 * not be sealed.
1317 			 */
1318 			initial_seals &= ~shmfd->shm_seals;
1319 
1320 			/*
1321 			 * initial_seals can't set additional seals if we've
1322 			 * already been set F_SEAL_SEAL.  If F_SEAL_SEAL is set,
1323 			 * then we've already removed that one from
1324 			 * initial_seals.  This is currently redundant as we
1325 			 * only allow setting F_SEAL_SEAL at creation time, but
1326 			 * it's cheap to check and decreases the effort required
1327 			 * to allow additional seals.
1328 			 */
1329 			if ((shmfd->shm_seals & F_SEAL_SEAL) != 0 &&
1330 			    initial_seals != 0)
1331 				error = EPERM;
1332 			else if ((flags & (O_CREAT | O_EXCL)) ==
1333 			    (O_CREAT | O_EXCL))
1334 				error = EEXIST;
1335 			else if (shmflags != 0 && shmflags != shmfd->shm_flags)
1336 				error = EINVAL;
1337 			else {
1338 #ifdef MAC
1339 				error = mac_posixshm_check_open(td->td_ucred,
1340 				    shmfd, FFLAGS(flags & O_ACCMODE));
1341 				if (error == 0)
1342 #endif
1343 				error = shm_access(shmfd, td->td_ucred,
1344 				    FFLAGS(flags & O_ACCMODE));
1345 			}
1346 
1347 			/*
1348 			 * Truncate the file back to zero length if
1349 			 * O_TRUNC was specified and the object was
1350 			 * opened with read/write.
1351 			 */
1352 			if (error == 0 &&
1353 			    (flags & (O_ACCMODE | O_TRUNC)) ==
1354 			    (O_RDWR | O_TRUNC)) {
1355 #ifdef MAC
1356 				error = mac_posixshm_check_truncate(
1357 				    td->td_ucred, fp->f_cred, shmfd);
1358 				if (error == 0)
1359 #endif
1360 					error = shm_dotruncate_cookie(shmfd, 0,
1361 					    rl_cookie);
1362 			}
1363 			if (error == 0) {
1364 				/*
1365 				 * Currently we only allow F_SEAL_SEAL to be
1366 				 * set initially.  As noted above, this would
1367 				 * need to be reworked should that change.
1368 				 */
1369 				shmfd->shm_seals |= initial_seals;
1370 				shm_hold(shmfd);
1371 			}
1372 			shm_rangelock_unlock(shmfd, rl_cookie);
1373 		}
1374 		sx_xunlock(&shm_dict_lock);
1375 
1376 		if (error != 0)
1377 			goto out;
1378 	}
1379 
1380 	finit(fp, FFLAGS(flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
1381 
1382 	td->td_retval[0] = fd;
1383 	fdrop(fp, td);
1384 	free(path, M_SHMFD);
1385 
1386 	return (0);
1387 
1388 out:
1389 	fdclose(td, fp, fd);
1390 	fdrop(fp, td);
1391 outnofp:
1392 	free(path, M_SHMFD);
1393 
1394 	return (error);
1395 }
1396 
1397 /* System calls. */
1398 #ifdef COMPAT_FREEBSD12
1399 int
1400 freebsd12_shm_open(struct thread *td, struct freebsd12_shm_open_args *uap)
1401 {
1402 
1403 	return (kern_shm_open(td, uap->path, uap->flags | O_CLOEXEC,
1404 	    uap->mode, NULL));
1405 }
1406 #endif
1407 
1408 int
1409 sys_shm_unlink(struct thread *td, struct shm_unlink_args *uap)
1410 {
1411 	char *path;
1412 	Fnv32_t fnv;
1413 	int error;
1414 
1415 	error = shm_copyin_path(td, uap->path, &path);
1416 	if (error != 0)
1417 		return (error);
1418 
1419 	AUDIT_ARG_UPATH1_CANON(path);
1420 	fnv = fnv_32_str(path, FNV1_32_INIT);
1421 	sx_xlock(&shm_dict_lock);
1422 	error = shm_remove(path, fnv, td->td_ucred);
1423 	sx_xunlock(&shm_dict_lock);
1424 	free(path, M_SHMFD);
1425 
1426 	return (error);
1427 }
1428 
1429 int
1430 sys_shm_rename(struct thread *td, struct shm_rename_args *uap)
1431 {
1432 	char *path_from = NULL, *path_to = NULL;
1433 	Fnv32_t fnv_from, fnv_to;
1434 	struct shmfd *fd_from;
1435 	struct shmfd *fd_to;
1436 	int error;
1437 	int flags;
1438 
1439 	flags = uap->flags;
1440 	AUDIT_ARG_FFLAGS(flags);
1441 
1442 	/*
1443 	 * Make sure the user passed only valid flags.
1444 	 * If you add a new flag, please add a new term here.
1445 	 */
1446 	if ((flags & ~(
1447 	    SHM_RENAME_NOREPLACE |
1448 	    SHM_RENAME_EXCHANGE
1449 	    )) != 0) {
1450 		error = EINVAL;
1451 		goto out;
1452 	}
1453 
1454 	/*
1455 	 * EXCHANGE and NOREPLACE don't quite make sense together. Let's
1456 	 * force the user to choose one or the other.
1457 	 */
1458 	if ((flags & SHM_RENAME_NOREPLACE) != 0 &&
1459 	    (flags & SHM_RENAME_EXCHANGE) != 0) {
1460 		error = EINVAL;
1461 		goto out;
1462 	}
1463 
1464 	/* Renaming to or from anonymous makes no sense */
1465 	if (uap->path_from == SHM_ANON || uap->path_to == SHM_ANON) {
1466 		error = EINVAL;
1467 		goto out;
1468 	}
1469 
1470 	error = shm_copyin_path(td, uap->path_from, &path_from);
1471 	if (error != 0)
1472 		goto out;
1473 
1474 	error = shm_copyin_path(td, uap->path_to, &path_to);
1475 	if (error != 0)
1476 		goto out;
1477 
1478 	AUDIT_ARG_UPATH1_CANON(path_from);
1479 	AUDIT_ARG_UPATH2_CANON(path_to);
1480 
1481 	/* Rename with from/to equal is a no-op */
1482 	if (strcmp(path_from, path_to) == 0)
1483 		goto out;
1484 
1485 	fnv_from = fnv_32_str(path_from, FNV1_32_INIT);
1486 	fnv_to = fnv_32_str(path_to, FNV1_32_INIT);
1487 
1488 	sx_xlock(&shm_dict_lock);
1489 
1490 	fd_from = shm_lookup(path_from, fnv_from);
1491 	if (fd_from == NULL) {
1492 		error = ENOENT;
1493 		goto out_locked;
1494 	}
1495 
1496 	fd_to = shm_lookup(path_to, fnv_to);
1497 	if ((flags & SHM_RENAME_NOREPLACE) != 0 && fd_to != NULL) {
1498 		error = EEXIST;
1499 		goto out_locked;
1500 	}
1501 
1502 	/*
1503 	 * Unconditionally prevents shm_remove from invalidating the 'from'
1504 	 * shm's state.
1505 	 */
1506 	shm_hold(fd_from);
1507 	error = shm_remove(path_from, fnv_from, td->td_ucred);
1508 
1509 	/*
1510 	 * One of my assumptions failed if ENOENT (e.g. locking didn't
1511 	 * protect us)
1512 	 */
1513 	KASSERT(error != ENOENT, ("Our shm disappeared during shm_rename: %s",
1514 	    path_from));
1515 	if (error != 0) {
1516 		shm_drop(fd_from);
1517 		goto out_locked;
1518 	}
1519 
1520 	/*
1521 	 * If we are exchanging, we need to ensure the shm_remove below
1522 	 * doesn't invalidate the dest shm's state.
1523 	 */
1524 	if ((flags & SHM_RENAME_EXCHANGE) != 0 && fd_to != NULL)
1525 		shm_hold(fd_to);
1526 
1527 	/*
1528 	 * NOTE: if path_to is not already in the hash, c'est la vie;
1529 	 * it simply means we have nothing already at path_to to unlink.
1530 	 * That is the ENOENT case.
1531 	 *
1532 	 * If we somehow don't have access to unlink this guy, but
1533 	 * did for the shm at path_from, then relink the shm to path_from
1534 	 * and abort with EACCES.
1535 	 *
1536 	 * All other errors: that is weird; let's relink and abort the
1537 	 * operation.
1538 	 */
1539 	error = shm_remove(path_to, fnv_to, td->td_ucred);
1540 	if (error != 0 && error != ENOENT) {
1541 		shm_insert(path_from, fnv_from, fd_from);
1542 		shm_drop(fd_from);
1543 		/* Don't free path_from now, since the hash references it */
1544 		path_from = NULL;
1545 		goto out_locked;
1546 	}
1547 
1548 	error = 0;
1549 
1550 	shm_insert(path_to, fnv_to, fd_from);
1551 
1552 	/* Don't free path_to now, since the hash references it */
1553 	path_to = NULL;
1554 
1555 	/* We kept a ref when we removed, and incremented again in insert */
1556 	shm_drop(fd_from);
1557 	KASSERT(fd_from->shm_refs > 0, ("Expected >0 refs; got: %d\n",
1558 	    fd_from->shm_refs));
1559 
1560 	if ((flags & SHM_RENAME_EXCHANGE) != 0 && fd_to != NULL) {
1561 		shm_insert(path_from, fnv_from, fd_to);
1562 		path_from = NULL;
1563 		shm_drop(fd_to);
1564 		KASSERT(fd_to->shm_refs > 0, ("Expected >0 refs; got: %d\n",
1565 		    fd_to->shm_refs));
1566 	}
1567 
1568 out_locked:
1569 	sx_xunlock(&shm_dict_lock);
1570 
1571 out:
1572 	free(path_from, M_SHMFD);
1573 	free(path_to, M_SHMFD);
1574 	return (error);
1575 }
1576 
1577 static int
1578 shm_mmap_large(struct shmfd *shmfd, vm_map_t map, vm_offset_t *addr,
1579     vm_size_t size, vm_prot_t prot, vm_prot_t max_prot, int flags,
1580     vm_ooffset_t foff, struct thread *td, void *rl_cookie)
1581 {
1582 	struct vmspace *vms;
1583 	vm_map_entry_t next_entry, prev_entry;
1584 	vm_offset_t align, mask, maxaddr;
1585 	int docow, error, rv, try;
1586 	bool curmap;
1587 
1588 	rangelock_cookie_assert(rl_cookie, RCA_LOCKED);
1589 
1590 	if (shmfd->shm_lp_psind == 0)
1591 		return (EINVAL);
1592 
1593 	/* MAP_PRIVATE is disabled */
1594 	if ((flags & ~(MAP_SHARED | MAP_FIXED | MAP_EXCL |
1595 	    MAP_NOCORE | MAP_32BIT | MAP_ALIGNMENT_MASK)) != 0)
1596 		return (EINVAL);
1597 
1598 	vms = td->td_proc->p_vmspace;
1599 	curmap = map == &vms->vm_map;
1600 	if (curmap) {
1601 		error = kern_mmap_racct_check(td, map, size);
1602 		if (error != 0)
1603 			return (error);
1604 	}
1605 
1606 	docow = shmfd->shm_lp_psind << MAP_SPLIT_BOUNDARY_SHIFT;
1607 	docow |= MAP_INHERIT_SHARE;
1608 	if ((flags & MAP_NOCORE) != 0)
1609 		docow |= MAP_DISABLE_COREDUMP;
1610 
1611 	mask = pagesizes[shmfd->shm_lp_psind] - 1;
1612 	if ((foff & mask) != 0)
1613 		return (EINVAL);
1614 	maxaddr = vm_map_max(map);
1615 	if ((flags & MAP_32BIT) != 0 && maxaddr > MAP_32BIT_MAX_ADDR)
1616 		maxaddr = MAP_32BIT_MAX_ADDR;
1617 	if (size == 0 || (size & mask) != 0 ||
1618 	    (*addr != 0 && ((*addr & mask) != 0 ||
1619 	    *addr + size < *addr || *addr + size > maxaddr)))
1620 		return (EINVAL);
1621 
1622 	align = flags & MAP_ALIGNMENT_MASK;
1623 	if (align == 0) {
1624 		align = pagesizes[shmfd->shm_lp_psind];
1625 	} else if (align == MAP_ALIGNED_SUPER) {
1626 		/*
1627 		 * MAP_ALIGNED_SUPER is only supported on superpage sizes,
1628 		 * i.e., [1, VM_NRESERVLEVEL].  shmfd->shm_lp_psind < 1 is
1629 		 * handled above.
1630 		 */
1631 		if (
1632 #if VM_NRESERVLEVEL > 0
1633 		    shmfd->shm_lp_psind > VM_NRESERVLEVEL
1634 #else
1635 		    shmfd->shm_lp_psind > 1
1636 #endif
1637 		    )
1638 			return (EINVAL);
1639 		align = pagesizes[shmfd->shm_lp_psind];
1640 	} else {
1641 		align >>= MAP_ALIGNMENT_SHIFT;
1642 		align = 1ULL << align;
1643 		/* Also handles overflow. */
1644 		if (align < pagesizes[shmfd->shm_lp_psind])
1645 			return (EINVAL);
1646 	}
1647 
1648 	vm_map_lock(map);
1649 	if ((flags & MAP_FIXED) == 0) {
1650 		try = 1;
1651 		if (curmap && (*addr == 0 ||
1652 		    (*addr >= round_page((vm_offset_t)vms->vm_taddr) &&
1653 		    *addr < round_page((vm_offset_t)vms->vm_daddr +
1654 		    lim_max(td, RLIMIT_DATA))))) {
1655 			*addr = roundup2((vm_offset_t)vms->vm_daddr +
1656 			    lim_max(td, RLIMIT_DATA),
1657 			    pagesizes[shmfd->shm_lp_psind]);
1658 		}
1659 again:
1660 		rv = vm_map_find_aligned(map, addr, size, maxaddr, align);
1661 		if (rv != KERN_SUCCESS) {
1662 			if (try == 1) {
1663 				try = 2;
1664 				*addr = vm_map_min(map);
1665 				if ((*addr & mask) != 0)
1666 					*addr = (*addr + mask) & mask;
1667 				goto again;
1668 			}
1669 			goto fail1;
1670 		}
1671 	} else if ((flags & MAP_EXCL) == 0) {
1672 		rv = vm_map_delete(map, *addr, *addr + size);
1673 		if (rv != KERN_SUCCESS)
1674 			goto fail1;
1675 	} else {
1676 		error = ENOSPC;
1677 		if (vm_map_lookup_entry(map, *addr, &prev_entry))
1678 			goto fail;
1679 		next_entry = vm_map_entry_succ(prev_entry);
1680 		if (next_entry->start < *addr + size)
1681 			goto fail;
1682 	}
1683 
1684 	rv = vm_map_insert(map, shmfd->shm_object, foff, *addr, *addr + size,
1685 	    prot, max_prot, docow);
1686 fail1:
1687 	error = vm_mmap_to_errno(rv);
1688 fail:
1689 	vm_map_unlock(map);
1690 	return (error);
1691 }
1692 
1693 static int
1694 shm_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t objsize,
1695     vm_prot_t prot, vm_prot_t max_maxprot, int flags,
1696     vm_ooffset_t foff, struct thread *td)
1697 {
1698 	struct shmfd *shmfd;
1699 	vm_prot_t maxprot;
1700 	int error;
1701 	bool writecnt;
1702 	void *rl_cookie;
1703 
1704 	shmfd = fp->f_data;
1705 	maxprot = VM_PROT_NONE;
1706 
1707 	rl_cookie = shm_rangelock_rlock(shmfd, 0, objsize);
1708 	/* FREAD should always be set. */
1709 	if ((fp->f_flag & FREAD) != 0)
1710 		maxprot |= VM_PROT_EXECUTE | VM_PROT_READ;
1711 
1712 	/*
1713 	 * If FWRITE's set, we can allow VM_PROT_WRITE unless it's a shared
1714 	 * mapping with a write seal applied.  Private mappings are always
1715 	 * writeable.
1716 	 */
1717 	if ((flags & MAP_SHARED) == 0) {
1718 		if ((max_maxprot & VM_PROT_WRITE) != 0)
1719 			maxprot |= VM_PROT_WRITE;
1720 		writecnt = false;
1721 	} else {
1722 		if ((fp->f_flag & FWRITE) != 0 &&
1723 		    (shmfd->shm_seals & F_SEAL_WRITE) == 0)
1724 			maxprot |= VM_PROT_WRITE;
1725 
1726 		/*
1727 		 * Any mappings from a writable descriptor may be upgraded to
1728 		 * VM_PROT_WRITE with mprotect(2), unless a write-seal was
1729 		 * applied between the open and subsequent mmap(2).  We want to
1730 		 * reject application of a write seal as long as any such
1731 		 * mapping exists so that the seal cannot be trivially bypassed.
1732 		 */
1733 		writecnt = (maxprot & VM_PROT_WRITE) != 0;
1734 		if (!writecnt && (prot & VM_PROT_WRITE) != 0) {
1735 			error = EACCES;
1736 			goto out;
1737 		}
1738 	}
1739 	maxprot &= max_maxprot;
1740 
1741 	/* See comment in vn_mmap(). */
1742 	if (
1743 #ifdef _LP64
1744 	    objsize > OFF_MAX ||
1745 #endif
1746 	    foff > OFF_MAX - objsize) {
1747 		error = EINVAL;
1748 		goto out;
1749 	}
1750 
1751 #ifdef MAC
1752 	error = mac_posixshm_check_mmap(td->td_ucred, shmfd, prot, flags);
1753 	if (error != 0)
1754 		goto out;
1755 #endif
1756 
1757 	mtx_lock(&shm_timestamp_lock);
1758 	vfs_timestamp(&shmfd->shm_atime);
1759 	mtx_unlock(&shm_timestamp_lock);
1760 	vm_object_reference(shmfd->shm_object);
1761 
1762 	if (shm_largepage(shmfd)) {
1763 		writecnt = false;
1764 		error = shm_mmap_large(shmfd, map, addr, objsize, prot,
1765 		    maxprot, flags, foff, td, rl_cookie);
1766 	} else {
1767 		if (writecnt) {
1768 			vm_pager_update_writecount(shmfd->shm_object, 0,
1769 			    objsize);
1770 		}
1771 		error = vm_mmap_object(map, addr, objsize, prot, maxprot, flags,
1772 		    shmfd->shm_object, foff, writecnt, td);
1773 	}
1774 	if (error != 0) {
1775 		if (writecnt)
1776 			vm_pager_release_writecount(shmfd->shm_object, 0,
1777 			    objsize);
1778 		vm_object_deallocate(shmfd->shm_object);
1779 	}
1780 out:
1781 	shm_rangelock_unlock(shmfd, rl_cookie);
1782 	return (error);
1783 }
1784 
1785 static int
1786 shm_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
1787     struct thread *td)
1788 {
1789 	struct shmfd *shmfd;
1790 	int error;
1791 
1792 	error = 0;
1793 	shmfd = fp->f_data;
1794 	mtx_lock(&shm_timestamp_lock);
1795 	/*
1796 	 * SUSv4 says that x bits of permission need not be affected.
1797 	 * Be consistent with our shm_open there.
1798 	 */
1799 #ifdef MAC
1800 	error = mac_posixshm_check_setmode(active_cred, shmfd, mode);
1801 	if (error != 0)
1802 		goto out;
1803 #endif
1804 	error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
1805 	    VADMIN, active_cred);
1806 	if (error != 0)
1807 		goto out;
1808 	shmfd->shm_mode = mode & ACCESSPERMS;
1809 out:
1810 	mtx_unlock(&shm_timestamp_lock);
1811 	return (error);
1812 }
1813 
1814 static int
1815 shm_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
1816     struct thread *td)
1817 {
1818 	struct shmfd *shmfd;
1819 	int error;
1820 
1821 	error = 0;
1822 	shmfd = fp->f_data;
1823 	mtx_lock(&shm_timestamp_lock);
1824 #ifdef MAC
1825 	error = mac_posixshm_check_setowner(active_cred, shmfd, uid, gid);
1826 	if (error != 0)
1827 		goto out;
1828 #endif
1829 	if (uid == (uid_t)-1)
1830 		uid = shmfd->shm_uid;
1831 	if (gid == (gid_t)-1)
1832                  gid = shmfd->shm_gid;
1833 	if (((uid != shmfd->shm_uid && uid != active_cred->cr_uid) ||
1834 	    (gid != shmfd->shm_gid && !groupmember(gid, active_cred))) &&
1835 	    (error = priv_check_cred(active_cred, PRIV_VFS_CHOWN)))
1836 		goto out;
1837 	shmfd->shm_uid = uid;
1838 	shmfd->shm_gid = gid;
1839 out:
1840 	mtx_unlock(&shm_timestamp_lock);
1841 	return (error);
1842 }
1843 
1844 /*
1845  * Helper routines to allow the backing object of a shared memory file
1846  * descriptor to be mapped in the kernel.
1847  */
1848 int
1849 shm_map(struct file *fp, size_t size, off_t offset, void **memp)
1850 {
1851 	struct shmfd *shmfd;
1852 	vm_offset_t kva, ofs;
1853 	vm_object_t obj;
1854 	int rv;
1855 
1856 	if (fp->f_type != DTYPE_SHM)
1857 		return (EINVAL);
1858 	shmfd = fp->f_data;
1859 	obj = shmfd->shm_object;
1860 	VM_OBJECT_WLOCK(obj);
1861 	/*
1862 	 * XXXRW: This validation is probably insufficient, and subject to
1863 	 * sign errors.  It should be fixed.
1864 	 */
1865 	if (offset >= shmfd->shm_size ||
1866 	    offset + size > round_page(shmfd->shm_size)) {
1867 		VM_OBJECT_WUNLOCK(obj);
1868 		return (EINVAL);
1869 	}
1870 
1871 	shmfd->shm_kmappings++;
1872 	vm_object_reference_locked(obj);
1873 	VM_OBJECT_WUNLOCK(obj);
1874 
1875 	/* Map the object into the kernel_map and wire it. */
1876 	kva = vm_map_min(kernel_map);
1877 	ofs = offset & PAGE_MASK;
1878 	offset = trunc_page(offset);
1879 	size = round_page(size + ofs);
1880 	rv = vm_map_find(kernel_map, obj, offset, &kva, size, 0,
1881 	    VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
1882 	    VM_PROT_READ | VM_PROT_WRITE, 0);
1883 	if (rv == KERN_SUCCESS) {
1884 		rv = vm_map_wire(kernel_map, kva, kva + size,
1885 		    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
1886 		if (rv == KERN_SUCCESS) {
1887 			*memp = (void *)(kva + ofs);
1888 			return (0);
1889 		}
1890 		vm_map_remove(kernel_map, kva, kva + size);
1891 	} else
1892 		vm_object_deallocate(obj);
1893 
1894 	/* On failure, drop our mapping reference. */
1895 	VM_OBJECT_WLOCK(obj);
1896 	shmfd->shm_kmappings--;
1897 	VM_OBJECT_WUNLOCK(obj);
1898 
1899 	return (vm_mmap_to_errno(rv));
1900 }
1901 
1902 /*
1903  * We require the caller to unmap the entire entry.  This allows us to
1904  * safely decrement shm_kmappings when a mapping is removed.
1905  */
1906 int
1907 shm_unmap(struct file *fp, void *mem, size_t size)
1908 {
1909 	struct shmfd *shmfd;
1910 	vm_map_entry_t entry;
1911 	vm_offset_t kva, ofs;
1912 	vm_object_t obj;
1913 	vm_pindex_t pindex;
1914 	vm_prot_t prot;
1915 	boolean_t wired;
1916 	vm_map_t map;
1917 	int rv;
1918 
1919 	if (fp->f_type != DTYPE_SHM)
1920 		return (EINVAL);
1921 	shmfd = fp->f_data;
1922 	kva = (vm_offset_t)mem;
1923 	ofs = kva & PAGE_MASK;
1924 	kva = trunc_page(kva);
1925 	size = round_page(size + ofs);
1926 	map = kernel_map;
1927 	rv = vm_map_lookup(&map, kva, VM_PROT_READ | VM_PROT_WRITE, &entry,
1928 	    &obj, &pindex, &prot, &wired);
1929 	if (rv != KERN_SUCCESS)
1930 		return (EINVAL);
1931 	if (entry->start != kva || entry->end != kva + size) {
1932 		vm_map_lookup_done(map, entry);
1933 		return (EINVAL);
1934 	}
1935 	vm_map_lookup_done(map, entry);
1936 	if (obj != shmfd->shm_object)
1937 		return (EINVAL);
1938 	vm_map_remove(map, kva, kva + size);
1939 	VM_OBJECT_WLOCK(obj);
1940 	KASSERT(shmfd->shm_kmappings > 0, ("shm_unmap: object not mapped"));
1941 	shmfd->shm_kmappings--;
1942 	VM_OBJECT_WUNLOCK(obj);
1943 	return (0);
1944 }
1945 
1946 static int
1947 shm_fill_kinfo_locked(struct shmfd *shmfd, struct kinfo_file *kif, bool list)
1948 {
1949 	const char *path, *pr_path;
1950 	size_t pr_pathlen;
1951 	bool visible;
1952 
1953 	sx_assert(&shm_dict_lock, SA_LOCKED);
1954 	kif->kf_type = KF_TYPE_SHM;
1955 	kif->kf_un.kf_file.kf_file_mode = S_IFREG | shmfd->shm_mode;
1956 	kif->kf_un.kf_file.kf_file_size = shmfd->shm_size;
1957 	if (shmfd->shm_path != NULL) {
1958 		path = shmfd->shm_path;
1959 		pr_path = curthread->td_ucred->cr_prison->pr_path;
1960 		if (strcmp(pr_path, "/") != 0) {
1961 			/* Return the jail-rooted pathname. */
1962 			pr_pathlen = strlen(pr_path);
1963 			visible = strncmp(path, pr_path, pr_pathlen) == 0 &&
1964 			    path[pr_pathlen] == '/';
1965 			if (list && !visible)
1966 				return (EPERM);
1967 			if (visible)
1968 				path += pr_pathlen;
1969 		}
1970 		strlcpy(kif->kf_path, path, sizeof(kif->kf_path));
1971 	}
1972 	return (0);
1973 }
1974 
1975 static int
1976 shm_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1977     struct filedesc *fdp __unused)
1978 {
1979 	int res;
1980 
1981 	sx_slock(&shm_dict_lock);
1982 	res = shm_fill_kinfo_locked(fp->f_data, kif, false);
1983 	sx_sunlock(&shm_dict_lock);
1984 	return (res);
1985 }
1986 
1987 static int
1988 shm_add_seals(struct file *fp, int seals)
1989 {
1990 	struct shmfd *shmfd;
1991 	void *rl_cookie;
1992 	vm_ooffset_t writemappings;
1993 	int error, nseals;
1994 
1995 	error = 0;
1996 	shmfd = fp->f_data;
1997 	rl_cookie = shm_rangelock_wlock(shmfd, 0, OFF_MAX);
1998 
1999 	/* Even already-set seals should result in EPERM. */
2000 	if ((shmfd->shm_seals & F_SEAL_SEAL) != 0) {
2001 		error = EPERM;
2002 		goto out;
2003 	}
2004 	nseals = seals & ~shmfd->shm_seals;
2005 	if ((nseals & F_SEAL_WRITE) != 0) {
2006 		if (shm_largepage(shmfd)) {
2007 			error = ENOTSUP;
2008 			goto out;
2009 		}
2010 
2011 		/*
2012 		 * The rangelock above prevents writable mappings from being
2013 		 * added after we've started applying seals.  The RLOCK here
2014 		 * is to avoid torn reads on ILP32 arches as unmapping/reducing
2015 		 * writemappings will be done without a rangelock.
2016 		 */
2017 		VM_OBJECT_RLOCK(shmfd->shm_object);
2018 		writemappings = shmfd->shm_object->un_pager.swp.writemappings;
2019 		VM_OBJECT_RUNLOCK(shmfd->shm_object);
2020 		/* kmappings are also writable */
2021 		if (writemappings > 0) {
2022 			error = EBUSY;
2023 			goto out;
2024 		}
2025 	}
2026 	shmfd->shm_seals |= nseals;
2027 out:
2028 	shm_rangelock_unlock(shmfd, rl_cookie);
2029 	return (error);
2030 }
2031 
2032 static int
2033 shm_get_seals(struct file *fp, int *seals)
2034 {
2035 	struct shmfd *shmfd;
2036 
2037 	shmfd = fp->f_data;
2038 	*seals = shmfd->shm_seals;
2039 	return (0);
2040 }
2041 
2042 static int
2043 shm_deallocate(struct shmfd *shmfd, off_t *offset, off_t *length, int flags)
2044 {
2045 	vm_object_t object;
2046 	vm_pindex_t pistart, pi, piend;
2047 	vm_ooffset_t off, len;
2048 	int startofs, endofs, end;
2049 	int error;
2050 
2051 	off = *offset;
2052 	len = *length;
2053 	KASSERT(off + len <= (vm_ooffset_t)OFF_MAX, ("off + len overflows"));
2054 	if (off + len > shmfd->shm_size)
2055 		len = shmfd->shm_size - off;
2056 	object = shmfd->shm_object;
2057 	startofs = off & PAGE_MASK;
2058 	endofs = (off + len) & PAGE_MASK;
2059 	pistart = OFF_TO_IDX(off);
2060 	piend = OFF_TO_IDX(off + len);
2061 	pi = OFF_TO_IDX(off + PAGE_MASK);
2062 	error = 0;
2063 
2064 	/* Handle the case when offset is on or beyond shm size. */
2065 	if ((off_t)len <= 0) {
2066 		*length = 0;
2067 		return (0);
2068 	}
2069 
2070 	VM_OBJECT_WLOCK(object);
2071 
2072 	if (startofs != 0) {
2073 		end = pistart != piend ? PAGE_SIZE : endofs;
2074 		error = shm_partial_page_invalidate(object, pistart, startofs,
2075 		    end);
2076 		if (error)
2077 			goto out;
2078 		off += end - startofs;
2079 		len -= end - startofs;
2080 	}
2081 
2082 	if (pi < piend) {
2083 		vm_object_page_remove(object, pi, piend, 0);
2084 		off += IDX_TO_OFF(piend - pi);
2085 		len -= IDX_TO_OFF(piend - pi);
2086 	}
2087 
2088 	if (endofs != 0 && pistart != piend) {
2089 		error = shm_partial_page_invalidate(object, piend, 0, endofs);
2090 		if (error)
2091 			goto out;
2092 		off += endofs;
2093 		len -= endofs;
2094 	}
2095 
2096 out:
2097 	VM_OBJECT_WUNLOCK(object);
2098 	*offset = off;
2099 	*length = len;
2100 	return (error);
2101 }
2102 
2103 static int
2104 shm_fspacectl(struct file *fp, int cmd, off_t *offset, off_t *length, int flags,
2105     struct ucred *active_cred, struct thread *td)
2106 {
2107 	void *rl_cookie;
2108 	struct shmfd *shmfd;
2109 	off_t off, len;
2110 	int error;
2111 
2112 	KASSERT(cmd == SPACECTL_DEALLOC, ("shm_fspacectl: Invalid cmd"));
2113 	KASSERT((flags & ~SPACECTL_F_SUPPORTED) == 0,
2114 	    ("shm_fspacectl: non-zero flags"));
2115 	KASSERT(*offset >= 0 && *length > 0 && *length <= OFF_MAX - *offset,
2116 	    ("shm_fspacectl: offset/length overflow or underflow"));
2117 
2118 	shmfd = fp->f_data;
2119 	off = *offset;
2120 	len = *length;
2121 
2122 	if (shm_largepage(shmfd))
2123 		return (ENOTSUP);
2124 
2125 	rl_cookie = shm_rangelock_wlock(shmfd, off, off + len);
2126 	switch (cmd) {
2127 	case SPACECTL_DEALLOC:
2128 		if ((shmfd->shm_seals & F_SEAL_WRITE) != 0) {
2129 			error = EPERM;
2130 			break;
2131 		}
2132 		error = shm_deallocate(shmfd, &off, &len, flags);
2133 		*offset = off;
2134 		*length = len;
2135 		break;
2136 	default:
2137 		__assert_unreachable();
2138 	}
2139 	shm_rangelock_unlock(shmfd, rl_cookie);
2140 	return (error);
2141 }
2142 
2143 
2144 static int
2145 shm_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
2146 {
2147 	void *rl_cookie;
2148 	struct shmfd *shmfd;
2149 	size_t size;
2150 	int error;
2151 
2152 	/* This assumes that the caller already checked for overflow. */
2153 	error = 0;
2154 	shmfd = fp->f_data;
2155 	size = offset + len;
2156 
2157 	/*
2158 	 * Just grab the rangelock for the range that we may be attempting to
2159 	 * grow, rather than blocking read/write for regions we won't be
2160 	 * touching while this (potential) resize is in progress.  Other
2161 	 * attempts to resize the shmfd will have to take a write lock from 0 to
2162 	 * OFF_MAX, so this being potentially beyond the current usable range of
2163 	 * the shmfd is not necessarily a concern.  If other mechanisms are
2164 	 * added to grow a shmfd, this may need to be re-evaluated.
2165 	 */
2166 	rl_cookie = shm_rangelock_wlock(shmfd, offset, size);
2167 	if (size > shmfd->shm_size)
2168 		error = shm_dotruncate_cookie(shmfd, size, rl_cookie);
2169 	shm_rangelock_unlock(shmfd, rl_cookie);
2170 	/* Translate to posix_fallocate(2) return value as needed. */
2171 	if (error == ENOMEM)
2172 		error = ENOSPC;
2173 	return (error);
2174 }
2175 
2176 static int
2177 sysctl_posix_shm_list(SYSCTL_HANDLER_ARGS)
2178 {
2179 	struct shm_mapping *shmm;
2180 	struct sbuf sb;
2181 	struct kinfo_file kif = {};
2182 	u_long i;
2183 	int error, error2;
2184 
2185 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file) * 5, req);
2186 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
2187 	error = 0;
2188 	sx_slock(&shm_dict_lock);
2189 	for (i = 0; i < shm_hash + 1; i++) {
2190 		LIST_FOREACH(shmm, &shm_dictionary[i], sm_link) {
2191 			error = shm_fill_kinfo_locked(shmm->sm_shmfd,
2192 			    &kif, true);
2193 			if (error == EPERM) {
2194 				error = 0;
2195 				continue;
2196 			}
2197 			if (error != 0)
2198 				break;
2199 			pack_kinfo(&kif);
2200 			error = sbuf_bcat(&sb, &kif, kif.kf_structsize) == 0 ?
2201 			    0 : ENOMEM;
2202 			if (error != 0)
2203 				break;
2204 		}
2205 	}
2206 	sx_sunlock(&shm_dict_lock);
2207 	error2 = sbuf_finish(&sb);
2208 	sbuf_delete(&sb);
2209 	return (error != 0 ? error : error2);
2210 }
2211 
2212 SYSCTL_PROC(_kern_ipc, OID_AUTO, posix_shm_list,
2213     CTLFLAG_RD | CTLFLAG_PRISON | CTLFLAG_MPSAFE | CTLTYPE_OPAQUE,
2214     NULL, 0, sysctl_posix_shm_list, "",
2215     "POSIX SHM list");
2216 
2217 int
2218 kern_shm_open(struct thread *td, const char *path, int flags, mode_t mode,
2219     struct filecaps *caps)
2220 {
2221 
2222 	return (kern_shm_open2(td, path, flags, mode, 0, caps, NULL, NULL));
2223 }
2224 
2225 /*
2226  * This version of the shm_open() interface leaves CLOEXEC behavior up to the
2227  * caller, and libc will enforce it for the traditional shm_open() call.  This
2228  * allows other consumers, like memfd_create(), to opt-in for CLOEXEC.  This
2229  * interface also includes a 'name' argument that is currently unused, but could
2230  * potentially be exported later via some interface for debugging purposes.
2231  * From the kernel's perspective, it is optional.  Individual consumers like
2232  * memfd_create() may require it in order to be compatible with other systems
2233  * implementing the same function.
2234  */
2235 int
2236 sys_shm_open2(struct thread *td, struct shm_open2_args *uap)
2237 {
2238 
2239 	return (kern_shm_open2(td, uap->path, uap->flags, uap->mode,
2240 	    uap->shmflags, NULL, uap->name, NULL));
2241 }
2242 
2243 int
2244 shm_get_path(struct vm_object *obj, char *path, size_t sz)
2245 {
2246 	struct shmfd *shmfd;
2247 	int error;
2248 
2249 	error = 0;
2250 	shmfd = NULL;
2251 	sx_slock(&shm_dict_lock);
2252 	VM_OBJECT_RLOCK(obj);
2253 	if ((obj->flags & OBJ_POSIXSHM) == 0) {
2254 		error = EINVAL;
2255 	} else {
2256 		if (obj->type == shmfd_pager_type)
2257 			shmfd = obj->un_pager.swp.swp_priv;
2258 		else if (obj->type == OBJT_PHYS)
2259 			shmfd = obj->un_pager.phys.phys_priv;
2260 		if (shmfd == NULL) {
2261 			error = ENXIO;
2262 		} else {
2263 			strlcpy(path, shmfd->shm_path == NULL ? "anon" :
2264 			    shmfd->shm_path, sz);
2265 		}
2266 	}
2267 	if (error != 0)
2268 		path[0] = '\0';
2269 	VM_OBJECT_RUNLOCK(obj);
2270 	sx_sunlock(&shm_dict_lock);
2271 	return (error);
2272 }
2273