Skip to contentSkip to conversation

Speed up cache loading time

PATCH Superseded Nguyễn Thái Ngọc Duy 3 participants 13 messages Jun 15, 2016

Subsystems (2)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 cover Speed up cache loading time

This is the polished version of v2 [1], rebased on master (now that split-index has graduated). I wanted to add some tests, but can't think of any way to do it (at least it won't work on Windows). Although with --strict turned on by default, it's less likely that bugs in index-helper could propagate far.

[1] http://article.gmane.org/gmane.comp.version-control.git/251186

Nguyễn Thái Ngọc Duy (9):
trace.c: add GIT_TRACE_PACK_STATS for pack usage statistics read-cache.c: fix constness of verify_hdr()
read-cache: allow to keep mmap'd memory after reading
index-helper: new daemon for caching index and related stuff trace.c: add GIT_TRACE_INDEX_STATS for index statistics
index-helper: add --strict
daemonize(): set a flag before exiting the main process
index-helper: add --detach
index-helper: add Windows support

 .gitignore                               |   1 +
 Documentation/git-index-helper.txt (new) |  56 +++++++
 Documentation/git.txt                    |   4 +
 Makefile                                 |   9 ++
 builtin/gc.c                             |   2 +-
 cache.h                                  |  11 +-
 config.mak.uname                         |   3 +
 daemon.c                                 |   2 +-
 git-compat-util.h                        |   1 +
 git.c                                    |   1 +
 index-helper.c (new)                     | 258 +++++++++++++++++++++++++++++++
 read-cache.c                             | 119 +++++++++++++-
 setup.c                                  |   4 +-
 sha1_file.c                              |  24 +++
 shm.c (new)                              | 163 +++++++++++++++++++
 shm.h (new)                              |  23 +++
 trace.c                                  |  16 ++
 trace.h                                  |   1 +
 18 files changed, 686 insertions(+), 12 deletions(-)
 create mode 100644 Documentation/git-index-helper.txt
 create mode 100644 index-helper.c
 create mode 100644 shm.c
 create mode 100644 shm.h
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#1 lore raw

PATCH v3 1/9 trace.c: add GIT_TRACE_PACK_STATS for pack usage statistics

trace_stats() is intended for GIT_TRACE_*_STATS variable group and GIT_TRACE_PACK_STATS is more like an example how new vars can be added.

---
 Documentation/git.txt |  3 +++
 cache.h               |  2 ++
 git.c                 |  1 +
 sha1_file.c           | 24 ++++++++++++++++++++++++
 trace.c               | 13 +++++++++++++
 trace.h               |  1 +
 6 files changed, 44 insertions(+)
Documentation/git.txt +3 -0
index a0f1ede..a124612 100644
@@ -946,6 +946,9 @@ Unsetting the variable, or setting it to empty, "0" or
 	time of each Git command.
 	See 'GIT_TRACE' for available trace output options.
 
+'GIT_TRACE_PACK_STATS'::
+	Print various statistics.
+
 'GIT_TRACE_SETUP'::
 	Enables trace messages printing the .git, working tree and current
 	working directory after Git has completed its setup phase.
cache.h +2 -0
index fcb511d..1c84227 100644
@@ -1502,4 +1502,6 @@ void stat_validity_update(struct stat_validity *sv, int fd);
 
 int versioncmp(const char *s1, const char *s2);
 
+void report_pack_stats(struct trace_key *key);
+
 #endif /* CACHE_H */
git.c +1 -0
index 9c49519..6a6a8a8 100644
@@ -614,6 +614,7 @@ int main(int argc, char **av)
 	git_setup_gettext();
 
 	trace_command_performance(argv);
