Update ips_total
[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.21 2008/10/26 09:50:15 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 #include <sys/in_cksum.h>
49
50 #include <machine/smp.h>
51
52 #include <net/if.h>
53 #include <net/route.h>
54 #include <net/netisr.h>
55 #include <net/netmsg2.h>
56
57 #include <netinet/in.h>
58 #include <netinet/ip.h>
59 #include <netinet/in_var.h>
60 #include <netinet/ip_var.h>
61 #include <netinet/ip_flow.h>
62
63 #define IPFLOW_TIMER            (5 * PR_SLOWHZ)
64 #define IPFLOW_HASHBITS         6       /* should not be a multiple of 8 */
65 #define IPFLOW_HASHSIZE         (1 << IPFLOW_HASHBITS)
66 #define IPFLOW_MAX              256
67
68 #define IPFLOW_RTENTRY_ISDOWN(rt) \
69         (((rt)->rt_flags & RTF_UP) == 0 || ((rt)->rt_ifp->if_flags & IFF_UP) == 0)
70
71 struct ipflow {
72         LIST_ENTRY(ipflow) ipf_next;    /* next ipflow in bucket */
73         struct in_addr ipf_dst;         /* destination address */
74         struct in_addr ipf_src;         /* source address */
75
76         uint8_t ipf_tos;                /* type-of-service */
77         struct route ipf_ro;            /* associated route entry */
78         u_long ipf_uses;                /* number of uses in this period */
79
80         int ipf_timer;                  /* remaining lifetime of this entry */
81         u_long ipf_dropped;             /* ENOBUFS returned by if_output */
82         u_long ipf_errors;              /* other errors returned by if_output */
83         u_long ipf_last_uses;           /* number of uses in last period */
84 };
85
86 #define ipflow_inuse            ipflow_inuse_pcpu[mycpuid]
87 #define ipflows                 ipflows_pcpu[mycpuid]
88
89 static LIST_HEAD(ipflowhead, ipflow) ipflows_pcpu[MAXCPU][IPFLOW_HASHSIZE];
90 static int              ipflow_inuse_pcpu[MAXCPU];
91 static struct netmsg    ipflow_timo_netmsgs[MAXCPU];
92 static int              ipflow_active = 0;
93
94 SYSCTL_NODE(_net_inet_ip, OID_AUTO, ipflow, CTLFLAG_RW, 0, "ip flow");
95 SYSCTL_INT(_net_inet_ip, IPCTL_FASTFORWARDING, fastforwarding, CTLFLAG_RW,
96            &ipflow_active, 0, "Enable flow-based IP forwarding");
97
98 static MALLOC_DEFINE(M_IPFLOW, "ip_flow", "IP flow");
99
100 static unsigned
101 ipflow_hash(struct in_addr dst, struct in_addr src, unsigned tos)
102 {
103         unsigned hash = tos;
104         int idx;
105
106         for (idx = 0; idx < 32; idx += IPFLOW_HASHBITS)
107                 hash += (dst.s_addr >> (32 - idx)) + (src.s_addr >> idx);
108         return hash & (IPFLOW_HASHSIZE-1);
109 }
110
111 static struct ipflow *
112 ipflow_lookup(const struct ip *ip)
113 {
114         unsigned hash;
115         struct ipflow *ipf;
116
117         hash = ipflow_hash(ip->ip_dst, ip->ip_src, ip->ip_tos);
118
119         crit_enter();
120         ipf = LIST_FIRST(&ipflows[hash]);
121         while (ipf != NULL) {
122                 if (ip->ip_dst.s_addr == ipf->ipf_dst.s_addr &&
123                     ip->ip_src.s_addr == ipf->ipf_src.s_addr &&
124                     ip->ip_tos == ipf->ipf_tos)
125                         break;
126                 ipf = LIST_NEXT(ipf, ipf_next);
127         }
128         crit_exit();
129
130         return ipf;
131 }
132
133 int
134 ipflow_fastforward(struct mbuf *m)
135 {
136         struct ip *ip;
137         struct ipflow *ipf;
138         struct rtentry *rt;
139         struct sockaddr *dst;
140         struct ifnet *ifp;
141         int error, iplen;
142
143         /*
144          * Are we forwarding packets?
145          */
146         if (!ipforwarding || !ipflow_active)
147                 return 0;
148
149         /*
150          * Was packet received as a link-level multicast or broadcast?
151          * If so, don't try to fast forward..
152          */
153         if (m->m_flags & (M_BCAST | M_MCAST))
154                 return 0;
155
156         /* length checks already done in ip_mport() */
157         KASSERT(m->m_len >= sizeof(struct ip), ("IP header not in one mbuf"));
158
159         /*
160          * IP header with no option and valid version and length
161          */
162         ip = mtod(m, struct ip *);
163         iplen = ntohs(ip->ip_len);
164         if (ip->ip_v != IPVERSION || ip->ip_hl != (sizeof(struct ip) >> 2) ||
165             iplen > m->m_pkthdr.len)
166                 return 0;
167
168         /* length checks already done in ip_mport() */
169         KKASSERT(iplen >= sizeof(struct ip));
170
171         /*
172          * Find a flow.
173          */
174         ipf = ipflow_lookup(ip);
175         if (ipf == NULL)
176                 return 0;
177
178         /*
179          * Verify the IP header checksum.
180          */
181         if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
182                 if (!(m->m_pkthdr.csum_flags & CSUM_IP_VALID))
183                         return 0;
184         } else {
185                 /* Must compute it ourselves. */
186                 if (in_cksum_hdr(ip) != 0)
187                         return 0;
188         }
189
190         /*
191          * Route and interface still up?
192          */
193         rt = ipf->ipf_ro.ro_rt;
194         if (IPFLOW_RTENTRY_ISDOWN(rt))
195                 return 0;
196         ifp = rt->rt_ifp;
197
198         /*
199          * Packet size OK?  TTL?
200          */
201         if (m->m_pkthdr.len > ifp->if_mtu || ip->ip_ttl <= IPTTLDEC)
202                 return 0;
203
204         /*
205          * Clear any in-bound checksum flags for this packet.
206          */
207         m->m_pkthdr.csum_flags = 0;
208
209         /*
210          * Everything checks out and so we can forward this packet.
211          * Modify the TTL and incrementally change the checksum.
212          * 
213          * This method of adding the checksum works on either endian CPU.
214          * If htons() is inlined, all the arithmetic is folded; otherwise
215          * the htons()s are combined by CSE due to the __const__ attribute.
216          *
217          * Don't bother using HW checksumming here -- the incremental
218          * update is pretty fast.
219          */
220         ip->ip_ttl -= IPTTLDEC;
221         if (ip->ip_sum >= (uint16_t)~htons(IPTTLDEC << 8))
222                 ip->ip_sum -= ~htons(IPTTLDEC << 8);
223         else
224                 ip->ip_sum += htons(IPTTLDEC << 8);
225
226         /*
227          * Trim the packet in case it's too long.. 
228          */
229         if (m->m_pkthdr.len > iplen) {
230                 if (m->m_len == m->m_pkthdr.len) {
231                         m->m_len = iplen;
232                         m->m_pkthdr.len = iplen;
233                 } else {
234                         m_adj(m, iplen - m->m_pkthdr.len);
235                 }
236         }
237
238         /*
239          * Send the packet on its way.  All we can get back is ENOBUFS
240          */
241         ipf->ipf_uses++;
242         ipf->ipf_timer = IPFLOW_TIMER;
243
244         if (rt->rt_flags & RTF_GATEWAY)
245                 dst = rt->rt_gateway;
246         else
247                 dst = &ipf->ipf_ro.ro_dst;
248
249         error = ifp->if_output(ifp, m, dst, rt);
250         if (error) {
251                 if (error == ENOBUFS)
252                         ipf->ipf_dropped++;
253                 else
254                         ipf->ipf_errors++;
255         }
256         return 1;
257 }
258
259 static void
260 ipflow_addstats(struct ipflow *ipf)
261 {
262         ipf->ipf_ro.ro_rt->rt_use += ipf->ipf_uses;
263         ipstat.ips_cantforward += ipf->ipf_errors + ipf->ipf_dropped;
264         ipstat.ips_total += ipf->ipf_uses;
265         ipstat.ips_forward += ipf->ipf_uses;
266         ipstat.ips_fastforward += ipf->ipf_uses;
267 }
268
269 static void
270 ipflow_free(struct ipflow *ipf)
271 {
272         /*
273          * Remove the flow from the hash table (at elevated IPL).
274          * Once it's off the list, we can deal with it at normal
275          * network IPL.
276          */
277         crit_enter();
278         LIST_REMOVE(ipf, ipf_next);
279
280         KKASSERT(ipflow_inuse > 0);
281         ipflow_inuse--;
282         crit_exit();
283
284         ipflow_addstats(ipf);
285         RTFREE(ipf->ipf_ro.ro_rt);
286         kfree(ipf, M_IPFLOW);
287 }
288
289 static struct ipflow *
290 ipflow_reap(void)
291 {
292         struct ipflow *ipf, *maybe_ipf = NULL;
293         int idx;
294
295         crit_enter();
296         for (idx = 0; idx < IPFLOW_HASHSIZE; idx++) {
297                 ipf = LIST_FIRST(&ipflows[idx]);
298                 while (ipf != NULL) {
299                         /*
300                          * If this no longer points to a valid route
301                          * reclaim it.
302                          */
303                         if ((ipf->ipf_ro.ro_rt->rt_flags & RTF_UP) == 0)
304                                 goto done;
305
306                         /*
307                          * choose the one that's been least recently used
308                          * or has had the least uses in the last 1.5
309                          * intervals.
310                          */
311                         if (maybe_ipf == NULL ||
312                             ipf->ipf_timer < maybe_ipf->ipf_timer ||
313                             (ipf->ipf_timer == maybe_ipf->ipf_timer &&
314                              ipf->ipf_last_uses + ipf->ipf_uses <
315                              maybe_ipf->ipf_last_uses + maybe_ipf->ipf_uses))
316                                 maybe_ipf = ipf;
317                         ipf = LIST_NEXT(ipf, ipf_next);
318                 }
319         }
320         ipf = maybe_ipf;
321 done:
322         /*
323          * Remove the entry from the flow table.
324          */
325         LIST_REMOVE(ipf, ipf_next);
326         crit_exit();
327
328         ipflow_addstats(ipf);
329         RTFREE(ipf->ipf_ro.ro_rt);
330         return ipf;
331 }
332
333 static void
334 ipflow_timo_dispatch(struct netmsg *nmsg)
335 {
336         struct ipflow *ipf;
337         int idx;
338
339         crit_enter();
340         lwkt_replymsg(&nmsg->nm_lmsg, 0);       /* reply ASAP */
341
342         for (idx = 0; idx < IPFLOW_HASHSIZE; idx++) {
343                 ipf = LIST_FIRST(&ipflows[idx]);
344                 while (ipf != NULL) {
345                         struct ipflow *next_ipf = LIST_NEXT(ipf, ipf_next);
346
347                         if (--ipf->ipf_timer == 0) {
348                                 ipflow_free(ipf);
349                         } else {
350                                 ipf->ipf_last_uses = ipf->ipf_uses;
351                                 ipf->ipf_ro.ro_rt->rt_use += ipf->ipf_uses;
352                                 ipstat.ips_total += ipf->ipf_uses;
353                                 ipstat.ips_forward += ipf->ipf_uses;
354                                 ipstat.ips_fastforward += ipf->ipf_uses;
355                                 ipf->ipf_uses = 0;
356                         }
357                         ipf = next_ipf;
358                 }
359         }
360         crit_exit();
361 }
362
363 static void
364 ipflow_timo_ipi(void *arg __unused)
365 {
366         struct lwkt_msg *msg = &ipflow_timo_netmsgs[mycpuid].nm_lmsg;
367
368         crit_enter();
369         if (msg->ms_flags & MSGF_DONE)
370                 lwkt_sendmsg(cpu_portfn(mycpuid), msg);
371         crit_exit();
372 }
373
374 void
375 ipflow_slowtimo(void)
376 {
377 #ifdef SMP
378         uint32_t mask = 0;
379         int i;
380
381         for (i = 0; i < ncpus; ++i) {
382                 if (ipflow_inuse_pcpu[i])
383                         mask |= 1 << i;
384         }
385         if (mask != 0)
386                 lwkt_send_ipiq_mask(mask, ipflow_timo_ipi, NULL);
387 #else
388         if (ipflow_inuse)
389                 ipflow_timo_ipi(NULL);
390 #endif
391 }
392
393 void
394 ipflow_create(const struct route *ro, struct mbuf *m)
395 {
396         const struct ip *const ip = mtod(m, struct ip *);
397         struct ipflow *ipf;
398         unsigned hash;
399
400         /*
401          * Don't create cache entries for ICMP messages.
402          */
403         if (!ipflow_active || ip->ip_p == IPPROTO_ICMP)
404                 return;
405
406         /*
407          * See if an existing flow struct exists.  If so remove it from it's
408          * list and free the old route.  If not, try to malloc a new one
409          * (if we aren't at our limit).
410          */
411         ipf = ipflow_lookup(ip);
412         if (ipf == NULL) {
413                 if (ipflow_inuse == IPFLOW_MAX) {
414                         ipf = ipflow_reap();
415                 } else {
416                         ipf = kmalloc(sizeof(*ipf), M_IPFLOW,
417                                       M_INTWAIT | M_NULLOK);
418                         if (ipf == NULL)
419                                 return;
420                         ipflow_inuse++;
421                 }
422                 bzero(ipf, sizeof(*ipf));
423         } else {
424                 crit_enter();
425                 LIST_REMOVE(ipf, ipf_next);
426                 crit_exit();
427
428                 ipflow_addstats(ipf);
429                 RTFREE(ipf->ipf_ro.ro_rt);
430                 ipf->ipf_uses = ipf->ipf_last_uses = 0;
431                 ipf->ipf_errors = ipf->ipf_dropped = 0;
432         }
433
434         /*
435          * Fill in the updated information.
436          */
437         ipf->ipf_ro = *ro;
438         ro->ro_rt->rt_refcnt++;
439         ipf->ipf_dst = ip->ip_dst;
440         ipf->ipf_src = ip->ip_src;
441         ipf->ipf_tos = ip->ip_tos;
442         ipf->ipf_timer = IPFLOW_TIMER;
443
444         /*
445          * Insert into the approriate bucket of the flow table.
446          */
447         hash = ipflow_hash(ip->ip_dst, ip->ip_src, ip->ip_tos);
448         crit_enter();
449         LIST_INSERT_HEAD(&ipflows[hash], ipf, ipf_next);
450         crit_exit();
451 }
452
453 static void
454 ipflow_init(void)
455 {
456         char oid_name[32];
457         int i;
458
459         for (i = 0; i < ncpus; ++i) {
460                 netmsg_init(&ipflow_timo_netmsgs[i], &netisr_adone_rport, 0,
461                             ipflow_timo_dispatch);
462
463                 ksnprintf(oid_name, sizeof(oid_name), "inuse%d", i);
464
465                 SYSCTL_ADD_INT(NULL,
466                 SYSCTL_STATIC_CHILDREN(_net_inet_ip_ipflow),
467                 OID_AUTO, oid_name, CTLFLAG_RD, &ipflow_inuse_pcpu[i], 0,
468                 "# of ip flow being used");
469         }
470 }
471 SYSINIT(arp, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY, ipflow_init, 0);