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