+	trace_stats();
 
 	/*
 	 * "git-xxxx" is the same as "git xxxx", but we obviously:
sha1_file.c +24 -0
index 3f70b1d..21a487b 100644
@@ -467,6 +467,7 @@ static unsigned int peak_pack_open_windows;
 static unsigned int pack_open_windows;
 static unsigned int pack_open_fds;
 static unsigned int pack_max_fds;
+static unsigned int pack_access_nr;
 static size_t peak_pack_mapped;
 static size_t pack_mapped;
 struct packed_git *packed_git;
@@ -492,6 +493,28 @@ void pack_report(void)
 		sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
 }
 
+void report_pack_stats(struct trace_key *key)
+{
+	trace_printf_key(key, "\n"
+			 "pack_report: getpagesize()            = %10" SZ_FMT "\n"
+			 "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
+			 "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n"
+			 "pack_report: pack_used_ctr            = %10u\n"
+			 "pack_report: pack_mmap_calls          = %10u\n"
+			 "pack_report: pack_open_windows        = %10u / %10u\n"
+			 "pack_report: pack_mapped              = "
+			 "%10" SZ_FMT " / %10" SZ_FMT "\n"
+			 "pack_report: pack accesss             = %10u\n",
+			 sz_fmt(getpagesize()),
+			 sz_fmt(packed_git_window_size),
+			 sz_fmt(packed_git_limit),
+			 pack_used_ctr,
+			 pack_mmap_calls,
+			 pack_open_windows, peak_pack_open_windows,
+			 sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped),
+			 pack_access_nr);
+}
+
 /*
  * Open and mmap the index file at path, perform a couple of
  * consistency checks, then record its information to p.  Return 0 on
@@ -2086,6 +2109,7 @@ static void write_pack_access_log(struct packed_git *p, off_t obj_offset)
 	static struct trace_key pack_access = TRACE_KEY_INIT(PACK_ACCESS);
 	trace_printf_key(&pack_access, "%s %"PRIuMAX"\n",
 			 p->pack_name, (uintmax_t)obj_offset);
+	pack_access_nr++;
 }
 
 int do_check_packed_object_crc;
trace.c +13 -0
index e583dc6..c52da0f 100644
@@ -426,3 +426,16 @@ void trace_command_performance(const char **argv)
 	sq_quote_argv(&command_line, argv, 0);
 	command_start_time = getnanotime();
 }
+
+static struct trace_key trace_pack_stats = TRACE_KEY_INIT(PACK_STATS);
+
+static void print_stats_atexit(void)
+{
+	report_pack_stats(&trace_pack_stats);
+}
+
+void trace_stats(void)
+{
+	if (trace_want(&trace_pack_stats))
+		atexit(print_stats_atexit);
+}
trace.h +1 -0
index ae6a332..9c06e82 100644
@@ -18,6 +18,7 @@ extern int trace_want(struct trace_key *key);
 extern void trace_disable(struct trace_key *key);
 extern uint64_t getnanotime(void);
 extern void trace_command_performance(const char **argv);
+extern void trace_stats(void);
 
 #ifndef HAVE_VARIADIC_MACROS
 
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#2 lore raw

PATCH v3 2/9 read-cache.c: fix constness of verify_hdr()

In reply to Nguyễn Thái Ngọc Duy
---
 read-cache.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
read-cache.c +1 -1
index 5d3c8bd..949270b 100644
@@ -1324,7 +1324,7 @@ struct ondisk_cache_entry_extended {
 			    ondisk_cache_entry_extended_size(ce_namelen(ce)) : \
 			    ondisk_cache_entry_size(ce_namelen(ce)))
 
-static int verify_hdr(struct cache_header *hdr, unsigned long size)
+static int verify_hdr(const struct cache_header *hdr, unsigned long size)
 {
 	git_SHA_CTX c;
 	unsigned char sha1[20];
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#3 lore raw

PATCH v3 3/9 read-cache: allow to keep mmap'd memory after reading

In reply to Nguyễn Thái Ngọc Duy
---
 cache.h      |  3 +++
 read-cache.c | 13 ++++++++++++-
 2 files changed, 15 insertions(+), 1 deletion(-)
cache.h +3 -0
index 1c84227..978e53d 100644
@@ -306,10 +306,13 @@ struct index_state {
 	struct split_index *split_index;
 	struct cache_time timestamp;
 	unsigned name_hash_initialized : 1,
+		 keep_mmap : 1,
 		 initialized : 1;
 	struct hashmap name_hash;
 	struct hashmap dir_hash;
 	unsigned char sha1[20];
+	void *mmap;
+	size_t mmap_size;
 };
 
 extern struct index_state the_index;
read-cache.c +12 -1
index 949270b..b679781 100644
@@ -1498,6 +1498,10 @@ int do_read_index(struct index_state *istate, const char *path, int must_exist)
 	mmap = xmmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
 	if (mmap == MAP_FAILED)
 		die_errno("unable to map index file");
+	if (istate->keep_mmap) {
+		istate->mmap = mmap;
+		istate->mmap_size = mmap_size;
+	}
 	close(fd);
 
 	hdr = mmap;
@@ -1550,10 +1554,12 @@ int do_read_index(struct index_state *istate, const char *path, int must_exist)
 		src_offset += 8;
 		src_offset += extsize;
 	}
-	munmap(mmap, mmap_size);
+	if (!istate->keep_mmap)
+		munmap(mmap, mmap_size);
 	return istate->cache_nr;
 
 unmap:
+	istate->mmap = NULL;
 	munmap(mmap, mmap_size);
 	die("index file corrupt");
 }
@@ -1579,6 +1585,7 @@ int read_index_from(struct index_state *istate, const char *path)
 		discard_index(split_index->base);
 	else
 		split_index->base = xcalloc(1, sizeof(*split_index->base));
+	split_index->base->keep_mmap = istate->keep_mmap;
 	ret = do_read_index(split_index->base,
 			    git_path("sharedindex.%s",
 				     sha1_to_hex(split_index->base_sha1)), 1);
@@ -1621,6 +1628,10 @@ int discard_index(struct index_state *istate)
 	free(istate->cache);
 	istate->cache = NULL;
 	istate->cache_alloc = 0;
+	if (istate->keep_mmap && istate->mmap) {
+		munmap(istate->mmap, istate->mmap_size);
+		istate->mmap = NULL;
+	}
 	discard_split_index(istate);
 	return 0;
 }
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#4 lore raw

PATCH v3 4/9 index-helper: new daemon for caching index and related stuff

In reply to Nguyễn Thái Ngọc Duy

Instead of reading the index from disk and worrying about disk corruption, the index is cached in memory (memory bit-flips happen too, but hopefully less often). The result is faster read.

The biggest gain is not having to verify the trailing SHA-1, which takes lots of time especially on large index files. But this also opens doors for further optimiztions:

- we could create an in-memory format that's essentially the memory dump of the index to eliminate most of parsing/allocation overhead. The mmap'd memory can be used straight away.

- we could cache non-index info such as name hash

The shared memory's name folows the template "git-<object>-<SHA1>" where <SHA1> is the trailing SHA-1 of the index file. <object> is "index" for cached index files (and may be "name-hash" for name-hash cache). If such shared memory exists, it contains the same index content as on disk. The content is already validated by the daemon and git won't validate it again (except comparing the trailing SHA-1s).

Git can poke the daemon to tell it to refresh the index cache, or to keep it alive some more minutes via UNIX signals. It can't give any real index data directly to the daemon. Real data goes to disk first, then the daemon reads and verifies it from there.

$GIT_DIR/index-helper.pid contains a reference to daemon process (and it's pid on *nix). The file's mtime is updated every time it's accessed (or should be updated often enough). Old index-helper.pid is considered stale and ignored.

index-helper requires POSIX realtime extension. POSIX shm interface however is abstracted away so that Windows support can be added later.

On webkit.git with index format v2, duplicating 8 times to 1.4m entries and 200MB in size:

(vanilla) 0.986986364 s: read_index_from .git/index
(index-helper) 0.267850279 s: read_index_from .git/index

Interestingly with index v4, we get less out of index-helper. It makes sense as v4 requires more processing after loading the index:

(vanilla) 0.722496666 s: read_index_from .git/index
(index-helper) 0.302741500 s: read_index_from .git/index

---
 .gitignore                               |   1 +
 Documentation/git-index-helper.txt (new) |  44 +++++++++
 Makefile                                 |   9 ++
 cache.h                                  |   2 +
 config.mak.uname                         |   1 +
 git-compat-util.h                        |   1 +
 index-helper.c (new)                     | 157 +++++++++++++++++++++++++++++++
 read-cache.c                             |  85 +++++++++++++++--
 shm.c (new)                              |  67 +++++++++++++
 shm.h (new)                              |  23 +++++
 10 files changed, 381 insertions(+), 9 deletions(-)
 create mode 100644 Documentation/git-index-helper.txt
 create mode 100644 index-helper.c
 create mode 100644 shm.c
 create mode 100644 shm.h
.gitignore +1 -0
index 81e12c0..66148ef 100644
@@ -71,6 +71,7 @@
 /git-http-fetch
 /git-http-push
 /git-imap-send
+/git-index-helper
 /git-index-pack
 /git-init
 /git-init-db
Documentation/git-index-helper.txt new file +44 -0

44 lines not on this page · raw message

Makefile +9 -0
index 2320de5..24734e6 100644
@@ -342,6 +342,8 @@ all::
 # return NULL when it receives a bogus time_t.
 #
 # Define HAVE_CLOCK_GETTIME if your platform has clock_gettime in librt.
+#
+# Define HAVE_SHM if you platform support shm_* functions in librt.
 
 GIT-VERSION-FILE: FORCE
 	@$(SHELL_PATH) ./GIT-VERSION-GEN
@@ -876,6 +878,7 @@ LIB_OBJS += sha1-lookup.o
 LIB_OBJS += sha1_file.o
 LIB_OBJS += sha1_name.o
 LIB_OBJS += shallow.o
+LIB_OBJS += shm.o
 LIB_OBJS += sideband.o
 LIB_OBJS += sigchain.o
 LIB_OBJS += split-index.o
@@ -1469,6 +1472,12 @@ ifdef HAVE_DEV_TTY
 	BASIC_CFLAGS += -DHAVE_DEV_TTY
 endif
 
+ifdef HAVE_SHM
+	BASIC_CFLAGS	+= -DHAVE_SHM
+	EXTLIBS	        += -lrt
+	PROGRAM_OBJS	+= index-helper.o
+endif
+
 ifdef DIR_HAS_BSD_GROUP_SEMANTICS
 	COMPAT_CFLAGS += -DDIR_HAS_BSD_GROUP_SEMANTICS
 endif
cache.h +2 -0
index 978e53d..29a0c53 100644
@@ -499,6 +499,7 @@ extern int is_index_unborn(struct index_state *);
 extern int read_index_unmerged(struct index_state *);
 #define COMMIT_LOCK		(1 << 0)
 #define CLOSE_LOCK		(1 << 1)
+#define REFRESH_DAEMON		(1 << 2)
 extern int write_locked_index(struct index_state *, struct lock_file *lock, unsigned flags);
 extern int discard_index(struct index_state *);
 extern int unmerged_index(const struct index_state *);
@@ -621,6 +622,7 @@ extern size_t packed_git_limit;
 extern size_t delta_base_cache_limit;
 extern unsigned long big_file_threshold;
 extern unsigned long pack_size_limit_cfg;
+extern int dont_poke_index_helper;
 
 /*
  * Do replace refs need to be checked this run?  This variable is
config.mak.uname +1 -0
index 00cf4c6..7e66d80 100644
@@ -35,6 +35,7 @@ ifeq ($(uname_S),Linux)
 	LIBC_CONTAINS_LIBINTL = YesPlease
 	HAVE_DEV_TTY = YesPlease
 	HAVE_CLOCK_GETTIME = YesPlease
+	HAVE_SHM = YesPlease
 endif
 ifeq ($(uname_S),GNU/kFreeBSD)
 	HAVE_ALLOCA_H = YesPlease
git-compat-util.h +1 -0
index 26e92f1..13eef92 100644
@@ -417,6 +417,7 @@ static inline int ends_with(const char *str, const char *suffix)
 #define PROT_READ 1
 #define PROT_WRITE 2
 #define MAP_PRIVATE 1
+#define MAP_SHARED 2
 #endif
 
 #define mmap git_mmap
index-helper.c new file +157 -0

157 lines not on this page · raw message

read-cache.c +76 -9

118 lines not on this page · raw message

shm.c new file +67 -0

67 lines not on this page · raw message

shm.h new file +23 -0
new file mode 100644
index 0000000..798d3fd
@@ -0,0 +1,23 @@
+#ifndef SHM_H
+#define SHM_H
+
+/*
+ * Create or open a shared memory and mmap it. Return mmap size if
+ * successful, -1 otherwise. If successful mmap contains the mmap'd
+ * pointer. If oflag does not contain O_CREAT and length is negative,
+ * the mmap size is retrieved from existing shared memory object.
+ *
+ * The mmap could be freed by munmap, even on Windows. Note that on
+ * Windows, git_shm_unlink() is no-op, so the last unmap will destroy
+ * the shared memory.
+ */
+ssize_t git_shm_map(int oflag, int perm, ssize_t length, void **mmap,
+		    int prot, int flags, const char *fmt, ...);
+
+/*
+ * Unlink a shared memory object. Only needed on POSIX platforms. On
+ * Windows this is no-op.
+ */
+void git_shm_unlink(const char *fmt, ...);
+
+#endif
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#8 lore raw

