- r = mmap_cache_allocate_window(m, &w);
- if (r < 0) {
- munmap(d, wsize);
- return r;
- }
-
- v = m->windows + w;
- v->fd = fd;
- v->ptr = d;
- v->offset = woffset;
- v->size = wsize;
-
- v->n_ref = 0;
- mmap_cache_window_add_lru(m, w);
- mmap_cache_fd_add(m, fd_index, w);
- mmap_cache_context_set(m, context, w);
-
- *ret = (uint8_t*) d + (offset - woffset);
- return 1;
-}
-
-static int fd_cmp(const void *_a, const void *_b) {
- const FileDescriptor *a = _a, *b = _b;
-
- if (a->fd < b->fd)
- return -1;
- if (a->fd > b->fd)
- return 1;
-
- return 0;
-}
-
-static int mmap_cache_peek_fd_index(MMapCache *m, int fd, unsigned *fd_index) {
- FileDescriptor *j;
- unsigned r;
-
- assert(m);
- assert(fd >= 0);
- assert(fd_index);
-
- for (r = 0; r < m->n_fds; r++)
- assert(m->by_fd[r].windows == (unsigned) -1 ||
- m->windows[m->by_fd[r].windows].fd == m->by_fd[r].fd);
-
- j = bsearch(&fd, m->by_fd, m->n_fds, sizeof(FileDescriptor), fd_cmp);
- if (!j)
- return 0;
-
- *fd_index = (unsigned) (j - m->by_fd);
- return 1;
-}
-
-static int mmap_cache_get_fd_index(MMapCache *m, int fd, unsigned *fd_index) {
- FileDescriptor *j;
- int r;
-
- assert(m);
- assert(fd >= 0);
- assert(fd_index);
-
- r = mmap_cache_peek_fd_index(m, fd, fd_index);
- if (r != 0)
- return r;
-
- if (m->n_fds >= m->fds_max) {
- unsigned k;
- FileDescriptor *n;
-
- k = m->n_fds * 2;
- n = realloc(m->by_fd, sizeof(FileDescriptor) * k);
- if (!n)
- return -ENOMEM;
-
- m->fds_max = k;
- m->by_fd = n;
- }
-
- j = m->by_fd + m->n_fds ++;
- j->fd = fd;
- j->windows = (unsigned) -1;
-
- qsort(m->by_fd, m->n_fds, sizeof(FileDescriptor), fd_cmp);
-
- return mmap_cache_peek_fd_index(m, fd, fd_index);
-}
-
-static bool mmap_cache_test_window(
- MMapCache *m,
- unsigned w,
- uint64_t offset,
- uint64_t size) {
- Window *v;
-
- assert(m);
- assert(w < m->n_windows);
- assert(size > 0);
-
- v = m->windows + w;
-
- return offset >= v->offset &&
- offset + size <= v->offset + v->size;
-}
-
-static int mmap_cache_current(
- MMapCache *m,
- int fd,
- unsigned context,
- uint64_t offset,
- uint64_t size,
- void **ret) {
-
- Window *v;
- unsigned w;