ip_flow.c revision 1.71 1 /* $NetBSD: ip_flow.c,v 1.71 2016/06/13 08:37:15 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.71 2016/06/13 08:37:15 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 KERNEL_LOCK(1, NULL);
327 if ((error = (*rt->rt_ifp->if_output)(rt->rt_ifp, m, dst, rt)) != 0) {
328 if (error == ENOBUFS)
329 ipf->ipf_dropped++;
330 else
331 ipf->ipf_errors++;
332 }
333 KERNEL_UNLOCK_ONE(NULL);
334 ret = 1;
335 out:
336 mutex_exit(&ipflow_lock);
337 return ret;
338 }
339
340 static void
342 ipflow_addstats(struct ipflow *ipf)
343 {
344 struct rtentry *rt;
345 uint64_t *ips;
346
347 if ((rt = rtcache_validate(&ipf->ipf_ro)) != NULL)
348 rt->rt_use += ipf->ipf_uses;
349
350 ips = IP_STAT_GETREF();
351 ips[IP_STAT_CANTFORWARD] += ipf->ipf_errors + ipf->ipf_dropped;
352 ips[IP_STAT_TOTAL] += ipf->ipf_uses;
353 ips[IP_STAT_FORWARD] += ipf->ipf_uses;
354 ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
355 IP_STAT_PUTREF();
356 }
357
358 static void
359 ipflow_free(struct ipflow *ipf)
360 {
361
362 KASSERT(mutex_owned(&ipflow_lock));
363
364 /*
365 * Remove the flow from the hash table (at elevated IPL).
366 * Once it's off the list, we can deal with it at normal
367 * network IPL.
368 */
369 IPFLOW_REMOVE(ipf);
370
371 ipflow_addstats(ipf);
372 rtcache_free(&ipf->ipf_ro);
373 ipflow_inuse--;
374 pool_put(&ipflow_pool, ipf);
375 }
376
377 static struct ipflow *
378 ipflow_reap(bool just_one)
379 {
380
381 KASSERT(mutex_owned(&ipflow_lock));
382
383 while (just_one || ipflow_inuse > ip_maxflows) {
384 struct ipflow *ipf, *maybe_ipf = NULL;
385
386 ipf = LIST_FIRST(&ipflowlist);
387 while (ipf != NULL) {
388 /*
389 * If this no longer points to a valid route
390 * reclaim it.
391 */
392 if (rtcache_validate(&ipf->ipf_ro) == NULL)
393 goto done;
394 /*
395 * choose the one that's been least recently
396 * used or has had the least uses in the
397 * last 1.5 intervals.
398 */
399 if (maybe_ipf == NULL ||
400 ipf->ipf_timer < maybe_ipf->ipf_timer ||
401 (ipf->ipf_timer == maybe_ipf->ipf_timer &&
402 ipf->ipf_last_uses + ipf->ipf_uses <
403 maybe_ipf->ipf_last_uses +
404 maybe_ipf->ipf_uses))
405 maybe_ipf = ipf;
406 ipf = LIST_NEXT(ipf, ipf_list);
407 }
408 ipf = maybe_ipf;
409 done:
410 /*
411 * Remove the entry from the flow table.
412 */
413 IPFLOW_REMOVE(ipf);
414
415 ipflow_addstats(ipf);
416 rtcache_free(&ipf->ipf_ro);
417 if (just_one)
418 return ipf;
419 pool_put(&ipflow_pool, ipf);
420 ipflow_inuse--;
421 }
422 return NULL;
423 }
424
425 void
426 ipflow_slowtimo(void)
427 {
428 struct rtentry *rt;
429 struct ipflow *ipf, *next_ipf;
430 uint64_t *ips;
431
432 mutex_enter(softnet_lock);
433 mutex_enter(&ipflow_lock);
434 KERNEL_LOCK(1, NULL);
435 for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
436 next_ipf = LIST_NEXT(ipf, ipf_list);
437 if (PRT_SLOW_ISEXPIRED(ipf->ipf_timer) ||
438 (rt = rtcache_validate(&ipf->ipf_ro)) == NULL) {
439 ipflow_free(ipf);
440 } else {
441 ipf->ipf_last_uses = ipf->ipf_uses;
442 rt->rt_use += ipf->ipf_uses;
443 ips = IP_STAT_GETREF();
444 ips[IP_STAT_TOTAL] += ipf->ipf_uses;
445 ips[IP_STAT_FORWARD] += ipf->ipf_uses;
446 ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
447 IP_STAT_PUTREF();
448 ipf->ipf_uses = 0;
449 }
450 }
451 KERNEL_UNLOCK_ONE(NULL);
452 mutex_exit(&ipflow_lock);
453 mutex_exit(softnet_lock);
454 }
455
456 void
457 ipflow_create(const struct route *ro, struct mbuf *m)
458 {
459 const struct ip *const ip = mtod(m, const struct ip *);
460 struct ipflow *ipf;
461 size_t hash;
462
463 mutex_enter(&ipflow_lock);
464
465 /*
466 * Don't create cache entries for ICMP messages.
467 */
468 if (ip_maxflows == 0 || ip->ip_p == IPPROTO_ICMP) {
469 mutex_exit(&ipflow_lock);
470 return;
471 }
472
473 KERNEL_LOCK(1, NULL);
474
475 /*
476 * See if an existing flow struct exists. If so remove it from its
477 * list and free the old route. If not, try to malloc a new one
478 * (if we aren't at our limit).
479 */
480 ipf = ipflow_lookup(ip);
481 if (ipf == NULL) {
482 if (ipflow_inuse >= ip_maxflows) {
483 ipf = ipflow_reap(true);
484 } else {
485 ipf = pool_get(&ipflow_pool, PR_NOWAIT);
486 if (ipf == NULL)
487 goto out;
488 ipflow_inuse++;
489 }
490 memset(ipf, 0, sizeof(*ipf));
491 } else {
492 IPFLOW_REMOVE(ipf);
493
494 ipflow_addstats(ipf);
495 rtcache_free(&ipf->ipf_ro);
496 ipf->ipf_uses = ipf->ipf_last_uses = 0;
497 ipf->ipf_errors = ipf->ipf_dropped = 0;
498 }
499
500 /*
501 * Fill in the updated information.
502 */
503 rtcache_copy(&ipf->ipf_ro, ro);
504 ipf->ipf_dst = ip->ip_dst;
505 ipf->ipf_src = ip->ip_src;
506 ipf->ipf_tos = ip->ip_tos;
507 PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
508
509 /*
510 * Insert into the approriate bucket of the flow table.
511 */
512 hash = ipflow_hash(ip);
513 IPFLOW_INSERT(&ipflowtable[hash], ipf);
514
515 out:
516 KERNEL_UNLOCK_ONE(NULL);
517 mutex_exit(&ipflow_lock);
518 }
519
520 int
521 ipflow_invalidate_all(int new_size)
522 {
523 struct ipflow *ipf, *next_ipf;
524 int error;
525
526 error = 0;
527
528 mutex_enter(&ipflow_lock);
529
530 for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
531 next_ipf = LIST_NEXT(ipf, ipf_list);
532 ipflow_free(ipf);
533 }
534
535 if (new_size)
536 error = ipflow_reinit(new_size);
537
538 mutex_exit(&ipflow_lock);
539
540 return error;
541 }
542
543 #ifdef GATEWAY
544 /*
545 * sysctl helper routine for net.inet.ip.maxflows.
546 */
547 static int
548 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
549 {
550 int error;
551
552 error = sysctl_lookup(SYSCTLFN_CALL(rnode));
553 if (error || newp == NULL)
554 return (error);
555
556 mutex_enter(softnet_lock);
557 mutex_enter(&ipflow_lock);
558 KERNEL_LOCK(1, NULL);
559
560 ipflow_reap(false);
561
562 KERNEL_UNLOCK_ONE(NULL);
563 mutex_exit(&ipflow_lock);
564 mutex_exit(softnet_lock);
565
566 return (0);
567 }
568
569 static int
570 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
571 {
572 int error, tmp;
573 struct sysctlnode node;
574
575 node = *rnode;
576 tmp = ip_hashsize;
577 node.sysctl_data = &tmp;
578 error = sysctl_lookup(SYSCTLFN_CALL(&node));
579 if (error || newp == NULL)
580 return (error);
581
582 if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
583 /*
584 * Can only fail due to malloc()
585 */
586 mutex_enter(softnet_lock);
587 KERNEL_LOCK(1, NULL);
588
589 error = ipflow_invalidate_all(tmp);
590
591 KERNEL_UNLOCK_ONE(NULL);
592 mutex_exit(softnet_lock);
593
594 } else {
595 /*
596 * EINVAL if not a power of 2
597 */
598 error = EINVAL;
599 }
600
601 return error;
602 }
603 #endif /* GATEWAY */
604
605 static void
606 ipflow_sysctl_init(struct sysctllog **clog)
607 {
608 sysctl_createv(clog, 0, NULL, NULL,
609 CTLFLAG_PERMANENT,
610 CTLTYPE_NODE, "inet",
611 SYSCTL_DESCR("PF_INET related settings"),
612 NULL, 0, NULL, 0,
613 CTL_NET, PF_INET, CTL_EOL);
614 sysctl_createv(clog, 0, NULL, NULL,
615 CTLFLAG_PERMANENT,
616 CTLTYPE_NODE, "ip",
617 SYSCTL_DESCR("IPv4 related settings"),
618 NULL, 0, NULL, 0,
619 CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
620
621 #ifdef GATEWAY
622 sysctl_createv(clog, 0, NULL, NULL,
623 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
624 CTLTYPE_INT, "maxflows",
625 SYSCTL_DESCR("Number of flows for fast forwarding"),
626 sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
627 CTL_NET, PF_INET, IPPROTO_IP,
628 IPCTL_MAXFLOWS, CTL_EOL);
629 sysctl_createv(clog, 0, NULL, NULL,
630 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
631 CTLTYPE_INT, "hashsize",
632 SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
633 sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
634 CTL_NET, PF_INET, IPPROTO_IP,
635 CTL_CREATE, CTL_EOL);
636 #endif /* GATEWAY */
637 }
638