PATCH v3 5/9 trace.c: add GIT_TRACE_INDEX_STATS for index statistics

In reply to Nguyễn Thái Ngọc Duy
---
 Documentation/git.txt |  1 +
 cache.h               |  1 +
 read-cache.c          | 16 ++++++++++++++++
 trace.c               |  5 ++++-
 4 files changed, 22 insertions(+), 1 deletion(-)
Documentation/git.txt +1 -0
index a124612..7077386 100644
@@ -947,6 +947,7 @@ Unsetting the variable, or setting it to empty, "0" or
 	See 'GIT_TRACE' for available trace output options.
 
 'GIT_TRACE_PACK_STATS'::
+'GIT_TRACE_INDEX_STATS'::
 	Print various statistics.
 
 'GIT_TRACE_SETUP'::
cache.h +1 -0
index 29a0c53..4266771 100644
@@ -1508,5 +1508,6 @@ void stat_validity_update(struct stat_validity *sv, int fd);
 int versioncmp(const char *s1, const char *s2);
 
 void report_pack_stats(struct trace_key *key);
+void report_index_stats(struct trace_key *key);
 
 #endif /* CACHE_H */
read-cache.c +16 -0
index ff28142..4bd2abe 100644
@@ -48,6 +48,10 @@ struct index_state the_index;
 static const char *alternate_index_output;
 int dont_poke_index_helper;
 
