blob: a894b57932a1c50332c996d6c334bb2f7a9b1ff8 [file] [log] [blame]
Chenbo Feng75b410b2018-10-10 15:01:19 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef BPF_BPFMAP_H
18#define BPF_BPFMAP_H
19
20#include <linux/bpf.h>
21
22#include <android-base/stringprintf.h>
23#include <android-base/unique_fd.h>
24#include <utils/Log.h>
25#include "bpf/BpfUtils.h"
26#include "netdutils/Status.h"
27#include "netdutils/StatusOr.h"
28
29namespace android {
30namespace bpf {
31
32// This is a class wrapper for eBPF maps. The eBPF map is a special in-kernel
33// data structure that stores data in <Key, Value> pairs. It can be read/write
34// from userspace by passing syscalls with the map file descriptor. This class
35// is used to generalize the procedure of interacting with eBPF maps and hide
36// the implementation detail from other process. Besides the basic syscalls
37// wrapper, it also provides some useful helper functions as well as an iterator
38// nested class to iterate the map more easily.
39//
40// NOTE: A kernel eBPF map may be accessed by both kernel and userspace
41// processes at the same time. Or if the map is pinned as a virtual file, it can
42// be obtained by multiple eBPF map class object and accessed concurrently.
43// Though the map class object and the underlying kernel map are thread safe, it
44// is not safe to iterate over a map while another thread or process is deleting
45// from it. In this case the iteration can return duplicate entries.
46template <class Key, class Value>
47class BpfMap {
48 public:
Maciej Żenczykowskie6cbd402019-08-09 18:20:26 -070049 BpfMap<Key, Value>() {};
Chenbo Feng4c9e9ec2018-10-16 20:31:52 -070050 explicit BpfMap<Key, Value>(int fd) : mMapFd(fd){};
Maciej Żenczykowskie6cbd402019-08-09 18:20:26 -070051
52 // We could technically implement this constructor either with
53 // : mMapFd(dup(fd)) {} // fd valid in caller, we have our own local copy
54 // or
55 // : mMapFd(fd.release()) {} // fd no longer valid in caller, we 'stole' it
56 //
57 // However, I think we're much better off with a compile time failure, since
58 // it's better for whoever passes in a unique_fd to think twice about whether
59 // they're trying to pass in ownership or not.
60 explicit BpfMap<Key, Value>(base::unique_fd fd) = delete;
61
Chenbo Feng75b410b2018-10-10 15:01:19 -070062 BpfMap<Key, Value>(bpf_map_type map_type, uint32_t max_entries, uint32_t map_flags) {
63 int map_fd = createMap(map_type, sizeof(Key), sizeof(Value), max_entries, map_flags);
64 if (map_fd < 0) {
65 mMapFd.reset(-1);
66 } else {
67 mMapFd.reset(map_fd);
68 }
69 }
70
Chenbo Feng75b410b2018-10-10 15:01:19 -070071 netdutils::StatusOr<Key> getFirstKey() const {
72 Key firstKey;
73 if (getFirstMapKey(mMapFd, &firstKey)) {
74 return netdutils::statusFromErrno(
75 errno, base::StringPrintf("Get firstKey map %d failed", mMapFd.get()));
76 }
77 return firstKey;
78 }
79
80 netdutils::StatusOr<Key> getNextKey(const Key& key) const {
81 Key nextKey;
82 if (getNextMapKey(mMapFd, const_cast<Key*>(&key), &nextKey)) {
83 return netdutils::statusFromErrno(
84 errno, base::StringPrintf("Get next key of map %d failed", mMapFd.get()));
85 }
86 return nextKey;
87 }
88
89 netdutils::Status writeValue(const Key& key, const Value& value, uint64_t flags) {
90 if (writeToMapEntry(mMapFd, const_cast<Key*>(&key), const_cast<Value*>(&value), flags)) {
91 return netdutils::statusFromErrno(
92 errno, base::StringPrintf("write to map %d failed", mMapFd.get()));
93 }
94 return netdutils::status::ok;
95 }
96
97 netdutils::StatusOr<Value> readValue(const Key key) const {
98 Value value;
99 if (findMapEntry(mMapFd, const_cast<Key*>(&key), &value)) {
100 return netdutils::statusFromErrno(
101 errno, base::StringPrintf("read value of map %d failed", mMapFd.get()));
102 }
103 return value;
104 }
105
106 netdutils::Status deleteValue(const Key& key) {
107 if (deleteMapEntry(mMapFd, const_cast<Key*>(&key))) {
108 return netdutils::statusFromErrno(
109 errno, base::StringPrintf("delete entry from map %d failed", mMapFd.get()));
110 }
111 return netdutils::status::ok;
112 }
113
Maciej Żenczykowski52108bf2019-04-01 10:41:13 -0700114 // Function that tries to get map from a pinned path.
115 netdutils::Status init(const char* path);
Chenbo Feng75b410b2018-10-10 15:01:19 -0700116
117 // Iterate through the map and handle each key retrieved based on the filter
118 // without modification of map content.
119 netdutils::Status iterate(
120 const std::function<netdutils::Status(const Key& key, const BpfMap<Key, Value>& map)>&
121 filter) const;
122
123 // Iterate through the map and get each <key, value> pair, handle each <key,
124 // value> pair based on the filter without modification of map content.
125 netdutils::Status iterateWithValue(
126 const std::function<netdutils::Status(const Key& key, const Value& value,
127 const BpfMap<Key, Value>& map)>& filter) const;
128
129 // Iterate through the map and handle each key retrieved based on the filter
130 netdutils::Status iterate(
131 const std::function<netdutils::Status(const Key& key, BpfMap<Key, Value>& map)>& filter);
132
133 // Iterate through the map and get each <key, value> pair, handle each <key,
134 // value> pair based on the filter.
135 netdutils::Status iterateWithValue(
136 const std::function<netdutils::Status(const Key& key, const Value& value,
137 BpfMap<Key, Value>& map)>& filter);
138
139 const base::unique_fd& getMap() const { return mMapFd; };
140
Chenbo Feng75b410b2018-10-10 15:01:19 -0700141 // Move constructor
142 void operator=(BpfMap<Key, Value>&& other) noexcept {
143 mMapFd = std::move(other.mMapFd);
Chenbo Feng75b410b2018-10-10 15:01:19 -0700144 other.reset();
145 }
146
147 void reset(int fd = -1) {
148 mMapFd.reset(fd);
Chenbo Feng75b410b2018-10-10 15:01:19 -0700149 }
150
151 bool isValid() const { return mMapFd != -1; }
152
153 // It is only safe to call this method if it is guaranteed that nothing will concurrently
154 // iterate over the map in any process.
155 netdutils::Status clear() {
156 const auto deleteAllEntries = [](const Key& key, BpfMap<Key, Value>& map) {
157 netdutils::Status res = map.deleteValue(key);
158 if (!isOk(res) && (res.code() != ENOENT)) {
159 ALOGE("Failed to delete data %s\n", strerror(res.code()));
160 }
161 return netdutils::status::ok;
162 };
163 RETURN_IF_NOT_OK(iterate(deleteAllEntries));
164 return netdutils::status::ok;
165 }
166
167 netdutils::StatusOr<bool> isEmpty() const {
168 auto key = this->getFirstKey();
169 // Return error code ENOENT means the map is empty
170 if (!isOk(key) && key.status().code() == ENOENT) return true;
171 RETURN_IF_NOT_OK(key);
172 return false;
173 }
174
175 private:
176 base::unique_fd mMapFd;
Chenbo Feng75b410b2018-10-10 15:01:19 -0700177};
178
179template <class Key, class Value>
Maciej Żenczykowski52108bf2019-04-01 10:41:13 -0700180netdutils::Status BpfMap<Key, Value>::init(const char* path) {
181 mMapFd = base::unique_fd(mapRetrieve(path, 0));
182 if (mMapFd == -1) {
183 reset();
184 return netdutils::statusFromErrno(
Chenbo Feng75b410b2018-10-10 15:01:19 -0700185 errno,
186 base::StringPrintf("pinned map not accessible or does not exist: (%s)\n", path));
Chenbo Feng75b410b2018-10-10 15:01:19 -0700187 }
188 return netdutils::status::ok;
189}
190
191template <class Key, class Value>
192netdutils::Status BpfMap<Key, Value>::iterate(
193 const std::function<netdutils::Status(const Key& key, const BpfMap<Key, Value>& map)>& filter)
194 const {
195 netdutils::StatusOr<Key> curKey = getFirstKey();
196 while (isOk(curKey)) {
197 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
198 RETURN_IF_NOT_OK(filter(curKey.value(), *this));
199 curKey = nextKey;
200 }
201 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
202}
203
204template <class Key, class Value>
205netdutils::Status BpfMap<Key, Value>::iterateWithValue(
206 const std::function<netdutils::Status(const Key& key, const Value& value,
207 const BpfMap<Key, Value>& map)>& filter) const {
208 netdutils::StatusOr<Key> curKey = getFirstKey();
209 while (isOk(curKey)) {
210 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
211 Value curValue;
212 ASSIGN_OR_RETURN(curValue, this->readValue(curKey.value()));
213 RETURN_IF_NOT_OK(filter(curKey.value(), curValue, *this));
214 curKey = nextKey;
215 }
216 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
217}
218
219template <class Key, class Value>
220netdutils::Status BpfMap<Key, Value>::iterate(
221 const std::function<netdutils::Status(const Key& key, BpfMap<Key, Value>& map)>& filter) {
222 netdutils::StatusOr<Key> curKey = getFirstKey();
223 while (isOk(curKey)) {
224 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
225 RETURN_IF_NOT_OK(filter(curKey.value(), *this));
226 curKey = nextKey;
227 }
228 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
229}
230
231template <class Key, class Value>
232netdutils::Status BpfMap<Key, Value>::iterateWithValue(
233 const std::function<netdutils::Status(const Key& key, const Value& value,
234 BpfMap<Key, Value>& map)>& filter) {
235 netdutils::StatusOr<Key> curKey = getFirstKey();
236 while (isOk(curKey)) {
237 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
238 Value curValue;
239 ASSIGN_OR_RETURN(curValue, this->readValue(curKey.value()));
240 RETURN_IF_NOT_OK(filter(curKey.value(), curValue, *this));
241 curKey = nextKey;
242 }
243 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
244}
245
246} // namespace bpf
247} // namespace android
248
249#endif