xref: /freebsd/sys/kern/uipc_shm.c (revision e72055b7feba695a760d45f01f0f8268b1cb4a74)
1 /*-
2  * Copyright (c) 2006, 2011 Robert N. M. Watson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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
24  * SUCH DAMAGE.
25  */
26 
27 /*
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.
31  *
32  * TODO:
33  *
34  * (1) 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?
37  *
38  * (2) Add support for this file type to fstat(1).
39  *
40  * (3) Resource limits?  Does this need its own resource limits or are the
41  *     existing limits in mmap(2) sufficient?
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_capsicum.h"
48 #include "opt_ktrace.h"
49 
50 #include <sys/param.h>
51 #include <sys/capsicum.h>
52 #include <sys/conf.h>
53 #include <sys/fcntl.h>
54 #include <sys/file.h>
55 #include <sys/filedesc.h>
56 #include <sys/fnv_hash.h>
57 #include <sys/kernel.h>
58 #include <sys/uio.h>
59 #include <sys/signal.h>
60 #include <sys/ktrace.h>
61 #include <sys/lock.h>
62 #include <sys/malloc.h>
63 #include <sys/mman.h>
64 #include <sys/mutex.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/refcount.h>
68 #include <sys/resourcevar.h>
69 #include <sys/rwlock.h>
70 #include <sys/stat.h>
71 #include <sys/sysctl.h>
72 #include <sys/sysproto.h>
73 #include <sys/systm.h>
74 #include <sys/sx.h>
75 #include <sys/time.h>
76 #include <sys/vnode.h>
77 #include <sys/unistd.h>
78 
79 #include <security/mac/mac_framework.h>
80 
81 #include <vm/vm.h>
82 #include <vm/vm_param.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_extern.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_kern.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_pager.h>
91 #include <vm/swap_pager.h>
92 
93 struct shm_mapping {
94 	char		*sm_path;
95 	Fnv32_t		sm_fnv;
96 	struct shmfd	*sm_shmfd;
97 	LIST_ENTRY(shm_mapping) sm_link;
98 };
99 
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;
107 
108 #define	SHM_HASH(fnv)	(&shm_dictionary[(fnv) & shm_hash])
109 
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);
119 
120 static fo_rdwr_t	shm_read;
121 static fo_rdwr_t	shm_write;
122 static fo_truncate_t	shm_truncate;
123 static fo_stat_t	shm_stat;
124 static fo_close_t	shm_close;
125 static fo_chmod_t	shm_chmod;
126 static fo_chown_t	shm_chown;
127 static fo_seek_t	shm_seek;
128 
129 /* File descriptor operations. */
130 static struct fileops shm_ops = {
131 	.fo_read = shm_read,
132 	.fo_write = shm_write,
133 	.fo_truncate = shm_truncate,
134 	.fo_ioctl = invfo_ioctl,
135 	.fo_poll = invfo_poll,
136 	.fo_kqfilter = invfo_kqfilter,
137 	.fo_stat = shm_stat,
138 	.fo_close = shm_close,
139 	.fo_chmod = shm_chmod,
140 	.fo_chown = shm_chown,
141 	.fo_sendfile = vn_sendfile,
142 	.fo_seek = shm_seek,
143 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
144 };
145 
146 FEATURE(posix_shm, "POSIX shared memory");
147 
148 static int
149 uiomove_object_page(vm_object_t obj, size_t len, struct uio *uio)
150 {
151 	vm_page_t m;
152 	vm_pindex_t idx;
153 	size_t tlen;
154 	int error, offset, rv;
155 
156 	idx = OFF_TO_IDX(uio->uio_offset);
157 	offset = uio->uio_offset & PAGE_MASK;
158 	tlen = MIN(PAGE_SIZE - offset, len);
159 
160 	VM_OBJECT_WLOCK(obj);
161 
162 	/*
163 	 * Parallel reads of the page content from disk are prevented
164 	 * by exclusive busy.
165 	 *
166 	 * Although the tmpfs vnode lock is held here, it is
167 	 * nonetheless safe to sleep waiting for a free page.  The
168 	 * pageout daemon does not need to acquire the tmpfs vnode
169 	 * lock to page out tobj's pages because tobj is a OBJT_SWAP
170 	 * type object.
171 	 */
172 	m = vm_page_grab(obj, idx, VM_ALLOC_NORMAL);
173 	if (m->valid != VM_PAGE_BITS_ALL) {
174 		if (vm_pager_has_page(obj, idx, NULL, NULL)) {
175 			rv = vm_pager_get_pages(obj, &m, 1, 0);
176 			m = vm_page_lookup(obj, idx);
177 			if (m == NULL) {
178 				printf(
179 		    "uiomove_object: vm_obj %p idx %jd null lookup rv %d\n",
180 				    obj, idx, rv);
181 				VM_OBJECT_WUNLOCK(obj);
182 				return (EIO);
183 			}
184 			if (rv != VM_PAGER_OK) {
185 				printf(
186 	    "uiomove_object: vm_obj %p idx %jd valid %x pager error %d\n",
187 				    obj, idx, m->valid, rv);
188 				vm_page_lock(m);
189 				vm_page_free(m);
190 				vm_page_unlock(m);
191 				VM_OBJECT_WUNLOCK(obj);
192 				return (EIO);
193 			}
194 		} else
195 			vm_page_zero_invalid(m, TRUE);
196 	}
197 	vm_page_xunbusy(m);
198 	vm_page_lock(m);
199 	vm_page_hold(m);
200 	if (m->queue == PQ_NONE) {
201 		vm_page_deactivate(m);
202 	} else {
203 		/* Requeue to maintain LRU ordering. */
204 		vm_page_requeue(m);
205 	}
206 	vm_page_unlock(m);
207 	VM_OBJECT_WUNLOCK(obj);
208 	error = uiomove_fromphys(&m, offset, tlen, uio);
209 	if (uio->uio_rw == UIO_WRITE && error == 0) {
210 		VM_OBJECT_WLOCK(obj);
211 		vm_page_dirty(m);
212 		vm_pager_page_unswapped(m);
213 		VM_OBJECT_WUNLOCK(obj);
214 	}
215 	vm_page_lock(m);
216 	vm_page_unhold(m);
217 	vm_page_unlock(m);
218 
219 	return (error);
220 }
221 
222 int
223 uiomove_object(vm_object_t obj, off_t obj_size, struct uio *uio)
224 {
225 	ssize_t resid;
226 	size_t len;
227 	int error;
228 
229 	error = 0;
230 	while ((resid = uio->uio_resid) > 0) {
231 		if (obj_size <= uio->uio_offset)
232 			break;
233 		len = MIN(obj_size - uio->uio_offset, resid);
234 		if (len == 0)
235 			break;
236 		error = uiomove_object_page(obj, len, uio);
237 		if (error != 0 || resid == uio->uio_resid)
238 			break;
239 	}
240 	return (error);
241 }
242 
243 static int
244 shm_seek(struct file *fp, off_t offset, int whence, struct thread *td)
245 {
246 	struct shmfd *shmfd;
247 	off_t foffset;
248 	int error;
249 
250 	shmfd = fp->f_data;
251 	foffset = foffset_lock(fp, 0);
252 	error = 0;
253 	switch (whence) {
254 	case L_INCR:
255 		if (foffset < 0 ||
256 		    (offset > 0 && foffset > OFF_MAX - offset)) {
257 			error = EOVERFLOW;
258 			break;
259 		}
260 		offset += foffset;
261 		break;
262 	case L_XTND:
263 		if (offset > 0 && shmfd->shm_size > OFF_MAX - offset) {
264 			error = EOVERFLOW;
265 			break;
266 		}
267 		offset += shmfd->shm_size;
268 		break;
269 	case L_SET:
270 		break;
271 	default:
272 		error = EINVAL;
273 	}
274 	if (error == 0) {
275 		if (offset < 0 || offset > shmfd->shm_size)
276 			error = EINVAL;
277 		else
278 			td->td_uretoff.tdu_off = offset;
279 	}
280 	foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
281 	return (error);
282 }
283 
284 static int
285 shm_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
286     int flags, struct thread *td)
287 {
288 	struct shmfd *shmfd;
289 	void *rl_cookie;
290 	int error;
291 
292 	shmfd = fp->f_data;
293 	foffset_lock_uio(fp, uio, flags);
294 	rl_cookie = rangelock_rlock(&shmfd->shm_rl, uio->uio_offset,
295 	    uio->uio_offset + uio->uio_resid, &shmfd->shm_mtx);
296 #ifdef MAC
297 	error = mac_posixshm_check_read(active_cred, fp->f_cred, shmfd);
298 	if (error)
299 		return (error);
300 #endif
301 	error = uiomove_object(shmfd->shm_object, shmfd->shm_size, uio);
302 	rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
303 	foffset_unlock_uio(fp, uio, flags);
304 	return (error);
305 }
306 
307 static int
308 shm_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
309     int flags, struct thread *td)
310 {
311 	struct shmfd *shmfd;
312 	void *rl_cookie;
313 	int error;
314 
315 	shmfd = fp->f_data;
316 #ifdef MAC
317 	error = mac_posixshm_check_write(active_cred, fp->f_cred, shmfd);
318 	if (error)
319 		return (error);
320 #endif
321 	foffset_lock_uio(fp, uio, flags);
322 	if ((flags & FOF_OFFSET) == 0) {
323 		rl_cookie = rangelock_wlock(&shmfd->shm_rl, 0, OFF_MAX,
324 		    &shmfd->shm_mtx);
325 	} else {
326 		rl_cookie = rangelock_wlock(&shmfd->shm_rl, uio->uio_offset,
327 		    uio->uio_offset + uio->uio_resid, &shmfd->shm_mtx);
328 	}
329 
330 	error = uiomove_object(shmfd->shm_object, shmfd->shm_size, uio);
331 	rangelock_unlock(&shmfd->shm_rl, rl_cookie, &shmfd->shm_mtx);
332 	foffset_unlock_uio(fp, uio, flags);
333 	return (error);
334 }
335 
336 static int
337 shm_truncate(struct file *fp, off_t length, struct ucred *active_cred,
338     struct thread *td)
339 {
340 	struct shmfd *shmfd;
341 #ifdef MAC
342 	int error;
343 #endif
344 
345 	shmfd = fp->f_data;
346 #ifdef MAC
347 	error = mac_posixshm_check_truncate(active_cred, fp->f_cred, shmfd);
348 	if (error)
349 		return (error);
350 #endif
351 	return (shm_dotruncate(shmfd, length));
352 }
353 
354 static int
355 shm_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
356     struct thread *td)
357 {
358 	struct shmfd *shmfd;
359 #ifdef MAC
360 	int error;
361 #endif
362 
363 	shmfd = fp->f_data;
364 
365 #ifdef MAC
366 	error = mac_posixshm_check_stat(active_cred, fp->f_cred, shmfd);
367 	if (error)
368 		return (error);
369 #endif
370 
371 	/*
372 	 * Attempt to return sanish values for fstat() on a memory file
373 	 * descriptor.
374 	 */
375 	bzero(sb, sizeof(*sb));
376 	sb->st_blksize = PAGE_SIZE;
377 	sb->st_size = shmfd->shm_size;
378 	sb->st_blocks = (sb->st_size + sb->st_blksize - 1) / sb->st_blksize;
379 	mtx_lock(&shm_timestamp_lock);
380 	sb->st_atim = shmfd->shm_atime;
381 	sb->st_ctim = shmfd->shm_ctime;
382 	sb->st_mtim = shmfd->shm_mtime;
383 	sb->st_birthtim = shmfd->shm_birthtime;
384 	sb->st_mode = S_IFREG | shmfd->shm_mode;		/* XXX */
385 	sb->st_uid = shmfd->shm_uid;
386 	sb->st_gid = shmfd->shm_gid;
387 	mtx_unlock(&shm_timestamp_lock);
388 	sb->st_dev = shm_dev_ino;
389 	sb->st_ino = shmfd->shm_ino;
390 
391 	return (0);
392 }
393 
394 static int
395 shm_close(struct file *fp, struct thread *td)
396 {
397 	struct shmfd *shmfd;
398 
399 	shmfd = fp->f_data;
400 	fp->f_data = NULL;
401 	shm_drop(shmfd);
402 
403 	return (0);
404 }
405 
406 static int
407 shm_dotruncate(struct shmfd *shmfd, off_t length)
408 {
409 	vm_object_t object;
410 	vm_page_t m, ma[1];
411 	vm_pindex_t idx, nobjsize;
412 	vm_ooffset_t delta;
413 	int base, rv;
414 
415 	object = shmfd->shm_object;
416 	VM_OBJECT_WLOCK(object);
417 	if (length == shmfd->shm_size) {
418 		VM_OBJECT_WUNLOCK(object);
419 		return (0);
420 	}
421 	nobjsize = OFF_TO_IDX(length + PAGE_MASK);
422 
423 	/* Are we shrinking?  If so, trim the end. */
424 	if (length < shmfd->shm_size) {
425 		/*
426 		 * Disallow any requests to shrink the size if this
427 		 * object is mapped into the kernel.
428 		 */
429 		if (shmfd->shm_kmappings > 0) {
430 			VM_OBJECT_WUNLOCK(object);
431 			return (EBUSY);
432 		}
433 
434 		/*
435 		 * Zero the truncated part of the last page.
436 		 */
437 		base = length & PAGE_MASK;
438 		if (base != 0) {
439 			idx = OFF_TO_IDX(length);
440 retry:
441 			m = vm_page_lookup(object, idx);
442 			if (m != NULL) {
443 				if (vm_page_sleep_if_busy(m, "shmtrc"))
444 					goto retry;
445 			} else if (vm_pager_has_page(object, idx, NULL, NULL)) {
446 				m = vm_page_alloc(object, idx, VM_ALLOC_NORMAL);
447 				if (m == NULL) {
448 					VM_OBJECT_WUNLOCK(object);
449 					VM_WAIT;
450 					VM_OBJECT_WLOCK(object);
451 					goto retry;
452 				} else if (m->valid != VM_PAGE_BITS_ALL) {
453 					ma[0] = m;
454 					rv = vm_pager_get_pages(object, ma, 1,
455 					    0);
456 					m = vm_page_lookup(object, idx);
457 				} else
458 					/* A cached page was reactivated. */
459 					rv = VM_PAGER_OK;
460 				vm_page_lock(m);
461 				if (rv == VM_PAGER_OK) {
462 					vm_page_deactivate(m);
463 					vm_page_unlock(m);
464 					vm_page_xunbusy(m);
465 				} else {
466 					vm_page_free(m);
467 					vm_page_unlock(m);
468 					VM_OBJECT_WUNLOCK(object);
469 					return (EIO);
470 				}
471 			}
472 			if (m != NULL) {
473 				pmap_zero_page_area(m, base, PAGE_SIZE - base);
474 				KASSERT(m->valid == VM_PAGE_BITS_ALL,
475 				    ("shm_dotruncate: page %p is invalid", m));
476 				vm_page_dirty(m);
477 				vm_pager_page_unswapped(m);
478 			}
479 		}
480 		delta = ptoa(object->size - nobjsize);
481 
482 		/* Toss in memory pages. */
483 		if (nobjsize < object->size)
484 			vm_object_page_remove(object, nobjsize, object->size,
485 			    0);
486 
487 		/* Toss pages from swap. */
488 		if (object->type == OBJT_SWAP)
489 			swap_pager_freespace(object, nobjsize, delta);
490 
491 		/* Free the swap accounted for shm */
492 		swap_release_by_cred(delta, object->cred);
493 		object->charge -= delta;
494 	} else {
495 		/* Attempt to reserve the swap */
496 		delta = ptoa(nobjsize - object->size);
497 		if (!swap_reserve_by_cred(delta, object->cred)) {
498 			VM_OBJECT_WUNLOCK(object);
499 			return (ENOMEM);
500 		}
501 		object->charge += delta;
502 	}
503 	shmfd->shm_size = length;
504 	mtx_lock(&shm_timestamp_lock);
505 	vfs_timestamp(&shmfd->shm_ctime);
506 	shmfd->shm_mtime = shmfd->shm_ctime;
507 	mtx_unlock(&shm_timestamp_lock);
508 	object->size = nobjsize;
509 	VM_OBJECT_WUNLOCK(object);
510 	return (0);
511 }
512 
513 /*
514  * shmfd object management including creation and reference counting
515  * routines.
516  */
517 static struct shmfd *
518 shm_alloc(struct ucred *ucred, mode_t mode)
519 {
520 	struct shmfd *shmfd;
521 	int ino;
522 
523 	shmfd = malloc(sizeof(*shmfd), M_SHMFD, M_WAITOK | M_ZERO);
524 	shmfd->shm_size = 0;
525 	shmfd->shm_uid = ucred->cr_uid;
526 	shmfd->shm_gid = ucred->cr_gid;
527 	shmfd->shm_mode = mode;
528 	shmfd->shm_object = vm_pager_allocate(OBJT_DEFAULT, NULL,
529 	    shmfd->shm_size, VM_PROT_DEFAULT, 0, ucred);
530 	KASSERT(shmfd->shm_object != NULL, ("shm_create: vm_pager_allocate"));
531 	VM_OBJECT_WLOCK(shmfd->shm_object);
532 	vm_object_clear_flag(shmfd->shm_object, OBJ_ONEMAPPING);
533 	vm_object_set_flag(shmfd->shm_object, OBJ_NOSPLIT);
534 	VM_OBJECT_WUNLOCK(shmfd->shm_object);
535 	vfs_timestamp(&shmfd->shm_birthtime);
536 	shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
537 	    shmfd->shm_birthtime;
538 	ino = alloc_unr(shm_ino_unr);
539 	if (ino == -1)
540 		shmfd->shm_ino = 0;
541 	else
542 		shmfd->shm_ino = ino;
543 	refcount_init(&shmfd->shm_refs, 1);
544 	mtx_init(&shmfd->shm_mtx, "shmrl", NULL, MTX_DEF);
545 	rangelock_init(&shmfd->shm_rl);
546 #ifdef MAC
547 	mac_posixshm_init(shmfd);
548 	mac_posixshm_create(ucred, shmfd);
549 #endif
550 
551 	return (shmfd);
552 }
553 
554 static struct shmfd *
555 shm_hold(struct shmfd *shmfd)
556 {
557 
558 	refcount_acquire(&shmfd->shm_refs);
559 	return (shmfd);
560 }
561 
562 static void
563 shm_drop(struct shmfd *shmfd)
564 {
565 
566 	if (refcount_release(&shmfd->shm_refs)) {
567 #ifdef MAC
568 		mac_posixshm_destroy(shmfd);
569 #endif
570 		rangelock_destroy(&shmfd->shm_rl);
571 		mtx_destroy(&shmfd->shm_mtx);
572 		vm_object_deallocate(shmfd->shm_object);
573 		if (shmfd->shm_ino != 0)
574 			free_unr(shm_ino_unr, shmfd->shm_ino);
575 		free(shmfd, M_SHMFD);
576 	}
577 }
578 
579 /*
580  * Determine if the credentials have sufficient permissions for a
581  * specified combination of FREAD and FWRITE.
582  */
583 static int
584 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
585 {
586 	accmode_t accmode;
587 	int error;
588 
589 	accmode = 0;
590 	if (flags & FREAD)
591 		accmode |= VREAD;
592 	if (flags & FWRITE)
593 		accmode |= VWRITE;
594 	mtx_lock(&shm_timestamp_lock);
595 	error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
596 	    accmode, ucred, NULL);
597 	mtx_unlock(&shm_timestamp_lock);
598 	return (error);
599 }
600 
601 /*
602  * Dictionary management.  We maintain an in-kernel dictionary to map
603  * paths to shmfd objects.  We use the FNV hash on the path to store
604  * the mappings in a hash table.
605  */
606 static void
607 shm_init(void *arg)
608 {
609 
610 	mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
611 	sx_init(&shm_dict_lock, "shm dictionary");
612 	shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
613 	shm_ino_unr = new_unrhdr(1, INT32_MAX, NULL);
614 	KASSERT(shm_ino_unr != NULL, ("shm fake inodes not initialized"));
615 	shm_dev_ino = devfs_alloc_cdp_inode();
616 	KASSERT(shm_dev_ino > 0, ("shm dev inode not initialized"));
617 }
618 SYSINIT(shm_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_init, NULL);
619 
620 static struct shmfd *
621 shm_lookup(char *path, Fnv32_t fnv)
622 {
623 	struct shm_mapping *map;
624 
625 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
626 		if (map->sm_fnv != fnv)
627 			continue;
628 		if (strcmp(map->sm_path, path) == 0)
629 			return (map->sm_shmfd);
630 	}
631 
632 	return (NULL);
633 }
634 
635 static void
636 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
637 {
638 	struct shm_mapping *map;
639 
640 	map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
641 	map->sm_path = path;
642 	map->sm_fnv = fnv;
643 	map->sm_shmfd = shm_hold(shmfd);
644 	shmfd->shm_path = path;
645 	LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
646 }
647 
648 static int
649 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
650 {
651 	struct shm_mapping *map;
652 	int error;
653 
654 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
655 		if (map->sm_fnv != fnv)
656 			continue;
657 		if (strcmp(map->sm_path, path) == 0) {
658 #ifdef MAC
659 			error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
660 			if (error)
661 				return (error);
662 #endif
663 			error = shm_access(map->sm_shmfd, ucred,
664 			    FREAD | FWRITE);
665 			if (error)
666 				return (error);
667 			map->sm_shmfd->shm_path = NULL;
668 			LIST_REMOVE(map, sm_link);
669 			shm_drop(map->sm_shmfd);
670 			free(map->sm_path, M_SHMFD);
671 			free(map, M_SHMFD);
672 			return (0);
673 		}
674 	}
675 
676 	return (ENOENT);
677 }
678 
679 /* System calls. */
680 int
681 sys_shm_open(struct thread *td, struct shm_open_args *uap)
682 {
683 	struct filedesc *fdp;
684 	struct shmfd *shmfd;
685 	struct file *fp;
686 	char *path;
687 	Fnv32_t fnv;
688 	mode_t cmode;
689 	int fd, error;
690 
691 #ifdef CAPABILITY_MODE
692 	/*
693 	 * shm_open(2) is only allowed for anonymous objects.
694 	 */
695 	if (IN_CAPABILITY_MODE(td) && (uap->path != SHM_ANON))
696 		return (ECAPMODE);
697 #endif
698 
699 	if ((uap->flags & O_ACCMODE) != O_RDONLY &&
700 	    (uap->flags & O_ACCMODE) != O_RDWR)
701 		return (EINVAL);
702 
703 	if ((uap->flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_CLOEXEC)) != 0)
704 		return (EINVAL);
705 
706 	fdp = td->td_proc->p_fd;
707 	cmode = (uap->mode & ~fdp->fd_cmask) & ACCESSPERMS;
708 
709 	error = falloc(td, &fp, &fd, O_CLOEXEC);
710 	if (error)
711 		return (error);
712 
713 	/* A SHM_ANON path pointer creates an anonymous object. */
714 	if (uap->path == SHM_ANON) {
715 		/* A read-only anonymous object is pointless. */
716 		if ((uap->flags & O_ACCMODE) == O_RDONLY) {
717 			fdclose(fdp, fp, fd, td);
718 			fdrop(fp, td);
719 			return (EINVAL);
720 		}
721 		shmfd = shm_alloc(td->td_ucred, cmode);
722 	} else {
723 		path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
724 		error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
725 #ifdef KTRACE
726 		if (error == 0 && KTRPOINT(curthread, KTR_NAMEI))
727 			ktrnamei(path);
728 #endif
729 		/* Require paths to start with a '/' character. */
730 		if (error == 0 && path[0] != '/')
731 			error = EINVAL;
732 		if (error) {
733 			fdclose(fdp, fp, fd, td);
734 			fdrop(fp, td);
735 			free(path, M_SHMFD);
736 			return (error);
737 		}
738 
739 		fnv = fnv_32_str(path, FNV1_32_INIT);
740 		sx_xlock(&shm_dict_lock);
741 		shmfd = shm_lookup(path, fnv);
742 		if (shmfd == NULL) {
743 			/* Object does not yet exist, create it if requested. */
744 			if (uap->flags & O_CREAT) {
745 #ifdef MAC
746 				error = mac_posixshm_check_create(td->td_ucred,
747 				    path);
748 				if (error == 0) {
749 #endif
750 					shmfd = shm_alloc(td->td_ucred, cmode);
751 					shm_insert(path, fnv, shmfd);
752 #ifdef MAC
753 				}
754 #endif
755 			} else {
756 				free(path, M_SHMFD);
757 				error = ENOENT;
758 			}
759 		} else {
760 			/*
761 			 * Object already exists, obtain a new
762 			 * reference if requested and permitted.
763 			 */
764 			free(path, M_SHMFD);
765 			if ((uap->flags & (O_CREAT | O_EXCL)) ==
766 			    (O_CREAT | O_EXCL))
767 				error = EEXIST;
768 			else {
769 #ifdef MAC
770 				error = mac_posixshm_check_open(td->td_ucred,
771 				    shmfd, FFLAGS(uap->flags & O_ACCMODE));
772 				if (error == 0)
773 #endif
774 				error = shm_access(shmfd, td->td_ucred,
775 				    FFLAGS(uap->flags & O_ACCMODE));
776 			}
777 
778 			/*
779 			 * Truncate the file back to zero length if
780 			 * O_TRUNC was specified and the object was
781 			 * opened with read/write.
782 			 */
783 			if (error == 0 &&
784 			    (uap->flags & (O_ACCMODE | O_TRUNC)) ==
785 			    (O_RDWR | O_TRUNC)) {
786 #ifdef MAC
787 				error = mac_posixshm_check_truncate(
788 					td->td_ucred, fp->f_cred, shmfd);
789 				if (error == 0)
790 #endif
791 					shm_dotruncate(shmfd, 0);
792 			}
793 			if (error == 0)
794 				shm_hold(shmfd);
795 		}
796 		sx_xunlock(&shm_dict_lock);
797 
798 		if (error) {
799 			fdclose(fdp, fp, fd, td);
800 			fdrop(fp, td);
801 			return (error);
802 		}
803 	}
804 
805 	finit(fp, FFLAGS(uap->flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
806 
807 	td->td_retval[0] = fd;
808 	fdrop(fp, td);
809 
810 	return (0);
811 }
812 
813 int
814 sys_shm_unlink(struct thread *td, struct shm_unlink_args *uap)
815 {
816 	char *path;
817 	Fnv32_t fnv;
818 	int error;
819 
820 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
821 	error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
822 	if (error) {
823 		free(path, M_TEMP);
824 		return (error);
825 	}
826 #ifdef KTRACE
827 	if (KTRPOINT(curthread, KTR_NAMEI))
828 		ktrnamei(path);
829 #endif
830 	fnv = fnv_32_str(path, FNV1_32_INIT);
831 	sx_xlock(&shm_dict_lock);
832 	error = shm_remove(path, fnv, td->td_ucred);
833 	sx_xunlock(&shm_dict_lock);
834 	free(path, M_TEMP);
835 
836 	return (error);
837 }
838 
839 /*
840  * mmap() helper to validate mmap() requests against shm object state
841  * and give mmap() the vm_object to use for the mapping.
842  */
843 int
844 shm_mmap(struct shmfd *shmfd, vm_size_t objsize, vm_ooffset_t foff,
845     vm_object_t *obj)
846 {
847 
848 	/*
849 	 * XXXRW: This validation is probably insufficient, and subject to
850 	 * sign errors.  It should be fixed.
851 	 */
852 	if (foff >= shmfd->shm_size ||
853 	    foff + objsize > round_page(shmfd->shm_size))
854 		return (EINVAL);
855 
856 	mtx_lock(&shm_timestamp_lock);
857 	vfs_timestamp(&shmfd->shm_atime);
858 	mtx_unlock(&shm_timestamp_lock);
859 	vm_object_reference(shmfd->shm_object);
860 	*obj = shmfd->shm_object;
861 	return (0);
862 }
863 
864 static int
865 shm_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
866     struct thread *td)
867 {
868 	struct shmfd *shmfd;
869 	int error;
870 
871 	error = 0;
872 	shmfd = fp->f_data;
873 	mtx_lock(&shm_timestamp_lock);
874 	/*
875 	 * SUSv4 says that x bits of permission need not be affected.
876 	 * Be consistent with our shm_open there.
877 	 */
878 #ifdef MAC
879 	error = mac_posixshm_check_setmode(active_cred, shmfd, mode);
880 	if (error != 0)
881 		goto out;
882 #endif
883 	error = vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid,
884 	    shmfd->shm_gid, VADMIN, active_cred, NULL);
885 	if (error != 0)
886 		goto out;
887 	shmfd->shm_mode = mode & ACCESSPERMS;
888 out:
889 	mtx_unlock(&shm_timestamp_lock);
890 	return (error);
891 }
892 
893 static int
894 shm_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
895     struct thread *td)
896 {
897 	struct shmfd *shmfd;
898 	int error;
899 
900 	error = 0;
901 	shmfd = fp->f_data;
902 	mtx_lock(&shm_timestamp_lock);
903 #ifdef MAC
904 	error = mac_posixshm_check_setowner(active_cred, shmfd, uid, gid);
905 	if (error != 0)
906 		goto out;
907 #endif
908 	if (uid == (uid_t)-1)
909 		uid = shmfd->shm_uid;
910 	if (gid == (gid_t)-1)
911                  gid = shmfd->shm_gid;
912 	if (((uid != shmfd->shm_uid && uid != active_cred->cr_uid) ||
913 	    (gid != shmfd->shm_gid && !groupmember(gid, active_cred))) &&
914 	    (error = priv_check_cred(active_cred, PRIV_VFS_CHOWN, 0)))
915 		goto out;
916 	shmfd->shm_uid = uid;
917 	shmfd->shm_gid = gid;
918 out:
919 	mtx_unlock(&shm_timestamp_lock);
920 	return (error);
921 }
922 
923 /*
924  * Helper routines to allow the backing object of a shared memory file
925  * descriptor to be mapped in the kernel.
926  */
927 int
928 shm_map(struct file *fp, size_t size, off_t offset, void **memp)
929 {
930 	struct shmfd *shmfd;
931 	vm_offset_t kva, ofs;
932 	vm_object_t obj;
933 	int rv;
934 
935 	if (fp->f_type != DTYPE_SHM)
936 		return (EINVAL);
937 	shmfd = fp->f_data;
938 	obj = shmfd->shm_object;
939 	VM_OBJECT_WLOCK(obj);
940 	/*
941 	 * XXXRW: This validation is probably insufficient, and subject to
942 	 * sign errors.  It should be fixed.
943 	 */
944 	if (offset >= shmfd->shm_size ||
945 	    offset + size > round_page(shmfd->shm_size)) {
946 		VM_OBJECT_WUNLOCK(obj);
947 		return (EINVAL);
948 	}
949 
950 	shmfd->shm_kmappings++;
951 	vm_object_reference_locked(obj);
952 	VM_OBJECT_WUNLOCK(obj);
953 
954 	/* Map the object into the kernel_map and wire it. */
955 	kva = vm_map_min(kernel_map);
956 	ofs = offset & PAGE_MASK;
957 	offset = trunc_page(offset);
958 	size = round_page(size + ofs);
959 	rv = vm_map_find(kernel_map, obj, offset, &kva, size, 0,
960 	    VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
961 	    VM_PROT_READ | VM_PROT_WRITE, 0);
962 	if (rv == KERN_SUCCESS) {
963 		rv = vm_map_wire(kernel_map, kva, kva + size,
964 		    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
965 		if (rv == KERN_SUCCESS) {
966 			*memp = (void *)(kva + ofs);
967 			return (0);
968 		}
969 		vm_map_remove(kernel_map, kva, kva + size);
970 	} else
971 		vm_object_deallocate(obj);
972 
973 	/* On failure, drop our mapping reference. */
974 	VM_OBJECT_WLOCK(obj);
975 	shmfd->shm_kmappings--;
976 	VM_OBJECT_WUNLOCK(obj);
977 
978 	return (vm_mmap_to_errno(rv));
979 }
980 
981 /*
982  * We require the caller to unmap the entire entry.  This allows us to
983  * safely decrement shm_kmappings when a mapping is removed.
984  */
985 int
986 shm_unmap(struct file *fp, void *mem, size_t size)
987 {
988 	struct shmfd *shmfd;
989 	vm_map_entry_t entry;
990 	vm_offset_t kva, ofs;
991 	vm_object_t obj;
992 	vm_pindex_t pindex;
993 	vm_prot_t prot;
994 	boolean_t wired;
995 	vm_map_t map;
996 	int rv;
997 
998 	if (fp->f_type != DTYPE_SHM)
999 		return (EINVAL);
1000 	shmfd = fp->f_data;
1001 	kva = (vm_offset_t)mem;
1002 	ofs = kva & PAGE_MASK;
1003 	kva = trunc_page(kva);
1004 	size = round_page(size + ofs);
1005 	map = kernel_map;
1006 	rv = vm_map_lookup(&map, kva, VM_PROT_READ | VM_PROT_WRITE, &entry,
1007 	    &obj, &pindex, &prot, &wired);
1008 	if (rv != KERN_SUCCESS)
1009 		return (EINVAL);
1010 	if (entry->start != kva || entry->end != kva + size) {
1011 		vm_map_lookup_done(map, entry);
1012 		return (EINVAL);
1013 	}
1014 	vm_map_lookup_done(map, entry);
1015 	if (obj != shmfd->shm_object)
1016 		return (EINVAL);
1017 	vm_map_remove(map, kva, kva + size);
1018 	VM_OBJECT_WLOCK(obj);
1019 	KASSERT(shmfd->shm_kmappings > 0, ("shm_unmap: object not mapped"));
1020 	shmfd->shm_kmappings--;
1021 	VM_OBJECT_WUNLOCK(obj);
1022 	return (0);
1023 }
1024 
1025 void
1026 shm_path(struct shmfd *shmfd, char *path, size_t size)
1027 {
1028 
1029 	if (shmfd->shm_path == NULL)
1030 		return;
1031 	sx_slock(&shm_dict_lock);
1032 	if (shmfd->shm_path != NULL)
1033 		strlcpy(path, shmfd->shm_path, size);
1034 	sx_sunlock(&shm_dict_lock);
1035 }
1036