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