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