db92bbcc7a5c3889918a001395fac381d44d4026
[dragonfly.git] / sys / netinet / in_rmx.c
1 /*
2  * Copyright 1994, 1995 Massachusetts Institute of Technology
3  *
4  * Permission to use, copy, modify, and distribute this software and
5  * its documentation for any purpose and without fee is hereby
6  * granted, provided that both the above copyright notice and this
7  * permission notice appear in all copies, that both the above
8  * copyright notice and this permission notice appear in all
9  * supporting documentation, and that the name of M.I.T. not be used
10  * in advertising or publicity pertaining to distribution of the
11  * software without specific, written prior permission.  M.I.T. makes
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied
14  * warranty.
15  *
16  * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''.  M.I.T. DISCLAIMS
17  * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
18  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
20  * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD: src/sys/netinet/in_rmx.c,v 1.37.2.3 2002/08/09 14:49:23 ru Exp $
30  * $DragonFly: src/sys/netinet/in_rmx.c,v 1.14 2006/04/11 06:59:34 dillon Exp $
31  */
32
33 /*
34  * This code does two things necessary for the enhanced TCP metrics to
35  * function in a useful manner:
36  *  1) It marks all non-host routes as `cloning', thus ensuring that
37  *     every actual reference to such a route actually gets turned
38  *     into a reference to a host route to the specific destination
39  *     requested.
40  *  2) When such routes lose all their references, it arranges for them
41  *     to be deleted in some random collection of circumstances, so that
42  *     a large quantity of stale routing data is not kept in kernel memory
43  *     indefinitely.  See in_rtqtimo() below for the exact mechanism.
44  */
45
46 #include "opt_carp.h"
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/kernel.h>
51 #include <sys/sysctl.h>
52 #include <sys/socket.h>
53 #include <sys/mbuf.h>
54 #include <sys/syslog.h>
55 #include <sys/globaldata.h>
56 #include <sys/thread2.h>
57
58 #include <net/if.h>
59 #include <net/route.h>
60 #include <net/if_var.h>
61 #ifdef CARP
62 #include <net/if_types.h>
63 #endif
64 #include <net/netmsg2.h>
65 #include <net/netisr2.h>
66 #include <netinet/in.h>
67 #include <netinet/in_var.h>
68 #include <netinet/ip_var.h>
69 #include <netinet/ip_flow.h>
70
71 #define RTPRF_EXPIRING  RTF_PROTO3      /* set on routes we manage */
72
73 struct in_rtq_pcpu {
74         struct radix_node_head  *rnh;
75
76         struct callout          timo_ch;
77         struct netmsg_base      timo_nmsg;
78
79         time_t                  lastdrain;
80         int                     draining;
81         struct netmsg_base      drain_nmsg;
82 } __cachealign;
83
84 static void     in_rtqtimo(void *);
85
86 static struct in_rtq_pcpu in_rtq_pcpu[MAXCPU];
87
88 /*
89  * Do what we need to do when inserting a route.
90  */
91 static struct radix_node *
92 in_addroute(char *key, char *mask, struct radix_node_head *head,
93             struct radix_node *treenodes)
94 {
95         struct rtentry *rt = (struct rtentry *)treenodes;
96         struct sockaddr_in *sin = (struct sockaddr_in *)rt_key(rt);
97         struct radix_node *ret;
98         struct in_ifaddr_container *iac;
99         struct in_ifaddr *ia;
100
101         /*
102          * For IP, mark routes to multicast addresses as such, because
103          * it's easy to do and might be useful (but this is much more
104          * dubious since it's so easy to inspect the address).
105          *
106          * For IP, all unicast non-host routes are automatically cloning.
107          */
108         if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr)))
109                 rt->rt_flags |= RTF_MULTICAST;
110
111         if (!(rt->rt_flags & (RTF_HOST | RTF_CLONING | RTF_MULTICAST)))
112                 rt->rt_flags |= RTF_PRCLONING;
113
114         /*
115          *   For host routes, we make sure that RTF_BROADCAST
116          *   is set for anything that looks like a broadcast address.
117          *   This way, we can avoid an expensive call to in_broadcast()
118          *   in ip_output() most of the time (because the route passed
119          *   to ip_output() is almost always a host route).
120          *
121          *   For local routes we set RTF_LOCAL allowing various shortcuts.
122          *
123          *   A cloned network route will point to one of several possible
124          *   addresses if an interface has aliases and must be repointed
125          *   back to the correct address or arp_rtrequest() will not properly
126          *   detect the local ip.
127          */
128         if (rt->rt_flags & RTF_HOST) {
129                 if (in_broadcast(sin->sin_addr, rt->rt_ifp)) {
130                         rt->rt_flags |= RTF_BROADCAST;
131                 } else if (satosin(rt->rt_ifa->ifa_addr)->sin_addr.s_addr ==
132                            sin->sin_addr.s_addr) {
133                         rt->rt_flags |= RTF_LOCAL;
134                 } else {
135                         LIST_FOREACH(iac, INADDR_HASH(sin->sin_addr.s_addr),
136                                      ia_hash) {
137                                 ia = iac->ia;
138                                 if (sin->sin_addr.s_addr ==
139                                     ia->ia_addr.sin_addr.s_addr) {
140                                         rt->rt_flags |= RTF_LOCAL;
141                                         IFAREF(&ia->ia_ifa);
142                                         IFAFREE(rt->rt_ifa);
143                                         rt->rt_ifa = &ia->ia_ifa;
144                                         rt->rt_ifp = rt->rt_ifa->ifa_ifp;
145                                         break;
146                                 }
147                         }
148                 }
149         }
150
151         if (rt->rt_rmx.rmx_mtu == 0 && !(rt->rt_rmx.rmx_locks & RTV_MTU) &&
152             rt->rt_ifp != NULL)
153                 rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
154
155         ret = rn_addroute(key, mask, head, treenodes);
156         if (ret == NULL && (rt->rt_flags & RTF_HOST)) {
157                 struct rtentry *oldrt;
158
159                 /*
160                  * We are trying to add a host route, but can't.
161                  * Find out if it is because of an ARP entry and
162                  * delete it if so.
163                  */
164                 oldrt = rtpurelookup((struct sockaddr *)sin);
165                 if (oldrt != NULL) {
166                         --oldrt->rt_refcnt;
167                         if ((oldrt->rt_flags & RTF_LLINFO) &&
168                             (oldrt->rt_flags & RTF_HOST) &&
169                             oldrt->rt_gateway &&
170                             oldrt->rt_gateway->sa_family == AF_LINK) {
171                                 rtrequest(RTM_DELETE, rt_key(oldrt),
172                                           oldrt->rt_gateway, rt_mask(oldrt),
173                                           oldrt->rt_flags, NULL);
174                                 ret = rn_addroute(key, mask, head, treenodes);
175                         }
176                 }
177         }
178
179         /*
180          * If the new route has been created successfully, and it is
181          * not a multicast/broadcast or cloned route, then we will
182          * have to flush the ipflow.  Otherwise, we may end up using
183          * the wrong route.
184          */
185         if (ret != NULL &&
186             (rt->rt_flags &
187              (RTF_MULTICAST | RTF_BROADCAST | RTF_WASCLONED)) == 0) {
188                 ipflow_flush_oncpu();
189         }
190         return ret;
191 }
192
193 /*
194  * This code is the inverse of in_closeroute: on first reference, if we
195  * were managing the route, stop doing so and set the expiration timer
196  * back off again.
197  */
198 static struct radix_node *
199 in_matchroute(char *key, struct radix_node_head *head)
200 {
201         struct radix_node *rn = rn_match(key, head);
202         struct rtentry *rt = (struct rtentry *)rn;
203
204         if (rt != NULL && rt->rt_refcnt == 0) { /* this is first reference */
205                 if (rt->rt_flags & RTPRF_EXPIRING) {
206                         rt->rt_flags &= ~RTPRF_EXPIRING;
207                         rt->rt_rmx.rmx_expire = 0;
208                 }
209         }
210         return rn;
211 }
212
213 static int rtq_reallyold = 60*60;  /* one hour is ``really old'' */
214 SYSCTL_INT(_net_inet_ip, IPCTL_RTEXPIRE, rtexpire, CTLFLAG_RW,
215     &rtq_reallyold , 0,
216     "Default expiration time on cloned routes");
217
218 static int rtq_minreallyold = 10;  /* never automatically crank down to less */
219 SYSCTL_INT(_net_inet_ip, IPCTL_RTMINEXPIRE, rtminexpire, CTLFLAG_RW,
220     &rtq_minreallyold , 0,
221     "Minimum time to attempt to hold onto cloned routes");
222
223 static int rtq_toomany = 128;      /* 128 cached routes is ``too many'' */
224 SYSCTL_INT(_net_inet_ip, IPCTL_RTMAXCACHE, rtmaxcache, CTLFLAG_RW,
225     &rtq_toomany , 0, "Upper limit on cloned routes");
226
227 /*
228  * On last reference drop, mark the route as belong to us so that it can be
229  * timed out.
230  */
231 static void
232 in_closeroute(struct radix_node *rn, struct radix_node_head *head)
233 {
234         struct rtentry *rt = (struct rtentry *)rn;
235
236         if (!(rt->rt_flags & RTF_UP))
237                 return;         /* prophylactic measures */
238
239         if ((rt->rt_flags & (RTF_LLINFO | RTF_HOST)) != RTF_HOST)
240                 return;
241
242         if ((rt->rt_flags & (RTF_WASCLONED | RTPRF_EXPIRING)) != RTF_WASCLONED)
243                 return;
244
245         /*
246          * As requested by David Greenman:
247          * If rtq_reallyold is 0, just delete the route without
248          * waiting for a timeout cycle to kill it.
249          */
250         if (rtq_reallyold != 0) {
251                 rt->rt_flags |= RTPRF_EXPIRING;
252                 rt->rt_rmx.rmx_expire = time_uptime + rtq_reallyold;
253         } else {
254                 /*
255                  * Remove route from the radix tree, but defer deallocation
256                  * until we return to rtfree().
257                  */
258                 rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway, rt_mask(rt),
259                           rt->rt_flags, &rt);
260         }
261 }
262
263 struct rtqk_arg {
264         struct radix_node_head *rnh;
265         int draining;
266         int killed;
267         int found;
268         int updating;
269         time_t nextstop;
270 };
271
272 /*
273  * Get rid of old routes.  When draining, this deletes everything, even when
274  * the timeout is not expired yet.  When updating, this makes sure that
275  * nothing has a timeout longer than the current value of rtq_reallyold.
276  */
277 static int
278 in_rtqkill(struct radix_node *rn, void *rock)
279 {
280         struct rtqk_arg *ap = rock;
281         struct rtentry *rt = (struct rtentry *)rn;
282         int err;
283
284         if (rt->rt_flags & RTPRF_EXPIRING) {
285                 ap->found++;
286                 if (ap->draining || rt->rt_rmx.rmx_expire <= time_uptime) {
287                         if (rt->rt_refcnt > 0)
288                                 panic("rtqkill route really not free");
289
290                         err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
291                                         rt_mask(rt), rt->rt_flags, NULL);
292                         if (err)
293                                 log(LOG_WARNING, "in_rtqkill: error %d\n", err);
294                         else
295                                 ap->killed++;
296                 } else {
297                         if (ap->updating &&
298                             (int)(rt->rt_rmx.rmx_expire - time_uptime) >
299                              rtq_reallyold) {
300                                 rt->rt_rmx.rmx_expire = time_uptime +
301                                     rtq_reallyold;
302                         }
303                         ap->nextstop = lmin(ap->nextstop,
304                                             rt->rt_rmx.rmx_expire);
305                 }
306         }
307
308         return 0;
309 }
310
311 #define RTQ_TIMEOUT     60*10   /* run no less than once every ten minutes */
312 static int rtq_timeout = RTQ_TIMEOUT;
313
314 /*
315  * NOTE:
316  * 'last_adjusted_timeout' and 'rtq_reallyold' are _not_ read-only, and
317  * could be changed by all CPUs.  However, they are changed at so low
318  * frequency that we could ignore the cache trashing issue and take them
319  * as read-mostly.
320  */
321 static void
322 in_rtqtimo_dispatch(netmsg_t nmsg)
323 {
324         struct rtqk_arg arg;
325         struct timeval atv;
326         static time_t last_adjusted_timeout = 0;
327         struct in_rtq_pcpu *pcpu = &in_rtq_pcpu[mycpuid];
328         struct radix_node_head *rnh = pcpu->rnh;
329
330         /* Reply ASAP */
331         crit_enter();
332         lwkt_replymsg(&nmsg->lmsg, 0);
333         crit_exit();
334
335         arg.found = arg.killed = 0;
336         arg.rnh = rnh;
337         arg.nextstop = time_uptime + rtq_timeout;
338         arg.draining = arg.updating = 0;
339         rnh->rnh_walktree(rnh, in_rtqkill, &arg);
340
341         /*
342          * Attempt to be somewhat dynamic about this:
343          * If there are ``too many'' routes sitting around taking up space,
344          * then crank down the timeout, and see if we can't make some more
345          * go away.  However, we make sure that we will never adjust more
346          * than once in rtq_timeout seconds, to keep from cranking down too
347          * hard.
348          */
349         if ((arg.found - arg.killed > rtq_toomany) &&
350             (int)(time_uptime - last_adjusted_timeout) >= rtq_timeout &&
351             rtq_reallyold > rtq_minreallyold) {
352                 rtq_reallyold = 2*rtq_reallyold / 3;
353                 if (rtq_reallyold < rtq_minreallyold) {
354                         rtq_reallyold = rtq_minreallyold;
355                 }
356
357                 last_adjusted_timeout = time_uptime;
358 #ifdef DIAGNOSTIC
359                 log(LOG_DEBUG, "in_rtqtimo: adjusted rtq_reallyold to %d\n",
360                     rtq_reallyold);
361 #endif
362                 arg.found = arg.killed = 0;
363                 arg.updating = 1;
364                 rnh->rnh_walktree(rnh, in_rtqkill, &arg);
365         }
366
367         atv.tv_usec = 0;
368         atv.tv_sec = arg.nextstop - time_uptime;
369         if ((int)atv.tv_sec < 1) {              /* time shift safety */
370                 atv.tv_sec = 1;
371                 arg.nextstop = time_uptime + atv.tv_sec;
372         }
373         if ((int)atv.tv_sec > rtq_timeout) {    /* time shift safety */
374                 atv.tv_sec = rtq_timeout;
375                 arg.nextstop = time_uptime + atv.tv_sec;
376         }
377         callout_reset(&pcpu->timo_ch, tvtohz_high(&atv), in_rtqtimo, NULL);
378 }
379
380 static void
381 in_rtqtimo(void *arg __unused)
382 {
383         int cpuid = mycpuid;
384         struct lwkt_msg *lmsg = &in_rtq_pcpu[cpuid].timo_nmsg.lmsg;
385
386         crit_enter();
387         if (lmsg->ms_flags & MSGF_DONE)
388                 lwkt_sendmsg_oncpu(netisr_cpuport(cpuid), lmsg);
389         crit_exit();
390 }
391
392 static void
393 in_rtqdrain_oncpu(struct in_rtq_pcpu *pcpu)
394 {
395         struct radix_node_head *rnh = rt_tables[mycpuid][AF_INET];
396         struct rtqk_arg arg;
397
398         arg.found = arg.killed = 0;
399         arg.rnh = rnh;
400         arg.nextstop = 0;
401         arg.draining = 1;
402         arg.updating = 0;
403         rnh->rnh_walktree(rnh, in_rtqkill, &arg);
404
405         pcpu->lastdrain = time_uptime;
406 }
407
408 static void
409 in_rtqdrain_dispatch(netmsg_t nmsg)
410 {
411         struct in_rtq_pcpu *pcpu = &in_rtq_pcpu[mycpuid];
412
413         /* Reply ASAP */
414         crit_enter();
415         lwkt_replymsg(&nmsg->lmsg, 0);
416         crit_exit();
417
418         in_rtqdrain_oncpu(pcpu);
419         pcpu->draining = 0;
420 }
421
422 static void
423 in_rtqdrain_ipi(void *arg __unused)
424 {
425         int cpu = mycpuid;
426         struct lwkt_msg *msg = &in_rtq_pcpu[cpu].drain_nmsg.lmsg;
427
428         crit_enter();
429         if (msg->ms_flags & MSGF_DONE)
430                 lwkt_sendmsg_oncpu(netisr_cpuport(cpu), msg);
431         crit_exit();
432 }
433
434 void
435 in_rtqdrain(void)
436 {
437         cpumask_t mask;
438         int cpu;
439
440         CPUMASK_ASSBMASK(mask, ncpus);
441         CPUMASK_ANDMASK(mask, smp_active_mask);
442
443         if (IS_NETISR(curthread, mycpuid)) {
444                 in_rtqdrain_oncpu(&in_rtq_pcpu[mycpuid]);
445                 CPUMASK_NANDBIT(mask, mycpuid);
446         }
447
448         for (cpu = 0; cpu < ncpus; ++cpu) {
449                 struct in_rtq_pcpu *pcpu = &in_rtq_pcpu[cpu];
450
451                 if (!CPUMASK_TESTBIT(mask, cpu))
452                         continue;
453
454                 if (pcpu->draining || pcpu->lastdrain == time_uptime) {
455                         /* Just drained or is draining; skip this cpu. */
456                         CPUMASK_NANDBIT(mask, cpu);
457                         continue;
458                 }
459                 pcpu->draining = 1;
460         }
461
462         if (CPUMASK_TESTNZERO(mask))
463                 lwkt_send_ipiq_mask(mask, in_rtqdrain_ipi, NULL);
464 }
465
466 /*
467  * Initialize our routing tree.
468  */
469 int
470 in_inithead(void **head, int off)
471 {
472         struct radix_node_head *rnh;
473         struct in_rtq_pcpu *pcpu;
474         int cpuid = mycpuid;
475
476         KKASSERT(head == (void **)&rt_tables[cpuid][AF_INET]);
477
478         if (!rn_inithead(head, rn_cpumaskhead(cpuid), off))
479                 return 0;
480
481         rnh = *head;
482         rnh->rnh_addaddr = in_addroute;
483         rnh->rnh_matchaddr = in_matchroute;
484         rnh->rnh_close = in_closeroute;
485
486         pcpu = &in_rtq_pcpu[cpuid];
487         pcpu->rnh = rnh;
488         callout_init_mp(&pcpu->timo_ch);
489         netmsg_init(&pcpu->timo_nmsg, NULL, &netisr_adone_rport, MSGF_PRIORITY,
490             in_rtqtimo_dispatch);
491         netmsg_init(&pcpu->drain_nmsg, NULL, &netisr_adone_rport, MSGF_PRIORITY,
492             in_rtqdrain_dispatch);
493
494         in_rtqtimo(NULL);       /* kick off timeout first time */
495         return 1;
496 }
497
498 /*
499  * This zaps old routes when the interface goes down or interface
500  * address is deleted.  In the latter case, it deletes static routes
501  * that point to this address.  If we don't do this, we may end up
502  * using the old address in the future.  The ones we always want to
503  * get rid of are things like ARP entries, since the user might down
504  * the interface, walk over to a completely different network, and
505  * plug back in.
506  *
507  * in_ifadown() is typically called when an interface is being brought
508  * down.  We must iterate through all per-cpu route tables and clean
509  * them up.
510  */
511 struct in_ifadown_arg {
512         struct radix_node_head *rnh;
513         struct ifaddr *ifa;
514         int del;
515 };
516
517 static int
518 in_ifadownkill(struct radix_node *rn, void *xap)
519 {
520         struct in_ifadown_arg *ap = xap;
521         struct rtentry *rt = (struct rtentry *)rn;
522         int err;
523
524         if (rt->rt_ifa == ap->ifa &&
525             (ap->del || !(rt->rt_flags & RTF_STATIC))) {
526                 /*
527                  * We need to disable the automatic prune that happens
528                  * in this case in rtrequest() because it will blow
529                  * away the pointers that rn_walktree() needs in order
530                  * continue our descent.  We will end up deleting all
531                  * the routes that rtrequest() would have in any case,
532                  * so that behavior is not needed there.
533                  */
534                 rt->rt_flags &= ~(RTF_CLONING | RTF_PRCLONING);
535                 err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
536                                 rt_mask(rt), rt->rt_flags, NULL);
537                 if (err)
538                         log(LOG_WARNING, "in_ifadownkill: error %d\n", err);
539         }
540         return 0;
541 }
542
543 struct netmsg_ifadown {
544         struct netmsg_base      base;
545         struct ifaddr           *ifa;
546         int                     del;
547 };
548
549 static void
550 in_ifadown_dispatch(netmsg_t msg)
551 {
552         struct netmsg_ifadown *rmsg = (void *)msg;
553         struct radix_node_head *rnh;
554         struct ifaddr *ifa = rmsg->ifa;
555         struct in_ifadown_arg arg;
556         int nextcpu, cpu;
557
558         cpu = mycpuid;
559
560         arg.rnh = rnh = rt_tables[cpu][AF_INET];
561         arg.ifa = ifa;
562         arg.del = rmsg->del;
563         rnh->rnh_walktree(rnh, in_ifadownkill, &arg);
564         ifa->ifa_flags &= ~IFA_ROUTE;
565
566         nextcpu = cpu + 1;
567         if (nextcpu < ncpus)
568                 lwkt_forwardmsg(netisr_cpuport(nextcpu), &rmsg->base.lmsg);
569         else
570                 lwkt_replymsg(&rmsg->base.lmsg, 0);
571 }
572
573 int
574 in_ifadown_force(struct ifaddr *ifa, int delete)
575 {
576         struct netmsg_ifadown msg;
577
578         if (ifa->ifa_addr->sa_family != AF_INET)
579                 return 1;
580
581         /*
582          * XXX individual requests are not independantly chained,
583          * which means that the per-cpu route tables will not be
584          * consistent in the middle of the operation.  If routes
585          * related to the interface are manipulated while we are
586          * doing this the inconsistancy could trigger a panic.
587          */
588         netmsg_init(&msg.base, NULL, &curthread->td_msgport, MSGF_PRIORITY,
589             in_ifadown_dispatch);
590         msg.ifa = ifa;
591         msg.del = delete;
592         rt_domsg_global(&msg.base);
593
594         return 0;
595 }
596
597 int
598 in_ifadown(struct ifaddr *ifa, int delete)
599 {
600 #ifdef CARP
601         if (ifa->ifa_ifp->if_type == IFT_CARP)
602                 return 0;
603 #endif
604         return in_ifadown_force(ifa, delete);
605 }