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