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