]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/uipc_shm.c
MFC 228509,228620,228533:
[FreeBSD/stable/8.git] / sys / kern / uipc_shm.c
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_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_pager.h>
90 #include <vm/swap_pager.h>
91
92 struct shm_mapping {
93         char            *sm_path;
94         Fnv32_t         sm_fnv;
95         struct shmfd    *sm_shmfd;
96         LIST_ENTRY(shm_mapping) sm_link;
97 };
98
99 static MALLOC_DEFINE(M_SHMFD, "shmfd", "shared memory file descriptor");
100 static LIST_HEAD(, shm_mapping) *shm_dictionary;
101 static struct sx shm_dict_lock;
102 static struct mtx shm_timestamp_lock;
103 static u_long shm_hash;
104
105 #define SHM_HASH(fnv)   (&shm_dictionary[(fnv) & shm_hash])
106
107 static int      shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags);
108 static struct shmfd *shm_alloc(struct ucred *ucred, mode_t mode);
109 static void     shm_dict_init(void *arg);
110 static void     shm_drop(struct shmfd *shmfd);
111 static struct shmfd *shm_hold(struct shmfd *shmfd);
112 static void     shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd);
113 static struct shmfd *shm_lookup(char *path, Fnv32_t fnv);
114 static int      shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred);
115 static int      shm_dotruncate(struct shmfd *shmfd, off_t length);
116
117 static fo_rdwr_t        shm_read;
118 static fo_rdwr_t        shm_write;
119 static fo_truncate_t    shm_truncate;
120 static fo_ioctl_t       shm_ioctl;
121 static fo_poll_t        shm_poll;
122 static fo_kqfilter_t    shm_kqfilter;
123 static fo_stat_t        shm_stat;
124 static fo_close_t       shm_close;
125
126 /* File descriptor operations. */
127 static struct fileops shm_ops = {
128         .fo_read = shm_read,
129         .fo_write = shm_write,
130         .fo_truncate = shm_truncate,
131         .fo_ioctl = shm_ioctl,
132         .fo_poll = shm_poll,
133         .fo_kqfilter = shm_kqfilter,
134         .fo_stat = shm_stat,
135         .fo_close = shm_close,
136         .fo_flags = DFLAG_PASSABLE
137 };
138
139 FEATURE(posix_shm, "POSIX shared memory");
140
141 static int
142 shm_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
143     int flags, struct thread *td)
144 {
145
146         return (EOPNOTSUPP);
147 }
148
149 static int
150 shm_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
151     int flags, struct thread *td)
152 {
153
154         return (EOPNOTSUPP);
155 }
156
157 static int
158 shm_truncate(struct file *fp, off_t length, struct ucred *active_cred,
159     struct thread *td)
160 {
161         struct shmfd *shmfd;
162 #ifdef MAC
163         int error;
164 #endif
165
166         shmfd = fp->f_data;
167 #ifdef MAC
168         error = mac_posixshm_check_truncate(active_cred, fp->f_cred, shmfd);
169         if (error)
170                 return (error);
171 #endif
172         return (shm_dotruncate(shmfd, length));
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 int
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         vm_ooffset_t delta;
253
254         object = shmfd->shm_object;
255         VM_OBJECT_LOCK(object);
256         if (length == shmfd->shm_size) {
257                 VM_OBJECT_UNLOCK(object);
258                 return (0);
259         }
260         nobjsize = OFF_TO_IDX(length + PAGE_MASK);
261
262         /* Are we shrinking?  If so, trim the end. */
263         if (length < shmfd->shm_size) {
264                 /*
265                  * Disallow any requests to shrink the size if this
266                  * object is mapped into the kernel.
267                  */
268                 if (shmfd->shm_kmappings > 0) {
269                         VM_OBJECT_UNLOCK(object);
270                         return (EBUSY);
271                 }
272                 delta = ptoa(object->size - nobjsize);
273
274                 /* Toss in memory pages. */
275                 if (nobjsize < object->size)
276                         vm_object_page_remove(object, nobjsize, object->size,
277                             FALSE);
278
279                 /* Toss pages from swap. */
280                 if (object->type == OBJT_SWAP)
281                         swap_pager_freespace(object, nobjsize, delta);
282
283                 /* Free the swap accounted for shm */
284                 swap_release_by_uid(delta, object->uip);
285                 object->charge -= delta;
286
287                 /*
288                  * If the last page is partially mapped, then zero out
289                  * the garbage at the end of the page.  See comments
290                  * in vnode_pager_setsize() for more details.
291                  *
292                  * XXXJHB: This handles in memory pages, but what about
293                  * a page swapped out to disk?
294                  */
295                 if ((length & PAGE_MASK) &&
296                     (m = vm_page_lookup(object, OFF_TO_IDX(length))) != NULL &&
297                     m->valid != 0) {
298                         int base = (int)length & PAGE_MASK;
299                         int size = PAGE_SIZE - base;
300
301                         pmap_zero_page_area(m, base, size);
302
303                         /*
304                          * Update the valid bits to reflect the blocks that
305                          * have been zeroed.  Some of these valid bits may
306                          * have already been set.
307                          */
308                         vm_page_set_valid(m, base, size);
309
310                         /*
311                          * Round "base" to the next block boundary so that the
312                          * dirty bit for a partially zeroed block is not
313                          * cleared.
314                          */
315                         base = roundup2(base, DEV_BSIZE);
316
317                         vm_page_lock_queues();
318                         vm_page_clear_dirty(m, base, PAGE_SIZE - base);
319                         vm_page_unlock_queues();
320                 } else if ((length & PAGE_MASK) &&
321                     __predict_false(object->cache != NULL)) {
322                         vm_page_cache_free(object, OFF_TO_IDX(length),
323                             nobjsize);
324                 }
325         } else {
326
327                 /* Attempt to reserve the swap */
328                 delta = ptoa(nobjsize - object->size);
329                 if (!swap_reserve_by_uid(delta, object->uip)) {
330                         VM_OBJECT_UNLOCK(object);
331                         return (ENOMEM);
332                 }
333                 object->charge += delta;
334         }
335         shmfd->shm_size = length;
336         mtx_lock(&shm_timestamp_lock);
337         vfs_timestamp(&shmfd->shm_ctime);
338         shmfd->shm_mtime = shmfd->shm_ctime;
339         mtx_unlock(&shm_timestamp_lock);
340         object->size = nobjsize;
341         VM_OBJECT_UNLOCK(object);
342         return (0);
343 }
344
345 /*
346  * shmfd object management including creation and reference counting
347  * routines.
348  */
349 static struct shmfd *
350 shm_alloc(struct ucred *ucred, mode_t mode)
351 {
352         struct shmfd *shmfd;
353
354         shmfd = malloc(sizeof(*shmfd), M_SHMFD, M_WAITOK | M_ZERO);
355         shmfd->shm_size = 0;
356         shmfd->shm_uid = ucred->cr_uid;
357         shmfd->shm_gid = ucred->cr_gid;
358         shmfd->shm_mode = mode;
359         shmfd->shm_object = vm_pager_allocate(OBJT_DEFAULT, NULL,
360             shmfd->shm_size, VM_PROT_DEFAULT, 0, ucred);
361         KASSERT(shmfd->shm_object != NULL, ("shm_create: vm_pager_allocate"));
362         VM_OBJECT_LOCK(shmfd->shm_object);
363         vm_object_clear_flag(shmfd->shm_object, OBJ_ONEMAPPING);
364         vm_object_set_flag(shmfd->shm_object, OBJ_NOSPLIT);
365         VM_OBJECT_UNLOCK(shmfd->shm_object);
366         vfs_timestamp(&shmfd->shm_birthtime);
367         shmfd->shm_atime = shmfd->shm_mtime = shmfd->shm_ctime =
368             shmfd->shm_birthtime;
369         refcount_init(&shmfd->shm_refs, 1);
370 #ifdef MAC
371         mac_posixshm_init(shmfd);
372         mac_posixshm_create(ucred, shmfd);
373 #endif
374
375         return (shmfd);
376 }
377
378 static struct shmfd *
379 shm_hold(struct shmfd *shmfd)
380 {
381
382         refcount_acquire(&shmfd->shm_refs);
383         return (shmfd);
384 }
385
386 static void
387 shm_drop(struct shmfd *shmfd)
388 {
389
390         if (refcount_release(&shmfd->shm_refs)) {
391 #ifdef MAC
392                 mac_posixshm_destroy(shmfd);
393 #endif
394                 vm_object_deallocate(shmfd->shm_object);
395                 free(shmfd, M_SHMFD);
396         }
397 }
398
399 /*
400  * Determine if the credentials have sufficient permissions for a
401  * specified combination of FREAD and FWRITE.
402  */
403 static int
404 shm_access(struct shmfd *shmfd, struct ucred *ucred, int flags)
405 {
406         accmode_t accmode;
407
408         accmode = 0;
409         if (flags & FREAD)
410                 accmode |= VREAD;
411         if (flags & FWRITE)
412                 accmode |= VWRITE;
413         return (vaccess(VREG, shmfd->shm_mode, shmfd->shm_uid, shmfd->shm_gid,
414             accmode, ucred, NULL));
415 }
416
417 /*
418  * Dictionary management.  We maintain an in-kernel dictionary to map
419  * paths to shmfd objects.  We use the FNV hash on the path to store
420  * the mappings in a hash table.
421  */
422 static void
423 shm_dict_init(void *arg)
424 {
425
426         mtx_init(&shm_timestamp_lock, "shm timestamps", NULL, MTX_DEF);
427         sx_init(&shm_dict_lock, "shm dictionary");
428         shm_dictionary = hashinit(1024, M_SHMFD, &shm_hash);
429 }
430 SYSINIT(shm_dict_init, SI_SUB_SYSV_SHM, SI_ORDER_ANY, shm_dict_init, NULL);
431
432 static struct shmfd *
433 shm_lookup(char *path, Fnv32_t fnv)
434 {
435         struct shm_mapping *map;
436
437         LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
438                 if (map->sm_fnv != fnv)
439                         continue;
440                 if (strcmp(map->sm_path, path) == 0)
441                         return (map->sm_shmfd);
442         }
443
444         return (NULL);
445 }
446
447 static void
448 shm_insert(char *path, Fnv32_t fnv, struct shmfd *shmfd)
449 {
450         struct shm_mapping *map;
451
452         map = malloc(sizeof(struct shm_mapping), M_SHMFD, M_WAITOK);
453         map->sm_path = path;
454         map->sm_fnv = fnv;
455         map->sm_shmfd = shm_hold(shmfd);
456         LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
457 }
458
459 static int
460 shm_remove(char *path, Fnv32_t fnv, struct ucred *ucred)
461 {
462         struct shm_mapping *map;
463         int error;
464
465         LIST_FOREACH(map, SHM_HASH(fnv), sm_link) {
466                 if (map->sm_fnv != fnv)
467                         continue;
468                 if (strcmp(map->sm_path, path) == 0) {
469 #ifdef MAC
470                         error = mac_posixshm_check_unlink(ucred, map->sm_shmfd);
471                         if (error)
472                                 return (error);
473 #endif
474                         error = shm_access(map->sm_shmfd, ucred,
475                             FREAD | FWRITE);
476                         if (error)
477                                 return (error);
478                         LIST_REMOVE(map, sm_link);
479                         shm_drop(map->sm_shmfd);
480                         free(map->sm_path, M_SHMFD);
481                         free(map, M_SHMFD);
482                         return (0);
483                 }
484         }
485
486         return (ENOENT);
487 }
488
489 /* System calls. */
490 int
491 shm_open(struct thread *td, struct shm_open_args *uap)
492 {
493         struct filedesc *fdp;
494         struct shmfd *shmfd;
495         struct file *fp;
496         char *path;
497         Fnv32_t fnv;
498         mode_t cmode;
499         int fd, error;
500
501         if ((uap->flags & O_ACCMODE) != O_RDONLY &&
502             (uap->flags & O_ACCMODE) != O_RDWR)
503                 return (EINVAL);
504
505         if ((uap->flags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) != 0)
506                 return (EINVAL);
507
508         fdp = td->td_proc->p_fd;
509         cmode = (uap->mode & ~fdp->fd_cmask) & ACCESSPERMS;
510
511         error = falloc(td, &fp, &fd);
512         if (error)
513                 return (error);
514
515         /* A SHM_ANON path pointer creates an anonymous object. */
516         if (uap->path == SHM_ANON) {
517                 /* A read-only anonymous object is pointless. */
518                 if ((uap->flags & O_ACCMODE) == O_RDONLY) {
519                         fdclose(fdp, fp, fd, td);
520                         fdrop(fp, td);
521                         return (EINVAL);
522                 }
523                 shmfd = shm_alloc(td->td_ucred, cmode);
524         } else {
525                 path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK);
526                 error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
527
528                 /* Require paths to start with a '/' character. */
529                 if (error == 0 && path[0] != '/')
530                         error = EINVAL;
531                 if (error) {
532                         fdclose(fdp, fp, fd, td);
533                         fdrop(fp, td);
534                         free(path, M_SHMFD);
535                         return (error);
536                 }
537
538                 fnv = fnv_32_str(path, FNV1_32_INIT);
539                 sx_xlock(&shm_dict_lock);
540                 shmfd = shm_lookup(path, fnv);
541                 if (shmfd == NULL) {
542                         /* Object does not yet exist, create it if requested. */
543                         if (uap->flags & O_CREAT) {
544                                 shmfd = shm_alloc(td->td_ucred, cmode);
545                                 shm_insert(path, fnv, shmfd);
546                         } else {
547                                 free(path, M_SHMFD);
548                                 error = ENOENT;
549                         }
550                 } else {
551                         /*
552                          * Object already exists, obtain a new
553                          * reference if requested and permitted.
554                          */
555                         free(path, M_SHMFD);
556                         if ((uap->flags & (O_CREAT | O_EXCL)) ==
557                             (O_CREAT | O_EXCL))
558                                 error = EEXIST;
559                         else {
560 #ifdef MAC
561                                 error = mac_posixshm_check_open(td->td_ucred,
562                                     shmfd);
563                                 if (error == 0)
564 #endif
565                                 error = shm_access(shmfd, td->td_ucred,
566                                     FFLAGS(uap->flags & O_ACCMODE));
567                         }
568
569                         /*
570                          * Truncate the file back to zero length if
571                          * O_TRUNC was specified and the object was
572                          * opened with read/write.
573                          */
574                         if (error == 0 &&
575                             (uap->flags & (O_ACCMODE | O_TRUNC)) ==
576                             (O_RDWR | O_TRUNC)) {
577 #ifdef MAC
578                                 error = mac_posixshm_check_truncate(
579                                         td->td_ucred, fp->f_cred, shmfd);
580                                 if (error == 0)
581 #endif
582                                         shm_dotruncate(shmfd, 0);
583                         }
584                         if (error == 0)
585                                 shm_hold(shmfd);
586                 }
587                 sx_xunlock(&shm_dict_lock);
588
589                 if (error) {
590                         fdclose(fdp, fp, fd, td);
591                         fdrop(fp, td);
592                         return (error);
593                 }
594         }
595
596         finit(fp, FFLAGS(uap->flags & O_ACCMODE), DTYPE_SHM, shmfd, &shm_ops);
597
598         FILEDESC_XLOCK(fdp);
599         if (fdp->fd_ofiles[fd] == fp)
600                 fdp->fd_ofileflags[fd] |= UF_EXCLOSE;
601         FILEDESC_XUNLOCK(fdp);
602         td->td_retval[0] = fd;
603         fdrop(fp, td);
604
605         return (0);
606 }
607
608 int
609 shm_unlink(struct thread *td, struct shm_unlink_args *uap)
610 {
611         char *path;
612         Fnv32_t fnv;
613         int error;
614
615         path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
616         error = copyinstr(uap->path, path, MAXPATHLEN, NULL);
617         if (error) {
618                 free(path, M_TEMP);
619                 return (error);
620         }
621
622         fnv = fnv_32_str(path, FNV1_32_INIT);
623         sx_xlock(&shm_dict_lock);
624         error = shm_remove(path, fnv, td->td_ucred);
625         sx_xunlock(&shm_dict_lock);
626         free(path, M_TEMP);
627
628         return (error);
629 }
630
631 /*
632  * mmap() helper to validate mmap() requests against shm object state
633  * and give mmap() the vm_object to use for the mapping.
634  */
635 int
636 shm_mmap(struct shmfd *shmfd, vm_size_t objsize, vm_ooffset_t foff,
637     vm_object_t *obj)
638 {
639
640         /*
641          * XXXRW: This validation is probably insufficient, and subject to
642          * sign errors.  It should be fixed.
643          */
644         if (foff >= shmfd->shm_size ||
645             foff + objsize > round_page(shmfd->shm_size))
646                 return (EINVAL);
647
648         mtx_lock(&shm_timestamp_lock);
649         vfs_timestamp(&shmfd->shm_atime);
650         mtx_unlock(&shm_timestamp_lock);
651         vm_object_reference(shmfd->shm_object);
652         *obj = shmfd->shm_object;
653         return (0);
654 }
655
656 /*
657  * Helper routines to allow the backing object of a shared memory file
658  * descriptor to be mapped in the kernel.
659  */
660 int
661 shm_map(struct file *fp, size_t size, off_t offset, void **memp)
662 {
663         struct shmfd *shmfd;
664         vm_offset_t kva, ofs;
665         vm_object_t obj;
666         int rv;
667
668         if (fp->f_type != DTYPE_SHM)
669                 return (EINVAL);
670         shmfd = fp->f_data;
671         obj = shmfd->shm_object;
672         VM_OBJECT_LOCK(obj);
673         /*
674          * XXXRW: This validation is probably insufficient, and subject to
675          * sign errors.  It should be fixed.
676          */
677         if (offset >= shmfd->shm_size ||
678             offset + size > round_page(shmfd->shm_size)) {
679                 VM_OBJECT_UNLOCK(obj);
680                 return (EINVAL);
681         }
682
683         shmfd->shm_kmappings++;
684         vm_object_reference_locked(obj);
685         VM_OBJECT_UNLOCK(obj);
686
687         /* Map the object into the kernel_map and wire it. */
688         kva = vm_map_min(kernel_map);
689         ofs = offset & PAGE_MASK;
690         offset = trunc_page(offset);
691         size = round_page(size + ofs);
692         rv = vm_map_find(kernel_map, obj, offset, &kva, size,
693             VMFS_ALIGNED_SPACE, VM_PROT_READ | VM_PROT_WRITE,
694             VM_PROT_READ | VM_PROT_WRITE, 0);
695         if (rv == KERN_SUCCESS) {
696                 rv = vm_map_wire(kernel_map, kva, kva + size,
697                     VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
698                 if (rv == KERN_SUCCESS) {
699                         *memp = (void *)(kva + ofs);
700                         return (0);
701                 }
702                 vm_map_remove(kernel_map, kva, kva + size);
703         } else
704                 vm_object_deallocate(obj);
705
706         /* On failure, drop our mapping reference. */
707         VM_OBJECT_LOCK(obj);
708         shmfd->shm_kmappings--;
709         VM_OBJECT_UNLOCK(obj);
710
711         return (vm_mmap_to_errno(rv));
712 }
713
714 /*
715  * We require the caller to unmap the entire entry.  This allows us to
716  * safely decrement shm_kmappings when a mapping is removed.
717  */
718 int
719 shm_unmap(struct file *fp, void *mem, size_t size)
720 {
721         struct shmfd *shmfd;
722         vm_map_entry_t entry;
723         vm_offset_t kva, ofs;
724         vm_object_t obj;
725         vm_pindex_t pindex;
726         vm_prot_t prot;
727         boolean_t wired;
728         vm_map_t map;
729         int rv;
730
731         if (fp->f_type != DTYPE_SHM)
732                 return (EINVAL);
733         shmfd = fp->f_data;
734         kva = (vm_offset_t)mem;
735         ofs = kva & PAGE_MASK;
736         kva = trunc_page(kva);
737         size = round_page(size + ofs);
738         map = kernel_map;
739         rv = vm_map_lookup(&map, kva, VM_PROT_READ | VM_PROT_WRITE, &entry,
740             &obj, &pindex, &prot, &wired);
741         if (rv != KERN_SUCCESS)
742                 return (EINVAL);
743         if (entry->start != kva || entry->end != kva + size) {
744                 vm_map_lookup_done(map, entry);
745                 return (EINVAL);
746         }
747         vm_map_lookup_done(map, entry);
748         if (obj != shmfd->shm_object)
749                 return (EINVAL);
750         vm_map_remove(map, kva, kva + size);
751         VM_OBJECT_LOCK(obj);
752         KASSERT(shmfd->shm_kmappings > 0, ("shm_unmap: object not mapped"));
753         shmfd->shm_kmappings--;
754         VM_OBJECT_UNLOCK(obj);
755         return (0);
756 }