xref: /freebsd/sys/netinet/tcp_hostcache.c (revision 41059135ce931c0f1014a999ffabc6bc470ce856)
1 /*-
2  * Copyright (c) 2002 Andre Oppermann, Internet Business Solutions AG
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote
14  *    products derived from this software without specific prior written
15  *    permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * The tcp_hostcache moves the tcp-specific cached metrics from the routing
32  * table to a dedicated structure indexed by the remote IP address.  It keeps
33  * information on the measured TCP parameters of past TCP sessions to allow
34  * better initial start values to be used with later connections to/from the
35  * same source.  Depending on the network parameters (delay, max MTU,
36  * congestion window) between local and remote sites, this can lead to
37  * significant speed-ups for new TCP connections after the first one.
38  *
39  * Due to the tcp_hostcache, all TCP-specific metrics information in the
40  * routing table have been removed.  The inpcb no longer keeps a pointer to
41  * the routing entry, and protocol-initiated route cloning has been removed
42  * as well.  With these changes, the routing table has gone back to being
43  * more lightwight and only carries information related to packet forwarding.
44  *
45  * tcp_hostcache is designed for multiple concurrent access in SMP
46  * environments and high contention.  All bucket rows have their own lock and
47  * thus multiple lookups and modifies can be done at the same time as long as
48  * they are in different bucket rows.  If a request for insertion of a new
49  * record can't be satisfied, it simply returns an empty structure.  Nobody
50  * and nothing outside of tcp_hostcache.c will ever point directly to any
51  * entry in the tcp_hostcache.  All communication is done in an
52  * object-oriented way and only functions of tcp_hostcache will manipulate
53  * hostcache entries.  Otherwise, we are unable to achieve good behaviour in
54  * concurrent access situations.  Since tcp_hostcache is only caching
55  * information, there are no fatal consequences if we either can't satisfy
56  * any particular request or have to drop/overwrite an existing entry because
57  * of bucket limit memory constrains.
58  */
59 
60 /*
61  * Many thanks to jlemon for basic structure of tcp_syncache which is being
62  * followed here.
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include "opt_inet6.h"
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/jail.h>
73 #include <sys/kernel.h>
74 #include <sys/lock.h>
75 #include <sys/mutex.h>
76 #include <sys/malloc.h>
77 #include <sys/proc.h>
78 #include <sys/sbuf.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/sysctl.h>
82 
83 #include <net/if.h>
84 #include <net/if_var.h>
85 #include <net/route.h>
86 #include <net/vnet.h>
87 
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/in_var.h>
92 #include <netinet/in_pcb.h>
93 #include <netinet/ip_var.h>
94 #ifdef INET6
95 #include <netinet/ip6.h>
96 #include <netinet6/ip6_var.h>
97 #endif
98 #include <netinet/tcp.h>
99 #include <netinet/tcp_var.h>
100 #include <netinet/tcp_hostcache.h>
101 #ifdef INET6
102 #include <netinet6/tcp6_var.h>
103 #endif
104 
105 #include <vm/uma.h>
106 
107 /* Arbitrary values */
108 #define TCP_HOSTCACHE_HASHSIZE		512
109 #define TCP_HOSTCACHE_BUCKETLIMIT	30
110 #define TCP_HOSTCACHE_EXPIRE		60*60	/* one hour */
111 #define TCP_HOSTCACHE_PRUNE		5*60	/* every 5 minutes */
112 
113 static VNET_DEFINE(struct tcp_hostcache, tcp_hostcache);
114 #define	V_tcp_hostcache		VNET(tcp_hostcache)
115 
116 static VNET_DEFINE(struct callout, tcp_hc_callout);
117 #define	V_tcp_hc_callout	VNET(tcp_hc_callout)
118 
119 static struct hc_metrics *tcp_hc_lookup(struct in_conninfo *);
120 static struct hc_metrics *tcp_hc_insert(struct in_conninfo *);
121 static int sysctl_tcp_hc_list(SYSCTL_HANDLER_ARGS);
122 static int sysctl_tcp_hc_purgenow(SYSCTL_HANDLER_ARGS);
123 static void tcp_hc_purge_internal(int);
124 static void tcp_hc_purge(void *);
125 
126 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, hostcache, CTLFLAG_RW, 0,
127     "TCP Host cache");
128 
129 VNET_DEFINE(int, tcp_use_hostcache) = 1;
130 #define V_tcp_use_hostcache  VNET(tcp_use_hostcache)
131 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
132     &VNET_NAME(tcp_use_hostcache), 0,
133     "Enable the TCP hostcache");
134 
135 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, cachelimit, CTLFLAG_VNET | CTLFLAG_RDTUN,
136     &VNET_NAME(tcp_hostcache.cache_limit), 0,
137     "Overall entry limit for hostcache");
138 
139 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
140     &VNET_NAME(tcp_hostcache.hashsize), 0,
141     "Size of TCP hostcache hashtable");
142 
143 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, bucketlimit,
144     CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(tcp_hostcache.bucket_limit), 0,
145     "Per-bucket hash limit for hostcache");
146 
147 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, count, CTLFLAG_VNET | CTLFLAG_RD,
148      &VNET_NAME(tcp_hostcache.cache_count), 0,
149     "Current number of entries in hostcache");
150 
151 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, expire, CTLFLAG_VNET | CTLFLAG_RW,
152     &VNET_NAME(tcp_hostcache.expire), 0,
153     "Expire time of TCP hostcache entries");
154 
155 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, prune, CTLFLAG_VNET | CTLFLAG_RW,
156     &VNET_NAME(tcp_hostcache.prune), 0,
157     "Time between purge runs");
158 
159 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, purge, CTLFLAG_VNET | CTLFLAG_RW,
160     &VNET_NAME(tcp_hostcache.purgeall), 0,
161     "Expire all entires on next purge run");
162 
163 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, list,
164     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_SKIP, 0, 0,
165     sysctl_tcp_hc_list, "A", "List of all hostcache entries");
166 
167 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, purgenow,
168     CTLTYPE_INT | CTLFLAG_RW, NULL, 0,
169     sysctl_tcp_hc_purgenow, "I", "Immediately purge all entries");
170 
171 static MALLOC_DEFINE(M_HOSTCACHE, "hostcache", "TCP hostcache");
172 
173 #define HOSTCACHE_HASH(ip) \
174 	(((ip)->s_addr ^ ((ip)->s_addr >> 7) ^ ((ip)->s_addr >> 17)) &	\
175 	  V_tcp_hostcache.hashmask)
176 
177 /* XXX: What is the recommended hash to get good entropy for IPv6 addresses? */
178 #define HOSTCACHE_HASH6(ip6)				\
179 	(((ip6)->s6_addr32[0] ^				\
180 	  (ip6)->s6_addr32[1] ^				\
181 	  (ip6)->s6_addr32[2] ^				\
182 	  (ip6)->s6_addr32[3]) &			\
183 	 V_tcp_hostcache.hashmask)
184 
185 #define THC_LOCK(lp)		mtx_lock(lp)
186 #define THC_UNLOCK(lp)		mtx_unlock(lp)
187 
188 void
189 tcp_hc_init(void)
190 {
191 	u_int cache_limit;
192 	int i;
193 
194 	/*
195 	 * Initialize hostcache structures.
196 	 */
197 	V_tcp_hostcache.cache_count = 0;
198 	V_tcp_hostcache.hashsize = TCP_HOSTCACHE_HASHSIZE;
199 	V_tcp_hostcache.bucket_limit = TCP_HOSTCACHE_BUCKETLIMIT;
200 	V_tcp_hostcache.expire = TCP_HOSTCACHE_EXPIRE;
201 	V_tcp_hostcache.prune = TCP_HOSTCACHE_PRUNE;
202 
203 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.hashsize",
204 	    &V_tcp_hostcache.hashsize);
205 	if (!powerof2(V_tcp_hostcache.hashsize)) {
206 		printf("WARNING: hostcache hash size is not a power of 2.\n");
207 		V_tcp_hostcache.hashsize = TCP_HOSTCACHE_HASHSIZE; /* default */
208 	}
209 	V_tcp_hostcache.hashmask = V_tcp_hostcache.hashsize - 1;
210 
211 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.bucketlimit",
212 	    &V_tcp_hostcache.bucket_limit);
213 
214 	cache_limit = V_tcp_hostcache.hashsize * V_tcp_hostcache.bucket_limit;
215 	V_tcp_hostcache.cache_limit = cache_limit;
216 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.cachelimit",
217 	    &V_tcp_hostcache.cache_limit);
218 	if (V_tcp_hostcache.cache_limit > cache_limit)
219 		V_tcp_hostcache.cache_limit = cache_limit;
220 
221 	/*
222 	 * Allocate the hash table.
223 	 */
224 	V_tcp_hostcache.hashbase = (struct hc_head *)
225 	    malloc(V_tcp_hostcache.hashsize * sizeof(struct hc_head),
226 		   M_HOSTCACHE, M_WAITOK | M_ZERO);
227 
228 	/*
229 	 * Initialize the hash buckets.
230 	 */
231 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
232 		TAILQ_INIT(&V_tcp_hostcache.hashbase[i].hch_bucket);
233 		V_tcp_hostcache.hashbase[i].hch_length = 0;
234 		mtx_init(&V_tcp_hostcache.hashbase[i].hch_mtx, "tcp_hc_entry",
235 			  NULL, MTX_DEF);
236 	}
237 
238 	/*
239 	 * Allocate the hostcache entries.
240 	 */
241 	V_tcp_hostcache.zone =
242 	    uma_zcreate("hostcache", sizeof(struct hc_metrics),
243 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
244 	uma_zone_set_max(V_tcp_hostcache.zone, V_tcp_hostcache.cache_limit);
245 
246 	/*
247 	 * Set up periodic cache cleanup.
248 	 */
249 	callout_init(&V_tcp_hc_callout, 1);
250 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
251 	    tcp_hc_purge, curvnet);
252 }
253 
254 #ifdef VIMAGE
255 void
256 tcp_hc_destroy(void)
257 {
258 	int i;
259 
260 	callout_drain(&V_tcp_hc_callout);
261 
262 	/* Purge all hc entries. */
263 	tcp_hc_purge_internal(1);
264 
265 	/* Free the uma zone and the allocated hash table. */
266 	uma_zdestroy(V_tcp_hostcache.zone);
267 
268 	for (i = 0; i < V_tcp_hostcache.hashsize; i++)
269 		mtx_destroy(&V_tcp_hostcache.hashbase[i].hch_mtx);
270 	free(V_tcp_hostcache.hashbase, M_HOSTCACHE);
271 }
272 #endif
273 
274 /*
275  * Internal function: look up an entry in the hostcache or return NULL.
276  *
277  * If an entry has been returned, the caller becomes responsible for
278  * unlocking the bucket row after he is done reading/modifying the entry.
279  */
280 static struct hc_metrics *
281 tcp_hc_lookup(struct in_conninfo *inc)
282 {
283 	int hash;
284 	struct hc_head *hc_head;
285 	struct hc_metrics *hc_entry;
286 
287 	if (!V_tcp_use_hostcache)
288 		return NULL;
289 
290 	KASSERT(inc != NULL, ("tcp_hc_lookup with NULL in_conninfo pointer"));
291 
292 	/*
293 	 * Hash the foreign ip address.
294 	 */
295 	if (inc->inc_flags & INC_ISIPV6)
296 		hash = HOSTCACHE_HASH6(&inc->inc6_faddr);
297 	else
298 		hash = HOSTCACHE_HASH(&inc->inc_faddr);
299 
300 	hc_head = &V_tcp_hostcache.hashbase[hash];
301 
302 	/*
303 	 * Acquire lock for this bucket row; we release the lock if we don't
304 	 * find an entry, otherwise the caller has to unlock after he is
305 	 * done.
306 	 */
307 	THC_LOCK(&hc_head->hch_mtx);
308 
309 	/*
310 	 * Iterate through entries in bucket row looking for a match.
311 	 */
312 	TAILQ_FOREACH(hc_entry, &hc_head->hch_bucket, rmx_q) {
313 		if (inc->inc_flags & INC_ISIPV6) {
314 			/* XXX: check ip6_zoneid */
315 			if (memcmp(&inc->inc6_faddr, &hc_entry->ip6,
316 			    sizeof(inc->inc6_faddr)) == 0)
317 				return hc_entry;
318 		} else {
319 			if (memcmp(&inc->inc_faddr, &hc_entry->ip4,
320 			    sizeof(inc->inc_faddr)) == 0)
321 				return hc_entry;
322 		}
323 	}
324 
325 	/*
326 	 * We were unsuccessful and didn't find anything.
327 	 */
328 	THC_UNLOCK(&hc_head->hch_mtx);
329 	return NULL;
330 }
331 
332 /*
333  * Internal function: insert an entry into the hostcache or return NULL if
334  * unable to allocate a new one.
335  *
336  * If an entry has been returned, the caller becomes responsible for
337  * unlocking the bucket row after he is done reading/modifying the entry.
338  */
339 static struct hc_metrics *
340 tcp_hc_insert(struct in_conninfo *inc)
341 {
342 	int hash;
343 	struct hc_head *hc_head;
344 	struct hc_metrics *hc_entry;
345 
346 	if (!V_tcp_use_hostcache)
347 		return NULL;
348 
349 	KASSERT(inc != NULL, ("tcp_hc_insert with NULL in_conninfo pointer"));
350 
351 	/*
352 	 * Hash the foreign ip address.
353 	 */
354 	if (inc->inc_flags & INC_ISIPV6)
355 		hash = HOSTCACHE_HASH6(&inc->inc6_faddr);
356 	else
357 		hash = HOSTCACHE_HASH(&inc->inc_faddr);
358 
359 	hc_head = &V_tcp_hostcache.hashbase[hash];
360 
361 	/*
362 	 * Acquire lock for this bucket row; we release the lock if we don't
363 	 * find an entry, otherwise the caller has to unlock after he is
364 	 * done.
365 	 */
366 	THC_LOCK(&hc_head->hch_mtx);
367 
368 	/*
369 	 * If the bucket limit is reached, reuse the least-used element.
370 	 */
371 	if (hc_head->hch_length >= V_tcp_hostcache.bucket_limit ||
372 	    V_tcp_hostcache.cache_count >= V_tcp_hostcache.cache_limit) {
373 		hc_entry = TAILQ_LAST(&hc_head->hch_bucket, hc_qhead);
374 		/*
375 		 * At first we were dropping the last element, just to
376 		 * reacquire it in the next two lines again, which isn't very
377 		 * efficient.  Instead just reuse the least used element.
378 		 * We may drop something that is still "in-use" but we can be
379 		 * "lossy".
380 		 * Just give up if this bucket row is empty and we don't have
381 		 * anything to replace.
382 		 */
383 		if (hc_entry == NULL) {
384 			THC_UNLOCK(&hc_head->hch_mtx);
385 			return NULL;
386 		}
387 		TAILQ_REMOVE(&hc_head->hch_bucket, hc_entry, rmx_q);
388 		V_tcp_hostcache.hashbase[hash].hch_length--;
389 		V_tcp_hostcache.cache_count--;
390 		TCPSTAT_INC(tcps_hc_bucketoverflow);
391 #if 0
392 		uma_zfree(V_tcp_hostcache.zone, hc_entry);
393 #endif
394 	} else {
395 		/*
396 		 * Allocate a new entry, or balk if not possible.
397 		 */
398 		hc_entry = uma_zalloc(V_tcp_hostcache.zone, M_NOWAIT);
399 		if (hc_entry == NULL) {
400 			THC_UNLOCK(&hc_head->hch_mtx);
401 			return NULL;
402 		}
403 	}
404 
405 	/*
406 	 * Initialize basic information of hostcache entry.
407 	 */
408 	bzero(hc_entry, sizeof(*hc_entry));
409 	if (inc->inc_flags & INC_ISIPV6) {
410 		hc_entry->ip6 = inc->inc6_faddr;
411 		hc_entry->ip6_zoneid = inc->inc6_zoneid;
412 	} else
413 		hc_entry->ip4 = inc->inc_faddr;
414 	hc_entry->rmx_head = hc_head;
415 	hc_entry->rmx_expire = V_tcp_hostcache.expire;
416 
417 	/*
418 	 * Put it upfront.
419 	 */
420 	TAILQ_INSERT_HEAD(&hc_head->hch_bucket, hc_entry, rmx_q);
421 	V_tcp_hostcache.hashbase[hash].hch_length++;
422 	V_tcp_hostcache.cache_count++;
423 	TCPSTAT_INC(tcps_hc_added);
424 
425 	return hc_entry;
426 }
427 
428 /*
429  * External function: look up an entry in the hostcache and fill out the
430  * supplied TCP metrics structure.  Fills in NULL when no entry was found or
431  * a value is not set.
432  */
433 void
434 tcp_hc_get(struct in_conninfo *inc, struct hc_metrics_lite *hc_metrics_lite)
435 {
436 	struct hc_metrics *hc_entry;
437 
438 	if (!V_tcp_use_hostcache)
439 		return;
440 
441 	/*
442 	 * Find the right bucket.
443 	 */
444 	hc_entry = tcp_hc_lookup(inc);
445 
446 	/*
447 	 * If we don't have an existing object.
448 	 */
449 	if (hc_entry == NULL) {
450 		bzero(hc_metrics_lite, sizeof(*hc_metrics_lite));
451 		return;
452 	}
453 	hc_entry->rmx_hits++;
454 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
455 
456 	hc_metrics_lite->rmx_mtu = hc_entry->rmx_mtu;
457 	hc_metrics_lite->rmx_ssthresh = hc_entry->rmx_ssthresh;
458 	hc_metrics_lite->rmx_rtt = hc_entry->rmx_rtt;
459 	hc_metrics_lite->rmx_rttvar = hc_entry->rmx_rttvar;
460 	hc_metrics_lite->rmx_cwnd = hc_entry->rmx_cwnd;
461 	hc_metrics_lite->rmx_sendpipe = hc_entry->rmx_sendpipe;
462 	hc_metrics_lite->rmx_recvpipe = hc_entry->rmx_recvpipe;
463 
464 	/*
465 	 * Unlock bucket row.
466 	 */
467 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
468 }
469 
470 /*
471  * External function: look up an entry in the hostcache and return the
472  * discovered path MTU.  Returns 0 if no entry is found or value is not
473  * set.
474  */
475 uint32_t
476 tcp_hc_getmtu(struct in_conninfo *inc)
477 {
478 	struct hc_metrics *hc_entry;
479 	uint32_t mtu;
480 
481 	if (!V_tcp_use_hostcache)
482 		return 0;
483 
484 	hc_entry = tcp_hc_lookup(inc);
485 	if (hc_entry == NULL) {
486 		return 0;
487 	}
488 	hc_entry->rmx_hits++;
489 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
490 
491 	mtu = hc_entry->rmx_mtu;
492 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
493 	return mtu;
494 }
495 
496 /*
497  * External function: update the MTU value of an entry in the hostcache.
498  * Creates a new entry if none was found.
499  */
500 void
501 tcp_hc_updatemtu(struct in_conninfo *inc, uint32_t mtu)
502 {
503 	struct hc_metrics *hc_entry;
504 
505 	if (!V_tcp_use_hostcache)
506 		return;
507 
508 	/*
509 	 * Find the right bucket.
510 	 */
511 	hc_entry = tcp_hc_lookup(inc);
512 
513 	/*
514 	 * If we don't have an existing object, try to insert a new one.
515 	 */
516 	if (hc_entry == NULL) {
517 		hc_entry = tcp_hc_insert(inc);
518 		if (hc_entry == NULL)
519 			return;
520 	}
521 	hc_entry->rmx_updates++;
522 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
523 
524 	hc_entry->rmx_mtu = mtu;
525 
526 	/*
527 	 * Put it upfront so we find it faster next time.
528 	 */
529 	TAILQ_REMOVE(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
530 	TAILQ_INSERT_HEAD(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
531 
532 	/*
533 	 * Unlock bucket row.
534 	 */
535 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
536 }
537 
538 /*
539  * External function: update the TCP metrics of an entry in the hostcache.
540  * Creates a new entry if none was found.
541  */
542 void
543 tcp_hc_update(struct in_conninfo *inc, struct hc_metrics_lite *hcml)
544 {
545 	struct hc_metrics *hc_entry;
546 
547 	if (!V_tcp_use_hostcache)
548 		return;
549 
550 	hc_entry = tcp_hc_lookup(inc);
551 	if (hc_entry == NULL) {
552 		hc_entry = tcp_hc_insert(inc);
553 		if (hc_entry == NULL)
554 			return;
555 	}
556 	hc_entry->rmx_updates++;
557 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
558 
559 	if (hcml->rmx_rtt != 0) {
560 		if (hc_entry->rmx_rtt == 0)
561 			hc_entry->rmx_rtt = hcml->rmx_rtt;
562 		else
563 			hc_entry->rmx_rtt = ((uint64_t)hc_entry->rmx_rtt +
564 			    (uint64_t)hcml->rmx_rtt) / 2;
565 		TCPSTAT_INC(tcps_cachedrtt);
566 	}
567 	if (hcml->rmx_rttvar != 0) {
568 	        if (hc_entry->rmx_rttvar == 0)
569 			hc_entry->rmx_rttvar = hcml->rmx_rttvar;
570 		else
571 			hc_entry->rmx_rttvar = ((uint64_t)hc_entry->rmx_rttvar +
572 			    (uint64_t)hcml->rmx_rttvar) / 2;
573 		TCPSTAT_INC(tcps_cachedrttvar);
574 	}
575 	if (hcml->rmx_ssthresh != 0) {
576 		if (hc_entry->rmx_ssthresh == 0)
577 			hc_entry->rmx_ssthresh = hcml->rmx_ssthresh;
578 		else
579 			hc_entry->rmx_ssthresh =
580 			    (hc_entry->rmx_ssthresh + hcml->rmx_ssthresh) / 2;
581 		TCPSTAT_INC(tcps_cachedssthresh);
582 	}
583 	if (hcml->rmx_cwnd != 0) {
584 		if (hc_entry->rmx_cwnd == 0)
585 			hc_entry->rmx_cwnd = hcml->rmx_cwnd;
586 		else
587 			hc_entry->rmx_cwnd = ((uint64_t)hc_entry->rmx_cwnd +
588 			    (uint64_t)hcml->rmx_cwnd) / 2;
589 		/* TCPSTAT_INC(tcps_cachedcwnd); */
590 	}
591 	if (hcml->rmx_sendpipe != 0) {
592 		if (hc_entry->rmx_sendpipe == 0)
593 			hc_entry->rmx_sendpipe = hcml->rmx_sendpipe;
594 		else
595 			hc_entry->rmx_sendpipe =
596 			    ((uint64_t)hc_entry->rmx_sendpipe +
597 			    (uint64_t)hcml->rmx_sendpipe) /2;
598 		/* TCPSTAT_INC(tcps_cachedsendpipe); */
599 	}
600 	if (hcml->rmx_recvpipe != 0) {
601 		if (hc_entry->rmx_recvpipe == 0)
602 			hc_entry->rmx_recvpipe = hcml->rmx_recvpipe;
603 		else
604 			hc_entry->rmx_recvpipe =
605 			    ((uint64_t)hc_entry->rmx_recvpipe +
606 			    (uint64_t)hcml->rmx_recvpipe) /2;
607 		/* TCPSTAT_INC(tcps_cachedrecvpipe); */
608 	}
609 
610 	TAILQ_REMOVE(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
611 	TAILQ_INSERT_HEAD(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
612 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
613 }
614 
615 /*
616  * Sysctl function: prints the list and values of all hostcache entries in
617  * unsorted order.
618  */
619 static int
620 sysctl_tcp_hc_list(SYSCTL_HANDLER_ARGS)
621 {
622 	const int linesize = 128;
623 	struct sbuf sb;
624 	int i, error;
625 	struct hc_metrics *hc_entry;
626 	char ip4buf[INET_ADDRSTRLEN];
627 #ifdef INET6
628 	char ip6buf[INET6_ADDRSTRLEN];
629 #endif
630 
631 	if (jailed_without_vnet(curthread->td_ucred) != 0)
632 		return (EPERM);
633 
634 	sbuf_new(&sb, NULL, linesize * (V_tcp_hostcache.cache_count + 1),
635 		SBUF_INCLUDENUL);
636 
637 	sbuf_printf(&sb,
638 	        "\nIP address        MTU  SSTRESH      RTT   RTTVAR "
639 		"    CWND SENDPIPE RECVPIPE HITS  UPD  EXP\n");
640 
641 #define msec(u) (((u) + 500) / 1000)
642 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
643 		THC_LOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
644 		TAILQ_FOREACH(hc_entry, &V_tcp_hostcache.hashbase[i].hch_bucket,
645 			      rmx_q) {
646 			sbuf_printf(&sb,
647 			    "%-15s %5u %8u %6lums %6lums %8u %8u %8u %4lu "
648 			    "%4lu %4i\n",
649 			    hc_entry->ip4.s_addr ?
650 			        inet_ntoa_r(hc_entry->ip4, ip4buf) :
651 #ifdef INET6
652 				ip6_sprintf(ip6buf, &hc_entry->ip6),
653 #else
654 				"IPv6?",
655 #endif
656 			    hc_entry->rmx_mtu,
657 			    hc_entry->rmx_ssthresh,
658 			    msec((u_long)hc_entry->rmx_rtt *
659 				(RTM_RTTUNIT / (hz * TCP_RTT_SCALE))),
660 			    msec((u_long)hc_entry->rmx_rttvar *
661 				(RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE))),
662 			    hc_entry->rmx_cwnd,
663 			    hc_entry->rmx_sendpipe,
664 			    hc_entry->rmx_recvpipe,
665 			    hc_entry->rmx_hits,
666 			    hc_entry->rmx_updates,
667 			    hc_entry->rmx_expire);
668 		}
669 		THC_UNLOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
670 	}
671 #undef msec
672 	error = sbuf_finish(&sb);
673 	if (error == 0)
674 		error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
675 	sbuf_delete(&sb);
676 	return(error);
677 }
678 
679 /*
680  * Caller has to make sure the curvnet is set properly.
681  */
682 static void
683 tcp_hc_purge_internal(int all)
684 {
685 	struct hc_metrics *hc_entry, *hc_next;
686 	int i;
687 
688 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
689 		THC_LOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
690 		TAILQ_FOREACH_SAFE(hc_entry,
691 		    &V_tcp_hostcache.hashbase[i].hch_bucket, rmx_q, hc_next) {
692 			if (all || hc_entry->rmx_expire <= 0) {
693 				TAILQ_REMOVE(&V_tcp_hostcache.hashbase[i].hch_bucket,
694 					      hc_entry, rmx_q);
695 				uma_zfree(V_tcp_hostcache.zone, hc_entry);
696 				V_tcp_hostcache.hashbase[i].hch_length--;
697 				V_tcp_hostcache.cache_count--;
698 			} else
699 				hc_entry->rmx_expire -= V_tcp_hostcache.prune;
700 		}
701 		THC_UNLOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
702 	}
703 }
704 
705 /*
706  * Expire and purge (old|all) entries in the tcp_hostcache.  Runs
707  * periodically from the callout.
708  */
709 static void
710 tcp_hc_purge(void *arg)
711 {
712 	CURVNET_SET((struct vnet *) arg);
713 	int all = 0;
714 
715 	if (V_tcp_hostcache.purgeall) {
716 		all = 1;
717 		V_tcp_hostcache.purgeall = 0;
718 	}
719 
720 	tcp_hc_purge_internal(all);
721 
722 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
723 	    tcp_hc_purge, arg);
724 	CURVNET_RESTORE();
725 }
726 
727 /*
728  * Expire and purge all entries in hostcache immediately.
729  */
730 static int
731 sysctl_tcp_hc_purgenow(SYSCTL_HANDLER_ARGS)
732 {
733 	int error, val;
734 
735 	val = 0;
736 	error = sysctl_handle_int(oidp, &val, 0, req);
737 	if (error || !req->newptr)
738 		return (error);
739 
740 	tcp_hc_purge_internal(1);
741 
742 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
743 	    tcp_hc_purge, curvnet);
744 
745 	return (0);
746 }
747