carp: Fix routes reset issue
[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 <netinet/in.h>
65 #include <netinet/in_var.h>
66 #include <netinet/ip_var.h>
67 #include <netinet/ip_flow.h>
68
69 #define RTPRF_EXPIRING  RTF_PROTO3      /* set on routes we manage */
70
71 static struct callout in_rtqtimo_ch[MAXCPU];
72
73 /*
74  * Do what we need to do when inserting a route.
75  */
76 static struct radix_node *
77 in_addroute(char *key, char *mask, struct radix_node_head *head,
78             struct radix_node *treenodes)
79 {
80         struct rtentry *rt = (struct rtentry *)treenodes;
81         struct sockaddr_in *sin = (struct sockaddr_in *)rt_key(rt);
82         struct radix_node *ret;
83         struct in_ifaddr_container *iac;
84         struct in_ifaddr *ia;
85
86         /*
87          * For IP, mark routes to multicast addresses as such, because
88          * it's easy to do and might be useful (but this is much more
89          * dubious since it's so easy to inspect the address).
90          *
91          * For IP, all unicast non-host routes are automatically cloning.
92          */
93         if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr)))
94                 rt->rt_flags |= RTF_MULTICAST;
95
96         if (!(rt->rt_flags & (RTF_HOST | RTF_CLONING | RTF_MULTICAST)))
97                 rt->rt_flags |= RTF_PRCLONING;
98
99         /*
100          *   For host routes, we make sure that RTF_BROADCAST
101          *   is set for anything that looks like a broadcast address.
102          *   This way, we can avoid an expensive call to in_broadcast()
103          *   in ip_output() most of the time (because the route passed
104          *   to ip_output() is almost always a host route).
105          *
106          *   For local routes we set RTF_LOCAL allowing various shortcuts.
107          *
108          *   A cloned network route will point to one of several possible
109          *   addresses if an interface has aliases and must be repointed
110          *   back to the correct address or arp_rtrequest() will not properly
111          *   detect the local ip.
112          */
113         if (rt->rt_flags & RTF_HOST) {
114                 if (in_broadcast(sin->sin_addr, rt->rt_ifp)) {
115                         rt->rt_flags |= RTF_BROADCAST;
116                 } else if (satosin(rt->rt_ifa->ifa_addr)->sin_addr.s_addr ==
117                            sin->sin_addr.s_addr) {
118                         rt->rt_flags |= RTF_LOCAL;
119                 } else {
120                         LIST_FOREACH(iac, INADDR_HASH(sin->sin_addr.s_addr),
121                                      ia_hash) {
122                                 ia = iac->ia;
123                                 if (sin->sin_addr.s_addr ==
124                                     ia->ia_addr.sin_addr.s_addr) {
125                                         rt->rt_flags |= RTF_LOCAL;
126                                         IFAREF(&ia->ia_ifa);
127                                         IFAFREE(rt->rt_ifa);
128                                         rt->rt_ifa = &ia->ia_ifa;
129                                         rt->rt_ifp = rt->rt_ifa->ifa_ifp;
130                                         break;
131                                 }
132                         }
133                 }
134         }
135
136         if (rt->rt_rmx.rmx_mtu != 0 && !(rt->rt_rmx.rmx_locks & RTV_MTU) &&
137             rt->rt_ifp != NULL)
138                 rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
139
140         ret = rn_addroute(key, mask, head, treenodes);
141         if (ret == NULL && (rt->rt_flags & RTF_HOST)) {
142                 struct rtentry *oldrt;
143
144                 /*
145                  * We are trying to add a host route, but can't.
146                  * Find out if it is because of an ARP entry and
147                  * delete it if so.
148                  */
149                 oldrt = rtpurelookup((struct sockaddr *)sin);
150                 if (oldrt != NULL) {
151                         --oldrt->rt_refcnt;
152                         if ((oldrt->rt_flags & RTF_LLINFO) &&
153                             (oldrt->rt_flags & RTF_HOST) &&
154                             oldrt->rt_gateway &&
155                             oldrt->rt_gateway->sa_family == AF_LINK) {
156                                 rtrequest(RTM_DELETE, rt_key(oldrt),
157                                           oldrt->rt_gateway, rt_mask(oldrt),
158                                           oldrt->rt_flags, NULL);
159                                 ret = rn_addroute(key, mask, head, treenodes);
160                         }
161                 }
162         }
163
164         /*
165          * If the new route has been created successfully, and it is
166          * not a multicast/broadcast or cloned route, then we will
167          * have to flush the ipflow.  Otherwise, we may end up using
168          * the wrong route.
169          */
170         if (ret != NULL &&
171             (rt->rt_flags &
172              (RTF_MULTICAST | RTF_BROADCAST | RTF_WASCLONED)) == 0) {
173                 ipflow_flush_oncpu();
174         }
175         return ret;
176 }
177
178 /*
179  * This code is the inverse of in_closeroute: on first reference, if we
180  * were managing the route, stop doing so and set the expiration timer
181  * back off again.
182  */
183 static struct radix_node *
184 in_matchroute(char *key, struct radix_node_head *head)
185 {
186         struct radix_node *rn = rn_match(key, head);
187         struct rtentry *rt = (struct rtentry *)rn;
188
189         if (rt != NULL && rt->rt_refcnt == 0) { /* this is first reference */
190                 if (rt->rt_flags & RTPRF_EXPIRING) {
191                         rt->rt_flags &= ~RTPRF_EXPIRING;
192                         rt->rt_rmx.rmx_expire = 0;
193                 }
194         }
195         return rn;
196 }
197
198 static int rtq_reallyold = 60*60;  /* one hour is ``really old'' */
199 SYSCTL_INT(_net_inet_ip, IPCTL_RTEXPIRE, rtexpire, CTLFLAG_RW,
200     &rtq_reallyold , 0,
201     "Default expiration time on cloned routes");
202
203 static int rtq_minreallyold = 10;  /* never automatically crank down to less */
204 SYSCTL_INT(_net_inet_ip, IPCTL_RTMINEXPIRE, rtminexpire, CTLFLAG_RW,
205     &rtq_minreallyold , 0,
206     "Minimum time to attempt to hold onto cloned routes");
207
208 static int rtq_toomany = 128;      /* 128 cached routes is ``too many'' */
209 SYSCTL_INT(_net_inet_ip, IPCTL_RTMAXCACHE, rtmaxcache, CTLFLAG_RW,
210     &rtq_toomany , 0, "Upper limit on cloned routes");
211
212 /*
213  * On last reference drop, mark the route as belong to us so that it can be
214  * timed out.
215  */
216 static void
217 in_closeroute(struct radix_node *rn, struct radix_node_head *head)
218 {
219         struct rtentry *rt = (struct rtentry *)rn;
220
221         if (!(rt->rt_flags & RTF_UP))
222                 return;         /* prophylactic measures */
223
224         if ((rt->rt_flags & (RTF_LLINFO | RTF_HOST)) != RTF_HOST)
225                 return;
226
227         if ((rt->rt_flags & (RTF_WASCLONED | RTPRF_EXPIRING)) != RTF_WASCLONED)
228                 return;
229
230         /*
231          * As requested by David Greenman:
232          * If rtq_reallyold is 0, just delete the route without
233          * waiting for a timeout cycle to kill it.
234          */
235         if (rtq_reallyold != 0) {
236                 rt->rt_flags |= RTPRF_EXPIRING;
237                 rt->rt_rmx.rmx_expire = time_second + rtq_reallyold;
238         } else {
239                 /*
240                  * Remove route from the radix tree, but defer deallocation
241                  * until we return to rtfree().
242                  */
243                 rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway, rt_mask(rt),
244                           rt->rt_flags, &rt);
245         }
246 }
247
248 struct rtqk_arg {
249         struct radix_node_head *rnh;
250         int draining;
251         int killed;
252         int found;
253         int updating;
254         time_t nextstop;
255 };
256
257 /*
258  * Get rid of old routes.  When draining, this deletes everything, even when
259  * the timeout is not expired yet.  When updating, this makes sure that
260  * nothing has a timeout longer than the current value of rtq_reallyold.
261  */
262 static int
263 in_rtqkill(struct radix_node *rn, void *rock)
264 {
265         struct rtqk_arg *ap = rock;
266         struct rtentry *rt = (struct rtentry *)rn;
267         int err;
268
269         if (rt->rt_flags & RTPRF_EXPIRING) {
270                 ap->found++;
271                 if (ap->draining || rt->rt_rmx.rmx_expire <= time_second) {
272                         if (rt->rt_refcnt > 0)
273                                 panic("rtqkill route really not free");
274
275                         err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
276                                         rt_mask(rt), rt->rt_flags, NULL);
277                         if (err)
278                                 log(LOG_WARNING, "in_rtqkill: error %d\n", err);
279                         else
280                                 ap->killed++;
281                 } else {
282                         if (ap->updating &&
283                             (rt->rt_rmx.rmx_expire - time_second >
284                              rtq_reallyold)) {
285                                 rt->rt_rmx.rmx_expire = time_second +
286                                     rtq_reallyold;
287                         }
288                         ap->nextstop = lmin(ap->nextstop,
289                                             rt->rt_rmx.rmx_expire);
290                 }
291         }
292
293         return 0;
294 }
295
296 #define RTQ_TIMEOUT     60*10   /* run no less than once every ten minutes */
297 static int rtq_timeout = RTQ_TIMEOUT;
298
299 static void
300 in_rtqtimo(void *rock)
301 {
302         struct radix_node_head *rnh = rock;
303         struct rtqk_arg arg;
304         struct timeval atv;
305         static time_t last_adjusted_timeout = 0;
306
307         arg.found = arg.killed = 0;
308         arg.rnh = rnh;
309         arg.nextstop = time_second + rtq_timeout;
310         arg.draining = arg.updating = 0;
311         crit_enter();
312         rnh->rnh_walktree(rnh, in_rtqkill, &arg);
313         crit_exit();
314
315         /*
316          * Attempt to be somewhat dynamic about this:
317          * If there are ``too many'' routes sitting around taking up space,
318          * then crank down the timeout, and see if we can't make some more
319          * go away.  However, we make sure that we will never adjust more
320          * than once in rtq_timeout seconds, to keep from cranking down too
321          * hard.
322          */
323         if ((arg.found - arg.killed > rtq_toomany) &&
324             (time_second - last_adjusted_timeout >= rtq_timeout) &&
325             rtq_reallyold > rtq_minreallyold) {
326                 rtq_reallyold = 2*rtq_reallyold / 3;
327                 if (rtq_reallyold < rtq_minreallyold) {
328                         rtq_reallyold = rtq_minreallyold;
329                 }
330
331                 last_adjusted_timeout = time_second;
332 #ifdef DIAGNOSTIC
333                 log(LOG_DEBUG, "in_rtqtimo: adjusted rtq_reallyold to %d\n",
334                     rtq_reallyold);
335 #endif
336                 arg.found = arg.killed = 0;
337                 arg.updating = 1;
338                 crit_enter();
339                 rnh->rnh_walktree(rnh, in_rtqkill, &arg);
340                 crit_exit();
341         }
342
343         atv.tv_usec = 0;
344         atv.tv_sec = arg.nextstop - time_second;
345         callout_reset(&in_rtqtimo_ch[mycpuid], tvtohz_high(&atv), in_rtqtimo,
346                       rock);
347 }
348
349 void
350 in_rtqdrain(void)
351 {
352         struct radix_node_head *rnh = rt_tables[mycpuid][AF_INET];
353         struct rtqk_arg arg;
354
355         arg.found = arg.killed = 0;
356         arg.rnh = rnh;
357         arg.nextstop = 0;
358         arg.draining = 1;
359         arg.updating = 0;
360         crit_enter();
361         rnh->rnh_walktree(rnh, in_rtqkill, &arg);
362         crit_exit();
363 }
364
365 /*
366  * Initialize our routing tree.
367  */
368 int
369 in_inithead(void **head, int off)
370 {
371         struct radix_node_head *rnh;
372
373         if (!rn_inithead(head, rn_cpumaskhead(mycpuid), off))
374                 return 0;
375
376         if (head != (void **)&rt_tables[mycpuid][AF_INET]) /* BOGUS! */
377                 return 1;       /* only do this for the real routing table */
378
379         rnh = *head;
380         rnh->rnh_addaddr = in_addroute;
381         rnh->rnh_matchaddr = in_matchroute;
382         rnh->rnh_close = in_closeroute;
383         callout_init(&in_rtqtimo_ch[mycpuid]);
384         in_rtqtimo(rnh);        /* kick off timeout first time */
385         return 1;
386 }
387
388 /*
389  * This zaps old routes when the interface goes down or interface
390  * address is deleted.  In the latter case, it deletes static routes
391  * that point to this address.  If we don't do this, we may end up
392  * using the old address in the future.  The ones we always want to
393  * get rid of are things like ARP entries, since the user might down
394  * the interface, walk over to a completely different network, and
395  * plug back in.
396  *
397  * in_ifadown() is typically called when an interface is being brought
398  * down.  We must iterate through all per-cpu route tables and clean
399  * them up.
400  */
401 struct in_ifadown_arg {
402         struct radix_node_head *rnh;
403         struct ifaddr *ifa;
404         int del;
405 };
406
407 static int
408 in_ifadownkill(struct radix_node *rn, void *xap)
409 {
410         struct in_ifadown_arg *ap = xap;
411         struct rtentry *rt = (struct rtentry *)rn;
412         int err;
413
414         if (rt->rt_ifa == ap->ifa &&
415             (ap->del || !(rt->rt_flags & RTF_STATIC))) {
416                 /*
417                  * We need to disable the automatic prune that happens
418                  * in this case in rtrequest() because it will blow
419                  * away the pointers that rn_walktree() needs in order
420                  * continue our descent.  We will end up deleting all
421                  * the routes that rtrequest() would have in any case,
422                  * so that behavior is not needed there.
423                  */
424                 rt->rt_flags &= ~(RTF_CLONING | RTF_PRCLONING);
425                 err = rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
426                                 rt_mask(rt), rt->rt_flags, NULL);
427                 if (err)
428                         log(LOG_WARNING, "in_ifadownkill: error %d\n", err);
429         }
430         return 0;
431 }
432
433 int
434 in_ifadown_force(struct ifaddr *ifa, int delete)
435 {
436         struct in_ifadown_arg arg;
437         struct radix_node_head *rnh;
438         int origcpu;
439         int cpu;
440
441         if (ifa->ifa_addr->sa_family != AF_INET)
442                 return 1;
443
444         /*
445          * XXX individual requests are not independantly chained,
446          * which means that the per-cpu route tables will not be
447          * consistent in the middle of the operation.  If routes
448          * related to the interface are manipulated while we are
449          * doing this the inconsistancy could trigger a panic.
450          */
451         origcpu = mycpuid;
452         for (cpu = 0; cpu < ncpus; cpu++) {
453                 lwkt_migratecpu(cpu);
454
455                 arg.rnh = rnh = rt_tables[cpu][AF_INET];
456                 arg.ifa = ifa;
457                 arg.del = delete;
458                 rnh->rnh_walktree(rnh, in_ifadownkill, &arg);
459                 ifa->ifa_flags &= ~IFA_ROUTE;
460         }
461         lwkt_migratecpu(origcpu);
462         return 0;
463 }
464
465 int
466 in_ifadown(struct ifaddr *ifa, int delete)
467 {
468 #ifdef CARP
469         if (ifa->ifa_ifp->if_type == IFT_CARP)
470                 return 0;
471 #endif
472         return in_ifadown_force(ifa, delete);
473 }