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