packfile: remove redundant fcntl F_GETFD/F_SETFD
[git] / packfile.c
1 #include "cache.h"
2 #include "list.h"
3 #include "pack.h"
4 #include "repository.h"
5 #include "dir.h"
6 #include "mergesort.h"
7 #include "packfile.h"
8 #include "delta.h"
9 #include "list.h"
10 #include "streaming.h"
11 #include "sha1-lookup.h"
12 #include "commit.h"
13 #include "object.h"
14 #include "tag.h"
15 #include "tree-walk.h"
16 #include "tree.h"
17 #include "object-store.h"
18 #include "midx.h"
19 #include "commit-graph.h"
20
21 char *odb_pack_name(struct strbuf *buf,
22                     const unsigned char *sha1,
23                     const char *ext)
24 {
25         strbuf_reset(buf);
26         strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
27                     sha1_to_hex(sha1), ext);
28         return buf->buf;
29 }
30
31 char *sha1_pack_name(const unsigned char *sha1)
32 {
33         static struct strbuf buf = STRBUF_INIT;
34         return odb_pack_name(&buf, sha1, "pack");
35 }
36
37 char *sha1_pack_index_name(const unsigned char *sha1)
38 {
39         static struct strbuf buf = STRBUF_INIT;
40         return odb_pack_name(&buf, sha1, "idx");
41 }
42
43 static unsigned int pack_used_ctr;
44 static unsigned int pack_mmap_calls;
45 static unsigned int peak_pack_open_windows;
46 static unsigned int pack_open_windows;
47 static unsigned int pack_open_fds;
48 static unsigned int pack_max_fds;
49 static size_t peak_pack_mapped;
50 static size_t pack_mapped;
51
52 #define SZ_FMT PRIuMAX
53 static inline uintmax_t sz_fmt(size_t s) { return s; }
54
55 void pack_report(void)
56 {
57         fprintf(stderr,
58                 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
59                 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
60                 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
61                 sz_fmt(getpagesize()),
62                 sz_fmt(packed_git_window_size),
63                 sz_fmt(packed_git_limit));
64         fprintf(stderr,
65                 "pack_report: pack_used_ctr            = %10u\n"
66                 "pack_report: pack_mmap_calls          = %10u\n"
67                 "pack_report: pack_open_windows        = %10u / %10u\n"
68                 "pack_report: pack_mapped              = "
69                         "%10" SZ_FMT " / %10" SZ_FMT "\n",
70                 pack_used_ctr,
71                 pack_mmap_calls,
72                 pack_open_windows, peak_pack_open_windows,
73                 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
74 }
75
76 /*
77  * Open and mmap the index file at path, perform a couple of
78  * consistency checks, then record its information to p.  Return 0 on
79  * success.
80  */
81 static int check_packed_git_idx(const char *path, struct packed_git *p)
82 {
83         void *idx_map;
84         size_t idx_size;
85         int fd = git_open(path), ret;
86         struct stat st;
87         const unsigned int hashsz = the_hash_algo->rawsz;
88
89         if (fd < 0)
90                 return -1;
91         if (fstat(fd, &st)) {
92                 close(fd);
93                 return -1;
94         }
95         idx_size = xsize_t(st.st_size);
96         if (idx_size < 4 * 256 + hashsz + hashsz) {
97                 close(fd);
98                 return error("index file %s is too small", path);
99         }
100         idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
101         close(fd);
102
103         ret = load_idx(path, hashsz, idx_map, idx_size, p);
104
105         if (ret)
106                 munmap(idx_map, idx_size);
107
108         return ret;
109 }
110
111 int load_idx(const char *path, const unsigned int hashsz, void *idx_map,
112              size_t idx_size, struct packed_git *p)
113 {
114         struct pack_idx_header *hdr = idx_map;
115         uint32_t version, nr, i, *index;
116
117         if (idx_size < 4 * 256 + hashsz + hashsz)
118                 return error("index file %s is too small", path);
119         if (idx_map == NULL)
120                 return error("empty data");
121
122         if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
123                 version = ntohl(hdr->idx_version);
124                 if (version < 2 || version > 2)
125                         return error("index file %s is version %"PRIu32
126                                      " and is not supported by this binary"
127                                      " (try upgrading GIT to a newer version)",
128                                      path, version);
129         } else
130                 version = 1;
131
132         nr = 0;
133         index = idx_map;
134         if (version > 1)
135                 index += 2;  /* skip index header */
136         for (i = 0; i < 256; i++) {
137                 uint32_t n = ntohl(index[i]);
138                 if (n < nr)
139                         return error("non-monotonic index %s", path);
140                 nr = n;
141         }
142
143         if (version == 1) {
144                 /*
145                  * Total size:
146                  *  - 256 index entries 4 bytes each
147                  *  - 24-byte entries * nr (object ID + 4-byte offset)
148                  *  - hash of the packfile
149                  *  - file checksum
150                  */
151                 if (idx_size != 4 * 256 + nr * (hashsz + 4) + hashsz + hashsz)
152                         return error("wrong index v1 file size in %s", path);
153         } else if (version == 2) {
154                 /*
155                  * Minimum size:
156                  *  - 8 bytes of header
157                  *  - 256 index entries 4 bytes each
158                  *  - object ID entry * nr
159                  *  - 4-byte crc entry * nr
160                  *  - 4-byte offset entry * nr
161                  *  - hash of the packfile
162                  *  - file checksum
163                  * And after the 4-byte offset table might be a
164                  * variable sized table containing 8-byte entries
165                  * for offsets larger than 2^31.
166                  */
167                 unsigned long min_size = 8 + 4*256 + nr*(hashsz + 4 + 4) + hashsz + hashsz;
168                 unsigned long max_size = min_size;
169                 if (nr)
170                         max_size += (nr - 1)*8;
171                 if (idx_size < min_size || idx_size > max_size)
172                         return error("wrong index v2 file size in %s", path);
173                 if (idx_size != min_size &&
174                     /*
175                      * make sure we can deal with large pack offsets.
176                      * 31-bit signed offset won't be enough, neither
177                      * 32-bit unsigned one will be.
178                      */
179                     (sizeof(off_t) <= 4))
180                         return error("pack too large for current definition of off_t in %s", path);
181         }
182
183         p->index_version = version;
184         p->index_data = idx_map;
185         p->index_size = idx_size;
186         p->num_objects = nr;
187         return 0;
188 }
189
190 int open_pack_index(struct packed_git *p)
191 {
192         char *idx_name;
193         size_t len;
194         int ret;
195
196         if (p->index_data)
197                 return 0;
198
199         if (!strip_suffix(p->pack_name, ".pack", &len))
200                 BUG("pack_name does not end in .pack");
201         idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
202         ret = check_packed_git_idx(idx_name, p);
203         free(idx_name);
204         return ret;
205 }
206
207 uint32_t get_pack_fanout(struct packed_git *p, uint32_t value)
208 {
209         const uint32_t *level1_ofs = p->index_data;
210
211         if (!level1_ofs) {
212                 if (open_pack_index(p))
213                         return 0;
214                 level1_ofs = p->index_data;
215         }
216
217         if (p->index_version > 1) {
218                 level1_ofs += 2;
219         }
220
221         return ntohl(level1_ofs[value]);
222 }
223
224 static struct packed_git *alloc_packed_git(int extra)
225 {
226         struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
227         memset(p, 0, sizeof(*p));
228         p->pack_fd = -1;
229         return p;
230 }
231
232 struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
233 {
234         const char *path = sha1_pack_name(sha1);
235         size_t alloc = st_add(strlen(path), 1);
236         struct packed_git *p = alloc_packed_git(alloc);
237
238         memcpy(p->pack_name, path, alloc); /* includes NUL */
239         hashcpy(p->hash, sha1);
240         if (check_packed_git_idx(idx_path, p)) {
241                 free(p);
242                 return NULL;
243         }
244
245         return p;
246 }
247
248 static void scan_windows(struct packed_git *p,
249         struct packed_git **lru_p,
250         struct pack_window **lru_w,
251         struct pack_window **lru_l)
252 {
253         struct pack_window *w, *w_l;
254
255         for (w_l = NULL, w = p->windows; w; w = w->next) {
256                 if (!w->inuse_cnt) {
257                         if (!*lru_w || w->last_used < (*lru_w)->last_used) {
258                                 *lru_p = p;
259                                 *lru_w = w;
260                                 *lru_l = w_l;
261                         }
262                 }
263                 w_l = w;
264         }
265 }
266
267 static int unuse_one_window(struct packed_git *current)
268 {
269         struct packed_git *p, *lru_p = NULL;
270         struct pack_window *lru_w = NULL, *lru_l = NULL;
271
272         if (current)
273                 scan_windows(current, &lru_p, &lru_w, &lru_l);
274         for (p = the_repository->objects->packed_git; p; p = p->next)
275                 scan_windows(p, &lru_p, &lru_w, &lru_l);
276         if (lru_p) {
277                 munmap(lru_w->base, lru_w->len);
278                 pack_mapped -= lru_w->len;
279                 if (lru_l)
280                         lru_l->next = lru_w->next;
281                 else
282                         lru_p->windows = lru_w->next;
283                 free(lru_w);
284                 pack_open_windows--;
285                 return 1;
286         }
287         return 0;
288 }
289
290 void release_pack_memory(size_t need)
291 {
292         size_t cur = pack_mapped;
293         while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
294                 ; /* nothing */
295 }
296
297 void close_pack_windows(struct packed_git *p)
298 {
299         while (p->windows) {
300                 struct pack_window *w = p->windows;
301
302                 if (w->inuse_cnt)
303                         die("pack '%s' still has open windows to it",
304                             p->pack_name);
305                 munmap(w->base, w->len);
306                 pack_mapped -= w->len;
307                 pack_open_windows--;
308                 p->windows = w->next;
309                 free(w);
310         }
311 }
312
313 int close_pack_fd(struct packed_git *p)
314 {
315         if (p->pack_fd < 0)
316                 return 0;
317
318         close(p->pack_fd);
319         pack_open_fds--;
320         p->pack_fd = -1;
321
322         return 1;
323 }
324
325 void close_pack_index(struct packed_git *p)
326 {
327         if (p->index_data) {
328                 munmap((void *)p->index_data, p->index_size);
329                 p->index_data = NULL;
330         }
331 }
332
333 void close_pack(struct packed_git *p)
334 {
335         close_pack_windows(p);
336         close_pack_fd(p);
337         close_pack_index(p);
338 }
339
340 void close_object_store(struct raw_object_store *o)
341 {
342         struct packed_git *p;
343
344         for (p = o->packed_git; p; p = p->next)
345                 if (p->do_not_close)
346                         BUG("want to close pack marked 'do-not-close'");
347                 else
348                         close_pack(p);
349
350         if (o->multi_pack_index) {
351                 close_midx(o->multi_pack_index);
352                 o->multi_pack_index = NULL;
353         }
354
355         close_commit_graph(o);
356 }
357
358 /*
359  * The LRU pack is the one with the oldest MRU window, preferring packs
360  * with no used windows, or the oldest mtime if it has no windows allocated.
361  */
362 static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
363 {
364         struct pack_window *w, *this_mru_w;
365         int has_windows_inuse = 0;
366
367         /*
368          * Reject this pack if it has windows and the previously selected
369          * one does not.  If this pack does not have windows, reject
370          * it if the pack file is newer than the previously selected one.
371          */
372         if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
373                 return;
374
375         for (w = this_mru_w = p->windows; w; w = w->next) {
376                 /*
377                  * Reject this pack if any of its windows are in use,
378                  * but the previously selected pack did not have any
379                  * inuse windows.  Otherwise, record that this pack
380                  * has windows in use.
381                  */
382                 if (w->inuse_cnt) {
383                         if (*accept_windows_inuse)
384                                 has_windows_inuse = 1;
385                         else
386                                 return;
387                 }
388
389                 if (w->last_used > this_mru_w->last_used)
390                         this_mru_w = w;
391
392                 /*
393                  * Reject this pack if it has windows that have been
394                  * used more recently than the previously selected pack.
395                  * If the previously selected pack had windows inuse and
396                  * we have not encountered a window in this pack that is
397                  * inuse, skip this check since we prefer a pack with no
398                  * inuse windows to one that has inuse windows.
399                  */
400                 if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
401                     this_mru_w->last_used > (*mru_w)->last_used)
402                         return;
403         }
404
405         /*
406          * Select this pack.
407          */
408         *mru_w = this_mru_w;
409         *lru_p = p;
410         *accept_windows_inuse = has_windows_inuse;
411 }
412
413 static int close_one_pack(void)
414 {
415         struct packed_git *p, *lru_p = NULL;
416         struct pack_window *mru_w = NULL;
417         int accept_windows_inuse = 1;
418
419         for (p = the_repository->objects->packed_git; p; p = p->next) {
420                 if (p->pack_fd == -1)
421                         continue;
422                 find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
423         }
424
425         if (lru_p)
426                 return close_pack_fd(lru_p);
427
428         return 0;
429 }
430
431 static unsigned int get_max_fd_limit(void)
432 {
433 #ifdef RLIMIT_NOFILE
434         {
435                 struct rlimit lim;
436
437                 if (!getrlimit(RLIMIT_NOFILE, &lim))
438                         return lim.rlim_cur;
439         }
440 #endif
441
442 #ifdef _SC_OPEN_MAX
443         {
444                 long open_max = sysconf(_SC_OPEN_MAX);
445                 if (0 < open_max)
446                         return open_max;
447                 /*
448                  * Otherwise, we got -1 for one of the two
449                  * reasons:
450                  *
451                  * (1) sysconf() did not understand _SC_OPEN_MAX
452                  *     and signaled an error with -1; or
453                  * (2) sysconf() said there is no limit.
454                  *
455                  * We _could_ clear errno before calling sysconf() to
456                  * tell these two cases apart and return a huge number
457                  * in the latter case to let the caller cap it to a
458                  * value that is not so selfish, but letting the
459                  * fallback OPEN_MAX codepath take care of these cases
460                  * is a lot simpler.
461                  */
462         }
463 #endif
464
465 #ifdef OPEN_MAX
466         return OPEN_MAX;
467 #else
468         return 1; /* see the caller ;-) */
469 #endif
470 }
471
472 const char *pack_basename(struct packed_git *p)
473 {
474         const char *ret = strrchr(p->pack_name, '/');
475         if (ret)
476                 ret = ret + 1; /* skip past slash */
477         else
478                 ret = p->pack_name; /* we only have a base */
479         return ret;
480 }
481
482 /*
483  * Do not call this directly as this leaks p->pack_fd on error return;
484  * call open_packed_git() instead.
485  */
486 static int open_packed_git_1(struct packed_git *p)
487 {
488         struct stat st;
489         struct pack_header hdr;
490         unsigned char hash[GIT_MAX_RAWSZ];
491         unsigned char *idx_hash;
492         ssize_t read_result;
493         const unsigned hashsz = the_hash_algo->rawsz;
494
495         if (!p->index_data) {
496                 struct multi_pack_index *m;
497                 const char *pack_name = pack_basename(p);
498
499                 for (m = the_repository->objects->multi_pack_index;
500                      m; m = m->next) {
501                         if (midx_contains_pack(m, pack_name))
502                                 break;
503                 }
504
505                 if (!m && open_pack_index(p))
506                         return error("packfile %s index unavailable", p->pack_name);
507         }
508
509         if (!pack_max_fds) {
510                 unsigned int max_fds = get_max_fd_limit();
511
512                 /* Save 3 for stdin/stdout/stderr, 22 for work */
513                 if (25 < max_fds)
514                         pack_max_fds = max_fds - 25;
515                 else
516                         pack_max_fds = 1;
517         }
518
519         while (pack_max_fds <= pack_open_fds && close_one_pack())
520                 ; /* nothing */
521
522         p->pack_fd = git_open(p->pack_name);
523         if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
524                 return -1;
525         pack_open_fds++;
526
527         /* If we created the struct before we had the pack we lack size. */
528         if (!p->pack_size) {
529                 if (!S_ISREG(st.st_mode))
530                         return error("packfile %s not a regular file", p->pack_name);
531                 p->pack_size = st.st_size;
532         } else if (p->pack_size != st.st_size)
533                 return error("packfile %s size changed", p->pack_name);
534
535         /* Verify we recognize this pack file format. */
536         read_result = read_in_full(p->pack_fd, &hdr, sizeof(hdr));
537         if (read_result < 0)
538                 return error_errno("error reading from %s", p->pack_name);
539         if (read_result != sizeof(hdr))
540                 return error("file %s is far too short to be a packfile", p->pack_name);
541         if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
542                 return error("file %s is not a GIT packfile", p->pack_name);
543         if (!pack_version_ok(hdr.hdr_version))
544                 return error("packfile %s is version %"PRIu32" and not"
545                         " supported (try upgrading GIT to a newer version)",
546                         p->pack_name, ntohl(hdr.hdr_version));
547
548         /* Skip index checking if in multi-pack-index */
549         if (!p->index_data)
550                 return 0;
551
552         /* Verify the pack matches its index. */
553         if (p->num_objects != ntohl(hdr.hdr_entries))
554                 return error("packfile %s claims to have %"PRIu32" objects"
555                              " while index indicates %"PRIu32" objects",
556                              p->pack_name, ntohl(hdr.hdr_entries),
557                              p->num_objects);
558         if (lseek(p->pack_fd, p->pack_size - hashsz, SEEK_SET) == -1)
559                 return error("end of packfile %s is unavailable", p->pack_name);
560         read_result = read_in_full(p->pack_fd, hash, hashsz);
561         if (read_result < 0)
562                 return error_errno("error reading from %s", p->pack_name);
563         if (read_result != hashsz)
564                 return error("packfile %s signature is unavailable", p->pack_name);
565         idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
566         if (!hasheq(hash, idx_hash))
567                 return error("packfile %s does not match index", p->pack_name);
568         return 0;
569 }
570
571 static int open_packed_git(struct packed_git *p)
572 {
573         if (!open_packed_git_1(p))
574                 return 0;
575         close_pack_fd(p);
576         return -1;
577 }
578
579 static int in_window(struct pack_window *win, off_t offset)
580 {
581         /* We must promise at least one full hash after the
582          * offset is available from this window, otherwise the offset
583          * is not actually in this window and a different window (which
584          * has that one hash excess) must be used.  This is to support
585          * the object header and delta base parsing routines below.
586          */
587         off_t win_off = win->offset;
588         return win_off <= offset
589                 && (offset + the_hash_algo->rawsz) <= (win_off + win->len);
590 }
591
592 unsigned char *use_pack(struct packed_git *p,
593                 struct pack_window **w_cursor,
594                 off_t offset,
595                 unsigned long *left)
596 {
597         struct pack_window *win = *w_cursor;
598
599         /* Since packfiles end in a hash of their content and it's
600          * pointless to ask for an offset into the middle of that
601          * hash, and the in_window function above wouldn't match
602          * don't allow an offset too close to the end of the file.
603          */
604         if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
605                 die("packfile %s cannot be accessed", p->pack_name);
606         if (offset > (p->pack_size - the_hash_algo->rawsz))
607                 die("offset beyond end of packfile (truncated pack?)");
608         if (offset < 0)
609                 die(_("offset before end of packfile (broken .idx?)"));
610
611         if (!win || !in_window(win, offset)) {
612                 if (win)
613                         win->inuse_cnt--;
614                 for (win = p->windows; win; win = win->next) {
615                         if (in_window(win, offset))
616                                 break;
617                 }
618                 if (!win) {
619                         size_t window_align = packed_git_window_size / 2;
620                         off_t len;
621
622                         if (p->pack_fd == -1 && open_packed_git(p))
623                                 die("packfile %s cannot be accessed", p->pack_name);
624
625                         win = xcalloc(1, sizeof(*win));
626                         win->offset = (offset / window_align) * window_align;
627                         len = p->pack_size - win->offset;
628                         if (len > packed_git_window_size)
629                                 len = packed_git_window_size;
630                         win->len = (size_t)len;
631                         pack_mapped += win->len;
632                         while (packed_git_limit < pack_mapped
633                                 && unuse_one_window(p))
634                                 ; /* nothing */
635                         win->base = xmmap_gently(NULL, win->len,
636                                 PROT_READ, MAP_PRIVATE,
637                                 p->pack_fd, win->offset);
638                         if (win->base == MAP_FAILED)
639                                 die_errno("packfile %s cannot be mapped",
640                                           p->pack_name);
641                         if (!win->offset && win->len == p->pack_size
642                                 && !p->do_not_close)
643                                 close_pack_fd(p);
644                         pack_mmap_calls++;
645                         pack_open_windows++;
646                         if (pack_mapped > peak_pack_mapped)
647                                 peak_pack_mapped = pack_mapped;
648                         if (pack_open_windows > peak_pack_open_windows)
649                                 peak_pack_open_windows = pack_open_windows;
650                         win->next = p->windows;
651                         p->windows = win;
652                 }
653         }
654         if (win != *w_cursor) {
655                 win->last_used = pack_used_ctr++;
656                 win->inuse_cnt++;
657                 *w_cursor = win;
658         }
659         offset -= win->offset;
660         if (left)
661                 *left = win->len - xsize_t(offset);
662         return win->base + offset;
663 }
664
665 void unuse_pack(struct pack_window **w_cursor)
666 {
667         struct pack_window *w = *w_cursor;
668         if (w) {
669                 w->inuse_cnt--;
670                 *w_cursor = NULL;
671         }
672 }
673
674 static void try_to_free_pack_memory(size_t size)
675 {
676         release_pack_memory(size);
677 }
678
679 struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
680 {
681         static int have_set_try_to_free_routine;
682         struct stat st;
683         size_t alloc;
684         struct packed_git *p;
685
686         if (!have_set_try_to_free_routine) {
687                 have_set_try_to_free_routine = 1;
688                 set_try_to_free_routine(try_to_free_pack_memory);
689         }
690
691         /*
692          * Make sure a corresponding .pack file exists and that
693          * the index looks sane.
694          */
695         if (!strip_suffix_mem(path, &path_len, ".idx"))
696                 return NULL;
697
698         /*
699          * ".promisor" is long enough to hold any suffix we're adding (and
700          * the use xsnprintf double-checks that)
701          */
702         alloc = st_add3(path_len, strlen(".promisor"), 1);
703         p = alloc_packed_git(alloc);
704         memcpy(p->pack_name, path, path_len);
705
706         xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
707         if (!access(p->pack_name, F_OK))
708                 p->pack_keep = 1;
709
710         xsnprintf(p->pack_name + path_len, alloc - path_len, ".promisor");
711         if (!access(p->pack_name, F_OK))
712                 p->pack_promisor = 1;
713
714         xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
715         if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
716                 free(p);
717                 return NULL;
718         }
719
720         /* ok, it looks sane as far as we can check without
721          * actually mapping the pack file.
722          */
723         p->pack_size = st.st_size;
724         p->pack_local = local;
725         p->mtime = st.st_mtime;
726         if (path_len < the_hash_algo->hexsz ||
727             get_sha1_hex(path + path_len - the_hash_algo->hexsz, p->hash))
728                 hashclr(p->hash);
729         return p;
730 }
731
732 void install_packed_git(struct repository *r, struct packed_git *pack)
733 {
734         if (pack->pack_fd != -1)
735                 pack_open_fds++;
736
737         pack->next = r->objects->packed_git;
738         r->objects->packed_git = pack;
739 }
740
741 void (*report_garbage)(unsigned seen_bits, const char *path);
742
743 static void report_helper(const struct string_list *list,
744                           int seen_bits, int first, int last)
745 {
746         if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
747                 return;
748
749         for (; first < last; first++)
750                 report_garbage(seen_bits, list->items[first].string);
751 }
752
753 static void report_pack_garbage(struct string_list *list)
754 {
755         int i, baselen = -1, first = 0, seen_bits = 0;
756
757         if (!report_garbage)
758                 return;
759
760         string_list_sort(list);
761
762         for (i = 0; i < list->nr; i++) {
763                 const char *path = list->items[i].string;
764                 if (baselen != -1 &&
765                     strncmp(path, list->items[first].string, baselen)) {
766                         report_helper(list, seen_bits, first, i);
767                         baselen = -1;
768                         seen_bits = 0;
769                 }
770                 if (baselen == -1) {
771                         const char *dot = strrchr(path, '.');
772                         if (!dot) {
773                                 report_garbage(PACKDIR_FILE_GARBAGE, path);
774                                 continue;
775                         }
776                         baselen = dot - path + 1;
777                         first = i;
778                 }
779                 if (!strcmp(path + baselen, "pack"))
780                         seen_bits |= 1;
781                 else if (!strcmp(path + baselen, "idx"))
782                         seen_bits |= 2;
783         }
784         report_helper(list, seen_bits, first, list->nr);
785 }
786
787 void for_each_file_in_pack_dir(const char *objdir,
788                                each_file_in_pack_dir_fn fn,
789                                void *data)
790 {
791         struct strbuf path = STRBUF_INIT;
792         size_t dirnamelen;
793         DIR *dir;
794         struct dirent *de;
795
796         strbuf_addstr(&path, objdir);
797         strbuf_addstr(&path, "/pack");
798         dir = opendir(path.buf);
799         if (!dir) {
800                 if (errno != ENOENT)
801                         error_errno("unable to open object pack directory: %s",
802                                     path.buf);
803                 strbuf_release(&path);
804                 return;
805         }
806         strbuf_addch(&path, '/');
807         dirnamelen = path.len;
808         while ((de = readdir(dir)) != NULL) {
809                 if (is_dot_or_dotdot(de->d_name))
810                         continue;
811
812                 strbuf_setlen(&path, dirnamelen);
813                 strbuf_addstr(&path, de->d_name);
814
815                 fn(path.buf, path.len, de->d_name, data);
816         }
817
818         closedir(dir);
819         strbuf_release(&path);
820 }
821
822 struct prepare_pack_data {
823         struct repository *r;
824         struct string_list *garbage;
825         int local;
826         struct multi_pack_index *m;
827 };
828
829 static void prepare_pack(const char *full_name, size_t full_name_len,
830                          const char *file_name, void *_data)
831 {
832         struct prepare_pack_data *data = (struct prepare_pack_data *)_data;
833         struct packed_git *p;
834         size_t base_len = full_name_len;
835
836         if (strip_suffix_mem(full_name, &base_len, ".idx") &&
837             !(data->m && midx_contains_pack(data->m, file_name))) {
838                 /* Don't reopen a pack we already have. */
839                 for (p = data->r->objects->packed_git; p; p = p->next) {
840                         size_t len;
841                         if (strip_suffix(p->pack_name, ".pack", &len) &&
842                             len == base_len &&
843                             !memcmp(p->pack_name, full_name, len))
844                                 break;
845                 }
846
847                 if (!p) {
848                         p = add_packed_git(full_name, full_name_len, data->local);
849                         if (p)
850                                 install_packed_git(data->r, p);
851                 }
852         }
853
854         if (!report_garbage)
855                 return;
856
857         if (!strcmp(file_name, "multi-pack-index"))
858                 return;
859         if (ends_with(file_name, ".idx") ||
860             ends_with(file_name, ".pack") ||
861             ends_with(file_name, ".bitmap") ||
862             ends_with(file_name, ".keep") ||
863             ends_with(file_name, ".promisor"))
864                 string_list_append(data->garbage, full_name);
865         else
866                 report_garbage(PACKDIR_FILE_GARBAGE, full_name);
867 }
868
869 static void prepare_packed_git_one(struct repository *r, char *objdir, int local)
870 {
871         struct prepare_pack_data data;
872         struct string_list garbage = STRING_LIST_INIT_DUP;
873
874         data.m = r->objects->multi_pack_index;
875
876         /* look for the multi-pack-index for this object directory */
877         while (data.m && strcmp(data.m->object_dir, objdir))
878                 data.m = data.m->next;
879
880         data.r = r;
881         data.garbage = &garbage;
882         data.local = local;
883
884         for_each_file_in_pack_dir(objdir, prepare_pack, &data);
885
886         report_pack_garbage(data.garbage);
887         string_list_clear(data.garbage, 0);
888 }
889
890 static void prepare_packed_git(struct repository *r);
891 /*
892  * Give a fast, rough count of the number of objects in the repository. This
893  * ignores loose objects completely. If you have a lot of them, then either
894  * you should repack because your performance will be awful, or they are
895  * all unreachable objects about to be pruned, in which case they're not really
896  * interesting as a measure of repo size in the first place.
897  */
898 unsigned long repo_approximate_object_count(struct repository *r)
899 {
900         if (!r->objects->approximate_object_count_valid) {
901                 unsigned long count;
902                 struct multi_pack_index *m;
903                 struct packed_git *p;
904
905                 prepare_packed_git(r);
906                 count = 0;
907                 for (m = get_multi_pack_index(r); m; m = m->next)
908                         count += m->num_objects;
909                 for (p = r->objects->packed_git; p; p = p->next) {
910                         if (open_pack_index(p))
911                                 continue;
912                         count += p->num_objects;
913                 }
914                 r->objects->approximate_object_count = count;
915         }
916         return r->objects->approximate_object_count;
917 }
918
919 static void *get_next_packed_git(const void *p)
920 {
921         return ((const struct packed_git *)p)->next;
922 }
923
924 static void set_next_packed_git(void *p, void *next)
925 {
926         ((struct packed_git *)p)->next = next;
927 }
928
929 static int sort_pack(const void *a_, const void *b_)
930 {
931         const struct packed_git *a = a_;
932         const struct packed_git *b = b_;
933         int st;
934
935         /*
936          * Local packs tend to contain objects specific to our
937          * variant of the project than remote ones.  In addition,
938          * remote ones could be on a network mounted filesystem.
939          * Favor local ones for these reasons.
940          */
941         st = a->pack_local - b->pack_local;
942         if (st)
943                 return -st;
944
945         /*
946          * Younger packs tend to contain more recent objects,
947          * and more recent objects tend to get accessed more
948          * often.
949          */
950         if (a->mtime < b->mtime)
951                 return 1;
952         else if (a->mtime == b->mtime)
953                 return 0;
954         return -1;
955 }
956
957 static void rearrange_packed_git(struct repository *r)
958 {
959         r->objects->packed_git = llist_mergesort(
960                 r->objects->packed_git, get_next_packed_git,
961                 set_next_packed_git, sort_pack);
962 }
963
964 static void prepare_packed_git_mru(struct repository *r)
965 {
966         struct packed_git *p;
967
968         INIT_LIST_HEAD(&r->objects->packed_git_mru);
969
970         for (p = r->objects->packed_git; p; p = p->next)
971                 list_add_tail(&p->mru, &r->objects->packed_git_mru);
972 }
973
974 static void prepare_packed_git(struct repository *r)
975 {
976         struct object_directory *odb;
977
978         if (r->objects->packed_git_initialized)
979                 return;
980
981         prepare_alt_odb(r);
982         for (odb = r->objects->odb; odb; odb = odb->next) {
983                 int local = (odb == r->objects->odb);
984                 prepare_multi_pack_index_one(r, odb->path, local);
985                 prepare_packed_git_one(r, odb->path, local);
986         }
987         rearrange_packed_git(r);
988
989         prepare_packed_git_mru(r);
990         r->objects->packed_git_initialized = 1;
991 }
992
993 void reprepare_packed_git(struct repository *r)
994 {
995         struct object_directory *odb;
996
997         for (odb = r->objects->odb; odb; odb = odb->next)
998                 odb_clear_loose_cache(odb);
999
1000         r->objects->approximate_object_count_valid = 0;
1001         r->objects->packed_git_initialized = 0;
1002         prepare_packed_git(r);
1003 }
1004
1005 struct packed_git *get_packed_git(struct repository *r)
1006 {
1007         prepare_packed_git(r);
1008         return r->objects->packed_git;
1009 }
1010
1011 struct multi_pack_index *get_multi_pack_index(struct repository *r)
1012 {
1013         prepare_packed_git(r);
1014         return r->objects->multi_pack_index;
1015 }
1016
1017 struct packed_git *get_all_packs(struct repository *r)
1018 {
1019         struct multi_pack_index *m;
1020
1021         prepare_packed_git(r);
1022         for (m = r->objects->multi_pack_index; m; m = m->next) {
1023                 uint32_t i;
1024                 for (i = 0; i < m->num_packs; i++)
1025                         prepare_midx_pack(r, m, i);
1026         }
1027
1028         return r->objects->packed_git;
1029 }
1030
1031 struct list_head *get_packed_git_mru(struct repository *r)
1032 {
1033         prepare_packed_git(r);
1034         return &r->objects->packed_git_mru;
1035 }
1036
1037 unsigned long unpack_object_header_buffer(const unsigned char *buf,
1038                 unsigned long len, enum object_type *type, unsigned long *sizep)
1039 {
1040         unsigned shift;
1041         unsigned long size, c;
1042         unsigned long used = 0;
1043
1044         c = buf[used++];
1045         *type = (c >> 4) & 7;
1046         size = c & 15;
1047         shift = 4;
1048         while (c & 0x80) {
1049                 if (len <= used || bitsizeof(long) <= shift) {
1050                         error("bad object header");
1051                         size = used = 0;
1052                         break;
1053                 }
1054                 c = buf[used++];
1055                 size += (c & 0x7f) << shift;
1056                 shift += 7;
1057         }
1058         *sizep = size;
1059         return used;
1060 }
1061
1062 unsigned long get_size_from_delta(struct packed_git *p,
1063                                   struct pack_window **w_curs,
1064                                   off_t curpos)
1065 {
1066         const unsigned char *data;
1067         unsigned char delta_head[20], *in;
1068         git_zstream stream;
1069         int st;
1070
1071         memset(&stream, 0, sizeof(stream));
1072         stream.next_out = delta_head;
1073         stream.avail_out = sizeof(delta_head);
1074
1075         git_inflate_init(&stream);
1076         do {
1077                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1078                 stream.next_in = in;
1079                 st = git_inflate(&stream, Z_FINISH);
1080                 curpos += stream.next_in - in;
1081         } while ((st == Z_OK || st == Z_BUF_ERROR) &&
1082                  stream.total_out < sizeof(delta_head));
1083         git_inflate_end(&stream);
1084         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head)) {
1085                 error("delta data unpack-initial failed");
1086                 return 0;
1087         }
1088
1089         /* Examine the initial part of the delta to figure out
1090          * the result size.
1091          */
1092         data = delta_head;
1093
1094         /* ignore base size */
1095         get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1096
1097         /* Read the result size */
1098         return get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
1099 }
1100
1101 int unpack_object_header(struct packed_git *p,
1102                          struct pack_window **w_curs,
1103                          off_t *curpos,
1104                          unsigned long *sizep)
1105 {
1106         unsigned char *base;
1107         unsigned long left;
1108         unsigned long used;
1109         enum object_type type;
1110
1111         /* use_pack() assures us we have [base, base + 20) available
1112          * as a range that we can look at.  (Its actually the hash
1113          * size that is assured.)  With our object header encoding
1114          * the maximum deflated object size is 2^137, which is just
1115          * insane, so we know won't exceed what we have been given.
1116          */
1117         base = use_pack(p, w_curs, *curpos, &left);
1118         used = unpack_object_header_buffer(base, left, &type, sizep);
1119         if (!used) {
1120                 type = OBJ_BAD;
1121         } else
1122                 *curpos += used;
1123
1124         return type;
1125 }
1126
1127 void mark_bad_packed_object(struct packed_git *p, const unsigned char *sha1)
1128 {
1129         unsigned i;
1130         const unsigned hashsz = the_hash_algo->rawsz;
1131         for (i = 0; i < p->num_bad_objects; i++)
1132                 if (hasheq(sha1, p->bad_object_sha1 + hashsz * i))
1133                         return;
1134         p->bad_object_sha1 = xrealloc(p->bad_object_sha1,
1135                                       st_mult(GIT_MAX_RAWSZ,
1136                                               st_add(p->num_bad_objects, 1)));
1137         hashcpy(p->bad_object_sha1 + hashsz * p->num_bad_objects, sha1);
1138         p->num_bad_objects++;
1139 }
1140
1141 const struct packed_git *has_packed_and_bad(struct repository *r,
1142                                             const unsigned char *sha1)
1143 {
1144         struct packed_git *p;
1145         unsigned i;
1146
1147         for (p = r->objects->packed_git; p; p = p->next)
1148                 for (i = 0; i < p->num_bad_objects; i++)
1149                         if (hasheq(sha1,
1150                                    p->bad_object_sha1 + the_hash_algo->rawsz * i))
1151                                 return p;
1152         return NULL;
1153 }
1154
1155 static off_t get_delta_base(struct packed_git *p,
1156                                     struct pack_window **w_curs,
1157                                     off_t *curpos,
1158                                     enum object_type type,
1159                                     off_t delta_obj_offset)
1160 {
1161         unsigned char *base_info = use_pack(p, w_curs, *curpos, NULL);
1162         off_t base_offset;
1163
1164         /* use_pack() assured us we have [base_info, base_info + 20)
1165          * as a range that we can look at without walking off the
1166          * end of the mapped window.  Its actually the hash size
1167          * that is assured.  An OFS_DELTA longer than the hash size
1168          * is stupid, as then a REF_DELTA would be smaller to store.
1169          */
1170         if (type == OBJ_OFS_DELTA) {
1171                 unsigned used = 0;
1172                 unsigned char c = base_info[used++];
1173                 base_offset = c & 127;
1174                 while (c & 128) {
1175                         base_offset += 1;
1176                         if (!base_offset || MSB(base_offset, 7))
1177                                 return 0;  /* overflow */
1178                         c = base_info[used++];
1179                         base_offset = (base_offset << 7) + (c & 127);
1180                 }
1181                 base_offset = delta_obj_offset - base_offset;
1182                 if (base_offset <= 0 || base_offset >= delta_obj_offset)
1183                         return 0;  /* out of bound */
1184                 *curpos += used;
1185         } else if (type == OBJ_REF_DELTA) {
1186                 /* The base entry _must_ be in the same pack */
1187                 base_offset = find_pack_entry_one(base_info, p);
1188                 *curpos += the_hash_algo->rawsz;
1189         } else
1190                 die("I am totally screwed");
1191         return base_offset;
1192 }
1193
1194 /*
1195  * Like get_delta_base above, but we return the sha1 instead of the pack
1196  * offset. This means it is cheaper for REF deltas (we do not have to do
1197  * the final object lookup), but more expensive for OFS deltas (we
1198  * have to load the revidx to convert the offset back into a sha1).
1199  */
1200 static const unsigned char *get_delta_base_sha1(struct packed_git *p,
1201                                                 struct pack_window **w_curs,
1202                                                 off_t curpos,
1203                                                 enum object_type type,
1204                                                 off_t delta_obj_offset)
1205 {
1206         if (type == OBJ_REF_DELTA) {
1207                 unsigned char *base = use_pack(p, w_curs, curpos, NULL);
1208                 return base;
1209         } else if (type == OBJ_OFS_DELTA) {
1210                 struct revindex_entry *revidx;
1211                 off_t base_offset = get_delta_base(p, w_curs, &curpos,
1212                                                    type, delta_obj_offset);
1213
1214                 if (!base_offset)
1215                         return NULL;
1216
1217                 revidx = find_pack_revindex(p, base_offset);
1218                 if (!revidx)
1219                         return NULL;
1220
1221                 return nth_packed_object_sha1(p, revidx->nr);
1222         } else
1223                 return NULL;
1224 }
1225
1226 static int retry_bad_packed_offset(struct repository *r,
1227                                    struct packed_git *p,
1228                                    off_t obj_offset)
1229 {
1230         int type;
1231         struct revindex_entry *revidx;
1232         struct object_id oid;
1233         revidx = find_pack_revindex(p, obj_offset);
1234         if (!revidx)
1235                 return OBJ_BAD;
1236         nth_packed_object_oid(&oid, p, revidx->nr);
1237         mark_bad_packed_object(p, oid.hash);
1238         type = oid_object_info(r, &oid, NULL);
1239         if (type <= OBJ_NONE)
1240                 return OBJ_BAD;
1241         return type;
1242 }
1243
1244 #define POI_STACK_PREALLOC 64
1245
1246 static enum object_type packed_to_object_type(struct repository *r,
1247                                               struct packed_git *p,
1248                                               off_t obj_offset,
1249                                               enum object_type type,
1250                                               struct pack_window **w_curs,
1251                                               off_t curpos)
1252 {
1253         off_t small_poi_stack[POI_STACK_PREALLOC];
1254         off_t *poi_stack = small_poi_stack;
1255         int poi_stack_nr = 0, poi_stack_alloc = POI_STACK_PREALLOC;
1256
1257         while (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1258                 off_t base_offset;
1259                 unsigned long size;
1260                 /* Push the object we're going to leave behind */
1261                 if (poi_stack_nr >= poi_stack_alloc && poi_stack == small_poi_stack) {
1262                         poi_stack_alloc = alloc_nr(poi_stack_nr);
1263                         ALLOC_ARRAY(poi_stack, poi_stack_alloc);
1264                         COPY_ARRAY(poi_stack, small_poi_stack, poi_stack_nr);
1265                 } else {
1266                         ALLOC_GROW(poi_stack, poi_stack_nr+1, poi_stack_alloc);
1267                 }
1268                 poi_stack[poi_stack_nr++] = obj_offset;
1269                 /* If parsing the base offset fails, just unwind */
1270                 base_offset = get_delta_base(p, w_curs, &curpos, type, obj_offset);
1271                 if (!base_offset)
1272                         goto unwind;
1273                 curpos = obj_offset = base_offset;
1274                 type = unpack_object_header(p, w_curs, &curpos, &size);
1275                 if (type <= OBJ_NONE) {
1276                         /* If getting the base itself fails, we first
1277                          * retry the base, otherwise unwind */
1278                         type = retry_bad_packed_offset(r, p, base_offset);
1279                         if (type > OBJ_NONE)
1280                                 goto out;
1281                         goto unwind;
1282                 }
1283         }
1284
1285         switch (type) {
1286         case OBJ_BAD:
1287         case OBJ_COMMIT:
1288         case OBJ_TREE:
1289         case OBJ_BLOB:
1290         case OBJ_TAG:
1291                 break;
1292         default:
1293                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1294                       type, (uintmax_t)obj_offset, p->pack_name);
1295                 type = OBJ_BAD;
1296         }
1297
1298 out:
1299         if (poi_stack != small_poi_stack)
1300                 free(poi_stack);
1301         return type;
1302
1303 unwind:
1304         while (poi_stack_nr) {
1305                 obj_offset = poi_stack[--poi_stack_nr];
1306                 type = retry_bad_packed_offset(r, p, obj_offset);
1307                 if (type > OBJ_NONE)
1308                         goto out;
1309         }
1310         type = OBJ_BAD;
1311         goto out;
1312 }
1313
1314 static struct hashmap delta_base_cache;
1315 static size_t delta_base_cached;
1316
1317 static LIST_HEAD(delta_base_cache_lru);
1318
1319 struct delta_base_cache_key {
1320         struct packed_git *p;
1321         off_t base_offset;
1322 };
1323
1324 struct delta_base_cache_entry {
1325         struct hashmap hash;
1326         struct delta_base_cache_key key;
1327         struct list_head lru;
1328         void *data;
1329         unsigned long size;
1330         enum object_type type;
1331 };
1332
1333 static unsigned int pack_entry_hash(struct packed_git *p, off_t base_offset)
1334 {
1335         unsigned int hash;
1336
1337         hash = (unsigned int)(intptr_t)p + (unsigned int)base_offset;
1338         hash += (hash >> 8) + (hash >> 16);
1339         return hash;
1340 }
1341
1342 static struct delta_base_cache_entry *
1343 get_delta_base_cache_entry(struct packed_git *p, off_t base_offset)
1344 {
1345         struct hashmap_entry entry;
1346         struct delta_base_cache_key key;
1347
1348         if (!delta_base_cache.cmpfn)
1349                 return NULL;
1350
1351         hashmap_entry_init(&entry, pack_entry_hash(p, base_offset));
1352         key.p = p;
1353         key.base_offset = base_offset;
1354         return hashmap_get(&delta_base_cache, &entry, &key);
1355 }
1356
1357 static int delta_base_cache_key_eq(const struct delta_base_cache_key *a,
1358                                    const struct delta_base_cache_key *b)
1359 {
1360         return a->p == b->p && a->base_offset == b->base_offset;
1361 }
1362
1363 static int delta_base_cache_hash_cmp(const void *unused_cmp_data,
1364                                      const void *va, const void *vb,
1365                                      const void *vkey)
1366 {
1367         const struct delta_base_cache_entry *a = va, *b = vb;
1368         const struct delta_base_cache_key *key = vkey;
1369         if (key)
1370                 return !delta_base_cache_key_eq(&a->key, key);
1371         else
1372                 return !delta_base_cache_key_eq(&a->key, &b->key);
1373 }
1374
1375 static int in_delta_base_cache(struct packed_git *p, off_t base_offset)
1376 {
1377         return !!get_delta_base_cache_entry(p, base_offset);
1378 }
1379
1380 /*
1381  * Remove the entry from the cache, but do _not_ free the associated
1382  * entry data. The caller takes ownership of the "data" buffer, and
1383  * should copy out any fields it wants before detaching.
1384  */
1385 static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
1386 {
1387         hashmap_remove(&delta_base_cache, ent, &ent->key);
1388         list_del(&ent->lru);
1389         delta_base_cached -= ent->size;
1390         free(ent);
1391 }
1392
1393 static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
1394                                    off_t base_offset, unsigned long *base_size,
1395                                    enum object_type *type)
1396 {
1397         struct delta_base_cache_entry *ent;
1398
1399         ent = get_delta_base_cache_entry(p, base_offset);
1400         if (!ent)
1401                 return unpack_entry(r, p, base_offset, type, base_size);
1402
1403         if (type)
1404                 *type = ent->type;
1405         if (base_size)
1406                 *base_size = ent->size;
1407         return xmemdupz(ent->data, ent->size);
1408 }
1409
1410 static inline void release_delta_base_cache(struct delta_base_cache_entry *ent)
1411 {
1412         free(ent->data);
1413         detach_delta_base_cache_entry(ent);
1414 }
1415
1416 void clear_delta_base_cache(void)
1417 {
1418         struct list_head *lru, *tmp;
1419         list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1420                 struct delta_base_cache_entry *entry =
1421                         list_entry(lru, struct delta_base_cache_entry, lru);
1422                 release_delta_base_cache(entry);
1423         }
1424 }
1425
1426 static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
1427         void *base, unsigned long base_size, enum object_type type)
1428 {
1429         struct delta_base_cache_entry *ent = xmalloc(sizeof(*ent));
1430         struct list_head *lru, *tmp;
1431
1432         delta_base_cached += base_size;
1433
1434         list_for_each_safe(lru, tmp, &delta_base_cache_lru) {
1435                 struct delta_base_cache_entry *f =
1436                         list_entry(lru, struct delta_base_cache_entry, lru);
1437                 if (delta_base_cached <= delta_base_cache_limit)
1438                         break;
1439                 release_delta_base_cache(f);
1440         }
1441
1442         ent->key.p = p;
1443         ent->key.base_offset = base_offset;
1444         ent->type = type;
1445         ent->data = base;
1446         ent->size = base_size;
1447         list_add_tail(&ent->lru, &delta_base_cache_lru);
1448
1449         if (!delta_base_cache.cmpfn)
1450                 hashmap_init(&delta_base_cache, delta_base_cache_hash_cmp, NULL, 0);
1451         hashmap_entry_init(ent, pack_entry_hash(p, base_offset));
1452         hashmap_add(&delta_base_cache, ent);
1453 }
1454
1455 int packed_object_info(struct repository *r, struct packed_git *p,
1456                        off_t obj_offset, struct object_info *oi)
1457 {
1458         struct pack_window *w_curs = NULL;
1459         unsigned long size;
1460         off_t curpos = obj_offset;
1461         enum object_type type;
1462
1463         /*
1464          * We always get the representation type, but only convert it to
1465          * a "real" type later if the caller is interested.
1466          */
1467         if (oi->contentp) {
1468                 *oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
1469                                                       &type);
1470                 if (!*oi->contentp)
1471                         type = OBJ_BAD;
1472         } else {
1473                 type = unpack_object_header(p, &w_curs, &curpos, &size);
1474         }
1475
1476         if (!oi->contentp && oi->sizep) {
1477                 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1478                         off_t tmp_pos = curpos;
1479                         off_t base_offset = get_delta_base(p, &w_curs, &tmp_pos,
1480                                                            type, obj_offset);
1481                         if (!base_offset) {
1482                                 type = OBJ_BAD;
1483                                 goto out;
1484                         }
1485                         *oi->sizep = get_size_from_delta(p, &w_curs, tmp_pos);
1486                         if (*oi->sizep == 0) {
1487                                 type = OBJ_BAD;
1488                                 goto out;
1489                         }
1490                 } else {
1491                         *oi->sizep = size;
1492                 }
1493         }
1494
1495         if (oi->disk_sizep) {
1496                 struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1497                 *oi->disk_sizep = revidx[1].offset - obj_offset;
1498         }
1499
1500         if (oi->typep || oi->type_name) {
1501                 enum object_type ptot;
1502                 ptot = packed_to_object_type(r, p, obj_offset,
1503                                              type, &w_curs, curpos);
1504                 if (oi->typep)
1505                         *oi->typep = ptot;
1506                 if (oi->type_name) {
1507                         const char *tn = type_name(ptot);
1508                         if (tn)
1509                                 strbuf_addstr(oi->type_name, tn);
1510                 }
1511                 if (ptot < 0) {
1512                         type = OBJ_BAD;
1513                         goto out;
1514                 }
1515         }
1516
1517         if (oi->delta_base_sha1) {
1518                 if (type == OBJ_OFS_DELTA || type == OBJ_REF_DELTA) {
1519                         const unsigned char *base;
1520
1521                         base = get_delta_base_sha1(p, &w_curs, curpos,
1522                                                    type, obj_offset);
1523                         if (!base) {
1524                                 type = OBJ_BAD;
1525                                 goto out;
1526                         }
1527
1528                         hashcpy(oi->delta_base_sha1, base);
1529                 } else
1530                         hashclr(oi->delta_base_sha1);
1531         }
1532
1533         oi->whence = in_delta_base_cache(p, obj_offset) ? OI_DBCACHED :
1534                                                           OI_PACKED;
1535
1536 out:
1537         unuse_pack(&w_curs);
1538         return type;
1539 }
1540
1541 static void *unpack_compressed_entry(struct packed_git *p,
1542                                     struct pack_window **w_curs,
1543                                     off_t curpos,
1544                                     unsigned long size)
1545 {
1546         int st;
1547         git_zstream stream;
1548         unsigned char *buffer, *in;
1549
1550         buffer = xmallocz_gently(size);
1551         if (!buffer)
1552                 return NULL;
1553         memset(&stream, 0, sizeof(stream));
1554         stream.next_out = buffer;
1555         stream.avail_out = size + 1;
1556
1557         git_inflate_init(&stream);
1558         do {
1559                 in = use_pack(p, w_curs, curpos, &stream.avail_in);
1560                 stream.next_in = in;
1561                 st = git_inflate(&stream, Z_FINISH);
1562                 if (!stream.avail_out)
1563                         break; /* the payload is larger than it should be */
1564                 curpos += stream.next_in - in;
1565         } while (st == Z_OK || st == Z_BUF_ERROR);
1566         git_inflate_end(&stream);
1567         if ((st != Z_STREAM_END) || stream.total_out != size) {
1568                 free(buffer);
1569                 return NULL;
1570         }
1571
1572         /* versions of zlib can clobber unconsumed portion of outbuf */
1573         buffer[size] = '\0';
1574
1575         return buffer;
1576 }
1577
1578 static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
1579 {
1580         static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
1581         trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
1582                          p->pack_name, (uintmax_t)obj_offset);
1583 }
1584
1585 int do_check_packed_object_crc;
1586
1587 #define UNPACK_ENTRY_STACK_PREALLOC 64
1588 struct unpack_entry_stack_ent {
1589         off_t obj_offset;
1590         off_t curpos;
1591         unsigned long size;
1592 };
1593
1594 static void *read_object(struct repository *r,
1595                          const struct object_id *oid,
1596                          enum object_type *type,
1597                          unsigned long *size)
1598 {
1599         struct object_info oi = OBJECT_INFO_INIT;
1600         void *content;
1601         oi.typep = type;
1602         oi.sizep = size;
1603         oi.contentp = &content;
1604
1605         if (oid_object_info_extended(r, oid, &oi, 0) < 0)
1606                 return NULL;
1607         return content;
1608 }
1609
1610 void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
1611                    enum object_type *final_type, unsigned long *final_size)
1612 {
1613         struct pack_window *w_curs = NULL;
1614         off_t curpos = obj_offset;
1615         void *data = NULL;
1616         unsigned long size;
1617         enum object_type type;
1618         struct unpack_entry_stack_ent small_delta_stack[UNPACK_ENTRY_STACK_PREALLOC];
1619         struct unpack_entry_stack_ent *delta_stack = small_delta_stack;
1620         int delta_stack_nr = 0, delta_stack_alloc = UNPACK_ENTRY_STACK_PREALLOC;
1621         int base_from_cache = 0;
1622
1623         write_pack_access_log(p, obj_offset);
1624
1625         /* PHASE 1: drill down to the innermost base object */
1626         for (;;) {
1627                 off_t base_offset;
1628                 int i;
1629                 struct delta_base_cache_entry *ent;
1630
1631                 ent = get_delta_base_cache_entry(p, curpos);
1632                 if (ent) {
1633                         type = ent->type;
1634                         data = ent->data;
1635                         size = ent->size;
1636                         detach_delta_base_cache_entry(ent);
1637                         base_from_cache = 1;
1638                         break;
1639                 }
1640
1641                 if (do_check_packed_object_crc && p->index_version > 1) {
1642                         struct revindex_entry *revidx = find_pack_revindex(p, obj_offset);
1643                         off_t len = revidx[1].offset - obj_offset;
1644                         if (check_pack_crc(p, &w_curs, obj_offset, len, revidx->nr)) {
1645                                 struct object_id oid;
1646                                 nth_packed_object_oid(&oid, p, revidx->nr);
1647                                 error("bad packed object CRC for %s",
1648                                       oid_to_hex(&oid));
1649                                 mark_bad_packed_object(p, oid.hash);
1650                                 data = NULL;
1651                                 goto out;
1652                         }
1653                 }
1654
1655                 type = unpack_object_header(p, &w_curs, &curpos, &size);
1656                 if (type != OBJ_OFS_DELTA && type != OBJ_REF_DELTA)
1657                         break;
1658
1659                 base_offset = get_delta_base(p, &w_curs, &curpos, type, obj_offset);
1660                 if (!base_offset) {
1661                         error("failed to validate delta base reference "
1662                               "at offset %"PRIuMAX" from %s",
1663                               (uintmax_t)curpos, p->pack_name);
1664                         /* bail to phase 2, in hopes of recovery */
1665                         data = NULL;
1666                         break;
1667                 }
1668
1669                 /* push object, proceed to base */
1670                 if (delta_stack_nr >= delta_stack_alloc
1671                     && delta_stack == small_delta_stack) {
1672                         delta_stack_alloc = alloc_nr(delta_stack_nr);
1673                         ALLOC_ARRAY(delta_stack, delta_stack_alloc);
1674                         COPY_ARRAY(delta_stack, small_delta_stack,
1675                                    delta_stack_nr);
1676                 } else {
1677                         ALLOC_GROW(delta_stack, delta_stack_nr+1, delta_stack_alloc);
1678                 }
1679                 i = delta_stack_nr++;
1680                 delta_stack[i].obj_offset = obj_offset;
1681                 delta_stack[i].curpos = curpos;
1682                 delta_stack[i].size = size;
1683
1684                 curpos = obj_offset = base_offset;
1685         }
1686
1687         /* PHASE 2: handle the base */
1688         switch (type) {
1689         case OBJ_OFS_DELTA:
1690         case OBJ_REF_DELTA:
1691                 if (data)
1692                         BUG("unpack_entry: left loop at a valid delta");
1693                 break;
1694         case OBJ_COMMIT:
1695         case OBJ_TREE:
1696         case OBJ_BLOB:
1697         case OBJ_TAG:
1698                 if (!base_from_cache)
1699                         data = unpack_compressed_entry(p, &w_curs, curpos, size);
1700                 break;
1701         default:
1702                 data = NULL;
1703                 error("unknown object type %i at offset %"PRIuMAX" in %s",
1704                       type, (uintmax_t)obj_offset, p->pack_name);
1705         }
1706
1707         /* PHASE 3: apply deltas in order */
1708
1709         /* invariants:
1710          *   'data' holds the base data, or NULL if there was corruption
1711          */
1712         while (delta_stack_nr) {
1713                 void *delta_data;
1714                 void *base = data;
1715                 void *external_base = NULL;
1716                 unsigned long delta_size, base_size = size;
1717                 int i;
1718
1719                 data = NULL;
1720
1721                 if (base)
1722                         add_delta_base_cache(p, obj_offset, base, base_size, type);
1723
1724                 if (!base) {
1725                         /*
1726                          * We're probably in deep shit, but let's try to fetch
1727                          * the required base anyway from another pack or loose.
1728                          * This is costly but should happen only in the presence
1729                          * of a corrupted pack, and is better than failing outright.
1730                          */
1731                         struct revindex_entry *revidx;
1732                         struct object_id base_oid;
1733                         revidx = find_pack_revindex(p, obj_offset);
1734                         if (revidx) {
1735                                 nth_packed_object_oid(&base_oid, p, revidx->nr);
1736                                 error("failed to read delta base object %s"
1737                                       " at offset %"PRIuMAX" from %s",
1738                                       oid_to_hex(&base_oid), (uintmax_t)obj_offset,
1739                                       p->pack_name);
1740                                 mark_bad_packed_object(p, base_oid.hash);
1741                                 base = read_object(r, &base_oid, &type, &base_size);
1742                                 external_base = base;
1743                         }
1744                 }
1745
1746                 i = --delta_stack_nr;
1747                 obj_offset = delta_stack[i].obj_offset;
1748                 curpos = delta_stack[i].curpos;
1749                 delta_size = delta_stack[i].size;
1750
1751                 if (!base)
1752                         continue;
1753
1754                 delta_data = unpack_compressed_entry(p, &w_curs, curpos, delta_size);
1755
1756                 if (!delta_data) {
1757                         error("failed to unpack compressed delta "
1758                               "at offset %"PRIuMAX" from %s",
1759                               (uintmax_t)curpos, p->pack_name);
1760                         data = NULL;
1761                         free(external_base);
1762                         continue;
1763                 }
1764
1765                 data = patch_delta(base, base_size,
1766                                    delta_data, delta_size,
1767                                    &size);
1768
1769                 /*
1770                  * We could not apply the delta; warn the user, but keep going.
1771                  * Our failure will be noticed either in the next iteration of
1772                  * the loop, or if this is the final delta, in the caller when
1773                  * we return NULL. Those code paths will take care of making
1774                  * a more explicit warning and retrying with another copy of
1775                  * the object.
1776                  */
1777                 if (!data)
1778                         error("failed to apply delta");
1779
1780                 free(delta_data);
1781                 free(external_base);
1782         }
1783
1784         if (final_type)
1785                 *final_type = type;
1786         if (final_size)
1787                 *final_size = size;
1788
1789 out:
1790         unuse_pack(&w_curs);
1791
1792         if (delta_stack != small_delta_stack)
1793                 free(delta_stack);
1794
1795         return data;
1796 }
1797
1798 int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32_t *result)
1799 {
1800         const unsigned char *index_fanout = p->index_data;
1801         const unsigned char *index_lookup;
1802         const unsigned int hashsz = the_hash_algo->rawsz;
1803         int index_lookup_width;
1804
1805         if (!index_fanout)
1806                 BUG("bsearch_pack called without a valid pack-index");
1807
1808         index_lookup = index_fanout + 4 * 256;
1809         if (p->index_version == 1) {
1810                 index_lookup_width = hashsz + 4;
1811                 index_lookup += 4;
1812         } else {
1813                 index_lookup_width = hashsz;
1814                 index_fanout += 8;
1815                 index_lookup += 8;
1816         }
1817
1818         return bsearch_hash(oid->hash, (const uint32_t*)index_fanout,
1819                             index_lookup, index_lookup_width, result);
1820 }
1821
1822 const unsigned char *nth_packed_object_sha1(struct packed_git *p,
1823                                             uint32_t n)
1824 {
1825         const unsigned char *index = p->index_data;
1826         const unsigned int hashsz = the_hash_algo->rawsz;
1827         if (!index) {
1828                 if (open_pack_index(p))
1829                         return NULL;
1830                 index = p->index_data;
1831         }
1832         if (n >= p->num_objects)
1833                 return NULL;
1834         index += 4 * 256;
1835         if (p->index_version == 1) {
1836                 return index + (hashsz + 4) * n + 4;
1837         } else {
1838                 index += 8;
1839                 return index + hashsz * n;
1840         }
1841 }
1842
1843 const struct object_id *nth_packed_object_oid(struct object_id *oid,
1844                                               struct packed_git *p,
1845                                               uint32_t n)
1846 {
1847         const unsigned char *hash = nth_packed_object_sha1(p, n);
1848         if (!hash)
1849                 return NULL;
1850         hashcpy(oid->hash, hash);
1851         return oid;
1852 }
1853
1854 void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
1855 {
1856         const unsigned char *ptr = vptr;
1857         const unsigned char *start = p->index_data;
1858         const unsigned char *end = start + p->index_size;
1859         if (ptr < start)
1860                 die(_("offset before start of pack index for %s (corrupt index?)"),
1861                     p->pack_name);
1862         /* No need to check for underflow; .idx files must be at least 8 bytes */
1863         if (ptr >= end - 8)
1864                 die(_("offset beyond end of pack index for %s (truncated index?)"),
1865                     p->pack_name);
1866 }
1867
1868 off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
1869 {
1870         const unsigned char *index = p->index_data;
1871         const unsigned int hashsz = the_hash_algo->rawsz;
1872         index += 4 * 256;
1873         if (p->index_version == 1) {
1874                 return ntohl(*((uint32_t *)(index + (hashsz + 4) * n)));
1875         } else {
1876                 uint32_t off;
1877                 index += 8 + p->num_objects * (hashsz + 4);
1878                 off = ntohl(*((uint32_t *)(index + 4 * n)));
1879                 if (!(off & 0x80000000))
1880                         return off;
1881                 index += p->num_objects * 4 + (off & 0x7fffffff) * 8;
1882                 check_pack_index_ptr(p, index);
1883                 return get_be64(index);
1884         }
1885 }
1886
1887 off_t find_pack_entry_one(const unsigned char *sha1,
1888                                   struct packed_git *p)
1889 {
1890         const unsigned char *index = p->index_data;
1891         struct object_id oid;
1892         uint32_t result;
1893
1894         if (!index) {
1895                 if (open_pack_index(p))
1896                         return 0;
1897         }
1898
1899         hashcpy(oid.hash, sha1);
1900         if (bsearch_pack(&oid, p, &result))
1901                 return nth_packed_object_offset(p, result);
1902         return 0;
1903 }
1904
1905 int is_pack_valid(struct packed_git *p)
1906 {
1907         /* An already open pack is known to be valid. */
1908         if (p->pack_fd != -1)
1909                 return 1;
1910
1911         /* If the pack has one window completely covering the
1912          * file size, the pack is known to be valid even if
1913          * the descriptor is not currently open.
1914          */
1915         if (p->windows) {
1916                 struct pack_window *w = p->windows;
1917
1918                 if (!w->offset && w->len == p->pack_size)
1919                         return 1;
1920         }
1921
1922         /* Force the pack to open to prove its valid. */
1923         return !open_packed_git(p);
1924 }
1925
1926 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1927                                   struct packed_git *packs)
1928 {
1929         struct packed_git *p;
1930
1931         for (p = packs; p; p = p->next) {
1932                 if (find_pack_entry_one(sha1, p))
1933                         return p;
1934         }
1935         return NULL;
1936
1937 }
1938
1939 static int fill_pack_entry(const struct object_id *oid,
1940                            struct pack_entry *e,
1941                            struct packed_git *p)
1942 {
1943         off_t offset;
1944
1945         if (p->num_bad_objects) {
1946                 unsigned i;
1947                 for (i = 0; i < p->num_bad_objects; i++)
1948                         if (hasheq(oid->hash,
1949                                    p->bad_object_sha1 + the_hash_algo->rawsz * i))
1950                                 return 0;
1951         }
1952
1953         offset = find_pack_entry_one(oid->hash, p);
1954         if (!offset)
1955                 return 0;
1956
1957         /*
1958          * We are about to tell the caller where they can locate the
1959          * requested object.  We better make sure the packfile is
1960          * still here and can be accessed before supplying that
1961          * answer, as it may have been deleted since the index was
1962          * loaded!
1963          */
1964         if (!is_pack_valid(p))
1965                 return 0;
1966         e->offset = offset;
1967         e->p = p;
1968         return 1;
1969 }
1970
1971 int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
1972 {
1973         struct list_head *pos;
1974         struct multi_pack_index *m;
1975
1976         prepare_packed_git(r);
1977         if (!r->objects->packed_git && !r->objects->multi_pack_index)
1978                 return 0;
1979
1980         for (m = r->objects->multi_pack_index; m; m = m->next) {
1981                 if (fill_midx_entry(r, oid, e, m))
1982                         return 1;
1983         }
1984
1985         list_for_each(pos, &r->objects->packed_git_mru) {
1986                 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1987                 if (!p->multi_pack_index && fill_pack_entry(oid, e, p)) {
1988                         list_move(&p->mru, &r->objects->packed_git_mru);
1989                         return 1;
1990                 }
1991         }
1992         return 0;
1993 }
1994
1995 int has_object_pack(const struct object_id *oid)
1996 {
1997         struct pack_entry e;
1998         return find_pack_entry(the_repository, oid, &e);
1999 }
2000
2001 int has_pack_index(const unsigned char *sha1)
2002 {
2003         struct stat st;
2004         if (stat(sha1_pack_index_name(sha1), &st))
2005                 return 0;
2006         return 1;
2007 }
2008
2009 int for_each_object_in_pack(struct packed_git *p,
2010                             each_packed_object_fn cb, void *data,
2011                             enum for_each_object_flags flags)
2012 {
2013         uint32_t i;
2014         int r = 0;
2015
2016         if (flags & FOR_EACH_OBJECT_PACK_ORDER) {
2017                 if (load_pack_revindex(p))
2018                         return -1;
2019         }
2020
2021         for (i = 0; i < p->num_objects; i++) {
2022                 uint32_t pos;
2023                 struct object_id oid;
2024
2025                 if (flags & FOR_EACH_OBJECT_PACK_ORDER)
2026                         pos = p->revindex[i].nr;
2027                 else
2028                         pos = i;
2029
2030                 if (!nth_packed_object_oid(&oid, p, pos))
2031                         return error("unable to get sha1 of object %u in %s",
2032                                      pos, p->pack_name);
2033
2034                 r = cb(&oid, p, pos, data);
2035                 if (r)
2036                         break;
2037         }
2038         return r;
2039 }
2040
2041 int for_each_packed_object(each_packed_object_fn cb, void *data,
2042                            enum for_each_object_flags flags)
2043 {
2044         struct packed_git *p;
2045         int r = 0;
2046         int pack_errors = 0;
2047
2048         prepare_packed_git(the_repository);
2049         for (p = get_all_packs(the_repository); p; p = p->next) {
2050                 if ((flags & FOR_EACH_OBJECT_LOCAL_ONLY) && !p->pack_local)
2051                         continue;
2052                 if ((flags & FOR_EACH_OBJECT_PROMISOR_ONLY) &&
2053                     !p->pack_promisor)
2054                         continue;
2055                 if (open_pack_index(p)) {
2056                         pack_errors = 1;
2057                         continue;
2058                 }
2059                 r = for_each_object_in_pack(p, cb, data, flags);
2060                 if (r)
2061                         break;
2062         }
2063         return r ? r : pack_errors;
2064 }
2065
2066 static int add_promisor_object(const struct object_id *oid,
2067                                struct packed_git *pack,
2068                                uint32_t pos,
2069                                void *set_)
2070 {
2071         struct oidset *set = set_;
2072         struct object *obj = parse_object(the_repository, oid);
2073         if (!obj)
2074                 return 1;
2075
2076         oidset_insert(set, oid);
2077
2078         /*
2079          * If this is a tree, commit, or tag, the objects it refers
2080          * to are also promisor objects. (Blobs refer to no objects->)
2081          */
2082         if (obj->type == OBJ_TREE) {
2083                 struct tree *tree = (struct tree *)obj;
2084                 struct tree_desc desc;
2085                 struct name_entry entry;
2086                 if (init_tree_desc_gently(&desc, tree->buffer, tree->size))
2087                         /*
2088                          * Error messages are given when packs are
2089                          * verified, so do not print any here.
2090                          */
2091                         return 0;
2092                 while (tree_entry_gently(&desc, &entry))
2093                         oidset_insert(set, &entry.oid);
2094         } else if (obj->type == OBJ_COMMIT) {
2095                 struct commit *commit = (struct commit *) obj;
2096                 struct commit_list *parents = commit->parents;
2097
2098                 oidset_insert(set, get_commit_tree_oid(commit));
2099                 for (; parents; parents = parents->next)
2100                         oidset_insert(set, &parents->item->object.oid);
2101         } else if (obj->type == OBJ_TAG) {
2102                 struct tag *tag = (struct tag *) obj;
2103                 oidset_insert(set, &tag->tagged->oid);
2104         }
2105         return 0;
2106 }
2107
2108 int is_promisor_object(const struct object_id *oid)
2109 {
2110         static struct oidset promisor_objects;
2111         static int promisor_objects_prepared;
2112
2113         if (!promisor_objects_prepared) {
2114                 if (repository_format_partial_clone) {
2115                         for_each_packed_object(add_promisor_object,
2116                                                &promisor_objects,
2117                                                FOR_EACH_OBJECT_PROMISOR_ONLY);
2118                 }
2119                 promisor_objects_prepared = 1;
2120         }
2121         return oidset_contains(&promisor_objects, oid);
2122 }