+static unsigned int nr_read_index;
+static unsigned int nr_read_shm_index;
+static unsigned int nr_write_index;
+
 static void set_index_entry(struct index_state *istate, int nr, struct cache_entry *ce)
 {
 	istate->cache[nr] = ce;
@@ -1523,6 +1527,7 @@ static int try_shm(struct index_state *istate)
 	istate->mmap = new_mmap;
 	istate->mmap_size = new_length;
 	poke_daemon(&st, 0);
+	nr_read_shm_index++;
 	return 0;
 }
 
@@ -1619,6 +1624,7 @@ int do_read_index(struct index_state *istate, const char *path, int must_exist)
 	}
 	if (!istate->keep_mmap)
 		munmap(mmap, mmap_size);
+	nr_read_index++;
 	return istate->cache_nr;
 
 unmap:
@@ -2087,6 +2093,7 @@ static int do_write_index(struct index_state *istate, int newfd,
 		return -1;
 	istate->timestamp.sec = (unsigned int)st.st_mtime;
 	istate->timestamp.nsec = ST_MTIME_NSEC(st);
+	nr_write_index++;
 	return 0;
 }
 
@@ -2346,3 +2353,12 @@ void stat_validity_update(struct stat_validity *sv, int fd)
 		fill_stat_data(sv->sd, &st);
 	}
 }
