token_bucket.c 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /* Copyright (c) 2018-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file token_bucket.c
  5. * \brief Functions to use and manipulate token buckets, used for
  6. * rate-limiting on connections and globally.
  7. *
  8. * Tor uses these token buckets to keep track of bandwidth usage, and
  9. * sometimes other things too.
  10. *
  11. * There are two layers of abstraction here: "raw" token buckets, in which all
  12. * the pieces are decoupled, and "read-write" token buckets, which combine all
  13. * the moving parts into one.
  14. *
  15. * Token buckets may become negative.
  16. **/
  17. #define TOKEN_BUCKET_PRIVATE
  18. #include "token_bucket.h"
  19. #include "util_bug.h"
  20. /**
  21. * Set the <b>rate</b> and <b>burst</b> value in a token_bucket_cfg.
  22. *
  23. * Note that the <b>rate</b> value is in arbitrary units, but those units will
  24. * determine the units of token_bucket_raw_dec(), token_bucket_raw_refill, and
  25. * so on.
  26. */
  27. void
  28. token_bucket_cfg_init(token_bucket_cfg_t *cfg,
  29. uint32_t rate,
  30. uint32_t burst)
  31. {
  32. tor_assert_nonfatal(rate > 0);
  33. tor_assert_nonfatal(burst > 0);
  34. if (burst > TOKEN_BUCKET_MAX_BURST)
  35. burst = TOKEN_BUCKET_MAX_BURST;
  36. cfg->rate = rate;
  37. cfg->burst = burst;
  38. }
  39. /**
  40. * Initialize a raw token bucket and its associated timestamp to the "full"
  41. * state, according to <b>cfg</b>.
  42. */
  43. void
  44. token_bucket_raw_reset(token_bucket_raw_t *bucket,
  45. const token_bucket_cfg_t *cfg)
  46. {
  47. bucket->bucket = cfg->burst;
  48. }
  49. /**
  50. * Adust a preexisting token bucket to respect the new configuration
  51. * <b>cfg</b>, by decreasing its current level if needed. */
  52. void
  53. token_bucket_raw_adjust(token_bucket_raw_t *bucket,
  54. const token_bucket_cfg_t *cfg)
  55. {
  56. bucket->bucket = MIN(bucket->bucket, cfg->burst);
  57. }
  58. /**
  59. * Given an amount of <b>elapsed</b> time units, and a bucket configuration
  60. * <b>cfg</b>, refill the level of <b>bucket</b> accordingly. Note that the
  61. * units of time in <b>elapsed</b> must correspond to those used to set the
  62. * rate in <b>cfg</b>, or the result will be illogical.
  63. */
  64. int
  65. token_bucket_raw_refill_steps(token_bucket_raw_t *bucket,
  66. const token_bucket_cfg_t *cfg,
  67. const uint32_t elapsed)
  68. {
  69. const int was_empty = (bucket->bucket <= 0);
  70. /* The casts here prevent an underflow.
  71. *
  72. * Note that even if the bucket value is negative, subtracting it from
  73. * "burst" will still produce a correct result. If this result is
  74. * ridiculously high, then the "elapsed > gap / rate" check below
  75. * should catch it. */
  76. const size_t gap = ((size_t)cfg->burst) - ((size_t)bucket->bucket);
  77. if (elapsed > gap / cfg->rate) {
  78. bucket->bucket = cfg->burst;
  79. } else {
  80. bucket->bucket += cfg->rate * elapsed;
  81. }
  82. return was_empty && bucket->bucket > 0;
  83. }
  84. /**
  85. * Decrement a provided bucket by <b>n</b> units. Note that <b>n</b>
  86. * must be nonnegative.
  87. */
  88. int
  89. token_bucket_raw_dec(token_bucket_raw_t *bucket,
  90. ssize_t n)
  91. {
  92. if (BUG(n < 0))
  93. return 0;
  94. const int becomes_empty = bucket->bucket > 0 && n >= bucket->bucket;
  95. bucket->bucket -= n;
  96. return becomes_empty;
  97. }
  98. /** Convert a rate in bytes per second to a rate in bytes per step */
  99. STATIC uint32_t
  100. rate_per_sec_to_rate_per_step(uint32_t rate)
  101. {
  102. /*
  103. The precise calculation we'd want to do is
  104. (rate / 1000) * to_approximate_msec(TICKS_PER_STEP). But to minimize
  105. rounding error, we do it this way instead, and divide last.
  106. */
  107. uint64_t units = (uint64_t) rate * TICKS_PER_STEP;
  108. uint32_t val = (uint32_t)
  109. (monotime_coarse_stamp_units_to_approx_msec(units) / 1000);
  110. return val ? val : 1;
  111. }
  112. /**
  113. * Initialize a token bucket in *<b>bucket</b>, set up to allow <b>rate</b>
  114. * bytes per second, with a maximum burst of <b>burst</b> bytes. The bucket
  115. * is created such that <b>now_ts</b> is the current timestamp. The bucket
  116. * starts out full.
  117. */
  118. void
  119. token_bucket_rw_init(token_bucket_rw_t *bucket,
  120. uint32_t rate,
  121. uint32_t burst,
  122. uint32_t now_ts)
  123. {
  124. memset(bucket, 0, sizeof(token_bucket_rw_t));
  125. token_bucket_rw_adjust(bucket, rate, burst);
  126. token_bucket_rw_reset(bucket, now_ts);
  127. }
  128. /**
  129. * Change the configured rate (in bytes per second) and burst (in bytes)
  130. * for the token bucket in *<b>bucket</b>.
  131. */
  132. void
  133. token_bucket_rw_adjust(token_bucket_rw_t *bucket,
  134. uint32_t rate,
  135. uint32_t burst)
  136. {
  137. token_bucket_cfg_init(&bucket->cfg,
  138. rate_per_sec_to_rate_per_step(rate),
  139. burst);
  140. token_bucket_raw_adjust(&bucket->read_bucket, &bucket->cfg);
  141. token_bucket_raw_adjust(&bucket->write_bucket, &bucket->cfg);
  142. }
  143. /**
  144. * Reset <b>bucket</b> to be full, as of timestamp <b>now_ts</b>.
  145. */
  146. void
  147. token_bucket_rw_reset(token_bucket_rw_t *bucket,
  148. uint32_t now_ts)
  149. {
  150. token_bucket_raw_reset(&bucket->read_bucket, &bucket->cfg);
  151. token_bucket_raw_reset(&bucket->write_bucket, &bucket->cfg);
  152. bucket->last_refilled_at_timestamp = now_ts;
  153. }
  154. /**
  155. * Refill <b>bucket</b> as appropriate, given that the current timestamp
  156. * is <b>now_ts</b>.
  157. *
  158. * Return a bitmask containing TB_READ iff read bucket was empty and became
  159. * nonempty, and TB_WRITE iff the write bucket was empty and became nonempty.
  160. */
  161. int
  162. token_bucket_rw_refill(token_bucket_rw_t *bucket,
  163. uint32_t now_ts)
  164. {
  165. const uint32_t elapsed_ticks =
  166. (now_ts - bucket->last_refilled_at_timestamp);
  167. if (elapsed_ticks > UINT32_MAX-(300*1000)) {
  168. /* Either about 48 days have passed since the last refill, or the
  169. * monotonic clock has somehow moved backwards. (We're looking at you,
  170. * Windows.). We accept up to a 5 minute jump backwards as
  171. * "unremarkable".
  172. */
  173. return 0;
  174. }
  175. const uint32_t elapsed_steps = elapsed_ticks / TICKS_PER_STEP;
  176. if (!elapsed_steps) {
  177. /* Note that if less than one whole step elapsed, we don't advance the
  178. * time in last_refilled_at. That's intentional: we want to make sure
  179. * that we add some bytes to it eventually. */
  180. return 0;
  181. }
  182. int flags = 0;
  183. if (token_bucket_raw_refill_steps(&bucket->read_bucket,
  184. &bucket->cfg, elapsed_steps))
  185. flags |= TB_READ;
  186. if (token_bucket_raw_refill_steps(&bucket->write_bucket,
  187. &bucket->cfg, elapsed_steps))
  188. flags |= TB_WRITE;
  189. bucket->last_refilled_at_timestamp = now_ts;
  190. return flags;
  191. }
  192. /**
  193. * Decrement the read token bucket in <b>bucket</b> by <b>n</b> bytes.
  194. *
  195. * Return true if the bucket was nonempty and became empty; return false
  196. * otherwise.
  197. */
  198. int
  199. token_bucket_rw_dec_read(token_bucket_rw_t *bucket,
  200. ssize_t n)
  201. {
  202. return token_bucket_raw_dec(&bucket->read_bucket, n);
  203. }
  204. /**
  205. * Decrement the write token bucket in <b>bucket</b> by <b>n</b> bytes.
  206. *
  207. * Return true if the bucket was nonempty and became empty; return false
  208. * otherwise.
  209. */
  210. int
  211. token_bucket_rw_dec_write(token_bucket_rw_t *bucket,
  212. ssize_t n)
  213. {
  214. return token_bucket_raw_dec(&bucket->write_bucket, n);
  215. }
  216. /**
  217. * As token_bucket_rw_dec_read and token_bucket_rw_dec_write, in a single
  218. * operation. Return a bitmask of TB_READ and TB_WRITE to indicate
  219. * which buckets became empty.
  220. */
  221. int
  222. token_bucket_rw_dec(token_bucket_rw_t *bucket,
  223. ssize_t n_read, ssize_t n_written)
  224. {
  225. int flags = 0;
  226. if (token_bucket_rw_dec_read(bucket, n_read))
  227. flags |= TB_READ;
  228. if (token_bucket_rw_dec_write(bucket, n_written))
  229. flags |= TB_WRITE;
  230. return flags;
  231. }