bpf: rework memlock-based memory accounting for maps
[linux-2.6-microblaze.git] / kernel / bpf / stackmap.c
1 /* Copyright (c) 2016 Facebook
2  *
3  * This program is free software; you can redistribute it and/or
4  * modify it under the terms of version 2 of the GNU General Public
5  * License as published by the Free Software Foundation.
6  */
7 #include <linux/bpf.h>
8 #include <linux/jhash.h>
9 #include <linux/filter.h>
10 #include <linux/stacktrace.h>
11 #include <linux/perf_event.h>
12 #include <linux/elf.h>
13 #include <linux/pagemap.h>
14 #include <linux/irq_work.h>
15 #include "percpu_freelist.h"
16
17 #define STACK_CREATE_FLAG_MASK                                  \
18         (BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY |        \
19          BPF_F_STACK_BUILD_ID)
20
21 struct stack_map_bucket {
22         struct pcpu_freelist_node fnode;
23         u32 hash;
24         u32 nr;
25         u64 data[];
26 };
27
28 struct bpf_stack_map {
29         struct bpf_map map;
30         void *elems;
31         struct pcpu_freelist freelist;
32         u32 n_buckets;
33         struct stack_map_bucket *buckets[];
34 };
35
36 /* irq_work to run up_read() for build_id lookup in nmi context */
37 struct stack_map_irq_work {
38         struct irq_work irq_work;
39         struct rw_semaphore *sem;
40 };
41
42 static void do_up_read(struct irq_work *entry)
43 {
44         struct stack_map_irq_work *work;
45
46         work = container_of(entry, struct stack_map_irq_work, irq_work);
47         up_read_non_owner(work->sem);
48         work->sem = NULL;
49 }
50
51 static DEFINE_PER_CPU(struct stack_map_irq_work, up_read_work);
52
53 static inline bool stack_map_use_build_id(struct bpf_map *map)
54 {
55         return (map->map_flags & BPF_F_STACK_BUILD_ID);
56 }
57
58 static inline int stack_map_data_size(struct bpf_map *map)
59 {
60         return stack_map_use_build_id(map) ?
61                 sizeof(struct bpf_stack_build_id) : sizeof(u64);
62 }
63
64 static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)
65 {
66         u32 elem_size = sizeof(struct stack_map_bucket) + smap->map.value_size;
67         int err;
68
69         smap->elems = bpf_map_area_alloc(elem_size * smap->map.max_entries,
70                                          smap->map.numa_node);
71         if (!smap->elems)
72                 return -ENOMEM;
73
74         err = pcpu_freelist_init(&smap->freelist);
75         if (err)
76                 goto free_elems;
77
78         pcpu_freelist_populate(&smap->freelist, smap->elems, elem_size,
79                                smap->map.max_entries);
80         return 0;
81
82 free_elems:
83         bpf_map_area_free(smap->elems);
84         return err;
85 }
86
87 /* Called from syscall */
88 static struct bpf_map *stack_map_alloc(union bpf_attr *attr)
89 {
90         u32 value_size = attr->value_size;
91         struct bpf_stack_map *smap;
92         struct bpf_map_memory mem;
93         u64 cost, n_buckets;
94         int err;
95
96         if (!capable(CAP_SYS_ADMIN))
97                 return ERR_PTR(-EPERM);
98
99         if (attr->map_flags & ~STACK_CREATE_FLAG_MASK)
100                 return ERR_PTR(-EINVAL);
101
102         /* check sanity of attributes */
103         if (attr->max_entries == 0 || attr->key_size != 4 ||
104             value_size < 8 || value_size % 8)
105                 return ERR_PTR(-EINVAL);
106
107         BUILD_BUG_ON(sizeof(struct bpf_stack_build_id) % sizeof(u64));
108         if (attr->map_flags & BPF_F_STACK_BUILD_ID) {
109                 if (value_size % sizeof(struct bpf_stack_build_id) ||
110                     value_size / sizeof(struct bpf_stack_build_id)
111                     > sysctl_perf_event_max_stack)
112                         return ERR_PTR(-EINVAL);
113         } else if (value_size / 8 > sysctl_perf_event_max_stack)
114                 return ERR_PTR(-EINVAL);
115
116         /* hash table size must be power of 2 */
117         n_buckets = roundup_pow_of_two(attr->max_entries);
118
119         cost = n_buckets * sizeof(struct stack_map_bucket *) + sizeof(*smap);
120         if (cost >= U32_MAX - PAGE_SIZE)
121                 return ERR_PTR(-E2BIG);
122         cost += n_buckets * (value_size + sizeof(struct stack_map_bucket));
123         if (cost >= U32_MAX - PAGE_SIZE)
124                 return ERR_PTR(-E2BIG);
125
126         err = bpf_map_charge_init(&mem,
127                                   round_up(cost, PAGE_SIZE) >> PAGE_SHIFT);
128         if (err)
129                 return ERR_PTR(err);
130
131         smap = bpf_map_area_alloc(cost, bpf_map_attr_numa_node(attr));
132         if (!smap) {
133                 bpf_map_charge_finish(&mem);
134                 return ERR_PTR(-ENOMEM);
135         }
136
137         bpf_map_init_from_attr(&smap->map, attr);
138         smap->map.value_size = value_size;
139         smap->n_buckets = n_buckets;
140
141         err = get_callchain_buffers(sysctl_perf_event_max_stack);
142         if (err)
143                 goto free_charge;
144
145         err = prealloc_elems_and_freelist(smap);
146         if (err)
147                 goto put_buffers;
148
149         bpf_map_charge_move(&smap->map.memory, &mem);
150
151         return &smap->map;
152
153 put_buffers:
154         put_callchain_buffers();
155 free_charge:
156         bpf_map_charge_finish(&mem);
157         bpf_map_area_free(smap);
158         return ERR_PTR(err);
159 }
160
161 #define BPF_BUILD_ID 3
162 /*
163  * Parse build id from the note segment. This logic can be shared between
164  * 32-bit and 64-bit system, because Elf32_Nhdr and Elf64_Nhdr are
165  * identical.
166  */
167 static inline int stack_map_parse_build_id(void *page_addr,
168                                            unsigned char *build_id,
169                                            void *note_start,
170                                            Elf32_Word note_size)
171 {
172         Elf32_Word note_offs = 0, new_offs;
173
174         /* check for overflow */
175         if (note_start < page_addr || note_start + note_size < note_start)
176                 return -EINVAL;
177
178         /* only supports note that fits in the first page */
179         if (note_start + note_size > page_addr + PAGE_SIZE)
180                 return -EINVAL;
181
182         while (note_offs + sizeof(Elf32_Nhdr) < note_size) {
183                 Elf32_Nhdr *nhdr = (Elf32_Nhdr *)(note_start + note_offs);
184
185                 if (nhdr->n_type == BPF_BUILD_ID &&
186                     nhdr->n_namesz == sizeof("GNU") &&
187                     nhdr->n_descsz > 0 &&
188                     nhdr->n_descsz <= BPF_BUILD_ID_SIZE) {
189                         memcpy(build_id,
190                                note_start + note_offs +
191                                ALIGN(sizeof("GNU"), 4) + sizeof(Elf32_Nhdr),
192                                nhdr->n_descsz);
193                         memset(build_id + nhdr->n_descsz, 0,
194                                BPF_BUILD_ID_SIZE - nhdr->n_descsz);
195                         return 0;
196                 }
197                 new_offs = note_offs + sizeof(Elf32_Nhdr) +
198                         ALIGN(nhdr->n_namesz, 4) + ALIGN(nhdr->n_descsz, 4);
199                 if (new_offs <= note_offs)  /* overflow */
200                         break;
201                 note_offs = new_offs;
202         }
203         return -EINVAL;
204 }
205
206 /* Parse build ID from 32-bit ELF */
207 static int stack_map_get_build_id_32(void *page_addr,
208                                      unsigned char *build_id)
209 {
210         Elf32_Ehdr *ehdr = (Elf32_Ehdr *)page_addr;
211         Elf32_Phdr *phdr;
212         int i;
213
214         /* only supports phdr that fits in one page */
215         if (ehdr->e_phnum >
216             (PAGE_SIZE - sizeof(Elf32_Ehdr)) / sizeof(Elf32_Phdr))
217                 return -EINVAL;
218
219         phdr = (Elf32_Phdr *)(page_addr + sizeof(Elf32_Ehdr));
220
221         for (i = 0; i < ehdr->e_phnum; ++i)
222                 if (phdr[i].p_type == PT_NOTE)
223                         return stack_map_parse_build_id(page_addr, build_id,
224                                         page_addr + phdr[i].p_offset,
225                                         phdr[i].p_filesz);
226         return -EINVAL;
227 }
228
229 /* Parse build ID from 64-bit ELF */
230 static int stack_map_get_build_id_64(void *page_addr,
231                                      unsigned char *build_id)
232 {
233         Elf64_Ehdr *ehdr = (Elf64_Ehdr *)page_addr;
234         Elf64_Phdr *phdr;
235         int i;
236
237         /* only supports phdr that fits in one page */
238         if (ehdr->e_phnum >
239             (PAGE_SIZE - sizeof(Elf64_Ehdr)) / sizeof(Elf64_Phdr))
240                 return -EINVAL;
241
242         phdr = (Elf64_Phdr *)(page_addr + sizeof(Elf64_Ehdr));
243
244         for (i = 0; i < ehdr->e_phnum; ++i)
245                 if (phdr[i].p_type == PT_NOTE)
246                         return stack_map_parse_build_id(page_addr, build_id,
247                                         page_addr + phdr[i].p_offset,
248                                         phdr[i].p_filesz);
249         return -EINVAL;
250 }
251
252 /* Parse build ID of ELF file mapped to vma */
253 static int stack_map_get_build_id(struct vm_area_struct *vma,
254                                   unsigned char *build_id)
255 {
256         Elf32_Ehdr *ehdr;
257         struct page *page;
258         void *page_addr;
259         int ret;
260
261         /* only works for page backed storage  */
262         if (!vma->vm_file)
263                 return -EINVAL;
264
265         page = find_get_page(vma->vm_file->f_mapping, 0);
266         if (!page)
267                 return -EFAULT; /* page not mapped */
268
269         ret = -EINVAL;
270         page_addr = kmap_atomic(page);
271         ehdr = (Elf32_Ehdr *)page_addr;
272
273         /* compare magic x7f "ELF" */
274         if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG) != 0)
275                 goto out;
276
277         /* only support executable file and shared object file */
278         if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
279                 goto out;
280
281         if (ehdr->e_ident[EI_CLASS] == ELFCLASS32)
282                 ret = stack_map_get_build_id_32(page_addr, build_id);
283         else if (ehdr->e_ident[EI_CLASS] == ELFCLASS64)
284                 ret = stack_map_get_build_id_64(page_addr, build_id);
285 out:
286         kunmap_atomic(page_addr);
287         put_page(page);
288         return ret;
289 }
290
291 static void stack_map_get_build_id_offset(struct bpf_stack_build_id *id_offs,
292                                           u64 *ips, u32 trace_nr, bool user)
293 {
294         int i;
295         struct vm_area_struct *vma;
296         bool irq_work_busy = false;
297         struct stack_map_irq_work *work = NULL;
298
299         if (in_nmi()) {
300                 work = this_cpu_ptr(&up_read_work);
301                 if (work->irq_work.flags & IRQ_WORK_BUSY)
302                         /* cannot queue more up_read, fallback */
303                         irq_work_busy = true;
304         }
305
306         /*
307          * We cannot do up_read() in nmi context. To do build_id lookup
308          * in nmi context, we need to run up_read() in irq_work. We use
309          * a percpu variable to do the irq_work. If the irq_work is
310          * already used by another lookup, we fall back to report ips.
311          *
312          * Same fallback is used for kernel stack (!user) on a stackmap
313          * with build_id.
314          */
315         if (!user || !current || !current->mm || irq_work_busy ||
316             down_read_trylock(&current->mm->mmap_sem) == 0) {
317                 /* cannot access current->mm, fall back to ips */
318                 for (i = 0; i < trace_nr; i++) {
319                         id_offs[i].status = BPF_STACK_BUILD_ID_IP;
320                         id_offs[i].ip = ips[i];
321                         memset(id_offs[i].build_id, 0, BPF_BUILD_ID_SIZE);
322                 }
323                 return;
324         }
325
326         for (i = 0; i < trace_nr; i++) {
327                 vma = find_vma(current->mm, ips[i]);
328                 if (!vma || stack_map_get_build_id(vma, id_offs[i].build_id)) {
329                         /* per entry fall back to ips */
330                         id_offs[i].status = BPF_STACK_BUILD_ID_IP;
331                         id_offs[i].ip = ips[i];
332                         memset(id_offs[i].build_id, 0, BPF_BUILD_ID_SIZE);
333                         continue;
334                 }
335                 id_offs[i].offset = (vma->vm_pgoff << PAGE_SHIFT) + ips[i]
336                         - vma->vm_start;
337                 id_offs[i].status = BPF_STACK_BUILD_ID_VALID;
338         }
339
340         if (!work) {
341                 up_read(&current->mm->mmap_sem);
342         } else {
343                 work->sem = &current->mm->mmap_sem;
344                 irq_work_queue(&work->irq_work);
345                 /*
346                  * The irq_work will release the mmap_sem with
347                  * up_read_non_owner(). The rwsem_release() is called
348                  * here to release the lock from lockdep's perspective.
349                  */
350                 rwsem_release(&current->mm->mmap_sem.dep_map, 1, _RET_IP_);
351         }
352 }
353
354 BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
355            u64, flags)
356 {
357         struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
358         struct perf_callchain_entry *trace;
359         struct stack_map_bucket *bucket, *new_bucket, *old_bucket;
360         u32 max_depth = map->value_size / stack_map_data_size(map);
361         /* stack_map_alloc() checks that max_depth <= sysctl_perf_event_max_stack */
362         u32 init_nr = sysctl_perf_event_max_stack - max_depth;
363         u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
364         u32 hash, id, trace_nr, trace_len;
365         bool user = flags & BPF_F_USER_STACK;
366         bool kernel = !user;
367         u64 *ips;
368         bool hash_matches;
369
370         if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
371                                BPF_F_FAST_STACK_CMP | BPF_F_REUSE_STACKID)))
372                 return -EINVAL;
373
374         trace = get_perf_callchain(regs, init_nr, kernel, user,
375                                    sysctl_perf_event_max_stack, false, false);
376
377         if (unlikely(!trace))
378                 /* couldn't fetch the stack trace */
379                 return -EFAULT;
380
381         /* get_perf_callchain() guarantees that trace->nr >= init_nr
382          * and trace-nr <= sysctl_perf_event_max_stack, so trace_nr <= max_depth
383          */
384         trace_nr = trace->nr - init_nr;
385
386         if (trace_nr <= skip)
387                 /* skipping more than usable stack trace */
388                 return -EFAULT;
389
390         trace_nr -= skip;
391         trace_len = trace_nr * sizeof(u64);
392         ips = trace->ip + skip + init_nr;
393         hash = jhash2((u32 *)ips, trace_len / sizeof(u32), 0);
394         id = hash & (smap->n_buckets - 1);
395         bucket = READ_ONCE(smap->buckets[id]);
396
397         hash_matches = bucket && bucket->hash == hash;
398         /* fast cmp */
399         if (hash_matches && flags & BPF_F_FAST_STACK_CMP)
400                 return id;
401
402         if (stack_map_use_build_id(map)) {
403                 /* for build_id+offset, pop a bucket before slow cmp */
404                 new_bucket = (struct stack_map_bucket *)
405                         pcpu_freelist_pop(&smap->freelist);
406                 if (unlikely(!new_bucket))
407                         return -ENOMEM;
408                 new_bucket->nr = trace_nr;
409                 stack_map_get_build_id_offset(
410                         (struct bpf_stack_build_id *)new_bucket->data,
411                         ips, trace_nr, user);
412                 trace_len = trace_nr * sizeof(struct bpf_stack_build_id);
413                 if (hash_matches && bucket->nr == trace_nr &&
414                     memcmp(bucket->data, new_bucket->data, trace_len) == 0) {
415                         pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);
416                         return id;
417                 }
418                 if (bucket && !(flags & BPF_F_REUSE_STACKID)) {
419                         pcpu_freelist_push(&smap->freelist, &new_bucket->fnode);
420                         return -EEXIST;
421                 }
422         } else {
423                 if (hash_matches && bucket->nr == trace_nr &&
424                     memcmp(bucket->data, ips, trace_len) == 0)
425                         return id;
426                 if (bucket && !(flags & BPF_F_REUSE_STACKID))
427                         return -EEXIST;
428
429                 new_bucket = (struct stack_map_bucket *)
430                         pcpu_freelist_pop(&smap->freelist);
431                 if (unlikely(!new_bucket))
432                         return -ENOMEM;
433                 memcpy(new_bucket->data, ips, trace_len);
434         }
435
436         new_bucket->hash = hash;
437         new_bucket->nr = trace_nr;
438
439         old_bucket = xchg(&smap->buckets[id], new_bucket);
440         if (old_bucket)
441                 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
442         return id;
443 }
444
445 const struct bpf_func_proto bpf_get_stackid_proto = {
446         .func           = bpf_get_stackid,
447         .gpl_only       = true,
448         .ret_type       = RET_INTEGER,
449         .arg1_type      = ARG_PTR_TO_CTX,
450         .arg2_type      = ARG_CONST_MAP_PTR,
451         .arg3_type      = ARG_ANYTHING,
452 };
453
454 BPF_CALL_4(bpf_get_stack, struct pt_regs *, regs, void *, buf, u32, size,
455            u64, flags)
456 {
457         u32 init_nr, trace_nr, copy_len, elem_size, num_elem;
458         bool user_build_id = flags & BPF_F_USER_BUILD_ID;
459         u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
460         bool user = flags & BPF_F_USER_STACK;
461         struct perf_callchain_entry *trace;
462         bool kernel = !user;
463         int err = -EINVAL;
464         u64 *ips;
465
466         if (unlikely(flags & ~(BPF_F_SKIP_FIELD_MASK | BPF_F_USER_STACK |
467                                BPF_F_USER_BUILD_ID)))
468                 goto clear;
469         if (kernel && user_build_id)
470                 goto clear;
471
472         elem_size = (user && user_build_id) ? sizeof(struct bpf_stack_build_id)
473                                             : sizeof(u64);
474         if (unlikely(size % elem_size))
475                 goto clear;
476
477         num_elem = size / elem_size;
478         if (sysctl_perf_event_max_stack < num_elem)
479                 init_nr = 0;
480         else
481                 init_nr = sysctl_perf_event_max_stack - num_elem;
482         trace = get_perf_callchain(regs, init_nr, kernel, user,
483                                    sysctl_perf_event_max_stack, false, false);
484         if (unlikely(!trace))
485                 goto err_fault;
486
487         trace_nr = trace->nr - init_nr;
488         if (trace_nr < skip)
489                 goto err_fault;
490
491         trace_nr -= skip;
492         trace_nr = (trace_nr <= num_elem) ? trace_nr : num_elem;
493         copy_len = trace_nr * elem_size;
494         ips = trace->ip + skip + init_nr;
495         if (user && user_build_id)
496                 stack_map_get_build_id_offset(buf, ips, trace_nr, user);
497         else
498                 memcpy(buf, ips, copy_len);
499
500         if (size > copy_len)
501                 memset(buf + copy_len, 0, size - copy_len);
502         return copy_len;
503
504 err_fault:
505         err = -EFAULT;
506 clear:
507         memset(buf, 0, size);
508         return err;
509 }
510
511 const struct bpf_func_proto bpf_get_stack_proto = {
512         .func           = bpf_get_stack,
513         .gpl_only       = true,
514         .ret_type       = RET_INTEGER,
515         .arg1_type      = ARG_PTR_TO_CTX,
516         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
517         .arg3_type      = ARG_CONST_SIZE_OR_ZERO,
518         .arg4_type      = ARG_ANYTHING,
519 };
520
521 /* Called from eBPF program */
522 static void *stack_map_lookup_elem(struct bpf_map *map, void *key)
523 {
524         return ERR_PTR(-EOPNOTSUPP);
525 }
526
527 /* Called from syscall */
528 int bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
529 {
530         struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
531         struct stack_map_bucket *bucket, *old_bucket;
532         u32 id = *(u32 *)key, trace_len;
533
534         if (unlikely(id >= smap->n_buckets))
535                 return -ENOENT;
536
537         bucket = xchg(&smap->buckets[id], NULL);
538         if (!bucket)
539                 return -ENOENT;
540
541         trace_len = bucket->nr * stack_map_data_size(map);
542         memcpy(value, bucket->data, trace_len);
543         memset(value + trace_len, 0, map->value_size - trace_len);
544
545         old_bucket = xchg(&smap->buckets[id], bucket);
546         if (old_bucket)
547                 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
548         return 0;
549 }
550
551 static int stack_map_get_next_key(struct bpf_map *map, void *key,
552                                   void *next_key)
553 {
554         struct bpf_stack_map *smap = container_of(map,
555                                                   struct bpf_stack_map, map);
556         u32 id;
557
558         WARN_ON_ONCE(!rcu_read_lock_held());
559
560         if (!key) {
561                 id = 0;
562         } else {
563                 id = *(u32 *)key;
564                 if (id >= smap->n_buckets || !smap->buckets[id])
565                         id = 0;
566                 else
567                         id++;
568         }
569
570         while (id < smap->n_buckets && !smap->buckets[id])
571                 id++;
572
573         if (id >= smap->n_buckets)
574                 return -ENOENT;
575
576         *(u32 *)next_key = id;
577         return 0;
578 }
579
580 static int stack_map_update_elem(struct bpf_map *map, void *key, void *value,
581                                  u64 map_flags)
582 {
583         return -EINVAL;
584 }
585
586 /* Called from syscall or from eBPF program */
587 static int stack_map_delete_elem(struct bpf_map *map, void *key)
588 {
589         struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
590         struct stack_map_bucket *old_bucket;
591         u32 id = *(u32 *)key;
592
593         if (unlikely(id >= smap->n_buckets))
594                 return -E2BIG;
595
596         old_bucket = xchg(&smap->buckets[id], NULL);
597         if (old_bucket) {
598                 pcpu_freelist_push(&smap->freelist, &old_bucket->fnode);
599                 return 0;
600         } else {
601                 return -ENOENT;
602         }
603 }
604
605 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
606 static void stack_map_free(struct bpf_map *map)
607 {
608         struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
609
610         /* wait for bpf programs to complete before freeing stack map */
611         synchronize_rcu();
612
613         bpf_map_area_free(smap->elems);
614         pcpu_freelist_destroy(&smap->freelist);
615         bpf_map_area_free(smap);
616         put_callchain_buffers();
617 }
618
619 const struct bpf_map_ops stack_trace_map_ops = {
620         .map_alloc = stack_map_alloc,
621         .map_free = stack_map_free,
622         .map_get_next_key = stack_map_get_next_key,
623         .map_lookup_elem = stack_map_lookup_elem,
624         .map_update_elem = stack_map_update_elem,
625         .map_delete_elem = stack_map_delete_elem,
626         .map_check_btf = map_check_no_btf,
627 };
628
629 static int __init stack_map_init(void)
630 {
631         int cpu;
632         struct stack_map_irq_work *work;
633
634         for_each_possible_cpu(cpu) {
635                 work = per_cpu_ptr(&up_read_work, cpu);
636                 init_irq_work(&work->irq_work, do_up_read);
637         }
638         return 0;
639 }
640 subsys_initcall(stack_map_init);