bcb3f62726c5f220289e7224f91373205222dedf
[dragonfly.git] / sys / netinet / ip_flow.c
1 /*-
2  * Copyright (c) 1998 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to The NetBSD Foundation
6  * by the 3am Software Foundry ("3am").  It was developed by Matt Thomas.
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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the NetBSD
19  *      Foundation, Inc. and its contributors.
20  * 4. Neither the name of The NetBSD Foundation nor the names of its
21  *    contributors may be used to endorse or promote products derived
22  *    from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  *
36  * $FreeBSD: src/sys/netinet/ip_flow.c,v 1.9.2.2 2001/11/04 17:35:31 luigi Exp $
37  * $DragonFly: src/sys/netinet/ip_flow.c,v 1.16 2008/10/26 07:11:28 sephe Exp $
38  */
39
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/protosw.h>
45 #include <sys/socket.h>
46 #include <sys/sysctl.h>
47 #include <sys/thread2.h>
48
49 #include <machine/smp.h>
50
51 #include <net/if.h>
52 #include <net/route.h>
53 #include <net/netisr.h>
54 #include <net/netmsg2.h>
55
56 #include <netinet/in.h>
57 #include <netinet/ip.h>
58 #include <netinet/in_var.h>
59 #include <netinet/ip_var.h>
60 #include <netinet/ip_flow.h>
61
62 #define IPFLOW_TIMER            (5 * PR_SLOWHZ)
63 #define IPFLOW_HASHBITS         6       /* should not be a multiple of 8 */
64 #define IPFLOW_HASHSIZE         (1 << IPFLOW_HASHBITS)
65 #define IPFLOW_MAX              256
66
67 #define IPFLOW_RTENTRY_ISDOWN(rt) \
68         (((rt)->rt_flags & RTF_UP) == 0 || ((rt)->rt_ifp->if_flags & IFF_UP) == 0)
69
70 struct ipflow {
71         LIST_ENTRY(ipflow) ipf_next;    /* next ipflow in bucket */
72         struct in_addr ipf_dst;         /* destination address */
73         struct in_addr ipf_src;         /* source address */
74
75         uint8_t ipf_tos;                /* type-of-service */
76         struct route ipf_ro;            /* associated route entry */
77         u_long ipf_uses;                /* number of uses in this period */
78
79         int ipf_timer;                  /* remaining lifetime of this entry */
80         u_long ipf_dropped;             /* ENOBUFS returned by if_output */
81         u_long ipf_errors;              /* other errors returned by if_output */
82         u_long ipf_last_uses;           /* number of uses in last period */
83 };
84
85 #define ipflow_inuse            ipflow_inuse_pcpu[mycpuid]
86 #define ipflows                 ipflows_pcpu[mycpuid]
87
88 static LIST_HEAD(ipflowhead, ipflow) ipflows_pcpu[MAXCPU][IPFLOW_HASHSIZE];
89 static int              ipflow_inuse_pcpu[MAXCPU];
90 static struct netmsg    ipflow_timo_netmsgs[MAXCPU];
91 static int              ipflow_active = 0;
92
93 SYSCTL_NODE(_net_inet_ip, OID_AUTO, ipflow, CTLFLAG_RW, 0, "ip flow");
94 SYSCTL_INT(_net_inet_ip, IPCTL_FASTFORWARDING, fastforwarding, CTLFLAG_RW,
95            &ipflow_active, 0, "Enable flow-based IP forwarding");
96
97 static MALLOC_DEFINE(M_IPFLOW, "ip_flow", "IP flow");
98
99 static unsigned
100 ipflow_hash(struct in_addr dst, struct in_addr src, unsigned tos)
101 {
102         unsigned hash = tos;
103         int idx;
104
105         for (idx = 0; idx < 32; idx += IPFLOW_HASHBITS)
106                 hash += (dst.s_addr >> (32 - idx)) + (src.s_addr >> idx);
107         return hash & (IPFLOW_HASHSIZE-1);
108 }
109
110 static struct ipflow *
111 ipflow_lookup(const struct ip *ip)
112 {
113         unsigned hash;
114         struct ipflow *ipf;
115
116         hash = ipflow_hash(ip->ip_dst, ip->ip_src, ip->ip_tos);
117
118         crit_enter();
119         ipf = LIST_FIRST(&ipflows[hash]);
120         while (ipf != NULL) {
121                 if (ip->ip_dst.s_addr == ipf->ipf_dst.s_addr &&
122                     ip->ip_src.s_addr == ipf->ipf_src.s_addr &&
123                     ip->ip_tos == ipf->ipf_tos)
124                         break;
125                 ipf = LIST_NEXT(ipf, ipf_next);
126         }
127         crit_exit();
128
129         return ipf;
130 }
131
132 int
133 ipflow_fastforward(struct mbuf *m)
134 {
135         struct ip *ip;
136         struct ipflow *ipf;
137         struct rtentry *rt;
138         struct sockaddr *dst;
139         struct ifnet *ifp;
140         int error;
141
142         /*
143          * Are we forwarding packets?  Big enough for an IP packet?
144          */
145         if (!ipforwarding || !ipflow_active || m->m_len < sizeof(struct ip))
146                 return 0;
147
148         /*
149          * IP header with no option and valid version and length
150          */
151         ip = mtod(m, struct ip *);
152         if (ip->ip_v != IPVERSION || ip->ip_hl != (sizeof(struct ip) >> 2) ||
153             ntohs(ip->ip_len) > m->m_pkthdr.len)
154                 return 0;
155
156         /*
157          * Find a flow.
158          */
159         ipf = ipflow_lookup(ip);
160         if (ipf == NULL)
161                 return 0;
162
163         /*
164          * Route and interface still up?
165          */
166         rt = ipf->ipf_ro.ro_rt;
167         if (IPFLOW_RTENTRY_ISDOWN(rt))
168                 return 0;
169         ifp = rt->rt_ifp;
170
171         /*
172          * Packet size OK?  TTL?
173          */
174         if (m->m_pkthdr.len > ifp->if_mtu || ip->ip_ttl <= IPTTLDEC)
175                 return 0;
176
177         /*
178          * Everything checks out and so we can forward this packet.
179          * Modify the TTL and incrementally change the checksum.
180          */
181         ip->ip_ttl -= IPTTLDEC;
182         if (ip->ip_sum >= htons(0xffff - (IPTTLDEC << 8)))
183                 ip->ip_sum += htons(IPTTLDEC << 8) + 1;
184         else
185                 ip->ip_sum += htons(IPTTLDEC << 8);
186
187         /*
188          * Send the packet on its way.  All we can get back is ENOBUFS
189          */
190         ipf->ipf_uses++;
191         ipf->ipf_timer = IPFLOW_TIMER;
192
193         if (rt->rt_flags & RTF_GATEWAY)
194                 dst = rt->rt_gateway;
195         else
196                 dst = &ipf->ipf_ro.ro_dst;
197
198         error = ifp->if_output(ifp, m, dst, rt);
199         if (error) {
200                 if (error == ENOBUFS)
201                         ipf->ipf_dropped++;
202                 else
203                         ipf->ipf_errors++;
204         }
205         return 1;
206 }
207
208 static void
209 ipflow_addstats(struct ipflow *ipf)
210 {
211         ipf->ipf_ro.ro_rt->rt_use += ipf->ipf_uses;
212         ipstat.ips_cantforward += ipf->ipf_errors + ipf->ipf_dropped;
213         ipstat.ips_forward += ipf->ipf_uses;
214         ipstat.ips_fastforward += ipf->ipf_uses;
215 }
216
217 static void
218 ipflow_free(struct ipflow *ipf)
219 {
220         /*
221          * Remove the flow from the hash table (at elevated IPL).
222          * Once it's off the list, we can deal with it at normal
223          * network IPL.
224          */
225         crit_enter();
226         LIST_REMOVE(ipf, ipf_next);
227
228         KKASSERT(ipflow_inuse > 0);
229         ipflow_inuse--;
230         crit_exit();
231
232         ipflow_addstats(ipf);
233         RTFREE(ipf->ipf_ro.ro_rt);
234         kfree(ipf, M_IPFLOW);
235 }
236
237 static struct ipflow *
238 ipflow_reap(void)
239 {
240         struct ipflow *ipf, *maybe_ipf = NULL;
241         int idx;
242
243         crit_enter();
244         for (idx = 0; idx < IPFLOW_HASHSIZE; idx++) {
245                 ipf = LIST_FIRST(&ipflows[idx]);
246                 while (ipf != NULL) {
247                         /*
248                          * If this no longer points to a valid route
249                          * reclaim it.
250                          */
251                         if ((ipf->ipf_ro.ro_rt->rt_flags & RTF_UP) == 0)
252                                 goto done;
253
254                         /*
255                          * choose the one that's been least recently used
256                          * or has had the least uses in the last 1.5
257                          * intervals.
258                          */
259                         if (maybe_ipf == NULL ||
260                             ipf->ipf_timer < maybe_ipf->ipf_timer ||
261                             (ipf->ipf_timer == maybe_ipf->ipf_timer &&
262                              ipf->ipf_last_uses + ipf->ipf_uses <
263                              maybe_ipf->ipf_last_uses + maybe_ipf->ipf_uses))
264                                 maybe_ipf = ipf;
265                         ipf = LIST_NEXT(ipf, ipf_next);
266                 }
267         }
268         ipf = maybe_ipf;
269 done:
270         /*
271          * Remove the entry from the flow table.
272          */
273         LIST_REMOVE(ipf, ipf_next);
274         crit_exit();
275
276         ipflow_addstats(ipf);
277         RTFREE(ipf->ipf_ro.ro_rt);
278         return ipf;
279 }
280
281 static void
282 ipflow_timo_dispatch(struct netmsg *nmsg)
283 {
284         struct ipflow *ipf;
285         int idx;
286
287         crit_enter();
288         lwkt_replymsg(&nmsg->nm_lmsg, 0);       /* reply ASAP */
289
290         for (idx = 0; idx < IPFLOW_HASHSIZE; idx++) {
291                 ipf = LIST_FIRST(&ipflows[idx]);
292                 while (ipf != NULL) {
293                         struct ipflow *next_ipf = LIST_NEXT(ipf, ipf_next);
294
295                         if (--ipf->ipf_timer == 0) {
296                                 ipflow_free(ipf);
297                         } else {
298                                 ipf->ipf_last_uses = ipf->ipf_uses;
299                                 ipf->ipf_ro.ro_rt->rt_use += ipf->ipf_uses;
300                                 ipstat.ips_forward += ipf->ipf_uses;
301                                 ipstat.ips_fastforward += ipf->ipf_uses;
302                                 ipf->ipf_uses = 0;
303                         }
304                         ipf = next_ipf;
305                 }
306         }
307         crit_exit();
308 }
309
310 static void
311 ipflow_timo_ipi(void *arg __unused)
312 {
313         struct lwkt_msg *msg = &ipflow_timo_netmsgs[mycpuid].nm_lmsg;
314
315         crit_enter();
316         if (msg->ms_flags & MSGF_DONE)
317                 lwkt_sendmsg(cpu_portfn(mycpuid), msg);
318         crit_exit();
319 }
320
321 void
322 ipflow_slowtimo(void)
323 {
324 #ifdef SMP
325         lwkt_send_ipiq_mask(smp_active_mask, ipflow_timo_ipi, NULL);
326 #else
327         ipflow_timo_ipi(NULL);
328 #endif
329 }
330
331 void
332 ipflow_create(const struct route *ro, struct mbuf *m)
333 {
334         const struct ip *const ip = mtod(m, struct ip *);
335         struct ipflow *ipf;
336         unsigned hash;
337
338         /*
339          * Don't create cache entries for ICMP messages.
340          */
341         if (!ipflow_active || ip->ip_p == IPPROTO_ICMP)
342                 return;
343
344         /*
345          * See if an existing flow struct exists.  If so remove it from it's
346          * list and free the old route.  If not, try to malloc a new one
347          * (if we aren't at our limit).
348          */
349         ipf = ipflow_lookup(ip);
350         if (ipf == NULL) {
351                 if (ipflow_inuse == IPFLOW_MAX) {
352                         ipf = ipflow_reap();
353                 } else {
354                         ipf = kmalloc(sizeof(*ipf), M_IPFLOW,
355                                       M_INTWAIT | M_NULLOK);
356                         if (ipf == NULL)
357                                 return;
358                         ipflow_inuse++;
359                 }
360                 bzero(ipf, sizeof(*ipf));
361         } else {
362                 crit_enter();
363                 LIST_REMOVE(ipf, ipf_next);
364                 crit_exit();
365
366                 ipflow_addstats(ipf);
367                 RTFREE(ipf->ipf_ro.ro_rt);
368                 ipf->ipf_uses = ipf->ipf_last_uses = 0;
369                 ipf->ipf_errors = ipf->ipf_dropped = 0;
370         }
371
372         /*
373          * Fill in the updated information.
374          */
375         ipf->ipf_ro = *ro;
376         ro->ro_rt->rt_refcnt++;
377         ipf->ipf_dst = ip->ip_dst;
378         ipf->ipf_src = ip->ip_src;
379         ipf->ipf_tos = ip->ip_tos;
380         ipf->ipf_timer = IPFLOW_TIMER;
381
382         /*
383          * Insert into the approriate bucket of the flow table.
384          */
385         hash = ipflow_hash(ip->ip_dst, ip->ip_src, ip->ip_tos);
386         crit_enter();
387         LIST_INSERT_HEAD(&ipflows[hash], ipf, ipf_next);
388         crit_exit();
389 }
390
391 static void
392 ipflow_init(void)
393 {
394         char oid_name[32];
395         int i;
396
397         for (i = 0; i < ncpus; ++i) {
398                 netmsg_init(&ipflow_timo_netmsgs[i], &netisr_adone_rport, 0,
399                             ipflow_timo_dispatch);
400
401                 ksnprintf(oid_name, sizeof(oid_name), "inuse%d", i);
402
403                 SYSCTL_ADD_INT(NULL,
404                 SYSCTL_STATIC_CHILDREN(_net_inet_ip_ipflow),
405                 OID_AUTO, oid_name, CTLFLAG_RD, &ipflow_inuse_pcpu[i], 0,
406                 "# of ip flow being used");
407         }
408 }
409 SYSINIT(arp, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY, ipflow_init, 0);