blob: 20db43e23c2ac4e28c2a4ef006cde73539515b80 [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:
49 BpfMap<Key, Value>() : mMapFd(-1){};
50 BpfMap<Key, Value>(int fd) : mMapFd(fd){};
51 BpfMap<Key, Value>(bpf_map_type map_type, uint32_t max_entries, uint32_t map_flags) {
52 int map_fd = createMap(map_type, sizeof(Key), sizeof(Value), max_entries, map_flags);
53 if (map_fd < 0) {
54 mMapFd.reset(-1);
55 } else {
56 mMapFd.reset(map_fd);
57 }
58 }
59
60 netdutils::Status pinToPath(const std::string path) {
61 int ret = bpfFdPin(mMapFd, path.c_str());
62 if (ret) {
63 return netdutils::statusFromErrno(errno,
64 base::StringPrintf("pin to %s failed", path.c_str()));
65 }
66 mPinnedPath = path;
67 return netdutils::status::ok;
68 }
69
70 netdutils::StatusOr<Key> getFirstKey() const {
71 Key firstKey;
72 if (getFirstMapKey(mMapFd, &firstKey)) {
73 return netdutils::statusFromErrno(
74 errno, base::StringPrintf("Get firstKey map %d failed", mMapFd.get()));
75 }
76 return firstKey;
77 }
78
79 netdutils::StatusOr<Key> getNextKey(const Key& key) const {
80 Key nextKey;
81 if (getNextMapKey(mMapFd, const_cast<Key*>(&key), &nextKey)) {
82 return netdutils::statusFromErrno(
83 errno, base::StringPrintf("Get next key of map %d failed", mMapFd.get()));
84 }
85 return nextKey;
86 }
87
88 netdutils::Status writeValue(const Key& key, const Value& value, uint64_t flags) {
89 if (writeToMapEntry(mMapFd, const_cast<Key*>(&key), const_cast<Value*>(&value), flags)) {
90 return netdutils::statusFromErrno(
91 errno, base::StringPrintf("write to map %d failed", mMapFd.get()));
92 }
93 return netdutils::status::ok;
94 }
95
96 netdutils::StatusOr<Value> readValue(const Key key) const {
97 Value value;
98 if (findMapEntry(mMapFd, const_cast<Key*>(&key), &value)) {
99 return netdutils::statusFromErrno(
100 errno, base::StringPrintf("read value of map %d failed", mMapFd.get()));
101 }
102 return value;
103 }
104
105 netdutils::Status deleteValue(const Key& key) {
106 if (deleteMapEntry(mMapFd, const_cast<Key*>(&key))) {
107 return netdutils::statusFromErrno(
108 errno, base::StringPrintf("delete entry from map %d failed", mMapFd.get()));
109 }
110 return netdutils::status::ok;
111 }
112
113 // Function that tries to get map from a pinned path, if the map doesn't
114 // exist yet, create a new one and pinned to the path.
115 netdutils::Status getOrCreate(const uint32_t maxEntries, const char* path,
116 const bpf_map_type mapType);
117
118 // Iterate through the map and handle each key retrieved based on the filter
119 // without modification of map content.
120 netdutils::Status iterate(
121 const std::function<netdutils::Status(const Key& key, const BpfMap<Key, Value>& map)>&
122 filter) const;
123
124 // Iterate through the map and get each <key, value> pair, handle each <key,
125 // value> pair based on the filter without modification of map content.
126 netdutils::Status iterateWithValue(
127 const std::function<netdutils::Status(const Key& key, const Value& value,
128 const BpfMap<Key, Value>& map)>& filter) const;
129
130 // Iterate through the map and handle each key retrieved based on the filter
131 netdutils::Status iterate(
132 const std::function<netdutils::Status(const Key& key, BpfMap<Key, Value>& map)>& filter);
133
134 // Iterate through the map and get each <key, value> pair, handle each <key,
135 // value> pair based on the filter.
136 netdutils::Status iterateWithValue(
137 const std::function<netdutils::Status(const Key& key, const Value& value,
138 BpfMap<Key, Value>& map)>& filter);
139
140 const base::unique_fd& getMap() const { return mMapFd; };
141
142 const std::string getPinnedPath() const { return mPinnedPath; };
143
144 // Move constructor
145 void operator=(BpfMap<Key, Value>&& other) noexcept {
146 mMapFd = std::move(other.mMapFd);
147 if (!other.mPinnedPath.empty()) {
148 mPinnedPath = other.mPinnedPath;
149 } else {
150 mPinnedPath.clear();
151 }
152 other.reset();
153 }
154
155 void reset(int fd = -1) {
156 mMapFd.reset(fd);
157 mPinnedPath.clear();
158 }
159
160 bool isValid() const { return mMapFd != -1; }
161
162 // It is only safe to call this method if it is guaranteed that nothing will concurrently
163 // iterate over the map in any process.
164 netdutils::Status clear() {
165 const auto deleteAllEntries = [](const Key& key, BpfMap<Key, Value>& map) {
166 netdutils::Status res = map.deleteValue(key);
167 if (!isOk(res) && (res.code() != ENOENT)) {
168 ALOGE("Failed to delete data %s\n", strerror(res.code()));
169 }
170 return netdutils::status::ok;
171 };
172 RETURN_IF_NOT_OK(iterate(deleteAllEntries));
173 return netdutils::status::ok;
174 }
175
176 netdutils::StatusOr<bool> isEmpty() const {
177 auto key = this->getFirstKey();
178 // Return error code ENOENT means the map is empty
179 if (!isOk(key) && key.status().code() == ENOENT) return true;
180 RETURN_IF_NOT_OK(key);
181 return false;
182 }
183
184 private:
185 base::unique_fd mMapFd;
186 std::string mPinnedPath;
187};
188
189template <class Key, class Value>
190netdutils::Status BpfMap<Key, Value>::getOrCreate(const uint32_t maxEntries, const char* path,
191 bpf_map_type mapType) {
192 int ret = access(path, R_OK);
193 /* Check the pinned location first to check if the map is already there.
194 * otherwise create a new one.
195 */
196 if (ret == 0) {
197 mMapFd = base::unique_fd(mapRetrieve(path, 0));
198 if (mMapFd == -1) {
199 reset();
200 return netdutils::statusFromErrno(
201 errno,
202 base::StringPrintf("pinned map not accessible or does not exist: (%s)\n", path));
203 }
204 mPinnedPath = path;
205 } else if (ret == -1 && errno == ENOENT) {
206 mMapFd = base::unique_fd(
207 createMap(mapType, sizeof(Key), sizeof(Value), maxEntries, BPF_F_NO_PREALLOC));
208 if (mMapFd == -1) {
209 reset();
210 return netdutils::statusFromErrno(errno,
211 base::StringPrintf("map create failed!: %s", path));
212 }
213 netdutils::Status pinStatus = pinToPath(path);
214 if (!isOk(pinStatus)) {
215 reset();
216 return pinStatus;
217 }
218 mPinnedPath = path;
219 } else {
220 return netdutils::statusFromErrno(
221 errno, base::StringPrintf("pinned map not accessible: %s", path));
222 }
223 return netdutils::status::ok;
224}
225
226template <class Key, class Value>
227netdutils::Status BpfMap<Key, Value>::iterate(
228 const std::function<netdutils::Status(const Key& key, const BpfMap<Key, Value>& map)>& filter)
229 const {
230 netdutils::StatusOr<Key> curKey = getFirstKey();
231 while (isOk(curKey)) {
232 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
233 RETURN_IF_NOT_OK(filter(curKey.value(), *this));
234 curKey = nextKey;
235 }
236 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
237}
238
239template <class Key, class Value>
240netdutils::Status BpfMap<Key, Value>::iterateWithValue(
241 const std::function<netdutils::Status(const Key& key, const Value& value,
242 const BpfMap<Key, Value>& map)>& filter) const {
243 netdutils::StatusOr<Key> curKey = getFirstKey();
244 while (isOk(curKey)) {
245 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
246 Value curValue;
247 ASSIGN_OR_RETURN(curValue, this->readValue(curKey.value()));
248 RETURN_IF_NOT_OK(filter(curKey.value(), curValue, *this));
249 curKey = nextKey;
250 }
251 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
252}
253
254template <class Key, class Value>
255netdutils::Status BpfMap<Key, Value>::iterate(
256 const std::function<netdutils::Status(const Key& key, BpfMap<Key, Value>& map)>& filter) {
257 netdutils::StatusOr<Key> curKey = getFirstKey();
258 while (isOk(curKey)) {
259 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
260 RETURN_IF_NOT_OK(filter(curKey.value(), *this));
261 curKey = nextKey;
262 }
263 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
264}
265
266template <class Key, class Value>
267netdutils::Status BpfMap<Key, Value>::iterateWithValue(
268 const std::function<netdutils::Status(const Key& key, const Value& value,
269 BpfMap<Key, Value>& map)>& filter) {
270 netdutils::StatusOr<Key> curKey = getFirstKey();
271 while (isOk(curKey)) {
272 const netdutils::StatusOr<Key>& nextKey = getNextKey(curKey.value());
273 Value curValue;
274 ASSIGN_OR_RETURN(curValue, this->readValue(curKey.value()));
275 RETURN_IF_NOT_OK(filter(curKey.value(), curValue, *this));
276 curKey = nextKey;
277 }
278 return curKey.status().code() == ENOENT ? netdutils::status::ok : curKey.status();
279}
280
281} // namespace bpf
282} // namespace android
283
284#endif