]> git.sesse.net Git - plocate/blob - plocate.cpp
Replace mmap with io_uring.
[plocate] / plocate.cpp
1 #include "vp4.h"
2 #include "io_uring_engine.h"
3
4 #include <algorithm>
5 #include <arpa/inet.h>
6 #include <chrono>
7 #include <endian.h>
8 #include <fcntl.h>
9 #include <functional>
10 #include <memory>
11 #include <stdio.h>
12 #include <string.h>
13 #include <string>
14 #include <unistd.h>
15 #include <unordered_map>
16 #include <vector>
17 #include <zstd.h>
18
19 using namespace std;
20 using namespace std::chrono;
21
22 #define dprintf(...)
23 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
24
25 class Serializer {
26 public:
27         void do_or_wait(int seq, function<void()> cb);
28
29 private:
30         int next_seq = 0;
31         struct Element {
32                 int seq;
33                 function<void()> cb;
34
35                 bool operator<(const Element &other) const
36                 {
37                         return seq > other.seq;
38                 }
39         };
40         priority_queue<Element> pending;
41 };
42
43 void Serializer::do_or_wait(int seq, function<void()> cb)
44 {
45         if (seq != next_seq) {
46                 pending.emplace(Element{ seq, move(cb) });
47                 return;
48         }
49
50         cb();
51         ++next_seq;
52
53         while (!pending.empty() && pending.top().seq == next_seq) {
54                 pending.top().cb();
55                 pending.pop();
56                 ++next_seq;
57         }
58 }
59
60 static inline uint32_t read_unigram(const string &s, size_t idx)
61 {
62         if (idx < s.size()) {
63                 return (unsigned char)s[idx];
64         } else {
65                 return 0;
66         }
67 }
68
69 static inline uint32_t read_trigram(const string &s, size_t start)
70 {
71         return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
72                 (read_unigram(s, start + 2) << 16);
73 }
74
75 bool has_access(const char *filename,
76                 unordered_map<string, bool> *access_rx_cache)
77 {
78         const char *end = strchr(filename + 1, '/');
79         while (end != nullptr) {
80                 string parent_path(filename, end);
81                 auto it = access_rx_cache->find(parent_path);
82                 bool ok;
83                 if (it == access_rx_cache->end()) {
84                         ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
85                         access_rx_cache->emplace(move(parent_path), ok);
86                 } else {
87                         ok = it->second;
88                 }
89                 if (!ok) {
90                         return false;
91                 }
92                 end = strchr(end + 1, '/');
93         }
94
95         return true;
96 }
97
98 struct Trigram {
99         uint32_t trgm;
100         uint32_t num_docids;
101         uint64_t offset;
102
103         bool operator==(const Trigram &other) const
104         {
105                 return trgm == other.trgm;
106         }
107         bool operator<(const Trigram &other) const
108         {
109                 return trgm < other.trgm;
110         }
111 };
112
113 class Corpus {
114 public:
115         Corpus(int fd, IOUringEngine *engine);
116         ~Corpus();
117         void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
118         void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
119         size_t get_num_filename_blocks() const;
120         off_t offset_for_block(uint32_t docid) const {
121                 return filename_index_offset + docid * sizeof(uint64_t);
122         }
123
124 public:
125         const int fd;
126         IOUringEngine *const engine;
127
128         off_t len;
129         uint64_t filename_index_offset;
130
131         uint64_t num_trigrams;
132         const off_t trigram_offset = sizeof(uint64_t) * 2;
133
134         void binary_search_trigram(uint32_t trgm, uint32_t left, uint32_t right, function<void(const Trigram *trgmptr, size_t len)> cb);
135 };
136
137 Corpus::Corpus(int fd, IOUringEngine *engine)
138         : fd(fd), engine(engine)
139 {
140         len = lseek(fd, 0, SEEK_END);
141         if (len == -1) {
142                 perror("lseek");
143                 exit(1);
144         }
145
146         // Uncomment to test cold-cache behavior (except for access()).
147         // posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
148
149         uint64_t vals[2];
150         complete_pread(fd, vals, sizeof(vals), /*offset=*/0);
151
152         num_trigrams = vals[0];
153         filename_index_offset = vals[1];
154 }
155
156 Corpus::~Corpus()
157 {
158         close(fd);
159 }
160
161 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
162 {
163         binary_search_trigram(trgm, 0, num_trigrams - 1, move(cb));
164 }
165
166 void Corpus::binary_search_trigram(uint32_t trgm, uint32_t left, uint32_t right, function<void(const Trigram *trgmptr, size_t len)> cb)
167 {
168         if (left > right) {
169                 cb(nullptr, 0);
170                 return;
171         }
172         uint32_t mid = (left + right) / 2;
173         engine->submit_read(fd, sizeof(Trigram) * 2, trigram_offset + sizeof(Trigram) * mid, [this, trgm, left, mid, right, cb{ move(cb) }](string s) {
174                 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
175                 const Trigram *next_trgmptr = trgmptr + 1;
176                 if (trgmptr->trgm < trgm) {
177                         binary_search_trigram(trgm, mid + 1, right, move(cb));
178                 } else if (trgmptr->trgm > trgm) {
179                         binary_search_trigram(trgm, left, mid - 1, move(cb));
180                 } else {
181                         cb(trgmptr, next_trgmptr->offset - trgmptr->offset);
182                 }
183         });
184 }
185
186 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
187 {
188         // Read the file offset from this docid and the next one.
189         // This is always allowed, since we have a sentinel block at the end.
190         engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
191                 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
192                 off_t offset = ptr[0];
193                 size_t len = ptr[1] - ptr[0];
194                 engine->submit_read(fd, len, offset, cb);
195         });
196 }
197
198 size_t Corpus::get_num_filename_blocks() const
199 {
200         // The beginning of the filename blocks is the end of the filename index blocks.
201         uint64_t end;
202         complete_pread(fd, &end, sizeof(end), filename_index_offset);
203
204         // Subtract the sentinel block.
205         return (end - filename_index_offset) / sizeof(uint64_t) - 1;
206 }
207
208 size_t scan_file_block(const string &needle, string_view compressed,
209                        unordered_map<string, bool> *access_rx_cache)
210 {
211         size_t matched = 0;
212
213         string block;
214         block.resize(ZSTD_getFrameContentSize(compressed.data(), compressed.size()) +
215                      1);
216
217         ZSTD_decompress(&block[0], block.size(), compressed.data(),
218                         compressed.size());
219         block[block.size() - 1] = '\0';
220
221         for (const char *filename = block.data();
222              filename != block.data() + block.size();
223              filename += strlen(filename) + 1) {
224                 if (strstr(filename, needle.c_str()) == nullptr) {
225                         continue;
226                 }
227                 if (has_access(filename, access_rx_cache)) {
228                         ++matched;
229                         printf("%s\n", filename);
230                 }
231         }
232         return matched;
233 }
234
235 size_t scan_docids(const string &needle, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
236 {
237         Serializer docids_in_order;
238         unordered_map<string, bool> access_rx_cache;
239         size_t matched = 0;
240         for (size_t i = 0; i < docids.size(); ++i) {
241                 uint32_t docid = docids[i];
242                 corpus.get_compressed_filename_block(docid, [i, &matched, &needle, &access_rx_cache, &docids_in_order](string compressed) {
243                         docids_in_order.do_or_wait(i, [&matched, &needle, compressed{ move(compressed) }, &access_rx_cache] {
244                                 matched += scan_file_block(needle, compressed, &access_rx_cache);
245                         });
246                 });
247         }
248         engine->finish();
249         return matched;
250 }
251
252 // We do this sequentially, as it's faster than scattering
253 // a lot of I/O through io_uring and hoping the kernel will
254 // coalesce it plus readahead for us.
255 void scan_all_docids(const string &needle, int fd, const Corpus &corpus, IOUringEngine *engine)
256 {
257         unordered_map<string, bool> access_rx_cache;
258         uint32_t num_blocks = corpus.get_num_filename_blocks();
259         unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
260         complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
261         string compressed;
262         for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
263                 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
264                 size_t io_len = offsets[last_docid] - offsets[io_docid];
265                 if (compressed.size() < io_len) {
266                         compressed.resize(io_len);
267                 }
268                 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
269
270                 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
271                         size_t relative_offset = offsets[docid] - offsets[io_docid];
272                         size_t len = offsets[docid + 1] - offsets[docid];
273                         scan_file_block(needle, {&compressed[relative_offset], len}, &access_rx_cache);
274                 }
275         }
276 }
277
278 void do_search_file(const string &needle, const char *filename)
279 {
280         int fd = open(filename, O_RDONLY);
281         if (fd == -1) {
282                 perror(filename);
283                 exit(1);
284         }
285
286         // Drop privileges.
287         if (setgid(getgid()) != 0) {
288                 perror("setgid");
289                 exit(EXIT_FAILURE);
290         }
291
292         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
293         if (access("/", R_OK | X_OK)) {
294                 // We can't find anything, no need to bother...
295                 return;
296         }
297
298         IOUringEngine engine;
299         Corpus corpus(fd, &engine);
300         dprintf("Corpus init took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
301
302         if (needle.size() < 3) {
303                 // Too short for trigram matching. Apply brute force.
304                 // (We could have searched through all trigrams that matched
305                 // the pattern and done a union of them, but that's a lot of
306                 // work for fairly unclear gain.)
307                 scan_all_docids(needle, fd, corpus, &engine);
308                 return;
309         }
310
311         vector<pair<Trigram, size_t>> trigrams;
312         for (size_t i = 0; i < needle.size() - 2; ++i) {
313                 uint32_t trgm = read_trigram(needle, i);
314                 pair<uint32_t, uint32_t> range{ 0, corpus.num_trigrams - 1 };
315                 corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
316                         if (trgmptr == nullptr) {
317                                 dprintf("trigram %06x isn't found, we abort the search\n", trgm);
318                                 return;
319                         }
320                         trigrams.emplace_back(*trgmptr, len);
321                 });
322         }
323         engine.finish();
324         dprintf("Binary search took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
325
326         sort(trigrams.begin(), trigrams.end());
327         {
328                 auto last = unique(trigrams.begin(), trigrams.end());
329                 trigrams.erase(last, trigrams.end());
330         }
331         sort(trigrams.begin(), trigrams.end(),
332              [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
333                      return a.first.num_docids < b.first.num_docids;
334              });
335
336         vector<uint32_t> in1, in2, out;
337         bool done = false;
338         for (auto [trgmptr, len] : trigrams) {
339                 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
340                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
341                         dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
342                                 "weed out false positives later)\n",
343                                 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
344                                 len, trgmptr.num_docids);
345                         break;
346                 }
347
348                 // Only stay a certain amount ahead, so that we don't spend I/O
349                 // on reading the latter, large posting lists. We are unlikely
350                 // to need them anyway, even if they should come in first.
351                 if (engine.get_waiting_reads() >= 5) {
352                         engine.finish();
353                         if (done)
354                                 break;
355                 }
356                 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
357                         uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
358                         size_t num = trgmptr.num_docids;
359                         unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
360                         if (in1.empty()) {
361                                 in1.resize(num + 128);
362                                 p4nd1dec128v32(pldata, num, &in1[0]);
363                                 in1.resize(num);
364                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
365                                         (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
366                         } else {
367                                 if (in2.size() < num + 128) {
368                                         in2.resize(num + 128);
369                                 }
370                                 p4nd1dec128v32(pldata, num, &in2[0]);
371
372                                 out.clear();
373                                 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
374                                                  back_inserter(out));
375                                 swap(in1, out);
376                                 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
377                                         trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
378                                         len, num, in1.size());
379                                 if (in1.empty()) {
380                                         dprintf("no matches (intersection list is empty)\n");
381                                         done = true;
382                                 }
383                         }
384                 });
385         }
386         engine.finish();
387         dprintf("Intersection took %.1f ms. Doing final verification and printing:\n",
388                 1e3 * duration<float>(steady_clock::now() - start).count());
389
390         size_t matched __attribute__((unused)) = scan_docids(needle, in1, corpus, &engine);
391         dprintf("Done in %.1f ms, found %zu matches.\n",
392                 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
393 }
394
395 int main(int argc, char **argv)
396 {
397         do_search_file(argv[1], "/var/lib/mlocate/plocate.db");
398 }