+
+void report_index_stats(struct trace_key *key)
+{
+	trace_printf_key(key, "\n"
+			 "index stats: file reads        = %10u\n"
+			 "index stats: cache reads       = %10u\n"
+			 "index stats: file writes       = %10u\n",
+			 nr_read_index, nr_read_shm_index, nr_write_index);
+}
trace.c +4 -1
index c52da0f..eb3a11a 100644
@@ -428,14 +428,17 @@ void trace_command_performance(const char **argv)
 }
 
 static struct trace_key trace_pack_stats = TRACE_KEY_INIT(PACK_STATS);
+static struct trace_key trace_index_stats = TRACE_KEY_INIT(INDEX_STATS);
 
 static void print_stats_atexit(void)
 {
 	report_pack_stats(&trace_pack_stats);
+	report_index_stats(&trace_index_stats);
 }
 
 void trace_stats(void)
 {
-	if (trace_want(&trace_pack_stats))
+	if (trace_want(&trace_pack_stats) ||
+	    trace_want(&trace_index_stats))
 		atexit(print_stats_atexit);
 }
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#9 lore raw

PATCH v3 6/9 index-helper: add --strict

In reply to Nguyễn Thái Ngọc Duy

There's are "holes" in the index-helper approach because the shared memory is not verified again by git. If $USER is compromised, shared memory could be modified. But then they can already modify $GIT_DIR/index. A more realistic risk is some bugs in index-helper produce corrupt shared memory. --strict is added to avoid that

Strictly speaking there's still a very small gap where corrupt shared memory could still be read by git: after we write the trailing SHA-1 in the shared memory (thus signaling "this shm is ready") and before verify_shm() detects an error.

---
 Documentation/git-index-helper.txt |  9 ++++++++
 cache.h                            |  1 +
 index-helper.c                     | 47 ++++++++++++++++++++++++++++++++++++++
 read-cache.c                       |  9 +++++---
 4 files changed, 63 insertions(+), 3 deletions(-)
Documentation/git-index-helper.txt +9 -0
index da41c4d..406856d 100644
@@ -22,6 +22,15 @@ OPTIONS
 	Exit if the cached index is not accessed for `<n>`
 	minutes. Specify 0 to wait forever. Default is 10.
 
+--strict::
+--no-strict::
+	Strict mode makes index-helper verify the shared memory after
+	it's created. If the result does not match what's read from
+	$GIT_DIR/index, the shared memory is destroyed. This makes
+	index-helper take more than double the amount of time required
+	for reading an index, but because it will happen in the
+	background, it's not noticable. `--strict` is enabled by default.
+
 NOTES
 -----
 On UNIX-like systems, $GIT_DIR/index-helper.pid contains the process
cache.h +1 -0
index 4266771..0f515e5 100644
@@ -307,6 +307,7 @@ struct index_state {
 	struct cache_time timestamp;
 	unsigned name_hash_initialized : 1,
 		 keep_mmap : 1,
+		 always_verify_trailing_sha1 : 1,
 		 initialized : 1;
 	struct hashmap name_hash;
 	struct hashmap dir_hash;
index-helper.c +47 -0

71 lines not on this page · raw message

read-cache.c +6 -3
index 4bd2abe..d6eb17f 100644
@@ -1568,9 +1568,12 @@ int do_read_index(struct index_state *istate, const char *path, int must_exist)
 
 	istate->mmap = mmap;
 	istate->mmap_size = mmap_size;
-	if (try_shm(istate) &&
-	    verify_hdr(istate->mmap, istate->mmap_size) < 0)
-		goto unmap;
+	if (try_shm(istate)) {
+		if (verify_hdr(istate->mmap, istate->mmap_size) < 0)
+			goto unmap;
+	} else if (istate->always_verify_trailing_sha1 &&
+		   verify_hdr(istate->mmap, istate->mmap_size) < 0)
+			goto unmap;
 	hdr = mmap = istate->mmap;
 	mmap_size = istate->mmap_size;
 	if (!istate->keep_mmap)
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#10 lore raw

PATCH v3 7/9 daemonize(): set a flag before exiting the main process

In reply to Nguyễn Thái Ngọc Duy

This allows signal handlers and atexit functions to realize this situation and not clean up.

---
 builtin/gc.c | 2 +-
 cache.h      | 2 +-
 daemon.c     | 2 +-
 setup.c      | 4 +++-
 4 files changed, 6 insertions(+), 4 deletions(-)
builtin/gc.c +1 -1
index 8d219d8..f120b4f 100644
@@ -341,7 +341,7 @@ int cmd_gc(int argc, const char **argv, const char *prefix)
 			 * failure to daemonize is ok, we'll continue
 			 * in foreground
 			 */
-			daemonize();
+			daemonize(NULL);
 		}
 	} else
 		add_repack_all_option();
cache.h +1 -1
index 0f515e5..f568c8a 100644
@@ -467,7 +467,7 @@ extern int set_git_dir_init(const char *git_dir, const char *real_git_dir, int);
 extern int init_db(const char *template_dir, unsigned int flags);
 
 extern void sanitize_stdfds(void);
-extern int daemonize(void);
+extern int daemonize(int *);
 
 #define alloc_nr(x) (((x)+16)*3/2)
 
