[code] [blog] [Repos] [GPS Tracker] [Music] [VNC] [Restart VNC] [E-Mail me]

browse files at this commit · zip

commit a3d925cbbc751db3b7c7270701a1b577c7e2c49d
Author: no-body-in-particular <admin@coredump.ws>
Date:   Wed Oct 14 22:04:21 2026 +0200

    Map cell.db instead of copying it into the heap, and let a lookup miss
    
    init_lbs() read all 1.4 GB of cell.db (46.6 million towers) into one
    private allocation in every worker. Being private and rarely touched, it
    ended up in swap: 1.36 GB of it after five days. It is now mapped read-only
    and shared; pages come from the page cache, which the kernel can drop and
    re-read, and startup no longer reads the file at all.
    
    binary_search() returned the last entry it looked at when the range ran
    down to one, whether or not it matched, so lbs_in_db() never missed: an
    unknown tower got the position of whichever tower sorted next to it -
    possibly another country - the positioning services were never asked, the
    nearest-in-area fallback never ran, and nothing was ever cached. The lookup
    is now a lower bound with an equality check.
    
    That miss used to be the only thing keeping the cache merge from running.
    It grew the whole database by a fifth and quick-sorted 46 million records
    under the LBS mutex, which on this data extrapolates to days. New towers
    now go to a small sorted cell.db.learned beside it, and are folded into
    cell.db at startup, streamed into a new file and renamed, once there are
    LBS_FOLD_MIN of them or a csv export is present.
    
    Unknown towers will now really be asked of Google/HERE/beaconDB, within the
    existing request budgets.
    
    fetch_celldb wrote over cell.db in place, which would fault a worker that
    has it mapped; it now builds the new file beside it and renames it.
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---
 device_server/config.h             |  16 +
 device_server/lbs_lookup.c         | 683 ++++++++++++++++++++++++++-----------
 device_server/lbs_lookup.h         |  22 +-
 device_server/test/Makefile        |   8 +
 device_server/test/test_lbs_mmap.c | 118 +++++++
 var/gps/fetch_celldb               |  10 +-
 6 files changed, 644 insertions(+), 213 deletions(-)

diff --git a/device_server/config.h b/device_server/config.h
index ce12830..a4b2853 100644
--- a/device_server/config.h
+++ b/device_server/config.h
@@ -209,6 +209,22 @@
 #define CELLDB_FILE "/var/gps/cell.db"
 #endif
 
+/*
+ * cell.db is mapped read-only rather than read into the heap (it is ~1.4 GB). Towers the
+ * positioning service answers for are kept, sorted, in a small file of the same format next
+ * to it, and folded into cell.db at startup once there are LBS_FOLD_MIN of them (or a csv
+ * import has added any). The global geolocation budget (GEO_GLOBAL_PER_HOUR) caps how fast
+ * that file can grow: under 30000 towers, under 1 MB, a day.
+ *
+ * cell.db must only ever be replaced by renaming a complete file over it (as this daemon
+ * does): a file truncated or rewritten in place under a running daemon makes its next lookup
+ * a SIGBUS.
+ */
+#ifndef CELLDB_LEARNED_FILE
+#define CELLDB_LEARNED_FILE CELLDB_FILE ".learned"
+#endif
+#define LBS_FOLD_MIN 65536
+
 #define OPENCELLID_FILE "opencellid.csv"
 #define MOZCELLID_FILE "mozilla.csv"
 
diff --git a/device_server/lbs_lookup.c b/device_server/lbs_lookup.c
index 7958d08..e8f7bff 100644
--- a/device_server/lbs_lookup.c
+++ b/device_server/lbs_lookup.c
@@ -2,75 +2,362 @@
 #include "string.h"
 #include "util.h"
 #include "web_geolocate.h"
-#include "sort.h"
-#include "search.h"
 #include <float.h>
 #include "crc64.h"
 #include <errno.h>
