1# SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2include ../../scripts/Makefile.include
3
4OUTPUT ?= $(abspath .output)/
5
6BPFTOOL_OUTPUT := $(OUTPUT)bpftool/
7DEFAULT_BPFTOOL := $(BPFTOOL_OUTPUT)bpftool
8BPFTOOL ?= $(DEFAULT_BPFTOOL)
9LIBBPF_SRC := $(abspath ../../lib/bpf)
10BPFOBJ_OUTPUT := $(OUTPUT)libbpf/
11BPFOBJ := $(BPFOBJ_OUTPUT)libbpf.a
12BPF_DESTDIR := $(BPFOBJ_OUTPUT)
13BPF_INCLUDE := $(BPF_DESTDIR)/include
14INCLUDES := -I$(OUTPUT) -I$(BPF_INCLUDE) -I$(abspath ../../include/uapi)
15CFLAGS := -g -Wall
16
17# Try to detect best kernel BTF source
18KERNEL_REL := $(shell uname -r)
19VMLINUX_BTF_PATHS := $(if $(O),$(O)/vmlinux)		\
20	$(if $(KBUILD_OUTPUT),$(KBUILD_OUTPUT)/vmlinux) \
21	../../../vmlinux /sys/kernel/btf/vmlinux	\
22	/boot/vmlinux-$(KERNEL_REL)
23VMLINUX_BTF_PATH := $(or $(VMLINUX_BTF),$(firstword			       \
24					  $(wildcard $(VMLINUX_BTF_PATHS))))
25
26ifeq ($(V),1)
27Q =
28else
29Q = @
30MAKEFLAGS += --no-print-directory
31submake_extras := feature_display=0
32endif
33
34.DELETE_ON_ERROR:
35
36.PHONY: all clean runqslower libbpf_hdrs
37all: runqslower
38
39runqslower: $(OUTPUT)/runqslower
40
41clean:
42	$(call QUIET_CLEAN, runqslower)
43	$(Q)$(RM) -r $(BPFOBJ_OUTPUT) $(BPFTOOL_OUTPUT)
44	$(Q)$(RM) $(OUTPUT)*.o $(OUTPUT)*.d
45	$(Q)$(RM) $(OUTPUT)*.skel.h $(OUTPUT)vmlinux.h
46	$(Q)$(RM) $(OUTPUT)runqslower
47	$(Q)$(RM) -r .output
48
49libbpf_hdrs: $(BPFOBJ)
50
51$(OUTPUT)/runqslower: $(OUTPUT)/runqslower.o $(BPFOBJ)
52	$(QUIET_LINK)$(CC) $(CFLAGS) $^ -lelf -lz -o $@
53
54$(OUTPUT)/runqslower.o: runqslower.h $(OUTPUT)/runqslower.skel.h	      \
55			$(OUTPUT)/runqslower.bpf.o | libbpf_hdrs
56
57$(OUTPUT)/runqslower.bpf.o: $(OUTPUT)/vmlinux.h runqslower.h | libbpf_hdrs
58
59$(OUTPUT)/%.skel.h: $(OUTPUT)/%.bpf.o | $(BPFTOOL)
60	$(QUIET_GEN)$(BPFTOOL) gen skeleton $< > $@
61
62$(OUTPUT)/%.bpf.o: %.bpf.c $(BPFOBJ) | $(OUTPUT)
63	$(QUIET_GEN)$(CLANG) -g -O2 -target bpf $(INCLUDES)		      \
64		 -c $(filter %.c,$^) -o $@ &&				      \
65	$(LLVM_STRIP) -g $@
66
67$(OUTPUT)/%.o: %.c | $(OUTPUT)
68	$(QUIET_CC)$(CC) $(CFLAGS) $(INCLUDES) -c $(filter %.c,$^) -o $@
69
70$(OUTPUT) $(BPFOBJ_OUTPUT) $(BPFTOOL_OUTPUT):
71	$(QUIET_MKDIR)mkdir -p $@
72
73$(OUTPUT)/vmlinux.h: $(VMLINUX_BTF_PATH) | $(OUTPUT) $(BPFTOOL)
74ifeq ($(VMLINUX_H),)
75	$(Q)if [ ! -e "$(VMLINUX_BTF_PATH)" ] ; then \
76		echo "Couldn't find kernel BTF; set VMLINUX_BTF to"	       \
77			"specify its location." >&2;			       \
78		exit 1;\
79	fi
80	$(QUIET_GEN)$(BPFTOOL) btf dump file $(VMLINUX_BTF_PATH) format c > $@
81else
82	$(Q)cp "$(VMLINUX_H)" $@
83endif
84
85$(BPFOBJ): $(wildcard $(LIBBPF_SRC)/*.[ch] $(LIBBPF_SRC)/Makefile) | $(BPFOBJ_OUTPUT)
86	$(Q)$(MAKE) $(submake_extras) -C $(LIBBPF_SRC) OUTPUT=$(BPFOBJ_OUTPUT) \
87		    DESTDIR=$(BPFOBJ_OUTPUT) prefix= $(abspath $@) install_headers
88
89$(DEFAULT_BPFTOOL): $(BPFOBJ) | $(BPFTOOL_OUTPUT)
90	$(Q)$(MAKE) $(submake_extras) -C ../bpftool OUTPUT=$(BPFTOOL_OUTPUT)   \
91		    CC=$(HOSTCC) LD=$(HOSTLD)
92