1// SPDX-License-Identifier: GPL-2.0
2/* Copyright (c) 2020, Oracle and/or its affiliates. */
3
4#include <test_progs.h>
5
6#include "trace_printk.lskel.h"
7
8#define TRACEFS_PIPE	"/sys/kernel/tracing/trace_pipe"
9#define DEBUGFS_PIPE	"/sys/kernel/debug/tracing/trace_pipe"
10#define SEARCHMSG	"testing,testing"
11
12void serial_test_trace_printk(void)
13{
14	struct trace_printk_lskel__bss *bss;
15	int err = 0, iter = 0, found = 0;
16	struct trace_printk_lskel *skel;
17	char *buf = NULL;
18	FILE *fp = NULL;
19	size_t buflen;
20
21	skel = trace_printk_lskel__open();
22	if (!ASSERT_OK_PTR(skel, "trace_printk__open"))
23		return;
24
25	ASSERT_EQ(skel->rodata->fmt[0], 'T', "skel->rodata->fmt[0]");
26	skel->rodata->fmt[0] = 't';
27
28	err = trace_printk_lskel__load(skel);
29	if (!ASSERT_OK(err, "trace_printk__load"))
30		goto cleanup;
31
32	bss = skel->bss;
33
34	err = trace_printk_lskel__attach(skel);
35	if (!ASSERT_OK(err, "trace_printk__attach"))
36		goto cleanup;
37
38	if (access(TRACEFS_PIPE, F_OK) == 0)
39		fp = fopen(TRACEFS_PIPE, "r");
40	else
41		fp = fopen(DEBUGFS_PIPE, "r");
42	if (!ASSERT_OK_PTR(fp, "fopen(TRACE_PIPE)"))
43		goto cleanup;
44
45	/* We do not want to wait forever if this test fails... */
46	fcntl(fileno(fp), F_SETFL, O_NONBLOCK);
47
48	/* wait for tracepoint to trigger */
49	usleep(1);
50	trace_printk_lskel__detach(skel);
51
52	if (!ASSERT_GT(bss->trace_printk_ran, 0, "bss->trace_printk_ran"))
53		goto cleanup;
54
55	if (!ASSERT_GT(bss->trace_printk_ret, 0, "bss->trace_printk_ret"))
56		goto cleanup;
57
58	/* verify our search string is in the trace buffer */
59	while (getline(&buf, &buflen, fp) >= 0 || errno == EAGAIN) {
60		if (strstr(buf, SEARCHMSG) != NULL)
61			found++;
62		if (found == bss->trace_printk_ran)
63			break;
64		if (++iter > 1000)
65			break;
66	}
67
68	if (!ASSERT_EQ(found, bss->trace_printk_ran, "found"))
69		goto cleanup;
70
71cleanup:
72	trace_printk_lskel__destroy(skel);
73	free(buf);
74	if (fp)
75		fclose(fp);
76}
77