xref: /freebsd/sys/netinet/tcp_hostcache.c (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2002 Andre Oppermann, Internet Business Solutions AG
5  * Copyright (c) 2021 Gleb Smirnoff <glebius@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote
17  *    products derived from this software without specific prior written
18  *    permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * The tcp_hostcache moves the tcp-specific cached metrics from the routing
35  * table to a dedicated structure indexed by the remote IP address.  It keeps
36  * information on the measured TCP parameters of past TCP sessions to allow
37  * better initial start values to be used with later connections to/from the
38  * same source.  Depending on the network parameters (delay, max MTU,
39  * congestion window) between local and remote sites, this can lead to
40  * significant speed-ups for new TCP connections after the first one.
41  *
42  * Due to the tcp_hostcache, all TCP-specific metrics information in the
43  * routing table have been removed.  The inpcb no longer keeps a pointer to
44  * the routing entry, and protocol-initiated route cloning has been removed
45  * as well.  With these changes, the routing table has gone back to being
46  * more lightwight and only carries information related to packet forwarding.
47  *
48  * tcp_hostcache is designed for multiple concurrent access in SMP
49  * environments and high contention.  It is a straight hash.  Each bucket row
50  * is protected by its own lock for modification.  Readers are protected by
51  * SMR.  This puts certain restrictions on writers, e.g. a writer shall only
52  * insert a fully populated entry into a row.  Writer can't reuse least used
53  * entry if a hash is full.  Value updates for an entry shall be atomic.
54  *
55  * TCP stack(s) communication with tcp_hostcache() is done via KBI functions
56  * tcp_hc_*() and the hc_metrics_lite structure.
57  *
58  * Since tcp_hostcache is only caching information, there are no fatal
59  * consequences if we either can't allocate a new entry or have to drop
60  * an existing entry, or return somewhat stale information.
61  */
62 
63 /*
64  * Many thanks to jlemon for basic structure of tcp_syncache which is being
65  * followed here.
66  */
67 
68 #include <sys/cdefs.h>
69 #include "opt_inet6.h"
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/hash.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/smr.h>
82 #include <sys/socket.h>
83 #include <sys/socketvar.h>
84 #include <sys/sysctl.h>
85 
86 #include <net/vnet.h>
87 
88 #include <netinet/in.h>
89 #include <netinet/in_pcb.h>
90 #include <netinet/tcp.h>
91 #include <netinet/tcp_var.h>
92 
93 #include <vm/uma.h>
94 
95 struct hc_head {
96 	CK_SLIST_HEAD(hc_qhead, hc_metrics) hch_bucket;
97 	u_int		hch_length;
98 	struct mtx	hch_mtx;
99 };
100 
101 struct hc_metrics {
102 	/* housekeeping */
103 	CK_SLIST_ENTRY(hc_metrics) rmx_q;
104 	struct		in_addr ip4;	/* IP address */
105 	struct		in6_addr ip6;	/* IP6 address */
106 	uint32_t	ip6_zoneid;	/* IPv6 scope zone id */
107 	/* endpoint specific values for tcp */
108 	uint32_t	rmx_mtu;	/* MTU for this path */
109 	uint32_t	rmx_ssthresh;	/* outbound gateway buffer limit */
110 	uint32_t	rmx_rtt;	/* estimated round trip time */
111 	uint32_t	rmx_rttvar;	/* estimated rtt variance */
112 	uint32_t	rmx_cwnd;	/* congestion window */
113 	uint32_t	rmx_sendpipe;	/* outbound delay-bandwidth product */
114 	uint32_t	rmx_recvpipe;	/* inbound delay-bandwidth product */
115 	/* TCP hostcache internal data */
116 	int		rmx_expire;	/* lifetime for object */
117 #ifdef	TCP_HC_COUNTERS
118 	u_long		rmx_hits;	/* number of hits */
119 	u_long		rmx_updates;	/* number of updates */
120 #endif
121 };
122 
123 struct tcp_hostcache {
124 	struct hc_head	*hashbase;
125 	uma_zone_t	zone;
126 	smr_t		smr;
127 	u_int		hashsize;
128 	u_int		hashmask;
129 	u_int		hashsalt;
130 	u_int		bucket_limit;
131 	u_int		cache_count;
132 	u_int		cache_limit;
133 	int		expire;
134 	int		prune;
135 	int		purgeall;
136 };
137 
138 /* Arbitrary values */
139 #define TCP_HOSTCACHE_HASHSIZE		512
140 #define TCP_HOSTCACHE_BUCKETLIMIT	30
141 #define TCP_HOSTCACHE_EXPIRE		60*60	/* one hour */
142 #define TCP_HOSTCACHE_PRUNE		5*60	/* every 5 minutes */
143 
144 VNET_DEFINE_STATIC(struct tcp_hostcache, tcp_hostcache);
145 #define	V_tcp_hostcache		VNET(tcp_hostcache)
146 
147 VNET_DEFINE_STATIC(struct callout, tcp_hc_callout);
148 #define	V_tcp_hc_callout	VNET(tcp_hc_callout)
149 
150 static struct hc_metrics *tcp_hc_lookup(struct in_conninfo *);
151 static int sysctl_tcp_hc_list(SYSCTL_HANDLER_ARGS);
152 static int sysctl_tcp_hc_histo(SYSCTL_HANDLER_ARGS);
153 static int sysctl_tcp_hc_purgenow(SYSCTL_HANDLER_ARGS);
154 static void tcp_hc_purge_internal(int);
155 static void tcp_hc_purge(void *);
156 
157 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, hostcache,
158     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
159     "TCP Host cache");
160 
161 VNET_DEFINE(int, tcp_use_hostcache) = 1;
162 #define V_tcp_use_hostcache  VNET(tcp_use_hostcache)
163 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
164     &VNET_NAME(tcp_use_hostcache), 0,
165     "Enable the TCP hostcache");
166 
167 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, cachelimit, CTLFLAG_VNET | CTLFLAG_RDTUN,
168     &VNET_NAME(tcp_hostcache.cache_limit), 0,
169     "Overall entry limit for hostcache");
170 
171 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
172     &VNET_NAME(tcp_hostcache.hashsize), 0,
173     "Size of TCP hostcache hashtable");
174 
175 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, bucketlimit,
176     CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(tcp_hostcache.bucket_limit), 0,
177     "Per-bucket hash limit for hostcache");
178 
179 SYSCTL_UINT(_net_inet_tcp_hostcache, OID_AUTO, count, CTLFLAG_VNET | CTLFLAG_RD,
180     &VNET_NAME(tcp_hostcache.cache_count), 0,
181     "Current number of entries in hostcache");
182 
183 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, expire, CTLFLAG_VNET | CTLFLAG_RW,
184     &VNET_NAME(tcp_hostcache.expire), 0,
185     "Expire time of TCP hostcache entries");
186 
187 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, prune, CTLFLAG_VNET | CTLFLAG_RW,
188     &VNET_NAME(tcp_hostcache.prune), 0,
189     "Time between purge runs");
190 
191 SYSCTL_INT(_net_inet_tcp_hostcache, OID_AUTO, purge, CTLFLAG_VNET | CTLFLAG_RW,
192     &VNET_NAME(tcp_hostcache.purgeall), 0,
193     "Expire all entries on next purge run");
194 
195 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, list,
196     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE,
197     0, 0, sysctl_tcp_hc_list, "A",
198     "List of all hostcache entries");
199 
200 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, histo,
201     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE,
202     0, 0, sysctl_tcp_hc_histo, "A",
203     "Print a histogram of hostcache hashbucket utilization");
204 
205 SYSCTL_PROC(_net_inet_tcp_hostcache, OID_AUTO, purgenow,
206     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
207     NULL, 0, sysctl_tcp_hc_purgenow, "I",
208     "Immediately purge all entries");
209 
210 static MALLOC_DEFINE(M_HOSTCACHE, "hostcache", "TCP hostcache");
211 
212 /* Use jenkins_hash32(), as in other parts of the tcp stack */
213 #define	HOSTCACHE_HASH(inc)						\
214 	((inc)->inc_flags & INC_ISIPV6) ?				\
215 		(jenkins_hash32((inc)->inc6_faddr.s6_addr32, 4,		\
216 		V_tcp_hostcache.hashsalt) & V_tcp_hostcache.hashmask)	\
217 	:								\
218 		(jenkins_hash32(&(inc)->inc_faddr.s_addr, 1,		\
219 		V_tcp_hostcache.hashsalt) & V_tcp_hostcache.hashmask)
220 
221 #define THC_LOCK(h)		mtx_lock(&(h)->hch_mtx)
222 #define THC_UNLOCK(h)		mtx_unlock(&(h)->hch_mtx)
223 
224 void
225 tcp_hc_init(void)
226 {
227 	u_int cache_limit;
228 	int i;
229 
230 	/*
231 	 * Initialize hostcache structures.
232 	 */
233 	atomic_store_int(&V_tcp_hostcache.cache_count, 0);
234 	V_tcp_hostcache.hashsize = TCP_HOSTCACHE_HASHSIZE;
235 	V_tcp_hostcache.bucket_limit = TCP_HOSTCACHE_BUCKETLIMIT;
236 	V_tcp_hostcache.expire = TCP_HOSTCACHE_EXPIRE;
237 	V_tcp_hostcache.prune = TCP_HOSTCACHE_PRUNE;
238 	V_tcp_hostcache.hashsalt = arc4random();
239 
240 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.hashsize",
241 	    &V_tcp_hostcache.hashsize);
242 	if (!powerof2(V_tcp_hostcache.hashsize)) {
243 		printf("WARNING: hostcache hash size is not a power of 2.\n");
244 		V_tcp_hostcache.hashsize = TCP_HOSTCACHE_HASHSIZE; /* default */
245 	}
246 	V_tcp_hostcache.hashmask = V_tcp_hostcache.hashsize - 1;
247 
248 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.bucketlimit",
249 	    &V_tcp_hostcache.bucket_limit);
250 
251 	cache_limit = V_tcp_hostcache.hashsize * V_tcp_hostcache.bucket_limit;
252 	V_tcp_hostcache.cache_limit = cache_limit;
253 	TUNABLE_INT_FETCH("net.inet.tcp.hostcache.cachelimit",
254 	    &V_tcp_hostcache.cache_limit);
255 	if (V_tcp_hostcache.cache_limit > cache_limit)
256 		V_tcp_hostcache.cache_limit = cache_limit;
257 
258 	/*
259 	 * Allocate the hash table.
260 	 */
261 	V_tcp_hostcache.hashbase = (struct hc_head *)
262 	    malloc(V_tcp_hostcache.hashsize * sizeof(struct hc_head),
263 		   M_HOSTCACHE, M_WAITOK | M_ZERO);
264 
265 	/*
266 	 * Initialize the hash buckets.
267 	 */
268 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
269 		CK_SLIST_INIT(&V_tcp_hostcache.hashbase[i].hch_bucket);
270 		V_tcp_hostcache.hashbase[i].hch_length = 0;
271 		mtx_init(&V_tcp_hostcache.hashbase[i].hch_mtx, "tcp_hc_entry",
272 			  NULL, MTX_DEF);
273 	}
274 
275 	/*
276 	 * Allocate the hostcache entries.
277 	 */
278 	V_tcp_hostcache.zone =
279 	    uma_zcreate("hostcache", sizeof(struct hc_metrics),
280 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
281 	uma_zone_set_max(V_tcp_hostcache.zone, V_tcp_hostcache.cache_limit);
282 	V_tcp_hostcache.smr = uma_zone_get_smr(V_tcp_hostcache.zone);
283 
284 	/*
285 	 * Set up periodic cache cleanup.
286 	 */
287 	callout_init(&V_tcp_hc_callout, 1);
288 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
289 	    tcp_hc_purge, curvnet);
290 }
291 
292 #ifdef VIMAGE
293 void
294 tcp_hc_destroy(void)
295 {
296 	int i;
297 
298 	callout_drain(&V_tcp_hc_callout);
299 
300 	/* Purge all hc entries. */
301 	tcp_hc_purge_internal(1);
302 
303 	/* Free the uma zone and the allocated hash table. */
304 	uma_zdestroy(V_tcp_hostcache.zone);
305 
306 	for (i = 0; i < V_tcp_hostcache.hashsize; i++)
307 		mtx_destroy(&V_tcp_hostcache.hashbase[i].hch_mtx);
308 	free(V_tcp_hostcache.hashbase, M_HOSTCACHE);
309 }
310 #endif
311 
312 /*
313  * Internal function: compare cache entry to a connection.
314  */
315 static bool
316 tcp_hc_cmp(struct hc_metrics *hc_entry, struct in_conninfo *inc)
317 {
318 
319 	if (inc->inc_flags & INC_ISIPV6) {
320 		/* XXX: check ip6_zoneid */
321 		if (memcmp(&inc->inc6_faddr, &hc_entry->ip6,
322 		    sizeof(inc->inc6_faddr)) == 0)
323 			return (true);
324 	} else {
325 		if (memcmp(&inc->inc_faddr, &hc_entry->ip4,
326 		    sizeof(inc->inc_faddr)) == 0)
327 			return (true);
328 	}
329 
330 	return (false);
331 }
332 
333 /*
334  * Internal function: look up an entry in the hostcache for read.
335  * On success returns in SMR section.
336  */
337 static struct hc_metrics *
338 tcp_hc_lookup(struct in_conninfo *inc)
339 {
340 	struct hc_head *hc_head;
341 	struct hc_metrics *hc_entry;
342 
343 	KASSERT(inc != NULL, ("%s: NULL in_conninfo", __func__));
344 
345 	hc_head = &V_tcp_hostcache.hashbase[HOSTCACHE_HASH(inc)];
346 
347 	/*
348 	 * Iterate through entries in bucket row looking for a match.
349 	 */
350 	smr_enter(V_tcp_hostcache.smr);
351 	CK_SLIST_FOREACH(hc_entry, &hc_head->hch_bucket, rmx_q)
352 		if (tcp_hc_cmp(hc_entry, inc))
353 			break;
354 
355 	if (hc_entry != NULL) {
356 		if (atomic_load_int(&hc_entry->rmx_expire) !=
357 		    V_tcp_hostcache.expire)
358 			atomic_store_int(&hc_entry->rmx_expire,
359 			    V_tcp_hostcache.expire);
360 #ifdef	TCP_HC_COUNTERS
361 		hc_entry->rmx_hits++;
362 #endif
363 	} else
364 		smr_exit(V_tcp_hostcache.smr);
365 
366 	return (hc_entry);
367 }
368 
369 /*
370  * External function: look up an entry in the hostcache and fill out the
371  * supplied TCP metrics structure.  Fills in NULL when no entry was found or
372  * a value is not set.
373  */
374 void
375 tcp_hc_get(struct in_conninfo *inc, struct hc_metrics_lite *hc_metrics_lite)
376 {
377 	struct hc_metrics *hc_entry;
378 
379 	if (!V_tcp_use_hostcache) {
380 		bzero(hc_metrics_lite, sizeof(*hc_metrics_lite));
381 		return;
382 	}
383 
384 	/*
385 	 * Find the right bucket.
386 	 */
387 	hc_entry = tcp_hc_lookup(inc);
388 
389 	/*
390 	 * If we don't have an existing object.
391 	 */
392 	if (hc_entry == NULL) {
393 		bzero(hc_metrics_lite, sizeof(*hc_metrics_lite));
394 		return;
395 	}
396 
397 	hc_metrics_lite->rmx_mtu = atomic_load_32(&hc_entry->rmx_mtu);
398 	hc_metrics_lite->rmx_ssthresh = atomic_load_32(&hc_entry->rmx_ssthresh);
399 	hc_metrics_lite->rmx_rtt = atomic_load_32(&hc_entry->rmx_rtt);
400 	hc_metrics_lite->rmx_rttvar = atomic_load_32(&hc_entry->rmx_rttvar);
401 	hc_metrics_lite->rmx_cwnd = atomic_load_32(&hc_entry->rmx_cwnd);
402 	hc_metrics_lite->rmx_sendpipe = atomic_load_32(&hc_entry->rmx_sendpipe);
403 	hc_metrics_lite->rmx_recvpipe = atomic_load_32(&hc_entry->rmx_recvpipe);
404 
405 	smr_exit(V_tcp_hostcache.smr);
406 }
407 
408 /*
409  * External function: look up an entry in the hostcache and return the
410  * discovered path MTU.  Returns 0 if no entry is found or value is not
411  * set.
412  */
413 uint32_t
414 tcp_hc_getmtu(struct in_conninfo *inc)
415 {
416 	struct hc_metrics *hc_entry;
417 	uint32_t mtu;
418 
419 	if (!V_tcp_use_hostcache)
420 		return (0);
421 
422 	hc_entry = tcp_hc_lookup(inc);
423 	if (hc_entry == NULL) {
424 		return (0);
425 	}
426 
427 	mtu = atomic_load_32(&hc_entry->rmx_mtu);
428 	smr_exit(V_tcp_hostcache.smr);
429 
430 	return (mtu);
431 }
432 
433 /*
434  * External function: update the MTU value of an entry in the hostcache.
435  * Creates a new entry if none was found.
436  */
437 void
438 tcp_hc_updatemtu(struct in_conninfo *inc, uint32_t mtu)
439 {
440 	struct hc_metrics_lite hcml = { .rmx_mtu = mtu };
441 
442 	return (tcp_hc_update(inc, &hcml));
443 }
444 
445 /*
446  * External function: update the TCP metrics of an entry in the hostcache.
447  * Creates a new entry if none was found.
448  */
449 void
450 tcp_hc_update(struct in_conninfo *inc, struct hc_metrics_lite *hcml)
451 {
452 	struct hc_head *hc_head;
453 	struct hc_metrics *hc_entry, *hc_prev;
454 	uint32_t v;
455 	bool new;
456 
457 	if (!V_tcp_use_hostcache)
458 		return;
459 
460 	hc_head = &V_tcp_hostcache.hashbase[HOSTCACHE_HASH(inc)];
461 	hc_prev = NULL;
462 
463 	THC_LOCK(hc_head);
464 	CK_SLIST_FOREACH(hc_entry, &hc_head->hch_bucket, rmx_q) {
465 		if (tcp_hc_cmp(hc_entry, inc))
466 			break;
467 		if (CK_SLIST_NEXT(hc_entry, rmx_q) != NULL)
468 			hc_prev = hc_entry;
469 	}
470 
471 	if (hc_entry != NULL) {
472 		if (atomic_load_int(&hc_entry->rmx_expire) !=
473 		    V_tcp_hostcache.expire)
474 			atomic_store_int(&hc_entry->rmx_expire,
475 			    V_tcp_hostcache.expire);
476 #ifdef	TCP_HC_COUNTERS
477 		hc_entry->rmx_updates++;
478 #endif
479 		new = false;
480 	} else {
481 		/*
482 		 * Try to allocate a new entry.  If the bucket limit is
483 		 * reached, delete the least-used element, located at the end
484 		 * of the CK_SLIST.  During lookup we saved the pointer to
485 		 * the second to last element, in case if list has at least 2
486 		 * elements.  This will allow to delete last element without
487 		 * extra traversal.
488 		 *
489 		 * Give up if the row is empty.
490 		 */
491 		if (hc_head->hch_length >= V_tcp_hostcache.bucket_limit ||
492 		    atomic_load_int(&V_tcp_hostcache.cache_count) >=
493 		    V_tcp_hostcache.cache_limit) {
494 			if (hc_prev != NULL) {
495 				hc_entry = CK_SLIST_NEXT(hc_prev, rmx_q);
496 				KASSERT(CK_SLIST_NEXT(hc_entry, rmx_q) == NULL,
497 				    ("%s: %p is not one to last",
498 				    __func__, hc_prev));
499 				CK_SLIST_REMOVE_AFTER(hc_prev, rmx_q);
500 			} else if ((hc_entry =
501 			    CK_SLIST_FIRST(&hc_head->hch_bucket)) != NULL) {
502 				KASSERT(CK_SLIST_NEXT(hc_entry, rmx_q) == NULL,
503 				    ("%s: %p is not the only element",
504 				    __func__, hc_entry));
505 				CK_SLIST_REMOVE_HEAD(&hc_head->hch_bucket,
506 				    rmx_q);
507 			} else {
508 				THC_UNLOCK(hc_head);
509 				return;
510 			}
511 			KASSERT(hc_head->hch_length > 0 &&
512 			    hc_head->hch_length <= V_tcp_hostcache.bucket_limit,
513 			    ("tcp_hostcache: bucket length violated at %p",
514 			    hc_head));
515 			hc_head->hch_length--;
516 			atomic_subtract_int(&V_tcp_hostcache.cache_count, 1);
517 			TCPSTAT_INC(tcps_hc_bucketoverflow);
518 			uma_zfree_smr(V_tcp_hostcache.zone, hc_entry);
519 		}
520 
521 		/*
522 		 * Allocate a new entry, or balk if not possible.
523 		 */
524 		hc_entry = uma_zalloc_smr(V_tcp_hostcache.zone, M_NOWAIT);
525 		if (hc_entry == NULL) {
526 			THC_UNLOCK(hc_head);
527 			return;
528 		}
529 
530 		/*
531 		 * Initialize basic information of hostcache entry.
532 		 */
533 		bzero(hc_entry, sizeof(*hc_entry));
534 		if (inc->inc_flags & INC_ISIPV6) {
535 			hc_entry->ip6 = inc->inc6_faddr;
536 			hc_entry->ip6_zoneid = inc->inc6_zoneid;
537 		} else
538 			hc_entry->ip4 = inc->inc_faddr;
539 		hc_entry->rmx_expire = V_tcp_hostcache.expire;
540 		new = true;
541 	}
542 
543 	/*
544 	 * Fill in data.  Use atomics, since an existing entry is
545 	 * accessible by readers in SMR section.
546 	 */
547 	if (hcml->rmx_mtu != 0) {
548 		atomic_store_32(&hc_entry->rmx_mtu, hcml->rmx_mtu);
549 	}
550 	if (hcml->rmx_rtt != 0) {
551 		if (hc_entry->rmx_rtt == 0)
552 			v = hcml->rmx_rtt;
553 		else
554 			v = ((uint64_t)hc_entry->rmx_rtt +
555 			    (uint64_t)hcml->rmx_rtt) / 2;
556 		atomic_store_32(&hc_entry->rmx_rtt, v);
557 		TCPSTAT_INC(tcps_cachedrtt);
558 	}
559 	if (hcml->rmx_rttvar != 0) {
560 	        if (hc_entry->rmx_rttvar == 0)
561 			v = hcml->rmx_rttvar;
562 		else
563 			v = ((uint64_t)hc_entry->rmx_rttvar +
564 			    (uint64_t)hcml->rmx_rttvar) / 2;
565 		atomic_store_32(&hc_entry->rmx_rttvar, v);
566 		TCPSTAT_INC(tcps_cachedrttvar);
567 	}
568 	if (hcml->rmx_ssthresh != 0) {
569 		if (hc_entry->rmx_ssthresh == 0)
570 			v = hcml->rmx_ssthresh;
571 		else
572 			v = (hc_entry->rmx_ssthresh + hcml->rmx_ssthresh) / 2;
573 		atomic_store_32(&hc_entry->rmx_ssthresh, v);
574 		TCPSTAT_INC(tcps_cachedssthresh);
575 	}
576 	if (hcml->rmx_cwnd != 0) {
577 		if (hc_entry->rmx_cwnd == 0)
578 			v = hcml->rmx_cwnd;
579 		else
580 			v = ((uint64_t)hc_entry->rmx_cwnd +
581 			    (uint64_t)hcml->rmx_cwnd) / 2;
582 		atomic_store_32(&hc_entry->rmx_cwnd, v);
583 		/* TCPSTAT_INC(tcps_cachedcwnd); */
584 	}
585 	if (hcml->rmx_sendpipe != 0) {
586 		if (hc_entry->rmx_sendpipe == 0)
587 			v = hcml->rmx_sendpipe;
588 		else
589 			v = ((uint64_t)hc_entry->rmx_sendpipe +
590 			    (uint64_t)hcml->rmx_sendpipe) /2;
591 		atomic_store_32(&hc_entry->rmx_sendpipe, v);
592 		/* TCPSTAT_INC(tcps_cachedsendpipe); */
593 	}
594 	if (hcml->rmx_recvpipe != 0) {
595 		if (hc_entry->rmx_recvpipe == 0)
596 			v = hcml->rmx_recvpipe;
597 		else
598 			v = ((uint64_t)hc_entry->rmx_recvpipe +
599 			    (uint64_t)hcml->rmx_recvpipe) /2;
600 		atomic_store_32(&hc_entry->rmx_recvpipe, v);
601 		/* TCPSTAT_INC(tcps_cachedrecvpipe); */
602 	}
603 
604 	/*
605 	 * Put it upfront.
606 	 */
607 	if (new) {
608 		CK_SLIST_INSERT_HEAD(&hc_head->hch_bucket, hc_entry, rmx_q);
609 		hc_head->hch_length++;
610 		KASSERT(hc_head->hch_length <= V_tcp_hostcache.bucket_limit,
611 		    ("tcp_hostcache: bucket length too high at %p", hc_head));
612 		atomic_add_int(&V_tcp_hostcache.cache_count, 1);
613 		TCPSTAT_INC(tcps_hc_added);
614 	} else if (hc_entry != CK_SLIST_FIRST(&hc_head->hch_bucket)) {
615 		KASSERT(CK_SLIST_NEXT(hc_prev, rmx_q) == hc_entry,
616 		    ("%s: %p next is not %p", __func__, hc_prev, hc_entry));
617 		CK_SLIST_REMOVE_AFTER(hc_prev, rmx_q);
618 		CK_SLIST_INSERT_HEAD(&hc_head->hch_bucket, hc_entry, rmx_q);
619 	}
620 	THC_UNLOCK(hc_head);
621 }
622 
623 /*
624  * Sysctl function: prints the list and values of all hostcache entries in
625  * unsorted order.
626  */
627 static int
628 sysctl_tcp_hc_list(SYSCTL_HANDLER_ARGS)
629 {
630 	const int linesize = 128;
631 	struct sbuf sb;
632 	int i, error, len;
633 	struct hc_metrics *hc_entry;
634 	char ip4buf[INET_ADDRSTRLEN];
635 #ifdef INET6
636 	char ip6buf[INET6_ADDRSTRLEN];
637 #endif
638 
639 	if (jailed_without_vnet(curthread->td_ucred) != 0)
640 		return (EPERM);
641 
642 	/* Optimize Buffer length query by sbin/sysctl */
643 	if (req->oldptr == NULL) {
644 		len = (atomic_load_int(&V_tcp_hostcache.cache_count) + 1) *
645 			linesize;
646 		return (SYSCTL_OUT(req, NULL, len));
647 	}
648 
649 	error = sysctl_wire_old_buffer(req, 0);
650 	if (error != 0) {
651 		return(error);
652 	}
653 
654 	/* Use a buffer sized for one full bucket */
655 	sbuf_new_for_sysctl(&sb, NULL, V_tcp_hostcache.bucket_limit *
656 		linesize, req);
657 
658 	sbuf_printf(&sb,
659 		"\nIP address        MTU  SSTRESH      RTT   RTTVAR "
660 		"    CWND SENDPIPE RECVPIPE "
661 #ifdef	TCP_HC_COUNTERS
662 		"HITS  UPD  "
663 #endif
664 		"EXP\n");
665 	sbuf_drain(&sb);
666 
667 #define msec(u) (((u) + 500) / 1000)
668 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
669 		THC_LOCK(&V_tcp_hostcache.hashbase[i]);
670 		CK_SLIST_FOREACH(hc_entry,
671 		    &V_tcp_hostcache.hashbase[i].hch_bucket, rmx_q) {
672 			sbuf_printf(&sb,
673 			    "%-15s %5u %8u %6lums %6lums %8u %8u %8u "
674 #ifdef	TCP_HC_COUNTERS
675 			    "%4lu %4lu "
676 #endif
677 			    "%4i\n",
678 			    hc_entry->ip4.s_addr ?
679 			        inet_ntoa_r(hc_entry->ip4, ip4buf) :
680 #ifdef INET6
681 				ip6_sprintf(ip6buf, &hc_entry->ip6),
682 #else
683 				"IPv6?",
684 #endif
685 			    hc_entry->rmx_mtu,
686 			    hc_entry->rmx_ssthresh,
687 			    msec((u_long)hc_entry->rmx_rtt *
688 				(RTM_RTTUNIT / (hz * TCP_RTT_SCALE))),
689 			    msec((u_long)hc_entry->rmx_rttvar *
690 				(RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE))),
691 			    hc_entry->rmx_cwnd,
692 			    hc_entry->rmx_sendpipe,
693 			    hc_entry->rmx_recvpipe,
694 #ifdef	TCP_HC_COUNTERS
695 			    hc_entry->rmx_hits,
696 			    hc_entry->rmx_updates,
697 #endif
698 			    hc_entry->rmx_expire);
699 		}
700 		THC_UNLOCK(&V_tcp_hostcache.hashbase[i]);
701 		sbuf_drain(&sb);
702 	}
703 #undef msec
704 	error = sbuf_finish(&sb);
705 	sbuf_delete(&sb);
706 	return(error);
707 }
708 
709 /*
710  * Sysctl function: prints a histogram of the hostcache hashbucket
711  * utilization.
712  */
713 static int
714 sysctl_tcp_hc_histo(SYSCTL_HANDLER_ARGS)
715 {
716 	const int linesize = 50;
717 	struct sbuf sb;
718 	int i, error;
719 	int *histo;
720 	u_int hch_length;
721 
722 	if (jailed_without_vnet(curthread->td_ucred) != 0)
723 		return (EPERM);
724 
725 	histo = (int *)malloc(sizeof(int) * (V_tcp_hostcache.bucket_limit + 1),
726 			M_TEMP, M_NOWAIT|M_ZERO);
727 	if (histo == NULL)
728 		return(ENOMEM);
729 
730 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
731 		hch_length = V_tcp_hostcache.hashbase[i].hch_length;
732 		KASSERT(hch_length <= V_tcp_hostcache.bucket_limit,
733 		    ("tcp_hostcache: bucket limit exceeded at %u: %u",
734 		    i, hch_length));
735 		histo[hch_length]++;
736 	}
737 
738 	/* Use a buffer for 16 lines */
739 	sbuf_new_for_sysctl(&sb, NULL, 16 * linesize, req);
740 
741 	sbuf_printf(&sb, "\nLength\tCount\n");
742 	for (i = 0; i <= V_tcp_hostcache.bucket_limit; i++) {
743 		sbuf_printf(&sb, "%u\t%u\n", i, histo[i]);
744 	}
745 	error = sbuf_finish(&sb);
746 	sbuf_delete(&sb);
747 	free(histo, M_TEMP);
748 	return(error);
749 }
750 
751 /*
752  * Caller has to make sure the curvnet is set properly.
753  */
754 static void
755 tcp_hc_purge_internal(int all)
756 {
757 	struct hc_head *head;
758 	struct hc_metrics *hc_entry, *hc_next, *hc_prev;
759 	int i;
760 
761 	for (i = 0; i < V_tcp_hostcache.hashsize; i++) {
762 		head = &V_tcp_hostcache.hashbase[i];
763 		hc_prev = NULL;
764 		THC_LOCK(head);
765 		CK_SLIST_FOREACH_SAFE(hc_entry, &head->hch_bucket, rmx_q,
766 		    hc_next) {
767 			KASSERT(head->hch_length > 0 && head->hch_length <=
768 			    V_tcp_hostcache.bucket_limit, ("tcp_hostcache: "
769 			    "bucket length out of range at %u: %u", i,
770 			    head->hch_length));
771 			if (all ||
772 			    atomic_load_int(&hc_entry->rmx_expire) <= 0) {
773 				if (hc_prev != NULL) {
774 					KASSERT(hc_entry ==
775 					    CK_SLIST_NEXT(hc_prev, rmx_q),
776 					    ("%s: %p is not next to %p",
777 					    __func__, hc_entry, hc_prev));
778 					CK_SLIST_REMOVE_AFTER(hc_prev, rmx_q);
779 				} else {
780 					KASSERT(hc_entry ==
781 					    CK_SLIST_FIRST(&head->hch_bucket),
782 					    ("%s: %p is not first",
783 					    __func__, hc_entry));
784 					CK_SLIST_REMOVE_HEAD(&head->hch_bucket,
785 					    rmx_q);
786 				}
787 				uma_zfree_smr(V_tcp_hostcache.zone, hc_entry);
788 				head->hch_length--;
789 				atomic_subtract_int(&V_tcp_hostcache.cache_count, 1);
790 			} else {
791 				atomic_subtract_int(&hc_entry->rmx_expire,
792 				    V_tcp_hostcache.prune);
793 				hc_prev = hc_entry;
794 			}
795 		}
796 		THC_UNLOCK(head);
797 	}
798 }
799 
800 /*
801  * Expire and purge (old|all) entries in the tcp_hostcache.  Runs
802  * periodically from the callout.
803  */
804 static void
805 tcp_hc_purge(void *arg)
806 {
807 	CURVNET_SET((struct vnet *) arg);
808 	int all = 0;
809 
810 	if (V_tcp_hostcache.purgeall) {
811 		if (V_tcp_hostcache.purgeall == 2)
812 			V_tcp_hostcache.hashsalt = arc4random();
813 		all = 1;
814 		V_tcp_hostcache.purgeall = 0;
815 	}
816 
817 	tcp_hc_purge_internal(all);
818 
819 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
820 	    tcp_hc_purge, arg);
821 	CURVNET_RESTORE();
822 }
823 
824 /*
825  * Expire and purge all entries in hostcache immediately.
826  */
827 static int
828 sysctl_tcp_hc_purgenow(SYSCTL_HANDLER_ARGS)
829 {
830 	int error, val;
831 
832 	val = 0;
833 	error = sysctl_handle_int(oidp, &val, 0, req);
834 	if (error || !req->newptr)
835 		return (error);
836 
837 	if (val == 2)
838 		V_tcp_hostcache.hashsalt = arc4random();
839 	tcp_hc_purge_internal(1);
840 
841 	callout_reset(&V_tcp_hc_callout, V_tcp_hostcache.prune * hz,
842 	    tcp_hc_purge, curvnet);
843 
844 	return (0);
845 }
846