1# SPDX-License-Identifier: GPL-2.0
2OUTPUT := .output
3abs_out := $(abspath $(OUTPUT))
4
5CLANG ?= clang
6LLC ?= llc
7LLVM_STRIP ?= llvm-strip
8
9TOOLS_PATH := $(abspath ../../../../tools)
10BPFTOOL_SRC := $(TOOLS_PATH)/bpf/bpftool
11BPFTOOL_OUTPUT := $(abs_out)/bpftool
12DEFAULT_BPFTOOL := $(BPFTOOL_OUTPUT)/bootstrap/bpftool
13BPFTOOL ?= $(DEFAULT_BPFTOOL)
14
15LIBBPF_SRC := $(TOOLS_PATH)/lib/bpf
16LIBBPF_OUTPUT := $(abs_out)/libbpf
17LIBBPF_DESTDIR := $(LIBBPF_OUTPUT)
18LIBBPF_INCLUDE := $(LIBBPF_DESTDIR)/include
19BPFOBJ := $(LIBBPF_OUTPUT)/libbpf.a
20
21INCLUDES := -I$(OUTPUT) -I$(LIBBPF_INCLUDE) -I$(TOOLS_PATH)/include/uapi
22CFLAGS := -g -Wall
23
24VMLINUX_BTF_PATHS ?= $(if $(O),$(O)/vmlinux)				\
25		     $(if $(KBUILD_OUTPUT),$(KBUILD_OUTPUT)/vmlinux)	\
26		     ../../../../vmlinux				\
27		     /sys/kernel/btf/vmlinux				\
28		     /boot/vmlinux-$(shell uname -r)
29VMLINUX_BTF ?= $(abspath $(firstword $(wildcard $(VMLINUX_BTF_PATHS))))
30ifeq ($(VMLINUX_BTF),)
31$(error Cannot find a vmlinux for VMLINUX_BTF at any of "$(VMLINUX_BTF_PATHS)")
32endif
33
34ifeq ($(V),1)
35Q =
36msg =
37else
38Q = @
39msg = @printf '  %-8s %s%s\n' "$(1)" "$(notdir $(2))" "$(if $(3), $(3))";
40MAKEFLAGS += --no-print-directory
41submake_extras := feature_display=0
42endif
43
44.DELETE_ON_ERROR:
45
46.PHONY: all clean
47
48SOURCES = $(wildcard *.bpf.c)
49TARGETS = $(SOURCES:.bpf.c=.bpf.o)
50
51all: $(TARGETS)
52
53clean:
54	$(call msg,CLEAN)
55	$(Q)rm -rf $(OUTPUT) $(TARGETS)
56
57%.bpf.o: %.bpf.c vmlinux.h $(BPFOBJ) | $(OUTPUT)
58	$(call msg,BPF,$@)
59	$(Q)$(CLANG) -g -O2 --target=bpf -Wall -Werror $(INCLUDES)	      \
60		 -c $(filter %.c,$^) -o $@ &&				      \
61	$(LLVM_STRIP) -g $@
62
63vmlinux.h: $(VMLINUX_BTF) $(BPFTOOL) | $(INCLUDE_DIR)
64ifeq ($(VMLINUX_H),)
65	$(call msg,GEN,,$@)
66	$(Q)$(BPFTOOL) btf dump file $(VMLINUX_BTF) format c > $@
67else
68	$(call msg,CP,,$@)
69	$(Q)cp "$(VMLINUX_H)" $@
70endif
71
72$(OUTPUT) $(LIBBPF_OUTPUT) $(BPFTOOL_OUTPUT):
73	$(call msg,MKDIR,$@)
74	$(Q)mkdir -p $@
75
76$(BPFOBJ): $(wildcard $(LIBBPF_SRC)/*.[ch] $(LIBBPF_SRC)/Makefile) | $(LIBBPF_OUTPUT)
77	$(Q)$(MAKE) $(submake_extras) -C $(LIBBPF_SRC)			       \
78		    OUTPUT=$(abspath $(dir $@))/ prefix=		       \
79		    DESTDIR=$(LIBBPF_DESTDIR) $(abspath $@) install_headers
80
81ifeq ($(CROSS_COMPILE),)
82$(DEFAULT_BPFTOOL): $(BPFOBJ) | $(BPFTOOL_OUTPUT)
83	$(Q)$(MAKE) $(submake_extras) -C $(BPFTOOL_SRC)			       \
84		    OUTPUT=$(BPFTOOL_OUTPUT)/				       \
85		    LIBBPF_BOOTSTRAP_OUTPUT=$(LIBBPF_OUTPUT)/		       \
86		    LIBBPF_BOOTSTRAP_DESTDIR=$(LIBBPF_DESTDIR)/ bootstrap
87else
88$(DEFAULT_BPFTOOL): | $(BPFTOOL_OUTPUT)
89	$(Q)$(MAKE) $(submake_extras) -C $(BPFTOOL_SRC)			       \
90		    OUTPUT=$(BPFTOOL_OUTPUT)/ bootstrap
91endif
92