2 #include "io_uring_engine.h"
17 #include <unordered_map>
22 using namespace std::chrono;
25 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
27 const char *dbpath = "/var/lib/mlocate/plocate.db";
28 bool print_nul = false;
32 void do_or_wait(int seq, function<void()> cb);
40 bool operator<(const Element &other) const
42 return seq > other.seq;
45 priority_queue<Element> pending;
48 void Serializer::do_or_wait(int seq, function<void()> cb)
50 if (seq != next_seq) {
51 pending.emplace(Element{ seq, move(cb) });
58 while (!pending.empty() && pending.top().seq == next_seq) {
65 static inline uint32_t read_unigram(const string &s, size_t idx)
68 return (unsigned char)s[idx];
74 static inline uint32_t read_trigram(const string &s, size_t start)
76 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
77 (read_unigram(s, start + 2) << 16);
80 bool has_access(const char *filename,
81 unordered_map<string, bool> *access_rx_cache)
83 const char *end = strchr(filename + 1, '/');
84 while (end != nullptr) {
85 string parent_path(filename, end);
86 auto it = access_rx_cache->find(parent_path);
88 if (it == access_rx_cache->end()) {
89 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
90 access_rx_cache->emplace(move(parent_path), ok);
97 end = strchr(end + 1, '/');
105 Corpus(int fd, IOUringEngine *engine);
107 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
108 void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
109 size_t get_num_filename_blocks() const;
110 off_t offset_for_block(uint32_t docid) const
112 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
117 IOUringEngine *const engine;
122 Corpus::Corpus(int fd, IOUringEngine *engine)
123 : fd(fd), engine(engine)
125 // Enable to test cold-cache behavior (except for access()).
127 off_t len = lseek(fd, 0, SEEK_END);
132 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
135 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
136 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
137 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
140 if (hdr.version != 0) {
141 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
151 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
153 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
154 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) {
155 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
156 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
157 if (trgmptr[i].trgm == trgm) {
158 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
168 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
170 // Read the file offset from this docid and the next one.
171 // This is always allowed, since we have a sentinel block at the end.
172 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
173 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
174 off_t offset = ptr[0];
175 size_t len = ptr[1] - ptr[0];
176 engine->submit_read(fd, len, offset, cb);
180 size_t Corpus::get_num_filename_blocks() const
182 // The beginning of the filename blocks is the end of the filename index blocks.
184 complete_pread(fd, &end, sizeof(end), hdr.filename_index_offset_bytes);
186 // Subtract the sentinel block.
187 return (end - hdr.filename_index_offset_bytes) / sizeof(uint64_t) - 1;
190 size_t scan_file_block(const vector<string> &needles, string_view compressed,
191 unordered_map<string, bool> *access_rx_cache)
195 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
196 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
197 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
202 block.resize(uncompressed_len + 1);
204 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
206 if (ZSTD_isError(err)) {
207 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
210 block[block.size() - 1] = '\0';
212 for (const char *filename = block.data();
213 filename != block.data() + block.size();
214 filename += strlen(filename) + 1) {
216 for (const string &needle : needles) {
217 if (strstr(filename, needle.c_str()) == nullptr) {
222 if (found && has_access(filename, access_rx_cache)) {
225 printf("%s%c", filename, 0);
227 printf("%s\n", filename);
234 size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
236 Serializer docids_in_order;
237 unordered_map<string, bool> access_rx_cache;
239 for (size_t i = 0; i < docids.size(); ++i) {
240 uint32_t docid = docids[i];
241 corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string compressed) {
242 docids_in_order.do_or_wait(i, [&matched, &needles, compressed{ move(compressed) }, &access_rx_cache] {
243 matched += scan_file_block(needles, compressed, &access_rx_cache);
251 // We do this sequentially, as it's faster than scattering
252 // a lot of I/O through io_uring and hoping the kernel will
253 // coalesce it plus readahead for us.
254 void scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
256 unordered_map<string, bool> access_rx_cache;
257 uint32_t num_blocks = corpus.get_num_filename_blocks();
258 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
259 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
261 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
262 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
263 size_t io_len = offsets[last_docid] - offsets[io_docid];
264 if (compressed.size() < io_len) {
265 compressed.resize(io_len);
267 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
269 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
270 size_t relative_offset = offsets[docid] - offsets[io_docid];
271 size_t len = offsets[docid + 1] - offsets[docid];
272 scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache);
277 void do_search_file(const vector<string> &needles, const char *filename)
279 int fd = open(filename, O_RDONLY);
286 if (setgid(getgid()) != 0) {
291 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
292 if (access("/", R_OK | X_OK)) {
293 // We can't find anything, no need to bother...
297 IOUringEngine engine;
298 Corpus corpus(fd, &engine);
299 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
301 vector<pair<Trigram, size_t>> trigrams;
302 for (const string &needle : needles) {
303 if (needle.size() < 3) continue;
304 for (size_t i = 0; i < needle.size() - 2; ++i) {
305 uint32_t trgm = read_trigram(needle, i);
306 corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
307 if (trgmptr == nullptr) {
308 dprintf("trigram %06x isn't found, we abort the search\n", trgm);
311 trigrams.emplace_back(*trgmptr, len);
316 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
318 if (trigrams.empty()) {
319 // Too short for trigram matching. Apply brute force.
320 // (We could have searched through all trigrams that matched
321 // the pattern and done a union of them, but that's a lot of
322 // work for fairly unclear gain.)
323 scan_all_docids(needles, fd, corpus, &engine);
326 sort(trigrams.begin(), trigrams.end());
328 auto last = unique(trigrams.begin(), trigrams.end());
329 trigrams.erase(last, trigrams.end());
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;
336 vector<uint32_t> in1, in2, out;
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);
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) {
356 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
359 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
360 size_t num = trgmptr.num_docids;
361 unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
363 in1.resize(num + 128);
364 p4nd1dec128v32(pldata, num, &in1[0]);
366 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
367 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
369 if (in2.size() < num + 128) {
370 in2.resize(num + 128);
372 p4nd1dec128v32(pldata, num, &in2[0]);
375 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
378 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
379 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
380 len, num, in1.size());
382 dprintf("no matches (intersection list is empty)\n");
392 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
393 1e3 * duration<float>(steady_clock::now() - start).count());
395 size_t matched __attribute__((unused)) = scan_docids(needles, in1, corpus, &engine);
396 dprintf("Done in %.1f ms, found %zu matches.\n",
397 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
402 // The help text comes from mlocate.
403 printf("Usage: slocate [OPTION]... PATTERN...\n");
404 printf(" -d, --database DBPATH use DBPATH instead of default database (which is\n");
405 printf(" %s)\n", dbpath);
406 printf(" -h, --help print this help\n");
407 printf(" -0, --null separate entries with NUL on output\n");
410 int main(int argc, char **argv)
412 static const struct option long_options[] = {
413 { "help", no_argument, 0, 'h' },
414 { "database", required_argument, 0, 'd' },
415 { "null", no_argument, 0, '0' },
420 int option_index = 0;
421 int c = getopt_long(argc, argv, "d:h0", long_options, &option_index);
427 dbpath = strdup(optarg);
438 vector<string> needles;
439 for (int i = optind; i < argc; ++i) {
440 needles.push_back(argv[i]);
442 if (needles.empty()) {
443 fprintf(stderr, "slocate: no pattern to search for specified\n");
446 do_search_file(needles, dbpath);