2 #include "io_uring_engine.h"
15 #include <unordered_map>
20 using namespace std::chrono;
23 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
27 void do_or_wait(int seq, function<void()> cb);
35 bool operator<(const Element &other) const
37 return seq > other.seq;
40 priority_queue<Element> pending;
43 void Serializer::do_or_wait(int seq, function<void()> cb)
45 if (seq != next_seq) {
46 pending.emplace(Element{ seq, move(cb) });
53 while (!pending.empty() && pending.top().seq == next_seq) {
60 static inline uint32_t read_unigram(const string &s, size_t idx)
63 return (unsigned char)s[idx];
69 static inline uint32_t read_trigram(const string &s, size_t start)
71 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
72 (read_unigram(s, start + 2) << 16);
75 bool has_access(const char *filename,
76 unordered_map<string, bool> *access_rx_cache)
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);
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);
92 end = strchr(end + 1, '/');
103 bool operator==(const Trigram &other) const
105 return trgm == other.trgm;
107 bool operator<(const Trigram &other) const
109 return trgm < other.trgm;
115 Corpus(int fd, IOUringEngine *engine);
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);
126 IOUringEngine *const engine;
129 uint64_t filename_index_offset;
131 uint64_t num_trigrams;
132 const off_t trigram_offset = sizeof(uint64_t) * 2;
134 void binary_search_trigram(uint32_t trgm, uint32_t left, uint32_t right, function<void(const Trigram *trgmptr, size_t len)> cb);
137 Corpus::Corpus(int fd, IOUringEngine *engine)
138 : fd(fd), engine(engine)
140 len = lseek(fd, 0, SEEK_END);
146 // Uncomment to test cold-cache behavior (except for access()).
147 // posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
150 complete_pread(fd, vals, sizeof(vals), /*offset=*/0);
152 num_trigrams = vals[0];
153 filename_index_offset = vals[1];
161 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
163 binary_search_trigram(trgm, 0, num_trigrams - 1, move(cb));
166 void Corpus::binary_search_trigram(uint32_t trgm, uint32_t left, uint32_t right, function<void(const Trigram *trgmptr, size_t len)> cb)
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));
181 cb(trgmptr, next_trgmptr->offset - trgmptr->offset);
186 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
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);
198 size_t Corpus::get_num_filename_blocks() const
200 // The beginning of the filename blocks is the end of the filename index blocks.
202 complete_pread(fd, &end, sizeof(end), filename_index_offset);
204 // Subtract the sentinel block.
205 return (end - filename_index_offset) / sizeof(uint64_t) - 1;
208 size_t scan_file_block(const string &needle, string_view compressed,
209 unordered_map<string, bool> *access_rx_cache)
213 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
214 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
215 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
220 block.resize(uncompressed_len + 1);
222 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
224 if (ZSTD_isError(err)) {
225 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
228 block[block.size() - 1] = '\0';
230 for (const char *filename = block.data();
231 filename != block.data() + block.size();
232 filename += strlen(filename) + 1) {
233 if (strstr(filename, needle.c_str()) == nullptr) {
236 if (has_access(filename, access_rx_cache)) {
238 printf("%s\n", filename);
244 size_t scan_docids(const string &needle, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
246 Serializer docids_in_order;
247 unordered_map<string, bool> access_rx_cache;
249 for (size_t i = 0; i < docids.size(); ++i) {
250 uint32_t docid = docids[i];
251 corpus.get_compressed_filename_block(docid, [i, &matched, &needle, &access_rx_cache, &docids_in_order](string compressed) {
252 docids_in_order.do_or_wait(i, [&matched, &needle, compressed{ move(compressed) }, &access_rx_cache] {
253 matched += scan_file_block(needle, compressed, &access_rx_cache);
261 // We do this sequentially, as it's faster than scattering
262 // a lot of I/O through io_uring and hoping the kernel will
263 // coalesce it plus readahead for us.
264 void scan_all_docids(const string &needle, int fd, const Corpus &corpus, IOUringEngine *engine)
266 unordered_map<string, bool> access_rx_cache;
267 uint32_t num_blocks = corpus.get_num_filename_blocks();
268 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
269 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
271 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
272 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
273 size_t io_len = offsets[last_docid] - offsets[io_docid];
274 if (compressed.size() < io_len) {
275 compressed.resize(io_len);
277 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
279 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
280 size_t relative_offset = offsets[docid] - offsets[io_docid];
281 size_t len = offsets[docid + 1] - offsets[docid];
282 scan_file_block(needle, {&compressed[relative_offset], len}, &access_rx_cache);
287 void do_search_file(const string &needle, const char *filename)
289 int fd = open(filename, O_RDONLY);
296 if (setgid(getgid()) != 0) {
301 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
302 if (access("/", R_OK | X_OK)) {
303 // We can't find anything, no need to bother...
307 IOUringEngine engine;
308 Corpus corpus(fd, &engine);
309 dprintf("Corpus init took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
311 if (needle.size() < 3) {
312 // Too short for trigram matching. Apply brute force.
313 // (We could have searched through all trigrams that matched
314 // the pattern and done a union of them, but that's a lot of
315 // work for fairly unclear gain.)
316 scan_all_docids(needle, fd, corpus, &engine);
320 vector<pair<Trigram, size_t>> trigrams;
321 for (size_t i = 0; i < needle.size() - 2; ++i) {
322 uint32_t trgm = read_trigram(needle, i);
323 corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
324 if (trgmptr == nullptr) {
325 dprintf("trigram %06x isn't found, we abort the search\n", trgm);
328 trigrams.emplace_back(*trgmptr, len);
332 dprintf("Binary search took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
334 sort(trigrams.begin(), trigrams.end());
336 auto last = unique(trigrams.begin(), trigrams.end());
337 trigrams.erase(last, trigrams.end());
339 sort(trigrams.begin(), trigrams.end(),
340 [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
341 return a.first.num_docids < b.first.num_docids;
344 vector<uint32_t> in1, in2, out;
346 for (auto [trgmptr, len] : trigrams) {
347 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
348 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
349 dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
350 "weed out false positives later)\n",
351 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
352 len, trgmptr.num_docids);
356 // Only stay a certain amount ahead, so that we don't spend I/O
357 // on reading the latter, large posting lists. We are unlikely
358 // to need them anyway, even if they should come in first.
359 if (engine.get_waiting_reads() >= 5) {
364 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
365 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
366 size_t num = trgmptr.num_docids;
367 unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
369 in1.resize(num + 128);
370 p4nd1dec128v32(pldata, num, &in1[0]);
372 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
373 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
375 if (in2.size() < num + 128) {
376 in2.resize(num + 128);
378 p4nd1dec128v32(pldata, num, &in2[0]);
381 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
384 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
385 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
386 len, num, in1.size());
388 dprintf("no matches (intersection list is empty)\n");
395 dprintf("Intersection took %.1f ms. Doing final verification and printing:\n",
396 1e3 * duration<float>(steady_clock::now() - start).count());
398 size_t matched __attribute__((unused)) = scan_docids(needle, in1, corpus, &engine);
399 dprintf("Done in %.1f ms, found %zu matches.\n",
400 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
403 int main(int argc, char **argv)
405 do_search_file(argv[1], "/var/lib/mlocate/plocate.db");