xref: /freebsd/sys/kern/uipc_shm.c (revision 1669d8afc64812c8d2d1d147ae1fd42ff441e1b1)
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 	vfs_timestamp(&shmfd->shm_birthtime);
323 	shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
324 	    shmfd->shm_birthtime;
325 	refcount_init(&shmfd->shm_refs, 1);
326 #ifdef MAC
327 	mac_posixshm_init(shmfd);
328 	mac_posixshm_create(ucred, shmfd);
329 #endif
330 
331 	return (shmfd);
332 }
333 
334 static struct shmfd *
335 shm_hold(struct shmfd *shmfd)
336 {
337 
338 	refcount_acquire(&shmfd->shm_refs);
339 	return (shmfd);
340 }
341 
342 static void
343 shm_drop(struct shmfd *shmfd)
344 {
345 
346 	if (refcount_release(&shmfd->shm_refs)) {
347 #ifdef MAC
348 		mac_posixshm_destroy(shmfd);
349 #endif
350 		vm_object_deallocate(shmfd->shm_object);
351 		free(shmfd, M_SHMFD);
352 	}
353 }
354 
355 /*
356  * Determine if the credentials have sufficient permissions for a
357  * specified combination of FREAD and FWRITE.
358  */
359 static int
360 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
361 {
362 	int acc_mode;
363 
364 	acc_mode = 0;
365 	if (flags & FREAD)
366 		acc_mode |= VREAD;
367 	if (flags & FWRITE)
368 		acc_mode |= VWRITE;
369 	return (vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
370 	    acc_mode, ucred, NULL));
371 }
372 
373 /*
374  * Dictionary management.  We maintain an in-kernel dictionary to map
375  * paths to shmfd objects.  We use the FNV hash on the path to store
376  * the mappings in a hash table.
377  */
378 static void
379 shm_dict_init(void *arg)
380 {
381 
382 	mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
383 	sx_init(&shm_dict_lock, "shm dictionary");
384 	shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
385 }
386 SYSINIT(shm_dict_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_dict_init, NULL);
387 
388 static struct shmfd *
389 shm_lookup(char *path, Fnv32_t fnv)
390 {
391 	struct shm_mapping *map;
392 
393 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
394 		if (map->sm_fnv != fnv)
395 			continue;
396 		if (strcmp(map->sm_path, path) == 0)
397 			return (map->sm_shmfd);
398 	}
399 
400 	return (NULL);
401 }
402 
403 static void
404 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
405 {
406 	struct shm_mapping *map;
407 
408 	map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
409 	map->sm_path = path;
410 	map->sm_fnv = fnv;
411 	map->sm_shmfd = shm_hold(shmfd);
412 	LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
413 }
414 
415 static int
416 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
417 {
418 	struct shm_mapping *map;
419 	int error;
420 
421 	LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
422 		if (map->sm_fnv != fnv)
423 			continue;
424 		if (strcmp(map->sm_path, path) == 0) {
425 #ifdef MAC
426 			error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
427 			if (error)
428 				return (error);
429 #endif
430 			error = shm_access(map->sm_shmfd, ucred,
431 			    FREAD | FWRITE);
432 			if (error)
433 				return (error);
434 			LIST_REMOVE(map, sm_link);
435 			shm_drop(map->sm_shmfd);
436 			free(map->sm_path, M_SHMFD);
437 			free(map, M_SHMFD);
438 			return (0);
439 		}
440 	}
441 
442 	return (ENOENT);
443 }
444 
445 /* System calls. */
446 int
447 shm_open(struct thread *td, struct shm_open_args *uap)
448 {
449 	struct filedesc *fdp;
450 	struct shmfd *shmfd;
451 	struct file *fp;
452 	char *path;
453 	Fnv32_t fnv;
454 	mode_t cmode;
455 	int fd, error;
456 
457 	if ((uap->flags & O_ACCMODE) != O_RDONLY &&
458 	    (uap->flags & O_ACCMODE) != O_RDWR)
459 		return (EINVAL);
460 
461 	if ((uap->flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) != 0)
462 		return (EINVAL);
463 
464 	fdp = td->td_proc->p_fd;
465 	cmode = (uap->mode & ~fdp->fd_cmask) & ACCESSPERMS;
466 
467 	error = falloc(td, &fp, &fd);
468 	if (error)
469 		return (error);
470 
471 	/* A SHM_ANON path pointer creates an anonymous object. */
472 	if (uap->path == SHM_ANON) {
473 		/* A read-only anonymous object is pointless. */
474 		if ((uap->flags & O_ACCMODE) == O_RDONLY) {
475 			fdclose(fdp, fp, fd, td);
476 			fdrop(fp, td);
477 			return (EINVAL);
478 		}
479 		shmfd = shm_alloc(td->td_ucred, cmode);
480 	} else {
481 		path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
482 		error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
483 
484 		/* Require paths to start with a '/' character. */
485 		if (error == 0 && path[0] != '/')
486 			error = EINVAL;
487 		if (error) {
488 			fdclose(fdp, fp, fd, td);
489 			fdrop(fp, td);
490 			free(path, M_SHMFD);
491 			return (error);
492 		}
493 
494 		fnv = fnv_32_str(path, FNV1_32_INIT);
495 		sx_xlock(&shm_dict_lock);
496 		shmfd = shm_lookup(path, fnv);
497 		if (shmfd == NULL) {
498 			/* Object does not yet exist, create it if requested. */
499 			if (uap->flags & O_CREAT) {
500 				shmfd = shm_alloc(td->td_ucred, cmode);
501 				shm_insert(path, fnv, shmfd);
502 			} else {
503 				free(path, M_SHMFD);
504 				error = ENOENT;
505 			}
506 		} else {
507 			/*
508 			 * Object already exists, obtain a new
509 			 * reference if requested and permitted.
510 			 */
511 			free(path, M_SHMFD);
512 			if ((uap->flags & (O_CREAT | O_EXCL)) ==
513 			    (O_CREAT | O_EXCL))
514 				error = EEXIST;
515 			else {
516 #ifdef MAC
517 				error = mac_posixshm_check_open(td->td_ucred,
518 				    shmfd);
519 				if (error == 0)
520 #endif
521 				error = shm_access(shmfd, td->td_ucred,
522 				    FFLAGS(uap->flags & O_ACCMODE));
523 			}
524 
525 			/*
526 			 * Truncate the file back to zero length if
527 			 * O_TRUNC was specified and the object was
528 			 * opened with read/write.
529 			 */
530 			if (error == 0 &&
531 			    (uap->flags & (O_ACCMODE | O_TRUNC)) ==
532 			    (O_RDWR | O_TRUNC)) {
533 #ifdef MAC
534 				error = mac_posixshm_check_truncate(
535 					td->td_ucred, fp->f_cred, shmfd);
536 				if (error == 0)
537 #endif
538 					shm_dotruncate(shmfd, 0);
539 			}
540 			if (error == 0)
541 				shm_hold(shmfd);
542 		}
543 		sx_xunlock(&shm_dict_lock);
544 
545 		if (error) {
546 			fdclose(fdp, fp, fd, td);
547 			fdrop(fp, td);
548 			return (error);
549 		}
550 	}
551 
552 	finit(fp, FFLAGS(uap->flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
553 
554 	FILEDESC_XLOCK(fdp);
555 	if (fdp->fd_ofiles[fd] == fp)
556 		fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
557 	FILEDESC_XUNLOCK(fdp);
558 	td->td_retval[0] = fd;
559 	fdrop(fp, td);
560 
561 	return (0);
562 }
563 
564 int
565 shm_unlink(struct thread *td, struct shm_unlink_args *uap)
566 {
567 	char *path;
568 	Fnv32_t fnv;
569 	int error;
570 
571 	path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
572 	error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
573 	if (error) {
574 		free(path, M_TEMP);
575 		return (error);
576 	}
577 
578 	fnv = fnv_32_str(path, FNV1_32_INIT);
579 	sx_xlock(&shm_dict_lock);
580 	error = shm_remove(path, fnv, td->td_ucred);
581 	sx_xunlock(&shm_dict_lock);
582 	free(path, M_TEMP);
583 
584 	return (error);
585 }
586 
587 /*
588  * mmap() helper to validate mmap() requests against shm object state
589  * and give mmap() the vm_object to use for the mapping.
590  */
591 int
592 shm_mmap(struct shmfd *shmfd, vm_size_t objsize, vm_ooffset_t foff,
593     vm_object_t *obj)
594 {
595 
596 	/*
597 	 * XXXRW: This validation is probably insufficient, and subject to
598 	 * sign errors.  It should be fixed.
599 	 */
600 	if (foff >= shmfd->shm_size || foff + objsize > shmfd->shm_size)
601 		return (EINVAL);
602 
603 	mtx_lock(&shm_timestamp_lock);
604 	vfs_timestamp(&shmfd->shm_atime);
605 	mtx_unlock(&shm_timestamp_lock);
606 	vm_object_reference(shmfd->shm_object);
607 	*obj = shmfd->shm_object;
608 	return (0);
609 }
610