inetpeer.c 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 <saw@msu.ru>
  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_IPV6_MOD_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(inet_peer, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
  75. }
  76. /* Called with rcu_read_lock() or base->lock held */
  77. static struct inet_peer *lookup(const struct inetpeer_addr *daddr,
  78. struct inet_peer_base *base,
  79. unsigned int seq,
  80. struct inet_peer *gc_stack[],
  81. unsigned int *gc_cnt,
  82. struct rb_node **parent_p,
  83. struct rb_node ***pp_p)
  84. {
  85. struct rb_node **pp, *parent, *next;
  86. struct inet_peer *p;
  87. u32 now;
  88. pp = &base->rb_root.rb_node;
  89. parent = NULL;
  90. while (1) {
  91. int cmp;
  92. next = rcu_dereference_raw(*pp);
  93. if (!next)
  94. break;
  95. parent = next;
  96. p = rb_entry(parent, struct inet_peer, rb_node);
  97. cmp = inetpeer_addr_cmp(daddr, &p->daddr);
  98. if (cmp == 0) {
  99. now = jiffies;
  100. if (READ_ONCE(p->dtime) != now)
  101. WRITE_ONCE(p->dtime, now);
  102. return p;
  103. }
  104. if (gc_stack) {
  105. if (*gc_cnt < PEER_MAX_GC)
  106. gc_stack[(*gc_cnt)++] = p;
  107. } else if (unlikely(read_seqretry(&base->lock, seq))) {
  108. break;
  109. }
  110. if (cmp == -1)
  111. pp = &next->rb_left;
  112. else
  113. pp = &next->rb_right;
  114. }
  115. *parent_p = parent;
  116. *pp_p = pp;
  117. return NULL;
  118. }
  119. /* perform garbage collect on all items stacked during a lookup */
  120. static void inet_peer_gc(struct inet_peer_base *base,
  121. struct inet_peer *gc_stack[],
  122. unsigned int gc_cnt)
  123. {
  124. int peer_threshold, peer_maxttl, peer_minttl;
  125. struct inet_peer *p;
  126. __u32 delta, ttl;
  127. int i;
  128. peer_threshold = READ_ONCE(inet_peer_threshold);
  129. peer_maxttl = READ_ONCE(inet_peer_maxttl);
  130. peer_minttl = READ_ONCE(inet_peer_minttl);
  131. if (base->total >= peer_threshold)
  132. ttl = 0; /* be aggressive */
  133. else
  134. ttl = peer_maxttl - (peer_maxttl - peer_minttl) / HZ *
  135. base->total / peer_threshold * HZ;
  136. for (i = 0; i < gc_cnt; i++) {
  137. p = gc_stack[i];
  138. delta = (__u32)jiffies - READ_ONCE(p->dtime);
  139. if (delta < ttl || !refcount_dec_if_one(&p->refcnt))
  140. gc_stack[i] = NULL;
  141. }
  142. for (i = 0; i < gc_cnt; i++) {
  143. p = gc_stack[i];
  144. if (p) {
  145. rb_erase(&p->rb_node, &base->rb_root);
  146. base->total--;
  147. kfree_rcu(p, rcu);
  148. }
  149. }
  150. }
  151. /* Must be called under RCU : No refcount change is done here. */
  152. struct inet_peer *inet_getpeer(struct inet_peer_base *base,
  153. const struct inetpeer_addr *daddr)
  154. {
  155. struct inet_peer *p, *gc_stack[PEER_MAX_GC];
  156. struct rb_node **pp, *parent;
  157. unsigned int gc_cnt, seq;
  158. /* Attempt a lockless lookup first.
  159. * Because of a concurrent writer, we might not find an existing entry.
  160. */
  161. seq = read_seqbegin(&base->lock);
  162. p = lookup(daddr, base, seq, NULL, &gc_cnt, &parent, &pp);
  163. if (p)
  164. return p;
  165. /* retry an exact lookup, taking the lock before.
  166. * At least, nodes should be hot in our cache.
  167. */
  168. parent = NULL;
  169. write_seqlock_bh(&base->lock);
  170. gc_cnt = 0;
  171. p = lookup(daddr, base, seq, gc_stack, &gc_cnt, &parent, &pp);
  172. if (!p) {
  173. p = kmem_cache_alloc(peer_cachep, GFP_ATOMIC);
  174. if (p) {
  175. p->daddr = *daddr;
  176. p->dtime = (__u32)jiffies;
  177. refcount_set(&p->refcnt, 1);
  178. atomic_set(&p->rid, 0);
  179. p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
  180. p->rate_tokens = 0;
  181. p->n_redirects = 0;
  182. /* 60*HZ is arbitrary, but chosen enough high so that the first
  183. * calculation of tokens is at its maximum.
  184. */
  185. p->rate_last = jiffies - 60*HZ;
  186. rb_link_node(&p->rb_node, parent, pp);
  187. rb_insert_color(&p->rb_node, &base->rb_root);
  188. base->total++;
  189. }
  190. }
  191. if (gc_cnt)
  192. inet_peer_gc(base, gc_stack, gc_cnt);
  193. write_sequnlock_bh(&base->lock);
  194. return p;
  195. }
  196. EXPORT_IPV6_MOD_GPL(inet_getpeer);
  197. void inet_putpeer(struct inet_peer *p)
  198. {
  199. if (refcount_dec_and_test(&p->refcnt))
  200. kfree_rcu(p, rcu);
  201. }
  202. /*
  203. * Check transmit rate limitation for given message.
  204. * The rate information is held in the inet_peer entries now.
  205. * This function is generic and could be used for other purposes
  206. * too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
  207. *
  208. * Note that the same inet_peer fields are modified by functions in
  209. * route.c too, but these work for packet destinations while xrlim_allow
  210. * works for icmp destinations. This means the rate limiting information
  211. * for one "ip object" is shared - and these ICMPs are twice limited:
  212. * by source and by destination.
  213. *
  214. * RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
  215. * SHOULD allow setting of rate limits
  216. *
  217. * Shared between ICMPv4 and ICMPv6.
  218. */
  219. #define XRLIM_BURST_FACTOR 6
  220. bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout)
  221. {
  222. unsigned long now, token, otoken, delta;
  223. bool rc = false;
  224. if (!peer)
  225. return true;
  226. token = otoken = READ_ONCE(peer->rate_tokens);
  227. now = jiffies;
  228. delta = now - READ_ONCE(peer->rate_last);
  229. if (delta) {
  230. WRITE_ONCE(peer->rate_last, now);
  231. token += delta;
  232. if (token > XRLIM_BURST_FACTOR * timeout)
  233. token = XRLIM_BURST_FACTOR * timeout;
  234. }
  235. if (token >= timeout) {
  236. token -= timeout;
  237. rc = true;
  238. }
  239. if (token != otoken)
  240. WRITE_ONCE(peer->rate_tokens, token);
  241. return rc;
  242. }
  243. EXPORT_IPV6_MOD(inet_peer_xrlim_allow);
  244. void inetpeer_invalidate_tree(struct inet_peer_base *base)
  245. {
  246. struct rb_node *p = rb_first(&base->rb_root);
  247. while (p) {
  248. struct inet_peer *peer = rb_entry(p, struct inet_peer, rb_node);
  249. p = rb_next(p);
  250. rb_erase(&peer->rb_node, &base->rb_root);
  251. inet_putpeer(peer);
  252. cond_resched();
  253. }
  254. base->total = 0;
  255. }
  256. EXPORT_IPV6_MOD(inetpeer_invalidate_tree);