2 #include "io_uring_engine.h"
19 #include <string_view>
21 #include <unordered_map>
27 using namespace std::chrono;
30 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
32 #include "turbopfor.h"
34 const char *dbpath = "/var/lib/mlocate/plocate.db";
35 bool only_count = false;
36 bool print_nul = false;
37 int64_t limit_matches = numeric_limits<int64_t>::max();
41 bool ready_to_print(int seq) { return next_seq == seq; }
42 void print_delayed(int seq, const vector<string> msg);
43 void release_current();
51 bool operator<(const Element &other) const
53 return seq > other.seq;
56 priority_queue<Element> pending;
59 void Serializer::print_delayed(int seq, const vector<string> msg)
61 pending.push(Element{ seq, move(msg) });
64 void Serializer::release_current()
68 // See if any delayed prints can now be dealt with.
69 while (!pending.empty() && pending.top().seq == next_seq) {
70 if (limit_matches-- <= 0)
72 for (const string &msg : pending.top().msg) {
74 printf("%s%c", msg.c_str(), 0);
76 printf("%s\n", msg.c_str());
84 static inline uint32_t read_unigram(const string &s, size_t idx)
87 return (unsigned char)s[idx];
93 static inline uint32_t read_trigram(const string &s, size_t start)
95 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
96 (read_unigram(s, start + 2) << 16);
99 bool has_access(const char *filename,
100 unordered_map<string, bool> *access_rx_cache)
102 const char *end = strchr(filename + 1, '/');
103 while (end != nullptr) {
104 string parent_path(filename, end);
105 auto it = access_rx_cache->find(parent_path);
107 if (it == access_rx_cache->end()) {
108 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
109 access_rx_cache->emplace(move(parent_path), ok);
116 end = strchr(end + 1, '/');
124 Corpus(int fd, IOUringEngine *engine);
126 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
127 void get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const;
128 size_t get_num_filename_blocks() const;
129 off_t offset_for_block(uint32_t docid) const
131 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
136 IOUringEngine *const engine;
141 Corpus::Corpus(int fd, IOUringEngine *engine)
142 : fd(fd), engine(engine)
144 // Enable to test cold-cache behavior (except for access()).
146 off_t len = lseek(fd, 0, SEEK_END);
151 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
154 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
155 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
156 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
159 if (hdr.version != 0) {
160 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
170 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
172 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
173 engine->submit_read(fd, sizeof(Trigram) * (hdr.extra_ht_slots + 2), hdr.hash_table_offset_bytes + sizeof(Trigram) * bucket, [this, trgm, cb{ move(cb) }](string_view s) {
174 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
175 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
176 if (trgmptr[i].trgm == trgm) {
177 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
187 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string_view)> cb) const
189 // Read the file offset from this docid and the next one.
190 // This is always allowed, since we have a sentinel block at the end.
191 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string_view s) {
192 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
193 off_t offset = ptr[0];
194 size_t len = ptr[1] - ptr[0];
195 engine->submit_read(fd, len, offset, cb);
199 size_t Corpus::get_num_filename_blocks() const
201 return hdr.num_docids;
204 uint64_t scan_file_block(const vector<string> &needles, string_view compressed,
205 unordered_map<string, bool> *access_rx_cache, int seq,
206 Serializer *serializer)
208 uint64_t matched = 0;
210 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
211 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
212 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
217 block.resize(uncompressed_len + 1);
219 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
221 if (ZSTD_isError(err)) {
222 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
225 block[block.size() - 1] = '\0';
227 bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
228 vector<string> delayed;
230 for (const char *filename = block.data();
231 filename != block.data() + block.size();
232 filename += strlen(filename) + 1) {
234 for (const string &needle : needles) {
235 if (strstr(filename, needle.c_str()) == nullptr) {
240 if (found && has_access(filename, access_rx_cache)) {
241 if (limit_matches-- <= 0)
246 if (immediate_print) {
248 printf("%s%c", filename, 0);
250 printf("%s\n", filename);
253 delayed.push_back(filename);
257 if (serializer != nullptr && !only_count) {
258 if (immediate_print) {
259 serializer->release_current();
261 serializer->print_delayed(seq, move(delayed));
267 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
269 Serializer docids_in_order;
270 unordered_map<string, bool> access_rx_cache;
271 uint64_t matched = 0;
272 for (size_t i = 0; i < docids.size(); ++i) {
273 uint32_t docid = docids[i];
274 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string_view compressed) {
275 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
282 // We do this sequentially, as it's faster than scattering
283 // a lot of I/O through io_uring and hoping the kernel will
284 // coalesce it plus readahead for us.
285 uint64_t scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
287 unordered_map<string, bool> access_rx_cache;
288 uint32_t num_blocks = corpus.get_num_filename_blocks();
289 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
290 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
292 uint64_t matched = 0;
293 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
294 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
295 size_t io_len = offsets[last_docid] - offsets[io_docid];
296 if (compressed.size() < io_len) {
297 compressed.resize(io_len);
299 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
301 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
302 size_t relative_offset = offsets[docid] - offsets[io_docid];
303 size_t len = offsets[docid + 1] - offsets[docid];
304 matched += scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
305 if (limit_matches <= 0)
312 void do_search_file(const vector<string> &needles, const char *filename)
314 int fd = open(filename, O_RDONLY);
321 if (setgid(getgid()) != 0) {
326 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
327 if (access("/", R_OK | X_OK)) {
328 // We can't find anything, no need to bother...
332 IOUringEngine engine(/*slop_bytes=*/16); // 16 slop bytes as described in turbopfor.h.
333 Corpus corpus(fd, &engine);
334 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
336 vector<pair<Trigram, size_t>> trigrams;
337 uint64_t shortest_so_far = numeric_limits<uint32_t>::max();
338 for (const string &needle : needles) {
339 if (needle.size() < 3)
341 for (size_t i = 0; i < needle.size() - 2; ++i) {
342 uint32_t trgm = read_trigram(needle, i);
343 corpus.find_trigram(trgm, [trgm, &trigrams, &shortest_so_far](const Trigram *trgmptr, size_t len) {
344 if (trgmptr == nullptr) {
345 dprintf("trigram '%c%c%c' isn't found, we abort the search\n",
346 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff);
352 if (trgmptr->num_docids > shortest_so_far * 100) {
353 dprintf("not loading trigram '%c%c%c' with %u docids, it would be ignored later anyway\n",
354 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
355 trgmptr->num_docids);
357 trigrams.emplace_back(*trgmptr, len);
358 shortest_so_far = std::min<uint64_t>(shortest_so_far, trgmptr->num_docids);
364 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
366 if (trigrams.empty()) {
367 // Too short for trigram matching. Apply brute force.
368 // (We could have searched through all trigrams that matched
369 // the pattern and done a union of them, but that's a lot of
370 // work for fairly unclear gain.)
371 uint64_t matched = scan_all_docids(needles, fd, corpus, &engine);
373 printf("%zu\n", matched);
377 sort(trigrams.begin(), trigrams.end());
379 auto last = unique(trigrams.begin(), trigrams.end());
380 trigrams.erase(last, trigrams.end());
382 sort(trigrams.begin(), trigrams.end(),
383 [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
384 return a.first.num_docids < b.first.num_docids;
387 vector<uint32_t> in1, in2, out;
389 for (auto [trgmptr, len] : trigrams) {
390 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
391 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
392 dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
393 "weed out false positives later)\n",
394 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
395 len, trgmptr.num_docids);
399 // Only stay a certain amount ahead, so that we don't spend I/O
400 // on reading the latter, large posting lists. We are unlikely
401 // to need them anyway, even if they should come in first.
402 if (engine.get_waiting_reads() >= 5) {
407 engine.submit_read(fd, len, trgmptr.offset, [trgmptr{ trgmptr }, len{ len }, &done, &in1, &in2, &out](string_view s) {
410 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
411 size_t num = trgmptr.num_docids;
412 const unsigned char *pldata = reinterpret_cast<const unsigned char *>(s.data());
414 in1.resize(num + 128);
415 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in1[0]);
417 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
418 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
420 if (in2.size() < num + 128) {
421 in2.resize(num + 128);
423 decode_pfor_delta1_128(pldata, num, /*interleaved=*/true, &in2[0]);
426 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
429 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
430 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
431 len, num, in1.size());
433 dprintf("no matches (intersection list is empty)\n");
443 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
444 1e3 * duration<float>(steady_clock::now() - start).count());
446 uint64_t matched = scan_docids(needles, in1, corpus, &engine);
447 dprintf("Done in %.1f ms, found %zu matches.\n",
448 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
451 printf("%zu\n", matched);
457 // The help text comes from mlocate.
458 printf("Usage: plocate [OPTION]... PATTERN...\n");
460 printf(" -c, --count only print number of found entries\n");
461 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
462 printf(" %s)\n", dbpath);
463 printf(" -h, --help print this help\n");
464 printf(" -l, --limit, -n LIMIT limit output (or counting) to LIMIT entries\n");
465 printf(" -0, --null separate entries with NUL on output\n");
468 int main(int argc, char **argv)
470 static const struct option long_options[] = {
471 { "help", no_argument, 0, 'h' },
472 { "count", no_argument, 0, 'c' },
473 { "database", required_argument, 0, 'd' },
474 { "limit", required_argument, 0, 'l' },
475 { nullptr, required_argument, 0, 'n' },
476 { "null", no_argument, 0, '0' },
481 int option_index = 0;
482 int c = getopt_long(argc, argv, "cd:hl:n:0", long_options, &option_index);
491 dbpath = strdup(optarg);
498 limit_matches = atoll(optarg);
508 vector<string> needles;
509 for (int i = optind; i < argc; ++i) {
510 needles.push_back(argv[i]);
512 if (needles.empty()) {
513 fprintf(stderr, "plocate: no pattern to search for specified\n");
516 do_search_file(needles, dbpath);