2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2006, 2011, 2016-2017 Robert N. M. Watson
5 * Copyright 2020 The FreeBSD Foundation
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.
13 * Portions of this software were developed by Konstantin Belousov
14 * under sponsorship from the FreeBSD Foundation.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
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.
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
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.
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
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
53 #include "opt_capsicum.h"
54 #include "opt_ktrace.h"
56 #include <sys/param.h>
57 #include <sys/capsicum.h>
59 #include <sys/fcntl.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>
67 #include <sys/signal.h>
69 #include <sys/ktrace.h>
71 #include <sys/malloc.h>
73 #include <sys/mutex.h>
76 #include <sys/refcount.h>
77 #include <sys/resourcevar.h>
78 #include <sys/rwlock.h>
81 #include <sys/syscallsubr.h>
82 #include <sys/sysctl.h>
83 #include <sys/sysproto.h>
84 #include <sys/systm.h>
87 #include <sys/vmmeter.h>
88 #include <sys/vnode.h>
89 #include <sys/unistd.h>
92 #include <security/audit/audit.h>
93 #include <security/mac/mac_framework.h>
96 #include <vm/vm_param.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>
110 struct shmfd *sm_shmfd;
111 LIST_ENTRY(shm_mapping) sm_link;
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;
122 #define SHM_HASH(fnv) (&shm_dictionary[(fnv) & shm_hash])
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,
130 static int shm_dotruncate_locked(struct shmfd *shmfd, off_t length,
132 static int shm_copyin_path(struct thread *td, const char *userpath_in,
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;
150 /* File descriptor operations. */
151 struct fileops shm_ops = {
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,
159 .fo_close = shm_close,
160 .fo_chmod = shm_chmod,
161 .fo_chown = shm_chown,
162 .fo_sendfile = vn_sendfile,
164 .fo_fill_kinfo = shm_fill_kinfo,
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,
172 FEATURE(posix_shm, "POSIX shared memory");
174 static SYSCTL_NODE(_vm, OID_AUTO, largepages, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
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");
183 uiomove_object_page(vm_object_t obj, size_t len, struct uio *uio)
188 int error, offset, rv;
190 idx = OFF_TO_IDX(uio->uio_offset);
191 offset = uio->uio_offset & PAGE_MASK;
192 tlen = MIN(PAGE_SIZE - offset, len);
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)
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.
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));
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
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",
227 VM_OBJECT_WUNLOCK(obj);
230 error = uiomove_fromphys(&m, offset, tlen, uio);
231 if (uio->uio_rw == UIO_WRITE && error == 0)
232 vm_page_set_dirty(m);
240 uiomove_object(vm_object_t obj, off_t obj_size, struct uio *uio)
247 while ((resid = uio->uio_resid) > 0) {
248 if (obj_size <= uio->uio_offset)
250 len = MIN(obj_size - uio->uio_offset, resid);
253 error = uiomove_object_page(obj, len, uio);
254 if (error != 0 || resid == uio->uio_resid)
260 static u_long count_largepages[MAXPAGESIZES];
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)
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);
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.
280 m = vm_page_grab(object, *first, VM_ALLOC_NORMAL | VM_ALLOC_NOCREAT);
283 *last = *first + atop(pagesizes[psind]) - 1;
284 return (VM_PAGER_OK);
288 shm_largepage_phys_haspage(vm_object_t object, vm_pindex_t pindex,
289 int *before, int *after)
293 psind = object->un_pager.phys.data_val;
294 if (psind == 0 || pindex >= object->size)
296 if (before != NULL) {
297 *before = pindex - rounddown2(pindex, pagesizes[psind] /
301 *after = roundup2(pindex, pagesizes[psind] / PAGE_SIZE) -
308 shm_largepage_phys_ctor(vm_object_t object, vm_prot_t prot,
309 vm_ooffset_t foff, struct ucred *cred)
314 shm_largepage_phys_dtor(vm_object_t object)
318 psind = object->un_pager.phys.data_val;
320 atomic_subtract_long(&count_largepages[psind],
321 object->size / (pagesizes[psind] / PAGE_SIZE));
322 vm_wire_sub(object->size);
324 KASSERT(object->size == 0,
325 ("largepage phys obj %p not initialized bit size %#jx > 0",
326 object, (uintmax_t)object->size));
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,
338 shm_largepage(struct shmfd *shmfd)
340 return (shmfd->shm_object->type == OBJT_PHYS);
344 shm_seek(struct file *fp, off_t offset, int whence, struct thread *td)
351 foffset = foffset_lock(fp, 0);
356 (offset > 0 && foffset > OFF_MAX - offset)) {
363 if (offset > 0 && shmfd->shm_size > OFF_MAX - offset) {
367 offset += shmfd->shm_size;
375 if (offset < 0 || offset > shmfd->shm_size)
378 td->td_uretoff.tdu_off = offset;
380 foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
385 shm_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
386 int flags, struct thread *td)
394 error = mac_posixshm_check_read(active_cred, fp->f_cred, shmfd);
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);
408 shm_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
409 int flags, struct thread *td)
418 error = mac_posixshm_check_write(active_cred, fp->f_cred, shmfd);
422 if (shm_largepage(shmfd) && shmfd->shm_lp_psind == 0)
424 foffset_lock_uio(fp, uio, flags);
425 if (uio->uio_resid > OFF_MAX - uio->uio_offset) {
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.
431 if ((shmfd->shm_flags & SHM_GROW_ON_WRITE) != 0) {
432 foffset_unlock_uio(fp, uio, flags);
436 size = shmfd->shm_size;
438 size = uio->uio_offset + uio->uio_resid;
440 if ((flags & FOF_OFFSET) == 0) {
441 rl_cookie = rangelock_wlock(&shmfd->shm_rl, 0, OFF_MAX,
444 rl_cookie = rangelock_wlock(&shmfd->shm_rl, uio->uio_offset,
445 size, &shmfd->shm_mtx);
447 if ((shmfd->shm_seals & F_SEAL_WRITE) != 0) {
451 if ((shmfd->shm_flags & SHM_GROW_ON_WRITE) != 0 &&
452 size > shmfd->shm_size) {
453 VM_OBJECT_WLOCK(shmfd->shm_object);
454 error = shm_dotruncate_locked(shmfd, size, rl_cookie);
455 VM_OBJECT_WUNLOCK(shmfd->shm_object);
458 error = uiomove_object(shmfd->shm_object,
459 shmfd->shm_size, uio);
461 rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
462 foffset_unlock_uio(fp, uio, flags);
467 shm_truncate(struct file *fp, off_t length, struct ucred *active_cred,
477 error = mac_posixshm_check_truncate(active_cred, fp->f_cred, shmfd);
481 return (shm_dotruncate(shmfd, length));
485 shm_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
489 struct shm_largepage_conf *conf;
497 * Allow fcntl(fd, F_SETFL, O_NONBLOCK) to work,
498 * just like it would on an unlinked regular file
502 if (!shm_largepage(shmfd))
505 if (shmfd->shm_lp_psind != 0 &&
506 conf->psind != shmfd->shm_lp_psind)
508 if (conf->psind <= 0 || conf->psind >= MAXPAGESIZES ||
509 pagesizes[conf->psind] == 0)
511 if (conf->alloc_policy != SHM_LARGEPAGE_ALLOC_DEFAULT &&
512 conf->alloc_policy != SHM_LARGEPAGE_ALLOC_NOWAIT &&
513 conf->alloc_policy != SHM_LARGEPAGE_ALLOC_HARD)
516 rl_cookie = rangelock_wlock(&shmfd->shm_rl, 0, OFF_MAX,
518 shmfd->shm_lp_psind = conf->psind;
519 shmfd->shm_lp_alloc_policy = conf->alloc_policy;
520 shmfd->shm_object->un_pager.phys.data_val = conf->psind;
521 rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
524 if (!shm_largepage(shmfd))
527 rl_cookie = rangelock_rlock(&shmfd->shm_rl, 0, OFF_MAX,
529 conf->psind = shmfd->shm_lp_psind;
530 conf->alloc_policy = shmfd->shm_lp_alloc_policy;
531 rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
539 shm_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
550 error = mac_posixshm_check_stat(active_cred, fp->f_cred, shmfd);
556 * Attempt to return sanish values for fstat() on a memory file
559 bzero(sb, sizeof(*sb));
560 sb->st_blksize = PAGE_SIZE;
561 sb->st_size = shmfd->shm_size;
562 sb->st_blocks = howmany(sb->st_size, sb->st_blksize);
563 mtx_lock(&shm_timestamp_lock);
564 sb->st_atim = shmfd->shm_atime;
565 sb->st_ctim = shmfd->shm_ctime;
566 sb->st_mtim = shmfd->shm_mtime;
567 sb->st_birthtim = shmfd->shm_birthtime;
568 sb->st_mode = S_IFREG | shmfd->shm_mode; /* XXX */
569 sb->st_uid = shmfd->shm_uid;
570 sb->st_gid = shmfd->shm_gid;
571 mtx_unlock(&shm_timestamp_lock);
572 sb->st_dev = shm_dev_ino;
573 sb->st_ino = shmfd->shm_ino;
574 sb->st_nlink = shmfd->shm_object->ref_count;
575 sb->st_blocks = shmfd->shm_object->size /
576 (pagesizes[shmfd->shm_lp_psind] >> PAGE_SHIFT);
582 shm_close(struct file *fp, struct thread *td)
594 shm_copyin_path(struct thread *td, const char *userpath_in, char **path_out) {
600 path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
601 pr_path = td->td_ucred->cr_prison->pr_path;
603 /* Construct a full pathname for jailed callers. */
604 pr_pathlen = strcmp(pr_path, "/") ==
605 0 ? 0 : strlcpy(path, pr_path, MAXPATHLEN);
606 error = copyinstr(userpath_in, path + pr_pathlen,
607 MAXPATHLEN - pr_pathlen, NULL);
612 if (KTRPOINT(curthread, KTR_NAMEI))
616 /* Require paths to start with a '/' character. */
617 if (path[pr_pathlen] != '/') {
632 shm_dotruncate_locked(struct shmfd *shmfd, off_t length, void *rl_cookie)
636 vm_pindex_t idx, nobjsize;
640 KASSERT(length >= 0, ("shm_dotruncate: length < 0"));
641 object = shmfd->shm_object;
642 VM_OBJECT_ASSERT_WLOCKED(object);
643 rangelock_cookie_assert(rl_cookie, RA_WLOCKED);
644 if (length == shmfd->shm_size)
646 nobjsize = OFF_TO_IDX(length + PAGE_MASK);
648 /* Are we shrinking? If so, trim the end. */
649 if (length < shmfd->shm_size) {
650 if ((shmfd->shm_seals & F_SEAL_SHRINK) != 0)
654 * Disallow any requests to shrink the size if this
655 * object is mapped into the kernel.
657 if (shmfd->shm_kmappings > 0)
661 * Zero the truncated part of the last page.
663 base = length & PAGE_MASK;
665 idx = OFF_TO_IDX(length);
667 m = vm_page_grab(object, idx, VM_ALLOC_NOCREAT);
669 MPASS(vm_page_all_valid(m));
670 } else if (vm_pager_has_page(object, idx, NULL, NULL)) {
671 m = vm_page_alloc(object, idx,
672 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL);
675 vm_object_pip_add(object, 1);
676 VM_OBJECT_WUNLOCK(object);
677 rv = vm_pager_get_pages(object, &m, 1, NULL,
679 VM_OBJECT_WLOCK(object);
680 vm_object_pip_wakeup(object);
681 if (rv == VM_PAGER_OK) {
683 * Since the page was not resident,
684 * and therefore not recently
685 * accessed, immediately enqueue it
686 * for asynchronous laundering. The
687 * current operation is not regarded
693 VM_OBJECT_WUNLOCK(object);
698 pmap_zero_page_area(m, base, PAGE_SIZE - base);
699 KASSERT(vm_page_all_valid(m),
700 ("shm_dotruncate: page %p is invalid", m));
701 vm_page_set_dirty(m);
705 delta = IDX_TO_OFF(object->size - nobjsize);
707 if (nobjsize < object->size)
708 vm_object_page_remove(object, nobjsize, object->size,
711 /* Free the swap accounted for shm */
712 swap_release_by_cred(delta, object->cred);
713 object->charge -= delta;
715 if ((shmfd->shm_seals & F_SEAL_GROW) != 0)
718 /* Try to reserve additional swap space. */
719 delta = IDX_TO_OFF(nobjsize - object->size);
720 if (!swap_reserve_by_cred(delta, object->cred))
722 object->charge += delta;
724 shmfd->shm_size = length;
725 mtx_lock(&shm_timestamp_lock);
726 vfs_timestamp(&shmfd->shm_ctime);
727 shmfd->shm_mtime = shmfd->shm_ctime;
728 mtx_unlock(&shm_timestamp_lock);
729 object->size = nobjsize;
734 shm_dotruncate_largepage(struct shmfd *shmfd, off_t length, void *rl_cookie)
738 vm_pindex_t newobjsz, oldobjsz;
739 int aflags, error, i, psind, try;
741 KASSERT(length >= 0, ("shm_dotruncate: length < 0"));
742 object = shmfd->shm_object;
743 VM_OBJECT_ASSERT_WLOCKED(object);
744 rangelock_cookie_assert(rl_cookie, RA_WLOCKED);
746 oldobjsz = object->size;
747 newobjsz = OFF_TO_IDX(length);
748 if (length == shmfd->shm_size)
750 psind = shmfd->shm_lp_psind;
751 if (psind == 0 && length != 0)
753 if ((length & (pagesizes[psind] - 1)) != 0)
756 if (length < shmfd->shm_size) {
757 if ((shmfd->shm_seals & F_SEAL_SHRINK) != 0)
759 if (shmfd->shm_kmappings > 0)
761 return (ENOTSUP); /* Pages are unmanaged. */
763 vm_object_page_remove(object, newobjsz, oldobjsz, 0);
764 object->size = newobjsz;
765 shmfd->shm_size = length;
770 aflags = VM_ALLOC_NORMAL | VM_ALLOC_ZERO;
771 if (shmfd->shm_lp_alloc_policy == SHM_LARGEPAGE_ALLOC_NOWAIT)
772 aflags |= VM_ALLOC_WAITFAIL;
776 * Extend shmfd and object, keeping all already fully
777 * allocated large pages intact even on error, because dropped
778 * object lock might allowed mapping of them.
780 while (object->size < newobjsz) {
781 m = vm_page_alloc_contig(object, object->size, aflags,
782 pagesizes[psind] / PAGE_SIZE, 0, ~0,
786 VM_OBJECT_WUNLOCK(object);
787 if (shmfd->shm_lp_alloc_policy ==
788 SHM_LARGEPAGE_ALLOC_NOWAIT ||
789 (shmfd->shm_lp_alloc_policy ==
790 SHM_LARGEPAGE_ALLOC_DEFAULT &&
791 try >= largepage_reclaim_tries)) {
792 VM_OBJECT_WLOCK(object);
795 error = vm_page_reclaim_contig(aflags,
796 pagesizes[psind] / PAGE_SIZE, 0, ~0,
797 pagesizes[psind], 0) ? 0 :
798 vm_wait_intr(object);
800 VM_OBJECT_WLOCK(object);
804 VM_OBJECT_WLOCK(object);
808 for (i = 0; i < pagesizes[psind] / PAGE_SIZE; i++) {
809 if ((m[i].flags & PG_ZERO) == 0)
810 pmap_zero_page(&m[i]);
811 vm_page_valid(&m[i]);
812 vm_page_xunbusy(&m[i]);
814 object->size += OFF_TO_IDX(pagesizes[psind]);
815 shmfd->shm_size += pagesizes[psind];
816 atomic_add_long(&count_largepages[psind], 1);
817 vm_wire_add(atop(pagesizes[psind]));
823 shm_dotruncate_cookie(struct shmfd *shmfd, off_t length, void *rl_cookie)
827 VM_OBJECT_WLOCK(shmfd->shm_object);
828 error = shm_largepage(shmfd) ? shm_dotruncate_largepage(shmfd,
829 length, rl_cookie) : shm_dotruncate_locked(shmfd, length,
831 VM_OBJECT_WUNLOCK(shmfd->shm_object);
836 shm_dotruncate(struct shmfd *shmfd, off_t length)
841 rl_cookie = rangelock_wlock(&shmfd->shm_rl, 0, OFF_MAX,
843 error = shm_dotruncate_cookie(shmfd, length, rl_cookie);
844 rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
849 * shmfd object management including creation and reference counting
853 shm_alloc(struct ucred *ucred, mode_t mode, bool largepage)
857 shmfd = malloc(sizeof(*shmfd), M_SHMFD, M_WAITOK | M_ZERO);
859 shmfd->shm_uid = ucred->cr_uid;
860 shmfd->shm_gid = ucred->cr_gid;
861 shmfd->shm_mode = mode;
863 shmfd->shm_object = phys_pager_allocate(NULL,
864 &shm_largepage_phys_ops, NULL, shmfd->shm_size,
865 VM_PROT_DEFAULT, 0, ucred);
866 shmfd->shm_lp_alloc_policy = SHM_LARGEPAGE_ALLOC_DEFAULT;
868 shmfd->shm_object = vm_pager_allocate(OBJT_SWAP, NULL,
869 shmfd->shm_size, VM_PROT_DEFAULT, 0, ucred);
871 KASSERT(shmfd->shm_object != NULL, ("shm_create: vm_pager_allocate"));
872 vfs_timestamp(&shmfd->shm_birthtime);
873 shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
874 shmfd->shm_birthtime;
875 shmfd->shm_ino = alloc_unr64(&shm_ino_unr);
876 refcount_init(&shmfd->shm_refs, 1);
877 mtx_init(&shmfd->shm_mtx, "shmrl", NULL, MTX_DEF);
878 rangelock_init(&shmfd->shm_rl);
880 mac_posixshm_init(shmfd);
881 mac_posixshm_create(ucred, shmfd);
888 shm_hold(struct shmfd *shmfd)
891 refcount_acquire(&shmfd->shm_refs);
896 shm_drop(struct shmfd *shmfd)
899 if (refcount_release(&shmfd->shm_refs)) {
901 mac_posixshm_destroy(shmfd);
903 rangelock_destroy(&shmfd->shm_rl);
904 mtx_destroy(&shmfd->shm_mtx);
905 vm_object_deallocate(shmfd->shm_object);
906 free(shmfd, M_SHMFD);
911 * Determine if the credentials have sufficient permissions for a
912 * specified combination of FREAD and FWRITE.
915 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
925 mtx_lock(&shm_timestamp_lock);
926 error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
928 mtx_unlock(&shm_timestamp_lock);
938 mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
939 sx_init(&shm_dict_lock, "shm dictionary");
940 shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
941 new_unrhdr64(&shm_ino_unr, 1);
942 shm_dev_ino = devfs_alloc_cdp_inode();
943 KASSERT(shm_dev_ino > 0, ("shm dev inode not initialized"));
945 for (i = 1; i < MAXPAGESIZES; i++) {
946 if (pagesizes[i] == 0)
948 #define M (1024 * 1024)
950 if (pagesizes[i] >= G)
951 snprintf(name, sizeof(name), "%luG", pagesizes[i] / G);
952 else if (pagesizes[i] >= M)
953 snprintf(name, sizeof(name), "%luM", pagesizes[i] / M);
955 snprintf(name, sizeof(name), "%lu", pagesizes[i]);
958 SYSCTL_ADD_ULONG(NULL, SYSCTL_STATIC_CHILDREN(_vm_largepages),
959 OID_AUTO, name, CTLFLAG_RD, &count_largepages[i],
960 "number of non-transient largepages allocated");
963 SYSINIT(shm_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_init, NULL);
966 * Dictionary management. We maintain an in-kernel dictionary to map
967 * paths to shmfd objects. We use the FNV hash on the path to store
968 * the mappings in a hash table.
970 static struct shmfd *
971 shm_lookup(char *path, Fnv32_t fnv)
973 struct shm_mapping *map;
975 LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
976 if (map->sm_fnv != fnv)
978 if (strcmp(map->sm_path, path) == 0)
979 return (map->sm_shmfd);
986 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
988 struct shm_mapping *map;
990 map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
993 map->sm_shmfd = shm_hold(shmfd);
994 shmfd->shm_path = path;
995 LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
999 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
1001 struct shm_mapping *map;
1004 LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
1005 if (map->sm_fnv != fnv)
1007 if (strcmp(map->sm_path, path) == 0) {
1009 error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
1013 error = shm_access(map->sm_shmfd, ucred,
1017 map->sm_shmfd->shm_path = NULL;
1018 LIST_REMOVE(map, sm_link);
1019 shm_drop(map->sm_shmfd);
1020 free(map->sm_path, M_SHMFD);
1030 kern_shm_open2(struct thread *td, const char *userpath, int flags, mode_t mode,
1031 int shmflags, struct filecaps *fcaps, const char *name __unused)
1033 struct filedesc *fdp;
1034 struct shmfd *shmfd;
1040 int error, fd, initial_seals;
1043 if ((shmflags & ~(SHM_ALLOW_SEALING | SHM_GROW_ON_WRITE |
1044 SHM_LARGEPAGE)) != 0)
1047 initial_seals = F_SEAL_SEAL;
1048 if ((shmflags & SHM_ALLOW_SEALING) != 0)
1049 initial_seals &= ~F_SEAL_SEAL;
1051 #ifdef CAPABILITY_MODE
1053 * shm_open(2) is only allowed for anonymous objects.
1055 if (IN_CAPABILITY_MODE(td) && (userpath != SHM_ANON))
1059 AUDIT_ARG_FFLAGS(flags);
1060 AUDIT_ARG_MODE(mode);
1062 if ((flags & O_ACCMODE) != O_RDONLY && (flags & O_ACCMODE) != O_RDWR)
1065 if ((flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_CLOEXEC)) != 0)
1068 largepage = (shmflags & SHM_LARGEPAGE) != 0;
1069 #if !defined(__amd64__)
1075 * Currently only F_SEAL_SEAL may be set when creating or opening shmfd.
1076 * If the decision is made later to allow additional seals, care must be
1077 * taken below to ensure that the seals are properly set if the shmfd
1078 * already existed -- this currently assumes that only F_SEAL_SEAL can
1079 * be set and doesn't take further precautions to ensure the validity of
1080 * the seals being added with respect to current mappings.
1082 if ((initial_seals & ~F_SEAL_SEAL) != 0)
1085 fdp = td->td_proc->p_fd;
1086 cmode = (mode & ~fdp->fd_cmask) & ACCESSPERMS;
1089 * shm_open(2) created shm should always have O_CLOEXEC set, as mandated
1090 * by POSIX. We allow it to be unset here so that an in-kernel
1091 * interface may be written as a thin layer around shm, optionally not
1092 * setting CLOEXEC. For shm_open(2), O_CLOEXEC is set unconditionally
1093 * in sys_shm_open() to keep this implementation compliant.
1095 error = falloc_caps(td, &fp, &fd, flags & O_CLOEXEC, fcaps);
1099 /* A SHM_ANON path pointer creates an anonymous object. */
1100 if (userpath == SHM_ANON) {
1101 /* A read-only anonymous object is pointless. */
1102 if ((flags & O_ACCMODE) == O_RDONLY) {
1103 fdclose(td, fp, fd);
1107 shmfd = shm_alloc(td->td_ucred, cmode, largepage);
1108 shmfd->shm_seals = initial_seals;
1109 shmfd->shm_flags = shmflags;
1111 error = shm_copyin_path(td, userpath, &path);
1113 fdclose(td, fp, fd);
1118 AUDIT_ARG_UPATH1_CANON(path);
1119 fnv = fnv_32_str(path, FNV1_32_INIT);
1120 sx_xlock(&shm_dict_lock);
1121 shmfd = shm_lookup(path, fnv);
1122 if (shmfd == NULL) {
1123 /* Object does not yet exist, create it if requested. */
1124 if (flags & O_CREAT) {
1126 error = mac_posixshm_check_create(td->td_ucred,
1130 shmfd = shm_alloc(td->td_ucred, cmode,
1132 shmfd->shm_seals = initial_seals;
1133 shmfd->shm_flags = shmflags;
1134 shm_insert(path, fnv, shmfd);
1139 free(path, M_SHMFD);
1143 rl_cookie = rangelock_wlock(&shmfd->shm_rl, 0, OFF_MAX,
1147 * kern_shm_open() likely shouldn't ever error out on
1148 * trying to set a seal that already exists, unlike
1149 * F_ADD_SEALS. This would break terribly as
1150 * shm_open(2) actually sets F_SEAL_SEAL to maintain
1151 * historical behavior where the underlying file could
1154 initial_seals &= ~shmfd->shm_seals;
1157 * Object already exists, obtain a new
1158 * reference if requested and permitted.
1160 free(path, M_SHMFD);
1163 * initial_seals can't set additional seals if we've
1164 * already been set F_SEAL_SEAL. If F_SEAL_SEAL is set,
1165 * then we've already removed that one from
1166 * initial_seals. This is currently redundant as we
1167 * only allow setting F_SEAL_SEAL at creation time, but
1168 * it's cheap to check and decreases the effort required
1169 * to allow additional seals.
1171 if ((shmfd->shm_seals & F_SEAL_SEAL) != 0 &&
1174 else if ((flags & (O_CREAT | O_EXCL)) ==
1177 else if (shmflags != 0 && shmflags != shmfd->shm_flags)
1181 error = mac_posixshm_check_open(td->td_ucred,
1182 shmfd, FFLAGS(flags & O_ACCMODE));
1185 error = shm_access(shmfd, td->td_ucred,
1186 FFLAGS(flags & O_ACCMODE));
1190 * Truncate the file back to zero length if
1191 * O_TRUNC was specified and the object was
1192 * opened with read/write.
1195 (flags & (O_ACCMODE | O_TRUNC)) ==
1196 (O_RDWR | O_TRUNC)) {
1197 VM_OBJECT_WLOCK(shmfd->shm_object);
1199 error = mac_posixshm_check_truncate(
1200 td->td_ucred, fp->f_cred, shmfd);
1203 error = shm_dotruncate_locked(shmfd, 0,
1205 VM_OBJECT_WUNLOCK(shmfd->shm_object);
1209 * Currently we only allow F_SEAL_SEAL to be
1210 * set initially. As noted above, this would
1211 * need to be reworked should that change.
1213 shmfd->shm_seals |= initial_seals;
1216 rangelock_unlock(&shmfd->shm_rl, rl_cookie,
1219 sx_xunlock(&shm_dict_lock);
1222 fdclose(td, fp, fd);
1228 finit(fp, FFLAGS(flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
1230 td->td_retval[0] = fd;
1237 #ifdef COMPAT_FREEBSD12
1239 freebsd12_shm_open(struct thread *td, struct freebsd12_shm_open_args *uap)
1242 return (kern_shm_open(td, uap->path, uap->flags | O_CLOEXEC,
1248 sys_shm_unlink(struct thread *td, struct shm_unlink_args *uap)
1254 error = shm_copyin_path(td, uap->path, &path);
1258 AUDIT_ARG_UPATH1_CANON(path);
1259 fnv = fnv_32_str(path, FNV1_32_INIT);
1260 sx_xlock(&shm_dict_lock);
1261 error = shm_remove(path, fnv, td->td_ucred);
1262 sx_xunlock(&shm_dict_lock);
1263 free(path, M_SHMFD);
1269 sys_shm_rename(struct thread *td, struct shm_rename_args *uap)
1271 char *path_from = NULL, *path_to = NULL;
1272 Fnv32_t fnv_from, fnv_to;
1273 struct shmfd *fd_from;
1274 struct shmfd *fd_to;
1279 AUDIT_ARG_FFLAGS(flags);
1282 * Make sure the user passed only valid flags.
1283 * If you add a new flag, please add a new term here.
1286 SHM_RENAME_NOREPLACE |
1294 * EXCHANGE and NOREPLACE don't quite make sense together. Let's
1295 * force the user to choose one or the other.
1297 if ((flags & SHM_RENAME_NOREPLACE) != 0 &&
1298 (flags & SHM_RENAME_EXCHANGE) != 0) {
1303 /* Renaming to or from anonymous makes no sense */
1304 if (uap->path_from == SHM_ANON || uap->path_to == SHM_ANON) {
1309 error = shm_copyin_path(td, uap->path_from, &path_from);
1313 error = shm_copyin_path(td, uap->path_to, &path_to);
1317 AUDIT_ARG_UPATH1_CANON(path_from);
1318 AUDIT_ARG_UPATH2_CANON(path_to);
1320 /* Rename with from/to equal is a no-op */
1321 if (strcmp(path_from, path_to) == 0)
1324 fnv_from = fnv_32_str(path_from, FNV1_32_INIT);
1325 fnv_to = fnv_32_str(path_to, FNV1_32_INIT);
1327 sx_xlock(&shm_dict_lock);
1329 fd_from = shm_lookup(path_from, fnv_from);
1330 if (fd_from == NULL) {
1335 fd_to = shm_lookup(path_to, fnv_to);
1336 if ((flags & SHM_RENAME_NOREPLACE) != 0 && fd_to != NULL) {
1342 * Unconditionally prevents shm_remove from invalidating the 'from'
1346 error = shm_remove(path_from, fnv_from, td->td_ucred);
1349 * One of my assumptions failed if ENOENT (e.g. locking didn't
1352 KASSERT(error != ENOENT, ("Our shm disappeared during shm_rename: %s",
1360 * If we are exchanging, we need to ensure the shm_remove below
1361 * doesn't invalidate the dest shm's state.
1363 if ((flags & SHM_RENAME_EXCHANGE) != 0 && fd_to != NULL)
1367 * NOTE: if path_to is not already in the hash, c'est la vie;
1368 * it simply means we have nothing already at path_to to unlink.
1369 * That is the ENOENT case.
1371 * If we somehow don't have access to unlink this guy, but
1372 * did for the shm at path_from, then relink the shm to path_from
1373 * and abort with EACCES.
1375 * All other errors: that is weird; let's relink and abort the
1378 error = shm_remove(path_to, fnv_to, td->td_ucred);
1379 if (error != 0 && error != ENOENT) {
1380 shm_insert(path_from, fnv_from, fd_from);
1382 /* Don't free path_from now, since the hash references it */
1389 shm_insert(path_to, fnv_to, fd_from);
1391 /* Don't free path_to now, since the hash references it */
1394 /* We kept a ref when we removed, and incremented again in insert */
1396 KASSERT(fd_from->shm_refs > 0, ("Expected >0 refs; got: %d\n",
1397 fd_from->shm_refs));
1399 if ((flags & SHM_RENAME_EXCHANGE) != 0 && fd_to != NULL) {
1400 shm_insert(path_from, fnv_from, fd_to);
1403 KASSERT(fd_to->shm_refs > 0, ("Expected >0 refs; got: %d\n",
1408 sx_xunlock(&shm_dict_lock);
1411 free(path_from, M_SHMFD);
1412 free(path_to, M_SHMFD);
1417 shm_mmap_large(struct shmfd *shmfd, vm_map_t map, vm_offset_t *addr,
1418 vm_size_t size, vm_prot_t prot, vm_prot_t max_prot, int flags,
1419 vm_ooffset_t foff, bool writecounted, struct thread *td)
1421 struct vmspace *vms;
1422 vm_map_entry_t next_entry, prev_entry;
1423 vm_offset_t align, mask, maxaddr;
1424 int docow, error, rv, try;
1427 if (shmfd->shm_lp_psind == 0)
1430 /* MAP_PRIVATE is disabled */
1431 if ((flags & ~(MAP_SHARED | MAP_FIXED | MAP_EXCL |
1436 MAP_ALIGNMENT_MASK)) != 0)
1439 vms = td->td_proc->p_vmspace;
1440 curmap = map == &vms->vm_map;
1442 error = kern_mmap_racct_check(td, map, size);
1447 docow = shmfd->shm_lp_psind << MAP_SPLIT_BOUNDARY_SHIFT;
1448 docow |= MAP_INHERIT_SHARE;
1449 if ((flags & MAP_NOCORE) != 0)
1450 docow |= MAP_DISABLE_COREDUMP;
1452 docow |= MAP_WRITECOUNT;
1454 mask = pagesizes[shmfd->shm_lp_psind] - 1;
1455 if ((foff & mask) != 0)
1457 maxaddr = vm_map_max(map);
1459 if ((flags & MAP_32BIT) != 0 && maxaddr > MAP_32BIT_MAX_ADDR)
1460 maxaddr = MAP_32BIT_MAX_ADDR;
1462 if (size == 0 || (size & mask) != 0 ||
1463 (*addr != 0 && ((*addr & mask) != 0 ||
1464 *addr + size < *addr || *addr + size > maxaddr)))
1467 align = flags & MAP_ALIGNMENT_MASK;
1469 align = pagesizes[shmfd->shm_lp_psind];
1470 } else if (align == MAP_ALIGNED_SUPER) {
1471 if (shmfd->shm_lp_psind != 1)
1473 align = pagesizes[1];
1475 align >>= MAP_ALIGNMENT_SHIFT;
1476 align = 1ULL << align;
1477 /* Also handles overflow. */
1478 if (align < pagesizes[shmfd->shm_lp_psind])
1483 if ((flags & MAP_FIXED) == 0) {
1485 if (curmap && (*addr == 0 ||
1486 (*addr >= round_page((vm_offset_t)vms->vm_taddr) &&
1487 *addr < round_page((vm_offset_t)vms->vm_daddr +
1488 lim_max(td, RLIMIT_DATA))))) {
1489 *addr = roundup2((vm_offset_t)vms->vm_daddr +
1490 lim_max(td, RLIMIT_DATA),
1491 pagesizes[shmfd->shm_lp_psind]);
1494 rv = vm_map_find_aligned(map, addr, size, maxaddr, align);
1495 if (rv != KERN_SUCCESS) {
1498 *addr = vm_map_min(map);
1499 if ((*addr & mask) != 0)
1500 *addr = (*addr + mask) & mask;
1505 } else if ((flags & MAP_EXCL) == 0) {
1506 rv = vm_map_delete(map, *addr, *addr + size);
1507 if (rv != KERN_SUCCESS)
1511 if (vm_map_lookup_entry(map, *addr, &prev_entry))
1513 next_entry = vm_map_entry_succ(prev_entry);
1514 if (next_entry->start < *addr + size)
1518 rv = vm_map_insert(map, shmfd->shm_object, foff, *addr, *addr + size,
1519 prot, max_prot, docow);
1521 error = vm_mmap_to_errno(rv);
1528 shm_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t objsize,
1529 vm_prot_t prot, vm_prot_t cap_maxprot, int flags,
1530 vm_ooffset_t foff, struct thread *td)
1532 struct shmfd *shmfd;
1539 maxprot = VM_PROT_NONE;
1541 rl_cookie = rangelock_rlock(&shmfd->shm_rl, 0, objsize,
1543 /* FREAD should always be set. */
1544 if ((fp->f_flag & FREAD) != 0)
1545 maxprot |= VM_PROT_EXECUTE | VM_PROT_READ;
1548 * If FWRITE's set, we can allow VM_PROT_WRITE unless it's a shared
1549 * mapping with a write seal applied. Private mappings are always
1552 if ((flags & MAP_SHARED) == 0) {
1553 cap_maxprot |= VM_PROT_WRITE;
1554 maxprot |= VM_PROT_WRITE;
1557 if ((fp->f_flag & FWRITE) != 0 &&
1558 (shmfd->shm_seals & F_SEAL_WRITE) == 0)
1559 maxprot |= VM_PROT_WRITE;
1562 * Any mappings from a writable descriptor may be upgraded to
1563 * VM_PROT_WRITE with mprotect(2), unless a write-seal was
1564 * applied between the open and subsequent mmap(2). We want to
1565 * reject application of a write seal as long as any such
1566 * mapping exists so that the seal cannot be trivially bypassed.
1568 writecnt = (maxprot & VM_PROT_WRITE) != 0;
1569 if (!writecnt && (prot & VM_PROT_WRITE) != 0) {
1574 maxprot &= cap_maxprot;
1576 /* See comment in vn_mmap(). */
1579 objsize > OFF_MAX ||
1581 foff < 0 || foff > OFF_MAX - objsize) {
1587 error = mac_posixshm_check_mmap(td->td_ucred, shmfd, prot, flags);
1592 mtx_lock(&shm_timestamp_lock);
1593 vfs_timestamp(&shmfd->shm_atime);
1594 mtx_unlock(&shm_timestamp_lock);
1595 vm_object_reference(shmfd->shm_object);
1598 vm_pager_update_writecount(shmfd->shm_object, 0, objsize);
1599 if (shm_largepage(shmfd)) {
1600 error = shm_mmap_large(shmfd, map, addr, objsize, prot,
1601 maxprot, flags, foff, writecnt, td);
1603 error = vm_mmap_object(map, addr, objsize, prot, maxprot, flags,
1604 shmfd->shm_object, foff, writecnt, td);
1608 vm_pager_release_writecount(shmfd->shm_object, 0,
1610 vm_object_deallocate(shmfd->shm_object);
1613 rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
1618 shm_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
1621 struct shmfd *shmfd;
1626 mtx_lock(&shm_timestamp_lock);
1628 * SUSv4 says that x bits of permission need not be affected.
1629 * Be consistent with our shm_open there.
1632 error = mac_posixshm_check_setmode(active_cred, shmfd, mode);
1636 error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
1637 VADMIN, active_cred);
1640 shmfd->shm_mode = mode & ACCESSPERMS;
1642 mtx_unlock(&shm_timestamp_lock);
1647 shm_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
1650 struct shmfd *shmfd;
1655 mtx_lock(&shm_timestamp_lock);
1657 error = mac_posixshm_check_setowner(active_cred, shmfd, uid, gid);
1661 if (uid == (uid_t)-1)
1662 uid = shmfd->shm_uid;
1663 if (gid == (gid_t)-1)
1664 gid = shmfd->shm_gid;
1665 if (((uid != shmfd->shm_uid && uid != active_cred->cr_uid) ||
1666 (gid != shmfd->shm_gid && !groupmember(gid, active_cred))) &&
1667 (error = priv_check_cred(active_cred, PRIV_VFS_CHOWN)))
1669 shmfd->shm_uid = uid;
1670 shmfd->shm_gid = gid;
1672 mtx_unlock(&shm_timestamp_lock);
1677 * Helper routines to allow the backing object of a shared memory file
1678 * descriptor to be mapped in the kernel.
1681 shm_map(struct file *fp, size_t size, off_t offset, void **memp)
1683 struct shmfd *shmfd;
1684 vm_offset_t kva, ofs;
1688 if (fp->f_type != DTYPE_SHM)
1691 obj = shmfd->shm_object;
1692 VM_OBJECT_WLOCK(obj);
1694 * XXXRW: This validation is probably insufficient, and subject to
1695 * sign errors. It should be fixed.
1697 if (offset >= shmfd->shm_size ||
1698 offset + size > round_page(shmfd->shm_size)) {
1699 VM_OBJECT_WUNLOCK(obj);
1703 shmfd->shm_kmappings++;
1704 vm_object_reference_locked(obj);
1705 VM_OBJECT_WUNLOCK(obj);
1707 /* Map the object into the kernel_map and wire it. */
1708 kva = vm_map_min(kernel_map);
1709 ofs = offset & PAGE_MASK;
1710 offset = trunc_page(offset);
1711 size = round_page(size + ofs);
1712 rv = vm_map_find(kernel_map, obj, offset, &kva, size, 0,
1713 VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
1714 VM_PROT_READ | VM_PROT_WRITE, 0);
1715 if (rv == KERN_SUCCESS) {
1716 rv = vm_map_wire(kernel_map, kva, kva + size,
1717 VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
1718 if (rv == KERN_SUCCESS) {
1719 *memp = (void *)(kva + ofs);
1722 vm_map_remove(kernel_map, kva, kva + size);
1724 vm_object_deallocate(obj);
1726 /* On failure, drop our mapping reference. */
1727 VM_OBJECT_WLOCK(obj);
1728 shmfd->shm_kmappings--;
1729 VM_OBJECT_WUNLOCK(obj);
1731 return (vm_mmap_to_errno(rv));
1735 * We require the caller to unmap the entire entry. This allows us to
1736 * safely decrement shm_kmappings when a mapping is removed.
1739 shm_unmap(struct file *fp, void *mem, size_t size)
1741 struct shmfd *shmfd;
1742 vm_map_entry_t entry;
1743 vm_offset_t kva, ofs;
1751 if (fp->f_type != DTYPE_SHM)
1754 kva = (vm_offset_t)mem;
1755 ofs = kva & PAGE_MASK;
1756 kva = trunc_page(kva);
1757 size = round_page(size + ofs);
1759 rv = vm_map_lookup(&map, kva, VM_PROT_READ | VM_PROT_WRITE, &entry,
1760 &obj, &pindex, &prot, &wired);
1761 if (rv != KERN_SUCCESS)
1763 if (entry->start != kva || entry->end != kva + size) {
1764 vm_map_lookup_done(map, entry);
1767 vm_map_lookup_done(map, entry);
1768 if (obj != shmfd->shm_object)
1770 vm_map_remove(map, kva, kva + size);
1771 VM_OBJECT_WLOCK(obj);
1772 KASSERT(shmfd->shm_kmappings > 0, ("shm_unmap: object not mapped"));
1773 shmfd->shm_kmappings--;
1774 VM_OBJECT_WUNLOCK(obj);
1779 shm_fill_kinfo_locked(struct shmfd *shmfd, struct kinfo_file *kif, bool list)
1781 const char *path, *pr_path;
1785 sx_assert(&shm_dict_lock, SA_LOCKED);
1786 kif->kf_type = KF_TYPE_SHM;
1787 kif->kf_un.kf_file.kf_file_mode = S_IFREG | shmfd->shm_mode;
1788 kif->kf_un.kf_file.kf_file_size = shmfd->shm_size;
1789 if (shmfd->shm_path != NULL) {
1790 if (shmfd->shm_path != NULL) {
1791 path = shmfd->shm_path;
1792 pr_path = curthread->td_ucred->cr_prison->pr_path;
1793 if (strcmp(pr_path, "/") != 0) {
1794 /* Return the jail-rooted pathname. */
1795 pr_pathlen = strlen(pr_path);
1796 visible = strncmp(path, pr_path, pr_pathlen)
1797 == 0 && path[pr_pathlen] == '/';
1798 if (list && !visible)
1803 strlcpy(kif->kf_path, path, sizeof(kif->kf_path));
1810 shm_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1811 struct filedesc *fdp __unused)
1815 sx_slock(&shm_dict_lock);
1816 res = shm_fill_kinfo_locked(fp->f_data, kif, false);
1817 sx_sunlock(&shm_dict_lock);
1822 shm_add_seals(struct file *fp, int seals)
1824 struct shmfd *shmfd;
1826 vm_ooffset_t writemappings;
1831 rl_cookie = rangelock_wlock(&shmfd->shm_rl, 0, OFF_MAX,
1834 /* Even already-set seals should result in EPERM. */
1835 if ((shmfd->shm_seals & F_SEAL_SEAL) != 0) {
1839 nseals = seals & ~shmfd->shm_seals;
1840 if ((nseals & F_SEAL_WRITE) != 0) {
1842 * The rangelock above prevents writable mappings from being
1843 * added after we've started applying seals. The RLOCK here
1844 * is to avoid torn reads on ILP32 arches as unmapping/reducing
1845 * writemappings will be done without a rangelock.
1847 VM_OBJECT_RLOCK(shmfd->shm_object);
1848 writemappings = shmfd->shm_object->un_pager.swp.writemappings;
1849 VM_OBJECT_RUNLOCK(shmfd->shm_object);
1850 /* kmappings are also writable */
1851 if (writemappings > 0) {
1856 shmfd->shm_seals |= nseals;
1858 rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
1863 shm_get_seals(struct file *fp, int *seals)
1865 struct shmfd *shmfd;
1868 *seals = shmfd->shm_seals;
1873 shm_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
1876 struct shmfd *shmfd;
1880 /* This assumes that the caller already checked for overflow. */
1883 size = offset + len;
1886 * Just grab the rangelock for the range that we may be attempting to
1887 * grow, rather than blocking read/write for regions we won't be
1888 * touching while this (potential) resize is in progress. Other
1889 * attempts to resize the shmfd will have to take a write lock from 0 to
1890 * OFF_MAX, so this being potentially beyond the current usable range of
1891 * the shmfd is not necessarily a concern. If other mechanisms are
1892 * added to grow a shmfd, this may need to be re-evaluated.
1894 rl_cookie = rangelock_wlock(&shmfd->shm_rl, offset, size,
1896 if (size > shmfd->shm_size)
1897 error = shm_dotruncate_cookie(shmfd, size, rl_cookie);
1898 rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
1899 /* Translate to posix_fallocate(2) return value as needed. */
1900 if (error == ENOMEM)
1906 sysctl_posix_shm_list(SYSCTL_HANDLER_ARGS)
1908 struct shm_mapping *shmm;
1910 struct kinfo_file kif;
1915 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file) * 5, req);
1916 sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
1919 sx_slock(&shm_dict_lock);
1920 for (i = 0; i < shm_hash + 1; i++) {
1921 LIST_FOREACH(shmm, &shm_dictionary[i], sm_link) {
1922 error = shm_fill_kinfo_locked(shmm->sm_shmfd,
1929 if (req->oldptr != NULL &&
1930 kif.kf_structsize + curlen > req->oldlen)
1932 error = sbuf_bcat(&sb, &kif, kif.kf_structsize) == 0 ?
1936 curlen += kif.kf_structsize;
1939 sx_sunlock(&shm_dict_lock);
1940 error2 = sbuf_finish(&sb);
1942 return (error != 0 ? error : error2);
1945 SYSCTL_PROC(_kern_ipc, OID_AUTO, posix_shm_list,
1946 CTLFLAG_RD | CTLFLAG_MPSAFE | CTLTYPE_OPAQUE,
1947 NULL, 0, sysctl_posix_shm_list, "",
1951 kern_shm_open(struct thread *td, const char *path, int flags, mode_t mode,
1952 struct filecaps *caps)
1955 return (kern_shm_open2(td, path, flags, mode, 0, caps, NULL));
1959 * This version of the shm_open() interface leaves CLOEXEC behavior up to the
1960 * caller, and libc will enforce it for the traditional shm_open() call. This
1961 * allows other consumers, like memfd_create(), to opt-in for CLOEXEC. This
1962 * interface also includes a 'name' argument that is currently unused, but could
1963 * potentially be exported later via some interface for debugging purposes.
1964 * From the kernel's perspective, it is optional. Individual consumers like
1965 * memfd_create() may require it in order to be compatible with other systems
1966 * implementing the same function.
1969 sys_shm_open2(struct thread *td, struct shm_open2_args *uap)
1972 return (kern_shm_open2(td, uap->path, uap->flags, uap->mode,
1973 uap->shmflags, NULL, uap->name));