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