Merge "Record the resolution start time on errors."
diff --git a/libc/dns/resolv/res_send.c b/libc/dns/resolv/res_send.c
index 0e30b28..4c4b953 100644
--- a/libc/dns/resolv/res_send.c
+++ b/libc/dns/resolv/res_send.c
@@ -552,10 +552,17 @@
 			n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
 				    ns, &now, &rcode, &delay);
 
-			struct __res_sample sample;
-			_res_stats_set_sample(&sample, now, rcode, delay);
-			_resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns,
-				&sample, params.max_samples);
+			/*
+			 * Only record stats the first time we try a query. This ensures that
+			 * queries that deterministically fail (e.g., a name that always returns
+			 * SERVFAIL or times out) do not unduly affect the stats.
+			 */
+			if (try == 0) {
+				struct __res_sample sample;
+				_res_stats_set_sample(&sample, now, rcode, delay);
+				_resolv_cache_add_resolver_stats_sample(statp->netid, revision_id,
+					ns, &sample, params.max_samples);
+			}
 
 			if (DBG) {
 				__libc_format_log(ANDROID_LOG_DEBUG, "libc",
@@ -576,10 +583,13 @@
 			n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
 				    ns, &v_circuit, &gotsomewhere, &now, &rcode, &delay);
 
-			struct __res_sample sample;
-			_res_stats_set_sample(&sample, now, rcode, delay);
-			_resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns,
-				&sample, params.max_samples);
+			/* Only record stats the first time we try a query. See above. */
+			if (try == 0) {
+				struct __res_sample sample;
+				_res_stats_set_sample(&sample, now, rcode, delay);
+				_resolv_cache_add_resolver_stats_sample(statp->netid, revision_id,
+					ns, &sample, params.max_samples);
+			}
 
 			if (DBG) {
 				__libc_format_log(ANDROID_LOG_DEBUG, "libc", "used send_dg %d\n",n);
@@ -741,7 +751,7 @@
 	const u_char *buf, int buflen, u_char *ans, int anssiz,
 	int *terrno, int ns, time_t* at, int* rcode, int* delay)
 {
-	*at = 0;
+	*at = time(NULL);
 	*rcode = RCODE_INTERNAL_ERROR;
 	*delay = 0;
 	const HEADER *hp = (const HEADER *)(const void *)buf;
@@ -919,9 +929,6 @@
 		return (0);
 	}
 
-	struct timespec done = evNowTime();
-	*at = done.tv_sec;
-
 	if (truncating) {
 		/*
 		 * Flush rest of answer so connection stays in synch.
@@ -959,6 +966,7 @@
 	 * next nameserver ought not be tried.
 	 */
 	if (resplen > 0) {
+	    struct timespec done = evNowTime();
 	    *delay = _res_stats_calculate_rtt(&done, &now);
 	    *rcode = anhp->rcode;
 	}
@@ -1074,7 +1082,7 @@
 	int *terrno, int ns, int *v_circuit, int *gotsomewhere,
 	time_t *at, int *rcode, int* delay)
 {
-	*at = 0;
+	*at = time(NULL);
 	*rcode = RCODE_INTERNAL_ERROR;
 	*delay = 0;
 	const HEADER *hp = (const HEADER *)(const void *)buf;
@@ -1261,7 +1269,6 @@
 		goto retry;;
 	}
 	done = evNowTime();
-	*at = done.tv_sec;
 	*delay = _res_stats_calculate_rtt(&done, &now);
 	if (anhp->rcode == SERVFAIL ||
 	    anhp->rcode == NOTIMP ||