1 #include <linux/bpf.h>
2 #include <linux/btf.h>
3 #include <linux/err.h>
4 #include <linux/irq_work.h>
5 #include <linux/slab.h>
6 #include <linux/filter.h>
7 #include <linux/mm.h>
8 #include <linux/vmalloc.h>
9 #include <linux/wait.h>
10 #include <linux/poll.h>
11 #include <linux/kmemleak.h>
12 #include <uapi/linux/btf.h>
13 #include <linux/btf_ids.h>
14 #include <asm/rqspinlock.h>
15
16 #define RINGBUF_CREATE_FLAG_MASK (BPF_F_NUMA_NODE)
17
18 /* non-mmap()'able part of bpf_ringbuf (everything up to consumer page) */
19 #define RINGBUF_PGOFF \
20 (offsetof(struct bpf_ringbuf, consumer_pos) >> PAGE_SHIFT)
21 /* consumer page and producer page */
22 #define RINGBUF_POS_PAGES 2
23 #define RINGBUF_NR_META_PAGES (RINGBUF_PGOFF + RINGBUF_POS_PAGES)
24
25 #define RINGBUF_MAX_RECORD_SZ (UINT_MAX/4)
26
27 struct bpf_ringbuf {
28 wait_queue_head_t waitq;
29 struct irq_work work;
30 u64 mask;
31 struct page **pages;
32 int nr_pages;
33 rqspinlock_t spinlock ____cacheline_aligned_in_smp;
34 /* For user-space producer ring buffers, an atomic_t busy bit is used
35 * to synchronize access to the ring buffers in the kernel, rather than
36 * the spinlock that is used for kernel-producer ring buffers. This is
37 * done because the ring buffer must hold a lock across a BPF program's
38 * callback:
39 *
40 * __bpf_user_ringbuf_peek() // lock acquired
41 * -> program callback_fn()
42 * -> __bpf_user_ringbuf_sample_release() // lock released
43 *
44 * It is unsafe and incorrect to hold an IRQ spinlock across what could
45 * be a long execution window, so we instead simply disallow concurrent
46 * access to the ring buffer by kernel consumers, and return -EBUSY from
47 * __bpf_user_ringbuf_peek() if the busy bit is held by another task.
48 */
49 atomic_t busy ____cacheline_aligned_in_smp;
50 /* Consumer and producer counters are put into separate pages to
51 * allow each position to be mapped with different permissions.
52 * This prevents a user-space application from modifying the
53 * position and ruining in-kernel tracking. The permissions of the
54 * pages depend on who is producing samples: user-space or the
55 * kernel. Note that the pending counter is placed in the same
56 * page as the producer, so that it shares the same cache line.
57 *
58 * Kernel-producer
59 * ---------------
60 * The producer position and data pages are mapped as r/o in
61 * userspace. For this approach, bits in the header of samples are
62 * used to signal to user-space, and to other producers, whether a
63 * sample is currently being written.
64 *
65 * User-space producer
66 * -------------------
67 * Only the page containing the consumer position is mapped r/o in
68 * user-space. User-space producers also use bits of the header to
69 * communicate to the kernel, but the kernel must carefully check and
70 * validate each sample to ensure that they're correctly formatted, and
71 * fully contained within the ring buffer.
72 */
73 unsigned long consumer_pos __aligned(PAGE_SIZE);
74 unsigned long producer_pos __aligned(PAGE_SIZE);
75 unsigned long pending_pos;
76 char data[] __aligned(PAGE_SIZE);
77 };
78
79 struct bpf_ringbuf_map {
80 struct bpf_map map;
81 struct bpf_ringbuf *rb;
82 };
83
84 /* 8-byte ring buffer record header structure */
85 struct bpf_ringbuf_hdr {
86 u32 len;
87 u32 pg_off;
88 };
89
bpf_ringbuf_area_alloc(size_t data_sz,int numa_node)90 static struct bpf_ringbuf *bpf_ringbuf_area_alloc(size_t data_sz, int numa_node)
91 {
92 const gfp_t flags = GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL |
93 __GFP_NOWARN | __GFP_ZERO;
94 int nr_meta_pages = RINGBUF_NR_META_PAGES;
95 int nr_data_pages = data_sz >> PAGE_SHIFT;
96 int nr_pages = nr_meta_pages + nr_data_pages;
97 struct page **pages, *page;
98 struct bpf_ringbuf *rb;
99 size_t array_size;
100 int i;
101
102 /* Each data page is mapped twice to allow "virtual"
103 * continuous read of samples wrapping around the end of ring
104 * buffer area:
105 * ------------------------------------------------------
106 * | meta pages | real data pages | same data pages |
107 * ------------------------------------------------------
108 * | | 1 2 3 4 5 6 7 8 9 | 1 2 3 4 5 6 7 8 9 |
109 * ------------------------------------------------------
110 * | | TA DA | TA DA |
111 * ------------------------------------------------------
112 * ^^^^^^^
113 * |
114 * Here, no need to worry about special handling of wrapped-around
115 * data due to double-mapped data pages. This works both in kernel and
116 * when mmap()'ed in user-space, simplifying both kernel and
117 * user-space implementations significantly.
118 */
119 array_size = (nr_meta_pages + 2 * nr_data_pages) * sizeof(*pages);
120 pages = bpf_map_area_alloc(array_size, numa_node);
121 if (!pages)
122 return NULL;
123
124 for (i = 0; i < nr_pages; i++) {
125 page = alloc_pages_node(numa_node, flags, 0);
126 if (!page) {
127 nr_pages = i;
128 goto err_free_pages;
129 }
130 pages[i] = page;
131 if (i >= nr_meta_pages)
132 pages[nr_data_pages + i] = page;
133 }
134
135 rb = vmap(pages, nr_meta_pages + 2 * nr_data_pages,
136 VM_MAP | VM_USERMAP, PAGE_KERNEL);
137 if (rb) {
138 kmemleak_not_leak(pages);
139 rb->pages = pages;
140 rb->nr_pages = nr_pages;
141 return rb;
142 }
143
144 err_free_pages:
145 for (i = 0; i < nr_pages; i++)
146 __free_page(pages[i]);
147 bpf_map_area_free(pages);
148 return NULL;
149 }
150
bpf_ringbuf_notify(struct irq_work * work)151 static void bpf_ringbuf_notify(struct irq_work *work)
152 {
153 struct bpf_ringbuf *rb = container_of(work, struct bpf_ringbuf, work);
154
155 wake_up_all(&rb->waitq);
156 }
157
158 /* Maximum size of ring buffer area is limited by 32-bit page offset within
159 * record header, counted in pages. Reserve 8 bits for extensibility, and
160 * take into account few extra pages for consumer/producer pages and
161 * non-mmap()'able parts, the current maximum size would be:
162 *
163 * (((1ULL << 24) - RINGBUF_POS_PAGES - RINGBUF_PGOFF) * PAGE_SIZE)
164 *
165 * This gives 64GB limit, which seems plenty for single ring buffer. Now
166 * considering that the maximum value of data_sz is (4GB - 1), there
167 * will be no overflow, so just note the size limit in the comments.
168 */
bpf_ringbuf_alloc(size_t data_sz,int numa_node)169 static struct bpf_ringbuf *bpf_ringbuf_alloc(size_t data_sz, int numa_node)
170 {
171 struct bpf_ringbuf *rb;
172
173 rb = bpf_ringbuf_area_alloc(data_sz, numa_node);
174 if (!rb)
175 return NULL;
176
177 raw_res_spin_lock_init(&rb->spinlock);
178 atomic_set(&rb->busy, 0);
179 init_waitqueue_head(&rb->waitq);
180 init_irq_work(&rb->work, bpf_ringbuf_notify);
181
182 rb->mask = data_sz - 1;
183 rb->consumer_pos = 0;
184 rb->producer_pos = 0;
185 rb->pending_pos = 0;
186
187 return rb;
188 }
189
ringbuf_map_alloc(union bpf_attr * attr)190 static struct bpf_map *ringbuf_map_alloc(union bpf_attr *attr)
191 {
192 struct bpf_ringbuf_map *rb_map;
193
194 if (attr->map_flags & ~RINGBUF_CREATE_FLAG_MASK)
195 return ERR_PTR(-EINVAL);
196
197 if (attr->key_size || attr->value_size ||
198 !is_power_of_2(attr->max_entries) ||
199 !PAGE_ALIGNED(attr->max_entries))
200 return ERR_PTR(-EINVAL);
201
202 rb_map = bpf_map_area_alloc(sizeof(*rb_map), NUMA_NO_NODE);
203 if (!rb_map)
204 return ERR_PTR(-ENOMEM);
205
206 bpf_map_init_from_attr(&rb_map->map, attr);
207
208 rb_map->rb = bpf_ringbuf_alloc(attr->max_entries, rb_map->map.numa_node);
209 if (!rb_map->rb) {
210 bpf_map_area_free(rb_map);
211 return ERR_PTR(-ENOMEM);
212 }
213
214 return &rb_map->map;
215 }
216
bpf_ringbuf_free(struct bpf_ringbuf * rb)217 static void bpf_ringbuf_free(struct bpf_ringbuf *rb)
218 {
219 irq_work_sync(&rb->work);
220
221 /* copy pages pointer and nr_pages to local variable, as we are going
222 * to unmap rb itself with vunmap() below
223 */
224 struct page **pages = rb->pages;
225 int i, nr_pages = rb->nr_pages;
226
227 vunmap(rb);
228 for (i = 0; i < nr_pages; i++)
229 __free_page(pages[i]);
230 bpf_map_area_free(pages);
231 }
232
ringbuf_map_free(struct bpf_map * map)233 static void ringbuf_map_free(struct bpf_map *map)
234 {
235 struct bpf_ringbuf_map *rb_map;
236
237 rb_map = container_of(map, struct bpf_ringbuf_map, map);
238 bpf_ringbuf_free(rb_map->rb);
239 bpf_map_area_free(rb_map);
240 }
241
ringbuf_map_lookup_elem(struct bpf_map * map,void * key)242 static void *ringbuf_map_lookup_elem(struct bpf_map *map, void *key)
243 {
244 return ERR_PTR(-ENOTSUPP);
245 }
246
ringbuf_map_update_elem(struct bpf_map * map,void * key,void * value,u64 flags)247 static long ringbuf_map_update_elem(struct bpf_map *map, void *key, void *value,
248 u64 flags)
249 {
250 return -ENOTSUPP;
251 }
252
ringbuf_map_delete_elem(struct bpf_map * map,void * key)253 static long ringbuf_map_delete_elem(struct bpf_map *map, void *key)
254 {
255 return -ENOTSUPP;
256 }
257
ringbuf_map_get_next_key(struct bpf_map * map,void * key,void * next_key)258 static int ringbuf_map_get_next_key(struct bpf_map *map, void *key,
259 void *next_key)
260 {
261 return -ENOTSUPP;
262 }
263
ringbuf_map_mmap_kern(struct bpf_map * map,struct vm_area_struct * vma)264 static int ringbuf_map_mmap_kern(struct bpf_map *map, struct vm_area_struct *vma)
265 {
266 struct bpf_ringbuf_map *rb_map;
267
268 rb_map = container_of(map, struct bpf_ringbuf_map, map);
269
270 if (vma->vm_flags & VM_WRITE) {
271 /* allow writable mapping for the consumer_pos only */
272 if (vma->vm_pgoff != 0 || vma->vm_end - vma->vm_start != PAGE_SIZE)
273 return -EPERM;
274 }
275 /* remap_vmalloc_range() checks size and offset constraints */
276 return remap_vmalloc_range(vma, rb_map->rb,
277 vma->vm_pgoff + RINGBUF_PGOFF);
278 }
279
ringbuf_map_mmap_user(struct bpf_map * map,struct vm_area_struct * vma)280 static int ringbuf_map_mmap_user(struct bpf_map *map, struct vm_area_struct *vma)
281 {
282 struct bpf_ringbuf_map *rb_map;
283
284 rb_map = container_of(map, struct bpf_ringbuf_map, map);
285
286 if (vma->vm_flags & VM_WRITE) {
287 if (vma->vm_pgoff == 0)
288 /* Disallow writable mappings to the consumer pointer,
289 * and allow writable mappings to both the producer
290 * position, and the ring buffer data itself.
291 */
292 return -EPERM;
293 }
294 /* remap_vmalloc_range() checks size and offset constraints */
295 return remap_vmalloc_range(vma, rb_map->rb, vma->vm_pgoff + RINGBUF_PGOFF);
296 }
297
ringbuf_avail_data_sz(struct bpf_ringbuf * rb)298 static unsigned long ringbuf_avail_data_sz(struct bpf_ringbuf *rb)
299 {
300 unsigned long cons_pos, prod_pos;
301
302 cons_pos = smp_load_acquire(&rb->consumer_pos);
303 prod_pos = smp_load_acquire(&rb->producer_pos);
304 return prod_pos - cons_pos;
305 }
306
ringbuf_total_data_sz(const struct bpf_ringbuf * rb)307 static u32 ringbuf_total_data_sz(const struct bpf_ringbuf *rb)
308 {
309 return rb->mask + 1;
310 }
311
ringbuf_map_poll_kern(struct bpf_map * map,struct file * filp,struct poll_table_struct * pts)312 static __poll_t ringbuf_map_poll_kern(struct bpf_map *map, struct file *filp,
313 struct poll_table_struct *pts)
314 {
315 struct bpf_ringbuf_map *rb_map;
316
317 rb_map = container_of(map, struct bpf_ringbuf_map, map);
318 poll_wait(filp, &rb_map->rb->waitq, pts);
319
320 if (ringbuf_avail_data_sz(rb_map->rb))
321 return EPOLLIN | EPOLLRDNORM;
322 return 0;
323 }
324
ringbuf_map_poll_user(struct bpf_map * map,struct file * filp,struct poll_table_struct * pts)325 static __poll_t ringbuf_map_poll_user(struct bpf_map *map, struct file *filp,
326 struct poll_table_struct *pts)
327 {
328 struct bpf_ringbuf_map *rb_map;
329
330 rb_map = container_of(map, struct bpf_ringbuf_map, map);
331 poll_wait(filp, &rb_map->rb->waitq, pts);
332
333 if (ringbuf_avail_data_sz(rb_map->rb) < ringbuf_total_data_sz(rb_map->rb))
334 return EPOLLOUT | EPOLLWRNORM;
335 return 0;
336 }
337
ringbuf_map_mem_usage(const struct bpf_map * map)338 static u64 ringbuf_map_mem_usage(const struct bpf_map *map)
339 {
340 struct bpf_ringbuf *rb;
341 int nr_data_pages;
342 int nr_meta_pages;
343 u64 usage = sizeof(struct bpf_ringbuf_map);
344
345 rb = container_of(map, struct bpf_ringbuf_map, map)->rb;
346 usage += (u64)rb->nr_pages << PAGE_SHIFT;
347 nr_meta_pages = RINGBUF_NR_META_PAGES;
348 nr_data_pages = map->max_entries >> PAGE_SHIFT;
349 usage += (nr_meta_pages + 2 * nr_data_pages) * sizeof(struct page *);
350 return usage;
351 }
352
353 BTF_ID_LIST_SINGLE(ringbuf_map_btf_ids, struct, bpf_ringbuf_map)
354 const struct bpf_map_ops ringbuf_map_ops = {
355 .map_meta_equal = bpf_map_meta_equal,
356 .map_alloc = ringbuf_map_alloc,
357 .map_free = ringbuf_map_free,
358 .map_mmap = ringbuf_map_mmap_kern,
359 .map_poll = ringbuf_map_poll_kern,
360 .map_lookup_elem = ringbuf_map_lookup_elem,
361 .map_update_elem = ringbuf_map_update_elem,
362 .map_delete_elem = ringbuf_map_delete_elem,
363 .map_get_next_key = ringbuf_map_get_next_key,
364 .map_mem_usage = ringbuf_map_mem_usage,
365 .map_btf_id = &ringbuf_map_btf_ids[0],
366 };
367
368 BTF_ID_LIST_SINGLE(user_ringbuf_map_btf_ids, struct, bpf_ringbuf_map)
369 const struct bpf_map_ops user_ringbuf_map_ops = {
370 .map_meta_equal = bpf_map_meta_equal,
371 .map_alloc = ringbuf_map_alloc,
372 .map_free = ringbuf_map_free,
373 .map_mmap = ringbuf_map_mmap_user,
374 .map_poll = ringbuf_map_poll_user,
375 .map_lookup_elem = ringbuf_map_lookup_elem,
376 .map_update_elem = ringbuf_map_update_elem,
377 .map_delete_elem = ringbuf_map_delete_elem,
378 .map_get_next_key = ringbuf_map_get_next_key,
379 .map_mem_usage = ringbuf_map_mem_usage,
380 .map_btf_id = &user_ringbuf_map_btf_ids[0],
381 };
382
383 /* Given pointer to ring buffer record metadata and struct bpf_ringbuf itself,
384 * calculate offset from record metadata to ring buffer in pages, rounded
385 * down. This page offset is stored as part of record metadata and allows to
386 * restore struct bpf_ringbuf * from record pointer. This page offset is
387 * stored at offset 4 of record metadata header.
388 */
bpf_ringbuf_rec_pg_off(struct bpf_ringbuf * rb,struct bpf_ringbuf_hdr * hdr)389 static size_t bpf_ringbuf_rec_pg_off(struct bpf_ringbuf *rb,
390 struct bpf_ringbuf_hdr *hdr)
391 {
392 return ((void *)hdr - (void *)rb) >> PAGE_SHIFT;
393 }
394
395 /* Given pointer to ring buffer record header, restore pointer to struct
396 * bpf_ringbuf itself by using page offset stored at offset 4
397 */
398 static struct bpf_ringbuf *
bpf_ringbuf_restore_from_rec(struct bpf_ringbuf_hdr * hdr)399 bpf_ringbuf_restore_from_rec(struct bpf_ringbuf_hdr *hdr)
400 {
401 unsigned long addr = (unsigned long)(void *)hdr;
402 unsigned long off = (unsigned long)hdr->pg_off << PAGE_SHIFT;
403
404 return (void*)((addr & PAGE_MASK) - off);
405 }
406
__bpf_ringbuf_reserve(struct bpf_ringbuf * rb,u64 size)407 static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
408 {
409 unsigned long cons_pos, prod_pos, new_prod_pos, pend_pos, flags;
410 struct bpf_ringbuf_hdr *hdr;
411 u32 len, pg_off, tmp_size, hdr_len;
412
413 if (unlikely(size > RINGBUF_MAX_RECORD_SZ))
414 return NULL;
415
416 len = round_up(size + BPF_RINGBUF_HDR_SZ, 8);
417 if (len > ringbuf_total_data_sz(rb))
418 return NULL;
419
420 cons_pos = smp_load_acquire(&rb->consumer_pos);
421
422 if (raw_res_spin_lock_irqsave(&rb->spinlock, flags))
423 return NULL;
424
425 pend_pos = rb->pending_pos;
426 prod_pos = rb->producer_pos;
427 new_prod_pos = prod_pos + len;
428
429 while (pend_pos < prod_pos) {
430 hdr = (void *)rb->data + (pend_pos & rb->mask);
431 hdr_len = READ_ONCE(hdr->len);
432 if (hdr_len & BPF_RINGBUF_BUSY_BIT)
433 break;
434 tmp_size = hdr_len & ~BPF_RINGBUF_DISCARD_BIT;
435 tmp_size = round_up(tmp_size + BPF_RINGBUF_HDR_SZ, 8);
436 pend_pos += tmp_size;
437 }
438 rb->pending_pos = pend_pos;
439
440 /* check for out of ringbuf space:
441 * - by ensuring producer position doesn't advance more than
442 * (ringbuf_size - 1) ahead
443 * - by ensuring oldest not yet committed record until newest
444 * record does not span more than (ringbuf_size - 1)
445 */
446 if (new_prod_pos - cons_pos > rb->mask ||
447 new_prod_pos - pend_pos > rb->mask) {
448 raw_res_spin_unlock_irqrestore(&rb->spinlock, flags);
449 return NULL;
450 }
451
452 hdr = (void *)rb->data + (prod_pos & rb->mask);
453 pg_off = bpf_ringbuf_rec_pg_off(rb, hdr);
454 hdr->len = size | BPF_RINGBUF_BUSY_BIT;
455 hdr->pg_off = pg_off;
456
457 /* pairs with consumer's smp_load_acquire() */
458 smp_store_release(&rb->producer_pos, new_prod_pos);
459
460 raw_res_spin_unlock_irqrestore(&rb->spinlock, flags);
461
462 return (void *)hdr + BPF_RINGBUF_HDR_SZ;
463 }
464
BPF_CALL_3(bpf_ringbuf_reserve,struct bpf_map *,map,u64,size,u64,flags)465 BPF_CALL_3(bpf_ringbuf_reserve, struct bpf_map *, map, u64, size, u64, flags)
466 {
467 struct bpf_ringbuf_map *rb_map;
468
469 if (unlikely(flags))
470 return 0;
471
472 rb_map = container_of(map, struct bpf_ringbuf_map, map);
473 return (unsigned long)__bpf_ringbuf_reserve(rb_map->rb, size);
474 }
475
476 const struct bpf_func_proto bpf_ringbuf_reserve_proto = {
477 .func = bpf_ringbuf_reserve,
478 .ret_type = RET_PTR_TO_RINGBUF_MEM_OR_NULL,
479 .arg1_type = ARG_CONST_MAP_PTR,
480 .arg2_type = ARG_CONST_ALLOC_SIZE_OR_ZERO,
481 .arg3_type = ARG_ANYTHING,
482 };
483
bpf_ringbuf_commit(void * sample,u64 flags,bool discard)484 static void bpf_ringbuf_commit(void *sample, u64 flags, bool discard)
485 {
486 unsigned long rec_pos, cons_pos;
487 struct bpf_ringbuf_hdr *hdr;
488 struct bpf_ringbuf *rb;
489 u32 new_len;
490
491 hdr = sample - BPF_RINGBUF_HDR_SZ;
492 rb = bpf_ringbuf_restore_from_rec(hdr);
493 new_len = hdr->len ^ BPF_RINGBUF_BUSY_BIT;
494 if (discard)
495 new_len |= BPF_RINGBUF_DISCARD_BIT;
496
497 /* update record header with correct final size prefix */
498 xchg(&hdr->len, new_len);
499
500 /* if consumer caught up and is waiting for our record, notify about
501 * new data availability
502 */
503 rec_pos = (void *)hdr - (void *)rb->data;
504 cons_pos = smp_load_acquire(&rb->consumer_pos) & rb->mask;
505
506 if (flags & BPF_RB_FORCE_WAKEUP)
507 irq_work_queue(&rb->work);
508 else if (cons_pos == rec_pos && !(flags & BPF_RB_NO_WAKEUP))
509 irq_work_queue(&rb->work);
510 }
511
BPF_CALL_2(bpf_ringbuf_submit,void *,sample,u64,flags)512 BPF_CALL_2(bpf_ringbuf_submit, void *, sample, u64, flags)
513 {
514 bpf_ringbuf_commit(sample, flags, false /* discard */);
515 return 0;
516 }
517
518 const struct bpf_func_proto bpf_ringbuf_submit_proto = {
519 .func = bpf_ringbuf_submit,
520 .ret_type = RET_VOID,
521 .arg1_type = ARG_PTR_TO_RINGBUF_MEM | OBJ_RELEASE,
522 .arg2_type = ARG_ANYTHING,
523 };
524
BPF_CALL_2(bpf_ringbuf_discard,void *,sample,u64,flags)525 BPF_CALL_2(bpf_ringbuf_discard, void *, sample, u64, flags)
526 {
527 bpf_ringbuf_commit(sample, flags, true /* discard */);
528 return 0;
529 }
530
531 const struct bpf_func_proto bpf_ringbuf_discard_proto = {
532 .func = bpf_ringbuf_discard,
533 .ret_type = RET_VOID,
534 .arg1_type = ARG_PTR_TO_RINGBUF_MEM | OBJ_RELEASE,
535 .arg2_type = ARG_ANYTHING,
536 };
537
BPF_CALL_4(bpf_ringbuf_output,struct bpf_map *,map,void *,data,u64,size,u64,flags)538 BPF_CALL_4(bpf_ringbuf_output, struct bpf_map *, map, void *, data, u64, size,
539 u64, flags)
540 {
541 struct bpf_ringbuf_map *rb_map;
542 void *rec;
543
544 if (unlikely(flags & ~(BPF_RB_NO_WAKEUP | BPF_RB_FORCE_WAKEUP)))
545 return -EINVAL;
546
547 rb_map = container_of(map, struct bpf_ringbuf_map, map);
548 rec = __bpf_ringbuf_reserve(rb_map->rb, size);
549 if (!rec)
550 return -EAGAIN;
551
552 memcpy(rec, data, size);
553 bpf_ringbuf_commit(rec, flags, false /* discard */);
554 return 0;
555 }
556
557 const struct bpf_func_proto bpf_ringbuf_output_proto = {
558 .func = bpf_ringbuf_output,
559 .ret_type = RET_INTEGER,
560 .arg1_type = ARG_CONST_MAP_PTR,
561 .arg2_type = ARG_PTR_TO_MEM | MEM_RDONLY,
562 .arg3_type = ARG_CONST_SIZE_OR_ZERO,
563 .arg4_type = ARG_ANYTHING,
564 };
565
BPF_CALL_2(bpf_ringbuf_query,struct bpf_map *,map,u64,flags)566 BPF_CALL_2(bpf_ringbuf_query, struct bpf_map *, map, u64, flags)
567 {
568 struct bpf_ringbuf *rb;
569
570 rb = container_of(map, struct bpf_ringbuf_map, map)->rb;
571
572 switch (flags) {
573 case BPF_RB_AVAIL_DATA:
574 return ringbuf_avail_data_sz(rb);
575 case BPF_RB_RING_SIZE:
576 return ringbuf_total_data_sz(rb);
577 case BPF_RB_CONS_POS:
578 return smp_load_acquire(&rb->consumer_pos);
579 case BPF_RB_PROD_POS:
580 return smp_load_acquire(&rb->producer_pos);
581 default:
582 return 0;
583 }
584 }
585
586 const struct bpf_func_proto bpf_ringbuf_query_proto = {
587 .func = bpf_ringbuf_query,
588 .ret_type = RET_INTEGER,
589 .arg1_type = ARG_CONST_MAP_PTR,
590 .arg2_type = ARG_ANYTHING,
591 };
592
BPF_CALL_4(bpf_ringbuf_reserve_dynptr,struct bpf_map *,map,u32,size,u64,flags,struct bpf_dynptr_kern *,ptr)593 BPF_CALL_4(bpf_ringbuf_reserve_dynptr, struct bpf_map *, map, u32, size, u64, flags,
594 struct bpf_dynptr_kern *, ptr)
595 {
596 struct bpf_ringbuf_map *rb_map;
597 void *sample;
598 int err;
599
600 if (unlikely(flags)) {
601 bpf_dynptr_set_null(ptr);
602 return -EINVAL;
603 }
604
605 err = bpf_dynptr_check_size(size);
606 if (err) {
607 bpf_dynptr_set_null(ptr);
608 return err;
609 }
610
611 rb_map = container_of(map, struct bpf_ringbuf_map, map);
612
613 sample = __bpf_ringbuf_reserve(rb_map->rb, size);
614 if (!sample) {
615 bpf_dynptr_set_null(ptr);
616 return -EINVAL;
617 }
618
619 bpf_dynptr_init(ptr, sample, BPF_DYNPTR_TYPE_RINGBUF, 0, size);
620
621 return 0;
622 }
623
624 const struct bpf_func_proto bpf_ringbuf_reserve_dynptr_proto = {
625 .func = bpf_ringbuf_reserve_dynptr,
626 .ret_type = RET_INTEGER,
627 .arg1_type = ARG_CONST_MAP_PTR,
628 .arg2_type = ARG_ANYTHING,
629 .arg3_type = ARG_ANYTHING,
630 .arg4_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_RINGBUF | MEM_UNINIT | MEM_WRITE,
631 };
632
BPF_CALL_2(bpf_ringbuf_submit_dynptr,struct bpf_dynptr_kern *,ptr,u64,flags)633 BPF_CALL_2(bpf_ringbuf_submit_dynptr, struct bpf_dynptr_kern *, ptr, u64, flags)
634 {
635 if (!ptr->data)
636 return 0;
637
638 bpf_ringbuf_commit(ptr->data, flags, false /* discard */);
639
640 bpf_dynptr_set_null(ptr);
641
642 return 0;
643 }
644
645 const struct bpf_func_proto bpf_ringbuf_submit_dynptr_proto = {
646 .func = bpf_ringbuf_submit_dynptr,
647 .ret_type = RET_VOID,
648 .arg1_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_RINGBUF | OBJ_RELEASE,
649 .arg2_type = ARG_ANYTHING,
650 };
651
BPF_CALL_2(bpf_ringbuf_discard_dynptr,struct bpf_dynptr_kern *,ptr,u64,flags)652 BPF_CALL_2(bpf_ringbuf_discard_dynptr, struct bpf_dynptr_kern *, ptr, u64, flags)
653 {
654 if (!ptr->data)
655 return 0;
656
657 bpf_ringbuf_commit(ptr->data, flags, true /* discard */);
658
659 bpf_dynptr_set_null(ptr);
660
661 return 0;
662 }
663
664 const struct bpf_func_proto bpf_ringbuf_discard_dynptr_proto = {
665 .func = bpf_ringbuf_discard_dynptr,
666 .ret_type = RET_VOID,
667 .arg1_type = ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_RINGBUF | OBJ_RELEASE,
668 .arg2_type = ARG_ANYTHING,
669 };
670
__bpf_user_ringbuf_peek(struct bpf_ringbuf * rb,void ** sample,u32 * size)671 static int __bpf_user_ringbuf_peek(struct bpf_ringbuf *rb, void **sample, u32 *size)
672 {
673 int err;
674 u32 hdr_len, sample_len, total_len, flags, *hdr;
675 u64 cons_pos, prod_pos;
676
677 /* Synchronizes with smp_store_release() in user-space producer. */
678 prod_pos = smp_load_acquire(&rb->producer_pos);
679 if (prod_pos % 8)
680 return -EINVAL;
681
682 /* Synchronizes with smp_store_release() in __bpf_user_ringbuf_sample_release() */
683 cons_pos = smp_load_acquire(&rb->consumer_pos);
684 if (cons_pos >= prod_pos)
685 return -ENODATA;
686
687 hdr = (u32 *)((uintptr_t)rb->data + (uintptr_t)(cons_pos & rb->mask));
688 /* Synchronizes with smp_store_release() in user-space producer. */
689 hdr_len = smp_load_acquire(hdr);
690 flags = hdr_len & (BPF_RINGBUF_BUSY_BIT | BPF_RINGBUF_DISCARD_BIT);
691 sample_len = hdr_len & ~flags;
692 total_len = round_up(sample_len + BPF_RINGBUF_HDR_SZ, 8);
693
694 /* The sample must fit within the region advertised by the producer position. */
695 if (total_len > prod_pos - cons_pos)
696 return -EINVAL;
697
698 /* The sample must fit within the data region of the ring buffer. */
699 if (total_len > ringbuf_total_data_sz(rb))
700 return -E2BIG;
701
702 /* The sample must fit into a struct bpf_dynptr. */
703 err = bpf_dynptr_check_size(sample_len);
704 if (err)
705 return -E2BIG;
706
707 if (flags & BPF_RINGBUF_DISCARD_BIT) {
708 /* If the discard bit is set, the sample should be skipped.
709 *
710 * Update the consumer pos, and return -EAGAIN so the caller
711 * knows to skip this sample and try to read the next one.
712 */
713 smp_store_release(&rb->consumer_pos, cons_pos + total_len);
714 return -EAGAIN;
715 }
716
717 if (flags & BPF_RINGBUF_BUSY_BIT)
718 return -ENODATA;
719
720 *sample = (void *)((uintptr_t)rb->data +
721 (uintptr_t)((cons_pos + BPF_RINGBUF_HDR_SZ) & rb->mask));
722 *size = sample_len;
723 return 0;
724 }
725
__bpf_user_ringbuf_sample_release(struct bpf_ringbuf * rb,size_t size,u64 flags)726 static void __bpf_user_ringbuf_sample_release(struct bpf_ringbuf *rb, size_t size, u64 flags)
727 {
728 u64 consumer_pos;
729 u32 rounded_size = round_up(size + BPF_RINGBUF_HDR_SZ, 8);
730
731 /* Using smp_load_acquire() is unnecessary here, as the busy-bit
732 * prevents another task from writing to consumer_pos after it was read
733 * by this task with smp_load_acquire() in __bpf_user_ringbuf_peek().
734 */
735 consumer_pos = rb->consumer_pos;
736 /* Synchronizes with smp_load_acquire() in user-space producer. */
737 smp_store_release(&rb->consumer_pos, consumer_pos + rounded_size);
738 }
739
BPF_CALL_4(bpf_user_ringbuf_drain,struct bpf_map *,map,void *,callback_fn,void *,callback_ctx,u64,flags)740 BPF_CALL_4(bpf_user_ringbuf_drain, struct bpf_map *, map,
741 void *, callback_fn, void *, callback_ctx, u64, flags)
742 {
743 struct bpf_ringbuf *rb;
744 long samples, discarded_samples = 0, ret = 0;
745 bpf_callback_t callback = (bpf_callback_t)callback_fn;
746 u64 wakeup_flags = BPF_RB_NO_WAKEUP | BPF_RB_FORCE_WAKEUP;
747 int busy = 0;
748
749 if (unlikely(flags & ~wakeup_flags))
750 return -EINVAL;
751
752 rb = container_of(map, struct bpf_ringbuf_map, map)->rb;
753
754 /* If another consumer is already consuming a sample, wait for them to finish. */
755 if (!atomic_try_cmpxchg(&rb->busy, &busy, 1))
756 return -EBUSY;
757
758 for (samples = 0; samples < BPF_MAX_USER_RINGBUF_SAMPLES && ret == 0; samples++) {
759 int err;
760 u32 size;
761 void *sample;
762 struct bpf_dynptr_kern dynptr;
763
764 err = __bpf_user_ringbuf_peek(rb, &sample, &size);
765 if (err) {
766 if (err == -ENODATA) {
767 break;
768 } else if (err == -EAGAIN) {
769 discarded_samples++;
770 continue;
771 } else {
772 ret = err;
773 goto schedule_work_return;
774 }
775 }
776
777 bpf_dynptr_init(&dynptr, sample, BPF_DYNPTR_TYPE_LOCAL, 0, size);
778 ret = callback((uintptr_t)&dynptr, (uintptr_t)callback_ctx, 0, 0, 0);
779 __bpf_user_ringbuf_sample_release(rb, size, flags);
780 }
781 ret = samples - discarded_samples;
782
783 schedule_work_return:
784 /* Prevent the clearing of the busy-bit from being reordered before the
785 * storing of any rb consumer or producer positions.
786 */
787 atomic_set_release(&rb->busy, 0);
788
789 if (flags & BPF_RB_FORCE_WAKEUP)
790 irq_work_queue(&rb->work);
791 else if (!(flags & BPF_RB_NO_WAKEUP) && samples > 0)
792 irq_work_queue(&rb->work);
793 return ret;
794 }
795
796 const struct bpf_func_proto bpf_user_ringbuf_drain_proto = {
797 .func = bpf_user_ringbuf_drain,
798 .ret_type = RET_INTEGER,
799 .arg1_type = ARG_CONST_MAP_PTR,
800 .arg2_type = ARG_PTR_TO_FUNC,
801 .arg3_type = ARG_PTR_TO_STACK_OR_NULL,
802 .arg4_type = ARG_ANYTHING,
803 };
804