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