Kirill A. Shutemov | 64c349f | 2017-11-17 15:31:22 -0800 | [diff] [blame] | 1 | #include <linux/kernel.h> |
| 2 | #include <linux/mm.h> |
| 3 | #include <linux/slab.h> |
| 4 | #include <linux/uaccess.h> |
| 5 | #include <linux/ktime.h> |
| 6 | #include <linux/debugfs.h> |
| 7 | |
| 8 | #define GUP_FAST_BENCHMARK _IOWR('g', 1, struct gup_benchmark) |
| 9 | |
| 10 | struct gup_benchmark { |
| 11 | __u64 delta_usec; |
| 12 | __u64 addr; |
| 13 | __u64 size; |
| 14 | __u32 nr_pages_per_call; |
| 15 | __u32 flags; |
| 16 | }; |
| 17 | |
| 18 | static int __gup_benchmark_ioctl(unsigned int cmd, |
| 19 | struct gup_benchmark *gup) |
| 20 | { |
| 21 | ktime_t start_time, end_time; |
| 22 | unsigned long i, nr, nr_pages, addr, next; |
| 23 | struct page **pages; |
| 24 | |
| 25 | nr_pages = gup->size / PAGE_SIZE; |
| 26 | pages = kvmalloc(sizeof(void *) * nr_pages, GFP_KERNEL); |
| 27 | if (!pages) |
| 28 | return -ENOMEM; |
| 29 | |
| 30 | i = 0; |
| 31 | nr = gup->nr_pages_per_call; |
| 32 | start_time = ktime_get(); |
| 33 | for (addr = gup->addr; addr < gup->addr + gup->size; addr = next) { |
| 34 | if (nr != gup->nr_pages_per_call) |
| 35 | break; |
| 36 | |
| 37 | next = addr + nr * PAGE_SIZE; |
| 38 | if (next > gup->addr + gup->size) { |
| 39 | next = gup->addr + gup->size; |
| 40 | nr = (next - addr) / PAGE_SIZE; |
| 41 | } |
| 42 | |
| 43 | nr = get_user_pages_fast(addr, nr, gup->flags & 1, pages + i); |
| 44 | i += nr; |
| 45 | } |
| 46 | end_time = ktime_get(); |
| 47 | |
| 48 | gup->delta_usec = ktime_us_delta(end_time, start_time); |
| 49 | gup->size = addr - gup->addr; |
| 50 | |
| 51 | for (i = 0; i < nr_pages; i++) { |
| 52 | if (!pages[i]) |
| 53 | break; |
| 54 | put_page(pages[i]); |
| 55 | } |
| 56 | |
| 57 | kvfree(pages); |
| 58 | return 0; |
| 59 | } |
| 60 | |
| 61 | static long gup_benchmark_ioctl(struct file *filep, unsigned int cmd, |
| 62 | unsigned long arg) |
| 63 | { |
| 64 | struct gup_benchmark gup; |
| 65 | int ret; |
| 66 | |
| 67 | if (cmd != GUP_FAST_BENCHMARK) |
| 68 | return -EINVAL; |
| 69 | |
| 70 | if (copy_from_user(&gup, (void __user *)arg, sizeof(gup))) |
| 71 | return -EFAULT; |
| 72 | |
| 73 | ret = __gup_benchmark_ioctl(cmd, &gup); |
| 74 | if (ret) |
| 75 | return ret; |
| 76 | |
| 77 | if (copy_to_user((void __user *)arg, &gup, sizeof(gup))) |
| 78 | return -EFAULT; |
| 79 | |
| 80 | return 0; |
| 81 | } |
| 82 | |
| 83 | static const struct file_operations gup_benchmark_fops = { |
| 84 | .open = nonseekable_open, |
| 85 | .unlocked_ioctl = gup_benchmark_ioctl, |
| 86 | }; |
| 87 | |
| 88 | static int gup_benchmark_init(void) |
| 89 | { |
| 90 | void *ret; |
| 91 | |
| 92 | ret = debugfs_create_file_unsafe("gup_benchmark", 0600, NULL, NULL, |
| 93 | &gup_benchmark_fops); |
| 94 | if (!ret) |
| 95 | pr_warn("Failed to create gup_benchmark in debugfs"); |
| 96 | |
| 97 | return 0; |
| 98 | } |
| 99 | |
| 100 | late_initcall(gup_benchmark_init); |