2 * Copyright (c) 2006 Robert N. M. Watson
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * Support for shared swap-backed anonymous memory objects via
29 * shm_open(2) and shm_unlink(2). While most of the implementation is
30 * here, vm_mmap.c contains mapping logic changes.
34 * (2) Need to export data to a userland tool via a sysctl. Should ipcs(1)
35 * and ipcrm(1) be expanded or should new tools to manage both POSIX
36 * kernel semaphores and POSIX shared memory be written?
38 * (3) Add support for this file type to fstat(1).
40 * (4) Resource limits? Does this need its own resource limits or are the
41 * existing limits in mmap(2) sufficient?
43 * (5) Partial page truncation. vnode_pager_setsize() will zero any parts
44 * of a partially mapped page as a result of ftruncate(2)/truncate(2).
45 * We can do the same (with the same pmap evil), but do we need to
46 * worry about the bits on disk if the page is swapped out or will the
47 * swapper zero the parts of a page that are invalid if the page is
48 * swapped back in for us?
50 * (6) Add MAC support in mac_biba(4) and mac_mls(4).
52 * (7) Add a MAC check_create() hook for creating new named objects.
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
58 #include <sys/param.h>
60 #include <sys/fcntl.h>
62 #include <sys/filedesc.h>
63 #include <sys/fnv_hash.h>
64 #include <sys/kernel.h>
66 #include <sys/malloc.h>
68 #include <sys/mutex.h>
70 #include <sys/refcount.h>
71 #include <sys/resourcevar.h>
73 #include <sys/sysctl.h>
74 #include <sys/sysproto.h>
75 #include <sys/systm.h>
78 #include <sys/vnode.h>
80 #include <security/mac/mac_framework.h>
83 #include <vm/vm_param.h>
85 #include <vm/vm_extern.h>
86 #include <vm/vm_map.h>
87 #include <vm/vm_kern.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pager.h>
91 #include <vm/swap_pager.h>
96 struct shmfd *sm_shmfd;
97 LIST_ENTRY(shm_mapping) sm_link;
100 static MALLOC_DEFINE(M_SHMFD, "shmfd", "shared memory file descriptor");
101 static LIST_HEAD(, shm_mapping) *shm_dictionary;
102 static struct sx shm_dict_lock;
103 static struct mtx shm_timestamp_lock;
104 static u_long shm_hash;
105 static struct unrhdr *shm_ino_unr;
106 static dev_t shm_dev_ino;
108 #define SHM_HASH(fnv) (&shm_dictionary[(fnv) & shm_hash])
110 static int shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags);
111 static struct shmfd *shm_alloc(struct ucred *ucred, mode_t mode);
112 static void shm_init(void *arg);
113 static void shm_drop(struct shmfd *shmfd);
114 static struct shmfd *shm_hold(struct shmfd *shmfd);
115 static void shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd);
116 static struct shmfd *shm_lookup(char *path, Fnv32_t fnv);
117 static int shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred);
118 static int shm_dotruncate(struct shmfd *shmfd, off_t length);
120 static fo_rdwr_t shm_read;
121 static fo_rdwr_t shm_write;
122 static fo_truncate_t shm_truncate;
123 static fo_ioctl_t shm_ioctl;
124 static fo_poll_t shm_poll;
125 static fo_kqfilter_t shm_kqfilter;
126 static fo_stat_t shm_stat;
127 static fo_close_t shm_close;
129 /* File descriptor operations. */
130 static struct fileops shm_ops = {
132 .fo_write = shm_write,
133 .fo_truncate = shm_truncate,
134 .fo_ioctl = shm_ioctl,
136 .fo_kqfilter = shm_kqfilter,
138 .fo_close = shm_close,
139 .fo_flags = DFLAG_PASSABLE
142 FEATURE(posix_shm, "POSIX shared memory");
145 shm_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
146 int flags, struct thread *td)
153 shm_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
154 int flags, struct thread *td)
161 shm_truncate(struct file *fp, off_t length, struct ucred *active_cred,
171 error = mac_posixshm_check_truncate(active_cred, fp->f_cred, shmfd);
175 return (shm_dotruncate(shmfd, length));
179 shm_ioctl(struct file *fp, u_long com, void *data,
180 struct ucred *active_cred, struct thread *td)
187 shm_poll(struct file *fp, int events, struct ucred *active_cred,
195 shm_kqfilter(struct file *fp, struct knote *kn)
202 shm_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
213 error = mac_posixshm_check_stat(active_cred, fp->f_cred, shmfd);
219 * Attempt to return sanish values for fstat() on a memory file
222 bzero(sb, sizeof(*sb));
223 sb->st_mode = S_IFREG | shmfd->shm_mode; /* XXX */
224 sb->st_blksize = PAGE_SIZE;
225 sb->st_size = shmfd->shm_size;
226 sb->st_blocks = (sb->st_size + sb->st_blksize - 1) / sb->st_blksize;
227 sb->st_atimespec = shmfd->shm_atime;
228 sb->st_ctimespec = shmfd->shm_ctime;
229 sb->st_mtimespec = shmfd->shm_mtime;
230 sb->st_birthtimespec = shmfd->shm_birthtime;
231 sb->st_uid = shmfd->shm_uid;
232 sb->st_gid = shmfd->shm_gid;
233 sb->st_dev = shm_dev_ino;
234 sb->st_ino = shmfd->shm_ino;
240 shm_close(struct file *fp, struct thread *td)
252 shm_dotruncate(struct shmfd *shmfd, off_t length)
256 vm_pindex_t nobjsize;
259 object = shmfd->shm_object;
260 VM_OBJECT_LOCK(object);
261 if (length == shmfd->shm_size) {
262 VM_OBJECT_UNLOCK(object);
265 nobjsize = OFF_TO_IDX(length + PAGE_MASK);
267 /* Are we shrinking? If so, trim the end. */
268 if (length < shmfd->shm_size) {
270 * Disallow any requests to shrink the size if this
271 * object is mapped into the kernel.
273 if (shmfd->shm_kmappings > 0) {
274 VM_OBJECT_UNLOCK(object);
277 delta = ptoa(object->size - nobjsize);
279 /* Toss in memory pages. */
280 if (nobjsize < object->size)
281 vm_object_page_remove(object, nobjsize, object->size,
284 /* Toss pages from swap. */
285 if (object->type == OBJT_SWAP)
286 swap_pager_freespace(object, nobjsize, delta);
288 /* Free the swap accounted for shm */
289 swap_release_by_uid(delta, object->uip);
290 object->charge -= delta;
293 * If the last page is partially mapped, then zero out
294 * the garbage at the end of the page. See comments
295 * in vnode_pager_setsize() for more details.
297 * XXXJHB: This handles in memory pages, but what about
298 * a page swapped out to disk?
300 if ((length & PAGE_MASK) &&
301 (m = vm_page_lookup(object, OFF_TO_IDX(length))) != NULL &&
303 int base = (int)length & PAGE_MASK;
304 int size = PAGE_SIZE - base;
306 pmap_zero_page_area(m, base, size);
309 * Update the valid bits to reflect the blocks that
310 * have been zeroed. Some of these valid bits may
311 * have already been set.
313 vm_page_set_valid(m, base, size);
316 * Round "base" to the next block boundary so that the
317 * dirty bit for a partially zeroed block is not
320 base = roundup2(base, DEV_BSIZE);
322 vm_page_lock_queues();
323 vm_page_clear_dirty(m, base, PAGE_SIZE - base);
324 vm_page_unlock_queues();
325 } else if ((length & PAGE_MASK) &&
326 __predict_false(object->cache != NULL)) {
327 vm_page_cache_free(object, OFF_TO_IDX(length),
332 /* Attempt to reserve the swap */
333 delta = ptoa(nobjsize - object->size);
334 if (!swap_reserve_by_uid(delta, object->uip)) {
335 VM_OBJECT_UNLOCK(object);
338 object->charge += delta;
340 shmfd->shm_size = length;
341 mtx_lock(&shm_timestamp_lock);
342 vfs_timestamp(&shmfd->shm_ctime);
343 shmfd->shm_mtime = shmfd->shm_ctime;
344 mtx_unlock(&shm_timestamp_lock);
345 object->size = nobjsize;
346 VM_OBJECT_UNLOCK(object);
351 * shmfd object management including creation and reference counting
354 static struct shmfd *
355 shm_alloc(struct ucred *ucred, mode_t mode)
360 shmfd = malloc(sizeof(*shmfd), M_SHMFD, M_WAITOK | M_ZERO);
362 shmfd->shm_uid = ucred->cr_uid;
363 shmfd->shm_gid = ucred->cr_gid;
364 shmfd->shm_mode = mode;
365 shmfd->shm_object = vm_pager_allocate(OBJT_DEFAULT, NULL,
366 shmfd->shm_size, VM_PROT_DEFAULT, 0, ucred);
367 KASSERT(shmfd->shm_object != NULL, ("shm_create: vm_pager_allocate"));
368 VM_OBJECT_LOCK(shmfd->shm_object);
369 vm_object_clear_flag(shmfd->shm_object, OBJ_ONEMAPPING);
370 vm_object_set_flag(shmfd->shm_object, OBJ_NOSPLIT);
371 VM_OBJECT_UNLOCK(shmfd->shm_object);
372 vfs_timestamp(&shmfd->shm_birthtime);
373 shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
374 shmfd->shm_birthtime;
375 ino = alloc_unr(shm_ino_unr);
379 shmfd->shm_ino = ino;
380 refcount_init(&shmfd->shm_refs, 1);
382 mac_posixshm_init(shmfd);
383 mac_posixshm_create(ucred, shmfd);
389 static struct shmfd *
390 shm_hold(struct shmfd *shmfd)
393 refcount_acquire(&shmfd->shm_refs);
398 shm_drop(struct shmfd *shmfd)
401 if (refcount_release(&shmfd->shm_refs)) {
403 mac_posixshm_destroy(shmfd);
405 vm_object_deallocate(shmfd->shm_object);
406 if (shmfd->shm_ino != 0)
407 free_unr(shm_ino_unr, shmfd->shm_ino);
408 free(shmfd, M_SHMFD);
413 * Determine if the credentials have sufficient permissions for a
414 * specified combination of FREAD and FWRITE.
417 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
426 return (vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
427 accmode, ucred, NULL));
431 * Dictionary management. We maintain an in-kernel dictionary to map
432 * paths to shmfd objects. We use the FNV hash on the path to store
433 * the mappings in a hash table.
439 mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
440 sx_init(&shm_dict_lock, "shm dictionary");
441 shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
442 shm_ino_unr = new_unrhdr(1, INT32_MAX, NULL);
443 KASSERT(shm_ino_unr != NULL, ("shm fake inodes not initialized"));
444 shm_dev_ino = devfs_alloc_cdp_inode();
445 KASSERT(shm_dev_ino > 0, ("shm dev inode not initialized"));
447 SYSINIT(shm_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_init, NULL);
449 static struct shmfd *
450 shm_lookup(char *path, Fnv32_t fnv)
452 struct shm_mapping *map;
454 LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
455 if (map->sm_fnv != fnv)
457 if (strcmp(map->sm_path, path) == 0)
458 return (map->sm_shmfd);
465 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
467 struct shm_mapping *map;
469 map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
472 map->sm_shmfd = shm_hold(shmfd);
473 shmfd->shm_path = path;
474 LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
478 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
480 struct shm_mapping *map;
483 LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
484 if (map->sm_fnv != fnv)
486 if (strcmp(map->sm_path, path) == 0) {
488 error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
492 error = shm_access(map->sm_shmfd, ucred,
496 map->sm_shmfd->shm_path = NULL;
497 LIST_REMOVE(map, sm_link);
498 shm_drop(map->sm_shmfd);
499 free(map->sm_path, M_SHMFD);
510 shm_open(struct thread *td, struct shm_open_args *uap)
512 struct filedesc *fdp;
520 if ((uap->flags & O_ACCMODE) != O_RDONLY &&
521 (uap->flags & O_ACCMODE) != O_RDWR)
524 if ((uap->flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) != 0)
527 fdp = td->td_proc->p_fd;
528 cmode = (uap->mode & ~fdp->fd_cmask) & ACCESSPERMS;
530 error = falloc(td, &fp, &fd);
534 /* A SHM_ANON path pointer creates an anonymous object. */
535 if (uap->path == SHM_ANON) {
536 /* A read-only anonymous object is pointless. */
537 if ((uap->flags & O_ACCMODE) == O_RDONLY) {
538 fdclose(fdp, fp, fd, td);
542 shmfd = shm_alloc(td->td_ucred, cmode);
544 path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
545 error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
547 /* Require paths to start with a '/' character. */
548 if (error == 0 && path[0] != '/')
551 fdclose(fdp, fp, fd, td);
557 fnv = fnv_32_str(path, FNV1_32_INIT);
558 sx_xlock(&shm_dict_lock);
559 shmfd = shm_lookup(path, fnv);
561 /* Object does not yet exist, create it if requested. */
562 if (uap->flags & O_CREAT) {
563 shmfd = shm_alloc(td->td_ucred, cmode);
564 shm_insert(path, fnv, shmfd);
571 * Object already exists, obtain a new
572 * reference if requested and permitted.
575 if ((uap->flags & (O_CREAT | O_EXCL)) ==
580 error = mac_posixshm_check_open(td->td_ucred,
584 error = shm_access(shmfd, td->td_ucred,
585 FFLAGS(uap->flags & O_ACCMODE));
589 * Truncate the file back to zero length if
590 * O_TRUNC was specified and the object was
591 * opened with read/write.
594 (uap->flags & (O_ACCMODE | O_TRUNC)) ==
595 (O_RDWR | O_TRUNC)) {
597 error = mac_posixshm_check_truncate(
598 td->td_ucred, fp->f_cred, shmfd);
601 shm_dotruncate(shmfd, 0);
606 sx_xunlock(&shm_dict_lock);
609 fdclose(fdp, fp, fd, td);
615 finit(fp, FFLAGS(uap->flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
618 if (fdp->fd_ofiles[fd] == fp)
619 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
620 FILEDESC_XUNLOCK(fdp);
621 td->td_retval[0] = fd;
628 shm_unlink(struct thread *td, struct shm_unlink_args *uap)
634 path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
635 error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
641 fnv = fnv_32_str(path, FNV1_32_INIT);
642 sx_xlock(&shm_dict_lock);
643 error = shm_remove(path, fnv, td->td_ucred);
644 sx_xunlock(&shm_dict_lock);
651 * mmap() helper to validate mmap() requests against shm object state
652 * and give mmap() the vm_object to use for the mapping.
655 shm_mmap(struct shmfd *shmfd, vm_size_t objsize, vm_ooffset_t foff,
660 * XXXRW: This validation is probably insufficient, and subject to
661 * sign errors. It should be fixed.
663 if (foff >= shmfd->shm_size ||
664 foff + objsize > round_page(shmfd->shm_size))
667 mtx_lock(&shm_timestamp_lock);
668 vfs_timestamp(&shmfd->shm_atime);
669 mtx_unlock(&shm_timestamp_lock);
670 vm_object_reference(shmfd->shm_object);
671 *obj = shmfd->shm_object;
676 * Helper routines to allow the backing object of a shared memory file
677 * descriptor to be mapped in the kernel.
680 shm_map(struct file *fp, size_t size, off_t offset, void **memp)
683 vm_offset_t kva, ofs;
687 if (fp->f_type != DTYPE_SHM)
690 obj = shmfd->shm_object;
693 * XXXRW: This validation is probably insufficient, and subject to
694 * sign errors. It should be fixed.
696 if (offset >= shmfd->shm_size ||
697 offset + size > round_page(shmfd->shm_size)) {
698 VM_OBJECT_UNLOCK(obj);
702 shmfd->shm_kmappings++;
703 vm_object_reference_locked(obj);
704 VM_OBJECT_UNLOCK(obj);
706 /* Map the object into the kernel_map and wire it. */
707 kva = vm_map_min(kernel_map);
708 ofs = offset & PAGE_MASK;
709 offset = trunc_page(offset);
710 size = round_page(size + ofs);
711 rv = vm_map_find(kernel_map, obj, offset, &kva, size,
712 VMFS_ALIGNED_SPACE, VM_PROT_READ | VM_PROT_WRITE,
713 VM_PROT_READ | VM_PROT_WRITE, 0);
714 if (rv == KERN_SUCCESS) {
715 rv = vm_map_wire(kernel_map, kva, kva + size,
716 VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
717 if (rv == KERN_SUCCESS) {
718 *memp = (void *)(kva + ofs);
721 vm_map_remove(kernel_map, kva, kva + size);
723 vm_object_deallocate(obj);
725 /* On failure, drop our mapping reference. */
727 shmfd->shm_kmappings--;
728 VM_OBJECT_UNLOCK(obj);
730 return (vm_mmap_to_errno(rv));
734 * We require the caller to unmap the entire entry. This allows us to
735 * safely decrement shm_kmappings when a mapping is removed.
738 shm_unmap(struct file *fp, void *mem, size_t size)
741 vm_map_entry_t entry;
742 vm_offset_t kva, ofs;
750 if (fp->f_type != DTYPE_SHM)
753 kva = (vm_offset_t)mem;
754 ofs = kva & PAGE_MASK;
755 kva = trunc_page(kva);
756 size = round_page(size + ofs);
758 rv = vm_map_lookup(&map, kva, VM_PROT_READ | VM_PROT_WRITE, &entry,
759 &obj, &pindex, &prot, &wired);
760 if (rv != KERN_SUCCESS)
762 if (entry->start != kva || entry->end != kva + size) {
763 vm_map_lookup_done(map, entry);
766 vm_map_lookup_done(map, entry);
767 if (obj != shmfd->shm_object)
769 vm_map_remove(map, kva, kva + size);
771 KASSERT(shmfd->shm_kmappings > 0, ("shm_unmap: object not mapped"));
772 shmfd->shm_kmappings--;
773 VM_OBJECT_UNLOCK(obj);
778 shm_path(struct shmfd *shmfd, char *path, size_t size)
781 if (shmfd->shm_path == NULL)
783 sx_slock(&shm_dict_lock);
784 if (shmfd->shm_path != NULL)
785 strlcpy(path, shmfd->shm_path, size);
786 sx_sunlock(&shm_dict_lock);