File: /usr/src/linux/net/ipv4/inetpeer.c

1     /*
2      *		INETPEER - A storage for permanent information about peers
3      *
4      *  This source is covered by the GNU GPL, the same as all kernel sources.
5      *
6      *  Version:	$Id: inetpeer.c,v 1.6 2001/06/21 20:30:14 davem Exp $
7      *
8      *  Authors:	Andrey V. Savochkin <saw@msu.ru>
9      */
10     
11     #include <linux/types.h>
12     #include <linux/slab.h>
13     #include <linux/interrupt.h>
14     #include <linux/spinlock.h>
15     #include <linux/random.h>
16     #include <linux/sched.h>
17     #include <linux/timer.h>
18     #include <linux/time.h>
19     #include <linux/kernel.h>
20     #include <linux/mm.h>
21     #include <net/inetpeer.h>
22     
23     /*
24      *  Theory of operations.
25      *  We keep one entry for each peer IP address.  The nodes contains long-living
26      *  information about the peer which doesn't depend on routes.
27      *  At this moment this information consists only of ID field for the next
28      *  outgoing IP packet.  This field is incremented with each packet as encoded
29      *  in inet_getid() function (include/net/inetpeer.h).
30      *  At the moment of writing this notes identifier of IP packets is generated
31      *  to be unpredictable using this code only for packets subjected
32      *  (actually or potentially) to defragmentation.  I.e. DF packets less than
33      *  PMTU in size uses a constant ID and do not use this code (see
34      *  ip_select_ident() in include/net/ip.h).
35      *
36      *  Route cache entries hold references to our nodes.
37      *  New cache entries get references via lookup by destination IP address in
38      *  the avl tree.  The reference is grabbed only when it's needed i.e. only
39      *  when we try to output IP packet which needs an unpredictable ID (see
40      *  __ip_select_ident() in net/ipv4/route.c).
41      *  Nodes are removed only when reference counter goes to 0.
42      *  When it's happened the node may be removed when a sufficient amount of
43      *  time has been passed since its last use.  The less-recently-used entry can
44      *  also be removed if the pool is overloaded i.e. if the total amount of
45      *  entries is greater-or-equal than the threshold.
46      *
47      *  Node pool is organised as an AVL tree.
48      *  Such an implementation has been chosen not just for fun.  It's a way to
49      *  prevent easy and efficient DoS attacks by creating hash collisions.  A huge
50      *  amount of long living nodes in a single hash slot would significantly delay
51      *  lookups performed with disabled BHs.
52      *
53      *  Serialisation issues.
54      *  1.  Nodes may appear in the tree only with the pool write lock held.
55      *  2.  Nodes may disappear from the tree only with the pool write lock held
56      *      AND reference count being 0.
57      *  3.  Nodes appears and disappears from unused node list only under
58      *      "inet_peer_unused_lock".
59      *  4.  Global variable peer_total is modified under the pool lock.
60      *  5.  struct inet_peer fields modification:
61      *		avl_left, avl_right, avl_parent, avl_height: pool lock
62      *		unused_next, unused_prevp: unused node list lock
63      *		refcnt: atomically against modifications on other CPU;
64      *		   usually under some other lock to prevent node disappearing
65      *		dtime: unused node list lock
66      *		v4daddr: unchangeable
67      *		ip_id_count: idlock
68      */
69     
70     spinlock_t inet_peer_idlock = SPIN_LOCK_UNLOCKED;
71     
72     static kmem_cache_t *peer_cachep;
73     
74     #define node_height(x) x->avl_height
75     static struct inet_peer peer_fake_node = {
76     	avl_left : &peer_fake_node,
77     	avl_right : &peer_fake_node,
78     	avl_height : 0
79     };
80     #define peer_avl_empty (&peer_fake_node)
81     static struct inet_peer *peer_root = peer_avl_empty;
82     static rwlock_t peer_pool_lock = RW_LOCK_UNLOCKED;
83     #define PEER_MAXDEPTH 40 /* sufficient for about 2^27 nodes */
84     
85     static volatile int peer_total;
86     int inet_peer_threshold = 65536 + 128;	/* start to throw entries more
87     					 * aggressively at this stage */
88     int inet_peer_minttl = 120 * HZ;	/* TTL under high load: 120 sec */
89     int inet_peer_maxttl = 10 * 60 * HZ;	/* usual time to live: 10 min */
90     struct inet_peer *inet_peer_unused_head,
91     		**inet_peer_unused_tailp = &inet_peer_unused_head;
92     spinlock_t inet_peer_unused_lock = SPIN_LOCK_UNLOCKED;
93     #define PEER_MAX_CLEANUP_WORK 30
94     
95     static void peer_check_expire(unsigned long dummy);
96     static struct timer_list peer_periodic_timer =
97     	{ { NULL, NULL }, 0, 0, &peer_check_expire };
98     int inet_peer_gc_mintime = 10 * HZ,
99         inet_peer_gc_maxtime = 120 * HZ;
100     
101     
102     void __init inet_initpeers(void)
103     {
104     	struct sysinfo si;
105     
106     	/* Use the straight interface to information about memory. */
107     	si_meminfo(&si);
108     	/* The values below were suggested by Alexey Kuznetsov
109     	 * <kuznet@ms2.inr.ac.ru>.  I don't have any opinion about the values
110     	 * myself.  --SAW
111     	 */
112     	if (si.totalram <= (32768*1024)/PAGE_SIZE)
113     		inet_peer_threshold >>= 1; /* max pool size about 1MB on IA32 */
114     	if (si.totalram <= (16384*1024)/PAGE_SIZE)
115     		inet_peer_threshold >>= 1; /* about 512KB */
116     	if (si.totalram <= (8192*1024)/PAGE_SIZE)
117     		inet_peer_threshold >>= 2; /* about 128KB */
118     
119     	peer_cachep = kmem_cache_create("inet_peer_cache",
120     			sizeof(struct inet_peer),
121     			0, SLAB_HWCACHE_ALIGN,
122     			NULL, NULL);
123     
124     	/* All the timers, started at system startup tend
125     	   to synchronize. Perturb it a bit.
126     	 */
127     	peer_periodic_timer.expires = jiffies
128     		+ net_random() % inet_peer_gc_maxtime
129     		+ inet_peer_gc_maxtime;
130     	add_timer(&peer_periodic_timer);
131     }
132     
133     /* Called with or without local BH being disabled. */
134     static void unlink_from_unused(struct inet_peer *p)
135     {
136     	spin_lock_bh(&inet_peer_unused_lock);
137     	if (p->unused_prevp != NULL) {
138     		/* On unused list. */
139     		*p->unused_prevp = p->unused_next;
140     		if (p->unused_next != NULL)
141     			p->unused_next->unused_prevp = p->unused_prevp;
142     		else
143     			inet_peer_unused_tailp = p->unused_prevp;
144     		p->unused_prevp = NULL; /* mark it as removed */
145     	}
146     	spin_unlock_bh(&inet_peer_unused_lock);
147     }
148     
149     /* Called with local BH disabled and the pool lock held. */
150     #define lookup(daddr) 						\
151     ({								\
152     	struct inet_peer *u, **v;				\
153     	stackptr = stack;					\
154     	*stackptr++ = &peer_root;				\
155     	for (u = peer_root; u != peer_avl_empty; ) {		\
156     		if (daddr == u->v4daddr)			\
157     			break;					\
158     		if (daddr < u->v4daddr)				\
159     			v = &u->avl_left;			\
160     		else						\
161     			v = &u->avl_right;			\
162     		*stackptr++ = v;				\
163     		u = *v;						\
164     	}							\
165     	u;							\
166     })
167     
168     /* Called with local BH disabled and the pool write lock held. */
169     #define lookup_rightempty(start)				\
170     ({								\
171     	struct inet_peer *u, **v;				\
172     	*stackptr++ = &start->avl_left;				\
173     	v = &start->avl_left;					\
174     	for (u = *v; u->avl_right != peer_avl_empty; ) {	\
175     		v = &u->avl_right;				\
176     		*stackptr++ = v;				\
177     		u = *v;						\
178     	}							\
179     	u;							\
180     })
181     
182     /* Called with local BH disabled and the pool write lock held.
183      * Variable names are the proof of operation correctness.
184      * Look into mm/map_avl.c for more detail description of the ideas.  */
185     static void peer_avl_rebalance(struct inet_peer **stack[],
186     		struct inet_peer ***stackend)
187     {
188     	struct inet_peer **nodep, *node, *l, *r;
189     	int lh, rh;
190     
191     	while (stackend > stack) {
192     		nodep = *--stackend;
193     		node = *nodep;
194     		l = node->avl_left;
195     		r = node->avl_right;
196     		lh = node_height(l);
197     		rh = node_height(r);
198     		if (lh > rh + 1) { /* l: RH+2 */
199     			struct inet_peer *ll, *lr, *lrl, *lrr;
200     			int lrh;
201     			ll = l->avl_left;
202     			lr = l->avl_right;
203     			lrh = node_height(lr);
204     			if (lrh <= node_height(ll)) {	/* ll: RH+1 */
205     				node->avl_left = lr;	/* lr: RH or RH+1 */
206     				node->avl_right = r;	/* r: RH */
207     				node->avl_height = lrh + 1; /* RH+1 or RH+2 */
208     				l->avl_left = ll;	/* ll: RH+1 */
209     				l->avl_right = node;	/* node: RH+1 or RH+2 */
210     				l->avl_height = node->avl_height + 1;
211     				*nodep = l;
212     			} else { /* ll: RH, lr: RH+1 */
213     				lrl = lr->avl_left;	/* lrl: RH or RH-1 */
214     				lrr = lr->avl_right;	/* lrr: RH or RH-1 */
215     				node->avl_left = lrr;	/* lrr: RH or RH-1 */
216     				node->avl_right = r;	/* r: RH */
217     				node->avl_height = rh + 1; /* node: RH+1 */
218     				l->avl_left = ll;	/* ll: RH */
219     				l->avl_right = lrl;	/* lrl: RH or RH-1 */
220     				l->avl_height = rh + 1;	/* l: RH+1 */
221     				lr->avl_left = l;	/* l: RH+1 */
222     				lr->avl_right = node;	/* node: RH+1 */
223     				lr->avl_height = rh + 2;
224     				*nodep = lr;
225     			}
226     		} else if (rh > lh + 1) { /* r: LH+2 */
227     			struct inet_peer *rr, *rl, *rlr, *rll;
228     			int rlh;
229     			rr = r->avl_right;
230     			rl = r->avl_left;
231     			rlh = node_height(rl);
232     			if (rlh <= node_height(rr)) {	/* rr: LH+1 */
233     				node->avl_right = rl;	/* rl: LH or LH+1 */
234     				node->avl_left = l;	/* l: LH */
235     				node->avl_height = rlh + 1; /* LH+1 or LH+2 */
236     				r->avl_right = rr;	/* rr: LH+1 */
237     				r->avl_left = node;	/* node: LH+1 or LH+2 */
238     				r->avl_height = node->avl_height + 1;
239     				*nodep = r;
240     			} else { /* rr: RH, rl: RH+1 */
241     				rlr = rl->avl_right;	/* rlr: LH or LH-1 */
242     				rll = rl->avl_left;	/* rll: LH or LH-1 */
243     				node->avl_right = rll;	/* rll: LH or LH-1 */
244     				node->avl_left = l;	/* l: LH */
245     				node->avl_height = lh + 1; /* node: LH+1 */
246     				r->avl_right = rr;	/* rr: LH */
247     				r->avl_left = rlr;	/* rlr: LH or LH-1 */
248     				r->avl_height = lh + 1;	/* r: LH+1 */
249     				rl->avl_right = r;	/* r: LH+1 */
250     				rl->avl_left = node;	/* node: LH+1 */
251     				rl->avl_height = lh + 2;
252     				*nodep = rl;
253     			}
254     		} else {
255     			node->avl_height = (lh > rh ? lh : rh) + 1;
256     		}
257     	}
258     }
259     
260     /* Called with local BH disabled and the pool write lock held. */
261     #define link_to_pool(n)						\
262     do {								\
263     	n->avl_height = 1;					\
264     	n->avl_left = peer_avl_empty;				\
265     	n->avl_right = peer_avl_empty;				\
266     	**--stackptr = n;					\
267     	peer_avl_rebalance(stack, stackptr);			\
268     } while(0)
269     
270     /* May be called with local BH enabled. */
271     static void unlink_from_pool(struct inet_peer *p)
272     {
273     	int do_free;
274     
275     	do_free = 0;
276     
277     	write_lock_bh(&peer_pool_lock);
278     	/* Check the reference counter.  It was artificially incremented by 1
279     	 * in cleanup() function to prevent sudden disappearing.  If the
280     	 * reference count is still 1 then the node is referenced only as `p'
281     	 * here and from the pool.  So under the exclusive pool lock it's safe
282     	 * to remove the node and free it later. */
283     	if (atomic_read(&p->refcnt) == 1) {
284     		struct inet_peer **stack[PEER_MAXDEPTH];
285     		struct inet_peer ***stackptr, ***delp;
286     		if (lookup(p->v4daddr) != p)
287     			BUG();
288     		delp = stackptr - 1; /* *delp[0] == p */
289     		if (p->avl_left == peer_avl_empty) {
290     			*delp[0] = p->avl_right;
291     			--stackptr;
292     		} else {
293     			/* look for a node to insert instead of p */
294     			struct inet_peer *t;
295     			t = lookup_rightempty(p);
296     			if (*stackptr[-1] != t)
297     				BUG();
298     			**--stackptr = t->avl_left;
299     			/* t is removed, t->v4daddr > x->v4daddr for any
300     			 * x in p->avl_left subtree.
301     			 * Put t in the old place of p. */
302     			*delp[0] = t;
303     			t->avl_left = p->avl_left;
304     			t->avl_right = p->avl_right;
305     			t->avl_height = p->avl_height;
306     			if (delp[1] != &p->avl_left)
307     				BUG();
308     			delp[1] = &t->avl_left; /* was &p->avl_left */
309     		}
310     		peer_avl_rebalance(stack, stackptr);
311     		peer_total--;
312     		do_free = 1;
313     	}
314     	write_unlock_bh(&peer_pool_lock);
315     
316     	if (do_free)
317     		kmem_cache_free(peer_cachep, p);
318     	else
319     		/* The node is used again.  Decrease the reference counter
320     		 * back.  The loop "cleanup -> unlink_from_unused
321     		 *   -> unlink_from_pool -> putpeer -> link_to_unused
322     		 *   -> cleanup (for the same node)"
323     		 * doesn't really exist because the entry will have a
324     		 * recent deletion time and will not be cleaned again soon. */
325     		inet_putpeer(p);
326     }
327     
328     /* May be called with local BH enabled. */
329     static int cleanup_once(unsigned long ttl)
330     {
331     	struct inet_peer *p;
332     
333     	/* Remove the first entry from the list of unused nodes. */
334     	spin_lock_bh(&inet_peer_unused_lock);
335     	p = inet_peer_unused_head;
336     	if (p != NULL) {
337     		if (time_after(p->dtime + ttl, jiffies)) {
338     			/* Do not prune fresh entries. */
339     			spin_unlock_bh(&inet_peer_unused_lock);
340     			return -1;
341     		}
342     		inet_peer_unused_head = p->unused_next;
343     		if (p->unused_next != NULL)
344     			p->unused_next->unused_prevp = p->unused_prevp;
345     		else
346     			inet_peer_unused_tailp = p->unused_prevp;
347     		p->unused_prevp = NULL; /* mark as not on the list */
348     		/* Grab an extra reference to prevent node disappearing
349     		 * before unlink_from_pool() call. */
350     		atomic_inc(&p->refcnt);
351     	}
352     	spin_unlock_bh(&inet_peer_unused_lock);
353     
354     	if (p == NULL)
355     		/* It means that the total number of USED entries has
356     		 * grown over inet_peer_threshold.  It shouldn't really
357     		 * happen because of entry limits in route cache. */
358     		return -1;
359     
360     	unlink_from_pool(p);
361     	return 0;
362     }
363     
364     /* Called with or without local BH being disabled. */
365     struct inet_peer *inet_getpeer(__u32 daddr, int create)
366     {
367     	struct inet_peer *p, *n;
368     	struct inet_peer **stack[PEER_MAXDEPTH], ***stackptr;
369     
370     	/* Look up for the address quickly. */
371     	read_lock_bh(&peer_pool_lock);
372     	p = lookup(daddr);
373     	if (p != peer_avl_empty)
374     		atomic_inc(&p->refcnt);
375     	read_unlock_bh(&peer_pool_lock);
376     
377     	if (p != peer_avl_empty) {
378     		/* The existing node has been found. */
379     		/* Remove the entry from unused list if it was there. */
380     		unlink_from_unused(p);
381     		return p;
382     	}
383     
384     	if (!create)
385     		return NULL;
386     
387     	/* Allocate the space outside the locked region. */
388     	n = kmem_cache_alloc(peer_cachep, GFP_ATOMIC);
389     	if (n == NULL)
390     		return NULL;
391     	n->v4daddr = daddr;
392     	atomic_set(&n->refcnt, 1);
393     	n->ip_id_count = secure_ip_id(daddr);
394     	n->tcp_ts_stamp = 0;
395     
396     	write_lock_bh(&peer_pool_lock);
397     	/* Check if an entry has suddenly appeared. */
398     	p = lookup(daddr);
399     	if (p != peer_avl_empty)
400     		goto out_free;
401     
402     	/* Link the node. */
403     	link_to_pool(n);
404     	n->unused_prevp = NULL; /* not on the list */
405     	peer_total++;
406     	write_unlock_bh(&peer_pool_lock);
407     
408     	if (peer_total >= inet_peer_threshold)
409     		/* Remove one less-recently-used entry. */
410     		cleanup_once(0);
411     
412     	return n;
413     
414     out_free:
415     	/* The appropriate node is already in the pool. */
416     	atomic_inc(&p->refcnt);
417     	write_unlock_bh(&peer_pool_lock);
418     	/* Remove the entry from unused list if it was there. */
419     	unlink_from_unused(p);
420     	/* Free preallocated the preallocated node. */
421     	kmem_cache_free(peer_cachep, n);
422     	return p;
423     }
424     
425     /* Called with local BH disabled. */
426     static void peer_check_expire(unsigned long dummy)
427     {
428     	int i;
429     	int ttl;
430     
431     	if (peer_total >= inet_peer_threshold)
432     		ttl = inet_peer_minttl;
433     	else
434     		ttl = inet_peer_maxttl
435     				- (inet_peer_maxttl - inet_peer_minttl) / HZ *
436     					peer_total / inet_peer_threshold * HZ;
437     	for (i = 0; i < PEER_MAX_CLEANUP_WORK && !cleanup_once(ttl); i++);
438     
439     	/* Trigger the timer after inet_peer_gc_mintime .. inet_peer_gc_maxtime
440     	 * interval depending on the total number of entries (more entries,
441     	 * less interval). */
442     	peer_periodic_timer.expires = jiffies
443     		+ inet_peer_gc_maxtime
444     		- (inet_peer_gc_maxtime - inet_peer_gc_mintime) / HZ *
445     			peer_total / inet_peer_threshold * HZ;
446     	add_timer(&peer_periodic_timer);
447     }
448