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