xref: /linux/kernel/bpf/stream.c (revision 2b5440b31cafad2fb4b4a83efb780a6d7430a385)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
3 
4 #include <linux/bpf.h>
5 #include <linux/anon_inodes.h>
6 #include <linux/filter.h>
7 #include <linux/bpf_mem_alloc.h>
8 #include <linux/gfp.h>
9 #include <linux/irq_work.h>
10 #include <linux/memory.h>
11 #include <linux/mutex.h>
12 #include <linux/poll.h>
13 #include <linux/refcount.h>
14 
15 static void bpf_stream_elem_init(struct bpf_stream_elem *elem, int len)
16 {
17 	init_llist_node(&elem->node);
18 	elem->total_len = len;
19 	elem->consumed_len = 0;
20 }
21 
22 static struct bpf_stream_elem *bpf_stream_elem_alloc(int len)
23 {
24 	const int max_len = ARRAY_SIZE((struct bpf_bprintf_buffers){}.buf);
25 	struct bpf_stream_elem *elem;
26 	size_t alloc_size;
27 
28 	/*
29 	 * Length is the payload pushed into the stream, excluding the
30 	 * trailing NUL of the bprintf buffer. Reject anything that cannot
31 	 * fit without copying that NUL into the stream element.
32 	 */
33 	if (len < 0 || len >= max_len)
34 		return NULL;
35 
36 	alloc_size = offsetof(struct bpf_stream_elem, str[len]);
37 	elem = kmalloc_nolock(alloc_size, __GFP_ZERO, -1);
38 	if (!elem)
39 		return NULL;
40 
41 	bpf_stream_elem_init(elem, len);
42 
43 	return elem;
44 }
45 
46 static int __bpf_stream_push_str(struct llist_head *log, const char *str, int len)
47 {
48 	struct bpf_stream_elem *elem = NULL;
49 
50 	/*
51 	 * Allocate a bpf_prog_stream_elem and push it to the bpf_prog_stream
52 	 * log, elements will be popped at once and reversed to print the log.
53 	 */
54 	elem = bpf_stream_elem_alloc(len);
55 	if (!elem)
56 		return -ENOMEM;
57 
58 	memcpy(elem->str, str, len);
59 	llist_add(&elem->node, log);
60 
61 	return 0;
62 }
63 
64 static int bpf_stream_consume_capacity(struct bpf_stream *stream, int len)
65 {
66 	if (atomic_read(&stream->capacity) >= BPF_STREAM_MAX_CAPACITY)
67 		return -ENOSPC;
68 	if (atomic_add_return(len, &stream->capacity) >= BPF_STREAM_MAX_CAPACITY) {
69 		atomic_sub(len, &stream->capacity);
70 		return -ENOSPC;
71 	}
72 	return 0;
73 }
74 
75 static void bpf_stream_release_capacity(struct bpf_stream *stream, int len)
76 {
77 	atomic_sub(len, &stream->capacity);
78 }
79 
80 static void bpf_stream_notify(struct irq_work *work)
81 {
82 	struct bpf_stream *stream = container_of(work, struct bpf_stream, notify_work);
83 
84 	/*
85 	 * Writers run in arbitrary program contexts, including NMI and regions
86 	 * that already hold wait queue or epoll locks. Wake waiters from
87 	 * irq_work instead, where taking those locks is safe.
88 	 */
89 	wake_up_interruptible_poll(&stream->waitq, EPOLLIN | EPOLLRDNORM);
90 }
91 
92 static void bpf_stream_queue_notify(struct bpf_stream *stream)
93 {
94 	/*
95 	 * Record that the work has been used so that teardown only pays for
96 	 * irq_work_sync(), which may wait for an RCU grace period, when a
97 	 * callback could actually be in flight.
98 	 */
99 	if (!READ_ONCE(stream->notify_used))
100 		WRITE_ONCE(stream->notify_used, true);
101 	irq_work_queue(&stream->notify_work);
102 }
103 
104 static int bpf_stream_readable_bytes(struct bpf_stream *stream)
105 {
106 	return atomic_read_acquire(&stream->readable);
107 }
108 
109 static void bpf_stream_publish(struct bpf_stream *stream, int len)
110 {
111 	/*
112 	 * Pairs with atomic_read_acquire() in bpf_stream_readable_bytes().
113 	 *
114 	 * Notify only when the stream turns from empty to readable. Readers
115 	 * block and pollers wait only after finding it empty, and a read never
116 	 * takes the count below zero, so the publication that makes it positive
117 	 * is the one they wait for. Publishing into a stream that already holds
118 	 * data would only raise an interrupt for waiters that are being woken
119 	 * already, or for nobody at all.
120 	 */
121 	if (atomic_add_return_release(len, &stream->readable) == len)
122 		bpf_stream_queue_notify(stream);
123 }
124 
125 static int bpf_stream_push_str(struct bpf_stream *stream, const char *str, int len)
126 {
127 	int ret;
128 
129 	/* Nothing to publish; do not allocate an element for it. */
130 	if (!len)
131 		return 0;
132 
133 	ret = bpf_stream_consume_capacity(stream, len);
134 	if (ret)
135 		return ret;
136 
137 	ret = __bpf_stream_push_str(&stream->log, str, len);
138 	if (ret)
139 		bpf_stream_release_capacity(stream, len);
140 	else
141 		bpf_stream_publish(stream, len);
142 
143 	return ret;
144 }
145 
146 static struct bpf_stream *bpf_stream_get(enum bpf_stream_id stream_id, struct bpf_prog_aux *aux)
147 {
148 	if (stream_id != BPF_STDOUT && stream_id != BPF_STDERR)
149 		return NULL;
150 	return aux->stream[stream_id - 1];
151 }
152 
153 static void bpf_stream_free_elem(struct bpf_stream_elem *elem)
154 {
155 	kfree_nolock(elem);
156 }
157 
158 static void bpf_stream_free_list(struct llist_node *list)
159 {
160 	struct bpf_stream_elem *elem, *tmp;
161 
162 	llist_for_each_entry_safe(elem, tmp, list, node)
163 		bpf_stream_free_elem(elem);
164 }
165 
166 static struct llist_node *bpf_stream_backlog_peek(struct bpf_stream *stream)
167 {
168 	return stream->backlog_head;
169 }
170 
171 static struct llist_node *bpf_stream_backlog_pop(struct bpf_stream *stream)
172 {
173 	struct llist_node *node;
174 
175 	node = stream->backlog_head;
176 	if (stream->backlog_head == stream->backlog_tail)
177 		stream->backlog_head = stream->backlog_tail = NULL;
178 	else
179 		stream->backlog_head = node->next;
180 	return node;
181 }
182 
183 static void bpf_stream_backlog_fill(struct bpf_stream *stream)
184 {
185 	struct llist_node *head, *tail;
186 
187 	if (llist_empty(&stream->log))
188 		return;
189 	tail = llist_del_all(&stream->log);
190 	if (!tail)
191 		return;
192 	head = llist_reverse_order(tail);
193 
194 	if (!stream->backlog_head) {
195 		stream->backlog_head = head;
196 		stream->backlog_tail = tail;
197 	} else {
198 		stream->backlog_tail->next = head;
199 		stream->backlog_tail = tail;
200 	}
201 
202 	return;
203 }
204 
205 static bool bpf_stream_consume_elem(struct bpf_stream_elem *elem, int *len)
206 {
207 	int rem = elem->total_len - elem->consumed_len;
208 	int used = min(rem, *len);
209 
210 	elem->consumed_len += used;
211 	*len -= used;
212 
213 	return elem->consumed_len == elem->total_len;
214 }
215 
216 static int bpf_stream_read(struct bpf_stream *stream, void __user *buf, int len)
217 {
218 	int read_len, rem_len, cons_len, ret = 0;
219 	struct bpf_stream_elem *elem = NULL;
220 	struct llist_node *node;
221 
222 	mutex_lock(&stream->lock);
223 	read_len = min(len, bpf_stream_readable_bytes(stream));
224 	rem_len = read_len;
225 
226 	while (rem_len) {
227 		int pos = read_len - rem_len;
228 		int chunk, n;
229 		bool cont;
230 
231 		node = bpf_stream_backlog_peek(stream);
232 		if (!node) {
233 			bpf_stream_backlog_fill(stream);
234 			node = bpf_stream_backlog_peek(stream);
235 		}
236 		if (!node)
237 			break;
238 		elem = container_of(node, typeof(*elem), node);
239 
240 		cons_len = elem->consumed_len;
241 		cont = bpf_stream_consume_elem(elem, &rem_len) == false;
242 		chunk = elem->consumed_len - cons_len;
243 
244 		n = copy_to_user(buf + pos, elem->str + cons_len, chunk);
245 		if (n) {
246 			/* Keep any successfully copied bytes; -EFAULT only if none. */
247 			elem->consumed_len -= n;
248 			rem_len += n;
249 			ret = (read_len == rem_len) ? -EFAULT : 0;
250 			break;
251 		}
252 
253 		if (cont)
254 			continue;
255 		bpf_stream_backlog_pop(stream);
256 		bpf_stream_release_capacity(stream, elem->total_len);
257 		bpf_stream_free_elem(elem);
258 	}
259 
260 	atomic_sub(read_len - rem_len, &stream->readable);
261 	mutex_unlock(&stream->lock);
262 	return ret ? ret : read_len - rem_len;
263 }
264 
265 int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, u32 len)
266 {
267 	struct bpf_stream *stream;
268 
269 	stream = bpf_stream_get(stream_id, prog->aux);
270 	if (!stream)
271 		return -ENOENT;
272 	if (len > INT_MAX)
273 		return -EINVAL;
274 	return bpf_stream_read(stream, buf, len);
275 }
276 
277 static bool bpf_stream_has_data(struct bpf_stream *stream)
278 {
279 	return bpf_stream_readable_bytes(stream) > 0;
280 }
281 
282 static void bpf_stream_put(struct bpf_stream *stream)
283 {
284 	if (refcount_dec_and_test(&stream->refcnt)) {
285 		struct llist_node *list;
286 
287 		/* Only a stream that ever queued its work can have a callback in flight. */
288 		if (READ_ONCE(stream->notify_used))
289 			irq_work_sync(&stream->notify_work);
290 		list = llist_del_all(&stream->log);
291 		bpf_stream_free_list(list);
292 		bpf_stream_free_list(stream->backlog_head);
293 		mutex_destroy(&stream->lock);
294 		kfree(stream);
295 	}
296 }
297 
298 static int bpf_stream_release(struct inode *inode, struct file *file)
299 {
300 	bpf_stream_put(file->private_data);
301 	return 0;
302 }
303 
304 static ssize_t bpf_stream_file_read(struct file *file, char __user *buf, size_t len,
305 				    loff_t *ppos)
306 {
307 	struct bpf_stream *stream = file->private_data;
308 	bool dead;
309 	int ret;
310 
311 	if (!len)
312 		return 0;
313 
314 	for (;;) {
315 		/*
316 		 * Sample teardown state before looking for data. Nothing is
317 		 * published once the program is gone, so finding the stream
318 		 * empty after observing dead means EOF. The opposite order could
319 		 * report EOF while data published just before teardown is still
320 		 * buffered.
321 		 */
322 		dead = smp_load_acquire(&stream->dead);
323 		ret = bpf_stream_read(stream, buf, len);
324 		if (ret)
325 			return ret;
326 		if (dead)
327 			return 0;
328 		if (file->f_flags & O_NONBLOCK)
329 			return -EAGAIN;
330 
331 		ret = wait_event_interruptible(stream->waitq,
332 					       bpf_stream_has_data(stream) ||
333 					       READ_ONCE(stream->dead));
334 		if (ret)
335 			return ret;
336 	}
337 }
338 
339 static __poll_t bpf_stream_poll(struct file *file, struct poll_table_struct *pts)
340 {
341 	struct bpf_stream *stream = file->private_data;
342 	__poll_t events = 0;
343 
344 	/*
345 	 * poll_wait() only registers the wait queue callback. Register before
346 	 * checking persistent state so a concurrent publication or teardown is
347 	 * observed either by the callback or by the checks below.
348 	 */
349 	poll_wait(file, &stream->waitq, pts);
350 	if (bpf_stream_has_data(stream))
351 		events |= EPOLLIN | EPOLLRDNORM;
352 	if (READ_ONCE(stream->dead))
353 		events |= EPOLLHUP;
354 	return events;
355 }
356 
357 static const struct file_operations bpf_stream_fops = {
358 	.release = bpf_stream_release,
359 	.read = bpf_stream_file_read,
360 	.poll = bpf_stream_poll,
361 };
362 
363 int bpf_prog_stream_new_fd(struct bpf_prog *prog, enum bpf_stream_id stream_id, u32 flags)
364 {
365 	struct bpf_stream *stream;
366 	int fd_flags = O_RDONLY | O_CLOEXEC;
367 	int fd;
368 
369 	stream = bpf_stream_get(stream_id, prog->aux);
370 	if (!stream)
371 		return -ENOENT;
372 	if (flags & BPF_F_STREAM_NONBLOCK)
373 		fd_flags |= O_NONBLOCK;
374 
375 	refcount_inc(&stream->refcnt);
376 	fd = anon_inode_getfd("bpf-stream", &bpf_stream_fops, stream, fd_flags);
377 	if (fd < 0)
378 		bpf_stream_put(stream);
379 	return fd;
380 }
381 
382 __bpf_kfunc_start_defs();
383 
384 /*
385  * Avoid using enum bpf_stream_id so that kfunc users don't have to pull in the
386  * enum in headers.
387  */
388 __bpf_kfunc int bpf_stream_vprintk(int stream_id, const char *fmt__str, const void *args,
389 				   u32 len__sz, struct bpf_prog_aux *aux)
390 {
391 	struct bpf_bprintf_data data = {
392 		.get_bin_args	= true,
393 		.get_buf	= true,
394 	};
395 	u32 fmt_size = strlen(fmt__str) + 1;
396 	struct bpf_stream *stream;
397 	u32 data_len = len__sz;
398 	int ret, num_args;
399 
400 	stream = bpf_stream_get(stream_id, aux);
401 	if (!stream)
402 		return -ENOENT;
403 
404 	if (data_len & 7 || data_len > MAX_BPRINTF_VARARGS * 8 ||
405 	    (data_len && !args))
406 		return -EINVAL;
407 	num_args = data_len / 8;
408 
409 	ret = bpf_bprintf_prepare(fmt__str, fmt_size, args, num_args, &data);
410 	if (ret < 0)
411 		return ret;
412 
413 	ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt__str, data.bin_args);
414 	/* Truncation: reject before capacity charge (not -ENOMEM). */
415 	if (ret >= MAX_BPRINTF_BUF) {
416 		bpf_bprintf_cleanup(&data);
417 		return -E2BIG;
418 	}
419 	/* Exclude NULL byte during push. */
420 	ret = bpf_stream_push_str(stream, data.buf, ret);
421 	bpf_bprintf_cleanup(&data);
422 
423 	return ret;
424 }
425 
426 /* Directly trigger a stack dump from the program. */
427 __bpf_kfunc int bpf_stream_print_stack(int stream_id, struct bpf_prog_aux *aux)
428 {
429 	struct bpf_stream_stage ss;
430 	struct bpf_prog *prog;
431 
432 	/* Make sure the stream ID is valid. */
433 	if (!bpf_stream_get(stream_id, aux))
434 		return -ENOENT;
435 
436 	prog = aux->main_prog_aux->prog;
437 
438 	bpf_stream_stage(ss, prog, stream_id, ({
439 		bpf_stream_dump_stack(ss);
440 	}));
441 
442 	return 0;
443 }
444 
445 __bpf_kfunc_end_defs();
446 
447 /* Added kfunc to common_btf_ids */
448 
449 int bpf_prog_stream_init(struct bpf_prog *prog, gfp_t gfp_extra_flags)
450 {
451 	int i;
452 
453 	for (i = 0; i < ARRAY_SIZE(prog->aux->stream); i++) {
454 		struct bpf_stream *stream;
455 
456 		/* On failure, bpf_prog_stream_free() releases the streams allocated so far. */
457 		stream = kzalloc_obj(*stream,
458 				     bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
459 		if (!stream)
460 			return -ENOMEM;
461 
462 		refcount_set(&stream->refcnt, 1);
463 		init_llist_head(&stream->log);
464 		mutex_init(&stream->lock);
465 		init_waitqueue_head(&stream->waitq);
466 		init_irq_work(&stream->notify_work, bpf_stream_notify);
467 		prog->aux->stream[i] = stream;
468 	}
469 	return 0;
470 }
471 
472 void bpf_prog_stream_free(struct bpf_prog *prog)
473 {
474 	int i;
475 
476 	for (i = 0; i < ARRAY_SIZE(prog->aux->stream); i++) {
477 		struct bpf_stream *stream = prog->aux->stream[i];
478 
479 		if (!stream)
480 			continue;
481 		/*
482 		 * Pairs with smp_load_acquire() in bpf_stream_file_read(): every
483 		 * publication precedes the dead flag, so a reader that observes
484 		 * it also observes all buffered data.
485 		 */
486 		smp_store_release(&stream->dead, true);
487 		wake_up_interruptible_poll(&stream->waitq, EPOLLHUP);
488 		bpf_stream_put(stream);
489 		prog->aux->stream[i] = NULL;
490 	}
491 }
492 
493 void bpf_stream_stage_init(struct bpf_stream_stage *ss)
494 {
495 	init_llist_head(&ss->log);
496 	ss->len = 0;
497 }
498 
499 void bpf_stream_stage_free(struct bpf_stream_stage *ss)
500 {
501 	struct llist_node *node;
502 
503 	node = llist_del_all(&ss->log);
504 	bpf_stream_free_list(node);
505 }
506 
507 int bpf_stream_stage_printk(struct bpf_stream_stage *ss, const char *fmt, ...)
508 {
509 	struct bpf_bprintf_buffers *buf;
510 	va_list args;
511 	int len, ret;
512 
513 	if (bpf_try_get_buffers(&buf))
514 		return -EBUSY;
515 
516 	va_start(args, fmt);
517 	len = vscnprintf(buf->buf, ARRAY_SIZE(buf->buf), fmt, args);
518 	va_end(args);
519 	/* Exclude NULL byte during push; skip empty output entirely. */
520 	ret = len ? __bpf_stream_push_str(&ss->log, buf->buf, len) : 0;
521 	if (!ret)
522 		ss->len += len;
523 	bpf_put_buffers();
524 	return ret;
525 }
526 
527 int bpf_stream_stage_commit(struct bpf_stream_stage *ss, struct bpf_prog *prog,
528 			    enum bpf_stream_id stream_id)
529 {
530 	struct llist_node *list, *head, *tail;
531 	struct bpf_stream *stream;
532 	int ret;
533 
534 	stream = bpf_stream_get(stream_id, prog->aux);
535 	if (!stream)
536 		return -EINVAL;
537 
538 	ret = bpf_stream_consume_capacity(stream, ss->len);
539 	if (ret)
540 		return ret;
541 
542 	list = llist_del_all(&ss->log);
543 	head = tail = list;
544 
545 	if (!list)
546 		return 0;
547 	while (llist_next(list)) {
548 		tail = llist_next(list);
549 		list = tail;
550 	}
551 	llist_add_batch(head, tail, &stream->log);
552 	bpf_stream_publish(stream, ss->len);
553 	return 0;
554 }
555 
556 struct dump_stack_ctx {
557 	struct bpf_stream_stage *ss;
558 	int err;
559 };
560 
561 static bool dump_stack_cb(void *cookie, u64 ip, u64 sp, u64 bp)
562 {
563 	struct dump_stack_ctx *ctxp = cookie;
564 	const char *file = "", *line = "";
565 	struct bpf_prog *prog;
566 	int num, ret;
567 
568 	rcu_read_lock();
569 	prog = bpf_prog_ksym_find(ip);
570 	rcu_read_unlock();
571 	if (prog) {
572 		ret = bpf_prog_get_file_line(prog, ip, &file, &line, &num);
573 		if (ret < 0)
574 			goto end;
575 		ctxp->err = bpf_stream_stage_printk(ctxp->ss, "%pS\n  %s @ %s:%d\n",
576 						    (void *)(long)ip, line, file, num);
577 		return !ctxp->err;
578 	}
579 end:
580 	ctxp->err = bpf_stream_stage_printk(ctxp->ss, "%pS\n", (void *)(long)ip);
581 	return !ctxp->err;
582 }
583 
584 int bpf_stream_stage_dump_stack(struct bpf_stream_stage *ss)
585 {
586 	struct dump_stack_ctx ctx = { .ss = ss };
587 	int ret;
588 
589 	ret = bpf_stream_stage_printk(ss, "CPU: %d UID: %d PID: %d Comm: %s\n",
590 				      raw_smp_processor_id(), __kuid_val(current_real_cred()->euid),
591 				      current->pid, current->comm);
592 	if (ret)
593 		return ret;
594 	ret = bpf_stream_stage_printk(ss, "Call trace:\n");
595 	if (ret)
596 		return ret;
597 	arch_bpf_stack_walk(dump_stack_cb, &ctx);
598 	if (ctx.err)
599 		return ctx.err;
600 	return bpf_stream_stage_printk(ss, "\n");
601 }
602