ip_flow.c revision 1.72 1 /* $NetBSD: ip_flow.c,v 1.72 2016/06/20 06:46:38 knakahara Exp $ */
2
3 /*-
4 * Copyright (c) 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by the 3am Software Foundry ("3am"). It was developed by Matt Thomas.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: ip_flow.c,v 1.72 2016/06/20 06:46:38 knakahara Exp $");
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/mbuf.h>
39 #include <sys/domain.h>
40 #include <sys/protosw.h>
41 #include <sys/socket.h>
42 #include <sys/socketvar.h>
43 #include <sys/errno.h>
44 #include <sys/time.h>
45 #include <sys/kernel.h>
46 #include <sys/pool.h>
47 #include <sys/sysctl.h>
48
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/route.h>
52 #include <net/pfil.h>
53
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
57 #include <netinet/in_pcb.h>
58 #include <netinet/in_var.h>
59 #include <netinet/ip_var.h>
60 #include <netinet/ip_private.h>
61
62 /*
63 * Similar code is very well commented in netinet6/ip6_flow.c
64 */
65
66 #define IPFLOW_HASHBITS 6 /* should not be a multiple of 8 */
67
68 static struct pool ipflow_pool;
69
70 LIST_HEAD(ipflowhead, ipflow);
71
72 #define IPFLOW_TIMER (5 * PR_SLOWHZ)
73 #define IPFLOW_DEFAULT_HASHSIZE (1 << IPFLOW_HASHBITS)
74
75 /*
76 * ip_flow.c internal lock.
77 * If we use softnet_lock, it would cause recursive lock.
78 *
79 * This is a tentative workaround.
80 * We should make it scalable somehow in the future.
81 */
82 static kmutex_t ipflow_lock;
83 static struct ipflowhead *ipflowtable = NULL;
84 static struct ipflowhead ipflowlist;
85 static int ipflow_inuse;
86
87 #define IPFLOW_INSERT(bucket, ipf) \
88 do { \
89 LIST_INSERT_HEAD((bucket), (ipf), ipf_hash); \
90 LIST_INSERT_HEAD(&ipflowlist, (ipf), ipf_list); \
91 } while (/*CONSTCOND*/ 0)
92
93 #define IPFLOW_REMOVE(ipf) \
94 do { \
95 LIST_REMOVE((ipf), ipf_hash); \
96 LIST_REMOVE((ipf), ipf_list); \
97 } while (/*CONSTCOND*/ 0)
98
99 #ifndef IPFLOW_MAX
100 #define IPFLOW_MAX 256
101 #endif
102 static int ip_maxflows = IPFLOW_MAX;
103 static int ip_hashsize = IPFLOW_DEFAULT_HASHSIZE;
104
105 static struct ipflow *ipflow_reap(bool);
106 static void ipflow_sysctl_init(struct sysctllog **);
107
108 static size_t
109 ipflow_hash(const struct ip *ip)
110 {
111 size_t hash = ip->ip_tos;
112 size_t idx;
113
114 for (idx = 0; idx < 32; idx += IPFLOW_HASHBITS) {
115 hash += (ip->ip_dst.s_addr >> (32 - idx)) +
116 (ip->ip_src.s_addr >> idx);
117 }
118
119 return hash & (ip_hashsize-1);
120 }
121
122 static struct ipflow *
123 ipflow_lookup(const struct ip *ip)
124 {
125 size_t hash;
126 struct ipflow *ipf;
127
128 KASSERT(mutex_owned(&ipflow_lock));
129
130 hash = ipflow_hash(ip);
131
132 LIST_FOREACH(ipf, &ipflowtable[hash], ipf_hash) {
133 if (ip->ip_dst.s_addr == ipf->ipf_dst.s_addr
134 && ip->ip_src.s_addr == ipf->ipf_src.s_addr
135 && ip->ip_tos == ipf->ipf_tos)
136 break;
137 }
138 return ipf;
139 }
140
141 void
142 ipflow_poolinit(void)
143 {
144
145 pool_init(&ipflow_pool, sizeof(struct ipflow), 0, 0, 0, "ipflowpl",
146 NULL, IPL_NET);
147 }
148
149 static int
150 ipflow_reinit(int table_size)
151 {
152 struct ipflowhead *new_table;
153 size_t i;
154
155 KASSERT(mutex_owned(&ipflow_lock));
156
157 new_table = (struct ipflowhead *)malloc(sizeof(struct ipflowhead) *
158 table_size, M_RTABLE, M_NOWAIT);
159
160 if (new_table == NULL)
161 return 1;
162
163 if (ipflowtable != NULL)
164 free(ipflowtable, M_RTABLE);
165
166 ipflowtable = new_table;
167 ip_hashsize = table_size;
168
169 LIST_INIT(&ipflowlist);
170 for (i = 0; i < ip_hashsize; i++)
171 LIST_INIT(&ipflowtable[i]);
172
173 return 0;
174 }
175
176 void
177 ipflow_init(void)
178 {
179
180 mutex_init(&ipflow_lock, MUTEX_DEFAULT, IPL_NONE);
181
182 mutex_enter(&ipflow_lock);
183 (void)ipflow_reinit(ip_hashsize);
184 mutex_exit(&ipflow_lock);
185 ipflow_sysctl_init(NULL);
186 }
187
188 int
189 ipflow_fastforward(struct mbuf *m)
190 {
191 struct ip *ip;
192 struct ip ip_store;
193 struct ipflow *ipf;
194 struct rtentry *rt;
195 const struct sockaddr *dst;
196 int error;
197 int iplen;
198 struct ifnet *ifp;
199 int s;
200 int ret = 0;
201
202 mutex_enter(&ipflow_lock);
203 /*
204 * Are we forwarding packets? Big enough for an IP packet?
205 */
206 if (!ipforwarding || ipflow_inuse == 0 || m->m_len < sizeof(struct ip))
207 goto out;
208
209 /*
210 * Was packet received as a link-level multicast or broadcast?
211 * If so, don't try to fast forward..
212 */
213 if ((m->m_flags & (M_BCAST|M_MCAST)) != 0)
214 goto out;
215
216 /*
217 * IP header with no option and valid version and length
218 */
219 if (IP_HDR_ALIGNED_P(mtod(m, const void *)))
220 ip = mtod(m, struct ip *);
221 else {
222 memcpy(&ip_store, mtod(m, const void *), sizeof(ip_store));
223 ip = &ip_store;
224 }
225 iplen = ntohs(ip->ip_len);
226 if (ip->ip_v != IPVERSION || ip->ip_hl != (sizeof(struct ip) >> 2) ||
227 iplen < sizeof(struct ip) || iplen > m->m_pkthdr.len)
228 goto out;
229 /*
230 * Find a flow.
231 */
232 if ((ipf = ipflow_lookup(ip)) == NULL)
233 goto out;
234
235 ifp = m_get_rcvif(m, &s);
236 /*
237 * Verify the IP header checksum.
238 */
239 switch (m->m_pkthdr.csum_flags &
240 ((ifp->if_csum_flags_rx & M_CSUM_IPv4) |
241 M_CSUM_IPv4_BAD)) {
242 case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
243 m_put_rcvif(ifp, &s);
244 goto out;
245
246 case M_CSUM_IPv4:
247 /* Checksum was okay. */
248 break;
249
250 default:
251 /* Must compute it ourselves. */
252 if (in_cksum(m, sizeof(struct ip)) != 0) {
253 m_put_rcvif(ifp, &s);
254 goto out;
255 }
256 break;
257 }
258 m_put_rcvif(ifp, &s);
259
260 /*
261 * Route and interface still up?
262 */
263 if ((rt = rtcache_validate(&ipf->ipf_ro)) == NULL ||
264 (rt->rt_ifp->if_flags & IFF_UP) == 0 ||
265 (rt->rt_flags & (RTF_BLACKHOLE | RTF_BROADCAST)) != 0)
266 goto out;
267
268 /*
269 * Packet size OK? TTL?
270 */
271 if (m->m_pkthdr.len > rt->rt_ifp->if_mtu || ip->ip_ttl <= IPTTLDEC)
272 goto out;
273
274 /*
275 * Clear any in-bound checksum flags for this packet.
276 */
277 m->m_pkthdr.csum_flags = 0;
278
279 /*
280 * Everything checks out and so we can forward this packet.
281 * Modify the TTL and incrementally change the checksum.
282 *
283 * This method of adding the checksum works on either endian CPU.
284 * If htons() is inlined, all the arithmetic is folded; otherwise
285 * the htons()s are combined by CSE due to the const attribute.
286 *
287 * Don't bother using HW checksumming here -- the incremental
288 * update is pretty fast.
289 */
290 ip->ip_ttl -= IPTTLDEC;
291 if (ip->ip_sum >= (u_int16_t) ~htons(IPTTLDEC << 8))
292 ip->ip_sum -= ~htons(IPTTLDEC << 8);
293 else
294 ip->ip_sum += htons(IPTTLDEC << 8);
295
296 /*
297 * Done modifying the header; copy it back, if necessary.
298 *
299 * XXX Use m_copyback_cow(9) here? --dyoung
300 */
301 if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0)
302 memcpy(mtod(m, void *), &ip_store, sizeof(ip_store));
303
304 /*
305 * Trim the packet in case it's too long..
306 */
307 if (m->m_pkthdr.len > iplen) {
308 if (m->m_len == m->m_pkthdr.len) {
309 m->m_len = iplen;
310 m->m_pkthdr.len = iplen;
311 } else
312 m_adj(m, iplen - m->m_pkthdr.len);
313 }
314
315 /*
316 * Send the packet on its way. All we can get back is ENOBUFS
317 */
318 ipf->ipf_uses++;
319 PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
320
321 if (rt->rt_flags & RTF_GATEWAY)
322 dst = rt->rt_gateway;
323 else
324 dst = rtcache_getdst(&ipf->ipf_ro);
325
326 if ((error = if_output_lock(rt->rt_ifp, rt->rt_ifp, m, dst, rt)) != 0) {
327 if (error == ENOBUFS)
328 ipf->ipf_dropped++;
329 else
330 ipf->ipf_errors++;
331 }
332 ret = 1;
333 out:
334 mutex_exit(&ipflow_lock);
335 return ret;
336 }
337
338 static void
340 ipflow_addstats(struct ipflow *ipf)
341 {
342 struct rtentry *rt;
343 uint64_t *ips;
344
345 if ((rt = rtcache_validate(&ipf->ipf_ro)) != NULL)
346 rt->rt_use += ipf->ipf_uses;
347
348 ips = IP_STAT_GETREF();
349 ips[IP_STAT_CANTFORWARD] += ipf->ipf_errors + ipf->ipf_dropped;
350 ips[IP_STAT_TOTAL] += ipf->ipf_uses;
351 ips[IP_STAT_FORWARD] += ipf->ipf_uses;
352 ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
353 IP_STAT_PUTREF();
354 }
355
356 static void
357 ipflow_free(struct ipflow *ipf)
358 {
359
360 KASSERT(mutex_owned(&ipflow_lock));
361
362 /*
363 * Remove the flow from the hash table (at elevated IPL).
364 * Once it's off the list, we can deal with it at normal
365 * network IPL.
366 */
367 IPFLOW_REMOVE(ipf);
368
369 ipflow_addstats(ipf);
370 rtcache_free(&ipf->ipf_ro);
371 ipflow_inuse--;
372 pool_put(&ipflow_pool, ipf);
373 }
374
375 static struct ipflow *
376 ipflow_reap(bool just_one)
377 {
378
379 KASSERT(mutex_owned(&ipflow_lock));
380
381 while (just_one || ipflow_inuse > ip_maxflows) {
382 struct ipflow *ipf, *maybe_ipf = NULL;
383
384 ipf = LIST_FIRST(&ipflowlist);
385 while (ipf != NULL) {
386 /*
387 * If this no longer points to a valid route
388 * reclaim it.
389 */
390 if (rtcache_validate(&ipf->ipf_ro) == NULL)
391 goto done;
392 /*
393 * choose the one that's been least recently
394 * used or has had the least uses in the
395 * last 1.5 intervals.
396 */
397 if (maybe_ipf == NULL ||
398 ipf->ipf_timer < maybe_ipf->ipf_timer ||
399 (ipf->ipf_timer == maybe_ipf->ipf_timer &&
400 ipf->ipf_last_uses + ipf->ipf_uses <
401 maybe_ipf->ipf_last_uses +
402 maybe_ipf->ipf_uses))
403 maybe_ipf = ipf;
404 ipf = LIST_NEXT(ipf, ipf_list);
405 }
406 ipf = maybe_ipf;
407 done:
408 /*
409 * Remove the entry from the flow table.
410 */
411 IPFLOW_REMOVE(ipf);
412
413 ipflow_addstats(ipf);
414 rtcache_free(&ipf->ipf_ro);
415 if (just_one)
416 return ipf;
417 pool_put(&ipflow_pool, ipf);
418 ipflow_inuse--;
419 }
420 return NULL;
421 }
422
423 void
424 ipflow_slowtimo(void)
425 {
426 struct rtentry *rt;
427 struct ipflow *ipf, *next_ipf;
428 uint64_t *ips;
429
430 mutex_enter(softnet_lock);
431 mutex_enter(&ipflow_lock);
432 KERNEL_LOCK(1, NULL);
433 for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
434 next_ipf = LIST_NEXT(ipf, ipf_list);
435 if (PRT_SLOW_ISEXPIRED(ipf->ipf_timer) ||
436 (rt = rtcache_validate(&ipf->ipf_ro)) == NULL) {
437 ipflow_free(ipf);
438 } else {
439 ipf->ipf_last_uses = ipf->ipf_uses;
440 rt->rt_use += ipf->ipf_uses;
441 ips = IP_STAT_GETREF();
442 ips[IP_STAT_TOTAL] += ipf->ipf_uses;
443 ips[IP_STAT_FORWARD] += ipf->ipf_uses;
444 ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
445 IP_STAT_PUTREF();
446 ipf->ipf_uses = 0;
447 }
448 }
449 KERNEL_UNLOCK_ONE(NULL);
450 mutex_exit(&ipflow_lock);
451 mutex_exit(softnet_lock);
452 }
453
454 void
455 ipflow_create(const struct route *ro, struct mbuf *m)
456 {
457 const struct ip *const ip = mtod(m, const struct ip *);
458 struct ipflow *ipf;
459 size_t hash;
460
461 mutex_enter(&ipflow_lock);
462
463 /*
464 * Don't create cache entries for ICMP messages.
465 */
466 if (ip_maxflows == 0 || ip->ip_p == IPPROTO_ICMP) {
467 mutex_exit(&ipflow_lock);
468 return;
469 }
470
471 KERNEL_LOCK(1, NULL);
472
473 /*
474 * See if an existing flow struct exists. If so remove it from its
475 * list and free the old route. If not, try to malloc a new one
476 * (if we aren't at our limit).
477 */
478 ipf = ipflow_lookup(ip);
479 if (ipf == NULL) {
480 if (ipflow_inuse >= ip_maxflows) {
481 ipf = ipflow_reap(true);
482 } else {
483 ipf = pool_get(&ipflow_pool, PR_NOWAIT);
484 if (ipf == NULL)
485 goto out;
486 ipflow_inuse++;
487 }
488 memset(ipf, 0, sizeof(*ipf));
489 } else {
490 IPFLOW_REMOVE(ipf);
491
492 ipflow_addstats(ipf);
493 rtcache_free(&ipf->ipf_ro);
494 ipf->ipf_uses = ipf->ipf_last_uses = 0;
495 ipf->ipf_errors = ipf->ipf_dropped = 0;
496 }
497
498 /*
499 * Fill in the updated information.
500 */
501 rtcache_copy(&ipf->ipf_ro, ro);
502 ipf->ipf_dst = ip->ip_dst;
503 ipf->ipf_src = ip->ip_src;
504 ipf->ipf_tos = ip->ip_tos;
505 PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
506
507 /*
508 * Insert into the approriate bucket of the flow table.
509 */
510 hash = ipflow_hash(ip);
511 IPFLOW_INSERT(&ipflowtable[hash], ipf);
512
513 out:
514 KERNEL_UNLOCK_ONE(NULL);
515 mutex_exit(&ipflow_lock);
516 }
517
518 int
519 ipflow_invalidate_all(int new_size)
520 {
521 struct ipflow *ipf, *next_ipf;
522 int error;
523
524 error = 0;
525
526 mutex_enter(&ipflow_lock);
527
528 for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
529 next_ipf = LIST_NEXT(ipf, ipf_list);
530 ipflow_free(ipf);
531 }
532
533 if (new_size)
534 error = ipflow_reinit(new_size);
535
536 mutex_exit(&ipflow_lock);
537
538 return error;
539 }
540
541 #ifdef GATEWAY
542 /*
543 * sysctl helper routine for net.inet.ip.maxflows.
544 */
545 static int
546 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
547 {
548 int error;
549
550 error = sysctl_lookup(SYSCTLFN_CALL(rnode));
551 if (error || newp == NULL)
552 return (error);
553
554 mutex_enter(softnet_lock);
555 mutex_enter(&ipflow_lock);
556 KERNEL_LOCK(1, NULL);
557
558 ipflow_reap(false);
559
560 KERNEL_UNLOCK_ONE(NULL);
561 mutex_exit(&ipflow_lock);
562 mutex_exit(softnet_lock);
563
564 return (0);
565 }
566
567 static int
568 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
569 {
570 int error, tmp;
571 struct sysctlnode node;
572
573 node = *rnode;
574 tmp = ip_hashsize;
575 node.sysctl_data = &tmp;
576 error = sysctl_lookup(SYSCTLFN_CALL(&node));
577 if (error || newp == NULL)
578 return (error);
579
580 if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
581 /*
582 * Can only fail due to malloc()
583 */
584 mutex_enter(softnet_lock);
585 KERNEL_LOCK(1, NULL);
586
587 error = ipflow_invalidate_all(tmp);
588
589 KERNEL_UNLOCK_ONE(NULL);
590 mutex_exit(softnet_lock);
591
592 } else {
593 /*
594 * EINVAL if not a power of 2
595 */
596 error = EINVAL;
597 }
598
599 return error;
600 }
601 #endif /* GATEWAY */
602
603 static void
604 ipflow_sysctl_init(struct sysctllog **clog)
605 {
606 sysctl_createv(clog, 0, NULL, NULL,
607 CTLFLAG_PERMANENT,
608 CTLTYPE_NODE, "inet",
609 SYSCTL_DESCR("PF_INET related settings"),
610 NULL, 0, NULL, 0,
611 CTL_NET, PF_INET, CTL_EOL);
612 sysctl_createv(clog, 0, NULL, NULL,
613 CTLFLAG_PERMANENT,
614 CTLTYPE_NODE, "ip",
615 SYSCTL_DESCR("IPv4 related settings"),
616 NULL, 0, NULL, 0,
617 CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
618
619 #ifdef GATEWAY
620 sysctl_createv(clog, 0, NULL, NULL,
621 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
622 CTLTYPE_INT, "maxflows",
623 SYSCTL_DESCR("Number of flows for fast forwarding"),
624 sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
625 CTL_NET, PF_INET, IPPROTO_IP,
626 IPCTL_MAXFLOWS, CTL_EOL);
627 sysctl_createv(clog, 0, NULL, NULL,
628 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
629 CTLTYPE_INT, "hashsize",
630 SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
631 sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
632 CTL_NET, PF_INET, IPPROTO_IP,
633 CTL_CREATE, CTL_EOL);
634 #endif /* GATEWAY */
635 }
636