xref: /linux/net/ipv4/inetpeer.c (revision 4e75db2e8ff2c97762e87f61f54d7cdeaab1a6b0)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  *		INETPEER - A storage for permanent information about peers
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  *  This source is covered by the GNU GPL, the same as all kernel sources.
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *  Authors:	Andrey V. Savochkin <saw@msu.ru>
71da177e4SLinus Torvalds  */
81da177e4SLinus Torvalds 
91da177e4SLinus Torvalds #include <linux/module.h>
101da177e4SLinus Torvalds #include <linux/types.h>
111da177e4SLinus Torvalds #include <linux/slab.h>
121da177e4SLinus Torvalds #include <linux/interrupt.h>
131da177e4SLinus Torvalds #include <linux/spinlock.h>
141da177e4SLinus Torvalds #include <linux/random.h>
151da177e4SLinus Torvalds #include <linux/timer.h>
161da177e4SLinus Torvalds #include <linux/time.h>
171da177e4SLinus Torvalds #include <linux/kernel.h>
181da177e4SLinus Torvalds #include <linux/mm.h>
191da177e4SLinus Torvalds #include <linux/net.h>
2020380731SArnaldo Carvalho de Melo #include <net/ip.h>
211da177e4SLinus Torvalds #include <net/inetpeer.h>
221da177e4SLinus Torvalds 
231da177e4SLinus Torvalds /*
241da177e4SLinus Torvalds  *  Theory of operations.
251da177e4SLinus Torvalds  *  We keep one entry for each peer IP address.  The nodes contains long-living
261da177e4SLinus Torvalds  *  information about the peer which doesn't depend on routes.
271da177e4SLinus Torvalds  *  At this moment this information consists only of ID field for the next
281da177e4SLinus Torvalds  *  outgoing IP packet.  This field is incremented with each packet as encoded
291da177e4SLinus Torvalds  *  in inet_getid() function (include/net/inetpeer.h).
301da177e4SLinus Torvalds  *  At the moment of writing this notes identifier of IP packets is generated
311da177e4SLinus Torvalds  *  to be unpredictable using this code only for packets subjected
321da177e4SLinus Torvalds  *  (actually or potentially) to defragmentation.  I.e. DF packets less than
331da177e4SLinus Torvalds  *  PMTU in size uses a constant ID and do not use this code (see
341da177e4SLinus Torvalds  *  ip_select_ident() in include/net/ip.h).
351da177e4SLinus Torvalds  *
361da177e4SLinus Torvalds  *  Route cache entries hold references to our nodes.
371da177e4SLinus Torvalds  *  New cache entries get references via lookup by destination IP address in
381da177e4SLinus Torvalds  *  the avl tree.  The reference is grabbed only when it's needed i.e. only
391da177e4SLinus Torvalds  *  when we try to output IP packet which needs an unpredictable ID (see
401da177e4SLinus Torvalds  *  __ip_select_ident() in net/ipv4/route.c).
411da177e4SLinus Torvalds  *  Nodes are removed only when reference counter goes to 0.
421da177e4SLinus Torvalds  *  When it's happened the node may be removed when a sufficient amount of
431da177e4SLinus Torvalds  *  time has been passed since its last use.  The less-recently-used entry can
441da177e4SLinus Torvalds  *  also be removed if the pool is overloaded i.e. if the total amount of
451da177e4SLinus Torvalds  *  entries is greater-or-equal than the threshold.
461da177e4SLinus Torvalds  *
471da177e4SLinus Torvalds  *  Node pool is organised as an AVL tree.
481da177e4SLinus Torvalds  *  Such an implementation has been chosen not just for fun.  It's a way to
491da177e4SLinus Torvalds  *  prevent easy and efficient DoS attacks by creating hash collisions.  A huge
501da177e4SLinus Torvalds  *  amount of long living nodes in a single hash slot would significantly delay
511da177e4SLinus Torvalds  *  lookups performed with disabled BHs.
521da177e4SLinus Torvalds  *
531da177e4SLinus Torvalds  *  Serialisation issues.
54aa1039e7SEric Dumazet  *  1.  Nodes may appear in the tree only with the pool lock held.
55aa1039e7SEric Dumazet  *  2.  Nodes may disappear from the tree only with the pool lock held
561da177e4SLinus Torvalds  *      AND reference count being 0.
571da177e4SLinus Torvalds  *  3.  Nodes appears and disappears from unused node list only under
581da177e4SLinus Torvalds  *      "inet_peer_unused_lock".
591da177e4SLinus Torvalds  *  4.  Global variable peer_total is modified under the pool lock.
601da177e4SLinus Torvalds  *  5.  struct inet_peer fields modification:
611da177e4SLinus Torvalds  *		avl_left, avl_right, avl_parent, avl_height: pool lock
62d71209deSPavel Emelyanov  *		unused: unused node list lock
631da177e4SLinus Torvalds  *		refcnt: atomically against modifications on other CPU;
641da177e4SLinus Torvalds  *		   usually under some other lock to prevent node disappearing
651da177e4SLinus Torvalds  *		dtime: unused node list lock
66582a72daSDavid S. Miller  *		daddr: unchangeable
67317fe0e6SEric Dumazet  *		ip_id_count: atomic value (no lock needed)
681da177e4SLinus Torvalds  */
691da177e4SLinus Torvalds 
70e18b890bSChristoph Lameter static struct kmem_cache *peer_cachep __read_mostly;
711da177e4SLinus Torvalds 
721da177e4SLinus Torvalds #define node_height(x) x->avl_height
73d6cc1d64SEric Dumazet 
74d6cc1d64SEric Dumazet #define peer_avl_empty ((struct inet_peer *)&peer_fake_node)
75b914c4eaSEric Dumazet #define peer_avl_empty_rcu ((struct inet_peer __rcu __force *)&peer_fake_node)
76d6cc1d64SEric Dumazet static const struct inet_peer peer_fake_node = {
77b914c4eaSEric Dumazet 	.avl_left	= peer_avl_empty_rcu,
78b914c4eaSEric Dumazet 	.avl_right	= peer_avl_empty_rcu,
791da177e4SLinus Torvalds 	.avl_height	= 0
801da177e4SLinus Torvalds };
81d6cc1d64SEric Dumazet 
82021e9299SDavid S. Miller struct inet_peer_base {
83b914c4eaSEric Dumazet 	struct inet_peer __rcu *root;
8465e8354eSEric Dumazet 	seqlock_t	lock;
85d6cc1d64SEric Dumazet 	int		total;
86021e9299SDavid S. Miller };
87021e9299SDavid S. Miller 
88021e9299SDavid S. Miller static struct inet_peer_base v4_peers = {
89b914c4eaSEric Dumazet 	.root		= peer_avl_empty_rcu,
9065e8354eSEric Dumazet 	.lock		= __SEQLOCK_UNLOCKED(v4_peers.lock),
91d6cc1d64SEric Dumazet 	.total		= 0,
92d6cc1d64SEric Dumazet };
93021e9299SDavid S. Miller 
94021e9299SDavid S. Miller static struct inet_peer_base v6_peers = {
95021e9299SDavid S. Miller 	.root		= peer_avl_empty_rcu,
9665e8354eSEric Dumazet 	.lock		= __SEQLOCK_UNLOCKED(v6_peers.lock),
97021e9299SDavid S. Miller 	.total		= 0,
98021e9299SDavid S. Miller };
99021e9299SDavid S. Miller 
1001da177e4SLinus Torvalds #define PEER_MAXDEPTH 40 /* sufficient for about 2^27 nodes */
1011da177e4SLinus Torvalds 
1021da177e4SLinus Torvalds /* Exported for sysctl_net_ipv4.  */
103243bbcaaSEric Dumazet int inet_peer_threshold __read_mostly = 65536 + 128;	/* start to throw entries more
1041da177e4SLinus Torvalds 					 * aggressively at this stage */
105243bbcaaSEric Dumazet int inet_peer_minttl __read_mostly = 120 * HZ;	/* TTL under high load: 120 sec */
106243bbcaaSEric Dumazet int inet_peer_maxttl __read_mostly = 10 * 60 * HZ;	/* usual time to live: 10 min */
107243bbcaaSEric Dumazet int inet_peer_gc_mintime __read_mostly = 10 * HZ;
108243bbcaaSEric Dumazet int inet_peer_gc_maxtime __read_mostly = 120 * HZ;
1091da177e4SLinus Torvalds 
110d6cc1d64SEric Dumazet static struct {
111d6cc1d64SEric Dumazet 	struct list_head	list;
112d6cc1d64SEric Dumazet 	spinlock_t		lock;
113d6cc1d64SEric Dumazet } unused_peers = {
114d6cc1d64SEric Dumazet 	.list			= LIST_HEAD_INIT(unused_peers.list),
115d6cc1d64SEric Dumazet 	.lock			= __SPIN_LOCK_UNLOCKED(unused_peers.lock),
116d6cc1d64SEric Dumazet };
1171da177e4SLinus Torvalds 
1181da177e4SLinus Torvalds static void peer_check_expire(unsigned long dummy);
1198d06afabSIngo Molnar static DEFINE_TIMER(peer_periodic_timer, peer_check_expire, 0, 0);
1201da177e4SLinus Torvalds 
1211da177e4SLinus Torvalds 
1221da177e4SLinus Torvalds /* Called from ip_output.c:ip_init  */
1231da177e4SLinus Torvalds void __init inet_initpeers(void)
1241da177e4SLinus Torvalds {
1251da177e4SLinus Torvalds 	struct sysinfo si;
1261da177e4SLinus Torvalds 
1271da177e4SLinus Torvalds 	/* Use the straight interface to information about memory. */
1281da177e4SLinus Torvalds 	si_meminfo(&si);
1291da177e4SLinus Torvalds 	/* The values below were suggested by Alexey Kuznetsov
1301da177e4SLinus Torvalds 	 * <kuznet@ms2.inr.ac.ru>.  I don't have any opinion about the values
1311da177e4SLinus Torvalds 	 * myself.  --SAW
1321da177e4SLinus Torvalds 	 */
1331da177e4SLinus Torvalds 	if (si.totalram <= (32768*1024)/PAGE_SIZE)
1341da177e4SLinus Torvalds 		inet_peer_threshold >>= 1; /* max pool size about 1MB on IA32 */
1351da177e4SLinus Torvalds 	if (si.totalram <= (16384*1024)/PAGE_SIZE)
1361da177e4SLinus Torvalds 		inet_peer_threshold >>= 1; /* about 512KB */
1371da177e4SLinus Torvalds 	if (si.totalram <= (8192*1024)/PAGE_SIZE)
1381da177e4SLinus Torvalds 		inet_peer_threshold >>= 2; /* about 128KB */
1391da177e4SLinus Torvalds 
1401da177e4SLinus Torvalds 	peer_cachep = kmem_cache_create("inet_peer_cache",
1411da177e4SLinus Torvalds 			sizeof(struct inet_peer),
142317fe0e6SEric Dumazet 			0, SLAB_HWCACHE_ALIGN | SLAB_PANIC,
14320c2df83SPaul Mundt 			NULL);
1441da177e4SLinus Torvalds 
1451da177e4SLinus Torvalds 	/* All the timers, started at system startup tend
1461da177e4SLinus Torvalds 	   to synchronize. Perturb it a bit.
1471da177e4SLinus Torvalds 	 */
1481da177e4SLinus Torvalds 	peer_periodic_timer.expires = jiffies
1491da177e4SLinus Torvalds 		+ net_random() % inet_peer_gc_maxtime
1501da177e4SLinus Torvalds 		+ inet_peer_gc_maxtime;
1511da177e4SLinus Torvalds 	add_timer(&peer_periodic_timer);
1521da177e4SLinus Torvalds }
1531da177e4SLinus Torvalds 
1541da177e4SLinus Torvalds /* Called with or without local BH being disabled. */
1551da177e4SLinus Torvalds static void unlink_from_unused(struct inet_peer *p)
1561da177e4SLinus Torvalds {
157d6cc1d64SEric Dumazet 	if (!list_empty(&p->unused)) {
158d6cc1d64SEric Dumazet 		spin_lock_bh(&unused_peers.lock);
159d71209deSPavel Emelyanov 		list_del_init(&p->unused);
160d6cc1d64SEric Dumazet 		spin_unlock_bh(&unused_peers.lock);
161d6cc1d64SEric Dumazet 	}
1621da177e4SLinus Torvalds }
1631da177e4SLinus Torvalds 
1648790ca17SDavid S. Miller static int addr_compare(const struct inetpeer_addr *a,
1658790ca17SDavid S. Miller 			const struct inetpeer_addr *b)
16602663045SDavid S. Miller {
16702663045SDavid S. Miller 	int i, n = (a->family == AF_INET ? 1 : 4);
16802663045SDavid S. Miller 
16902663045SDavid S. Miller 	for (i = 0; i < n; i++) {
1707a71ed89SDavid S. Miller 		if (a->addr.a6[i] == b->addr.a6[i])
17102663045SDavid S. Miller 			continue;
1727a71ed89SDavid S. Miller 		if (a->addr.a6[i] < b->addr.a6[i])
17302663045SDavid S. Miller 			return -1;
17402663045SDavid S. Miller 		return 1;
17502663045SDavid S. Miller 	}
17602663045SDavid S. Miller 
17702663045SDavid S. Miller 	return 0;
17802663045SDavid S. Miller }
17902663045SDavid S. Miller 
18065e8354eSEric Dumazet #define rcu_deref_locked(X, BASE)				\
18165e8354eSEric Dumazet 	rcu_dereference_protected(X, lockdep_is_held(&(BASE)->lock.lock))
18265e8354eSEric Dumazet 
183243bbcaaSEric Dumazet /*
184243bbcaaSEric Dumazet  * Called with local BH disabled and the pool lock held.
185243bbcaaSEric Dumazet  */
18698158f5aSDavid S. Miller #define lookup(_daddr, _stack, _base)				\
1871da177e4SLinus Torvalds ({								\
188b914c4eaSEric Dumazet 	struct inet_peer *u;					\
189b914c4eaSEric Dumazet 	struct inet_peer __rcu **v;				\
190aa1039e7SEric Dumazet 								\
191243bbcaaSEric Dumazet 	stackptr = _stack;					\
19298158f5aSDavid S. Miller 	*stackptr++ = &_base->root;				\
19365e8354eSEric Dumazet 	for (u = rcu_deref_locked(_base->root, _base);		\
194b914c4eaSEric Dumazet 	     u != peer_avl_empty; ) {				\
19502663045SDavid S. Miller 		int cmp = addr_compare(_daddr, &u->daddr);	\
19602663045SDavid S. Miller 		if (cmp == 0)					\
1971da177e4SLinus Torvalds 			break;					\
19802663045SDavid S. Miller 		if (cmp == -1)					\
1991da177e4SLinus Torvalds 			v = &u->avl_left;			\
2001da177e4SLinus Torvalds 		else						\
2011da177e4SLinus Torvalds 			v = &u->avl_right;			\
2021da177e4SLinus Torvalds 		*stackptr++ = v;				\
20365e8354eSEric Dumazet 		u = rcu_deref_locked(*v, _base);		\
2041da177e4SLinus Torvalds 	}							\
2051da177e4SLinus Torvalds 	u;							\
2061da177e4SLinus Torvalds })
2071da177e4SLinus Torvalds 
208aa1039e7SEric Dumazet /*
2097b46ac4eSDavid S. Miller  * Called with rcu_read_lock()
210aa1039e7SEric Dumazet  * Because we hold no lock against a writer, its quite possible we fall
211aa1039e7SEric Dumazet  * in an endless loop.
212aa1039e7SEric Dumazet  * But every pointer we follow is guaranteed to be valid thanks to RCU.
213aa1039e7SEric Dumazet  * We exit from this function if number of links exceeds PEER_MAXDEPTH
214aa1039e7SEric Dumazet  */
2157b46ac4eSDavid S. Miller static struct inet_peer *lookup_rcu(const struct inetpeer_addr *daddr,
21602663045SDavid S. Miller 				    struct inet_peer_base *base)
217aa1039e7SEric Dumazet {
2187b46ac4eSDavid S. Miller 	struct inet_peer *u = rcu_dereference(base->root);
219aa1039e7SEric Dumazet 	int count = 0;
220aa1039e7SEric Dumazet 
221aa1039e7SEric Dumazet 	while (u != peer_avl_empty) {
22202663045SDavid S. Miller 		int cmp = addr_compare(daddr, &u->daddr);
22302663045SDavid S. Miller 		if (cmp == 0) {
2245f2f8920SEric Dumazet 			/* Before taking a reference, check if this entry was
2255f2f8920SEric Dumazet 			 * deleted, unlink_from_pool() sets refcnt=-1 to make
2265f2f8920SEric Dumazet 			 * distinction between an unused entry (refcnt=0) and
2275f2f8920SEric Dumazet 			 * a freed one.
2285f2f8920SEric Dumazet 			 */
2295f2f8920SEric Dumazet 			if (unlikely(!atomic_add_unless(&u->refcnt, 1, -1)))
230aa1039e7SEric Dumazet 				u = NULL;
231aa1039e7SEric Dumazet 			return u;
232aa1039e7SEric Dumazet 		}
23302663045SDavid S. Miller 		if (cmp == -1)
2347b46ac4eSDavid S. Miller 			u = rcu_dereference(u->avl_left);
235aa1039e7SEric Dumazet 		else
2367b46ac4eSDavid S. Miller 			u = rcu_dereference(u->avl_right);
237aa1039e7SEric Dumazet 		if (unlikely(++count == PEER_MAXDEPTH))
238aa1039e7SEric Dumazet 			break;
239aa1039e7SEric Dumazet 	}
240aa1039e7SEric Dumazet 	return NULL;
241aa1039e7SEric Dumazet }
242aa1039e7SEric Dumazet 
243aa1039e7SEric Dumazet /* Called with local BH disabled and the pool lock held. */
24498158f5aSDavid S. Miller #define lookup_rightempty(start, base)				\
2451da177e4SLinus Torvalds ({								\
246b914c4eaSEric Dumazet 	struct inet_peer *u;					\
247b914c4eaSEric Dumazet 	struct inet_peer __rcu **v;				\
2481da177e4SLinus Torvalds 	*stackptr++ = &start->avl_left;				\
2491da177e4SLinus Torvalds 	v = &start->avl_left;					\
25065e8354eSEric Dumazet 	for (u = rcu_deref_locked(*v, base);			\
251b914c4eaSEric Dumazet 	     u->avl_right != peer_avl_empty_rcu; ) {		\
2521da177e4SLinus Torvalds 		v = &u->avl_right;				\
2531da177e4SLinus Torvalds 		*stackptr++ = v;				\
25465e8354eSEric Dumazet 		u = rcu_deref_locked(*v, base);			\
2551da177e4SLinus Torvalds 	}							\
2561da177e4SLinus Torvalds 	u;							\
2571da177e4SLinus Torvalds })
2581da177e4SLinus Torvalds 
259aa1039e7SEric Dumazet /* Called with local BH disabled and the pool lock held.
2601da177e4SLinus Torvalds  * Variable names are the proof of operation correctness.
261aa1039e7SEric Dumazet  * Look into mm/map_avl.c for more detail description of the ideas.
262aa1039e7SEric Dumazet  */
263b914c4eaSEric Dumazet static void peer_avl_rebalance(struct inet_peer __rcu **stack[],
26498158f5aSDavid S. Miller 			       struct inet_peer __rcu ***stackend,
26598158f5aSDavid S. Miller 			       struct inet_peer_base *base)
2661da177e4SLinus Torvalds {
267b914c4eaSEric Dumazet 	struct inet_peer __rcu **nodep;
268b914c4eaSEric Dumazet 	struct inet_peer *node, *l, *r;
2691da177e4SLinus Torvalds 	int lh, rh;
2701da177e4SLinus Torvalds 
2711da177e4SLinus Torvalds 	while (stackend > stack) {
2721da177e4SLinus Torvalds 		nodep = *--stackend;
27365e8354eSEric Dumazet 		node = rcu_deref_locked(*nodep, base);
27465e8354eSEric Dumazet 		l = rcu_deref_locked(node->avl_left, base);
27565e8354eSEric Dumazet 		r = rcu_deref_locked(node->avl_right, base);
2761da177e4SLinus Torvalds 		lh = node_height(l);
2771da177e4SLinus Torvalds 		rh = node_height(r);
2781da177e4SLinus Torvalds 		if (lh > rh + 1) { /* l: RH+2 */
2791da177e4SLinus Torvalds 			struct inet_peer *ll, *lr, *lrl, *lrr;
2801da177e4SLinus Torvalds 			int lrh;
28165e8354eSEric Dumazet 			ll = rcu_deref_locked(l->avl_left, base);
28265e8354eSEric Dumazet 			lr = rcu_deref_locked(l->avl_right, base);
2831da177e4SLinus Torvalds 			lrh = node_height(lr);
2841da177e4SLinus Torvalds 			if (lrh <= node_height(ll)) {	/* ll: RH+1 */
285b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_left, lr);	/* lr: RH or RH+1 */
286b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_right, r);	/* r: RH */
2871da177e4SLinus Torvalds 				node->avl_height = lrh + 1; /* RH+1 or RH+2 */
288b914c4eaSEric Dumazet 				RCU_INIT_POINTER(l->avl_left, ll);       /* ll: RH+1 */
289b914c4eaSEric Dumazet 				RCU_INIT_POINTER(l->avl_right, node);	/* node: RH+1 or RH+2 */
2901da177e4SLinus Torvalds 				l->avl_height = node->avl_height + 1;
291b914c4eaSEric Dumazet 				RCU_INIT_POINTER(*nodep, l);
2921da177e4SLinus Torvalds 			} else { /* ll: RH, lr: RH+1 */
29365e8354eSEric Dumazet 				lrl = rcu_deref_locked(lr->avl_left, base);/* lrl: RH or RH-1 */
29465e8354eSEric Dumazet 				lrr = rcu_deref_locked(lr->avl_right, base);/* lrr: RH or RH-1 */
295b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_left, lrr);	/* lrr: RH or RH-1 */
296b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_right, r);	/* r: RH */
2971da177e4SLinus Torvalds 				node->avl_height = rh + 1; /* node: RH+1 */
298b914c4eaSEric Dumazet 				RCU_INIT_POINTER(l->avl_left, ll);	/* ll: RH */
299b914c4eaSEric Dumazet 				RCU_INIT_POINTER(l->avl_right, lrl);	/* lrl: RH or RH-1 */
3001da177e4SLinus Torvalds 				l->avl_height = rh + 1;	/* l: RH+1 */
301b914c4eaSEric Dumazet 				RCU_INIT_POINTER(lr->avl_left, l);	/* l: RH+1 */
302b914c4eaSEric Dumazet 				RCU_INIT_POINTER(lr->avl_right, node);	/* node: RH+1 */
3031da177e4SLinus Torvalds 				lr->avl_height = rh + 2;
304b914c4eaSEric Dumazet 				RCU_INIT_POINTER(*nodep, lr);
3051da177e4SLinus Torvalds 			}
3061da177e4SLinus Torvalds 		} else if (rh > lh + 1) { /* r: LH+2 */
3071da177e4SLinus Torvalds 			struct inet_peer *rr, *rl, *rlr, *rll;
3081da177e4SLinus Torvalds 			int rlh;
30965e8354eSEric Dumazet 			rr = rcu_deref_locked(r->avl_right, base);
31065e8354eSEric Dumazet 			rl = rcu_deref_locked(r->avl_left, base);
3111da177e4SLinus Torvalds 			rlh = node_height(rl);
3121da177e4SLinus Torvalds 			if (rlh <= node_height(rr)) {	/* rr: LH+1 */
313b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_right, rl);	/* rl: LH or LH+1 */
314b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_left, l);	/* l: LH */
3151da177e4SLinus Torvalds 				node->avl_height = rlh + 1; /* LH+1 or LH+2 */
316b914c4eaSEric Dumazet 				RCU_INIT_POINTER(r->avl_right, rr);	/* rr: LH+1 */
317b914c4eaSEric Dumazet 				RCU_INIT_POINTER(r->avl_left, node);	/* node: LH+1 or LH+2 */
3181da177e4SLinus Torvalds 				r->avl_height = node->avl_height + 1;
319b914c4eaSEric Dumazet 				RCU_INIT_POINTER(*nodep, r);
3201da177e4SLinus Torvalds 			} else { /* rr: RH, rl: RH+1 */
32165e8354eSEric Dumazet 				rlr = rcu_deref_locked(rl->avl_right, base);/* rlr: LH or LH-1 */
32265e8354eSEric Dumazet 				rll = rcu_deref_locked(rl->avl_left, base);/* rll: LH or LH-1 */
323b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_right, rll);	/* rll: LH or LH-1 */
324b914c4eaSEric Dumazet 				RCU_INIT_POINTER(node->avl_left, l);	/* l: LH */
3251da177e4SLinus Torvalds 				node->avl_height = lh + 1; /* node: LH+1 */
326b914c4eaSEric Dumazet 				RCU_INIT_POINTER(r->avl_right, rr);	/* rr: LH */
327b914c4eaSEric Dumazet 				RCU_INIT_POINTER(r->avl_left, rlr);	/* rlr: LH or LH-1 */
3281da177e4SLinus Torvalds 				r->avl_height = lh + 1;	/* r: LH+1 */
329b914c4eaSEric Dumazet 				RCU_INIT_POINTER(rl->avl_right, r);	/* r: LH+1 */
330b914c4eaSEric Dumazet 				RCU_INIT_POINTER(rl->avl_left, node);	/* node: LH+1 */
3311da177e4SLinus Torvalds 				rl->avl_height = lh + 2;
332b914c4eaSEric Dumazet 				RCU_INIT_POINTER(*nodep, rl);
3331da177e4SLinus Torvalds 			}
3341da177e4SLinus Torvalds 		} else {
3351da177e4SLinus Torvalds 			node->avl_height = (lh > rh ? lh : rh) + 1;
3361da177e4SLinus Torvalds 		}
3371da177e4SLinus Torvalds 	}
3381da177e4SLinus Torvalds }
3391da177e4SLinus Torvalds 
340aa1039e7SEric Dumazet /* Called with local BH disabled and the pool lock held. */
34198158f5aSDavid S. Miller #define link_to_pool(n, base)					\
3421da177e4SLinus Torvalds do {								\
3431da177e4SLinus Torvalds 	n->avl_height = 1;					\
344b914c4eaSEric Dumazet 	n->avl_left = peer_avl_empty_rcu;			\
345b914c4eaSEric Dumazet 	n->avl_right = peer_avl_empty_rcu;			\
346b914c4eaSEric Dumazet 	/* lockless readers can catch us now */			\
347b914c4eaSEric Dumazet 	rcu_assign_pointer(**--stackptr, n);			\
34898158f5aSDavid S. Miller 	peer_avl_rebalance(stack, stackptr, base);		\
3491da177e4SLinus Torvalds } while (0)
3501da177e4SLinus Torvalds 
351aa1039e7SEric Dumazet static void inetpeer_free_rcu(struct rcu_head *head)
352aa1039e7SEric Dumazet {
353aa1039e7SEric Dumazet 	kmem_cache_free(peer_cachep, container_of(head, struct inet_peer, rcu));
354aa1039e7SEric Dumazet }
355aa1039e7SEric Dumazet 
3561da177e4SLinus Torvalds /* May be called with local BH enabled. */
35798158f5aSDavid S. Miller static void unlink_from_pool(struct inet_peer *p, struct inet_peer_base *base)
3581da177e4SLinus Torvalds {
3591da177e4SLinus Torvalds 	int do_free;
3601da177e4SLinus Torvalds 
3611da177e4SLinus Torvalds 	do_free = 0;
3621da177e4SLinus Torvalds 
36365e8354eSEric Dumazet 	write_seqlock_bh(&base->lock);
3641da177e4SLinus Torvalds 	/* Check the reference counter.  It was artificially incremented by 1
365aa1039e7SEric Dumazet 	 * in cleanup() function to prevent sudden disappearing.  If we can
366aa1039e7SEric Dumazet 	 * atomically (because of lockless readers) take this last reference,
367aa1039e7SEric Dumazet 	 * it's safe to remove the node and free it later.
3685f2f8920SEric Dumazet 	 * We use refcnt=-1 to alert lockless readers this entry is deleted.
369aa1039e7SEric Dumazet 	 */
3705f2f8920SEric Dumazet 	if (atomic_cmpxchg(&p->refcnt, 1, -1) == 1) {
371b914c4eaSEric Dumazet 		struct inet_peer __rcu **stack[PEER_MAXDEPTH];
372b914c4eaSEric Dumazet 		struct inet_peer __rcu ***stackptr, ***delp;
37302663045SDavid S. Miller 		if (lookup(&p->daddr, stack, base) != p)
3741da177e4SLinus Torvalds 			BUG();
3751da177e4SLinus Torvalds 		delp = stackptr - 1; /* *delp[0] == p */
376b914c4eaSEric Dumazet 		if (p->avl_left == peer_avl_empty_rcu) {
3771da177e4SLinus Torvalds 			*delp[0] = p->avl_right;
3781da177e4SLinus Torvalds 			--stackptr;
3791da177e4SLinus Torvalds 		} else {
3801da177e4SLinus Torvalds 			/* look for a node to insert instead of p */
3811da177e4SLinus Torvalds 			struct inet_peer *t;
38298158f5aSDavid S. Miller 			t = lookup_rightempty(p, base);
38365e8354eSEric Dumazet 			BUG_ON(rcu_deref_locked(*stackptr[-1], base) != t);
3841da177e4SLinus Torvalds 			**--stackptr = t->avl_left;
385582a72daSDavid S. Miller 			/* t is removed, t->daddr > x->daddr for any
3861da177e4SLinus Torvalds 			 * x in p->avl_left subtree.
3871da177e4SLinus Torvalds 			 * Put t in the old place of p. */
388b914c4eaSEric Dumazet 			RCU_INIT_POINTER(*delp[0], t);
3891da177e4SLinus Torvalds 			t->avl_left = p->avl_left;
3901da177e4SLinus Torvalds 			t->avl_right = p->avl_right;
3911da177e4SLinus Torvalds 			t->avl_height = p->avl_height;
39209a62660SKris Katterjohn 			BUG_ON(delp[1] != &p->avl_left);
3931da177e4SLinus Torvalds 			delp[1] = &t->avl_left; /* was &p->avl_left */
3941da177e4SLinus Torvalds 		}
39598158f5aSDavid S. Miller 		peer_avl_rebalance(stack, stackptr, base);
39698158f5aSDavid S. Miller 		base->total--;
3971da177e4SLinus Torvalds 		do_free = 1;
3981da177e4SLinus Torvalds 	}
39965e8354eSEric Dumazet 	write_sequnlock_bh(&base->lock);
4001da177e4SLinus Torvalds 
4011da177e4SLinus Torvalds 	if (do_free)
402*4e75db2eSEric Dumazet 		call_rcu(&p->rcu, inetpeer_free_rcu);
4031da177e4SLinus Torvalds 	else
4041da177e4SLinus Torvalds 		/* The node is used again.  Decrease the reference counter
4051da177e4SLinus Torvalds 		 * back.  The loop "cleanup -> unlink_from_unused
4061da177e4SLinus Torvalds 		 *   -> unlink_from_pool -> putpeer -> link_to_unused
4071da177e4SLinus Torvalds 		 *   -> cleanup (for the same node)"
4081da177e4SLinus Torvalds 		 * doesn't really exist because the entry will have a
409aa1039e7SEric Dumazet 		 * recent deletion time and will not be cleaned again soon.
410aa1039e7SEric Dumazet 		 */
4111da177e4SLinus Torvalds 		inet_putpeer(p);
4121da177e4SLinus Torvalds }
4131da177e4SLinus Torvalds 
414021e9299SDavid S. Miller static struct inet_peer_base *family_to_base(int family)
415021e9299SDavid S. Miller {
416021e9299SDavid S. Miller 	return (family == AF_INET ? &v4_peers : &v6_peers);
417021e9299SDavid S. Miller }
418021e9299SDavid S. Miller 
41998158f5aSDavid S. Miller static struct inet_peer_base *peer_to_base(struct inet_peer *p)
42098158f5aSDavid S. Miller {
421021e9299SDavid S. Miller 	return family_to_base(p->daddr.family);
42298158f5aSDavid S. Miller }
42398158f5aSDavid S. Miller 
4241da177e4SLinus Torvalds /* May be called with local BH enabled. */
4251da177e4SLinus Torvalds static int cleanup_once(unsigned long ttl)
4261da177e4SLinus Torvalds {
427d71209deSPavel Emelyanov 	struct inet_peer *p = NULL;
4281da177e4SLinus Torvalds 
4291da177e4SLinus Torvalds 	/* Remove the first entry from the list of unused nodes. */
430d6cc1d64SEric Dumazet 	spin_lock_bh(&unused_peers.lock);
431d6cc1d64SEric Dumazet 	if (!list_empty(&unused_peers.list)) {
432d71209deSPavel Emelyanov 		__u32 delta;
433d71209deSPavel Emelyanov 
434d6cc1d64SEric Dumazet 		p = list_first_entry(&unused_peers.list, struct inet_peer, unused);
435d71209deSPavel Emelyanov 		delta = (__u32)jiffies - p->dtime;
436d71209deSPavel Emelyanov 
4374663afe2SEric Dumazet 		if (delta < ttl) {
4381da177e4SLinus Torvalds 			/* Do not prune fresh entries. */
439d6cc1d64SEric Dumazet 			spin_unlock_bh(&unused_peers.lock);
4401da177e4SLinus Torvalds 			return -1;
4411da177e4SLinus Torvalds 		}
442d71209deSPavel Emelyanov 
443d71209deSPavel Emelyanov 		list_del_init(&p->unused);
444d71209deSPavel Emelyanov 
4451da177e4SLinus Torvalds 		/* Grab an extra reference to prevent node disappearing
4461da177e4SLinus Torvalds 		 * before unlink_from_pool() call. */
4471da177e4SLinus Torvalds 		atomic_inc(&p->refcnt);
4481da177e4SLinus Torvalds 	}
449d6cc1d64SEric Dumazet 	spin_unlock_bh(&unused_peers.lock);
4501da177e4SLinus Torvalds 
4511da177e4SLinus Torvalds 	if (p == NULL)
4521da177e4SLinus Torvalds 		/* It means that the total number of USED entries has
4531da177e4SLinus Torvalds 		 * grown over inet_peer_threshold.  It shouldn't really
4541da177e4SLinus Torvalds 		 * happen because of entry limits in route cache. */
4551da177e4SLinus Torvalds 		return -1;
4561da177e4SLinus Torvalds 
45798158f5aSDavid S. Miller 	unlink_from_pool(p, peer_to_base(p));
4581da177e4SLinus Torvalds 	return 0;
4591da177e4SLinus Torvalds }
4601da177e4SLinus Torvalds 
4611da177e4SLinus Torvalds /* Called with or without local BH being disabled. */
4628790ca17SDavid S. Miller struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create)
4631da177e4SLinus Torvalds {
464b914c4eaSEric Dumazet 	struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
4653408404aSDavid S. Miller 	struct inet_peer_base *base = family_to_base(daddr->family);
46698158f5aSDavid S. Miller 	struct inet_peer *p;
46765e8354eSEric Dumazet 	unsigned int sequence;
46865e8354eSEric Dumazet 	int invalidated;
4691da177e4SLinus Torvalds 
470aa1039e7SEric Dumazet 	/* Look up for the address quickly, lockless.
471aa1039e7SEric Dumazet 	 * Because of a concurrent writer, we might not find an existing entry.
472aa1039e7SEric Dumazet 	 */
4737b46ac4eSDavid S. Miller 	rcu_read_lock();
47465e8354eSEric Dumazet 	sequence = read_seqbegin(&base->lock);
4757b46ac4eSDavid S. Miller 	p = lookup_rcu(daddr, base);
47665e8354eSEric Dumazet 	invalidated = read_seqretry(&base->lock, sequence);
4777b46ac4eSDavid S. Miller 	rcu_read_unlock();
4781da177e4SLinus Torvalds 
479aa1039e7SEric Dumazet 	if (p) {
480aa1039e7SEric Dumazet 		/* The existing node has been found.
481aa1039e7SEric Dumazet 		 * Remove the entry from unused list if it was there.
482aa1039e7SEric Dumazet 		 */
4831da177e4SLinus Torvalds 		unlink_from_unused(p);
4841da177e4SLinus Torvalds 		return p;
4851da177e4SLinus Torvalds 	}
4861da177e4SLinus Torvalds 
48765e8354eSEric Dumazet 	/* If no writer did a change during our lookup, we can return early. */
48865e8354eSEric Dumazet 	if (!create && !invalidated)
48965e8354eSEric Dumazet 		return NULL;
49065e8354eSEric Dumazet 
491aa1039e7SEric Dumazet 	/* retry an exact lookup, taking the lock before.
492aa1039e7SEric Dumazet 	 * At least, nodes should be hot in our cache.
493aa1039e7SEric Dumazet 	 */
49465e8354eSEric Dumazet 	write_seqlock_bh(&base->lock);
49502663045SDavid S. Miller 	p = lookup(daddr, stack, base);
496aa1039e7SEric Dumazet 	if (p != peer_avl_empty) {
497aa1039e7SEric Dumazet 		atomic_inc(&p->refcnt);
49865e8354eSEric Dumazet 		write_sequnlock_bh(&base->lock);
499aa1039e7SEric Dumazet 		/* Remove the entry from unused list if it was there. */
500aa1039e7SEric Dumazet 		unlink_from_unused(p);
501aa1039e7SEric Dumazet 		return p;
502aa1039e7SEric Dumazet 	}
503aa1039e7SEric Dumazet 	p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
504aa1039e7SEric Dumazet 	if (p) {
505b534ecf1SDavid S. Miller 		p->daddr = *daddr;
506aa1039e7SEric Dumazet 		atomic_set(&p->refcnt, 1);
507aa1039e7SEric Dumazet 		atomic_set(&p->rid, 0);
5087a71ed89SDavid S. Miller 		atomic_set(&p->ip_id_count, secure_ip_id(daddr->addr.a4));
509aa1039e7SEric Dumazet 		p->tcp_ts_stamp = 0;
510144001bdSDavid S. Miller 		p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
51192d86829SDavid S. Miller 		p->rate_tokens = 0;
51292d86829SDavid S. Miller 		p->rate_last = 0;
513ddd4aa42SDavid S. Miller 		p->pmtu_expires = 0;
51446af3180SHiroaki SHIMODA 		p->pmtu_orig = 0;
515ddd4aa42SDavid S. Miller 		memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
516aa1039e7SEric Dumazet 		INIT_LIST_HEAD(&p->unused);
517aa1039e7SEric Dumazet 
5181da177e4SLinus Torvalds 
5191da177e4SLinus Torvalds 		/* Link the node. */
52098158f5aSDavid S. Miller 		link_to_pool(p, base);
52198158f5aSDavid S. Miller 		base->total++;
522aa1039e7SEric Dumazet 	}
52365e8354eSEric Dumazet 	write_sequnlock_bh(&base->lock);
5241da177e4SLinus Torvalds 
52598158f5aSDavid S. Miller 	if (base->total >= inet_peer_threshold)
5261da177e4SLinus Torvalds 		/* Remove one less-recently-used entry. */
5271da177e4SLinus Torvalds 		cleanup_once(0);
5281da177e4SLinus Torvalds 
5291da177e4SLinus Torvalds 	return p;
5301da177e4SLinus Torvalds }
5311da177e4SLinus Torvalds 
53298158f5aSDavid S. Miller static int compute_total(void)
53398158f5aSDavid S. Miller {
534021e9299SDavid S. Miller 	return v4_peers.total + v6_peers.total;
53598158f5aSDavid S. Miller }
536b3419363SDavid S. Miller EXPORT_SYMBOL_GPL(inet_getpeer);
53798158f5aSDavid S. Miller 
5381da177e4SLinus Torvalds /* Called with local BH disabled. */
5391da177e4SLinus Torvalds static void peer_check_expire(unsigned long dummy)
5401da177e4SLinus Torvalds {
5414663afe2SEric Dumazet 	unsigned long now = jiffies;
54298158f5aSDavid S. Miller 	int ttl, total;
5431da177e4SLinus Torvalds 
54498158f5aSDavid S. Miller 	total = compute_total();
54598158f5aSDavid S. Miller 	if (total >= inet_peer_threshold)
5461da177e4SLinus Torvalds 		ttl = inet_peer_minttl;
5471da177e4SLinus Torvalds 	else
5481da177e4SLinus Torvalds 		ttl = inet_peer_maxttl
5491da177e4SLinus Torvalds 				- (inet_peer_maxttl - inet_peer_minttl) / HZ *
55098158f5aSDavid S. Miller 					total / inet_peer_threshold * HZ;
5514663afe2SEric Dumazet 	while (!cleanup_once(ttl)) {
5524663afe2SEric Dumazet 		if (jiffies != now)
5534663afe2SEric Dumazet 			break;
5544663afe2SEric Dumazet 	}
5551da177e4SLinus Torvalds 
5561da177e4SLinus Torvalds 	/* Trigger the timer after inet_peer_gc_mintime .. inet_peer_gc_maxtime
5571da177e4SLinus Torvalds 	 * interval depending on the total number of entries (more entries,
5581da177e4SLinus Torvalds 	 * less interval). */
55998158f5aSDavid S. Miller 	total = compute_total();
56098158f5aSDavid S. Miller 	if (total >= inet_peer_threshold)
5611344a416SDave Johnson 		peer_periodic_timer.expires = jiffies + inet_peer_gc_mintime;
5621344a416SDave Johnson 	else
5631da177e4SLinus Torvalds 		peer_periodic_timer.expires = jiffies
5641da177e4SLinus Torvalds 			+ inet_peer_gc_maxtime
5651da177e4SLinus Torvalds 			- (inet_peer_gc_maxtime - inet_peer_gc_mintime) / HZ *
56698158f5aSDavid S. Miller 				total / inet_peer_threshold * HZ;
5671da177e4SLinus Torvalds 	add_timer(&peer_periodic_timer);
5681da177e4SLinus Torvalds }
5694663afe2SEric Dumazet 
5704663afe2SEric Dumazet void inet_putpeer(struct inet_peer *p)
5714663afe2SEric Dumazet {
572d6cc1d64SEric Dumazet 	local_bh_disable();
573d6cc1d64SEric Dumazet 
574d6cc1d64SEric Dumazet 	if (atomic_dec_and_lock(&p->refcnt, &unused_peers.lock)) {
575d6cc1d64SEric Dumazet 		list_add_tail(&p->unused, &unused_peers.list);
5764663afe2SEric Dumazet 		p->dtime = (__u32)jiffies;
577d6cc1d64SEric Dumazet 		spin_unlock(&unused_peers.lock);
5784663afe2SEric Dumazet 	}
579d6cc1d64SEric Dumazet 
580d6cc1d64SEric Dumazet 	local_bh_enable();
5814663afe2SEric Dumazet }
582b3419363SDavid S. Miller EXPORT_SYMBOL_GPL(inet_putpeer);
58392d86829SDavid S. Miller 
58492d86829SDavid S. Miller /*
58592d86829SDavid S. Miller  *	Check transmit rate limitation for given message.
58692d86829SDavid S. Miller  *	The rate information is held in the inet_peer entries now.
58792d86829SDavid S. Miller  *	This function is generic and could be used for other purposes
58892d86829SDavid S. Miller  *	too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
58992d86829SDavid S. Miller  *
59092d86829SDavid S. Miller  *	Note that the same inet_peer fields are modified by functions in
59192d86829SDavid S. Miller  *	route.c too, but these work for packet destinations while xrlim_allow
59292d86829SDavid S. Miller  *	works for icmp destinations. This means the rate limiting information
59392d86829SDavid S. Miller  *	for one "ip object" is shared - and these ICMPs are twice limited:
59492d86829SDavid S. Miller  *	by source and by destination.
59592d86829SDavid S. Miller  *
59692d86829SDavid S. Miller  *	RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
59792d86829SDavid S. Miller  *			  SHOULD allow setting of rate limits
59892d86829SDavid S. Miller  *
59992d86829SDavid S. Miller  * 	Shared between ICMPv4 and ICMPv6.
60092d86829SDavid S. Miller  */
60192d86829SDavid S. Miller #define XRLIM_BURST_FACTOR 6
60292d86829SDavid S. Miller bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout)
60392d86829SDavid S. Miller {
60492d86829SDavid S. Miller 	unsigned long now, token;
60592d86829SDavid S. Miller 	bool rc = false;
60692d86829SDavid S. Miller 
60792d86829SDavid S. Miller 	if (!peer)
60892d86829SDavid S. Miller 		return true;
60992d86829SDavid S. Miller 
61092d86829SDavid S. Miller 	token = peer->rate_tokens;
61192d86829SDavid S. Miller 	now = jiffies;
61292d86829SDavid S. Miller 	token += now - peer->rate_last;
61392d86829SDavid S. Miller 	peer->rate_last = now;
61492d86829SDavid S. Miller 	if (token > XRLIM_BURST_FACTOR * timeout)
61592d86829SDavid S. Miller 		token = XRLIM_BURST_FACTOR * timeout;
61692d86829SDavid S. Miller 	if (token >= timeout) {
61792d86829SDavid S. Miller 		token -= timeout;
61892d86829SDavid S. Miller 		rc = true;
61992d86829SDavid S. Miller 	}
62092d86829SDavid S. Miller 	peer->rate_tokens = token;
62192d86829SDavid S. Miller 	return rc;
62292d86829SDavid S. Miller }
62392d86829SDavid S. Miller EXPORT_SYMBOL(inet_peer_xrlim_allow);
624