]> git.sesse.net Git - plocate/blobdiff - plocate.cpp
Move exception shifting to later; allows us to get it into SSE2.
[plocate] / plocate.cpp
index 84fcd7a7e47a93e0b85a453e742e50bd444df994..2c5514ee8b16bc5f3c8461a0c97821e6a2216987 100644 (file)
@@ -1,13 +1,16 @@
 #include "db.h"
-#include "vp4.h"
 #include "io_uring_engine.h"
+#include "vp4.h"
 
 #include <algorithm>
 #include <arpa/inet.h>
+#include <assert.h>
 #include <chrono>
 #include <endian.h>
 #include <fcntl.h>
 #include <functional>
+#include <getopt.h>
+#include <limits.h>
 #include <memory>
 #include <stdio.h>
 #include <string.h>
@@ -23,15 +26,22 @@ using namespace std::chrono;
 #define dprintf(...)
 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
 
+#include "turbopfor.h"
+
+const char *dbpath = "/var/lib/mlocate/plocate.db";
+bool print_nul = false;
+
 class Serializer {
 public:
-       void do_or_wait(int seq, function<void()> cb);
+       bool ready_to_print(int seq) { return next_seq == seq; }
+       void print_delayed(int seq, const vector<string> msg);
+       void release_current();
 
 private:
        int next_seq = 0;
        struct Element {
                int seq;
-               function<void()> cb;
+               vector<string> msg;
 
                bool operator<(const Element &other) const
                {
@@ -41,18 +51,24 @@ private:
        priority_queue<Element> pending;
 };
 
-void Serializer::do_or_wait(int seq, function<void()> cb)
+void Serializer::print_delayed(int seq, const vector<string> msg)
 {
-       if (seq != next_seq) {
-               pending.emplace(Element{ seq, move(cb) });
-               return;
-       }
+       pending.push(Element{ seq, move(msg) });
+}
 
-       cb();
+void Serializer::release_current()
+{
        ++next_seq;
 
+       // See if any delayed prints can now be dealt with.
        while (!pending.empty() && pending.top().seq == next_seq) {
-               pending.top().cb();
+               for (const string &msg : pending.top().msg) {
+                       if (print_nul) {
+                               printf("%s%c", msg.c_str(), 0);
+                       } else {
+                               printf("%s\n", msg.c_str());
+                       }
+               }
                pending.pop();
                ++next_seq;
        }
@@ -103,7 +119,8 @@ public:
        void find_trigram(uint32_t trgm, function<void(const Trigram *trgmptr, size_t len)> cb);
        void get_compressed_filename_block(uint32_t docid, function<void(string)> cb) const;
        size_t get_num_filename_blocks() const;
-       off_t offset_for_block(uint32_t docid) const {
+       off_t offset_for_block(uint32_t docid) const
+       {
                return hdr.filename_index_offset_bytes + docid * sizeof(uint64_t);
        }
 
@@ -174,16 +191,12 @@ void Corpus::get_compressed_filename_block(uint32_t docid, function<void(string)
 
 size_t Corpus::get_num_filename_blocks() const
 {
-       // The beginning of the filename blocks is the end of the filename index blocks.
-       uint64_t end;
-       complete_pread(fd, &end, sizeof(end), hdr.filename_index_offset_bytes);
-
-       // Subtract the sentinel block.
-       return (end - hdr.filename_index_offset_bytes) / sizeof(uint64_t) - 1;
+       return hdr.num_docids;
 }
 
-size_t scan_file_block(const string &needle, string_view compressed,
-                       unordered_map<string, bool> *access_rx_cache)
+size_t scan_file_block(const vector<string> &needles, string_view compressed,
+                       unordered_map<string, bool> *access_rx_cache, int seq,
+                       Serializer *serializer)
 {
        size_t matched = 0;
 
@@ -197,38 +210,58 @@ size_t scan_file_block(const string &needle, string_view compressed,
        block.resize(uncompressed_len + 1);
 
        size_t err = ZSTD_decompress(&block[0], block.size(), compressed.data(),
-                       compressed.size());
+                                    compressed.size());
        if (ZSTD_isError(err)) {
                fprintf(stderr, "ZSTD_decompress(): %s\n", ZSTD_getErrorName(err));
                exit(1);
        }
        block[block.size() - 1] = '\0';
 
+       bool immediate_print = (serializer == nullptr || serializer->ready_to_print(seq));
+       vector<string> delayed;
+
        for (const char *filename = block.data();
             filename != block.data() + block.size();
             filename += strlen(filename) + 1) {
-               if (strstr(filename, needle.c_str()) == nullptr) {
-                       continue;
+               bool found = true;
+               for (const string &needle : needles) {
+                       if (strstr(filename, needle.c_str()) == nullptr) {
+                               found = false;
+                               break;
+                       }
                }
-               if (has_access(filename, access_rx_cache)) {
+               if (found && has_access(filename, access_rx_cache)) {
                        ++matched;
-                       printf("%s\n", filename);
+                       if (immediate_print) {
+                               if (print_nul) {
+                                       printf("%s%c", filename, 0);
+                               } else {
+                                       printf("%s\n", filename);
+                               }
+                       } else {
+                               delayed.push_back(filename);
+                       }
+               }
+       }
+       if (serializer != nullptr) {
+               if (immediate_print) {
+                       serializer->release_current();
+               } else {
+                       serializer->print_delayed(seq, move(delayed));
                }
        }
        return matched;
 }
 
-size_t scan_docids(const string &needle, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
+size_t scan_docids(const vector<string> &needles, const vector<uint32_t> &docids, const Corpus &corpus, IOUringEngine *engine)
 {
        Serializer docids_in_order;
        unordered_map<string, bool> access_rx_cache;
        size_t matched = 0;
        for (size_t i = 0; i < docids.size(); ++i) {
                uint32_t docid = docids[i];
-               corpus.get_compressed_filename_block(docid, [i, &matched, &needle, &access_rx_cache, &docids_in_order](string compressed) {
-                       docids_in_order.do_or_wait(i, [&matched, &needle, compressed{ move(compressed) }, &access_rx_cache] {
-                               matched += scan_file_block(needle, compressed, &access_rx_cache);
-                       });
+               corpus.get_compressed_filename_block(docid, [i, &matched, &needles, &access_rx_cache, &docids_in_order](string compressed) {
+                       matched += scan_file_block(needles, compressed, &access_rx_cache, i, &docids_in_order);
                });
        }
        engine->finish();
@@ -238,7 +271,7 @@ size_t scan_docids(const string &needle, const vector<uint32_t> &docids, const C
 // We do this sequentially, as it's faster than scattering
 // a lot of I/O through io_uring and hoping the kernel will
 // coalesce it plus readahead for us.
-void scan_all_docids(const string &needle, int fd, const Corpus &corpus, IOUringEngine *engine)
+void scan_all_docids(const vector<string> &needles, int fd, const Corpus &corpus, IOUringEngine *engine)
 {
        unordered_map<string, bool> access_rx_cache;
        uint32_t num_blocks = corpus.get_num_filename_blocks();
@@ -256,12 +289,12 @@ void scan_all_docids(const string &needle, int fd, const Corpus &corpus, IOUring
                for (uint32_t docid = io_docid; docid < last_docid; ++docid) {
                        size_t relative_offset = offsets[docid] - offsets[io_docid];
                        size_t len = offsets[docid + 1] - offsets[docid];
-                       scan_file_block(needle, {&compressed[relative_offset], len}, &access_rx_cache);
+                       scan_file_block(needles, { &compressed[relative_offset], len }, &access_rx_cache, 0, nullptr);
                }
        }
 }
 
-void do_search_file(const string &needle, const char *filename)
+void do_search_file(const vector<string> &needles, const char *filename)
 {
        int fd = open(filename, O_RDONLY);
        if (fd == -1) {
@@ -285,29 +318,41 @@ void do_search_file(const string &needle, const char *filename)
        Corpus corpus(fd, &engine);
        dprintf("Corpus init done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
 
-       if (needle.size() < 3) {
+       vector<pair<Trigram, size_t>> trigrams;
+       uint64_t shortest_so_far = numeric_limits<uint32_t>::max();
+       for (const string &needle : needles) {
+               if (needle.size() < 3)
+                       continue;
+               for (size_t i = 0; i < needle.size() - 2; ++i) {
+                       uint32_t trgm = read_trigram(needle, i);
+                       corpus.find_trigram(trgm, [trgm, &trigrams, &shortest_so_far](const Trigram *trgmptr, size_t len) {
+                               if (trgmptr == nullptr) {
+                                       dprintf("trigram '%c%c%c' isn't found, we abort the search\n",
+                                               trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff);
+                                       exit(0);
+                               }
+                               if (trgmptr->num_docids > shortest_so_far * 100) {
+                                       dprintf("not loading trigram '%c%c%c' with %u docids, it would be ignored later anyway\n",
+                                               trgm & 0xff, (trgm >> 8) & 0xff, (trgm >> 16) & 0xff,
+                                               trgmptr->num_docids);
+                               } else {
+                                       trigrams.emplace_back(*trgmptr, len);
+                                       shortest_so_far = std::min<uint64_t>(shortest_so_far, trgmptr->num_docids);
+                               }
+                       });
+               }
+       }
+       engine.finish();
+       dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
+
+       if (trigrams.empty()) {
                // Too short for trigram matching. Apply brute force.
                // (We could have searched through all trigrams that matched
                // the pattern and done a union of them, but that's a lot of
                // work for fairly unclear gain.)
-               scan_all_docids(needle, fd, corpus, &engine);
+               scan_all_docids(needles, fd, corpus, &engine);
                return;
        }
-
-       vector<pair<Trigram, size_t>> trigrams;
-       for (size_t i = 0; i < needle.size() - 2; ++i) {
-               uint32_t trgm = read_trigram(needle, i);
-               corpus.find_trigram(trgm, [trgm, &trigrams](const Trigram *trgmptr, size_t len) {
-                       if (trgmptr == nullptr) {
-                               dprintf("trigram %06x isn't found, we abort the search\n", trgm);
-                               return;
-                       }
-                       trigrams.emplace_back(*trgmptr, len);
-               });
-       }
-       engine.finish();
-       dprintf("Hashtable lookups done after %.1f ms.\n", 1e3 * duration<float>(steady_clock::now() - start).count());
-
        sort(trigrams.begin(), trigrams.end());
        {
                auto last = unique(trigrams.begin(), trigrams.end());
@@ -339,12 +384,14 @@ void do_search_file(const string &needle, const char *filename)
                                break;
                }
                engine.submit_read(fd, len, trgmptr.offset, [trgmptr, len, &done, &in1, &in2, &out](string s) {
+                       if (done)
+                               return;
                        uint32_t trgm __attribute__((unused)) = trgmptr.trgm;
                        size_t num = trgmptr.num_docids;
                        unsigned char *pldata = reinterpret_cast<unsigned char *>(s.data());
                        if (in1.empty()) {
                                in1.resize(num + 128);
-                               p4nd1dec128v32(pldata, num, &in1[0]);
+                               decode_pfor_delta1<128>(pldata, num, /*interleaved=*/true, &in1[0]);
                                in1.resize(num);
                                dprintf("trigram '%c%c%c' (%zu bytes) decoded to %zu entries\n", trgm & 0xff,
                                        (trgm >> 8) & 0xff, (trgm >> 16) & 0xff, len, num);
@@ -352,7 +399,7 @@ void do_search_file(const string &needle, const char *filename)
                                if (in2.size() < num + 128) {
                                        in2.resize(num + 128);
                                }
-                               p4nd1dec128v32(pldata, num, &in2[0]);
+                               decode_pfor_delta1<128>(pldata, num, /*interleaved=*/true, &in2[0]);
 
                                out.clear();
                                set_intersection(in1.begin(), in1.end(), in2.begin(), in2.begin() + num,
@@ -369,15 +416,65 @@ void do_search_file(const string &needle, const char *filename)
                });
        }
        engine.finish();
+       if (done) {
+               return;
+       }
        dprintf("Intersection done after %.1f ms. Doing final verification and printing:\n",
                1e3 * duration<float>(steady_clock::now() - start).count());
 
-       size_t matched __attribute__((unused)) = scan_docids(needle, in1, corpus, &engine);
+       size_t matched __attribute__((unused)) = scan_docids(needles, in1, corpus, &engine);
        dprintf("Done in %.1f ms, found %zu matches.\n",
                1e3 * duration<float>(steady_clock::now() - start).count(), matched);
 }
 
+void usage()
+{
+       // The help text comes from mlocate.
+       printf("Usage: plocate [OPTION]... PATTERN...\n");
+       printf("\n");
+       printf("  -d, --database DBPATH  use DBPATH instead of default database (which is\n");
+       printf("                         %s)\n", dbpath);
+       printf("  -h, --help             print this help\n");
+       printf("  -0, --null             separate entries with NUL on output\n");
+}
+
 int main(int argc, char **argv)
 {
-       do_search_file(argv[1], "/var/lib/mlocate/plocate.db");
+       static const struct option long_options[] = {
+               { "help", no_argument, 0, 'h' },
+               { "database", required_argument, 0, 'd' },
+               { "null", no_argument, 0, '0' },
+               { 0, 0, 0, 0 }
+       };
+
+       for (;;) {
+               int option_index = 0;
+               int c = getopt_long(argc, argv, "d:h0", long_options, &option_index);
+               if (c == -1) {
+                       break;
+               }
+               switch (c) {
+               case 'd':
+                       dbpath = strdup(optarg);
+                       break;
+               case 'h':
+                       usage();
+                       exit(0);
+               case '0':
+                       print_nul = true;
+                       break;
+               default:
+                       exit(1);
+               }
+       }
+
+       vector<string> needles;
+       for (int i = optind; i < argc; ++i) {
+               needles.push_back(argv[i]);
+       }
+       if (needles.empty()) {
+               fprintf(stderr, "plocate: no pattern to search for specified\n");
+               exit(0);
+       }
+       do_search_file(needles, dbpath);
 }