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