setup: merge configuration of repository formats
[git/gitster.git] / packfile.c
blob813584646f762ac096e971b9074c1a7bd0ca74c9
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "list.h"
8 #include "pack.h"
9 #include "repository.h"
10 #include "dir.h"
11 #include "mergesort.h"
12 #include "packfile.h"
13 #include "delta.h"
14 #include "hash-lookup.h"
15 #include "commit.h"
16 #include "object.h"
17 #include "tag.h"
18 #include "trace.h"
19 #include "tree-walk.h"
20 #include "tree.h"
21 #include "object-file.h"
22 #include "object-store-ll.h"
23 #include "midx.h"
24 #include "commit-graph.h"
25 #include "pack-revindex.h"
26 #include "promisor-remote.h"
28 char *odb_pack_name(struct strbuf *buf,
29 const unsigned char *hash,
30 const char *ext)
32 strbuf_reset(buf);
33 strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
34 hash_to_hex(hash), ext);
35 return buf->buf;
38 char *sha1_pack_name(const unsigned char *sha1)
40 static struct strbuf buf = STRBUF_INIT;
41 return odb_pack_name(&buf, sha1, "pack");
44 char *sha1_pack_index_name(const unsigned char *sha1)
46 static struct strbuf buf = STRBUF_INIT;
47 return odb_pack_name(&buf, sha1, "idx");
50 static unsigned int pack_used_ctr;
51 static unsigned int pack_mmap_calls;
52 static unsigned int peak_pack_open_windows;
53 static unsigned int pack_open_windows;
54 static unsigned int pack_open_fds;
55 static unsigned int pack_max_fds;
56 static size_t peak_pack_mapped;
57 static size_t pack_mapped;
59 #define SZ_FMT PRIuMAX
60 static inline uintmax_t sz_fmt(size_t s) { return s; }
62 void pack_report(void)
64 fprintf(stderr,
65 "pack_report: getpagesize() = %10" SZ_FMT "\n"
66 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
67 "pack_report: core.packedGitLimit = %10" SZ_FMT "\n",
68 sz_fmt(getpagesize()),
69 sz_fmt(packed_git_window_size),
70 sz_fmt(packed_git_limit));
71 fprintf(stderr,
72 "pack_report: pack_used_ctr = %10u\n"
73 "pack_report: pack_mmap_calls = %10u\n"
74 "pack_report: pack_open_windows = %10u / %10u\n"
75 "pack_report: pack_mapped = "
76 "%10" SZ_FMT " / %10" SZ_FMT "\n",
77 pack_used_ctr,
78 pack_mmap_calls,
79 pack_open_windows, peak_pack_open_windows,
80 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
84 * Open and mmap the index file at path, perform a couple of
85 * consistency checks, then record its information to p. Return 0 on
86 * success.
88 static int check_packed_git_idx(const char *path, struct packed_git *p)
90 void *idx_map;
91 size_t idx_size;
92 int fd = git_open(path), ret;
93 struct stat st;
94 const unsigned int hashsz = the_hash_algo->rawsz;
96 if (fd < 0)
97 return -1;
98 if (fstat(fd, &st)) {
99 close(fd);
100 return -1;
102 idx_size = xsize_t(st.st_size);
103 if (idx_size < 4 * 256 + hashsz + hashsz) {
104 close(fd);
105 return error("index file %s is too small", path);
107 idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
108 close(fd);
110 ret = load_idx(path, hashsz, idx_map, idx_size, p);
112 if (ret)
113 munmap(idx_map, idx_size);
115 return ret;
118 int load_idx(const char *path, const unsigned int hashsz, void *idx_map,
119 size_t idx_size, struct packed_git *p)
121 struct pack_idx_header *hdr = idx_map;
122 uint32_t version, nr, i, *index;
124 if (idx_size < 4 * 256 + hashsz + hashsz)
125 return error("index file %s is too small", path);
126 if (!idx_map)
127 return error("empty data");
129 if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
130 version = ntohl(hdr->idx_version);
131 if (version < 2 || version > 2)
132 return error("index file %s is version %"PRIu32
133 " and is not supported by this binary"
134 " (try upgrading GIT to a newer version)",
135 path, version);
136 } else
137 version = 1;
139 nr = 0;
140 index = idx_map;
141 if (version > 1)
142 index += 2; /* skip index header */
143 for (i = 0; i < 256; i++) {
144 uint32_t n = ntohl(index[i]);
145 if (n < nr)
146 return error("non-monotonic index %s", path);
147 nr = n;
150 if (version == 1) {
152 * Total size:
153 * - 256 index entries 4 bytes each
154 * - 24-byte entries * nr (object ID + 4-byte offset)
155 * - hash of the packfile
156 * - file checksum
158 if (idx_size != st_add(4 * 256 + hashsz + hashsz, st_mult(nr, hashsz + 4)))
159 return error("wrong index v1 file size in %s", path);
160 } else if (version == 2) {
162 * Minimum size:
163 * - 8 bytes of header
164 * - 256 index entries 4 bytes each
165 * - object ID entry * nr
166 * - 4-byte crc entry * nr
167 * - 4-byte offset entry * nr
168 * - hash of the packfile
169 * - file checksum
170 * And after the 4-byte offset table might be a
171 * variable sized table containing 8-byte entries
172 * for offsets larger than 2^31.
174 size_t min_size = st_add(8 + 4*256 + hashsz + hashsz, st_mult(nr, hashsz + 4 + 4));
175 size_t max_size = min_size;
176 if (nr)
177 max_size = st_add(max_size, st_mult(nr - 1, 8));
178 if (idx_size < min_size || idx_size > max_size)
179 return error("wrong index v2 file size in %s", path);
180 if (idx_size != min_size &&
182 * make sure we can deal with large pack offsets.
183 * 31-bit signed offset won't be enough, neither
184 * 32-bit unsigned one will be.
186 (sizeof(off_t) <= 4))
187 return error("pack too large for current definition of off_t in %s", path);
188 p->crc_offset = st_add(8 + 4 * 256, st_mult(nr, hashsz));
191 p->index_version = version;
192 p->index_data = idx_map;
193 p->index_size = idx_size;
194 p->num_objects = nr;
195 return 0;
198 int open_pack_index(struct packed_git *p)
200 char *idx_name;
201 size_t len;
202 int ret;
204 if (p->index_data)
205 return 0;
207 if (!strip_suffix(p->pack_name, ".pack", &len))
208 BUG("pack_name does not end in .pack");
209 idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
210 ret = check_packed_git_idx(idx_name, p);
211 free(idx_name);
212 return ret;
215 uint32_t get_pack_fanout(struct packed_git *p, uint32_t value)
217 const uint32_t *level1_ofs = p->index_data;
219 if (!level1_ofs) {
220 if (open_pack_index(p))
221 return 0;
222 level1_ofs = p->index_data;
225 if (p->index_version > 1) {
226 level1_ofs += 2;
229 return ntohl(level1_ofs[value]);
232 static struct packed_git *alloc_packed_git(int extra)
234 struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
235 memset(p, 0, sizeof(*p));
236 p->pack_fd = -1;
237 return p;
240 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
242 const char *path = sha1_pack_name(sha1);
243 size_t alloc = st_add(strlen(path), 1);
244 struct packed_git *p = alloc_packed_git(alloc);
246 memcpy(p->pack_name, path, alloc); /* includes NUL */
247 hashcpy(p->hash, sha1, the_repository->hash_algo);
248 if (check_packed_git_idx(idx_path, p)) {
249 free(p);
250 return NULL;
253 return p;
256 static void scan_windows(struct packed_git *p,
257 struct packed_git **lru_p,
258 struct pack_window **lru_w,
259 struct pack_window **lru_l)
261 struct pack_window *w, *w_l;
263 for (w_l = NULL, w = p->windows; w; w = w->next) {
264 if (!w->inuse_cnt) {
265 if (!*lru_w || w->last_used < (*lru_w)->last_used) {
266 *lru_p = p;
267 *lru_w = w;
268 *lru_l = w_l;
271 w_l = w;
275 static int unuse_one_window(struct packed_git *current)
277 struct packed_git *p, *lru_p = NULL;
278 struct pack_window *lru_w = NULL, *lru_l = NULL;
280 if (current)
281 scan_windows(current, &lru_p, &lru_w, &lru_l);
282 for (p = the_repository->objects->packed_git; p; p = p->next)
283 scan_windows(p, &lru_p, &lru_w, &lru_l);
284 if (lru_p) {
285 munmap(lru_w->base, lru_w->len);
286 pack_mapped -= lru_w->len;
287 if (lru_l)
288 lru_l->next = lru_w->next;
289 else
290 lru_p->windows = lru_w->next;
291 free(lru_w);
292 pack_open_windows--;
293 return 1;
295 return 0;
298 void close_pack_windows(struct packed_git *p)
300 while (p->windows) {
301 struct pack_window *w = p->windows;
303 if (w->inuse_cnt)
304 die("pack '%s' still has open windows to it",
305 p->pack_name);
306 munmap(w->base, w->len);
307 pack_mapped -= w->len;
308 pack_open_windows--;
309 p->windows = w->next;
310 free(w);
314 int close_pack_fd(struct packed_git *p)
316 if (p->pack_fd < 0)
317 return 0;
319 close(p->pack_fd);
320 pack_open_fds--;
321 p->pack_fd = -1;
323 return 1;
326 void close_pack_index(struct packed_git *p)
328 if (p->index_data) {
329 munmap((void *)p->index_data, p->index_size);
330 p->index_data = NULL;
334 static void close_pack_revindex(struct packed_git *p)
336 if (!p->revindex_map)
337 return;
339 munmap((void *)p->revindex_map, p->revindex_size);
340 p->revindex_map = NULL;
341 p->revindex_data = NULL;
344 static void close_pack_mtimes(struct packed_git *p)
346 if (!p->mtimes_map)
347 return;
349 munmap((void *)p->mtimes_map, p->mtimes_size);
350 p->mtimes_map = NULL;
353 void close_pack(struct packed_git *p)
355 close_pack_windows(p);
356 close_pack_fd(p);
357 close_pack_index(p);
358 close_pack_revindex(p);
359 close_pack_mtimes(p);
360 oidset_clear(&p->bad_objects);
363 void close_object_store(struct raw_object_store *o)
365 struct packed_git *p;
367 for (p = o->packed_git; p; p = p->next)
368 if (p->do_not_close)
369 BUG("want to close pack marked 'do-not-close'");
370 else
371 close_pack(p);
373 if (o->multi_pack_index) {
374 close_midx(o->multi_pack_index);
375 o->multi_pack_index = NULL;
378 close_commit_graph(o);
381 void unlink_pack_path(const char *pack_name, int force_delete)
383 static const char *exts[] = {".idx", ".pack", ".rev", ".keep", ".bitmap", ".promisor", ".mtimes"};
384 int i;
385 struct strbuf buf = STRBUF_INIT;
386 size_t plen;
388 strbuf_addstr(&buf, pack_name);
389 strip_suffix_mem(buf.buf, &buf.len, ".pack");
390 plen = buf.len;
392 if (!force_delete) {
393 strbuf_addstr(&buf, ".keep");
394 if (!access(buf.buf, F_OK)) {
395 strbuf_release(&buf);
396 return;
400 for (i = 0; i < ARRAY_SIZE(exts); i++) {
401 strbuf_setlen(&buf, plen);
402 strbuf_addstr(&buf, exts[i]);
403 unlink(buf.buf);
406 strbuf_release(&buf);
410 * The LRU pack is the one with the oldest MRU window, preferring packs
411 * with no used windows, or the oldest mtime if it has no windows allocated.
413 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
415 struct pack_window *w, *this_mru_w;
416 int has_windows_inuse = 0;
419 * Reject this pack if it has windows and the previously selected
420 * one does not. If this pack does not have windows, reject
421 * it if the pack file is newer than the previously selected one.
423 if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
424 return;
426 for (w = this_mru_w = p->windows; w; w = w->next) {
428 * Reject this pack if any of its windows are in use,
429 * but the previously selected pack did not have any
430 * inuse windows. Otherwise, record that this pack
431 * has windows in use.
433 if (w->inuse_cnt) {
434 if (*accept_windows_inuse)
435 has_windows_inuse = 1;
436 else
437 return;
440 if (w->last_used > this_mru_w->last_used)
441 this_mru_w = w;
444 * Reject this pack if it has windows that have been
445 * used more recently than the previously selected pack.
446 * If the previously selected pack had windows inuse and
447 * we have not encountered a window in this pack that is
448 * inuse, skip this check since we prefer a pack with no
449 * inuse windows to one that has inuse windows.
451 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
452 this_mru_w->last_used > (*mru_w)->last_used)
453 return;
457 * Select this pack.
459 *mru_w = this_mru_w;
460 *lru_p = p;
461 *accept_windows_inuse = has_windows_inuse;
464 static int close_one_pack(void)
466 struct packed_git *p, *lru_p = NULL;
467 struct pack_window *mru_w = NULL;
468 int accept_windows_inuse = 1;
470 for (p = the_repository->objects->packed_git; p; p = p->next) {
471 if (p->pack_fd == -1)
472 continue;
473 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
476 if (lru_p)
477 return close_pack_fd(lru_p);
479 return 0;
482 static unsigned int get_max_fd_limit(void)
484 #ifdef RLIMIT_NOFILE
486 struct rlimit lim;
488 if (!getrlimit(RLIMIT_NOFILE, &lim))
489 return lim.rlim_cur;
491 #endif
493 #ifdef _SC_OPEN_MAX
495 long open_max = sysconf(_SC_OPEN_MAX);
496 if (0 < open_max)
497 return open_max;
499 * Otherwise, we got -1 for one of the two
500 * reasons:
502 * (1) sysconf() did not understand _SC_OPEN_MAX
503 * and signaled an error with -1; or
504 * (2) sysconf() said there is no limit.
506 * We _could_ clear errno before calling sysconf() to
507 * tell these two cases apart and return a huge number
508 * in the latter case to let the caller cap it to a
509 * value that is not so selfish, but letting the
510 * fallback OPEN_MAX codepath take care of these cases
511 * is a lot simpler.
514 #endif
516 #ifdef OPEN_MAX
517 return OPEN_MAX;
518 #else
519 return 1; /* see the caller ;-) */
520 #endif
523 const char *pack_basename(struct packed_git *p)
525 const char *ret = strrchr(p->pack_name, '/');
526 if (ret)
527 ret = ret + 1; /* skip past slash */
528 else
529 ret = p->pack_name; /* we only have a base */
530 return ret;
534 * Do not call this directly as this leaks p->pack_fd on error return;
535 * call open_packed_git() instead.
537 static int open_packed_git_1(struct packed_git *p)
539 struct stat st;
540 struct pack_header hdr;
541 unsigned char hash[GIT_MAX_RAWSZ];
542 unsigned char *idx_hash;
543 ssize_t read_result;
544 const unsigned hashsz = the_hash_algo->rawsz;
546 if (open_pack_index(p))
547 return error("packfile %s index unavailable", p->pack_name);
549 if (!pack_max_fds) {
550 unsigned int max_fds = get_max_fd_limit();
552 /* Save 3 for stdin/stdout/stderr, 22 for work */
553 if (25 < max_fds)
554 pack_max_fds = max_fds - 25;
555 else
556 pack_max_fds = 1;
559 while (pack_max_fds <= pack_open_fds && close_one_pack())
560 ; /* nothing */
562 p->pack_fd = git_open(p->pack_name);
563 if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
564 return -1;
565 pack_open_fds++;
567 /* If we created the struct before we had the pack we lack size. */
568 if (!p->pack_size) {
569 if (!S_ISREG(st.st_mode))
570 return error("packfile %s not a regular file", p->pack_name);
571 p->pack_size = st.st_size;
572 } else if (p->pack_size != st.st_size)
573 return error("packfile %s size changed", p->pack_name);
575 /* Verify we recognize this pack file format. */
576 read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
577 if (read_result < 0)
578 return error_errno("error reading from %s", p->pack_name);
579 if (read_result != sizeof(hdr))
580 return error("file %s is far too short to be a packfile", p->pack_name);
581 if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
582 return error("file %s is not a GIT packfile", p->pack_name);
583 if (!pack_version_ok(hdr.hdr_version))
584 return error("packfile %s is version %"PRIu32" and not"
585 " supported (try upgrading GIT to a newer version)",
586 p->pack_name, ntohl(hdr.hdr_version));
588 /* Verify the pack matches its index. */
589 if (p->num_objects != ntohl(hdr.hdr_entries))
590 return error("packfile %s claims to have %"PRIu32" objects"
591 " while index indicates %"PRIu32" objects",
592 p->pack_name, ntohl(hdr.hdr_entries),
593 p->num_objects);
594 read_result = pread_in_full(p->pack_fd, hash, hashsz,
595 p->pack_size - hashsz);
596 if (read_result < 0)
597 return error_errno("error reading from %s", p->pack_name);
598 if (read_result != hashsz)
599 return error("packfile %s signature is unavailable", p->pack_name);
600 idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
601 if (!hasheq(hash, idx_hash, the_repository->hash_algo))
602 return error("packfile %s does not match index", p->pack_name);
603 return 0;
606 static int open_packed_git(struct packed_git *p)
608 if (!open_packed_git_1(p))
609 return 0;
610 close_pack_fd(p);
611 return -1;
614 static int in_window(struct pack_window *win, off_t offset)
616 /* We must promise at least one full hash after the
617 * offset is available from this window, otherwise the offset
618 * is not actually in this window and a different window (which
619 * has that one hash excess) must be used. This is to support
620 * the object header and delta base parsing routines below.
622 off_t win_off = win->offset;
623 return win_off <= offset
624 && (offset + the_hash_algo->rawsz) <= (win_off + win->len);
627 unsigned char *use_pack(struct packed_git *p,
628 struct pack_window **w_cursor,
629 off_t offset,
630 unsigned long *left)
632 struct pack_window *win = *w_cursor;
634 /* Since packfiles end in a hash of their content and it's
635 * pointless to ask for an offset into the middle of that
636 * hash, and the in_window function above wouldn't match
637 * don't allow an offset too close to the end of the file.
639 if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
640 die("packfile %s cannot be accessed", p->pack_name);
641 if (offset > (p->pack_size - the_hash_algo->rawsz))
642 die("offset beyond end of packfile (truncated pack?)");
643 if (offset < 0)
644 die(_("offset before end of packfile (broken .idx?)"));
646 if (!win || !in_window(win, offset)) {
647 if (win)
648 win->inuse_cnt--;
649 for (win = p->windows; win; win = win->next) {
650 if (in_window(win, offset))
651 break;
653 if (!win) {
654 size_t window_align = packed_git_window_size / 2;
655 off_t len;
657 if (p->pack_fd == -1 && open_packed_git(p))
658 die("packfile %s cannot be accessed", p->pack_name);
660 CALLOC_ARRAY(win, 1);
661 win->offset = (offset / window_align) * window_align;
662 len = p->pack_size - win->offset;
663 if (len > packed_git_window_size)
664 len = packed_git_window_size;
665 win->len = (size_t)len;
666 pack_mapped += win->len;
667 while (packed_git_limit < pack_mapped
668 && unuse_one_window(p))
669 ; /* nothing */
670 win->base = xmmap_gently(NULL, win->len,
671 PROT_READ, MAP_PRIVATE,
672 p->pack_fd, win->offset);
673 if (win->base == MAP_FAILED)
674 die_errno(_("packfile %s cannot be mapped%s"),
675 p->pack_name, mmap_os_err());
676 if (!win->offset && win->len == p->pack_size
677 && !p->do_not_close)
678 close_pack_fd(p);
679 pack_mmap_calls++;
680 pack_open_windows++;
681 if (pack_mapped > peak_pack_mapped)
682 peak_pack_mapped = pack_mapped;
683 if (pack_open_windows > peak_pack_open_windows)
684 peak_pack_open_windows = pack_open_windows;
685 win->next = p->windows;
686 p->windows = win;
689 if (win != *w_cursor) {
690 win->last_used = pack_used_ctr++;
691 win->inuse_cnt++;
692 *w_cursor = win;
694 offset -= win->offset;
695 if (left)
696 *left = win->len - xsize_t(offset);
697 return win->base + offset;
700 void unuse_pack(struct pack_window **w_cursor)
702 struct pack_window *w = *w_cursor;
703 if (w) {
704 w->inuse_cnt--;
705 *w_cursor = NULL;
709 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
711 struct stat st;
712 size_t alloc;
713 struct packed_git *p;
716 * Make sure a corresponding .pack file exists and that
717 * the index looks sane.
719 if (!strip_suffix_mem(path, &path_len, ".idx"))
720 return NULL;
723 * ".promisor" is long enough to hold any suffix we're adding (and
724 * the use xsnprintf double-checks that)
726 alloc = st_add3(path_len, strlen(".promisor"), 1);
727 p = alloc_packed_git(alloc);
728 memcpy(p->pack_name, path, path_len);
730 xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
731 if (!access(p->pack_name, F_OK))
732 p->pack_keep = 1;
734 xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
735 if (!access(p->pack_name, F_OK))
736 p->pack_promisor = 1;
738 xsnprintf(p->pack_name + path_len, alloc - path_len, ".mtimes");
739 if (!access(p->pack_name, F_OK))
740 p->is_cruft = 1;
742 xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
743 if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
744 free(p);
745 return NULL;
748 /* ok, it looks sane as far as we can check without
749 * actually mapping the pack file.
751 p->pack_size = st.st_size;
752 p->pack_local = local;
753 p->mtime = st.st_mtime;
754 if (path_len < the_hash_algo->hexsz ||
755 get_hash_hex(path + path_len - the_hash_algo->hexsz, p->hash))
756 hashclr(p->hash, the_repository->hash_algo);
757 return p;
760 void install_packed_git(struct repository *r, struct packed_git *pack)
762 if (pack->pack_fd != -1)
763 pack_open_fds++;
765 pack->next = r->objects->packed_git;
766 r->objects->packed_git = pack;
768 hashmap_entry_init(&pack->packmap_ent, strhash(pack->pack_name));
769 hashmap_add(&r->objects->pack_map, &pack->packmap_ent);
772 void (*report_garbage)(unsigned seen_bits, const char *path);
774 static void report_helper(const struct string_list *list,
775 int seen_bits, int first, int last)
777 if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
778 return;
780 for (; first < last; first++)
781 report_garbage(seen_bits, list->items[first].string);
784 static void report_pack_garbage(struct string_list *list)
786 int i, baselen = -1, first = 0, seen_bits = 0;
788 if (!report_garbage)
789 return;
791 string_list_sort(list);
793 for (i = 0; i < list->nr; i++) {
794 const char *path = list->items[i].string;
795 if (baselen != -1 &&
796 strncmp(path, list->items[first].string, baselen)) {
797 report_helper(list, seen_bits, first, i);
798 baselen = -1;
799 seen_bits = 0;
801 if (baselen == -1) {
802 const char *dot = strrchr(path, '.');
803 if (!dot) {
804 report_garbage(PACKDIR_FILE_GARBAGE, path);
805 continue;
807 baselen = dot - path + 1;
808 first = i;
810 if (!strcmp(path + baselen, "pack"))
811 seen_bits |= 1;
812 else if (!strcmp(path + baselen, "idx"))
813 seen_bits |= 2;
815 report_helper(list, seen_bits, first, list->nr);
818 void for_each_file_in_pack_dir(const char *objdir,
819 each_file_in_pack_dir_fn fn,
820 void *data)
822 struct strbuf path = STRBUF_INIT;
823 size_t dirnamelen;
824 DIR *dir;
825 struct dirent *de;
827 strbuf_addstr(&path, objdir);
828 strbuf_addstr(&path, "/pack");
829 dir = opendir(path.buf);
830 if (!dir) {
831 if (errno != ENOENT)
832 error_errno("unable to open object pack directory: %s",
833 path.buf);
834 strbuf_release(&path);
835 return;
837 strbuf_addch(&path, '/');
838 dirnamelen = path.len;
839 while ((de = readdir_skip_dot_and_dotdot(dir)) != NULL) {
840 strbuf_setlen(&path, dirnamelen);
841 strbuf_addstr(&path, de->d_name);
843 fn(path.buf, path.len, de->d_name, data);
846 closedir(dir);
847 strbuf_release(&path);
850 struct prepare_pack_data {
851 struct repository *r;
852 struct string_list *garbage;
853 int local;
854 struct multi_pack_index *m;
857 static void prepare_pack(const char *full_name, size_t full_name_len,
858 const char *file_name, void *_data)
860 struct prepare_pack_data *data = (struct prepare_pack_data *)_data;
861 struct packed_git *p;
862 size_t base_len = full_name_len;
864 if (strip_suffix_mem(full_name, &base_len, ".idx") &&
865 !(data->m && midx_contains_pack(data->m, file_name))) {
866 struct hashmap_entry hent;
867 char *pack_name = xstrfmt("%.*s.pack", (int)base_len, full_name);
868 unsigned int hash = strhash(pack_name);
869 hashmap_entry_init(&hent, hash);
871 /* Don't reopen a pack we already have. */
872 if (!hashmap_get(&data->r->objects->pack_map, &hent, pack_name)) {
873 p = add_packed_git(full_name, full_name_len, data->local);
874 if (p)
875 install_packed_git(data->r, p);
877 free(pack_name);
880 if (!report_garbage)
881 return;
883 if (!strcmp(file_name, "multi-pack-index"))
884 return;
885 if (starts_with(file_name, "multi-pack-index") &&
886 (ends_with(file_name, ".bitmap") || ends_with(file_name, ".rev")))
887 return;
888 if (ends_with(file_name, ".idx") ||
889 ends_with(file_name, ".rev") ||
890 ends_with(file_name, ".pack") ||
891 ends_with(file_name, ".bitmap") ||
892 ends_with(file_name, ".keep") ||
893 ends_with(file_name, ".promisor") ||
894 ends_with(file_name, ".mtimes"))
895 string_list_append(data->garbage, full_name);
896 else
897 report_garbage(PACKDIR_FILE_GARBAGE, full_name);
900 static void prepare_packed_git_one(struct repository *r, char *objdir, int local)
902 struct prepare_pack_data data;
903 struct string_list garbage = STRING_LIST_INIT_DUP;
905 data.m = r->objects->multi_pack_index;
907 /* look for the multi-pack-index for this object directory */
908 while (data.m && strcmp(data.m->object_dir, objdir))
909 data.m = data.m->next;
911 data.r = r;
912 data.garbage = &garbage;
913 data.local = local;
915 for_each_file_in_pack_dir(objdir, prepare_pack, &data);
917 report_pack_garbage(data.garbage);
918 string_list_clear(data.garbage, 0);
921 static void prepare_packed_git(struct repository *r);
923 * Give a fast, rough count of the number of objects in the repository. This
924 * ignores loose objects completely. If you have a lot of them, then either
925 * you should repack because your performance will be awful, or they are
926 * all unreachable objects about to be pruned, in which case they're not really
927 * interesting as a measure of repo size in the first place.
929 unsigned long repo_approximate_object_count(struct repository *r)
931 if (!r->objects->approximate_object_count_valid) {
932 unsigned long count;
933 struct multi_pack_index *m;
934 struct packed_git *p;
936 prepare_packed_git(r);
937 count = 0;
938 for (m = get_multi_pack_index(r); m; m = m->next)
939 count += m->num_objects;
940 for (p = r->objects->packed_git; p; p = p->next) {
941 if (open_pack_index(p))
942 continue;
943 count += p->num_objects;
945 r->objects->approximate_object_count = count;
946 r->objects->approximate_object_count_valid = 1;
948 return r->objects->approximate_object_count;
951 DEFINE_LIST_SORT(static, sort_packs, struct packed_git, next);
953 static int sort_pack(const struct packed_git *a, const struct packed_git *b)
955 int st;
958 * Local packs tend to contain objects specific to our
959 * variant of the project than remote ones. In addition,
960 * remote ones could be on a network mounted filesystem.
961 * Favor local ones for these reasons.
963 st = a->pack_local - b->pack_local;
964 if (st)
965 return -st;
968 * Younger packs tend to contain more recent objects,
969 * and more recent objects tend to get accessed more
970 * often.
972 if (a->mtime < b->mtime)
973 return 1;
974 else if (a->mtime == b->mtime)
975 return 0;
976 return -1;
979 static void rearrange_packed_git(struct repository *r)
981 sort_packs(&r->objects->packed_git, sort_pack);
984 static void prepare_packed_git_mru(struct repository *r)
986 struct packed_git *p;
988 INIT_LIST_HEAD(&r->objects->packed_git_mru);
990 for (p = r->objects->packed_git; p; p = p->next)
991 list_add_tail(&p->mru, &r->objects->packed_git_mru);
994 static void prepare_packed_git(struct repository *r)
996 struct object_directory *odb;
998 if (r->objects->packed_git_initialized)
999 return;
1001 prepare_alt_odb(r);
1002 for (odb = r->objects->odb; odb; odb = odb->next) {
1003 int local = (odb == r->objects->odb);
1004 prepare_multi_pack_index_one(r, odb->path, local);
1005 prepare_packed_git_one(r, odb->path, local);
1007 rearrange_packed_git(r);
1009 prepare_packed_git_mru(r);
1010 r->objects->packed_git_initialized = 1;
1013 void reprepare_packed_git(struct repository *r)
1015 struct object_directory *odb;
1017 obj_read_lock();
1020 * Reprepare alt odbs, in case the alternates file was modified
1021 * during the course of this process. This only _adds_ odbs to
1022 * the linked list, so existing odbs will continue to exist for
1023 * the lifetime of the process.
1025 r->objects->loaded_alternates = 0;
1026 prepare_alt_odb(r);
1028 for (odb = r->objects->odb; odb; odb = odb->next)
1029 odb_clear_loose_cache(odb);
1031 r->objects->approximate_object_count_valid = 0;
1032 r->objects->packed_git_initialized = 0;
1033 prepare_packed_git(r);
1034 obj_read_unlock();
1037 struct packed_git *get_packed_git(struct repository *r)
1039 prepare_packed_git(r);
1040 return r->objects->packed_git;
1043 struct multi_pack_index *get_multi_pack_index(struct repository *r)
1045 prepare_packed_git(r);
1046 return r->objects->multi_pack_index;
1049 struct multi_pack_index *get_local_multi_pack_index(struct repository *r)
1051 struct multi_pack_index *m = get_multi_pack_index(r);
1053 /* no need to iterate; we always put the local one first (if any) */
1054 if (m && m->local)
1055 return m;
1057 return NULL;
1060 struct packed_git *get_all_packs(struct repository *r)
1062 struct multi_pack_index *m;
1064 prepare_packed_git(r);
1065 for (m = r->objects->multi_pack_index; m; m = m->next) {
1066 uint32_t i;
1067 for (i = 0; i < m->num_packs; i++)
1068 prepare_midx_pack(r, m, i);
1071 return r->objects->packed_git;
1074 struct list_head *get_packed_git_mru(struct repository *r)
1076 prepare_packed_git(r);
1077 return &r->objects->packed_git_mru;
1080 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1081 unsigned long len, enum object_type *type, unsigned long *sizep)
1083 unsigned shift;
1084 size_t size, c;
1085 unsigned long used = 0;
1087 c = buf[used++];
1088 *type = (c >> 4) & 7;
1089 size = c & 15;
1090 shift = 4;
1091 while (c & 0x80) {
1092 if (len <= used || (bitsizeof(long) - 7) < shift) {
1093 error("bad object header");
1094 size = used = 0;
1095 break;
1097 c = buf[used++];
1098 size = st_add(size, st_left_shift(c & 0x7f, shift));
1099 shift += 7;
1101 *sizep = cast_size_t_to_ulong(size);
1102 return used;
1105 unsigned long get_size_from_delta(struct packed_git *p,
1106 struct pack_window **w_curs,
1107 off_t curpos)
1109 const unsigned char *data;
1110 unsigned char delta_head[20], *in;
1111 git_zstream stream;
1112 int st;
1114 memset(&stream, 0, sizeof(stream));
1115 stream.next_out = delta_head;
1116 stream.avail_out = sizeof(delta_head);
1118 git_inflate_init(&stream);
1119 do {
1120 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1121 stream.next_in = in;
1123 * Note: the window section returned by use_pack() must be
1124 * available throughout git_inflate()'s unlocked execution. To
1125 * ensure no other thread will modify the window in the
1126 * meantime, we rely on the packed_window.inuse_cnt. This
1127 * counter is incremented before window reading and checked
1128 * before window disposal.
1130 * Other worrying sections could be the call to close_pack_fd(),
1131 * which can close packs even with in-use windows, and to
1132 * reprepare_packed_git(). Regarding the former, mmap doc says:
1133 * "closing the file descriptor does not unmap the region". And
1134 * for the latter, it won't re-open already available packs.
1136 obj_read_unlock();
1137 st = git_inflate(&stream, Z_FINISH);
1138 obj_read_lock();
1139 curpos += stream.next_in - in;
1140 } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1141 stream.total_out < sizeof(delta_head));
1142 git_inflate_end(&stream);
1143 if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1144 error("delta data unpack-initial failed");
1145 return 0;
1148 /* Examine the initial part of the delta to figure out
1149 * the result size.
1151 data = delta_head;
1153 /* ignore base size */
1154 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1156 /* Read the result size */
1157 return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1160 int unpack_object_header(struct packed_git *p,
1161 struct pack_window **w_curs,
1162 off_t *curpos,
1163 unsigned long *sizep)
1165 unsigned char *base;
1166 unsigned long left;
1167 unsigned long used;
1168 enum object_type type;
1170 /* use_pack() assures us we have [base, base + 20) available
1171 * as a range that we can look at. (Its actually the hash
1172 * size that is assured.) With our object header encoding
1173 * the maximum deflated object size is 2^137, which is just
1174 * insane, so we know won't exceed what we have been given.
1176 base = use_pack(p, w_curs, *curpos, &left);
1177 used = unpack_object_header_buffer(base, left, &type, sizep);
1178 if (!used) {
1179 type = OBJ_BAD;
1180 } else
1181 *curpos += used;
1183 return type;
1186 void mark_bad_packed_object(struct packed_git *p, const struct object_id *oid)
1188 oidset_insert(&p->bad_objects, oid);
1191 const struct packed_git *has_packed_and_bad(struct repository *r,
1192 const struct object_id *oid)
1194 struct packed_git *p;
1196 for (p = r->objects->packed_git; p; p = p->next)
1197 if (oidset_contains(&p->bad_objects, oid))
1198 return p;
1199 return NULL;
1202 off_t get_delta_base(struct packed_git *p,
1203 struct pack_window **w_curs,
1204 off_t *curpos,
1205 enum object_type type,
1206 off_t delta_obj_offset)
1208 unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1209 off_t base_offset;
1211 /* use_pack() assured us we have [base_info, base_info + 20)
1212 * as a range that we can look at without walking off the
1213 * end of the mapped window. Its actually the hash size
1214 * that is assured. An OFS_DELTA longer than the hash size
1215 * is stupid, as then a REF_DELTA would be smaller to store.
1217 if (type == OBJ_OFS_DELTA) {
1218 unsigned used = 0;
1219 unsigned char c = base_info[used++];
1220 base_offset = c & 127;
1221 while (c & 128) {
1222 base_offset += 1;
1223 if (!base_offset || MSB(base_offset, 7))
1224 return 0; /* overflow */
1225 c = base_info[used++];
1226 base_offset = (base_offset << 7) + (c & 127);
1228 base_offset = delta_obj_offset - base_offset;
1229 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1230 return 0; /* out of bound */
1231 *curpos += used;
1232 } else if (type == OBJ_REF_DELTA) {
1233 /* The base entry _must_ be in the same pack */
1234 base_offset = find_pack_entry_one(base_info, p);
1235 *curpos += the_hash_algo->rawsz;
1236 } else
1237 die("I am totally screwed");
1238 return base_offset;
1242 * Like get_delta_base above, but we return the sha1 instead of the pack
1243 * offset. This means it is cheaper for REF deltas (we do not have to do
1244 * the final object lookup), but more expensive for OFS deltas (we
1245 * have to load the revidx to convert the offset back into a sha1).
1247 static int get_delta_base_oid(struct packed_git *p,
1248 struct pack_window **w_curs,
1249 off_t curpos,
1250 struct object_id *oid,
1251 enum object_type type,
1252 off_t delta_obj_offset)
1254 if (type == OBJ_REF_DELTA) {
1255 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1256 oidread(oid, base, the_repository->hash_algo);
1257 return 0;
1258 } else if (type == OBJ_OFS_DELTA) {
1259 uint32_t base_pos;
1260 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1261 type, delta_obj_offset);
1263 if (!base_offset)
1264 return -1;
1266 if (offset_to_pack_pos(p, base_offset, &base_pos) < 0)
1267 return -1;
1269 return nth_packed_object_id(oid, p,
1270 pack_pos_to_index(p, base_pos));
1271 } else
1272 return -1;
1275 static int retry_bad_packed_offset(struct repository *r,
1276 struct packed_git *p,
1277 off_t obj_offset)
1279 int type;
1280 uint32_t pos;
1281 struct object_id oid;
1282 if (offset_to_pack_pos(p, obj_offset, &pos) < 0)
1283 return OBJ_BAD;
1284 nth_packed_object_id(&oid, p, pack_pos_to_index(p, pos));
1285 mark_bad_packed_object(p, &oid);
1286 type = oid_object_info(r, &oid, NULL);
1287 if (type <= OBJ_NONE)
1288 return OBJ_BAD;
1289 return type;
1292 #define POI_STACK_PREALLOC 64
1294 static enum object_type packed_to_object_type(struct repository *r,
1295 struct packed_git *p,
1296 off_t obj_offset,
1297 enum object_type type,
1298 struct pack_window **w_curs,
1299 off_t curpos)
1301 off_t small_poi_stack[POI_STACK_PREALLOC];
1302 off_t *poi_stack = small_poi_stack;
1303 int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1305 while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1306 off_t base_offset;
1307 unsigned long size;
1308 /* Push the object we're going to leave behind */
1309 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1310 poi_stack_alloc = alloc_nr(poi_stack_nr);
1311 ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1312 COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1313 } else {
1314 ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1316 poi_stack[poi_stack_nr++] = obj_offset;
1317 /* If parsing the base offset fails, just unwind */
1318 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1319 if (!base_offset)
1320 goto unwind;
1321 curpos = obj_offset = base_offset;
1322 type = unpack_object_header(p, w_curs, &curpos, &size);
1323 if (type <= OBJ_NONE) {
1324 /* If getting the base itself fails, we first
1325 * retry the base, otherwise unwind */
1326 type = retry_bad_packed_offset(r, p, base_offset);
1327 if (type > OBJ_NONE)
1328 goto out;
1329 goto unwind;
1333 switch (type) {
1334 case OBJ_BAD:
1335 case OBJ_COMMIT:
1336 case OBJ_TREE:
1337 case OBJ_BLOB:
1338 case OBJ_TAG:
1339 break;
1340 default:
1341 error("unknown object type %i at offset %"PRIuMAX" in %s",
1342 type, (uintmax_t)obj_offset, p->pack_name);
1343 type = OBJ_BAD;
1346 out:
1347 if (poi_stack != small_poi_stack)
1348 free(poi_stack);
1349 return type;
1351 unwind:
1352 while (poi_stack_nr) {
1353 obj_offset = poi_stack[--poi_stack_nr];
1354 type = retry_bad_packed_offset(r, p, obj_offset);
1355 if (type > OBJ_NONE)
1356 goto out;
1358 type = OBJ_BAD;
1359 goto out;
1362 static struct hashmap delta_base_cache;
1363 static size_t delta_base_cached;
1365 static LIST_HEAD(delta_base_cache_lru);
1367 struct delta_base_cache_key {
1368 struct packed_git *p;
1369 off_t base_offset;
1372 struct delta_base_cache_entry {
1373 struct hashmap_entry ent;
1374 struct delta_base_cache_key key;
1375 struct list_head lru;
1376 void *data;
1377 unsigned long size;
1378 enum object_type type;
1381 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1383 unsigned int hash;
1385 hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1386 hash += (hash >> 8) + (hash >> 16);
1387 return hash;
1390 static struct delta_base_cache_entry *
1391 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1393 struct hashmap_entry entry, *e;
1394 struct delta_base_cache_key key;
1396 if (!delta_base_cache.cmpfn)
1397 return NULL;
1399 hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1400 key.p = p;
1401 key.base_offset = base_offset;
1402 e = hashmap_get(&delta_base_cache, &entry, &key);
1403 return e ? container_of(e, struct delta_base_cache_entry, ent) : NULL;
1406 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1407 const struct delta_base_cache_key *b)
1409 return a->p == b->p && a->base_offset == b->base_offset;
1412 static int delta_base_cache_hash_cmp(const void *cmp_data UNUSED,
1413 const struct hashmap_entry *va,
1414 const struct hashmap_entry *vb,
1415 const void *vkey)
1417 const struct delta_base_cache_entry *a, *b;
1418 const struct delta_base_cache_key *key = vkey;
1420 a = container_of(va, const struct delta_base_cache_entry, ent);
1421 b = container_of(vb, const struct delta_base_cache_entry, ent);
1423 if (key)
1424 return !delta_base_cache_key_eq(&a->key, key);
1425 else
1426 return !delta_base_cache_key_eq(&a->key, &b->key);
1429 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1431 return !!get_delta_base_cache_entry(p, base_offset);
1435 * Remove the entry from the cache, but do _not_ free the associated
1436 * entry data. The caller takes ownership of the "data" buffer, and
1437 * should copy out any fields it wants before detaching.
1439 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1441 hashmap_remove(&delta_base_cache, &ent->ent, &ent->key);
1442 list_del(&ent->lru);
1443 delta_base_cached -= ent->size;
1444 free(ent);
1447 static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1448 off_t base_offset, unsigned long *base_size,
1449 enum object_type *type)
1451 struct delta_base_cache_entry *ent;
1453 ent = get_delta_base_cache_entry(p, base_offset);
1454 if (!ent)
1455 return unpack_entry(r, p, base_offset, type, base_size);
1457 if (type)
1458 *type = ent->type;
1459 if (base_size)
1460 *base_size = ent->size;
1461 return xmemdupz(ent->data, ent->size);
1464 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1466 free(ent->data);
1467 detach_delta_base_cache_entry(ent);
1470 void clear_delta_base_cache(void)
1472 struct list_head *lru, *tmp;
1473 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1474 struct delta_base_cache_entry *entry =
1475 list_entry(lru, struct delta_base_cache_entry, lru);
1476 release_delta_base_cache(entry);
1480 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1481 void *base, unsigned long base_size, enum object_type type)
1483 struct delta_base_cache_entry *ent;
1484 struct list_head *lru, *tmp;
1487 * Check required to avoid redundant entries when more than one thread
1488 * is unpacking the same object, in unpack_entry() (since its phases I
1489 * and III might run concurrently across multiple threads).
1491 if (in_delta_base_cache(p, base_offset)) {
1492 free(base);
1493 return;
1496 delta_base_cached += base_size;
1498 list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1499 struct delta_base_cache_entry *f =
1500 list_entry(lru, struct delta_base_cache_entry, lru);
1501 if (delta_base_cached <= delta_base_cache_limit)
1502 break;
1503 release_delta_base_cache(f);
1506 ent = xmalloc(sizeof(*ent));
1507 ent->key.p = p;
1508 ent->key.base_offset = base_offset;
1509 ent->type = type;
1510 ent->data = base;
1511 ent->size = base_size;
1512 list_add_tail(&ent->lru, &delta_base_cache_lru);
1514 if (!delta_base_cache.cmpfn)
1515 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1516 hashmap_entry_init(&ent->ent, pack_entry_hash(p, base_offset));
1517 hashmap_add(&delta_base_cache, &ent->ent);
1520 int packed_object_info(struct repository *r, struct packed_git *p,
1521 off_t obj_offset, struct object_info *oi)
1523 struct pack_window *w_curs = NULL;
1524 unsigned long size;
1525 off_t curpos = obj_offset;
1526 enum object_type type;
1529 * We always get the representation type, but only convert it to
1530 * a "real" type later if the caller is interested.
1532 if (oi->contentp) {
1533 *oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
1534 &type);
1535 if (!*oi->contentp)
1536 type = OBJ_BAD;
1537 } else {
1538 type = unpack_object_header(p, &w_curs, &curpos, &size);
1541 if (!oi->contentp && oi->sizep) {
1542 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1543 off_t tmp_pos = curpos;
1544 off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1545 type, obj_offset);
1546 if (!base_offset) {
1547 type = OBJ_BAD;
1548 goto out;
1550 *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1551 if (*oi->sizep == 0) {
1552 type = OBJ_BAD;
1553 goto out;
1555 } else {
1556 *oi->sizep = size;
1560 if (oi->disk_sizep) {
1561 uint32_t pos;
1562 if (offset_to_pack_pos(p, obj_offset, &pos) < 0) {
1563 error("could not find object at offset %"PRIuMAX" "
1564 "in pack %s", (uintmax_t)obj_offset, p->pack_name);
1565 type = OBJ_BAD;
1566 goto out;
1569 *oi->disk_sizep = pack_pos_to_offset(p, pos + 1) - obj_offset;
1572 if (oi->typep || oi->type_name) {
1573 enum object_type ptot;
1574 ptot = packed_to_object_type(r, p, obj_offset,
1575 type, &w_curs, curpos);
1576 if (oi->typep)
1577 *oi->typep = ptot;
1578 if (oi->type_name) {
1579 const char *tn = type_name(ptot);
1580 if (tn)
1581 strbuf_addstr(oi->type_name, tn);
1583 if (ptot < 0) {
1584 type = OBJ_BAD;
1585 goto out;
1589 if (oi->delta_base_oid) {
1590 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1591 if (get_delta_base_oid(p, &w_curs, curpos,
1592 oi->delta_base_oid,
1593 type, obj_offset) < 0) {
1594 type = OBJ_BAD;
1595 goto out;
1597 } else
1598 oidclr(oi->delta_base_oid, the_repository->hash_algo);
1601 oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1602 OI_PACKED;
1604 out:
1605 unuse_pack(&w_curs);
1606 return type;
1609 static void *unpack_compressed_entry(struct packed_git *p,
1610 struct pack_window **w_curs,
1611 off_t curpos,
1612 unsigned long size)
1614 int st;
1615 git_zstream stream;
1616 unsigned char *buffer, *in;
1618 buffer = xmallocz_gently(size);
1619 if (!buffer)
1620 return NULL;
1621 memset(&stream, 0, sizeof(stream));
1622 stream.next_out = buffer;
1623 stream.avail_out = size + 1;
1625 git_inflate_init(&stream);
1626 do {
1627 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1628 stream.next_in = in;
1630 * Note: we must ensure the window section returned by
1631 * use_pack() will be available throughout git_inflate()'s
1632 * unlocked execution. Please refer to the comment at
1633 * get_size_from_delta() to see how this is done.
1635 obj_read_unlock();
1636 st = git_inflate(&stream, Z_FINISH);
1637 obj_read_lock();
1638 if (!stream.avail_out)
1639 break; /* the payload is larger than it should be */
1640 curpos += stream.next_in - in;
1641 } while (st == Z_OK || st == Z_BUF_ERROR);
1642 git_inflate_end(&stream);
1643 if ((st != Z_STREAM_END) || stream.total_out != size) {
1644 free(buffer);
1645 return NULL;
1648 /* versions of zlib can clobber unconsumed portion of outbuf */
1649 buffer[size] = '\0';
1651 return buffer;
1654 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1656 static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1657 trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1658 p->pack_name, (uintmax_t)obj_offset);
1661 int do_check_packed_object_crc;
1663 #define UNPACK_ENTRY_STACK_PREALLOC 64
1664 struct unpack_entry_stack_ent {
1665 off_t obj_offset;
1666 off_t curpos;
1667 unsigned long size;
1670 void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1671 enum object_type *final_type, unsigned long *final_size)
1673 struct pack_window *w_curs = NULL;
1674 off_t curpos = obj_offset;
1675 void *data = NULL;
1676 unsigned long size;
1677 enum object_type type;
1678 struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1679 struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1680 int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1681 int base_from_cache = 0;
1683 write_pack_access_log(p, obj_offset);
1685 /* PHASE 1: drill down to the innermost base object */
1686 for (;;) {
1687 off_t base_offset;
1688 int i;
1689 struct delta_base_cache_entry *ent;
1691 ent = get_delta_base_cache_entry(p, curpos);
1692 if (ent) {
1693 type = ent->type;
1694 data = ent->data;
1695 size = ent->size;
1696 detach_delta_base_cache_entry(ent);
1697 base_from_cache = 1;
1698 break;
1701 if (do_check_packed_object_crc && p->index_version > 1) {
1702 uint32_t pack_pos, index_pos;
1703 off_t len;
1705 if (offset_to_pack_pos(p, obj_offset, &pack_pos) < 0) {
1706 error("could not find object at offset %"PRIuMAX" in pack %s",
1707 (uintmax_t)obj_offset, p->pack_name);
1708 data = NULL;
1709 goto out;
1712 len = pack_pos_to_offset(p, pack_pos + 1) - obj_offset;
1713 index_pos = pack_pos_to_index(p, pack_pos);
1714 if (check_pack_crc(p, &w_curs, obj_offset, len, index_pos)) {
1715 struct object_id oid;
1716 nth_packed_object_id(&oid, p, index_pos);
1717 error("bad packed object CRC for %s",
1718 oid_to_hex(&oid));
1719 mark_bad_packed_object(p, &oid);
1720 data = NULL;
1721 goto out;
1725 type = unpack_object_header(p, &w_curs, &curpos, &size);
1726 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1727 break;
1729 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1730 if (!base_offset) {
1731 error("failed to validate delta base reference "
1732 "at offset %"PRIuMAX" from %s",
1733 (uintmax_t)curpos, p->pack_name);
1734 /* bail to phase 2, in hopes of recovery */
1735 data = NULL;
1736 break;
1739 /* push object, proceed to base */
1740 if (delta_stack_nr >= delta_stack_alloc
1741 && delta_stack == small_delta_stack) {
1742 delta_stack_alloc = alloc_nr(delta_stack_nr);
1743 ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1744 COPY_ARRAY(delta_stack, small_delta_stack,
1745 delta_stack_nr);
1746 } else {
1747 ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1749 i = delta_stack_nr++;
1750 delta_stack[i].obj_offset = obj_offset;
1751 delta_stack[i].curpos = curpos;
1752 delta_stack[i].size = size;
1754 curpos = obj_offset = base_offset;
1757 /* PHASE 2: handle the base */
1758 switch (type) {
1759 case OBJ_OFS_DELTA:
1760 case OBJ_REF_DELTA:
1761 if (data)
1762 BUG("unpack_entry: left loop at a valid delta");
1763 break;
1764 case OBJ_COMMIT:
1765 case OBJ_TREE:
1766 case OBJ_BLOB:
1767 case OBJ_TAG:
1768 if (!base_from_cache)
1769 data = unpack_compressed_entry(p, &w_curs, curpos, size);
1770 break;
1771 default:
1772 data = NULL;
1773 error("unknown object type %i at offset %"PRIuMAX" in %s",
1774 type, (uintmax_t)obj_offset, p->pack_name);
1777 /* PHASE 3: apply deltas in order */
1779 /* invariants:
1780 * 'data' holds the base data, or NULL if there was corruption
1782 while (delta_stack_nr) {
1783 void *delta_data;
1784 void *base = data;
1785 void *external_base = NULL;
1786 unsigned long delta_size, base_size = size;
1787 int i;
1788 off_t base_obj_offset = obj_offset;
1790 data = NULL;
1792 if (!base) {
1794 * We're probably in deep shit, but let's try to fetch
1795 * the required base anyway from another pack or loose.
1796 * This is costly but should happen only in the presence
1797 * of a corrupted pack, and is better than failing outright.
1799 uint32_t pos;
1800 struct object_id base_oid;
1801 if (!(offset_to_pack_pos(p, obj_offset, &pos))) {
1802 struct object_info oi = OBJECT_INFO_INIT;
1804 nth_packed_object_id(&base_oid, p,
1805 pack_pos_to_index(p, pos));
1806 error("failed to read delta base object %s"
1807 " at offset %"PRIuMAX" from %s",
1808 oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1809 p->pack_name);
1810 mark_bad_packed_object(p, &base_oid);
1812 oi.typep = &type;
1813 oi.sizep = &base_size;
1814 oi.contentp = &base;
1815 if (oid_object_info_extended(r, &base_oid, &oi, 0) < 0)
1816 base = NULL;
1818 external_base = base;
1822 i = --delta_stack_nr;
1823 obj_offset = delta_stack[i].obj_offset;
1824 curpos = delta_stack[i].curpos;
1825 delta_size = delta_stack[i].size;
1827 if (!base)
1828 continue;
1830 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1832 if (!delta_data) {
1833 error("failed to unpack compressed delta "
1834 "at offset %"PRIuMAX" from %s",
1835 (uintmax_t)curpos, p->pack_name);
1836 data = NULL;
1837 } else {
1838 data = patch_delta(base, base_size, delta_data,
1839 delta_size, &size);
1842 * We could not apply the delta; warn the user, but
1843 * keep going. Our failure will be noticed either in
1844 * the next iteration of the loop, or if this is the
1845 * final delta, in the caller when we return NULL.
1846 * Those code paths will take care of making a more
1847 * explicit warning and retrying with another copy of
1848 * the object.
1850 if (!data)
1851 error("failed to apply delta");
1855 * We delay adding `base` to the cache until the end of the loop
1856 * because unpack_compressed_entry() momentarily releases the
1857 * obj_read_mutex, giving another thread the chance to access
1858 * the cache. Therefore, if `base` was already there, this other
1859 * thread could free() it (e.g. to make space for another entry)
1860 * before we are done using it.
1862 if (!external_base)
1863 add_delta_base_cache(p, base_obj_offset, base, base_size, type);
1865 free(delta_data);
1866 free(external_base);
1869 if (final_type)
1870 *final_type = type;
1871 if (final_size)
1872 *final_size = size;
1874 out:
1875 unuse_pack(&w_curs);
1877 if (delta_stack != small_delta_stack)
1878 free(delta_stack);
1880 return data;
1883 int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1885 const unsigned char *index_fanout = p->index_data;
1886 const unsigned char *index_lookup;
1887 const unsigned int hashsz = the_hash_algo->rawsz;
1888 int index_lookup_width;
1890 if (!index_fanout)
1891 BUG("bsearch_pack called without a valid pack-index");
1893 index_lookup = index_fanout + 4 * 256;
1894 if (p->index_version == 1) {
1895 index_lookup_width = hashsz + 4;
1896 index_lookup += 4;
1897 } else {
1898 index_lookup_width = hashsz;
1899 index_fanout += 8;
1900 index_lookup += 8;
1903 return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1904 index_lookup, index_lookup_width, result);
1907 int nth_packed_object_id(struct object_id *oid,
1908 struct packed_git *p,
1909 uint32_t n)
1911 const unsigned char *index = p->index_data;
1912 const unsigned int hashsz = the_hash_algo->rawsz;
1913 if (!index) {
1914 if (open_pack_index(p))
1915 return -1;
1916 index = p->index_data;
1918 if (n >= p->num_objects)
1919 return -1;
1920 index += 4 * 256;
1921 if (p->index_version == 1) {
1922 oidread(oid, index + st_add(st_mult(hashsz + 4, n), 4),
1923 the_repository->hash_algo);
1924 } else {
1925 index += 8;
1926 oidread(oid, index + st_mult(hashsz, n),
1927 the_repository->hash_algo);
1929 return 0;
1932 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1934 const unsigned char *ptr = vptr;
1935 const unsigned char *start = p->index_data;
1936 const unsigned char *end = start + p->index_size;
1937 if (ptr < start)
1938 die(_("offset before start of pack index for %s (corrupt index?)"),
1939 p->pack_name);
1940 /* No need to check for underflow; .idx files must be at least 8 bytes */
1941 if (ptr >= end - 8)
1942 die(_("offset beyond end of pack index for %s (truncated index?)"),
1943 p->pack_name);
1946 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1948 const unsigned char *index = p->index_data;
1949 const unsigned int hashsz = the_hash_algo->rawsz;
1950 index += 4 * 256;
1951 if (p->index_version == 1) {
1952 return ntohl(*((uint32_t *)(index + st_mult(hashsz + 4, n))));
1953 } else {
1954 uint32_t off;
1955 index += st_add(8, st_mult(p->num_objects, hashsz + 4));
1956 off = ntohl(*((uint32_t *)(index + st_mult(4, n))));
1957 if (!(off & 0x80000000))
1958 return off;
1959 index += st_add(st_mult(p->num_objects, 4),
1960 st_mult(off & 0x7fffffff, 8));
1961 check_pack_index_ptr(p, index);
1962 return get_be64(index);
1966 off_t find_pack_entry_one(const unsigned char *sha1,
1967 struct packed_git *p)
1969 const unsigned char *index = p->index_data;
1970 struct object_id oid;
1971 uint32_t result;
1973 if (!index) {
1974 if (open_pack_index(p))
1975 return 0;
1978 hashcpy(oid.hash, sha1, the_repository->hash_algo);
1979 if (bsearch_pack(&oid, p, &result))
1980 return nth_packed_object_offset(p, result);
1981 return 0;
1984 int is_pack_valid(struct packed_git *p)
1986 /* An already open pack is known to be valid. */
1987 if (p->pack_fd != -1)
1988 return 1;
1990 /* If the pack has one window completely covering the
1991 * file size, the pack is known to be valid even if
1992 * the descriptor is not currently open.
1994 if (p->windows) {
1995 struct pack_window *w = p->windows;
1997 if (!w->offset && w->len == p->pack_size)
1998 return 1;
2001 /* Force the pack to open to prove its valid. */
2002 return !open_packed_git(p);
2005 struct packed_git *find_sha1_pack(const unsigned char *sha1,
2006 struct packed_git *packs)
2008 struct packed_git *p;
2010 for (p = packs; p; p = p->next) {
2011 if (find_pack_entry_one(sha1, p))
2012 return p;
2014 return NULL;
2018 static int fill_pack_entry(const struct object_id *oid,
2019 struct pack_entry *e,
2020 struct packed_git *p)
2022 off_t offset;
2024 if (oidset_size(&p->bad_objects) &&
2025 oidset_contains(&p->bad_objects, oid))
2026 return 0;
2028 offset = find_pack_entry_one(oid->hash, p);
2029 if (!offset)
2030 return 0;
2033 * We are about to tell the caller where they can locate the
2034 * requested object. We better make sure the packfile is
2035 * still here and can be accessed before supplying that
2036 * answer, as it may have been deleted since the index was
2037 * loaded!
2039 if (!is_pack_valid(p))
2040 return 0;
2041 e->offset = offset;
2042 e->p = p;
2043 return 1;
2046 int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
2048 struct list_head *pos;
2049 struct multi_pack_index *m;
2051 prepare_packed_git(r);
2052 if (!r->objects->packed_git && !r->objects->multi_pack_index)
2053 return 0;
2055 for (m = r->objects->multi_pack_index; m; m = m->next) {
2056 if (fill_midx_entry(r, oid, e, m))
2057 return 1;
2060 list_for_each(pos, &r->objects->packed_git_mru) {
2061 struct packed_git *p = list_entry(pos, struct packed_git, mru);
2062 if (!p->multi_pack_index && fill_pack_entry(oid, e, p)) {
2063 list_move(&p->mru, &r->objects->packed_git_mru);
2064 return 1;
2067 return 0;
2070 static void maybe_invalidate_kept_pack_cache(struct repository *r,
2071 unsigned flags)
2073 if (!r->objects->kept_pack_cache.packs)
2074 return;
2075 if (r->objects->kept_pack_cache.flags == flags)
2076 return;
2077 FREE_AND_NULL(r->objects->kept_pack_cache.packs);
2078 r->objects->kept_pack_cache.flags = 0;
2081 static struct packed_git **kept_pack_cache(struct repository *r, unsigned flags)
2083 maybe_invalidate_kept_pack_cache(r, flags);
2085 if (!r->objects->kept_pack_cache.packs) {
2086 struct packed_git **packs = NULL;
2087 size_t nr = 0, alloc = 0;
2088 struct packed_git *p;
2091 * We want "all" packs here, because we need to cover ones that
2092 * are used by a midx, as well. We need to look in every one of
2093 * them (instead of the midx itself) to cover duplicates. It's
2094 * possible that an object is found in two packs that the midx
2095 * covers, one kept and one not kept, but the midx returns only
2096 * the non-kept version.
2098 for (p = get_all_packs(r); p; p = p->next) {
2099 if ((p->pack_keep && (flags & ON_DISK_KEEP_PACKS)) ||
2100 (p->pack_keep_in_core && (flags & IN_CORE_KEEP_PACKS))) {
2101 ALLOC_GROW(packs, nr + 1, alloc);
2102 packs[nr++] = p;
2105 ALLOC_GROW(packs, nr + 1, alloc);
2106 packs[nr] = NULL;
2108 r->objects->kept_pack_cache.packs = packs;
2109 r->objects->kept_pack_cache.flags = flags;
2112 return r->objects->kept_pack_cache.packs;
2115 int find_kept_pack_entry(struct repository *r,
2116 const struct object_id *oid,
2117 unsigned flags,
2118 struct pack_entry *e)
2120 struct packed_git **cache;
2122 for (cache = kept_pack_cache(r, flags); *cache; cache++) {
2123 struct packed_git *p = *cache;
2124 if (fill_pack_entry(oid, e, p))
2125 return 1;
2128 return 0;
2131 int has_object_pack(const struct object_id *oid)
2133 struct pack_entry e;
2134 return find_pack_entry(the_repository, oid, &e);
2137 int has_object_kept_pack(const struct object_id *oid, unsigned flags)
2139 struct pack_entry e;
2140 return find_kept_pack_entry(the_repository, oid, flags, &e);
2143 int has_pack_index(const unsigned char *sha1)
2145 struct stat st;
2146 if (stat(sha1_pack_index_name(sha1), &st))
2147 return 0;
2148 return 1;
2151 int for_each_object_in_pack(struct packed_git *p,
2152 each_packed_object_fn cb, void *data,
2153 enum for_each_object_flags flags)
2155 uint32_t i;
2156 int r = 0;
2158 if (flags & FOR_EACH_OBJECT_PACK_ORDER) {
2159 if (load_pack_revindex(the_repository, p))
2160 return -1;
2163 for (i = 0; i < p->num_objects; i++) {
2164 uint32_t index_pos;
2165 struct object_id oid;
2168 * We are iterating "i" from 0 up to num_objects, but its
2169 * meaning may be different, depending on the requested output
2170 * order:
2172 * - in object-name order, it is the same as the index order
2173 * used by nth_packed_object_id(), so we can pass it
2174 * directly
2176 * - in pack-order, it is pack position, which we must
2177 * convert to an index position in order to get the oid.
2179 if (flags & FOR_EACH_OBJECT_PACK_ORDER)
2180 index_pos = pack_pos_to_index(p, i);
2181 else
2182 index_pos = i;
2184 if (nth_packed_object_id(&oid, p, index_pos) < 0)
2185 return error("unable to get sha1 of object %u in %s",
2186 index_pos, p->pack_name);
2188 r = cb(&oid, p, index_pos, data);
2189 if (r)
2190 break;
2192 return r;
2195 int for_each_packed_object(each_packed_object_fn cb, void *data,
2196 enum for_each_object_flags flags)
2198 struct packed_git *p;
2199 int r = 0;
2200 int pack_errors = 0;
2202 prepare_packed_git(the_repository);
2203 for (p = get_all_packs(the_repository); p; p = p->next) {
2204 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
2205 continue;
2206 if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
2207 !p->pack_promisor)
2208 continue;
2209 if ((flags & FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS) &&
2210 p->pack_keep_in_core)
2211 continue;
2212 if ((flags & FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS) &&
2213 p->pack_keep)
2214 continue;
2215 if (open_pack_index(p)) {
2216 pack_errors = 1;
2217 continue;
2219 r = for_each_object_in_pack(p, cb, data, flags);
2220 if (r)
2221 break;
2223 return r ? r : pack_errors;
2226 static int add_promisor_object(const struct object_id *oid,
2227 struct packed_git *pack UNUSED,
2228 uint32_t pos UNUSED,
2229 void *set_)
2231 struct oidset *set = set_;
2232 struct object *obj;
2233 int we_parsed_object;
2235 obj = lookup_object(the_repository, oid);
2236 if (obj && obj->parsed) {
2237 we_parsed_object = 0;
2238 } else {
2239 we_parsed_object = 1;
2240 obj = parse_object(the_repository, oid);
2243 if (!obj)
2244 return 1;
2246 oidset_insert(set, oid);
2249 * If this is a tree, commit, or tag, the objects it refers
2250 * to are also promisor objects. (Blobs refer to no objects->)
2252 if (obj->type == OBJ_TREE) {
2253 struct tree *tree = (struct tree *)obj;
2254 struct tree_desc desc;
2255 struct name_entry entry;
2256 if (init_tree_desc_gently(&desc, &tree->object.oid,
2257 tree->buffer, tree->size, 0))
2259 * Error messages are given when packs are
2260 * verified, so do not print any here.
2262 return 0;
2263 while (tree_entry_gently(&desc, &entry))
2264 oidset_insert(set, &entry.oid);
2265 if (we_parsed_object)
2266 free_tree_buffer(tree);
2267 } else if (obj->type == OBJ_COMMIT) {
2268 struct commit *commit = (struct commit *) obj;
2269 struct commit_list *parents = commit->parents;
2271 oidset_insert(set, get_commit_tree_oid(commit));
2272 for (; parents; parents = parents->next)
2273 oidset_insert(set, &parents->item->object.oid);
2274 } else if (obj->type == OBJ_TAG) {
2275 struct tag *tag = (struct tag *) obj;
2276 oidset_insert(set, get_tagged_oid(tag));
2278 return 0;
2281 int is_promisor_object(const struct object_id *oid)
2283 static struct oidset promisor_objects;
2284 static int promisor_objects_prepared;
2286 if (!promisor_objects_prepared) {
2287 if (repo_has_promisor_remote(the_repository)) {
2288 for_each_packed_object(add_promisor_object,
2289 &promisor_objects,
2290 FOR_EACH_OBJECT_PROMISOR_ONLY |
2291 FOR_EACH_OBJECT_PACK_ORDER);
2293 promisor_objects_prepared = 1;
2295 return oidset_contains(&promisor_objects, oid);