xref: /freebsd-src/sys/netinet/tcp_hostcache.c (revision 2cca4c0ee03dde51ec64db6684933fcb0a2de290)
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 #ifdef INET6
103 #include <netinet6/tcp6_var.h>
104 #endif
105 
106 #include <vm/uma.h>
107 
108 TAILQ_HEAD(hc_qhead, hc_metrics);
109 
110 struct hc_head {
111 	struct hc_qhead	hch_bucket;
112 	u_int		hch_length;
113 	struct mtx	hch_mtx;
114 };
115 
116 struct hc_metrics {
117 	/* housekeeping */
118 	TAILQ_ENTRY(hc_metrics) rmx_q;
119 	struct		hc_head *rmx_head; /* head of bucket tail queue */
120 	struct		in_addr ip4;	/* IP address */
121 	struct		in6_addr ip6;	/* IP6 address */
122 	uint32_t	ip6_zoneid;	/* IPv6 scope zone id */
123 	/* endpoint specific values for tcp */
124 	uint32_t	rmx_mtu;	/* MTU for this path */
125 	uint32_t	rmx_ssthresh;	/* outbound gateway buffer limit */
126 	uint32_t	rmx_rtt;	/* estimated round trip time */
127 	uint32_t	rmx_rttvar;	/* estimated rtt variance */
128 	uint32_t	rmx_cwnd;	/* congestion window */
129 	uint32_t	rmx_sendpipe;	/* outbound delay-bandwidth product */
130 	uint32_t	rmx_recvpipe;	/* inbound delay-bandwidth product */
131 	/* TCP hostcache internal data */
132 	int		rmx_expire;	/* lifetime for object */
133 	u_long		rmx_hits;	/* number of hits */
134 	u_long		rmx_updates;	/* number of updates */
135 };
136 
137 struct tcp_hostcache {
138 	struct hc_head	*hashbase;
139 	uma_zone_t	zone;
140 	u_int		hashsize;
141 	u_int		hashmask;
142 	u_int		bucket_limit;
143 	u_int		cache_count;
144 	u_int		cache_limit;
145 	int		expire;
146 	int		prune;
147 	int		purgeall;
148 };
149 
150 /* Arbitrary values */
151 #define TCP_HOSTCACHE_HASHSIZE		512
152 #define TCP_HOSTCACHE_BUCKETLIMIT	30
153 #define TCP_HOSTCACHE_EXPIRE		60*60	/* one hour */
154 #define TCP_HOSTCACHE_PRUNE		5*60	/* every 5 minutes */
155 
156 VNET_DEFINE_STATIC(struct tcp_hostcache, tcp_hostcache);
157 #define	V_tcp_hostcache		VNET(tcp_hostcache)
158 
159 VNET_DEFINE_STATIC(struct callout, tcp_hc_callout);
160 #define	V_tcp_hc_callout	VNET(tcp_hc_callout)
161 
162 static struct hc_metrics *tcp_hc_lookup(struct in_conninfo *);
163 static struct hc_metrics *tcp_hc_insert(struct in_conninfo *);
164 static int sysctl_tcp_hc_list(SYSCTL_HANDLER_ARGS);
165 static int sysctl_tcp_hc_histo(SYSCTL_HANDLER_ARGS);
166 static int sysctl_tcp_hc_purgenow(SYSCTL_HANDLER_ARGS);
167 static void tcp_hc_purge_internal(int);
168 static void tcp_hc_purge(void *);
169 
170 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, hostcache,
171     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
172     "TCP Host cache");
173 
174 VNET_DEFINE(int, tcp_use_hostcache) = 1;
175 #define V_tcp_use_hostcache  VNET(tcp_use_hostcache)
176 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
177     &VNET_NAME(tcp_use_hostcache), 0,
178     "Enable the TCP hostcache");
179 
180 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, cachelimit, CTLFLAG_VNET | CTLFLAG_RDTUN,
181     &VNET_NAME(tcp_hostcache.cache_limit), 0,
182     "Overall entry limit for hostcache");
183 
184 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
185     &VNET_NAME(tcp_hostcache.hashsize), 0,
186     "Size of TCP hostcache hashtable");
187 
188 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, bucketlimit,
189     CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(tcp_hostcache.bucket_limit), 0,
190     "Per-bucket hash limit for hostcache");
191 
192 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, count, CTLFLAG_VNET | CTLFLAG_RD,
193      &VNET_NAME(tcp_hostcache.cache_count), 0,
194     "Current number of entries in hostcache");
195 
196 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, expire, CTLFLAG_VNET | CTLFLAG_RW,
197     &VNET_NAME(tcp_hostcache.expire), 0,
198     "Expire time of TCP hostcache entries");
199 
200 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, prune, CTLFLAG_VNET | CTLFLAG_RW,
201     &VNET_NAME(tcp_hostcache.prune), 0,
202     "Time between purge runs");
203 
204 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, purge, CTLFLAG_VNET | CTLFLAG_RW,
205     &VNET_NAME(tcp_hostcache.purgeall), 0,
206     "Expire all entires on next purge run");
207 
208 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, list,
209     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE,
210     0, 0, sysctl_tcp_hc_list, "A",
211     "List of all hostcache entries");
212 
213 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, histo,
214     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE,
215     0, 0, sysctl_tcp_hc_histo, "A",
216     "Print a histogram of hostcache hashbucket utilization");
217 
218 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, purgenow,
219     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
220     NULL, 0, sysctl_tcp_hc_purgenow, "I",
221     "Immediately purge all entries");
222 
223 static MALLOC_DEFINE(M_HOSTCACHE, "hostcache", "TCP hostcache");
224 
225 #define HOSTCACHE_HASH(ip) \
226 	(((ip)->s_addr ^ ((ip)->s_addr >> 7) ^ ((ip)->s_addr >> 17)) &	\
227 	  V_tcp_hostcache.hashmask)
228 
229 /* XXX: What is the recommended hash to get good entropy for IPv6 addresses? */
230 #define HOSTCACHE_HASH6(ip6)				\
231 	(((ip6)->s6_addr32[0] ^				\
232 	  (ip6)->s6_addr32[1] ^				\
233 	  (ip6)->s6_addr32[2] ^				\
234 	  (ip6)->s6_addr32[3]) &			\
235 	 V_tcp_hostcache.hashmask)
236 
237 #define THC_LOCK(lp)		mtx_lock(lp)
238 #define THC_UNLOCK(lp)		mtx_unlock(lp)
239 
240 void
241 tcp_hc_init(void)
242 {
243 	u_int cache_limit;
244 	int i;
245 
246 	/*
247 	 * Initialize hostcache structures.
248 	 */
249 	atomic_store_int(&V_tcp_hostcache.cache_count, 0);
250 	V_tcp_hostcache.hashsize = TCP_HOSTCACHE_HASHSIZE;
251 	V_tcp_hostcache.bucket_limit = TCP_HOSTCACHE_BUCKETLIMIT;
252 	V_tcp_hostcache.expire = TCP_HOSTCACHE_EXPIRE;
253 	V_tcp_hostcache.prune = TCP_HOSTCACHE_PRUNE;
254 
255 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.hashsize",
256 	    &V_tcp_hostcache.hashsize);
257 	if (!powerof2(V_tcp_hostcache.hashsize)) {
258 		printf("WARNING: hostcache hash size is not a power of 2.\n");
259 		V_tcp_hostcache.hashsize = TCP_HOSTCACHE_HASHSIZE; /* default */
260 	}
261 	V_tcp_hostcache.hashmask = V_tcp_hostcache.hashsize - 1;
262 
263 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.bucketlimit",
264 	    &V_tcp_hostcache.bucket_limit);
265 
266 	cache_limit = V_tcp_hostcache.hashsize * V_tcp_hostcache.bucket_limit;
267 	V_tcp_hostcache.cache_limit = cache_limit;
268 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.cachelimit",
269 	    &V_tcp_hostcache.cache_limit);
270 	if (V_tcp_hostcache.cache_limit > cache_limit)
271 		V_tcp_hostcache.cache_limit = cache_limit;
272 
273 	/*
274 	 * Allocate the hash table.
275 	 */
276 	V_tcp_hostcache.hashbase = (struct hc_head *)
277 	    malloc(V_tcp_hostcache.hashsize * sizeof(struct hc_head),
278 		   M_HOSTCACHE, M_WAITOK | M_ZERO);
279 
280 	/*
281 	 * Initialize the hash buckets.
282 	 */
283 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
284 		TAILQ_INIT(&V_tcp_hostcache.hashbase[i].hch_bucket);
285 		V_tcp_hostcache.hashbase[i].hch_length = 0;
286 		mtx_init(&V_tcp_hostcache.hashbase[i].hch_mtx, "tcp_hc_entry",
287 			  NULL, MTX_DEF);
288 	}
289 
290 	/*
291 	 * Allocate the hostcache entries.
292 	 */
293 	V_tcp_hostcache.zone =
294 	    uma_zcreate("hostcache", sizeof(struct hc_metrics),
295 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
296 	uma_zone_set_max(V_tcp_hostcache.zone, V_tcp_hostcache.cache_limit);
297 
298 	/*
299 	 * Set up periodic cache cleanup.
300 	 */
301 	callout_init(&V_tcp_hc_callout, 1);
302 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
303 	    tcp_hc_purge, curvnet);
304 }
305 
306 #ifdef VIMAGE
307 void
308 tcp_hc_destroy(void)
309 {
310 	int i;
311 
312 	callout_drain(&V_tcp_hc_callout);
313 
314 	/* Purge all hc entries. */
315 	tcp_hc_purge_internal(1);
316 
317 	/* Free the uma zone and the allocated hash table. */
318 	uma_zdestroy(V_tcp_hostcache.zone);
319 
320 	for (i = 0; i < V_tcp_hostcache.hashsize; i++)
321 		mtx_destroy(&V_tcp_hostcache.hashbase[i].hch_mtx);
322 	free(V_tcp_hostcache.hashbase, M_HOSTCACHE);
323 }
324 #endif
325 
326 /*
327  * Internal function: look up an entry in the hostcache or return NULL.
328  *
329  * If an entry has been returned, the caller becomes responsible for
330  * unlocking the bucket row after he is done reading/modifying the entry.
331  */
332 static struct hc_metrics *
333 tcp_hc_lookup(struct in_conninfo *inc)
334 {
335 	int hash;
336 	struct hc_head *hc_head;
337 	struct hc_metrics *hc_entry;
338 
339 	if (!V_tcp_use_hostcache)
340 		return NULL;
341 
342 	KASSERT(inc != NULL, ("tcp_hc_lookup with NULL in_conninfo pointer"));
343 
344 	/*
345 	 * Hash the foreign ip address.
346 	 */
347 	if (inc->inc_flags & INC_ISIPV6)
348 		hash = HOSTCACHE_HASH6(&inc->inc6_faddr);
349 	else
350 		hash = HOSTCACHE_HASH(&inc->inc_faddr);
351 
352 	hc_head = &V_tcp_hostcache.hashbase[hash];
353 
354 	/*
355 	 * Acquire lock for this bucket row; we release the lock if we don't
356 	 * find an entry, otherwise the caller has to unlock after he is
357 	 * done.
358 	 */
359 	THC_LOCK(&hc_head->hch_mtx);
360 
361 	/*
362 	 * Iterate through entries in bucket row looking for a match.
363 	 */
364 	TAILQ_FOREACH(hc_entry, &hc_head->hch_bucket, rmx_q) {
365 		if (inc->inc_flags & INC_ISIPV6) {
366 			/* XXX: check ip6_zoneid */
367 			if (memcmp(&inc->inc6_faddr, &hc_entry->ip6,
368 			    sizeof(inc->inc6_faddr)) == 0)
369 				return hc_entry;
370 		} else {
371 			if (memcmp(&inc->inc_faddr, &hc_entry->ip4,
372 			    sizeof(inc->inc_faddr)) == 0)
373 				return hc_entry;
374 		}
375 	}
376 
377 	/*
378 	 * We were unsuccessful and didn't find anything.
379 	 */
380 	THC_UNLOCK(&hc_head->hch_mtx);
381 	return NULL;
382 }
383 
384 /*
385  * Internal function: insert an entry into the hostcache or return NULL if
386  * unable to allocate a new one.
387  *
388  * If an entry has been returned, the caller becomes responsible for
389  * unlocking the bucket row after he is done reading/modifying the entry.
390  */
391 static struct hc_metrics *
392 tcp_hc_insert(struct in_conninfo *inc)
393 {
394 	int hash;
395 	struct hc_head *hc_head;
396 	struct hc_metrics *hc_entry;
397 
398 	if (!V_tcp_use_hostcache)
399 		return NULL;
400 
401 	KASSERT(inc != NULL, ("tcp_hc_insert with NULL in_conninfo pointer"));
402 
403 	/*
404 	 * Hash the foreign ip address.
405 	 */
406 	if (inc->inc_flags & INC_ISIPV6)
407 		hash = HOSTCACHE_HASH6(&inc->inc6_faddr);
408 	else
409 		hash = HOSTCACHE_HASH(&inc->inc_faddr);
410 
411 	hc_head = &V_tcp_hostcache.hashbase[hash];
412 
413 	/*
414 	 * Acquire lock for this bucket row; we release the lock if we don't
415 	 * find an entry, otherwise the caller has to unlock after he is
416 	 * done.
417 	 */
418 	THC_LOCK(&hc_head->hch_mtx);
419 
420 	/*
421 	 * If the bucket limit is reached, reuse the least-used element.
422 	 */
423 	if (hc_head->hch_length >= V_tcp_hostcache.bucket_limit ||
424 	    atomic_load_int(&V_tcp_hostcache.cache_count) >= V_tcp_hostcache.cache_limit) {
425 		hc_entry = TAILQ_LAST(&hc_head->hch_bucket, hc_qhead);
426 		/*
427 		 * At first we were dropping the last element, just to
428 		 * reacquire it in the next two lines again, which isn't very
429 		 * efficient.  Instead just reuse the least used element.
430 		 * We may drop something that is still "in-use" but we can be
431 		 * "lossy".
432 		 * Just give up if this bucket row is empty and we don't have
433 		 * anything to replace.
434 		 */
435 		if (hc_entry == NULL) {
436 			THC_UNLOCK(&hc_head->hch_mtx);
437 			return NULL;
438 		}
439 		TAILQ_REMOVE(&hc_head->hch_bucket, hc_entry, rmx_q);
440 		KASSERT(V_tcp_hostcache.hashbase[hash].hch_length > 0 &&
441 			V_tcp_hostcache.hashbase[hash].hch_length <=
442 			V_tcp_hostcache.bucket_limit,
443 			("tcp_hostcache: bucket length range violated at %u: %u",
444 			hash, V_tcp_hostcache.hashbase[hash].hch_length));
445 		V_tcp_hostcache.hashbase[hash].hch_length--;
446 		atomic_subtract_int(&V_tcp_hostcache.cache_count, 1);
447 		TCPSTAT_INC(tcps_hc_bucketoverflow);
448 #if 0
449 		uma_zfree(V_tcp_hostcache.zone, hc_entry);
450 #endif
451 	} else {
452 		/*
453 		 * Allocate a new entry, or balk if not possible.
454 		 */
455 		hc_entry = uma_zalloc(V_tcp_hostcache.zone, M_NOWAIT);
456 		if (hc_entry == NULL) {
457 			THC_UNLOCK(&hc_head->hch_mtx);
458 			return NULL;
459 		}
460 	}
461 
462 	/*
463 	 * Initialize basic information of hostcache entry.
464 	 */
465 	bzero(hc_entry, sizeof(*hc_entry));
466 	if (inc->inc_flags & INC_ISIPV6) {
467 		hc_entry->ip6 = inc->inc6_faddr;
468 		hc_entry->ip6_zoneid = inc->inc6_zoneid;
469 	} else
470 		hc_entry->ip4 = inc->inc_faddr;
471 	hc_entry->rmx_head = hc_head;
472 	hc_entry->rmx_expire = V_tcp_hostcache.expire;
473 
474 	/*
475 	 * Put it upfront.
476 	 */
477 	TAILQ_INSERT_HEAD(&hc_head->hch_bucket, hc_entry, rmx_q);
478 	V_tcp_hostcache.hashbase[hash].hch_length++;
479 	KASSERT(V_tcp_hostcache.hashbase[hash].hch_length <
480 		V_tcp_hostcache.bucket_limit,
481 		("tcp_hostcache: bucket length too high at %u: %u",
482 		hash, V_tcp_hostcache.hashbase[hash].hch_length));
483 	atomic_add_int(&V_tcp_hostcache.cache_count, 1);
484 	TCPSTAT_INC(tcps_hc_added);
485 
486 	return hc_entry;
487 }
488 
489 /*
490  * External function: look up an entry in the hostcache and fill out the
491  * supplied TCP metrics structure.  Fills in NULL when no entry was found or
492  * a value is not set.
493  */
494 void
495 tcp_hc_get(struct in_conninfo *inc, struct hc_metrics_lite *hc_metrics_lite)
496 {
497 	struct hc_metrics *hc_entry;
498 
499 	if (!V_tcp_use_hostcache) {
500 		bzero(hc_metrics_lite, sizeof(*hc_metrics_lite));
501 		return;
502 	}
503 
504 	/*
505 	 * Find the right bucket.
506 	 */
507 	hc_entry = tcp_hc_lookup(inc);
508 
509 	/*
510 	 * If we don't have an existing object.
511 	 */
512 	if (hc_entry == NULL) {
513 		bzero(hc_metrics_lite, sizeof(*hc_metrics_lite));
514 		return;
515 	}
516 	hc_entry->rmx_hits++;
517 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
518 
519 	hc_metrics_lite->rmx_mtu = hc_entry->rmx_mtu;
520 	hc_metrics_lite->rmx_ssthresh = hc_entry->rmx_ssthresh;
521 	hc_metrics_lite->rmx_rtt = hc_entry->rmx_rtt;
522 	hc_metrics_lite->rmx_rttvar = hc_entry->rmx_rttvar;
523 	hc_metrics_lite->rmx_cwnd = hc_entry->rmx_cwnd;
524 	hc_metrics_lite->rmx_sendpipe = hc_entry->rmx_sendpipe;
525 	hc_metrics_lite->rmx_recvpipe = hc_entry->rmx_recvpipe;
526 
527 	/*
528 	 * Unlock bucket row.
529 	 */
530 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
531 }
532 
533 /*
534  * External function: look up an entry in the hostcache and return the
535  * discovered path MTU.  Returns 0 if no entry is found or value is not
536  * set.
537  */
538 uint32_t
539 tcp_hc_getmtu(struct in_conninfo *inc)
540 {
541 	struct hc_metrics *hc_entry;
542 	uint32_t mtu;
543 
544 	if (!V_tcp_use_hostcache)
545 		return 0;
546 
547 	hc_entry = tcp_hc_lookup(inc);
548 	if (hc_entry == NULL) {
549 		return 0;
550 	}
551 	hc_entry->rmx_hits++;
552 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
553 
554 	mtu = hc_entry->rmx_mtu;
555 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
556 	return mtu;
557 }
558 
559 /*
560  * External function: update the MTU value of an entry in the hostcache.
561  * Creates a new entry if none was found.
562  */
563 void
564 tcp_hc_updatemtu(struct in_conninfo *inc, uint32_t mtu)
565 {
566 	struct hc_metrics *hc_entry;
567 
568 	if (!V_tcp_use_hostcache)
569 		return;
570 
571 	/*
572 	 * Find the right bucket.
573 	 */
574 	hc_entry = tcp_hc_lookup(inc);
575 
576 	/*
577 	 * If we don't have an existing object, try to insert a new one.
578 	 */
579 	if (hc_entry == NULL) {
580 		hc_entry = tcp_hc_insert(inc);
581 		if (hc_entry == NULL)
582 			return;
583 	}
584 	hc_entry->rmx_updates++;
585 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
586 
587 	hc_entry->rmx_mtu = mtu;
588 
589 	/*
590 	 * Put it upfront so we find it faster next time.
591 	 */
592 	TAILQ_REMOVE(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
593 	TAILQ_INSERT_HEAD(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
594 
595 	/*
596 	 * Unlock bucket row.
597 	 */
598 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
599 }
600 
601 /*
602  * External function: update the TCP metrics of an entry in the hostcache.
603  * Creates a new entry if none was found.
604  */
605 void
606 tcp_hc_update(struct in_conninfo *inc, struct hc_metrics_lite *hcml)
607 {
608 	struct hc_metrics *hc_entry;
609 
610 	if (!V_tcp_use_hostcache)
611 		return;
612 
613 	hc_entry = tcp_hc_lookup(inc);
614 	if (hc_entry == NULL) {
615 		hc_entry = tcp_hc_insert(inc);
616 		if (hc_entry == NULL)
617 			return;
618 	}
619 	hc_entry->rmx_updates++;
620 	hc_entry->rmx_expire = V_tcp_hostcache.expire; /* start over again */
621 
622 	if (hcml->rmx_rtt != 0) {
623 		if (hc_entry->rmx_rtt == 0)
624 			hc_entry->rmx_rtt = hcml->rmx_rtt;
625 		else
626 			hc_entry->rmx_rtt = ((uint64_t)hc_entry->rmx_rtt +
627 			    (uint64_t)hcml->rmx_rtt) / 2;
628 		TCPSTAT_INC(tcps_cachedrtt);
629 	}
630 	if (hcml->rmx_rttvar != 0) {
631 	        if (hc_entry->rmx_rttvar == 0)
632 			hc_entry->rmx_rttvar = hcml->rmx_rttvar;
633 		else
634 			hc_entry->rmx_rttvar = ((uint64_t)hc_entry->rmx_rttvar +
635 			    (uint64_t)hcml->rmx_rttvar) / 2;
636 		TCPSTAT_INC(tcps_cachedrttvar);
637 	}
638 	if (hcml->rmx_ssthresh != 0) {
639 		if (hc_entry->rmx_ssthresh == 0)
640 			hc_entry->rmx_ssthresh = hcml->rmx_ssthresh;
641 		else
642 			hc_entry->rmx_ssthresh =
643 			    (hc_entry->rmx_ssthresh + hcml->rmx_ssthresh) / 2;
644 		TCPSTAT_INC(tcps_cachedssthresh);
645 	}
646 	if (hcml->rmx_cwnd != 0) {
647 		if (hc_entry->rmx_cwnd == 0)
648 			hc_entry->rmx_cwnd = hcml->rmx_cwnd;
649 		else
650 			hc_entry->rmx_cwnd = ((uint64_t)hc_entry->rmx_cwnd +
651 			    (uint64_t)hcml->rmx_cwnd) / 2;
652 		/* TCPSTAT_INC(tcps_cachedcwnd); */
653 	}
654 	if (hcml->rmx_sendpipe != 0) {
655 		if (hc_entry->rmx_sendpipe == 0)
656 			hc_entry->rmx_sendpipe = hcml->rmx_sendpipe;
657 		else
658 			hc_entry->rmx_sendpipe =
659 			    ((uint64_t)hc_entry->rmx_sendpipe +
660 			    (uint64_t)hcml->rmx_sendpipe) /2;
661 		/* TCPSTAT_INC(tcps_cachedsendpipe); */
662 	}
663 	if (hcml->rmx_recvpipe != 0) {
664 		if (hc_entry->rmx_recvpipe == 0)
665 			hc_entry->rmx_recvpipe = hcml->rmx_recvpipe;
666 		else
667 			hc_entry->rmx_recvpipe =
668 			    ((uint64_t)hc_entry->rmx_recvpipe +
669 			    (uint64_t)hcml->rmx_recvpipe) /2;
670 		/* TCPSTAT_INC(tcps_cachedrecvpipe); */
671 	}
672 
673 	TAILQ_REMOVE(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
674 	TAILQ_INSERT_HEAD(&hc_entry->rmx_head->hch_bucket, hc_entry, rmx_q);
675 	THC_UNLOCK(&hc_entry->rmx_head->hch_mtx);
676 }
677 
678 /*
679  * Sysctl function: prints the list and values of all hostcache entries in
680  * unsorted order.
681  */
682 static int
683 sysctl_tcp_hc_list(SYSCTL_HANDLER_ARGS)
684 {
685 	const int linesize = 128;
686 	struct sbuf sb;
687 	int i, error, len;
688 	struct hc_metrics *hc_entry;
689 	char ip4buf[INET_ADDRSTRLEN];
690 #ifdef INET6
691 	char ip6buf[INET6_ADDRSTRLEN];
692 #endif
693 
694 	if (jailed_without_vnet(curthread->td_ucred) != 0)
695 		return (EPERM);
696 
697 	/* Optimize Buffer length query by sbin/sysctl */
698 	if (req->oldptr == NULL) {
699 		len = (atomic_load_int(&V_tcp_hostcache.cache_count) + 1) *
700 			linesize;
701 		return (SYSCTL_OUT(req, NULL, len));
702 	}
703 
704 	error = sysctl_wire_old_buffer(req, 0);
705 	if (error != 0) {
706 		return(error);
707 	}
708 
709 	/* Use a buffer sized for one full bucket */
710 	sbuf_new_for_sysctl(&sb, NULL, V_tcp_hostcache.bucket_limit *
711 		linesize, req);
712 
713 	sbuf_printf(&sb,
714 		"\nIP address        MTU  SSTRESH      RTT   RTTVAR "
715 		"    CWND SENDPIPE RECVPIPE HITS  UPD  EXP\n");
716 	sbuf_drain(&sb);
717 
718 #define msec(u) (((u) + 500) / 1000)
719 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
720 		THC_LOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
721 		TAILQ_FOREACH(hc_entry, &V_tcp_hostcache.hashbase[i].hch_bucket,
722 			      rmx_q) {
723 			sbuf_printf(&sb,
724 			    "%-15s %5u %8u %6lums %6lums %8u %8u %8u %4lu "
725 			    "%4lu %4i\n",
726 			    hc_entry->ip4.s_addr ?
727 			        inet_ntoa_r(hc_entry->ip4, ip4buf) :
728 #ifdef INET6
729 				ip6_sprintf(ip6buf, &hc_entry->ip6),
730 #else
731 				"IPv6?",
732 #endif
733 			    hc_entry->rmx_mtu,
734 			    hc_entry->rmx_ssthresh,
735 			    msec((u_long)hc_entry->rmx_rtt *
736 				(RTM_RTTUNIT / (hz * TCP_RTT_SCALE))),
737 			    msec((u_long)hc_entry->rmx_rttvar *
738 				(RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE))),
739 			    hc_entry->rmx_cwnd,
740 			    hc_entry->rmx_sendpipe,
741 			    hc_entry->rmx_recvpipe,
742 			    hc_entry->rmx_hits,
743 			    hc_entry->rmx_updates,
744 			    hc_entry->rmx_expire);
745 		}
746 		THC_UNLOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
747 		sbuf_drain(&sb);
748 	}
749 #undef msec
750 	error = sbuf_finish(&sb);
751 	sbuf_delete(&sb);
752 	return(error);
753 }
754 
755 /*
756  * Sysctl function: prints a histogram of the hostcache hashbucket
757  * utilization.
758  */
759 static int
760 sysctl_tcp_hc_histo(SYSCTL_HANDLER_ARGS)
761 {
762 	const int linesize = 50;
763 	struct sbuf sb;
764 	int i, error;
765 	int *histo;
766 	u_int hch_length;
767 
768 	if (jailed_without_vnet(curthread->td_ucred) != 0)
769 		return (EPERM);
770 
771 	histo = (int *)malloc(sizeof(int) * (V_tcp_hostcache.bucket_limit + 1),
772 			M_TEMP, M_NOWAIT|M_ZERO);
773 	if (histo == NULL)
774 		return(ENOMEM);
775 
776 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
777 		hch_length = V_tcp_hostcache.hashbase[i].hch_length;
778 		KASSERT(hch_length <= V_tcp_hostcache.bucket_limit,
779 			("tcp_hostcache: bucket limit exceeded at %u: %u",
780 			i, hch_length));
781 		histo[hch_length]++;
782 	}
783 
784 	/* Use a buffer for 16 lines */
785 	sbuf_new_for_sysctl(&sb, NULL, 16 * linesize, req);
786 
787 	sbuf_printf(&sb, "\nLength\tCount\n");
788 	for (i = 0; i <= V_tcp_hostcache.bucket_limit; i++) {
789 		sbuf_printf(&sb, "%u\t%u\n", i, histo[i]);
790 	}
791 	error = sbuf_finish(&sb);
792 	sbuf_delete(&sb);
793 	free(histo, M_TEMP);
794 	return(error);
795 }
796 
797 /*
798  * Caller has to make sure the curvnet is set properly.
799  */
800 static void
801 tcp_hc_purge_internal(int all)
802 {
803 	struct hc_metrics *hc_entry, *hc_next;
804 	int i;
805 
806 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
807 		THC_LOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
808 		TAILQ_FOREACH_SAFE(hc_entry,
809 		    &V_tcp_hostcache.hashbase[i].hch_bucket, rmx_q, hc_next) {
810 			KASSERT(V_tcp_hostcache.hashbase[i].hch_length > 0 &&
811 				V_tcp_hostcache.hashbase[i].hch_length <=
812 				V_tcp_hostcache.bucket_limit,
813 				("tcp_hostcache: bucket length out of range at %u: %u",
814 				i, V_tcp_hostcache.hashbase[i].hch_length));
815 			if (all || hc_entry->rmx_expire <= 0) {
816 				TAILQ_REMOVE(&V_tcp_hostcache.hashbase[i].hch_bucket,
817 					      hc_entry, rmx_q);
818 				uma_zfree(V_tcp_hostcache.zone, hc_entry);
819 				V_tcp_hostcache.hashbase[i].hch_length--;
820 				atomic_subtract_int(&V_tcp_hostcache.cache_count, 1);
821 			} else
822 				hc_entry->rmx_expire -= V_tcp_hostcache.prune;
823 		}
824 		THC_UNLOCK(&V_tcp_hostcache.hashbase[i].hch_mtx);
825 	}
826 }
827 
828 /*
829  * Expire and purge (old|all) entries in the tcp_hostcache.  Runs
830  * periodically from the callout.
831  */
832 static void
833 tcp_hc_purge(void *arg)
834 {
835 	CURVNET_SET((struct vnet *) arg);
836 	int all = 0;
837 
838 	if (V_tcp_hostcache.purgeall) {
839 		all = 1;
840 		V_tcp_hostcache.purgeall = 0;
841 	}
842 
843 	tcp_hc_purge_internal(all);
844 
845 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
846 	    tcp_hc_purge, arg);
847 	CURVNET_RESTORE();
848 }
849 
850 /*
851  * Expire and purge all entries in hostcache immediately.
852  */
853 static int
854 sysctl_tcp_hc_purgenow(SYSCTL_HANDLER_ARGS)
855 {
856 	int error, val;
857 
858 	val = 0;
859 	error = sysctl_handle_int(oidp, &val, 0, req);
860 	if (error || !req->newptr)
861 		return (error);
862 
863 	tcp_hc_purge_internal(1);
864 
865 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
866 	    tcp_hc_purge, curvnet);
867 
868 	return (0);
869 }
870