3 * Anonymous Shared Memory Subsystem, ashmem
5 * Copyright (C) 2008 Google, Inc.
7 * Robert Love <rlove@google.com>
9 * This software is licensed under the terms of the GNU General Public
10 * License version 2, as published by the Free Software Foundation, and
11 * may be copied, distributed, and modified under those terms.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
19 #define pr_fmt(fmt) "ashmem: " fmt
21 #include <linux/module.h>
22 #include <linux/file.h>
24 #include <linux/falloc.h>
25 #include <linux/miscdevice.h>
26 #include <linux/security.h>
28 #include <linux/mman.h>
29 #include <linux/uaccess.h>
30 #include <linux/personality.h>
31 #include <linux/bitops.h>
32 #include <linux/mutex.h>
33 #include <linux/shmem_fs.h>
36 #define ASHMEM_NAME_PREFIX "dev/ashmem/"
37 #define ASHMEM_NAME_PREFIX_LEN (sizeof(ASHMEM_NAME_PREFIX) - 1)
38 #define ASHMEM_FULL_NAME_LEN (ASHMEM_NAME_LEN + ASHMEM_NAME_PREFIX_LEN)
41 * ashmem_area - anonymous shared memory area
42 * Lifecycle: From our parent file's open() until its release()
43 * Locking: Protected by `ashmem_mutex'
44 * Big Note: Mappings do NOT pin this structure; it dies on close()
47 char name[ASHMEM_FULL_NAME_LEN]; /* optional name in /proc/pid/maps */
48 struct list_head unpinned_list; /* list of all ashmem areas */
49 struct file *file; /* the shmem-based backing file */
50 size_t size; /* size of the mapping, in bytes */
51 unsigned long prot_mask; /* allowed prot bits, as vm_flags */
55 * ashmem_range - represents an interval of unpinned (evictable) pages
56 * Lifecycle: From unpin to pin
57 * Locking: Protected by `ashmem_mutex'
60 struct list_head lru; /* entry in LRU list */
61 struct list_head unpinned; /* entry in its area's unpinned list */
62 struct ashmem_area *asma; /* associated area */
63 size_t pgstart; /* starting page, inclusive */
64 size_t pgend; /* ending page, inclusive */
65 unsigned int purged; /* ASHMEM_NOT or ASHMEM_WAS_PURGED */
68 /* LRU list of unpinned pages, protected by ashmem_mutex */
69 static LIST_HEAD(ashmem_lru_list);
71 /* Count of pages on our LRU list, protected by ashmem_mutex */
72 static unsigned long lru_count;
75 * ashmem_mutex - protects the list of and each individual ashmem_area
77 * Lock Ordering: ashmex_mutex -> i_mutex -> i_alloc_sem
79 static DEFINE_MUTEX(ashmem_mutex);
81 static struct kmem_cache *ashmem_area_cachep __read_mostly;
82 static struct kmem_cache *ashmem_range_cachep __read_mostly;
84 #define range_size(range) \
85 ((range)->pgend - (range)->pgstart + 1)
87 #define range_on_lru(range) \
88 ((range)->purged == ASHMEM_NOT_PURGED)
90 #define page_range_subsumes_range(range, start, end) \
91 (((range)->pgstart >= (start)) && ((range)->pgend <= (end)))
93 #define page_range_subsumed_by_range(range, start, end) \
94 (((range)->pgstart <= (start)) && ((range)->pgend >= (end)))
96 #define page_in_range(range, page) \
97 (((range)->pgstart <= (page)) && ((range)->pgend >= (page)))
99 #define page_range_in_range(range, start, end) \
100 (page_in_range(range, start) || page_in_range(range, end) || \
101 page_range_subsumes_range(range, start, end))
103 #define range_before_page(range, page) \
104 ((range)->pgend < (page))
106 #define PROT_MASK (PROT_EXEC | PROT_READ | PROT_WRITE)
108 static inline void lru_add(struct ashmem_range *range)
110 list_add_tail(&range->lru, &ashmem_lru_list);
111 lru_count += range_size(range);
114 static inline void lru_del(struct ashmem_range *range)
116 list_del(&range->lru);
117 lru_count -= range_size(range);
121 * range_alloc - allocate and initialize a new ashmem_range structure
123 * 'asma' - associated ashmem_area
124 * 'prev_range' - the previous ashmem_range in the sorted asma->unpinned list
125 * 'purged' - initial purge value (ASMEM_NOT_PURGED or ASHMEM_WAS_PURGED)
126 * 'start' - starting page, inclusive
127 * 'end' - ending page, inclusive
129 * Caller must hold ashmem_mutex.
131 static int range_alloc(struct ashmem_area *asma,
132 struct ashmem_range *prev_range, unsigned int purged,
133 size_t start, size_t end)
135 struct ashmem_range *range;
137 range = kmem_cache_zalloc(ashmem_range_cachep, GFP_KERNEL);
138 if (unlikely(!range))
142 range->pgstart = start;
144 range->purged = purged;
146 list_add_tail(&range->unpinned, &prev_range->unpinned);
148 if (range_on_lru(range))
154 static void range_del(struct ashmem_range *range)
156 list_del(&range->unpinned);
157 if (range_on_lru(range))
159 kmem_cache_free(ashmem_range_cachep, range);
163 * range_shrink - shrinks a range
165 * Caller must hold ashmem_mutex.
167 static inline void range_shrink(struct ashmem_range *range,
168 size_t start, size_t end)
170 size_t pre = range_size(range);
172 range->pgstart = start;
175 if (range_on_lru(range))
176 lru_count -= pre - range_size(range);
179 static int ashmem_open(struct inode *inode, struct file *file)
181 struct ashmem_area *asma;
184 ret = generic_file_open(inode, file);
188 asma = kmem_cache_zalloc(ashmem_area_cachep, GFP_KERNEL);
192 INIT_LIST_HEAD(&asma->unpinned_list);
193 memcpy(asma->name, ASHMEM_NAME_PREFIX, ASHMEM_NAME_PREFIX_LEN);
194 asma->prot_mask = PROT_MASK;
195 file->private_data = asma;
200 static int ashmem_release(struct inode *ignored, struct file *file)
202 struct ashmem_area *asma = file->private_data;
203 struct ashmem_range *range, *next;
205 mutex_lock(&ashmem_mutex);
206 list_for_each_entry_safe(range, next, &asma->unpinned_list, unpinned)
208 mutex_unlock(&ashmem_mutex);
212 kmem_cache_free(ashmem_area_cachep, asma);
217 static ssize_t ashmem_read(struct file *file, char __user *buf,
218 size_t len, loff_t *pos)
220 struct ashmem_area *asma = file->private_data;
223 mutex_lock(&ashmem_mutex);
225 /* If size is not set, or set to 0, always return EOF. */
234 mutex_unlock(&ashmem_mutex);
237 * asma and asma->file are used outside the lock here. We assume
238 * once asma->file is set it will never be changed, and will not
239 * be destroyed until all references to the file are dropped and
240 * ashmem_release is called.
242 ret = asma->file->f_op->read(asma->file, buf, len, pos);
244 /** Update backing file pos, since f_ops->read() doesn't */
245 asma->file->f_pos = *pos;
250 mutex_unlock(&ashmem_mutex);
254 static loff_t ashmem_llseek(struct file *file, loff_t offset, int origin)
256 struct ashmem_area *asma = file->private_data;
259 mutex_lock(&ashmem_mutex);
261 if (asma->size == 0) {
271 ret = asma->file->f_op->llseek(asma->file, offset, origin);
275 /** Copy f_pos from backing file, since f_ops->llseek() sets it */
276 file->f_pos = asma->file->f_pos;
279 mutex_unlock(&ashmem_mutex);
283 static inline vm_flags_t calc_vm_may_flags(unsigned long prot)
285 return _calc_vm_trans(prot, PROT_READ, VM_MAYREAD) |
286 _calc_vm_trans(prot, PROT_WRITE, VM_MAYWRITE) |
287 _calc_vm_trans(prot, PROT_EXEC, VM_MAYEXEC);
290 static int ashmem_mmap(struct file *file, struct vm_area_struct *vma)
292 struct ashmem_area *asma = file->private_data;
295 mutex_lock(&ashmem_mutex);
297 /* user needs to SET_SIZE before mapping */
298 if (unlikely(!asma->size)) {
303 /* requested protection bits must match our allowed protection mask */
304 if (unlikely((vma->vm_flags & ~calc_vm_prot_bits(asma->prot_mask)) &
305 calc_vm_prot_bits(PROT_MASK))) {
309 vma->vm_flags &= ~calc_vm_may_flags(~asma->prot_mask);
312 char *name = ASHMEM_NAME_DEF;
315 if (asma->name[ASHMEM_NAME_PREFIX_LEN] != '\0')
318 /* ... and allocate the backing shmem file */
319 vmfile = shmem_file_setup(name, asma->size, vma->vm_flags);
320 if (unlikely(IS_ERR(vmfile))) {
321 ret = PTR_ERR(vmfile);
326 get_file(asma->file);
328 if (vma->vm_flags & VM_SHARED)
329 shmem_set_file(vma, asma->file);
333 vma->vm_file = asma->file;
337 mutex_unlock(&ashmem_mutex);
342 * ashmem_shrink - our cache shrinker, called from mm/vmscan.c :: shrink_slab
344 * 'nr_to_scan' is the number of objects (pages) to prune, or 0 to query how
345 * many objects (pages) we have in total.
347 * 'gfp_mask' is the mask of the allocation that got us into this mess.
349 * Return value is the number of objects (pages) remaining, or -1 if we cannot
350 * proceed without risk of deadlock (due to gfp_mask).
352 * We approximate LRU via least-recently-unpinned, jettisoning unpinned partial
353 * chunks of ashmem regions LRU-wise one-at-a-time until we hit 'nr_to_scan'
356 static int ashmem_shrink(struct shrinker *s, struct shrink_control *sc)
358 struct ashmem_range *range, *next;
360 /* We might recurse into filesystem code, so bail out if necessary */
361 if (sc->nr_to_scan && !(sc->gfp_mask & __GFP_FS))
366 mutex_lock(&ashmem_mutex);
367 list_for_each_entry_safe(range, next, &ashmem_lru_list, lru) {
368 loff_t start = range->pgstart * PAGE_SIZE;
369 loff_t end = (range->pgend + 1) * PAGE_SIZE;
371 do_fallocate(range->asma->file,
372 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
374 range->purged = ASHMEM_WAS_PURGED;
377 sc->nr_to_scan -= range_size(range);
378 if (sc->nr_to_scan <= 0)
381 mutex_unlock(&ashmem_mutex);
386 static struct shrinker ashmem_shrinker = {
387 .shrink = ashmem_shrink,
388 .seeks = DEFAULT_SEEKS * 4,
391 static int set_prot_mask(struct ashmem_area *asma, unsigned long prot)
395 mutex_lock(&ashmem_mutex);
397 /* the user can only remove, not add, protection bits */
398 if (unlikely((asma->prot_mask & prot) != prot)) {
403 /* does the application expect PROT_READ to imply PROT_EXEC? */
404 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
407 asma->prot_mask = prot;
410 mutex_unlock(&ashmem_mutex);
414 static int set_name(struct ashmem_area *asma, void __user *name)
418 char local_name[ASHMEM_NAME_LEN];
421 * Holding the ashmem_mutex while doing a copy_from_user might cause
422 * an data abort which would try to access mmap_sem. If another
423 * thread has invoked ashmem_mmap then it will be holding the
424 * semaphore and will be waiting for ashmem_mutex, there by leading to
425 * deadlock. We'll release the mutex and take the name to a local
426 * variable that does not need protection and later copy the local
427 * variable to the structure member with lock held.
429 len = strncpy_from_user(local_name, name, ASHMEM_NAME_LEN);
432 if (len == ASHMEM_NAME_LEN)
433 local_name[ASHMEM_NAME_LEN - 1] = '\0';
434 mutex_lock(&ashmem_mutex);
435 /* cannot change an existing mapping's name */
436 if (unlikely(asma->file))
439 strcpy(asma->name + ASHMEM_NAME_PREFIX_LEN, local_name);
441 mutex_unlock(&ashmem_mutex);
445 static int get_name(struct ashmem_area *asma, void __user *name)
450 * Have a local variable to which we'll copy the content
451 * from asma with the lock held. Later we can copy this to the user
452 * space safely without holding any locks. So even if we proceed to
453 * wait for mmap_sem, it won't lead to deadlock.
455 char local_name[ASHMEM_NAME_LEN];
457 mutex_lock(&ashmem_mutex);
458 if (asma->name[ASHMEM_NAME_PREFIX_LEN] != '\0') {
461 * Copying only `len', instead of ASHMEM_NAME_LEN, bytes
462 * prevents us from revealing one user's stack to another.
464 len = strlen(asma->name + ASHMEM_NAME_PREFIX_LEN) + 1;
465 memcpy(local_name, asma->name + ASHMEM_NAME_PREFIX_LEN, len);
467 len = sizeof(ASHMEM_NAME_DEF);
468 memcpy(local_name, ASHMEM_NAME_DEF, len);
470 mutex_unlock(&ashmem_mutex);
473 * Now we are just copying from the stack variable to userland
476 if (unlikely(copy_to_user(name, local_name, len)))
482 * ashmem_pin - pin the given ashmem region, returning whether it was
483 * previously purged (ASHMEM_WAS_PURGED) or not (ASHMEM_NOT_PURGED).
485 * Caller must hold ashmem_mutex.
487 static int ashmem_pin(struct ashmem_area *asma, size_t pgstart, size_t pgend)
489 struct ashmem_range *range, *next;
490 int ret = ASHMEM_NOT_PURGED;
492 list_for_each_entry_safe(range, next, &asma->unpinned_list, unpinned) {
493 /* moved past last applicable page; we can short circuit */
494 if (range_before_page(range, pgstart))
498 * The user can ask us to pin pages that span multiple ranges,
499 * or to pin pages that aren't even unpinned, so this is messy.
502 * 1. The requested range subsumes an existing range, so we
503 * just remove the entire matching range.
504 * 2. The requested range overlaps the start of an existing
505 * range, so we just update that range.
506 * 3. The requested range overlaps the end of an existing
507 * range, so we just update that range.
508 * 4. The requested range punches a hole in an existing range,
509 * so we have to update one side of the range and then
510 * create a new range for the other side.
512 if (page_range_in_range(range, pgstart, pgend)) {
513 ret |= range->purged;
515 /* Case #1: Easy. Just nuke the whole thing. */
516 if (page_range_subsumes_range(range, pgstart, pgend)) {
521 /* Case #2: We overlap from the start, so adjust it */
522 if (range->pgstart >= pgstart) {
523 range_shrink(range, pgend + 1, range->pgend);
527 /* Case #3: We overlap from the rear, so adjust it */
528 if (range->pgend <= pgend) {
529 range_shrink(range, range->pgstart, pgstart-1);
534 * Case #4: We eat a chunk out of the middle. A bit
535 * more complicated, we allocate a new range for the
536 * second half and adjust the first chunk's endpoint.
538 range_alloc(asma, range, range->purged,
539 pgend + 1, range->pgend);
540 range_shrink(range, range->pgstart, pgstart - 1);
549 * ashmem_unpin - unpin the given range of pages. Returns zero on success.
551 * Caller must hold ashmem_mutex.
553 static int ashmem_unpin(struct ashmem_area *asma, size_t pgstart, size_t pgend)
555 struct ashmem_range *range, *next;
556 unsigned int purged = ASHMEM_NOT_PURGED;
559 list_for_each_entry_safe(range, next, &asma->unpinned_list, unpinned) {
560 /* short circuit: this is our insertion point */
561 if (range_before_page(range, pgstart))
565 * The user can ask us to unpin pages that are already entirely
566 * or partially pinned. We handle those two cases here.
568 if (page_range_subsumed_by_range(range, pgstart, pgend))
570 if (page_range_in_range(range, pgstart, pgend)) {
571 pgstart = min_t(size_t, range->pgstart, pgstart),
572 pgend = max_t(size_t, range->pgend, pgend);
573 purged |= range->purged;
579 return range_alloc(asma, range, purged, pgstart, pgend);
583 * ashmem_get_pin_status - Returns ASHMEM_IS_UNPINNED if _any_ pages in the
584 * given interval are unpinned and ASHMEM_IS_PINNED otherwise.
586 * Caller must hold ashmem_mutex.
588 static int ashmem_get_pin_status(struct ashmem_area *asma, size_t pgstart,
591 struct ashmem_range *range;
592 int ret = ASHMEM_IS_PINNED;
594 list_for_each_entry(range, &asma->unpinned_list, unpinned) {
595 if (range_before_page(range, pgstart))
597 if (page_range_in_range(range, pgstart, pgend)) {
598 ret = ASHMEM_IS_UNPINNED;
606 static int ashmem_pin_unpin(struct ashmem_area *asma, unsigned long cmd,
609 struct ashmem_pin pin;
610 size_t pgstart, pgend;
613 if (unlikely(!asma->file))
616 if (unlikely(copy_from_user(&pin, p, sizeof(pin))))
619 /* per custom, you can pass zero for len to mean "everything onward" */
621 pin.len = PAGE_ALIGN(asma->size) - pin.offset;
623 if (unlikely((pin.offset | pin.len) & ~PAGE_MASK))
626 if (unlikely(((__u32) -1) - pin.offset < pin.len))
629 if (unlikely(PAGE_ALIGN(asma->size) < pin.offset + pin.len))
632 pgstart = pin.offset / PAGE_SIZE;
633 pgend = pgstart + (pin.len / PAGE_SIZE) - 1;
635 mutex_lock(&ashmem_mutex);
639 ret = ashmem_pin(asma, pgstart, pgend);
642 ret = ashmem_unpin(asma, pgstart, pgend);
644 case ASHMEM_GET_PIN_STATUS:
645 ret = ashmem_get_pin_status(asma, pgstart, pgend);
649 mutex_unlock(&ashmem_mutex);
654 static long ashmem_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
656 struct ashmem_area *asma = file->private_data;
660 case ASHMEM_SET_NAME:
661 ret = set_name(asma, (void __user *) arg);
663 case ASHMEM_GET_NAME:
664 ret = get_name(asma, (void __user *) arg);
666 case ASHMEM_SET_SIZE:
670 asma->size = (size_t) arg;
673 case ASHMEM_GET_SIZE:
676 case ASHMEM_SET_PROT_MASK:
677 ret = set_prot_mask(asma, arg);
679 case ASHMEM_GET_PROT_MASK:
680 ret = asma->prot_mask;
684 case ASHMEM_GET_PIN_STATUS:
685 ret = ashmem_pin_unpin(asma, cmd, (void __user *) arg);
687 case ASHMEM_PURGE_ALL_CACHES:
689 if (capable(CAP_SYS_ADMIN)) {
690 struct shrink_control sc = {
691 .gfp_mask = GFP_KERNEL,
694 ret = ashmem_shrink(&ashmem_shrinker, &sc);
696 ashmem_shrink(&ashmem_shrinker, &sc);
704 /* support of 32bit userspace on 64bit platforms */
706 static long compat_ashmem_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
710 case COMPAT_ASHMEM_SET_SIZE:
711 cmd = ASHMEM_SET_SIZE;
713 case COMPAT_ASHMEM_SET_PROT_MASK:
714 cmd = ASHMEM_SET_PROT_MASK;
717 return ashmem_ioctl(file, cmd, arg);
721 static const struct file_operations ashmem_fops = {
722 .owner = THIS_MODULE,
724 .release = ashmem_release,
726 .llseek = ashmem_llseek,
728 .unlocked_ioctl = ashmem_ioctl,
730 .compat_ioctl = compat_ashmem_ioctl,
734 static struct miscdevice ashmem_misc = {
735 .minor = MISC_DYNAMIC_MINOR,
737 .fops = &ashmem_fops,
740 static int __init ashmem_init(void)
744 ashmem_area_cachep = kmem_cache_create("ashmem_area_cache",
745 sizeof(struct ashmem_area),
747 if (unlikely(!ashmem_area_cachep)) {
748 pr_err("failed to create slab cache\n");
752 ashmem_range_cachep = kmem_cache_create("ashmem_range_cache",
753 sizeof(struct ashmem_range),
755 if (unlikely(!ashmem_range_cachep)) {
756 pr_err("failed to create slab cache\n");
760 ret = misc_register(&ashmem_misc);
762 pr_err("failed to register misc device!\n");
766 register_shrinker(&ashmem_shrinker);
768 pr_info("initialized\n");
773 static void __exit ashmem_exit(void)
777 unregister_shrinker(&ashmem_shrinker);
779 ret = misc_deregister(&ashmem_misc);
781 pr_err("failed to unregister misc device!\n");
783 kmem_cache_destroy(ashmem_range_cachep);
784 kmem_cache_destroy(ashmem_area_cachep);
786 pr_info("unloaded\n");
789 module_init(ashmem_init);
790 module_exit(ashmem_exit);
792 MODULE_LICENSE("GPL");