put tethering bpf maps & programs in /sys/fs/bpf/tethering/...

This makes it harder for system and mainline bpf programs to
conflict with each other, thus enabling easier mainline module
updates.

Test: builds and boots, atest, TreeHugger
Signed-off-by: Maciej Żenczykowski <maze@google.com>
Change-Id: Ic1b69bb1ddc4a10bd4861dadbd6b97e2520c532d
diff --git a/bpfloader/BpfLoader.cpp b/bpfloader/BpfLoader.cpp
index 9bc6451..7a68894 100644
--- a/bpfloader/BpfLoader.cpp
+++ b/bpfloader/BpfLoader.cpp
@@ -51,10 +51,23 @@
 using android::base::EndsWith;
 using std::string;
 
-#define BPF_PROG_PATH_MAINLINE_TETHERING "/apex/com.android.tethering/etc/bpf/"
-#define BPF_PROG_PATH_SYSTEM "/system/etc/bpf/"
+struct {
+    const char* const dir;
+    const char* const prefix;
+} locations[] = {
+        // Tethering mainline module
+        {
+                .dir = "/apex/com.android.tethering/etc/bpf/",
+                .prefix = "tethering/",
+        },
+        // Core operating system
+        {
+                .dir = "/system/etc/bpf/",
+                .prefix = "",
+        },
+};
 
-int loadAllElfObjects(const char* progDir) {
+int loadAllElfObjects(const char* const progDir, const char* const prefix) {
     int retVal = 0;
     DIR* dir;
     struct dirent* ent;
@@ -68,7 +81,7 @@
             progPath += s;
 
             bool critical;
-            int ret = android::bpf::loadProg(progPath.c_str(), &critical);
+            int ret = android::bpf::loadProg(progPath.c_str(), &critical, prefix);
             if (ret) {
                 if (critical) retVal = ret;
                 ALOGE("Failed to load object: %s, ret: %s", progPath.c_str(), std::strerror(-ret));
@@ -81,11 +94,29 @@
     return retVal;
 }
 
+void createSysFsBpfSubDir(const char* const prefix) {
+    if (*prefix) {
+        mode_t prevUmask = umask(0);
+
+        string s = "/sys/fs/bpf/";
+        s += prefix;
+
+        errno = 0;
+        int ret = mkdir(s.c_str(), S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO);
+        if (ret && errno != EEXIST) {
+            ALOGW("Failed to create directory: %s, ret: %s", s.c_str(), std::strerror(errno));
+        }
+
+        umask(prevUmask);
+    }
+}
+
 int main() {
     // Load all ELF objects, create programs and maps, and pin them
-    for (const auto dir : {BPF_PROG_PATH_MAINLINE_TETHERING, BPF_PROG_PATH_SYSTEM}) {
-        if (loadAllElfObjects(dir) != 0) {
-            ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", dir);
+    for (const auto location : locations) {
+        createSysFsBpfSubDir(location.prefix);
+        if (loadAllElfObjects(location.dir, location.prefix) != 0) {
+            ALOGE("=== CRITICAL FAILURE LOADING BPF PROGRAMS FROM %s ===", location.dir);
             ALOGE("If this triggers reliably, you're probably missing kernel options or patches.");
             ALOGE("If this triggers randomly, you might be hitting some memory allocation "
                   "problems or startup script race.");