xref: /freebsd/sys/kern/uipc_shm.c (revision 2be1a816b9ff69588e55be0a84cbe2a31efc0f2f)
1 /*-
2  * Copyright (c) 2006 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  * (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?
37  *
38  * (3) Add support for this file type to fstat(1).
39  *
40  * (4) Resource limits?  Does this need its own resource limits or are the
41  *     existing limits in mmap(2) sufficient?
42  *
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?
49  */
50 
51 #include <sys/cdefs.h>
52 __FBSDID("$FreeBSD$");
53 
54 #include "opt_mac.h"
55 
56 #include <sys/param.h>
57 #include <sys/fcntl.h>
58 #include <sys/file.h>
59 #include <sys/filedesc.h>
60 #include <sys/fnv_hash.h>
61 #include <sys/kernel.h>
62 #include <sys/lock.h>
63 #include <sys/malloc.h>
64 #include <sys/mman.h>
65 #include <sys/mutex.h>
66 #include <sys/proc.h>
67 #include <sys/refcount.h>
68 #include <sys/resourcevar.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/sysproto.h>
72 #include <sys/systm.h>
73 #include <sys/sx.h>
74 #include <sys/time.h>
75 #include <sys/vnode.h>
76 
77 #include <security/mac/mac_framework.h>
78 
79 #include <vm/vm.h>
80 #include <vm/vm_param.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_object.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_pager.h>
86 #include <vm/swap_pager.h>
87 
88 struct shm_mapping {
89 	char		*sm_path;
90 	Fnv32_t		sm_fnv;
91 	struct shmfd	*sm_shmfd;
92 	LIST_ENTRY(shm_mapping) sm_link;
93 };
94 
95 static MALLOC_DEFINE(M_SHMFD, "shmfd", "shared memory file descriptor");
96 static LIST_HEAD(, shm_mapping) *shm_dictionary;
97 static struct sx shm_dict_lock;
98 static struct mtx shm_timestamp_lock;
99 static u_long shm_hash;
100 
101 #define	SHM_HASH(fnv)	(&shm_dictionary[(fnv) & shm_hash])
102 
103 static int	shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags);
104 static struct shmfd *shm_alloc(struct ucred *ucred, mode_t mode);
105 static void	shm_dict_init(void *arg);
106 static void	shm_drop(struct shmfd *shmfd);
107 static struct shmfd *shm_hold(struct shmfd *shmfd);
108 static void	shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd);
109 static struct shmfd *shm_lookup(char *path, Fnv32_t fnv);
110 static int	shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred);
111 static void	shm_dotruncate(struct shmfd *shmfd, off_t length);
112 
113 static fo_rdwr_t	shm_read;
114 static fo_rdwr_t	shm_write;
115 static fo_truncate_t	shm_truncate;
116 static fo_ioctl_t	shm_ioctl;
117 static fo_poll_t	shm_poll;
118 static fo_kqfilter_t	shm_kqfilter;
119 static fo_stat_t	shm_stat;
120 static fo_close_t	shm_close;
121 
122 /* File descriptor operations. */
123 static struct fileops shm_ops = {
124 	.fo_read = shm_read,
125 	.fo_write = shm_write,
126 	.fo_truncate = shm_truncate,
127 	.fo_ioctl = shm_ioctl,
128 	.fo_poll = shm_poll,
129 	.fo_kqfilter = shm_kqfilter,
130 	.fo_stat = shm_stat,
131 	.fo_close = shm_close,
132 	.fo_flags = DFLAG_PASSABLE
133 };
134 
135 FEATURE(posix_shm, "POSIX shared memory");
136 
137 static int
138 shm_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
139     int flags, struct thread *td)
140 {
141 
142 	return (EOPNOTSUPP);
143 }
144 
145 static int
146 shm_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
147     int flags, struct thread *td)
148 {
149 
150 	return (EOPNOTSUPP);
151 }
152 
153 static int
154 shm_truncate(struct file *fp, off_t length, struct ucred *active_cred,
155     struct thread *td)
156 {
157 	struct shmfd *shmfd;
158 #ifdef MAC
159 	int error;
160 #endif
161 
162 	shmfd = fp->f_data;
163 #ifdef MAC
164 	error = mac_posixshm_check_truncate(active_cred, fp->f_cred, shmfd);
165 	if (error)
166 		return (error);
167 #endif
168 	shm_dotruncate(shmfd, length);
169 	return (0);
170 }
171 
172 static int
173 shm_ioctl(struct file *fp, u_long com, void *data,
174     struct ucred *active_cred, struct thread *td)
175 {
176 
177 	return (EOPNOTSUPP);
178 }
179 
180 static int
181 shm_poll(struct file *fp, int events, struct ucred *active_cred,
182     struct thread *td)
183 {
184 
185 	return (EOPNOTSUPP);
186 }
187 
188 static int
189 shm_kqfilter(struct file *fp, struct knote *kn)
190 {
191 
192 	return (EOPNOTSUPP);
193 }
194 
195 static int
196 shm_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
197     struct thread *td)
198 {
199 	struct shmfd *shmfd;
200 #ifdef MAC
201 	int error;
202 #endif
203 
204 	shmfd = fp->f_data;
205 
206 #ifdef MAC
207 	error = mac_posixshm_check_stat(active_cred, fp->f_cred, shmfd);
208 	if (error)
209 		return (error);
210 #endif
211 
212 	/*
213 	 * Attempt to return sanish values for fstat() on a memory file
214 	 * descriptor.
215 	 */
216 	bzero(sb, sizeof(*sb));
217 	sb->st_mode = S_IFREG | shmfd->shm_mode;		/* XXX */
218 	sb->st_blksize = PAGE_SIZE;
219 	sb->st_size = shmfd->shm_size;
220 	sb->st_blocks = (sb->st_size + sb->st_blksize - 1) / sb->st_blksize;
221 	sb->st_atimespec = shmfd->shm_atime;
222 	sb->st_ctimespec = shmfd->shm_ctime;
223 	sb->st_mtimespec = shmfd->shm_mtime;
224 	sb->st_birthtimespec = shmfd->shm_birthtime;
225 	sb->st_uid = shmfd->shm_uid;
226 	sb->st_gid = shmfd->shm_gid;
227 
228 	return (0);
229 }
230 
231 static int
232 shm_close(struct file *fp, struct thread *td)
233 {
234 	struct shmfd *shmfd;
235 
236 	shmfd = fp->f_data;
237 	fp->f_data = NULL;
238 	shm_drop(shmfd);
239 
240 	return (0);
241 }
242 
243 static void
244 shm_dotruncate(struct shmfd *shmfd, off_t length)
245 {
246 	vm_object_t object;
247 	vm_page_t m;
248 	vm_pindex_t nobjsize;
249 
250 	object = shmfd->shm_object;
251 	VM_OBJECT_LOCK(object);
252 	if (length == shmfd->shm_size) {
253 		VM_OBJECT_UNLOCK(object);
254 		return;
255 	}
256 	nobjsize = OFF_TO_IDX(length + PAGE_MASK);
257 
258 	/* Are we shrinking?  If so, trim the end. */
259 	if (length < shmfd->shm_size) {
260 		/* Toss in memory pages. */
261 		if (nobjsize < object->size)
262 			vm_object_page_remove(object, nobjsize, object->size,
263 			    FALSE);
264 
265 		/* Toss pages from swap. */
266 		if (object->type == OBJT_SWAP)
267 			swap_pager_freespace(object, nobjsize,
268 			    object->size - nobjsize);
269 
270 		/*
271 		 * If the last page is partially mapped, then zero out
272 		 * the garbage at the end of the page.  See comments
273 		 * in vnode_page_setsize() for more details.
274 		 *
275 		 * XXXJHB: This handles in memory pages, but what about
276 		 * a page swapped out to disk?
277 		 */
278 		if ((length & PAGE_MASK) &&
279 		    (m = vm_page_lookup(object, OFF_TO_IDX(length))) != NULL &&
280 		    m->valid != 0) {
281 			int base = (int)length & PAGE_MASK;
282 			int size = PAGE_SIZE - base;
283 
284 			pmap_zero_page_area(m, base, size);
285 			vm_page_lock_queues();
286 			vm_page_set_validclean(m, base, size);
287 			if (m->dirty != 0)
288 				m->dirty = VM_PAGE_BITS_ALL;
289 			vm_page_unlock_queues();
290 		} else if ((length & PAGE_MASK) &&
291 		    __predict_false(object->cache != NULL)) {
292 			vm_page_cache_free(object, OFF_TO_IDX(length),
293 			    nobjsize);
294 		}
295 	}
296 	shmfd->shm_size = length;
297 	mtx_lock(&shm_timestamp_lock);
298 	vfs_timestamp(&shmfd->shm_ctime);
299 	shmfd->shm_mtime = shmfd->shm_ctime;
300 	mtx_unlock(&shm_timestamp_lock);
301 	object->size = nobjsize;
302 	VM_OBJECT_UNLOCK(object);
303 }
304 
305 /*
306  * shmfd object management including creation and reference counting
307  * routines.
308  */
309 static struct shmfd *
310 shm_alloc(struct ucred *ucred, mode_t mode)
311 {
312 	struct shmfd *shmfd;
313 
314 	shmfd = malloc(sizeof(*shmfd), M_SHMFD, M_WAITOK | M_ZERO);
315 	shmfd->shm_size = 0;
316 	shmfd->shm_uid = ucred->cr_uid;
317 	shmfd->shm_gid = ucred->cr_gid;
318 	shmfd->shm_mode = mode;
319 	shmfd->shm_object = vm_pager_allocate(OBJT_DEFAULT, NULL,
320 	    shmfd->shm_size, VM_PROT_DEFAULT, 0);
321 	KASSERT(shmfd->shm_object != NULL, ("shm_create: vm_pager_allocate"));
322 	VM_OBJECT_LOCK(shmfd->shm_object);
323 	vm_object_clear_flag(shmfd->shm_object, OBJ_ONEMAPPING);
324 	vm_object_set_flag(shmfd->shm_object, OBJ_NOSPLIT);
325 	VM_OBJECT_UNLOCK(shmfd->shm_object);
326 	vfs_timestamp(&shmfd->shm_birthtime);
327 	shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
328 	    shmfd->shm_birthtime;
329 	refcount_init(&shmfd->shm_refs, 1);
330 #ifdef MAC
331 	mac_posixshm_init(shmfd);
332 	mac_posixshm_create(ucred, shmfd);
333 #endif
334 
335 	return (shmfd);
336 }
337 
338 static struct shmfd *
339 shm_hold(struct shmfd *shmfd)
340 {
341 
342 	refcount_acquire(&shmfd->shm_refs);
343 	return (shmfd);
344 }
345 
346 static void
347 shm_drop(struct shmfd *shmfd)
348 {
349 
350 	if (refcount_release(&shmfd->shm_refs)) {
351 #ifdef MAC
352 		mac_posixshm_destroy(shmfd);
353 #endif
354 		vm_object_deallocate(shmfd->shm_object);
355 		free(shmfd, M_SHMFD);
356 	}
357 }
358 
359 /*
360  * Determine if the credentials have sufficient permissions for a
361  * specified combination of FREAD and FWRITE.
362  */
363 static int
364 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
365 {
366 	int acc_mode;
367 
368 	acc_mode = 0;
369 	if (flags & FREAD)
370 		acc_mode |= VREAD;
371 	if (flags & FWRITE)
372 		acc_mode |= VWRITE;
373 	return (vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
374 	    acc_mode, ucred, NULL));
375 }
376 
377 /*
378  * Dictionary management.  We maintain an in-kernel dictionary to map
379  * paths to shmfd objects.  We use the FNV hash on the path to store
380  * the mappings in a hash table.
381  */
382 static void
383 shm_dict_init(void *arg)
384 {
385 
386 	mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
387 	sx_init(&shm_dict_lock, "shm dictionary");
388 	shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
389 }
390 SYSINIT(shm_dict_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_dict_init, NULL);
391 
392 static struct shmfd *
393 shm_lookup(char *path, Fnv32_t fnv)
394 {
395 	struct shm_mapping *map;
396 
397 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
398 		if (map->sm_fnv != fnv)
399 			continue;
400 		if (strcmp(map->sm_path, path) == 0)
401 			return (map->sm_shmfd);
402 	}
403 
404 	return (NULL);
405 }
406 
407 static void
408 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
409 {
410 	struct shm_mapping *map;
411 
412 	map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
413 	map->sm_path = path;
414 	map->sm_fnv = fnv;
415 	map->sm_shmfd = shm_hold(shmfd);
416 	LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
417 }
418 
419 static int
420 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
421 {
422 	struct shm_mapping *map;
423 	int error;
424 
425 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
426 		if (map->sm_fnv != fnv)
427 			continue;
428 		if (strcmp(map->sm_path, path) == 0) {
429 #ifdef MAC
430 			error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
431 			if (error)
432 				return (error);
433 #endif
434 			error = shm_access(map->sm_shmfd, ucred,
435 			    FREAD | FWRITE);
436 			if (error)
437 				return (error);
438 			LIST_REMOVE(map, sm_link);
439 			shm_drop(map->sm_shmfd);
440 			free(map->sm_path, M_SHMFD);
441 			free(map, M_SHMFD);
442 			return (0);
443 		}
444 	}
445 
446 	return (ENOENT);
447 }
448 
449 /* System calls. */
450 int
451 shm_open(struct thread *td, struct shm_open_args *uap)
452 {
453 	struct filedesc *fdp;
454 	struct shmfd *shmfd;
455 	struct file *fp;
456 	char *path;
457 	Fnv32_t fnv;
458 	mode_t cmode;
459 	int fd, error;
460 
461 	if ((uap->flags & O_ACCMODE) != O_RDONLY &&
462 	    (uap->flags & O_ACCMODE) != O_RDWR)
463 		return (EINVAL);
464 
465 	if ((uap->flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) != 0)
466 		return (EINVAL);
467 
468 	fdp = td->td_proc->p_fd;
469 	cmode = (uap->mode & ~fdp->fd_cmask) & ACCESSPERMS;
470 
471 	error = falloc(td, &fp, &fd);
472 	if (error)
473 		return (error);
474 
475 	/* A SHM_ANON path pointer creates an anonymous object. */
476 	if (uap->path == SHM_ANON) {
477 		/* A read-only anonymous object is pointless. */
478 		if ((uap->flags & O_ACCMODE) == O_RDONLY) {
479 			fdclose(fdp, fp, fd, td);
480 			fdrop(fp, td);
481 			return (EINVAL);
482 		}
483 		shmfd = shm_alloc(td->td_ucred, cmode);
484 	} else {
485 		path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
486 		error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
487 
488 		/* Require paths to start with a '/' character. */
489 		if (error == 0 && path[0] != '/')
490 			error = EINVAL;
491 		if (error) {
492 			fdclose(fdp, fp, fd, td);
493 			fdrop(fp, td);
494 			free(path, M_SHMFD);
495 			return (error);
496 		}
497 
498 		fnv = fnv_32_str(path, FNV1_32_INIT);
499 		sx_xlock(&shm_dict_lock);
500 		shmfd = shm_lookup(path, fnv);
501 		if (shmfd == NULL) {
502 			/* Object does not yet exist, create it if requested. */
503 			if (uap->flags & O_CREAT) {
504 				shmfd = shm_alloc(td->td_ucred, cmode);
505 				shm_insert(path, fnv, shmfd);
506 			} else {
507 				free(path, M_SHMFD);
508 				error = ENOENT;
509 			}
510 		} else {
511 			/*
512 			 * Object already exists, obtain a new
513 			 * reference if requested and permitted.
514 			 */
515 			free(path, M_SHMFD);
516 			if ((uap->flags & (O_CREAT | O_EXCL)) ==
517 			    (O_CREAT | O_EXCL))
518 				error = EEXIST;
519 			else {
520 #ifdef MAC
521 				error = mac_posixshm_check_open(td->td_ucred,
522 				    shmfd);
523 				if (error == 0)
524 #endif
525 				error = shm_access(shmfd, td->td_ucred,
526 				    FFLAGS(uap->flags & O_ACCMODE));
527 			}
528 
529 			/*
530 			 * Truncate the file back to zero length if
531 			 * O_TRUNC was specified and the object was
532 			 * opened with read/write.
533 			 */
534 			if (error == 0 &&
535 			    (uap->flags & (O_ACCMODE | O_TRUNC)) ==
536 			    (O_RDWR | O_TRUNC)) {
537 #ifdef MAC
538 				error = mac_posixshm_check_truncate(
539 					td->td_ucred, fp->f_cred, shmfd);
540 				if (error == 0)
541 #endif
542 					shm_dotruncate(shmfd, 0);
543 			}
544 			if (error == 0)
545 				shm_hold(shmfd);
546 		}
547 		sx_xunlock(&shm_dict_lock);
548 
549 		if (error) {
550 			fdclose(fdp, fp, fd, td);
551 			fdrop(fp, td);
552 			return (error);
553 		}
554 	}
555 
556 	finit(fp, FFLAGS(uap->flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
557 
558 	FILEDESC_XLOCK(fdp);
559 	if (fdp->fd_ofiles[fd] == fp)
560 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
561 	FILEDESC_XUNLOCK(fdp);
562 	td->td_retval[0] = fd;
563 	fdrop(fp, td);
564 
565 	return (0);
566 }
567 
568 int
569 shm_unlink(struct thread *td, struct shm_unlink_args *uap)
570 {
571 	char *path;
572 	Fnv32_t fnv;
573 	int error;
574 
575 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
576 	error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
577 	if (error) {
578 		free(path, M_TEMP);
579 		return (error);
580 	}
581 
582 	fnv = fnv_32_str(path, FNV1_32_INIT);
583 	sx_xlock(&shm_dict_lock);
584 	error = shm_remove(path, fnv, td->td_ucred);
585 	sx_xunlock(&shm_dict_lock);
586 	free(path, M_TEMP);
587 
588 	return (error);
589 }
590 
591 /*
592  * mmap() helper to validate mmap() requests against shm object state
593  * and give mmap() the vm_object to use for the mapping.
594  */
595 int
596 shm_mmap(struct shmfd *shmfd, vm_size_t objsize, vm_ooffset_t foff,
597     vm_object_t *obj)
598 {
599 
600 	/*
601 	 * XXXRW: This validation is probably insufficient, and subject to
602 	 * sign errors.  It should be fixed.
603 	 */
604 	if (foff >= shmfd->shm_size || foff + objsize > shmfd->shm_size)
605 		return (EINVAL);
606 
607 	mtx_lock(&shm_timestamp_lock);
608 	vfs_timestamp(&shmfd->shm_atime);
609 	mtx_unlock(&shm_timestamp_lock);
610 	vm_object_reference(shmfd->shm_object);
611 	*obj = shmfd->shm_object;
612 	return (0);
613 }
614