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