daemon.c +1 -1
index e6b51ed..cfdf0f6 100644
@@ -1306,7 +1306,7 @@ int main(int argc, char **argv)
 		return execute();
 
 	if (detach) {
-		if (daemonize())
+		if (daemonize(NULL))
 			die("--detach not supported on this platform");
 	} else
 		sanitize_stdfds();
setup.c +3 -1
index 0a22f8b..b509395 100644
@@ -842,7 +842,7 @@ void sanitize_stdfds(void)
 		close(fd);
 }
 
-int daemonize(void)
+int daemonize(int *daemonized)
 {
 #ifdef NO_POSIX_GOODIES
 	errno = ENOSYS;
@@ -854,6 +854,8 @@ int daemonize(void)
 		case -1:
 			die_errno("fork failed");
 		default:
+			if (daemonized)
+				*daemonized = 1;
 			exit(0);
 	}
 	if (setsid() == -1)
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#11 lore raw

PATCH v3 8/9 index-helper: add --detach

In reply to Nguyễn Thái Ngọc Duy
---
 Documentation/git-index-helper.txt |  3 +++
 index-helper.c                     | 10 ++++++++--
 2 files changed, 11 insertions(+), 2 deletions(-)
Documentation/git-index-helper.txt +3 -0
index 406856d..d8fbdab 100644
@@ -31,6 +31,9 @@ OPTIONS
 	for reading an index, but because it will happen in the
 	background, it's not noticable. `--strict` is enabled by default.
 
+--detach::
+	Detach from the shell.
+
 NOTES
 -----
 On UNIX-like systems, $GIT_DIR/index-helper.pid contains the process
