inetpeer.c 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. * Authors: Andrey V. Savochkin <[email protected]>
  7. */
  8. #include <linux/cache.h>
  9. #include <linux/module.h>
  10. #include <linux/types.h>
  11. #include <linux/slab.h>
  12. #include <linux/interrupt.h>
  13. #include <linux/spinlock.h>
  14. #include <linux/random.h>
  15. #include <linux/timer.h>
  16. #include <linux/time.h>
  17. #include <linux/kernel.h>
  18. #include <linux/mm.h>
  19. #include <linux/net.h>
  20. #include <linux/workqueue.h>
  21. #include <net/ip.h>
  22. #include <net/inetpeer.h>
  23. #include <net/secure_seq.h>
  24. /*
  25. * Theory of operations.
  26. * We keep one entry for each peer IP address. The nodes contains long-living
  27. * information about the peer which doesn't depend on routes.
  28. *
  29. * Nodes are removed only when reference counter goes to 0.
  30. * When it's happened the node may be removed when a sufficient amount of
  31. * time has been passed since its last use. The less-recently-used entry can
  32. * also be removed if the pool is overloaded i.e. if the total amount of
  33. * entries is greater-or-equal than the threshold.
  34. *
  35. * Node pool is organised as an RB tree.
  36. * Such an implementation has been chosen not just for fun. It's a way to
  37. * prevent easy and efficient DoS attacks by creating hash collisions. A huge
  38. * amount of long living nodes in a single hash slot would significantly delay
  39. * lookups performed with disabled BHs.
  40. *
  41. * Serialisation issues.
  42. * 1. Nodes may appear in the tree only with the pool lock held.
  43. * 2. Nodes may disappear from the tree only with the pool lock held
  44. * AND reference count being 0.
  45. * 3. Global variable peer_total is modified under the pool lock.
  46. * 4. struct inet_peer fields modification:
  47. * rb_node: pool lock
  48. * refcnt: atomically against modifications on other CPU;
  49. * usually under some other lock to prevent node disappearing
  50. * daddr: unchangeable
  51. */
  52. static struct kmem_cache *peer_cachep __ro_after_init;
  53. void inet_peer_base_init(struct inet_peer_base *bp)
  54. {
  55. bp->rb_root = RB_ROOT;
  56. seqlock_init(&bp->lock);
  57. bp->total = 0;
  58. }
  59. EXPORT_SYMBOL_GPL(inet_peer_base_init);
  60. #define PEER_MAX_GC 32
  61. /* Exported for sysctl_net_ipv4. */
  62. int inet_peer_threshold __read_mostly; /* start to throw entries more
  63. * aggressively at this stage */
  64. int inet_peer_minttl __read_mostly = 120 * HZ; /* TTL under high load: 120 sec */
  65. int inet_peer_maxttl __read_mostly = 10 * 60 * HZ; /* usual time to live: 10 min */
  66. /* Called from ip_output.c:ip_init */
  67. void __init inet_initpeers(void)
  68. {
  69. u64 nr_entries;
  70. /* 1% of physical memory */
  71. nr_entries = div64_ul((u64)totalram_pages() << PAGE_SHIFT,
  72. 100 * L1_CACHE_ALIGN(sizeof(struct inet_peer)));
  73. inet_peer_threshold = clamp_val(nr_entries, 4096, 65536 + 128);
  74. peer_cachep = kmem_cache_create("inet_peer_cache",
  75. sizeof(struct inet_peer),
  76. 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC,
  77. NULL);
  78. }
  79. /* Called with rcu_read_lock() or base->lock held */
  80. static struct inet_peer *lookup(const struct inetpeer_addr *daddr,
  81. struct inet_peer_base *base,
  82. unsigned int seq,
  83. struct inet_peer *gc_stack[],
  84. unsigned int *gc_cnt,
  85. struct rb_node **parent_p,
  86. struct rb_node ***pp_p)
  87. {
  88. struct rb_node **pp, *parent, *next;
  89. struct inet_peer *p;
  90. pp = &base->rb_root.rb_node;
  91. parent = NULL;
  92. while (1) {
  93. int cmp;
  94. next = rcu_dereference_raw(*pp);
  95. if (!next)
  96. break;
  97. parent = next;
  98. p = rb_entry(parent, struct inet_peer, rb_node);
  99. cmp = inetpeer_addr_cmp(daddr, &p->daddr);
  100. if (cmp == 0) {
  101. if (!refcount_inc_not_zero(&p->refcnt))
  102. break;
  103. return p;
  104. }
  105. if (gc_stack) {
  106. if (*gc_cnt < PEER_MAX_GC)
  107. gc_stack[(*gc_cnt)++] = p;
  108. } else if (unlikely(read_seqretry(&base->lock, seq))) {
  109. break;
  110. }
  111. if (cmp == -1)
  112. pp = &next->rb_left;
  113. else
  114. pp = &next->rb_right;
  115. }
  116. *parent_p = parent;
  117. *pp_p = pp;
  118. return NULL;
  119. }
  120. static void inetpeer_free_rcu(struct rcu_head *head)
  121. {
  122. kmem_cache_free(peer_cachep, container_of(head, struct inet_peer, rcu));
  123. }
  124. /* perform garbage collect on all items stacked during a lookup */
  125. static void inet_peer_gc(struct inet_peer_base *base,
  126. struct inet_peer *gc_stack[],
  127. unsigned int gc_cnt)
  128. {
  129. int peer_threshold, peer_maxttl, peer_minttl;
  130. struct inet_peer *p;
  131. __u32 delta, ttl;
  132. int i;
  133. peer_threshold = READ_ONCE(inet_peer_threshold);
  134. peer_maxttl = READ_ONCE(inet_peer_maxttl);
  135. peer_minttl = READ_ONCE(inet_peer_minttl);
  136. if (base->total >= peer_threshold)
  137. ttl = 0; /* be aggressive */
  138. else
  139. ttl = peer_maxttl - (peer_maxttl - peer_minttl) / HZ *
  140. base->total / peer_threshold * HZ;
  141. for (i = 0; i < gc_cnt; i++) {
  142. p = gc_stack[i];
  143. /* The READ_ONCE() pairs with the WRITE_ONCE()
  144. * in inet_putpeer()
  145. */
  146. delta = (__u32)jiffies - READ_ONCE(p->dtime);
  147. if (delta < ttl || !refcount_dec_if_one(&p->refcnt))
  148. gc_stack[i] = NULL;
  149. }
  150. for (i = 0; i < gc_cnt; i++) {
  151. p = gc_stack[i];
  152. if (p) {
  153. rb_erase(&p->rb_node, &base->rb_root);
  154. base->total--;
  155. call_rcu(&p->rcu, inetpeer_free_rcu);
  156. }
  157. }
  158. }
  159. struct inet_peer *inet_getpeer(struct inet_peer_base *base,
  160. const struct inetpeer_addr *daddr,
  161. int create)
  162. {
  163. struct inet_peer *p, *gc_stack[PEER_MAX_GC];
  164. struct rb_node **pp, *parent;
  165. unsigned int gc_cnt, seq;
  166. int invalidated;
  167. /* Attempt a lockless lookup first.
  168. * Because of a concurrent writer, we might not find an existing entry.
  169. */
  170. rcu_read_lock();
  171. seq = read_seqbegin(&base->lock);
  172. p = lookup(daddr, base, seq, NULL, &gc_cnt, &parent, &pp);
  173. invalidated = read_seqretry(&base->lock, seq);
  174. rcu_read_unlock();
  175. if (p)
  176. return p;
  177. /* If no writer did a change during our lookup, we can return early. */
  178. if (!create && !invalidated)
  179. return NULL;
  180. /* retry an exact lookup, taking the lock before.
  181. * At least, nodes should be hot in our cache.
  182. */
  183. parent = NULL;
  184. write_seqlock_bh(&base->lock);
  185. gc_cnt = 0;
  186. p = lookup(daddr, base, seq, gc_stack, &gc_cnt, &parent, &pp);
  187. if (!p && create) {
  188. p = kmem_cache_alloc(peer_cachep, GFP_ATOMIC);
  189. if (p) {
  190. p->daddr = *daddr;
  191. p->dtime = (__u32)jiffies;
  192. refcount_set(&p->refcnt, 2);
  193. atomic_set(&p->rid, 0);
  194. p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
  195. p->rate_tokens = 0;
  196. p->n_redirects = 0;
  197. /* 60*HZ is arbitrary, but chosen enough high so that the first
  198. * calculation of tokens is at its maximum.
  199. */
  200. p->rate_last = jiffies - 60*HZ;
  201. rb_link_node(&p->rb_node, parent, pp);
  202. rb_insert_color(&p->rb_node, &base->rb_root);
  203. base->total++;
  204. }
  205. }
  206. if (gc_cnt)
  207. inet_peer_gc(base, gc_stack, gc_cnt);
  208. write_sequnlock_bh(&base->lock);
  209. return p;
  210. }
  211. EXPORT_SYMBOL_GPL(inet_getpeer);
  212. void inet_putpeer(struct inet_peer *p)
  213. {
  214. /* The WRITE_ONCE() pairs with itself (we run lockless)
  215. * and the READ_ONCE() in inet_peer_gc()
  216. */
  217. WRITE_ONCE(p->dtime, (__u32)jiffies);
  218. if (refcount_dec_and_test(&p->refcnt))
  219. call_rcu(&p->rcu, inetpeer_free_rcu);
  220. }
  221. EXPORT_SYMBOL_GPL(inet_putpeer);
  222. /*
  223. * Check transmit rate limitation for given message.
  224. * The rate information is held in the inet_peer entries now.
  225. * This function is generic and could be used for other purposes
  226. * too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
  227. *
  228. * Note that the same inet_peer fields are modified by functions in
  229. * route.c too, but these work for packet destinations while xrlim_allow
  230. * works for icmp destinations. This means the rate limiting information
  231. * for one "ip object" is shared - and these ICMPs are twice limited:
  232. * by source and by destination.
  233. *
  234. * RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
  235. * SHOULD allow setting of rate limits
  236. *
  237. * Shared between ICMPv4 and ICMPv6.
  238. */
  239. #define XRLIM_BURST_FACTOR 6
  240. bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout)
  241. {
  242. unsigned long now, token;
  243. bool rc = false;
  244. if (!peer)
  245. return true;
  246. token = peer->rate_tokens;
  247. now = jiffies;
  248. token += now - peer->rate_last;
  249. peer->rate_last = now;
  250. if (token > XRLIM_BURST_FACTOR * timeout)
  251. token = XRLIM_BURST_FACTOR * timeout;
  252. if (token >= timeout) {
  253. token -= timeout;
  254. rc = true;
  255. }
  256. peer->rate_tokens = token;
  257. return rc;
  258. }
  259. EXPORT_SYMBOL(inet_peer_xrlim_allow);
  260. void inetpeer_invalidate_tree(struct inet_peer_base *base)
  261. {
  262. struct rb_node *p = rb_first(&base->rb_root);
  263. while (p) {
  264. struct inet_peer *peer = rb_entry(p, struct inet_peer, rb_node);
  265. p = rb_next(p);
  266. rb_erase(&peer->rb_node, &base->rb_root);
  267. inet_putpeer(peer);
  268. cond_resched();
  269. }
  270. base->total = 0;
  271. }
  272. EXPORT_SYMBOL(inetpeer_invalidate_tree);