3 #include "io_uring_engine.h"
16 #include <unordered_map>
21 using namespace std::chrono;
24 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
28 void do_or_wait(int seq, function<void()> cb);
36 bool operator<(const Element &other) const
38 return seq > other.seq;
41 priority_queue<Element> pending;
44 void Serializer::do_or_wait(int seq, function<void()> cb)
46 if (seq != next_seq) {
47 pending.emplace(Element{ seq, move(cb) });
54 while (!pending.empty() && pending.top().seq == next_seq) {
61 static inline uint32_t read_unigram(const string &s, size_t idx)
64 return (unsigned char)s[idx];
70 static inline uint32_t read_trigram(const string &s, size_t start)
72 return read_unigram(s, start) | (read_unigram(s, start + 1) << 8) |
73 (read_unigram(s, start + 2) << 16);
76 bool has_access(const char *filename,
77 unordered_map<string, bool> *access_rx_cache)
79 const char *end = strchr(filename + 1, '/');
80 while (end != nullptr) {
81 string parent_path(filename, end);
82 auto it = access_rx_cache->find(parent_path);
84 if (it == access_rx_cache->end()) {
85 ok = access(parent_path.c_str(), R_OK | X_OK) == 0;
86 access_rx_cache->emplace(move(parent_path), ok);
93 end = strchr(end + 1, '/');
101 Corpus(int fd, IOUringEngine *engine);
103 void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
104 void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
105 size_t get_num_filename_blocks() const;
106 off_t offset_for_block(uint32_t docid) const {
107 return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
112 IOUringEngine *const engine;
117 Corpus::Corpus(int fd, IOUringEngine *engine)
118 : fd(fd), engine(engine)
120 // Enable to test cold-cache behavior (except for access()).
122 off_t len = lseek(fd, 0, SEEK_END);
127 posix_fadvise(fd, 0, len, POSIX_FADV_DONTNEED);
130 complete_pread(fd, &hdr, sizeof(hdr), /*offset=*/0);
131 if (memcmp(hdr.magic, "\0plocate", 8) != 0) {
132 fprintf(stderr, "plocate.db is corrupt or an old version; please rebuild it.\n");
135 if (hdr.version != 0) {
136 fprintf(stderr, "plocate.db has version %u, expected 0; please rebuild it.\n", hdr.version);
146 void Corpus::find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb)
148 uint32_t bucket = hash_trigram(trgm, hdr.hashtable_size);
149 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) {
150 const Trigram *trgmptr = reinterpret_cast<const Trigram *>(s.data());
151 for (unsigned i = 0; i < hdr.extra_ht_slots + 1; ++i) {
152 if (trgmptr[i].trgm == trgm) {
153 cb(trgmptr + i, trgmptr[i + 1].offset - trgmptr[i].offset);
163 void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const
165 // Read the file offset from this docid and the next one.
166 // This is always allowed, since we have a sentinel block at the end.
167 engine->submit_read(fd, sizeof(uint64_t) * 2, offset_for_block(docid), [this, cb{ move(cb) }](string s) {
168 const uint64_t *ptr = reinterpret_cast<const uint64_t *>(s.data());
169 off_t offset = ptr[0];
170 size_t len = ptr[1] - ptr[0];
171 engine->submit_read(fd, len, offset, cb);
175 size_t Corpus::get_num_filename_blocks() const
177 // The beginning of the filename blocks is the end of the filename index blocks.
179 complete_pread(fd, &end, sizeof(end), hdr.filename_index_offset_bytes);
181 // Subtract the sentinel block.
182 return (end - hdr.filename_index_offset_bytes) / sizeof(uint64_t) - 1;
185 size_t scan_file_block(const string &needle, string_view compressed,
186 unordered_map<string, bool> *access_rx_cache)
190 unsigned long long uncompressed_len = ZSTD_getFrameContentSize(compressed.data(), compressed.size());
191 if (uncompressed_len == ZSTD_CONTENTSIZE_UNKNOWN || uncompressed_len == ZSTD_CONTENTSIZE_ERROR) {
192 fprintf(stderr, "ZSTD_getFrameContentSize() failed\n");
197 block.resize(uncompressed_len + 1);
199 size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
201 if (ZSTD_isError(err)) {
202 fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
205 block[block.size() - 1] = '\0';
207 for (const char *filename = block.data();
208 filename != block.data() + block.size();
209 filename += strlen(filename) + 1) {
210 if (strstr(filename, needle.c_str()) == nullptr) {
213 if (has_access(filename, access_rx_cache)) {
215 printf("%s\n", filename);
221 size_t scan_docids(const string &needle, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
223 Serializer docids_in_order;
224 unordered_map<string, bool> access_rx_cache;
226 for (size_t i = 0; i < docids.size(); ++i) {
227 uint32_t docid = docids[i];
228 corpus.get_compressed_filename_block(docid, [i, &matched, &needle, &access_rx_cache, &docids_in_order](string compressed) {
229 docids_in_order.do_or_wait(i, [&matched, &needle, compressed{ move(compressed) }, &access_rx_cache] {
230 matched += scan_file_block(needle, compressed, &access_rx_cache);
238 // We do this sequentially, as it's faster than scattering
239 // a lot of I/O through io_uring and hoping the kernel will
240 // coalesce it plus readahead for us.
241 void scan_all_docids(const string &needle, int fd, const Corpus &corpus, IOUringEngine *engine)
243 unordered_map<string, bool> access_rx_cache;
244 uint32_t num_blocks = corpus.get_num_filename_blocks();
245 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
246 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
248 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
249 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
250 size_t io_len = offsets[last_docid] - offsets[io_docid];
251 if (compressed.size() < io_len) {
252 compressed.resize(io_len);
254 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
256 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
257 size_t relative_offset = offsets[docid] - offsets[io_docid];
258 size_t len = offsets[docid + 1] - offsets[docid];
259 scan_file_block(needle, {&compressed[relative_offset], len}, &access_rx_cache);
264 void do_search_file(const string &needle, const char *filename)
266 int fd = open(filename, O_RDONLY);
273 if (setgid(getgid()) != 0) {
278 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
279 if (access("/", R_OK | X_OK)) {
280 // We can't find anything, no need to bother...
284 IOUringEngine engine;
285 Corpus corpus(fd, &engine);
286 dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
288 if (needle.size() < 3) {
289 // Too short for trigram matching. Apply brute force.
290 // (We could have searched through all trigrams that matched
291 // the pattern and done a union of them, but that's a lot of
292 // work for fairly unclear gain.)
293 scan_all_docids(needle, fd, corpus, &engine);
297 vector<pair<Trigram, size_t>> trigrams;
298 for (size_t i = 0; i < needle.size() - 2; ++i) {
299 uint32_t trgm = read_trigram(needle, i);
300 corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
301 if (trgmptr == nullptr) {
302 dprintf("trigram %06x isn't found, we abort the search\n", trgm);
305 trigrams.emplace_back(*trgmptr, len);
309 dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
311 sort(trigrams.begin(), trigrams.end());
313 auto last = unique(trigrams.begin(), trigrams.end());
314 trigrams.erase(last, trigrams.end());
316 sort(trigrams.begin(), trigrams.end(),
317 [&](const pair<Trigram, size_t> &a, const pair<Trigram, size_t> &b) {
318 return a.first.num_docids < b.first.num_docids;
321 vector<uint32_t> in1, in2, out;
323 for (auto [trgmptr, len] : trigrams) {
324 if (!in1.empty() && trgmptr.num_docids > in1.size() * 100) {
325 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
326 dprintf("trigram '%c%c%c' (%zu bytes) has %u entries, ignoring the rest (will "
327 "weed out false positives later)\n",
328 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
329 len, trgmptr.num_docids);
333 // Only stay a certain amount ahead, so that we don't spend I/O
334 // on reading the latter, large posting lists. We are unlikely
335 // to need them anyway, even if they should come in first.
336 if (engine.get_waiting_reads() >= 5) {
341 engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
342 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
343 size_t num = trgmptr.num_docids;
344 unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
346 in1.resize(num + 128);
347 p4nd1dec128v32(pldata, num, &in1[0]);
349 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
350 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
352 if (in2.size() < num + 128) {
353 in2.resize(num + 128);
355 p4nd1dec128v32(pldata, num, &in2[0]);
358 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
361 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
362 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
363 len, num, in1.size());
365 dprintf("no matches (intersection list is empty)\n");
372 dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
373 1e3 * duration<float>(steady_clock::now() - start).count());
375 size_t matched __attribute__((unused)) = scan_docids(needle, in1, corpus, &engine);
376 dprintf("Done in %.1f ms, found %zu matches.\n",
377 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
380 int main(int argc, char **argv)
382 do_search_file(argv[1], "/var/lib/mlocate/plocate.db");