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)
214 block.resize(ZSTD_getFrameContentSize(compressed.data(), compressed.size()) +
217 ZSTD_decompress(&block[0], block.size(), compressed.data(),
219 block[block.size() - 1] = '\0';
221 for (const char *filename = block.data();
222 filename != block.data() + block.size();
223 filename += strlen(filename) + 1) {
224 if (strstr(filename, needle.c_str()) == nullptr) {
227 if (has_access(filename, access_rx_cache)) {
229 printf("%s\n", filename);
235 size_t scan_docids(const string &needle, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
237 Serializer docids_in_order;
238 unordered_map<string, bool> access_rx_cache;
240 for (size_t i = 0; i < docids.size(); ++i) {
241 uint32_t docid = docids[i];
242 corpus.get_compressed_filename_block(docid, [i, &matched, &needle, &access_rx_cache, &docids_in_order](string compressed) {
243 docids_in_order.do_or_wait(i, [&matched, &needle, compressed{ move(compressed) }, &access_rx_cache] {
244 matched += scan_file_block(needle, compressed, &access_rx_cache);
252 // We do this sequentially, as it's faster than scattering
253 // a lot of I/O through io_uring and hoping the kernel will
254 // coalesce it plus readahead for us.
255 void scan_all_docids(const string &needle, int fd, const Corpus &corpus, IOUringEngine *engine)
257 unordered_map<string, bool> access_rx_cache;
258 uint32_t num_blocks = corpus.get_num_filename_blocks();
259 unique_ptr<uint64_t[]> offsets(new uint64_t[num_blocks + 1]);
260 complete_pread(fd, offsets.get(), (num_blocks + 1) * sizeof(uint64_t), corpus.offset_for_block(0));
262 for (uint32_t io_docid = 0; io_docid < num_blocks; io_docid += 32) {
263 uint32_t last_docid = std::min(io_docid + 32, num_blocks);
264 size_t io_len = offsets[last_docid] - offsets[io_docid];
265 if (compressed.size() < io_len) {
266 compressed.resize(io_len);
268 complete_pread(fd, &compressed[0], io_len, offsets[io_docid]);
270 for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
271 size_t relative_offset = offsets[docid] - offsets[io_docid];
272 size_t len = offsets[docid + 1] - offsets[docid];
273 scan_file_block(needle, {&compressed[relative_offset], len}, &access_rx_cache);
278 void do_search_file(const string &needle, const char *filename)
280 int fd = open(filename, O_RDONLY);
287 if (setgid(getgid()) != 0) {
292 steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
293 if (access("/", R_OK | X_OK)) {
294 // We can't find anything, no need to bother...
298 IOUringEngine engine;
299 Corpus corpus(fd, &engine);
300 dprintf("Corpus init took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
302 if (needle.size() < 3) {
303 // Too short for trigram matching. Apply brute force.
304 // (We could have searched through all trigrams that matched
305 // the pattern and done a union of them, but that's a lot of
306 // work for fairly unclear gain.)
307 scan_all_docids(needle, fd, corpus, &engine);
311 vector<pair<Trigram, size_t>> trigrams;
312 for (size_t i = 0; i < needle.size() - 2; ++i) {
313 uint32_t trgm = read_trigram(needle, i);
314 pair<uint32_t, uint32_t> range{ 0, corpus.num_trigrams - 1 };
315 corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
316 if (trgmptr == nullptr) {
317 dprintf("trigram %06x isn't found, we abort the search\n", trgm);
320 trigrams.emplace_back(*trgmptr, len);
324 dprintf("Binary search took %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
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) {
357 uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
358 size_t num = trgmptr.num_docids;
359 unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
361 in1.resize(num + 128);
362 p4nd1dec128v32(pldata, num, &in1[0]);
364 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
365 (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
367 if (in2.size() < num + 128) {
368 in2.resize(num + 128);
370 p4nd1dec128v32(pldata, num, &in2[0]);
373 set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
376 dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries, %zu left\n",
377 trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
378 len, num, in1.size());
380 dprintf("no matches (intersection list is empty)\n");
387 dprintf("Intersection took %.1f ms. Doing final verification and printing:\n",
388 1e3 * duration<float>(steady_clock::now() - start).count());
390 size_t matched __attribute__((unused)) = scan_docids(needle, in1, corpus, &engine);
391 dprintf("Done in %.1f ms, found %zu matches.\n",
392 1e3 * duration<float>(steady_clock::now() - start).count(), matched);
395 int main(int argc, char **argv)
397 do_search_file(argv[1], "/var/lib/mlocate/plocate.db");