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