index-helper.c +8 -2
index c82d307..4262678 100644
@@ -13,7 +13,7 @@ struct index_shm {
 
 static struct index_shm shm_index;
 static struct index_shm shm_base_index;
-static int to_verify = 1;
+static int daemonized, to_verify = 1;
 
 static void free_index_shm(struct index_shm *is)
 {
@@ -32,6 +32,8 @@ static void cleanup_shm(void)
 
 static void cleanup(void)
 {
+	if (daemonized)
+		return;
 	unlink(git_path("index-helper.pid"));
 	cleanup_shm();
 }
@@ -164,12 +166,13 @@ int main(int argc, char **argv)
 	static struct lock_file lock;
 	struct strbuf sb = STRBUF_INIT;
 	const char *prefix;
-	int fd, idle_in_minutes = 10;
+	int fd, idle_in_minutes = 10, detach = 0;
 	struct option options[] = {
 		OPT_INTEGER(0, "exit-after", &idle_in_minutes,
 			    N_("exit if not used after some minutes")),
 		OPT_BOOL(0, "strict", &to_verify,
 			 "verify shared memory after creating"),
+		OPT_BOOL(0, "detach", &detach, "detach the process"),
 		OPT_END()
 	};
 
@@ -196,6 +199,9 @@ int main(int argc, char **argv)
 	atexit(cleanup);
 	sigchain_push_common(cleanup_on_signal);
 
+	if (detach && daemonize(&daemonized))
+		die_errno("unable to detach");
+
 	if (!idle_in_minutes)
 		idle_in_minutes = 0xffffffff / 60;
 	loop(sb.buf, idle_in_minutes * 60);
Signature · 1 line
2.1.0.rc0.66.gb9187ad
#12 lore raw

PATCH v3 9/9 index-helper: add Windows support

In reply to Nguyễn Thái Ngọc Duy

Windows supports shared memory, but the semantics is a bit different than POSIX shm. The most noticeable thing is there's no way to get the shared memory's size by the reader, and wrapping fstat to do that would be hell. So the shm size is added near the end, hidden away from shm users (storing it in headers would cause more problems with munmap, storing it as a separate shm is even worse).

PostMessage is used instead of UNIX signals for notification. Lightweight (at least code-wise) on the client side.

---
 config.mak.uname |  2 ++
 index-helper.c   | 48 ++++++++++++++++++++++++++++
 read-cache.c     |  6 ++++
 shm.c            | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 152 insertions(+)
config.mak.uname +2 -0
index 7e66d80..74e764f 100644
@@ -377,6 +377,7 @@ ifndef DEBUG
 else
 	BASIC_CFLAGS += -Zi -MDd
 endif
+	PROGRAM_OBJS += index-helper.o
 	X = .exe
 endif
 ifeq ($(uname_S),Interix)
@@ -532,6 +533,7 @@ ifneq (,$(wildcard ../THIS_IS_MSYSGIT))
 else
 	NO_CURL = YesPlease
 endif
+	PROGRAM_OBJS += index-helper.o
 endif
 ifeq ($(uname_S),QNX)
 	COMPAT_CFLAGS += -DSA_RESTART=0
index-helper.c +48 -0

60 lines not on this page · raw message

read-cache.c +6 -0
index d6eb17f..0ca3345 100644
@@ -1489,6 +1489,12 @@ static void poke_daemon(const struct stat *st, int refresh_cache)
 		pid_t pid = strtoul(sb.buf, &end, 10);
 		if (end && sb.buf + st->st_size == end)
 			kill(pid, refresh_cache ? SIGHUP : SIGUSR1);
+#elif defined(GIT_WINDOWS_NATIVE)
+		if (starts_with(sb.buf, "HWND")) {
+			HWND hwnd = FindWindow("git-index-helper", sb.buf);
+			PostMessage(hwnd, refresh_cache ? WM_USER : WM_USER + 1,
+				    0, 0);
+		}
 #endif
 	}
 	close(fd);
shm.c +96 -0

102 lines not on this page · raw message

Signature · 1 line
2.1.0.rc0.66.gb9187ad
#5 lore raw

Re: [PATCH v3 4/9] index-helper: new daemon for caching index and related stuff

In reply to Nguyễn Thái Ngọc Duy
Quoted 1 line · Nguyễn Thái Ngọc Duy

+# Define HAVE_SHM if you platform support shm_* functions in librt.

s/you/your/

Quoted 1 line

+static void free_index_shm(struct index_shm *is)

Does not actually free its argument; should be release_index_shm.

#6 lore raw

Re: [PATCH v3 4/9] index-helper: new daemon for caching index and related stuff

In reply to Nguyễn Thái Ngọc Duy
Quoted 7 lines · Nguyễn Thái Ngọc Duy

Instead of reading the index from disk and worrying about disk corruption, the index is cached in memory (memory bit-flips happen too, but hopefully less often). The result is faster read.

The biggest gain is not having to verify the trailing SHA-1, which takes lots of time especially on large index files. But this also opens doors for further optimiztions:

s/optimiztions/optimizations/

Quoted 7 lines

- we could create an in-memory format that's essentially the memory dump of the index to eliminate most of parsing/allocation overhead. The mmap'd memory can be used straight away.

- we could cache non-index info such as name hash

The shared memory's name folows the template "git-<object>-<SHA1>"

s/folows/follows/

Quoted 6 lines

where <SHA1> is the trailing SHA-1 of the index file. <object> is "index" for cached index files (and may be "name-hash" for name-hash cache). If such shared memory exists, it contains the same index content as on disk. The content is already validated by the daemon and git won't validate it again (except comparing the trailing SHA-1s).

Quoted 7 lines

Git can poke the daemon to tell it to refresh the index cache, or to keep it alive some more minutes via UNIX signals. It can't give any real index data directly to the daemon. Real data goes to disk first, then the daemon reads and verifies it from there.

$GIT_DIR/index-helper.pid contains a reference to daemon process (and it's pid on *nix). The file's mtime is updated every time it's accessed

s/it's pid/its pid/

Quoted 11 lines

(or should be updated often enough). Old index-helper.pid is considered stale and ignored.

---

index-helper.c new file +0 -0
new file mode 100644
index 0000000..8fa0af9

index-helper.c line 10

Quoted 10 lines
index-helper.c new file +10 -0
@@ -0,0 +1,157 @@
+static void share_index(struct index_state *istate, struct index_shm *is)
+{
+       void *new_mmap;
+       if (istate->mmap_size <= 20 ||
+           hashcmp(istate->sha1,
+                   (unsigned char *)istate->mmap + istate->mmap_size - 20) ||
+           !hashcmp(istate->sha1, is->sha1) ||
+           git_shm_map(O_CREAT | O_EXCL | O_RDWR, 0700, istate->mmap_size,
+                       &new_mmap, PROT_READ | PROT_WRITE, MAP_SHARED,
+                       "git-index-%s", sha1_to_hex(istate->sha1)) < 0)

Do any of these failure conditions deserve a diagnostic message to let the user know that there was a problem?

Quoted 22 lines
index-helper.c new file +15 -0
+               return;
+
+       free_index_shm(is);
+       is->size = istate->mmap_size;
+       is->shm = new_mmap;
+       hashcpy(is->sha1, istate->sha1);
+       memcpy(new_mmap, istate->mmap, istate->mmap_size - 20);
+
+       /*
+        * The trailing hash must be written last after everything is
+        * written. It's the indication that the shared memory is now
+        * ready.
+        */
+       hashcpy((unsigned char *)new_mmap + istate->mmap_size - 20, is->sha1);
+}
read-cache.c +0 -0
index b679781..ff28142 100644
@@ -1465,6 +1467,65 @@ static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk,
        return ce;
 }

read-cache.c static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk, · line 1478

Quoted 10 lines
read-cache.c +9 -0
 
+/*
+ * Try to open and verify a cached shm index if available. Return 0 if
+ * succeeds (istate->mmap and istate->mmap_size are updated). Return
+ * negative otherwise.
+ */
+static int try_shm(struct index_state *istate)
+{
+       void *new_mmap = NULL;
+       size_t old_size = istate->mmap_size;

Is old_size needed? Can you not simply reference istate->mmap_size directly each place old_size is mentioned?

read-cache.c static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk, · line 1503

Quoted 1 line
read-cache.c +1 -0
+       ssize_t new_length;

Nit: 'size' vs. 'length' inconsistency in variable name choices.

Quoted 36 lines
read-cache.c +25 -0
+       const unsigned char *sha1;
+       struct stat st;
+
+       if (old_size <= 20 ||
+           stat(git_path("index-helper.pid"), &st))
+               return -1;
+       sha1 = (unsigned char *)istate->mmap + old_size - 20;
+       new_length = git_shm_map(O_RDONLY, 0700, -1, &new_mmap,
+                                PROT_READ, MAP_SHARED,
+                                "git-index-%s", sha1_to_hex(sha1));
+       if (new_length <= 20 ||
+           hashcmp((unsigned char *)istate->mmap + old_size - 20,
+                   (unsigned char *)new_mmap + new_length - 20)) {
+               if (new_mmap)
+                       munmap(new_mmap, new_length);
+               poke_daemon(&st, 1);
+               return -1;
+       }
+       munmap(istate->mmap, istate->mmap_size);
+       istate->mmap = new_mmap;
+       istate->mmap_size = new_length;
+       poke_daemon(&st, 0);
+       return 0;
+}
+
 /* remember to discard_cache() before reading a different cache! */
 int do_read_index(struct index_state *istate, const char *path, int must_exist)
 {
shm.c new file +2 -0
new file mode 100644
index 0000000..4ec1a00
@@ -0,0 +1,67 @@
+#include "git-compat-util.h"
+#include "shm.h"

shm.c line 12

Quoted 10 lines
shm.c new file +10 -0
+
+#ifdef HAVE_SHM
+
+#define SHM_PATH_LEN 72                /* we don't create very long paths.. */
+
+ssize_t git_shm_map(int oflag, int perm, ssize_t length, void **mmap,
+                   int prot, int flags, const char *fmt, ...)
+{
+       va_list ap;
+       char path[SHM_PATH_LEN];

Is there a reason to avoid strbuf here?

Quoted 29 lines
shm.c new file +29 -0
+       int fd;
+
+       path[0] = '/';
+       va_start(ap, fmt);
+       vsprintf(path + 1, fmt, ap);
+       va_end(ap);
+       fd = shm_open(path, oflag, perm);
+       if (fd < 0)
+               return -1;
+       if (length > 0 && ftruncate(fd, length)) {
+               shm_unlink(path);
+               close(fd);
+               return -1;
+       }
+       if (length < 0 && !(oflag & O_CREAT)) {
+               struct stat st;
+               if (fstat(fd, &st))
+                       die_errno("unable to stat %s", path);
+               length = st.st_size;
+       }
+       *mmap = xmmap(NULL, length, prot, flags, fd, 0);
+       close(fd);
+       if (*mmap == MAP_FAILED) {
+               *mmap = NULL;
+               shm_unlink(path);
+               return -1;
+       }
+       return length;
+}
author
#7 lore raw

Re: [PATCH v3 4/9] index-helper: new daemon for caching index and related stuff

Quoted 5 lines · Eric Sunshine
Quoted 5 lines
index-helper.c new file +5 -0
+static void share_index(struct index_state *istate, struct index_shm *is)
+{
+       void *new_mmap;
+       if (istate->mmap_size <= 20 ||
+           hashcmp(istate->sha1,
Quoted 8 lines

index-helper.c line 54

Quoted 5 lines
index-helper.c new file +5 -0
+                   (unsigned char *)istate->mmap + istate->mmap_size - 20) ||
+           !hashcmp(istate->sha1, is->sha1) ||
+           git_shm_map(O_CREAT | O_EXCL | O_RDWR, 0700, istate->mmap_size,
+                       &new_mmap, PROT_READ | PROT_WRITE, MAP_SHARED,
+                       "git-index-%s", sha1_to_hex(istate->sha1)) < 0)

Do any of these failure conditions deserve a diagnostic message to let the user know that there was a problem?

Hmm.. diagnostic messages are a problem already. This most likely runs as a daemon, nowhere to print to. But if running on foreground, some messages would help.

Quoted 11 lines

read-cache.c static struct cache_entry *create_from_disk(struct ondisk_cache_entry *ondisk, · line 1502

Quoted 4 lines
read-cache.c +4 -0
+static int try_shm(struct index_state *istate)
+{
+       void *new_mmap = NULL;
+       size_t old_size = istate->mmap_size;

Is old_size needed? Can you not simply reference istate->mmap_size directly each place old_size is mentioned?

Quoted 1 line

+ ssize_t new_length;

Nit: 'size' vs. 'length' inconsistency in variable name choices.

Leftovers after many iterations. Will fix.

Quoted 9 lines

shm.c line 12

Quoted 7 lines
shm.c new file +7 -0
+#define SHM_PATH_LEN 72                /* we don't create very long paths.. */
+
+ssize_t git_shm_map(int oflag, int perm, ssize_t length, void **mmap,
+                   int prot, int flags, const char *fmt, ...)
+{
+       va_list ap;
+       char path[SHM_PATH_LEN];

Is there a reason to avoid strbuf here?

Laziness (which is ironic as I'm working on patches to clean up fixed size buffers)

Signature · 1 line
Duy