1#!/bin/bash
2# Test data symbol
3
4# SPDX-License-Identifier: GPL-2.0
5# Leo Yan <leo.yan@linaro.org>, 2022
6
7skip_if_no_mem_event() {
8	perf mem record -e list 2>&1 | egrep -q 'available' && return 0
9	return 2
10}
11
12skip_if_no_mem_event || exit 2
13
14# skip if there's no compiler
15if ! [ -x "$(command -v cc)" ]; then
16	echo "skip: no compiler, install gcc"
17	exit 2
18fi
19
20TEST_PROGRAM=$(mktemp /tmp/__perf_test.program.XXXXX)
21PERF_DATA=$(mktemp /tmp/__perf_test.perf.data.XXXXX)
22
23check_result() {
24	# The memory report format is as below:
25	#    99.92%  ...  [.] buf1+0x38
26	result=$(perf mem report -i ${PERF_DATA} -s symbol_daddr -q 2>&1 |
27		 awk '/buf1/ { print $4 }')
28
29	# Testing is failed if has no any sample for "buf1"
30	[ -z "$result" ] && return 1
31
32	while IFS= read -r line; do
33		# The "data1" and "data2" fields in structure "buf1" have
34		# offset "0x0" and "0x38", returns failure if detect any
35		# other offset value.
36		if [ "$line" != "buf1+0x0" ] && [ "$line" != "buf1+0x38" ]; then
37			return 1
38		fi
39	done <<< "$result"
40
41	return 0
42}
43
44cleanup_files()
45{
46	echo "Cleaning up files..."
47	rm -f ${PERF_DATA}
48	rm -f ${TEST_PROGRAM}
49}
50
51trap cleanup_files exit term int
52
53# compile test program
54echo "Compiling test program..."
55cat << EOF | cc -o ${TEST_PROGRAM} -x c -
56typedef struct _buf {
57	char data1;
58	char reserved[55];
59	char data2;
60} buf __attribute__((aligned(64)));
61
62static buf buf1;
63
64int main(void) {
65	for (;;) {
66		buf1.data1++;
67		buf1.data2 += buf1.data1;
68	}
69	return 0;
70}
71EOF
72
73echo "Recording workload..."
74
75# perf mem/c2c internally uses IBS PMU on AMD CPU which doesn't support
76# user/kernel filtering and per-process monitoring, spin program on
77# specific CPU and test in per-CPU mode.
78is_amd=$(egrep -c 'vendor_id.*AuthenticAMD' /proc/cpuinfo)
79if (($is_amd >= 1)); then
80	perf mem record -o ${PERF_DATA} -C 0 -- taskset -c 0 $TEST_PROGRAM &
81else
82	perf mem record --all-user -o ${PERF_DATA} -- $TEST_PROGRAM &
83fi
84
85PERFPID=$!
86
87sleep 1
88
89kill $PERFPID
90wait $PERFPID
91
92check_result
93exit $?
94