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