2 #include "io_uring_engine.h"
19 #include <unordered_map>
24 using namespace std::chrono;
27 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
29 #include "turbopfor.h"
31 const char *dbpath = "/var/lib/mlocate/plocate.db";
32 bool print_nul = false;
36 bool ready_to_print(int seq) { return next_seq == seq; }
37 void print_delayed(int seq, const vector<string> msg);
38 void release_current();
46 bool operator<(const Element &other) const
48 return seq > other.seq;
51 priority_queue<Element> pending;
54 void Serializer::print_delayed(int seq, const vector<string> msg)
56 pending.push(Element{ seq, move(msg) });
59 void Serializer::release_current()
63 // See if any delayed prints can now be dealt with.
64 while (!pending.empty() && pending.top().seq == next_seq) {
65 for (const string &msg : pending.top().msg) {
67 printf("%s%c", msg.c_str(), 0);
69 printf("%s\n", msg.c_str());
77 static inline uint32_t read_unigram(const string &s, size_t idx)
80 return (unsigned char)s[idx];
86 static inline uint32_t read_trigram(const string &s, size_t start)
88 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
89 (read_unigram(s, start + 2) << 16);
92 bool has_access(const char *filename,
93 unordered_map<string, bool> *access_rx_cache)
95 const char *end = strchr(filename + 1, '/');
96 while (end != nullptr) {
97 string parent_path(filename, end);
98 auto it = access_rx_cache->find(parent_path);
100 if (it == access_rx_cache->end()) {
101 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
102 access_rx_cache->emplace(move(parent_path), ok);
109 end = strchr(end + 1, '/');
117 Corpus(int fd, IOUringEngine *engine);
119 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
120 void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
121 size_t get_num_filename_blocks() const;
122 off_t offset_for_block(uint32_t docid) const
124 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
129 IOUringEngine *const engine;
134 Corpus::Corpus(int fd, IOUringEngine *engine)
135 : fd(fd), engine(engine)
137 // Enable to test cold-cache behavior (except for access()).
139 off_t len = lseek(fd, 0, SEEK_END);
144 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
147 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
148 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
149 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
152 if (hdr.version != 0) {
153 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
163 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
165 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
166 engine->submit_read(fd, sizeof(Trigram) * (hdr.extra_ht_slots + 2), hdr.hash_table_offset_bytes + sizeof(Trigram) * bucket, [this, trgm, bucket, cb{ move(cb) }](string s) {
167 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
168 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
169 if (trgmptr[i].trgm == trgm) {
170 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
180 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
182 // Read the file offset from this docid and the next one.
183 // This is always allowed, since we have a sentinel block at the end.
184 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
185 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
186 off_t offset = ptr[0];
187 size_t len = ptr[1] - ptr[0];
188 engine->submit_read(fd, len, offset, cb);
192 size_t Corpus::get_num_filename_blocks() const
194 return hdr.num_docids;
197 size_t scan_file_block(const vector<string> &needles, string_view compressed,
198 unordered_map<string, bool> *access_rx_cache, int seq,
199 Serializer *serializer)
203 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
204 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
205 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
210 block.resize(uncompressed_len + 1);
212 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
214 if (ZSTD_isError(err)) {
215 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
218 block[block.size() - 1] = '\0';
220 bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
221 vector<string> delayed;
223 for (const char *filename = block.data();
224 filename != block.data() + block.size();
225 filename += strlen(filename) + 1) {
227 for (const string &needle : needles) {
228 if (strstr(filename, needle.c_str()) == nullptr) {
233 if (found && has_access(filename, access_rx_cache)) {
235 if (immediate_print) {
237 printf("%s%c", filename, 0);
239 printf("%s\n", filename);
242 delayed.push_back(filename);
246 if (serializer != nullptr) {
247 if (immediate_print) {
248 serializer->release_current();
250 serializer->print_delayed(seq, move(delayed));
256 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
258 Serializer docids_in_order;
259 unordered_map<string, bool> access_rx_cache;
261 for (size_t i = 0; i < docids.size(); ++i) {
262 uint32_t docid = docids[i];
263 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string compressed) {
264 matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
271 // We do this sequentially, as it's faster than scattering
272 // a lot of I/O through io_uring and hoping the kernel will
273 // coalesce it plus readahead for us.
274 void scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
276 unordered_map<string, bool> access_rx_cache;
277 uint32_t num_blocks = corpus.get_num_filename_blocks();
278 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
279 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
281 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
282 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
283 size_t io_len = offsets[last_docid] - offsets[io_docid];
284 if (compressed.size() < io_len) {
285 compressed.resize(io_len);
287 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
289 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
290 size_t relative_offset = offsets[docid] - offsets[io_docid];
291 size_t len = offsets[docid + 1] - offsets[docid];
292 scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
297 void do_search_file(const vector<string> &needles, const char *filename)
299 int fd = open(filename, O_RDONLY);
306 if (setgid(getgid()) != 0) {
311 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
312 if (access("/", R_OK | X_OK)) {
313 // We can't find anything, no need to bother...
317 IOUringEngine engine;
318 Corpus corpus(fd, &engine);
319 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
321 vector<pair<Trigram, size_t>> trigrams;
322 uint64_t shortest_so_far = numeric_limits<uint32_t>::max();
323 for (const string &needle : needles) {
324 if (needle.size() < 3)
326 for (size_t i = 0; i < needle.size() - 2; ++i) {
327 uint32_t trgm = read_trigram(needle, i);
328 corpus.find_trigram(trgm, [trgm, &trigrams, &shortest_so_far](const Trigram *trgmptr, size_t len) {
329 if (trgmptr == nullptr) {
330 dprintf("trigram '%c%c%c' isn't found, we abort the search\n",
331 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff);
334 if (trgmptr->num_docids > shortest_so_far * 100) {
335 dprintf("not loading trigram '%c%c%c' with %u docids, it would be ignored later anyway\n",
336 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
337 trgmptr->num_docids);
339 trigrams.emplace_back(*trgmptr, len);
340 shortest_so_far = std::min<uint64_t>(shortest_so_far, trgmptr->num_docids);
346 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
348 if (trigrams.empty()) {
349 // Too short for trigram matching. Apply brute force.
350 // (We could have searched through all trigrams that matched
351 // the pattern and done a union of them, but that's a lot of
352 // work for fairly unclear gain.)
353 scan_all_docids(needles, fd, corpus, &engine);
356 sort(trigrams.begin(), trigrams.end());
358 auto last = unique(trigrams.begin(), trigrams.end());
359 trigrams.erase(last, trigrams.end());
361 sort(trigrams.begin(), trigrams.end(),
362 [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
363 return a.first.num_docids < b.first.num_docids;
366 vector<uint32_t> in1, in2, out;
368 for (auto [trgmptr, len] : trigrams) {
369 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
370 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
371 dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
372 "weed out false positives later)\n",
373 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
374 len, trgmptr.num_docids);
378 // Only stay a certain amount ahead, so that we don't spend I/O
379 // on reading the latter, large posting lists. We are unlikely
380 // to need them anyway, even if they should come in first.
381 if (engine.get_waiting_reads() >= 5) {
386 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
389 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
390 size_t num = trgmptr.num_docids;
391 unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
393 in1.resize(num + 128);
394 decode_pfor_delta1<128>(pldata, num, &in1[0]);
396 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
397 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
399 if (in2.size() < num + 128) {
400 in2.resize(num + 128);
402 decode_pfor_delta1<128>(pldata, num, &in2[0]);
405 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
408 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
409 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
410 len, num, in1.size());
412 dprintf("no matches (intersection list is empty)\n");
422 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
423 1e3 * duration<float>(steady_clock::now() - start).count());
425 size_t matched __attribute__((unused)) = scan_docids(needles, in1, corpus, &engine);
426 dprintf("Done in %.1f ms, found %zu matches.\n",
427 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
432 // The help text comes from mlocate.
433 printf("Usage: plocate [OPTION]... PATTERN...\n");
435 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
436 printf(" %s)\n", dbpath);
437 printf(" -h, --help print this help\n");
438 printf(" -0, --null separate entries with NUL on output\n");
441 int main(int argc, char **argv)
443 static const struct option long_options[] = {
444 { "help", no_argument, 0, 'h' },
445 { "database", required_argument, 0, 'd' },
446 { "null", no_argument, 0, '0' },
451 int option_index = 0;
452 int c = getopt_long(argc, argv, "d:h0", long_options, &option_index);
458 dbpath = strdup(optarg);
471 vector<string> needles;
472 for (int i = optind; i < argc; ++i) {
473 needles.push_back(argv[i]);
475 if (needles.empty()) {
476 fprintf(stderr, "plocate: no pattern to search for specified\n");
479 do_search_file(needles, dbpath);