inetpeer.c 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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_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(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. static void inetpeer_free_rcu(struct rcu_head *head)
  120. {
  121. kmem_cache_free(peer_cachep, container_of(head, struct inet_peer, rcu));
  122. }
  123. /* perform garbage collect on all items stacked during a lookup */
  124. static void inet_peer_gc(struct inet_peer_base *base,
  125. struct inet_peer *gc_stack[],
  126. unsigned int gc_cnt)
  127. {
  128. int peer_threshold, peer_maxttl, peer_minttl;
  129. struct inet_peer *p;
  130. __u32 delta, ttl;
  131. int i;
  132. peer_threshold = READ_ONCE(inet_peer_threshold);
  133. peer_maxttl = READ_ONCE(inet_peer_maxttl);
  134. peer_minttl = READ_ONCE(inet_peer_minttl);
  135. if (base->total >= peer_threshold)
  136. ttl = 0; /* be aggressive */
  137. else
  138. ttl = peer_maxttl - (peer_maxttl - peer_minttl) / HZ *
  139. base->total / peer_threshold * HZ;
  140. for (i = 0; i < gc_cnt; i++) {
  141. p = gc_stack[i];
  142. delta = (__u32)jiffies - READ_ONCE(p->dtime);
  143. if (delta < ttl || !refcount_dec_if_one(&p->refcnt))
  144. gc_stack[i] = NULL;
  145. }
  146. for (i = 0; i < gc_cnt; i++) {
  147. p = gc_stack[i];
  148. if (p) {
  149. rb_erase(&p->rb_node, &base->rb_root);
  150. base->total--;
  151. call_rcu(&p->rcu, inetpeer_free_rcu);
  152. }
  153. }
  154. }
  155. /* Must be called under RCU : No refcount change is done here. */
  156. struct inet_peer *inet_getpeer(struct inet_peer_base *base,
  157. const struct inetpeer_addr *daddr)
  158. {
  159. struct inet_peer *p, *gc_stack[PEER_MAX_GC];
  160. struct rb_node **pp, *parent;
  161. unsigned int gc_cnt, seq;
  162. /* Attempt a lockless lookup first.
  163. * Because of a concurrent writer, we might not find an existing entry.
  164. */
  165. seq = read_seqbegin(&base->lock);
  166. p = lookup(daddr, base, seq, NULL, &gc_cnt, &parent, &pp);
  167. if (p)
  168. return p;
  169. /* retry an exact lookup, taking the lock before.
  170. * At least, nodes should be hot in our cache.
  171. */
  172. parent = NULL;
  173. write_seqlock_bh(&base->lock);
  174. gc_cnt = 0;
  175. p = lookup(daddr, base, seq, gc_stack, &gc_cnt, &parent, &pp);
  176. if (!p) {
  177. p = kmem_cache_alloc(peer_cachep, GFP_ATOMIC);
  178. if (p) {
  179. p->daddr = *daddr;
  180. p->dtime = (__u32)jiffies;
  181. refcount_set(&p->refcnt, 1);
  182. atomic_set(&p->rid, 0);
  183. p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
  184. p->rate_tokens = 0;
  185. p->n_redirects = 0;
  186. /* 60*HZ is arbitrary, but chosen enough high so that the first
  187. * calculation of tokens is at its maximum.
  188. */
  189. p->rate_last = jiffies - 60*HZ;
  190. rb_link_node(&p->rb_node, parent, pp);
  191. rb_insert_color(&p->rb_node, &base->rb_root);
  192. base->total++;
  193. }
  194. }
  195. if (gc_cnt)
  196. inet_peer_gc(base, gc_stack, gc_cnt);
  197. write_sequnlock_bh(&base->lock);
  198. return p;
  199. }
  200. EXPORT_SYMBOL_GPL(inet_getpeer);
  201. void inet_putpeer(struct inet_peer *p)
  202. {
  203. if (refcount_dec_and_test(&p->refcnt))
  204. call_rcu(&p->rcu, inetpeer_free_rcu);
  205. }
  206. /*
  207. * Check transmit rate limitation for given message.
  208. * The rate information is held in the inet_peer entries now.
  209. * This function is generic and could be used for other purposes
  210. * too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
  211. *
  212. * Note that the same inet_peer fields are modified by functions in
  213. * route.c too, but these work for packet destinations while xrlim_allow
  214. * works for icmp destinations. This means the rate limiting information
  215. * for one "ip object" is shared - and these ICMPs are twice limited:
  216. * by source and by destination.
  217. *
  218. * RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
  219. * SHOULD allow setting of rate limits
  220. *
  221. * Shared between ICMPv4 and ICMPv6.
  222. */
  223. #define XRLIM_BURST_FACTOR 6
  224. bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout)
  225. {
  226. unsigned long now, token;
  227. bool rc = false;
  228. if (!peer)
  229. return true;
  230. token = peer->rate_tokens;
  231. now = jiffies;
  232. token += now - peer->rate_last;
  233. peer->rate_last = now;
  234. if (token > XRLIM_BURST_FACTOR * timeout)
  235. token = XRLIM_BURST_FACTOR * timeout;
  236. if (token >= timeout) {
  237. token -= timeout;
  238. rc = true;
  239. }
  240. peer->rate_tokens = token;
  241. return rc;
  242. }
  243. EXPORT_SYMBOL(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_SYMBOL(inetpeer_invalidate_tree);