-
-double compare_lbs(void  * tower_a, void * tower_b) {
-    return memcmp(tower_b, tower_a, 9);
+#include <fcntl.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+
+//the nine bytes every lookup is keyed on: mcc, lac, mnc, cell id
+#define LBS_KEY 9
+//the five of them every tower in one area shares: mcc, lac, mnc
+#define LBS_AREA 5
+//the count at the start of cell.db and the learned file
+#define LBS_HEADER sizeof(uint64_t)
+
+static int compare_lbs_key(const void * a, const void * b) {
+    return memcmp(a, b, LBS_KEY);
 }
 
-//the arguments are reversed to match compare_lbs. partition() calls COMPARE(pivot, elem)
-//and moves elem to the front when the result is negative, and binary_search() calls
-//COMPARE(mid, to_find) and steps left when the result is negative - both of which only
-//land correctly on the ascending array this convention produces. Comparing in the plain
-//order here meant the partial search stepped left when the target lay to the right, so it
-//routinely landed outside the block it was looking for.
-double compare_lbs_partial(void  * tower_a, void * tower_b) {
-    return memcmp(tower_b, tower_a, 5);
+/*
+ * The first of towers[0..count) whose first `len` bytes are not below key's. The array is
+ * sorted ascending by memcmp of its first nine bytes, and so by any prefix of them.
+ *
+ * This replaces binary_search() from search.c for the tower arrays. That one never reports a
+ * miss: once it has narrowed the range to one entry it returns that entry whether it matches
+ * or not, so lbs_in_db() answered every unknown tower with whatever happened to sort next to
+ * it - often another area or another country - and never asked the positioning service. The
+ * cache stayed empty and cell.db has not been rewritten since it was installed.
+ */
+static size_t lbs_lower_bound(const cell_tower * towers, size_t count, const void * key, size_t len) {
+    size_t lo = 0, hi = count;
+
+    while (lo < hi) {
+        size_t mid = lo + (hi - lo) / 2;
+
+        if (memcmp(&towers[mid], key, len) < 0) {
+            lo = mid + 1;
+
+        } else {
+            hi = mid;
+        }
+    }
+
+    return lo;
 }
 
+static const cell_tower * lbs_find(const cell_tower * towers, size_t count, const cell_tower * key) {
+    size_t at = lbs_lower_bound(towers, count, key, LBS_KEY);
+    return (at < count && memcmp(&towers[at], key, LBS_KEY) == 0) ? &towers[at] : NULL;
+}
 
 /*
- * Make room for at least `want` towers in tower_buffer, keeping tower_memory_size equal to
- * what is actually allocated. Every resize of the buffer goes through here.
+ * Sort towers and drop repeated keys, keeping the last of each - the newest, for an array
+ * that was appended to in order. qsort is not stable, so each tower is sorted together with
+ * its position and that breaks ties.
  *
- * Two of them used to bypass it. lbs_database_from_file() and read_lbs_file() reallocated the
- * buffer to exactly the number of towers read while tower_memory_size kept saying 1048576,
- * so the next merge believed it had room it did not and memcpy'd the cache past the end of
- * the heap block. And a cache file holding no towers made that realloc a realloc(p, 0), which
- * frees p and returns NULL: the failure branch kept the freed pointer, and the next merge
- * reallocated it a second time.
- *
- * Never asks for zero bytes. Returns false, with the buffer and its size unchanged, if the
- * allocation fails.
+ * (quick_sort() from sort.c is not used for this: it picks its pivot from fast_rand(), which
+ * never exceeds 32767, so on a large array that is already mostly sorted - cell.db plus a few
+ * new towers, which is what it used to be handed - every partition splits off a few thousand
+ * entries at most and the sort runs to tens of billions of comparisons.)
+ */
+typedef struct __attribute__((packed)) {
+    cell_tower tower;
+    uint32_t order;
+}
+
+lbs_sort_entry;
+
+static int compare_lbs_sort_entry(const void * a, const void * b) {
+    int c = memcmp(a, b, LBS_KEY);
+
+    if (c != 0) {
+        return c;
+    }
+
+    uint32_t oa = ((const lbs_sort_entry *)a)->order, ob = ((const lbs_sort_entry *)b)->order;
+    return (oa > ob) - (oa < ob);
+}
+
+static size_t lbs_sort_unique(cell_tower * towers, size_t count) {
+    if (count < 2) {
+        return count;
+    }
+
+    lbs_sort_entry * e = malloc(count * sizeof(lbs_sort_entry));
+
+    if (e == NULL) {
+        //no room for the order: sort anyway, and which of two equal keys survives is arbitrary
+        qsort(towers, count, sizeof(cell_tower), compare_lbs_key);
+
+    } else {
+        for (size_t n = 0; n < count; n++) {
+            e[n].tower = towers[n];
+            e[n].order = (uint32_t)n;
+        }
+
+        qsort(e, count, sizeof(lbs_sort_entry), compare_lbs_sort_entry);
+
+        for (size_t n = 0; n < count; n++) {
+            towers[n] = e[n].tower;
+        }
+
+        free(e);
+    }
+
+    size_t out = 0;
+
+    for (size_t n = 0; n < count; n++) {
+        if (out > 0 && memcmp(&towers[out - 1], &towers[n], LBS_KEY) == 0) {
+            towers[out - 1] = towers[n];
+
+        } else {
+            towers[out++] = towers[n];
+        }
+    }
+
+    return out;
+}
+
+/*
+ * Merge two sorted, duplicate free arrays into a new one; where both hold a key, b's tower is
+ * kept. Returns NULL (and leaves *out_count alone) if there is no memory for it.
+ */
+static cell_tower * lbs_merge(const cell_tower * a, size_t a_count, const cell_tower * b, size_t b_count, size_t * out_count) {
+    cell_tower * out = malloc((a_count + b_count ? a_count + b_count : 1) * sizeof(cell_tower));
+
+    if (out == NULL) {
+        return NULL;
+    }
+
+    size_t i = 0, j = 0, n = 0;
+
+    while (i < a_count || j < b_count) {
+        int c = (i == a_count) ? 1 : (j == b_count) ? -1 : memcmp(&a[i], &b[j], LBS_KEY);
+
+        if (c < 0) {
+            out[n++] = a[i++];
+
+        } else {
+            if (c == 0) {
+                i++;
+            }
+
+            out[n++] = b[j++];
+        }
+    }
+
+    *out_count = n;
+    return out;
+}
+
+/*
+ * Write base and extra (both sorted, extra winning on equal keys) to `file` in the cell.db
+ * format: a temporary file renamed over the old one - see atomic_file_begin(). Base is the
+ * mapped cell.db (or empty), copied in runs straight from the mapping rather than record by
+ * record. Returns false and leaves `file` untouched on any failure.
+ */
+/*
+ * Write towers[0..count) of a read-only file mapping, a few megabytes at a time, letting go of
+ * each stretch once it is written. A fold reads all of cell.db through the mapping; without
+ * this every page of it stays mapped into the worker afterwards (RSS 1.4 GB again, if only
+ * page cache). MADV_DONTNEED on a shared file mapping drops only this process's page table
+ * entries - the file and the page cache are untouched - so it is never used on heap memory.
  */
-static bool lbs_reserve(cell_db * database, size_t want) {
-    if (want <= database->tower_memory_size && database->tower_buffer) {
-        return true;
+static void lbs_write_mapped(FILE * fp, const cell_tower * towers, size_t count) {
+    const size_t chunk = 65536;
+    uintptr_t page = (uintptr_t)sysconf(_SC_PAGESIZE);
+
+    for (size_t done = 0; done < count; done += chunk) {
+        size_t n = count - done < chunk ? count - done : chunk;
+        fwrite(towers + done, sizeof(cell_tower), n, fp);
+        uintptr_t from = ((uintptr_t)(towers + done)) & ~(page - 1);
+        uintptr_t to = ((uintptr_t)(towers + done + n)) & ~(page - 1);
+
+        if (to > from) {
+            madvise((void *)from, to - from, MADV_DONTNEED);
+        }
     }
+}
+
+static bool lbs_write_merged(const char * file, const cell_tower * base, size_t base_count,
+                             const cell_tower * extra, size_t extra_count) {
+    char tmp[FILENAME_MAX];
+    FILE * fp = atomic_file_begin(file, tmp, sizeof(tmp));
 
-    size_t size = database->tower_memory_size < 5 ? 5 : database->tower_memory_size;
+    if (NULL == fp) {
+        fprintf(stdout, "Failed to write LBS database: %s: %s\n", file, strerror(errno));
+        return false;
+    }
 
-    //grow by a fifth for a merge; a load that needs far more gets exactly what it needs
-    size_t next = size + size / 5;
-    size = next < want ? want : next;
+    uint64_t count = 0;
+    fwrite(&count, sizeof(count), 1, fp);
+    size_t at = 0;
+
+    for (size_t j = 0; j < extra_count; j++) {
+        //galloping rather than a plain binary search over the rest of the file, so the pages
+        //read are the ones just ahead of what has been written - not ~20 scattered over all
+        //of it for every extra tower, which kept hundreds of megabytes mapped in
+        size_t step = 1;
+
+        while (at + step < base_count && memcmp(&base[at + step - 1], &extra[j], LBS_KEY) < 0) {
+            step *= 2;
+        }
+
+        size_t span = (at + step < base_count ? step : base_count - at);
+        size_t skip = step / 2 > span ? span : step / 2;
+        size_t upto = at + skip + lbs_lower_bound(base + at + skip, span - skip, &extra[j], LBS_KEY);
+
+        if (upto > at) {
+            lbs_write_mapped(fp, base + at, upto - at);
+            count += upto - at;
+        }
+
+        at = upto;
+
+        if (at < base_count && memcmp(&base[at], &extra[j], LBS_KEY) == 0) {
+            at++;
+        }
+
+        fwrite(&extra[j], sizeof(cell_tower), 1, fp);
+        count++;
+    }
+
+    if (at < base_count) {
+        lbs_write_mapped(fp, base + at, base_count - at);
+        count += base_count - at;
+    }
 
-    cell_tower * grown = realloc(database->tower_buffer, sizeof(cell_tower) * size);
+    //the count goes in last, so a file cut short by a full disk says so rather than claiming
+    //towers it does not have (the loader believes the size of the file over the count anyway)
+    if (fseek(fp, 0, SEEK_SET) != 0 || fwrite(&count, sizeof(count), 1, fp) != 1) {
+        fprintf(stdout, "Failed to write LBS database: %s: %s\n", file, strerror(errno));
+    }
 
-    if (grown == NULL) {
+    if (!atomic_file_commit(fp, tmp, file)) {
+        fprintf(stdout, "Failed to write LBS database: %s: %s\n", file, strerror(errno));
         return false;
     }
 
-    database->tower_buffer = grown;
-    database->tower_memory_size = size;
     return true;
 }
 
-void lbs_sort(cell_db * database) {
-    database->tower_count = quick_sort(database->tower_buffer, database->tower_count, sizeof(cell_tower), compare_lbs, 0);
+/*
+ * Open a file in the cell.db format and work out how many whole towers it really holds: the
+ * count in its header, believed only as far as the size of the file backs it up. Returns the
+ * descriptor, or -1 if there is no usable file.
+ */
+static int lbs_open_db(const char * file, size_t * towers, size_t * file_size) {
+    int fd = devfile_open(file, O_RDONLY, 0);
+    struct stat st;
+    uint64_t count;
+
+    if (fd < 0) {
+        return -1;
+    }
+
+    if (fstat(fd, &st) != 0 || (size_t)st.st_size < LBS_HEADER ||
+            pread(fd, &count, sizeof(count), 0) != (ssize_t)sizeof(count)) {
+        close(fd);
+        return -1;
+    }
+
+    size_t fits = ((size_t)st.st_size - LBS_HEADER) / sizeof(cell_tower);
+
+    if (count > fits) {
+        fprintf(stdout, "   %s claims %lu towers but only holds %lu, using the smaller\n",
+                file, (unsigned long)count, (unsigned long)fits);
+        count = fits;
+    }
+
+    *towers = (size_t)count;
+    *file_size = (size_t)st.st_size;
+    return fd;
+}
+
+static void lbs_unmap(cell_db * database) {
+    if (database->map) {
+        munmap((void *)database->map, database->map_len);
+    }
+
+    database->map = NULL;
+    database->map_len = 0;
+    database->towers = NULL;
+    database->tower_count = 0;
+}
+
+/*
+ * Map cell.db read-only in place of whatever was mapped before. It used to be fread() into one
+ * malloc'd block - 1.4 GB of private anonymous memory that, once the worker had been idle for
+ * a while, went to swap and had to come back from swap a page at a time. Mapped, the same
+ * pages are clean page cache: the kernel drops them when it needs the memory and reads them
+ * back from the file, and the worker's anonymous footprint does not include them at all.
+ *
+ * Lookups are binary searches - about 26 probes, the first ones always in the same few pages -
+ * so the file is advised as random access and only the pages actually probed are read in.
+ */
+static void lbs_map(cell_db * database, const char * file) {
+    size_t count = 0, size = 0;
+    int fd = lbs_open_db(file, &count, &size);
+
+    lbs_unmap(database);
+
+    if (fd < 0) {
+        fprintf(stdout, "   no LBS database at %s, starting empty.\n", file);
+        return;
+    }
+
+    if (count == 0) {
+        close(fd);
+        return;
+    }
+
+    void * map = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
+    close(fd);
+
+    if (map == MAP_FAILED) {
+        fprintf(stdout, "   could not map %s: %s, continuing without it\n", file, strerror(errno));
+        return;
+    }
+
+    madvise(map, size, MADV_RANDOM);
+    database->map = map;
+    database->map_len = size;
+    database->towers = (const cell_tower *)((const uint8_t *)map + LBS_HEADER);
+    database->tower_count = count;
+}
+
+//read a whole cell.db format file into the heap - used for the learned file only, which is small
+static cell_tower * lbs_read_small(const char * file, size_t * count) {
+    size_t size = 0;
+    int fd = lbs_open_db(file, count, &size);
+
+    if (fd < 0) {
+        *count = 0;
+        return NULL;
+    }
+
+    cell_tower * towers = *count ? malloc(*count * sizeof(cell_tower)) : NULL;
+    size_t bytes = *count * sizeof(cell_tower);
+
+    if (*count && (towers == NULL || pread(fd, towers, bytes, LBS_HEADER) != (ssize_t)bytes)) {
+        fprintf(stdout, "   could not read %s, ignoring it\n", file);
+        free(towers);
+        towers = NULL;
+        *count = 0;
+    }
+
+    close(fd);
+    return towers;
 }
 
-//create mutex and read from file
 void lbs_initialise_database(cell_db * database) {
     memset(database, 0, sizeof(cell_db));
-    database->tower_count = 0;
-    database->tower_buffer = malloc(sizeof(cell_tower) * 1048576);
-    database->current_cache = malloc(sizeof(cell_tower) * 10240);
-    database->tower_memory_size = 1048576;
-    database->cache_memory_size = 10240;
+    database->current_cache = malloc(sizeof(cell_tower) * 1024);
+    database->cache_memory_size = database->current_cache ? 1024 : 0;
     database->cache_size = 0;
     database->cache_age = time(0);
     pthread_mutexattr_t attr;
@@ -79,112 +366,159 @@ void lbs_initialise_database(cell_db * database) {
     pthread_mutex_init(&database->mutex, &attr);
 }
 
+/*
+ * Parse an OpenCelliD / Mozilla Location Service export (radio,mcc,net,area,cell,unit,lon,lat,
+ * range,...) and add it to the learned towers, which init_lbs() then folds into cell.db. The
+ * export is held in the heap only while it is being folded in.
+ */
 void read_lbs_file(cell_db * database, char * file) {
     char buffer[BUF_SIZE];
     FILE * fp = devfile_fopen(file, "r");
     fprintf(stdout, "Reading file with LBS data: %s \n", file);
 
-    //if there's no commands file, well there is nothing to do
     if (NULL == fp) {
         fprintf(stdout, "Failed to open file.");
         return;
     }
 
     size_t line_count = 0;
-    fprintf(stdout, "Computing size...\n");
 
     while (fgets(buffer, BUF_SIZE - 1, fp) ) {
         if (strlen(buffer) > 2 && memcmp(buffer, "radio", 5) != 0) {
             line_count++;
-            //we have a line
         }
     }
 
     fprintf(stdout, "Number of entries: %zu\n", line_count);
-    size_t tower_idx =   database->tower_count;
+    cell_tower * csv = malloc((line_count ? line_count : 1) * sizeof(cell_tower));
 
-    if (!lbs_reserve(database, database->tower_count + line_count)) {
+    if (csv == NULL) {
         fprintf(stdout, "Could not allocate room for %zu more towers, skipping %s\n", line_count, file);
         fclose(fp);
         return;
     }
 
+    size_t tower_idx = 0;
     fseek(fp, 0, SEEK_SET);
 
-    while (tower_idx < database->tower_memory_size && fgets(buffer, BUF_SIZE - 1, fp) ) {
+    while (tower_idx < line_count && fgets(buffer, BUF_SIZE - 1, fp) ) {
         if (strlen(buffer) > 2 && memcmp(buffer, "radio", 5) != 0) {
             char * sptrs[11];
 
-            if (split_to(',', buffer, strlen(buffer), (unsigned char * *)&sptrs, 11) >= 10) {
-                memset(& database->tower_buffer[tower_idx], 0, sizeof(cell_tower));
-                database->tower_buffer[tower_idx].mcc = parse_int(sptrs[1], 5); //64000
-                database->tower_buffer[tower_idx].mnc = parse_int(sptrs[2], 3);
-                database->tower_buffer[tower_idx].lac = parse_int(sptrs[3], 5);
-                database->tower_buffer[tower_idx].cell_id = parse_int(sptrs[4], 9);
-                database->tower_buffer[tower_idx].location.lat = parse_float(sptrs[7]);
-                database->tower_buffer[tower_idx].location.lng = parse_float(sptrs[6]);
-                database->tower_buffer[tower_idx].location.valid = true;
-                database->tower_buffer[tower_idx].location.radius = parse_float(sptrs[8]);
-                database->tower_buffer[tower_idx].location.last_tried = 0;
+            if (split_to(',', (unsigned char *)buffer, strlen(buffer), (unsigned char * *)&sptrs, 11) >= 10) {
+                cell_tower * t = &csv[tower_idx];
+                memset(t, 0, sizeof(cell_tower));
+                t->mcc = parse_int(sptrs[1], 5); //64000
+                t->mnc = parse_int(sptrs[2], 3);
+                t->lac = parse_int(sptrs[3], 5);
+                t->cell_id = parse_int(sptrs[4], 9);
+                t->location.lat = parse_float(sptrs[7]);
+                t->location.lng = parse_float(sptrs[6]);
+                t->location.valid = true;
+                t->location.radius = parse_float(sptrs[8]);
+                t->location.last_tried = 0;
                 tower_idx++;
             }
         }
     }
 
-    //only the lines that parsed (and were still there on the second pass) are towers
-    database->tower_count = tower_idx;
-    fprintf(stdout, "Read all towers: %zu\n", tower_idx);
-    lbs_sort(database);
-    fprintf(stdout, "size in memory:%lu\n", database->tower_count * sizeof(cell_tower));
     fclose(fp);
-}
+    fprintf(stdout, "Read all towers: %zu\n", tower_idx);
+    tower_idx = lbs_sort_unique(csv, tower_idx);
 
+    //what the service told us is newer than any export, so where both have a tower it wins
+    size_t merged_count = 0;
+    cell_tower * merged = lbs_merge(csv, tower_idx, database->learned, database->learned_count, &merged_count);
+    free(csv);
 
-//written to a temporary file and renamed over the old one - see atomic_file_begin()
-void lbs_database_to_file(cell_db * database, char * file) {
-    char tmp[FILENAME_MAX];
-    FILE * fp = atomic_file_begin(file, tmp, sizeof(tmp));
+    if (merged == NULL) {
+        fprintf(stdout, "Could not allocate room for %zu more towers, skipping %s\n", tower_idx, file);
+        return;
+    }
 
-    if (NULL == fp) {
-        fprintf(stdout, "Failed to write LBS database: %s: %s\n", file, strerror(errno));
+    free(database->learned);
+    database->learned = merged;
+    database->learned_count = merged_count;
+}
+
+/*
+ * Fold the learned towers into cell.db (written to `file`) and map the result. Startup only:
+ * it reads all of cell.db and writes all of it again.
+ */
+void lbs_database_to_file(cell_db * database, char * file) {
+    if (!lbs_write_merged(file, database->towers, database->tower_count, database->learned, database->learned_count)) {
         return;
     }
 
-    size_t count = database->tower_count;
-    fwrite(&count, sizeof(count), 1, fp);
+    lbs_map(database, file);
 
-    if (count) {
-        fwrite(database->tower_buffer, count * sizeof(cell_tower), 1, fp);
+    //the new file has just been written through the page cache; let it go rather than evict
+    //everything else to keep 1.4 GB that is read back a few pages at a time
+    int fd = devfile_open(file, O_RDONLY, 0);
+
+    if (fd >= 0) {
+        posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
+        close(fd);
     }
 
-    if (!atomic_file_commit(fp, tmp, file)) {
-        fprintf(stdout, "Failed to write LBS database: %s: %s\n", file, strerror(errno));
+    if (strcmp(file, CELLDB_FILE) == 0) {
+        free(database->learned);
+        database->learned = NULL;
+        database->learned_count = 0;
+
+        if (unlink(CELLDB_LEARNED_FILE) != 0 && errno != ENOENT) {
+            //left behind it is only towers cell.db now holds; it is folded in again next time
+            fprintf(stdout, "   could not remove %s: %s\n", CELLDB_LEARNED_FILE, strerror(errno));
+        }
     }
 }
 
-void lbs_cache_to_database(cell_db * database) {
-    fprintf(stdout, "Merging cache to LBS database and writing to file.\n");
+/*
+ * Every CACHE_SAVE_TIME: sort what the service answered since the last save into the learned
+ * towers and write those (only those - a few hundred kilobytes at most, see LBS_FOLD_MIN) to
+ * CELLDB_LEARNED_FILE. cell.db itself is not touched; it used to be appended to in memory,
+ * re-sorted whole and rewritten whole - 1.4 GB - on every save, all with the lock held.
+ * Called with the mutex held.
+ */
+static void lbs_save_locked(cell_db * database) {
     database->cache_age = time(0);
 
     if (database->cache_size == 0) {
-        fprintf(stdout, "   Nothing to do.. quitting.\n");
         return;
     }
 
-    size_t tower_idx =   database->tower_count;
+    fprintf(stdout, "Saving %zu new towers to %s.\n", database->cache_size, CELLDB_LEARNED_FILE);
+    size_t fresh = lbs_sort_unique(database->current_cache, database->cache_size);
+    size_t merged_count = 0;
+    cell_tower * merged = lbs_merge(database->learned, database->learned_count,
+                                    database->current_cache, fresh, &merged_count);
 
-    //the realloc result used to be stored unchecked over the only pointer to the buffer
-    if (!lbs_reserve(database, database->tower_count + database->cache_size)) {
-        fprintf(stdout, "   could not grow the LBS database, keeping the cache for the next save\n");
+    if (merged == NULL) {
+        fprintf(stdout, "   could not grow the learned towers, keeping the cache for the next save\n");
+        database->cache_size = fresh;
         return;
     }
 
-    database->tower_count += database->cache_size;
-    memcpy(database->tower_buffer + tower_idx, database->current_cache, database->cache_size * sizeof(cell_tower));
+    free(database->learned);
+    database->learned = merged;
+    database->learned_count = merged_count;
     database->cache_size = 0;
-    lbs_sort(database);
-    lbs_database_to_file(database, CELLDB_FILE);
-    fprintf(stdout, "Done writing LBS database.\n");
+
+    //a failure is logged and costs nothing but the file: the towers are in memory either way
+    //and the whole set is written again at the next save
+    lbs_write_merged(CELLDB_LEARNED_FILE, NULL, 0, database->learned, database->learned_count);
+}
+
+static cell_db lbs_db;
+
+static pthread_mutex_t * lbs_mutex(void) {
+    return &lbs_db.mutex;
+}
+
+void lbs_cache_to_database(cell_db * database) {
+    pthread_mutex_lock(&database->mutex);
+    lbs_save_locked(database);
+    pthread_mutex_unlock(&database->mutex);
 }
 
 void lbs_to_cache(cell_db * database, cell_tower * tower) {
@@ -205,97 +539,36 @@ void lbs_to_cache(cell_db * database, cell_tower * tower) {
     database->cache_size++;
 }
 
-void lbs_database_from_file(cell_db * database, char * file) {
-    fprintf(stdout, "Loading LBS cache.\n");
-    FILE * fp = devfile_fopen(file, "rb");
-
-    if (fp == NULL) {
-        fprintf(stdout, "   failed to open cache file.\n");
-        return;
-    }
-
-    if (fread(&database->tower_count, sizeof(database->tower_count), 1, fp) != 1) {
-        fprintf(stdout, "   cache file has no count in it, starting empty.\n");
-        database->tower_count = 0;
-        fclose(fp);
-        return;
-    }
-
-    /*
-     * The count comes out of the file, so believe it only as far as the file can back it up.
-     * A truncated or half written cache otherwise asks for an allocation of whatever the
-     * first few bytes happened to be.
-     */
-    long here = ftell(fp);
-
-    if (fseek(fp, 0, SEEK_END) == 0) {
-        long size = ftell(fp);
-        fseek(fp, here, SEEK_SET);
-
-        if (size > here) {
-            size_t fits = ((size_t)(size - here)) / sizeof(cell_tower);
-
-            if (database->tower_count > fits) {
-                fprintf(stdout, "   cache claims %lu towers but only holds %lu, using the smaller\n",
-                        (unsigned long)database->tower_count, (unsigned long)fits);
-                database->tower_count = fits;
-            }
-        }
-    }
-
-    /*
-     * And check the allocation. This cache runs to well over a gigabyte, the machine is set
-     * to vm.overcommit_memory=2 so a large request is refused outright rather than handed
-     * back lazily, and the result went straight into fread() - so on a machine short of
-     * memory the server did not report a problem, it segfaulted here on startup. Losing the
-     * cache costs a lookup; crashing costs every device on the server.
-     */
-    if (!lbs_reserve(database, database->tower_count)) {
-        fprintf(stdout, "   could not allocate %lu bytes for the LBS cache, continuing without it\n",
-                (unsigned long)(database->tower_count * sizeof(cell_tower)));
-        database->tower_count = 0;
-        fclose(fp);
-        return;
-    }
-
-    if (database->tower_count &&
-            fread(database->tower_buffer, database->tower_count * sizeof(cell_tower), 1, fp) != 1) {
-        fprintf(stdout, "   cache file is shorter than it claims, starting empty.\n");
-        database->tower_count = 0;
-    }
-
-    fclose(fp);
-    fprintf(stdout, "   done.\n");
-}
-
-
-
-static cell_db lbs_db;
-
-//cell_db is packed, so taking the mutex's address warns; done in one place rather than at
-//every lock and unlock
-static pthread_mutex_t * lbs_mutex(void) {
-    return &lbs_db.mutex;
-}
-
 void init_lbs() {
     lbs_initialise_database(&lbs_db);
-    lbs_database_from_file(&lbs_db, CELLDB_FILE);
+    fprintf(stdout, "Loading LBS cache.\n");
+    lbs_map(&lbs_db, CELLDB_FILE);
+    lbs_db.learned = lbs_read_small(CELLDB_LEARNED_FILE, &lbs_db.learned_count);
+    lbs_db.learned_count = lbs_sort_unique(lbs_db.learned, lbs_db.learned_count);
+    bool imported = false;
 
     if (file_exists(OPENCELLID_FILE)) {
-        read_lbs_file(&lbs_db, "opencellid.csv");
-        lbs_database_to_file(&lbs_db, CELLDB_FILE);
+        read_lbs_file(&lbs_db, OPENCELLID_FILE);
+        imported = true;
     }
 
     if (file_exists(MOZCELLID_FILE)) {
-        read_lbs_file(&lbs_db, "mozilla.csv");
+        read_lbs_file(&lbs_db, MOZCELLID_FILE);
+        imported = true;
+    }
+
+    if (imported || lbs_db.learned_count >= LBS_FOLD_MIN) {
+        fprintf(stdout, "   folding %zu towers into %s\n", lbs_db.learned_count, CELLDB_FILE);
         lbs_database_to_file(&lbs_db, CELLDB_FILE);
     }
+
+    fprintf(stdout, "   done: %zu towers mapped, %zu learned.\n", lbs_db.tower_count, lbs_db.learned_count);
 }
 
-location_result lbs_in_cache(cell_tower * to_find) {
+//called with the mutex held
+static location_result lbs_in_cache(cell_tower * to_find) {
     for (size_t n = 0; n < lbs_db.cache_size; n++) {
-        if (memcmp(&lbs_db.current_cache[n], to_find, 9) == 0) {
+        if (memcmp(&lbs_db.current_cache[n], to_find, LBS_KEY) == 0) {
             return  lbs_db.current_cache[n].location;
         }
     }
@@ -305,19 +578,23 @@ location_result lbs_in_cache(cell_tower * to_find) {
     return failure;
 }
 
-location_result lbs_in_db(cell_tower * to_find) {
-    void * ret = lbs_db.tower_count == 0 ? 0 : binary_search(lbs_db.tower_buffer, (lbs_db.tower_buffer + lbs_db.tower_count),  to_find,  sizeof(cell_tower), compare_lbs) ;
+//called with the mutex held; the learned copy of a tower is newer than cell.db's
+static location_result lbs_in_db(cell_tower * to_find) {
+    const cell_tower * found = lbs_find(lbs_db.learned, lbs_db.learned_count, to_find);
 
-    if (NULL == ret) {
+    if (found == NULL) {
+        found = lbs_find(lbs_db.towers, lbs_db.tower_count, to_find);
+    }
+
+    if (NULL == found) {
         location_result failure = {0, 0, 0, 0};
         failure.valid = false;
-        return failure;;
+        return failure;
     }
 
-    return ((cell_tower *)ret)->location;
+    return found->location;
 }
 
-
 /*
  * The negative cache - see GEO_NEGATIVE_CACHE_SEC in config.h. Direct mapped on a hash of the
  * tower or the scan: a fixed table, so it costs the same memory however many invented towers
@@ -360,45 +637,37 @@ void geo_memo_put(uint64_t key, location_result result) {
     pthread_mutex_unlock(&geo_memo_lock);
 }
 
-//the five byte prefix (mcc, lac) every tower in one area shares, with the guess built from the
-//nearest of them to where the device last was. Called with the mutex held.
-static location_result lbs_nearest_known(cell_tower * to_find, float last_lat, float last_lng) {
-    location_result ret = {0, 0, 0, 0};
-    ret.valid = false;
-    //larger than any distance on earth, so the first candidate always replaces it. it used
-    //to be compared against a value truncated to a byte, which could never exceed 255 and
-    //made the sentinel meaningless.
-    double closest_match = DBL_MAX;
-    cell_tower * current_tower =   lbs_db.tower_count == 0 ? 0 :  binary_search(lbs_db.tower_buffer, (lbs_db.tower_buffer + lbs_db.tower_count),  to_find,  sizeof(cell_tower), compare_lbs_partial) ;
-
-    //the first five bytes are a prefix of the nine the array is sorted on, so every
-    //tower sharing them sits in one contiguous block - but the search lands somewhere
-    //inside that block rather than at its start. walk back to the first entry, or the
-    //scan below only ever sees the tail of the candidates.
-    while (current_tower != 0 && current_tower > lbs_db.tower_buffer
-            && memcmp(current_tower - 1, to_find, 5) == 0) {
-        current_tower--;
-    }
-
-    for (; current_tower != 0 && (current_tower < (lbs_db.tower_buffer + lbs_db.tower_count)); current_tower++) {
-        if (memcmp(current_tower, to_find, 5) != 0) {
-            break;
-        }
 
+//the nearest to (last_lat, last_lng) of the towers in towers[0..count) sharing to_find's five
+//byte area prefix (mcc, lac, mnc) - one contiguous block of the sorted array
+static void lbs_nearest_in(const cell_tower * towers, size_t count, cell_tower * to_find,
+                           float last_lat, float last_lng, double * closest, location_result * ret) {
+    for (size_t at = lbs_lower_bound(towers, count, to_find, LBS_AREA);
+            at < count && memcmp(&towers[at], to_find, LBS_AREA) == 0; at++) {
         //this is a distance in kilometres and needs to stay one. truncating it to
         //a uint8_t wrapped it modulo 256, so a tower 256km away scored a perfect
         //zero and beat every genuinely close one - which is what threw fixes
         //hundreds of kilometres across the map.
-        double diff = haversineDistance(current_tower->location.lat, current_tower->location.lng, last_lat, last_lng);
+        double diff = haversineDistance(towers[at].location.lat, towers[at].location.lng, last_lat, last_lng);
 
-        if (diff < closest_match) {
-            closest_match = diff;
-            ret = current_tower->location;
-            ret.last_tried = time(0);
-            ret.valid = true;
+        if (diff < *closest) {
+            *closest = diff;
+            *ret = towers[at].location;
+            ret->last_tried = time(0);
+            ret->valid = true;
         }
     }
+}
 
+//the guess built from the nearest known tower in the same area to where the device last was.
+//Called with the mutex held.
+static location_result lbs_nearest_known(cell_tower * to_find, float last_lat, float last_lng) {
+    location_result ret = {0, 0, 0, 0};
+    ret.valid = false;
+    //larger than any distance on earth, so the first candidate always replaces it
+    double closest_match = DBL_MAX;
+    lbs_nearest_in(lbs_db.towers, lbs_db.tower_count, to_find, last_lat, last_lng, &closest_match, &ret);
+    lbs_nearest_in(lbs_db.learned, lbs_db.learned_count, to_find, last_lat, last_lng, &closest_match, &ret);
     return ret;
 }
 
@@ -414,12 +683,12 @@ static location_result lbs_nearest_known(cell_tower * to_find, float last_lat, f
  */
 location_result lbs_lookup(cell_tower * to_find, float last_lat, float last_lng) {
     //the key is the nine bytes the database sorts on: mcc, lac, mnc, cell id
-    uint64_t memo_key = crc64(0x4c4253, (const unsigned char *)to_find, 9);
+    uint64_t memo_key = crc64(0x4c4253, (const unsigned char *)to_find, LBS_KEY);
     cell_tower query = *to_find;
     pthread_mutex_lock(lbs_mutex());
 
     if ((time(0) - lbs_db.cache_age) > CACHE_SAVE_TIME) {
-        lbs_cache_to_database(&lbs_db);
+        lbs_save_locked(&lbs_db);
     }
 
     location_result ret =   lbs_in_db(to_find);
diff --git a/device_server/lbs_lookup.h b/device_server/lbs_lookup.h
index 857f9af..acd66c6 100644
--- a/device_server/lbs_lookup.h
+++ b/device_server/lbs_lookup.h
@@ -10,13 +10,27 @@
 #include "web_geolocate.h"
 #include <stdbool.h>
 
-typedef struct __attribute__((packed)) {
-    cell_tower * tower_buffer ;
+/*
+ * The cell tower database. Three sorted-or-not layers, newest last:
+ *
+ *  - towers: cell.db, mapped read-only. A uint64 count followed by that many packed
+ *    cell_tower records, sorted ascending by the first nine bytes (memcmp). File backed and
+ *    clean, so the kernel can drop and re-read its pages; none of it is anonymous memory.
+ *  - learned: towers the positioning service has answered for since cell.db was written,
+ *    sorted, in the heap and in CELLDB_LEARNED_FILE (same format). Small.
+ *  - current_cache: answers since the last save, unsorted, merged into learned every
+ *    CACHE_SAVE_TIME.
+ */
+typedef struct {
+    const uint8_t * map;
+    size_t map_len;
+    const cell_tower * towers;
+    size_t tower_count;
+    cell_tower * learned;
+    size_t learned_count;
     cell_tower * current_cache ;
     size_t cache_size;
-    size_t tower_memory_size;
     size_t cache_memory_size;
-    size_t tower_count;
     time_t cache_age;
     pthread_mutex_t mutex;
 }
diff --git a/device_server/test/Makefile b/device_server/test/Makefile
index 439c7ce..978cf11 100644
--- a/device_server/test/Makefile
+++ b/device_server/test/Makefile
@@ -46,3 +46,11 @@ lbs: test_lbs_lookup.o ../sort.o ../search.o ../web_geolocate.o ../wifi_lookup.o
 
 style:
 	astyle --style=java --break-blocks=all --pad-oper --pad-oper --pad-comma --pad-header --indent-switches --delete-empty-lines -k2 -xf --add-braces -Q  -n --recursive "*.c" "*.h"
+
+# cell.db lookups against a throwaway database in a scratch directory - no network, no /var/gps
+lbs-mmap:
+	rm -rf lbs-mmap.d && mkdir lbs-mmap.d
+	$(CC) -g -O1 -fsanitize=address,undefined -std=gnu99 -iquote .. -DCELLDB_FILE='"cell.db"' \
+		test_lbs_mmap.c ../util.c ../string.c ../sort.c ../search.c ../crc64.c \
+		-lm -lpthread -Wl,--allow-multiple-definition -o lbs-mmap.d/test_lbs_mmap
+	cd lbs-mmap.d && ./test_lbs_mmap >log.txt && tail -1 log.txt
diff --git a/device_server/test/test_lbs_mmap.c b/device_server/test/test_lbs_mmap.c
new file mode 100644
index 0000000..a88706d
--- /dev/null
+++ b/device_server/test/test_lbs_mmap.c
@@ -0,0 +1,118 @@
+/* unit tests for lbs_lookup.c (cell.db mapped read-only, learned towers, folding).
+ * "make lbs-mmap" builds and runs it in a scratch directory; the positioning service is stubbed. */
+#include "../lbs_lookup.c"
+#include <assert.h>
+#include <fcntl.h>
+#include <unistd.h>
+static int answer = 0; static long calls = 0;
+location_result geolocate_tower(cell_tower * t) { location_result r = {0}; calls++;
+  if (answer) { r.lat = 1.0f + t->cell_id; r.lng = 2; r.radius = 3; r.valid = true; } return r; }
+bool geo_lookup_allowed(void) { return true; }
+bool geo_lookup_was_limited(void) { return false; }
+static int fails = 0;
+#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)
+
+static cell_tower T(uint16_t mcc, uint16_t lac, uint8_t mnc, uint32_t cid, float lat, float lng) {
+  cell_tower t; memset(&t, 0, sizeof t); t.mcc = mcc; t.lac = lac; t.mnc = mnc; t.cell_id = cid;
+  t.location.lat = lat; t.location.lng = lng; t.location.radius = 100; t.location.valid = true; return t; }
+static int cmp9(const void*a,const void*b){return memcmp(a,b,9);}
+static void write_db(const char*path, cell_tower*t, size_t n, uint64_t claim, size_t extra_bytes){
+  qsort(t,n,sizeof *t,cmp9); FILE*f=fopen(path,"wb"); fwrite(&claim,8,1,f); fwrite(t,sizeof *t,n,f);
+  for(size_t i=0;i<extra_bytes;i++) fputc(0,f); fclose(f); }
+static void restart(void){ lbs_unmap(&lbs_db); free(lbs_db.learned); free(lbs_db.current_cache); init_lbs(); }
+static location_result look(cell_tower t){ t.location.valid=false; return lbs_lookup(&t, 0, 0); }
+static size_t file_check(const char*path, uint64_t*hdr){ /* returns records, -1 if unsorted/dup */
+  FILE*f=fopen(path,"rb"); if(!f) return (size_t)-2; fread(hdr,8,1,f); cell_tower a,b; size_t n=0;
+  while(fread(&b,sizeof b,1,f)==1){ if(n && memcmp(&a,&b,9)>=0){fclose(f);return (size_t)-1;} a=b; n++; } fclose(f); return n; }
+
+int main(void){
+  unlink(CELLDB_FILE); unlink(CELLDB_LEARNED_FILE); unlink(OPENCELLID_FILE);
+  /* 1. no database at all */
+  init_lbs(); CHECK(lbs_db.tower_count==0 && lbs_db.map==NULL);
+  long c0=calls; CHECK(!look(T(1,1,1,1,0,0)).valid); CHECK(calls==c0+1);
+
+  /* 2. a database: every key found by the exact path, and nothing else */
+  enum { N = 3000 }; static cell_tower db[N]; size_t n=0;
+  for(uint16_t mcc=200; mcc<203; mcc++) for(uint16_t lac=1; lac<=10; lac++) for(uint32_t cid=1; cid<=100; cid++)
+     db[n++]=T(mcc, lac*300, 1, cid*7, (float)lac, (float)cid/10);
+  write_db(CELLDB_FILE, db, n, n, 0); restart();
+  CHECK(lbs_db.tower_count==N);
+  size_t ok=0; c0=calls;
+  for(size_t i=0;i<n;i++){ location_result r=look(db[i]); ok += r.valid && r.lat==db[i].location.lat && r.lng==db[i].location.lng && r.last_tried==0; }
+  CHECK(ok==N); CHECK(calls==c0);
+  /* unknown tower in a known area: service asked, then the nearest tower of that area answers */
+  c0=calls; cell_tower u=T(201, 5*300, 1, 3, 0,0); /* cid 3 is not a multiple of 7 */
+  location_result r=lbs_lookup(&u, 5.0f, 0.0f);
+  CHECK(calls==c0+1); CHECK(r.valid && r.last_tried>0 && r.lat==5.0f && r.lng==0.1f); /* key cid 7 (lng .1) is nearest to (5,0) */
+  /* unknown area: no answer at all */
+  CHECK(!look(T(999, 1, 1, 1, 0,0)).valid);
+  /* first and last keys, and keys just outside them */
+  CHECK(look(db[0]).valid && look(db[n-1]).valid);
+  CHECK(!lbs_in_db(&(cell_tower){0}).valid);
+  cell_tower hi; memset(&hi,0xff,sizeof hi); CHECK(!lbs_in_db(&hi).valid);
+
+  /* 3. a truncated file: the header claims more than is there */
+  write_db(CELLDB_FILE, db, 1000, 5000, 17); restart();
+  CHECK(lbs_db.tower_count==1000);
+  write_db(CELLDB_FILE, db, n, n, 0); restart(); CHECK(lbs_db.tower_count==N);
+
+  /* 4. towers the service answers are cached, saved to the learned file, and survive a restart */
+  answer=1; c0=calls;
+  for(uint32_t i=0;i<50;i++){ cell_tower t=T(300, 1, 2, 1000+i, 0,0); CHECK(look(t).valid); }
+  CHECK(calls==c0+50); CHECK(lbs_db.cache_size==50);
+  /* asking again answers from the cache */
+  c0=calls; CHECK(look(T(300,1,2,1010,0,0)).lat==1011.0f); CHECK(calls==c0);
+  lbs_cache_to_database(&lbs_db);
+  CHECK(lbs_db.cache_size==0 && lbs_db.learned_count==50);
+  uint64_t hdr; CHECK(file_check(CELLDB_LEARNED_FILE,&hdr)==50 && hdr==50);
+  CHECK(file_check(CELLDB_FILE,&hdr)==N);            /* cell.db untouched */
+  answer=0; restart(); CHECK(lbs_db.learned_count==50 && lbs_db.tower_count==N);
+  c0=calls; CHECK(look(T(300,1,2,1049,0,0)).lat==1050.0f); CHECK(calls==c0);
+  /* a re-asked tower already in cell.db: the learned copy wins */
+  answer=1; lbs_db.cache_age=0; /* force a save on the next lookup */
+  cell_tower again=db[5];
+  again.location.lat=77; lbs_to_cache(&lbs_db,&again); look(T(1,2,3,4,0,0));
+  CHECK(lbs_db.learned_count==51); CHECK(look(db[5]).lat==77.0f);
+  answer=0;
+
+  /* 5. a csv import folds everything into cell.db and removes the learned file */
+  FILE*f=fopen(OPENCELLID_FILE,"w");
+  fprintf(f,"radio,mcc,net,area,cell,unit,lon,lat,range,samples,changeable\n");
+  fprintf(f,"GSM,400,9,77,123,0,4.5,6.5,250,1,1\n");                       /* new */
+  fprintf(f,"GSM,%u,%u,%u,%u,0,8.0,9.0,250,1,1\n", db[7].mcc, db[7].mnc, db[7].lac, db[7].cell_id); /* overrides cell.db */
+  fprintf(f,"GSM,%u,%u,%u,%u,0,8.0,9.0,250,1,1\n", db[5].mcc, db[5].mnc, db[5].lac, db[5].cell_id); /* loses to learned */
+  fprintf(f,"GSM,300,2,1,1003,0,8.0,9.0,250,1,1\n");                       /* loses to learned */
+  fclose(f);
+  restart();
+  CHECK(lbs_db.learned_count==0); CHECK(access(CELLDB_LEARNED_FILE,F_OK)!=0);
+  CHECK(lbs_db.tower_count==N+50+1);
+  CHECK(file_check(CELLDB_FILE,&hdr)==N+51 && hdr==N+51);
+  r=look(T(400,77,9,123,0,0)); CHECK(r.valid && r.lat==6.5f && r.lng==4.5f);
+  r=look(db[7]); CHECK(r.lat==9.0f && r.lng==8.0f);
+  CHECK(look(db[5]).lat==77.0f); CHECK(look(T(300,1,2,1003,0,0)).lat==1004.0f);
+  ok=0; for(size_t i=0;i<n;i++) ok+=look(db[i]).valid; CHECK(ok==N);
+  unlink(OPENCELLID_FILE);
+  /* and a restart after the fold maps the folded file as is */
+  restart(); CHECK(lbs_db.tower_count==N+51 && lbs_db.learned_count==0);
+
+  /* 7. randomised: fold of a mapped base and a learned set equals a naive merge */
+  for (int round = 0; round < 40; round++) {
+    size_t nb = (size_t)(rand() % 6000), ne = (size_t)(rand() % 700);
+    cell_tower *b = malloc((nb+1)*sizeof *b), *e = malloc((ne+1)*sizeof *e), *want = malloc((nb+ne+1)*sizeof *want);
+    for (size_t i=0;i<nb;i++) b[i]=T(rand()%4, rand()%8, rand()%3, rand()%300, 1, (float)i);
+    for (size_t i=0;i<ne;i++) e[i]=T(rand()%4, rand()%8, rand()%3, rand()%300, 2, (float)i);
+    nb = lbs_sort_unique(b, nb); ne = lbs_sort_unique(e, ne);
+    write_db(CELLDB_FILE, b, nb, nb, 0); unlink(CELLDB_LEARNED_FILE); restart();
+    free(lbs_db.learned); lbs_db.learned = malloc((ne+1)*sizeof *e); memcpy(lbs_db.learned, e, ne*sizeof *e); lbs_db.learned_count = ne;
+    size_t nw = 0; for (size_t i=0;i<nb;i++) want[nw++]=b[i]; for (size_t i=0;i<ne;i++) want[nw++]=e[i];
+    nw = lbs_sort_unique(want, nw);   /* e after b: e wins */
+    lbs_database_to_file(&lbs_db, CELLDB_FILE);
+    CHECK(lbs_db.tower_count == nw && lbs_db.learned_count == 0);
+    CHECK(nw == 0 || memcmp(lbs_db.towers, want, nw*sizeof *want) == 0);
+    for (size_t i=0;i<nw;i++) if (!lbs_find(lbs_db.towers, lbs_db.tower_count, &want[i])) { CHECK(0); break; }
+    free(b); free(e); free(want);
+  }
+
+  /* 6. the mapping is file backed: no anonymous copy of cell.db */
+  CHECK(lbs_db.current_cache && lbs_db.map);
+  printf(fails ? "%d FAILED\n" : "all lbs tests passed\n", fails); return fails != 0; }
diff --git a/var/gps/fetch_celldb b/var/gps/fetch_celldb
index c65986b..e6380c2 100644
--- a/var/gps/fetch_celldb
+++ b/var/gps/fetch_celldb
@@ -1,3 +1,9 @@
 #!/bin/bash
-wget https://coredump.ws/files/cell.db.gz
-zcat cell.db.gz > cell.db
+# jimitrack maps cell.db read-only while it runs; writing over the file in place would make
+# the running daemon fault (SIGBUS) on the pages that changed under it. Build the new file
+# beside it and rename it into place: the daemon keeps its mapping of the old one until it
+# restarts, and picks up the new one then.
+set -e
+wget -O cell.db.gz https://coredump.ws/files/cell.db.gz
+zcat cell.db.gz > cell.db.new
+mv cell.db.new cell.db