bufferevent_ratelim.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. /*
  2. * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  3. * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. The name of the author may not be used to endorse or promote products
  15. * derived from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #include "evconfig-private.h"
  29. #include <sys/types.h>
  30. #include <limits.h>
  31. #include <string.h>
  32. #include <stdlib.h>
  33. #include "event2/event.h"
  34. #include "event2/event_struct.h"
  35. #include "event2/util.h"
  36. #include "event2/bufferevent.h"
  37. #include "event2/bufferevent_struct.h"
  38. #include "event2/buffer.h"
  39. #include "ratelim-internal.h"
  40. #include "bufferevent-internal.h"
  41. #include "mm-internal.h"
  42. #include "util-internal.h"
  43. #include "event-internal.h"
  44. int
  45. ev_token_bucket_init_(struct ev_token_bucket *bucket,
  46. const struct ev_token_bucket_cfg *cfg,
  47. ev_uint32_t current_tick,
  48. int reinitialize)
  49. {
  50. if (reinitialize) {
  51. /* on reinitialization, we only clip downwards, since we've
  52. already used who-knows-how-much bandwidth this tick. We
  53. leave "last_updated" as it is; the next update will add the
  54. appropriate amount of bandwidth to the bucket.
  55. */
  56. if (bucket->read_limit > (ev_int64_t) cfg->read_maximum)
  57. bucket->read_limit = cfg->read_maximum;
  58. if (bucket->write_limit > (ev_int64_t) cfg->write_maximum)
  59. bucket->write_limit = cfg->write_maximum;
  60. } else {
  61. bucket->read_limit = cfg->read_rate;
  62. bucket->write_limit = cfg->write_rate;
  63. bucket->last_updated = current_tick;
  64. }
  65. return 0;
  66. }
  67. int
  68. ev_token_bucket_update_(struct ev_token_bucket *bucket,
  69. const struct ev_token_bucket_cfg *cfg,
  70. ev_uint32_t current_tick)
  71. {
  72. /* It's okay if the tick number overflows, since we'll just
  73. * wrap around when we do the unsigned substraction. */
  74. unsigned n_ticks = current_tick - bucket->last_updated;
  75. /* Make sure some ticks actually happened, and that time didn't
  76. * roll back. */
  77. if (n_ticks == 0 || n_ticks > INT_MAX)
  78. return 0;
  79. /* Naively, we would say
  80. bucket->limit += n_ticks * cfg->rate;
  81. if (bucket->limit > cfg->maximum)
  82. bucket->limit = cfg->maximum;
  83. But we're worried about overflow, so we do it like this:
  84. */
  85. if ((cfg->read_maximum - bucket->read_limit) / n_ticks < cfg->read_rate)
  86. bucket->read_limit = cfg->read_maximum;
  87. else
  88. bucket->read_limit += n_ticks * cfg->read_rate;
  89. if ((cfg->write_maximum - bucket->write_limit) / n_ticks < cfg->write_rate)
  90. bucket->write_limit = cfg->write_maximum;
  91. else
  92. bucket->write_limit += n_ticks * cfg->write_rate;
  93. bucket->last_updated = current_tick;
  94. return 1;
  95. }
  96. static inline void
  97. bufferevent_update_buckets(struct bufferevent_private *bev)
  98. {
  99. /* Must hold lock on bev. */
  100. struct timeval now;
  101. unsigned tick;
  102. event_base_gettimeofday_cached(bev->bev.ev_base, &now);
  103. tick = ev_token_bucket_get_tick_(&now, bev->rate_limiting->cfg);
  104. if (tick != bev->rate_limiting->limit.last_updated)
  105. ev_token_bucket_update_(&bev->rate_limiting->limit,
  106. bev->rate_limiting->cfg, tick);
  107. }
  108. ev_uint32_t
  109. ev_token_bucket_get_tick_(const struct timeval *tv,
  110. const struct ev_token_bucket_cfg *cfg)
  111. {
  112. /* This computation uses two multiplies and a divide. We could do
  113. * fewer if we knew that the tick length was an integer number of
  114. * seconds, or if we knew it divided evenly into a second. We should
  115. * investigate that more.
  116. */
  117. /* We cast to an ev_uint64_t first, since we don't want to overflow
  118. * before we do the final divide. */
  119. ev_uint64_t msec = (ev_uint64_t)tv->tv_sec * 1000 + tv->tv_usec / 1000;
  120. return (unsigned)(msec / cfg->msec_per_tick);
  121. }
  122. struct ev_token_bucket_cfg *
  123. ev_token_bucket_cfg_new(size_t read_rate, size_t read_burst,
  124. size_t write_rate, size_t write_burst,
  125. const struct timeval *tick_len)
  126. {
  127. struct ev_token_bucket_cfg *r;
  128. struct timeval g;
  129. if (! tick_len) {
  130. g.tv_sec = 1;
  131. g.tv_usec = 0;
  132. tick_len = &g;
  133. }
  134. if (read_rate > read_burst || write_rate > write_burst ||
  135. read_rate < 1 || write_rate < 1)
  136. return NULL;
  137. if (read_rate > EV_RATE_LIMIT_MAX ||
  138. write_rate > EV_RATE_LIMIT_MAX ||
  139. read_burst > EV_RATE_LIMIT_MAX ||
  140. write_burst > EV_RATE_LIMIT_MAX)
  141. return NULL;
  142. r = mm_calloc(1, sizeof(struct ev_token_bucket_cfg));
  143. if (!r)
  144. return NULL;
  145. r->read_rate = read_rate;
  146. r->write_rate = write_rate;
  147. r->read_maximum = read_burst;
  148. r->write_maximum = write_burst;
  149. memcpy(&r->tick_timeout, tick_len, sizeof(struct timeval));
  150. r->msec_per_tick = (tick_len->tv_sec * 1000) +
  151. (tick_len->tv_usec & COMMON_TIMEOUT_MICROSECONDS_MASK)/1000;
  152. return r;
  153. }
  154. void
  155. ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg)
  156. {
  157. mm_free(cfg);
  158. }
  159. /* Default values for max_single_read & max_single_write variables. */
  160. #define MAX_SINGLE_READ_DEFAULT 16384
  161. #define MAX_SINGLE_WRITE_DEFAULT 16384
  162. #define LOCK_GROUP(g) EVLOCK_LOCK((g)->lock, 0)
  163. #define UNLOCK_GROUP(g) EVLOCK_UNLOCK((g)->lock, 0)
  164. static int bev_group_suspend_reading_(struct bufferevent_rate_limit_group *g);
  165. static int bev_group_suspend_writing_(struct bufferevent_rate_limit_group *g);
  166. static void bev_group_unsuspend_reading_(struct bufferevent_rate_limit_group *g);
  167. static void bev_group_unsuspend_writing_(struct bufferevent_rate_limit_group *g);
  168. /** Helper: figure out the maximum amount we should write if is_write, or
  169. the maximum amount we should read if is_read. Return that maximum, or
  170. 0 if our bucket is wholly exhausted.
  171. */
  172. static inline ev_ssize_t
  173. bufferevent_get_rlim_max_(struct bufferevent_private *bev, int is_write)
  174. {
  175. /* needs lock on bev. */
  176. ev_ssize_t max_so_far = is_write?bev->max_single_write:bev->max_single_read;
  177. #define LIM(x) \
  178. (is_write ? (x).write_limit : (x).read_limit)
  179. #define GROUP_SUSPENDED(g) \
  180. (is_write ? (g)->write_suspended : (g)->read_suspended)
  181. /* Sets max_so_far to MIN(x, max_so_far) */
  182. #define CLAMPTO(x) \
  183. do { \
  184. if (max_so_far > (x)) \
  185. max_so_far = (x); \
  186. } while (0);
  187. if (!bev->rate_limiting)
  188. return max_so_far;
  189. /* If rate-limiting is enabled at all, update the appropriate
  190. bucket, and take the smaller of our rate limit and the group
  191. rate limit.
  192. */
  193. if (bev->rate_limiting->cfg) {
  194. bufferevent_update_buckets(bev);
  195. max_so_far = LIM(bev->rate_limiting->limit);
  196. }
  197. if (bev->rate_limiting->group) {
  198. struct bufferevent_rate_limit_group *g =
  199. bev->rate_limiting->group;
  200. ev_ssize_t share;
  201. LOCK_GROUP(g);
  202. if (GROUP_SUSPENDED(g)) {
  203. /* We can get here if we failed to lock this
  204. * particular bufferevent while suspending the whole
  205. * group. */
  206. if (is_write)
  207. bufferevent_suspend_write_(&bev->bev,
  208. BEV_SUSPEND_BW_GROUP);
  209. else
  210. bufferevent_suspend_read_(&bev->bev,
  211. BEV_SUSPEND_BW_GROUP);
  212. share = 0;
  213. } else {
  214. /* XXXX probably we should divide among the active
  215. * members, not the total members. */
  216. share = LIM(g->rate_limit) / g->n_members;
  217. if (share < g->min_share)
  218. share = g->min_share;
  219. }
  220. UNLOCK_GROUP(g);
  221. CLAMPTO(share);
  222. }
  223. if (max_so_far < 0)
  224. max_so_far = 0;
  225. return max_so_far;
  226. }
  227. ev_ssize_t
  228. bufferevent_get_read_max_(struct bufferevent_private *bev)
  229. {
  230. return bufferevent_get_rlim_max_(bev, 0);
  231. }
  232. ev_ssize_t
  233. bufferevent_get_write_max_(struct bufferevent_private *bev)
  234. {
  235. return bufferevent_get_rlim_max_(bev, 1);
  236. }
  237. int
  238. bufferevent_decrement_read_buckets_(struct bufferevent_private *bev, ev_ssize_t bytes)
  239. {
  240. /* XXXXX Make sure all users of this function check its return value */
  241. int r = 0;
  242. /* need to hold lock on bev */
  243. if (!bev->rate_limiting)
  244. return 0;
  245. if (bev->rate_limiting->cfg) {
  246. bev->rate_limiting->limit.read_limit -= bytes;
  247. if (bev->rate_limiting->limit.read_limit <= 0) {
  248. bufferevent_suspend_read_(&bev->bev, BEV_SUSPEND_BW);
  249. if (event_add(&bev->rate_limiting->refill_bucket_event,
  250. &bev->rate_limiting->cfg->tick_timeout) < 0)
  251. r = -1;
  252. } else if (bev->read_suspended & BEV_SUSPEND_BW) {
  253. if (!(bev->write_suspended & BEV_SUSPEND_BW))
  254. event_del(&bev->rate_limiting->refill_bucket_event);
  255. bufferevent_unsuspend_read_(&bev->bev, BEV_SUSPEND_BW);
  256. }
  257. }
  258. if (bev->rate_limiting->group) {
  259. LOCK_GROUP(bev->rate_limiting->group);
  260. bev->rate_limiting->group->rate_limit.read_limit -= bytes;
  261. bev->rate_limiting->group->total_read += bytes;
  262. if (bev->rate_limiting->group->rate_limit.read_limit <= 0) {
  263. bev_group_suspend_reading_(bev->rate_limiting->group);
  264. } else if (bev->rate_limiting->group->read_suspended) {
  265. bev_group_unsuspend_reading_(bev->rate_limiting->group);
  266. }
  267. UNLOCK_GROUP(bev->rate_limiting->group);
  268. }
  269. return r;
  270. }
  271. int
  272. bufferevent_decrement_write_buckets_(struct bufferevent_private *bev, ev_ssize_t bytes)
  273. {
  274. /* XXXXX Make sure all users of this function check its return value */
  275. int r = 0;
  276. /* need to hold lock */
  277. if (!bev->rate_limiting)
  278. return 0;
  279. if (bev->rate_limiting->cfg) {
  280. bev->rate_limiting->limit.write_limit -= bytes;
  281. if (bev->rate_limiting->limit.write_limit <= 0) {
  282. bufferevent_suspend_write_(&bev->bev, BEV_SUSPEND_BW);
  283. if (event_add(&bev->rate_limiting->refill_bucket_event,
  284. &bev->rate_limiting->cfg->tick_timeout) < 0)
  285. r = -1;
  286. } else if (bev->write_suspended & BEV_SUSPEND_BW) {
  287. if (!(bev->read_suspended & BEV_SUSPEND_BW))
  288. event_del(&bev->rate_limiting->refill_bucket_event);
  289. bufferevent_unsuspend_write_(&bev->bev, BEV_SUSPEND_BW);
  290. }
  291. }
  292. if (bev->rate_limiting->group) {
  293. LOCK_GROUP(bev->rate_limiting->group);
  294. bev->rate_limiting->group->rate_limit.write_limit -= bytes;
  295. bev->rate_limiting->group->total_written += bytes;
  296. if (bev->rate_limiting->group->rate_limit.write_limit <= 0) {
  297. bev_group_suspend_writing_(bev->rate_limiting->group);
  298. } else if (bev->rate_limiting->group->write_suspended) {
  299. bev_group_unsuspend_writing_(bev->rate_limiting->group);
  300. }
  301. UNLOCK_GROUP(bev->rate_limiting->group);
  302. }
  303. return r;
  304. }
  305. /** Stop reading on every bufferevent in <b>g</b> */
  306. static int
  307. bev_group_suspend_reading_(struct bufferevent_rate_limit_group *g)
  308. {
  309. /* Needs group lock */
  310. struct bufferevent_private *bev;
  311. g->read_suspended = 1;
  312. g->pending_unsuspend_read = 0;
  313. /* Note that in this loop we call EVLOCK_TRY_LOCK_ instead of BEV_LOCK,
  314. to prevent a deadlock. (Ordinarily, the group lock nests inside
  315. the bufferevent locks. If we are unable to lock any individual
  316. bufferevent, it will find out later when it looks at its limit
  317. and sees that its group is suspended.)
  318. */
  319. LIST_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
  320. if (EVLOCK_TRY_LOCK_(bev->lock)) {
  321. bufferevent_suspend_read_(&bev->bev,
  322. BEV_SUSPEND_BW_GROUP);
  323. EVLOCK_UNLOCK(bev->lock, 0);
  324. }
  325. }
  326. return 0;
  327. }
  328. /** Stop writing on every bufferevent in <b>g</b> */
  329. static int
  330. bev_group_suspend_writing_(struct bufferevent_rate_limit_group *g)
  331. {
  332. /* Needs group lock */
  333. struct bufferevent_private *bev;
  334. g->write_suspended = 1;
  335. g->pending_unsuspend_write = 0;
  336. LIST_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
  337. if (EVLOCK_TRY_LOCK_(bev->lock)) {
  338. bufferevent_suspend_write_(&bev->bev,
  339. BEV_SUSPEND_BW_GROUP);
  340. EVLOCK_UNLOCK(bev->lock, 0);
  341. }
  342. }
  343. return 0;
  344. }
  345. /** Timer callback invoked on a single bufferevent with one or more exhausted
  346. buckets when they are ready to refill. */
  347. static void
  348. bev_refill_callback_(evutil_socket_t fd, short what, void *arg)
  349. {
  350. unsigned tick;
  351. struct timeval now;
  352. struct bufferevent_private *bev = arg;
  353. int again = 0;
  354. BEV_LOCK(&bev->bev);
  355. if (!bev->rate_limiting || !bev->rate_limiting->cfg) {
  356. BEV_UNLOCK(&bev->bev);
  357. return;
  358. }
  359. /* First, update the bucket */
  360. event_base_gettimeofday_cached(bev->bev.ev_base, &now);
  361. tick = ev_token_bucket_get_tick_(&now,
  362. bev->rate_limiting->cfg);
  363. ev_token_bucket_update_(&bev->rate_limiting->limit,
  364. bev->rate_limiting->cfg,
  365. tick);
  366. /* Now unsuspend any read/write operations as appropriate. */
  367. if ((bev->read_suspended & BEV_SUSPEND_BW)) {
  368. if (bev->rate_limiting->limit.read_limit > 0)
  369. bufferevent_unsuspend_read_(&bev->bev, BEV_SUSPEND_BW);
  370. else
  371. again = 1;
  372. }
  373. if ((bev->write_suspended & BEV_SUSPEND_BW)) {
  374. if (bev->rate_limiting->limit.write_limit > 0)
  375. bufferevent_unsuspend_write_(&bev->bev, BEV_SUSPEND_BW);
  376. else
  377. again = 1;
  378. }
  379. if (again) {
  380. /* One or more of the buckets may need another refill if they
  381. started negative.
  382. XXXX if we need to be quiet for more ticks, we should
  383. maybe figure out what timeout we really want.
  384. */
  385. /* XXXX Handle event_add failure somehow */
  386. event_add(&bev->rate_limiting->refill_bucket_event,
  387. &bev->rate_limiting->cfg->tick_timeout);
  388. }
  389. BEV_UNLOCK(&bev->bev);
  390. }
  391. /** Helper: grab a random element from a bufferevent group.
  392. *
  393. * Requires that we hold the lock on the group.
  394. */
  395. static struct bufferevent_private *
  396. bev_group_random_element_(struct bufferevent_rate_limit_group *group)
  397. {
  398. int which;
  399. struct bufferevent_private *bev;
  400. /* requires group lock */
  401. if (!group->n_members)
  402. return NULL;
  403. EVUTIL_ASSERT(! LIST_EMPTY(&group->members));
  404. which = evutil_weakrand_range_(&group->weakrand_seed, group->n_members);
  405. bev = LIST_FIRST(&group->members);
  406. while (which--)
  407. bev = LIST_NEXT(bev, rate_limiting->next_in_group);
  408. return bev;
  409. }
  410. /** Iterate over the elements of a rate-limiting group 'g' with a random
  411. starting point, assigning each to the variable 'bev', and executing the
  412. block 'block'.
  413. We do this in a half-baked effort to get fairness among group members.
  414. XXX Round-robin or some kind of priority queue would be even more fair.
  415. */
  416. #define FOREACH_RANDOM_ORDER(block) \
  417. do { \
  418. first = bev_group_random_element_(g); \
  419. for (bev = first; bev != LIST_END(&g->members); \
  420. bev = LIST_NEXT(bev, rate_limiting->next_in_group)) { \
  421. block ; \
  422. } \
  423. for (bev = LIST_FIRST(&g->members); bev && bev != first; \
  424. bev = LIST_NEXT(bev, rate_limiting->next_in_group)) { \
  425. block ; \
  426. } \
  427. } while (0)
  428. static void
  429. bev_group_unsuspend_reading_(struct bufferevent_rate_limit_group *g)
  430. {
  431. int again = 0;
  432. struct bufferevent_private *bev, *first;
  433. g->read_suspended = 0;
  434. FOREACH_RANDOM_ORDER({
  435. if (EVLOCK_TRY_LOCK_(bev->lock)) {
  436. bufferevent_unsuspend_read_(&bev->bev,
  437. BEV_SUSPEND_BW_GROUP);
  438. EVLOCK_UNLOCK(bev->lock, 0);
  439. } else {
  440. again = 1;
  441. }
  442. });
  443. g->pending_unsuspend_read = again;
  444. }
  445. static void
  446. bev_group_unsuspend_writing_(struct bufferevent_rate_limit_group *g)
  447. {
  448. int again = 0;
  449. struct bufferevent_private *bev, *first;
  450. g->write_suspended = 0;
  451. FOREACH_RANDOM_ORDER({
  452. if (EVLOCK_TRY_LOCK_(bev->lock)) {
  453. bufferevent_unsuspend_write_(&bev->bev,
  454. BEV_SUSPEND_BW_GROUP);
  455. EVLOCK_UNLOCK(bev->lock, 0);
  456. } else {
  457. again = 1;
  458. }
  459. });
  460. g->pending_unsuspend_write = again;
  461. }
  462. /** Callback invoked every tick to add more elements to the group bucket
  463. and unsuspend group members as needed.
  464. */
  465. static void
  466. bev_group_refill_callback_(evutil_socket_t fd, short what, void *arg)
  467. {
  468. struct bufferevent_rate_limit_group *g = arg;
  469. unsigned tick;
  470. struct timeval now;
  471. event_base_gettimeofday_cached(event_get_base(&g->master_refill_event), &now);
  472. LOCK_GROUP(g);
  473. tick = ev_token_bucket_get_tick_(&now, &g->rate_limit_cfg);
  474. ev_token_bucket_update_(&g->rate_limit, &g->rate_limit_cfg, tick);
  475. if (g->pending_unsuspend_read ||
  476. (g->read_suspended && (g->rate_limit.read_limit >= g->min_share))) {
  477. bev_group_unsuspend_reading_(g);
  478. }
  479. if (g->pending_unsuspend_write ||
  480. (g->write_suspended && (g->rate_limit.write_limit >= g->min_share))){
  481. bev_group_unsuspend_writing_(g);
  482. }
  483. /* XXXX Rather than waiting to the next tick to unsuspend stuff
  484. * with pending_unsuspend_write/read, we should do it on the
  485. * next iteration of the mainloop.
  486. */
  487. UNLOCK_GROUP(g);
  488. }
  489. int
  490. bufferevent_set_rate_limit(struct bufferevent *bev,
  491. struct ev_token_bucket_cfg *cfg)
  492. {
  493. struct bufferevent_private *bevp = BEV_UPCAST(bev);
  494. int r = -1;
  495. struct bufferevent_rate_limit *rlim;
  496. struct timeval now;
  497. ev_uint32_t tick;
  498. int reinit = 0, suspended = 0;
  499. /* XXX reference-count cfg */
  500. BEV_LOCK(bev);
  501. if (cfg == NULL) {
  502. if (bevp->rate_limiting) {
  503. rlim = bevp->rate_limiting;
  504. rlim->cfg = NULL;
  505. bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
  506. bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
  507. if (event_initialized(&rlim->refill_bucket_event))
  508. event_del(&rlim->refill_bucket_event);
  509. }
  510. r = 0;
  511. goto done;
  512. }
  513. event_base_gettimeofday_cached(bev->ev_base, &now);
  514. tick = ev_token_bucket_get_tick_(&now, cfg);
  515. if (bevp->rate_limiting && bevp->rate_limiting->cfg == cfg) {
  516. /* no-op */
  517. r = 0;
  518. goto done;
  519. }
  520. if (bevp->rate_limiting == NULL) {
  521. rlim = mm_calloc(1, sizeof(struct bufferevent_rate_limit));
  522. if (!rlim)
  523. goto done;
  524. bevp->rate_limiting = rlim;
  525. } else {
  526. rlim = bevp->rate_limiting;
  527. }
  528. reinit = rlim->cfg != NULL;
  529. rlim->cfg = cfg;
  530. ev_token_bucket_init_(&rlim->limit, cfg, tick, reinit);
  531. if (reinit) {
  532. EVUTIL_ASSERT(event_initialized(&rlim->refill_bucket_event));
  533. event_del(&rlim->refill_bucket_event);
  534. }
  535. event_assign(&rlim->refill_bucket_event, bev->ev_base,
  536. -1, EV_FINALIZE, bev_refill_callback_, bevp);
  537. if (rlim->limit.read_limit > 0) {
  538. bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
  539. } else {
  540. bufferevent_suspend_read_(bev, BEV_SUSPEND_BW);
  541. suspended=1;
  542. }
  543. if (rlim->limit.write_limit > 0) {
  544. bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
  545. } else {
  546. bufferevent_suspend_write_(bev, BEV_SUSPEND_BW);
  547. suspended = 1;
  548. }
  549. if (suspended)
  550. event_add(&rlim->refill_bucket_event, &cfg->tick_timeout);
  551. r = 0;
  552. done:
  553. BEV_UNLOCK(bev);
  554. return r;
  555. }
  556. struct bufferevent_rate_limit_group *
  557. bufferevent_rate_limit_group_new(struct event_base *base,
  558. const struct ev_token_bucket_cfg *cfg)
  559. {
  560. struct bufferevent_rate_limit_group *g;
  561. struct timeval now;
  562. ev_uint32_t tick;
  563. event_base_gettimeofday_cached(base, &now);
  564. tick = ev_token_bucket_get_tick_(&now, cfg);
  565. g = mm_calloc(1, sizeof(struct bufferevent_rate_limit_group));
  566. if (!g)
  567. return NULL;
  568. memcpy(&g->rate_limit_cfg, cfg, sizeof(g->rate_limit_cfg));
  569. LIST_INIT(&g->members);
  570. ev_token_bucket_init_(&g->rate_limit, cfg, tick, 0);
  571. event_assign(&g->master_refill_event, base, -1, EV_PERSIST|EV_FINALIZE,
  572. bev_group_refill_callback_, g);
  573. /*XXXX handle event_add failure */
  574. event_add(&g->master_refill_event, &cfg->tick_timeout);
  575. EVTHREAD_ALLOC_LOCK(g->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  576. bufferevent_rate_limit_group_set_min_share(g, 64);
  577. evutil_weakrand_seed_(&g->weakrand_seed,
  578. (ev_uint32_t) ((now.tv_sec + now.tv_usec) + (ev_intptr_t)g));
  579. return g;
  580. }
  581. int
  582. bufferevent_rate_limit_group_set_cfg(
  583. struct bufferevent_rate_limit_group *g,
  584. const struct ev_token_bucket_cfg *cfg)
  585. {
  586. int same_tick;
  587. if (!g || !cfg)
  588. return -1;
  589. LOCK_GROUP(g);
  590. same_tick = evutil_timercmp(
  591. &g->rate_limit_cfg.tick_timeout, &cfg->tick_timeout, ==);
  592. memcpy(&g->rate_limit_cfg, cfg, sizeof(g->rate_limit_cfg));
  593. if (g->rate_limit.read_limit > (ev_ssize_t)cfg->read_maximum)
  594. g->rate_limit.read_limit = cfg->read_maximum;
  595. if (g->rate_limit.write_limit > (ev_ssize_t)cfg->write_maximum)
  596. g->rate_limit.write_limit = cfg->write_maximum;
  597. if (!same_tick) {
  598. /* This can cause a hiccup in the schedule */
  599. event_add(&g->master_refill_event, &cfg->tick_timeout);
  600. }
  601. /* The new limits might force us to adjust min_share differently. */
  602. bufferevent_rate_limit_group_set_min_share(g, g->configured_min_share);
  603. UNLOCK_GROUP(g);
  604. return 0;
  605. }
  606. int
  607. bufferevent_rate_limit_group_set_min_share(
  608. struct bufferevent_rate_limit_group *g,
  609. size_t share)
  610. {
  611. if (share > EV_SSIZE_MAX)
  612. return -1;
  613. g->configured_min_share = share;
  614. /* Can't set share to less than the one-tick maximum. IOW, at steady
  615. * state, at least one connection can go per tick. */
  616. if (share > g->rate_limit_cfg.read_rate)
  617. share = g->rate_limit_cfg.read_rate;
  618. if (share > g->rate_limit_cfg.write_rate)
  619. share = g->rate_limit_cfg.write_rate;
  620. g->min_share = share;
  621. return 0;
  622. }
  623. void
  624. bufferevent_rate_limit_group_free(struct bufferevent_rate_limit_group *g)
  625. {
  626. LOCK_GROUP(g);
  627. EVUTIL_ASSERT(0 == g->n_members);
  628. event_del(&g->master_refill_event);
  629. UNLOCK_GROUP(g);
  630. EVTHREAD_FREE_LOCK(g->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  631. mm_free(g);
  632. }
  633. int
  634. bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
  635. struct bufferevent_rate_limit_group *g)
  636. {
  637. int wsuspend, rsuspend;
  638. struct bufferevent_private *bevp = BEV_UPCAST(bev);
  639. BEV_LOCK(bev);
  640. if (!bevp->rate_limiting) {
  641. struct bufferevent_rate_limit *rlim;
  642. rlim = mm_calloc(1, sizeof(struct bufferevent_rate_limit));
  643. if (!rlim) {
  644. BEV_UNLOCK(bev);
  645. return -1;
  646. }
  647. event_assign(&rlim->refill_bucket_event, bev->ev_base,
  648. -1, EV_FINALIZE, bev_refill_callback_, bevp);
  649. bevp->rate_limiting = rlim;
  650. }
  651. if (bevp->rate_limiting->group == g) {
  652. BEV_UNLOCK(bev);
  653. return 0;
  654. }
  655. if (bevp->rate_limiting->group)
  656. bufferevent_remove_from_rate_limit_group(bev);
  657. LOCK_GROUP(g);
  658. bevp->rate_limiting->group = g;
  659. ++g->n_members;
  660. LIST_INSERT_HEAD(&g->members, bevp, rate_limiting->next_in_group);
  661. rsuspend = g->read_suspended;
  662. wsuspend = g->write_suspended;
  663. UNLOCK_GROUP(g);
  664. if (rsuspend)
  665. bufferevent_suspend_read_(bev, BEV_SUSPEND_BW_GROUP);
  666. if (wsuspend)
  667. bufferevent_suspend_write_(bev, BEV_SUSPEND_BW_GROUP);
  668. BEV_UNLOCK(bev);
  669. return 0;
  670. }
  671. int
  672. bufferevent_remove_from_rate_limit_group(struct bufferevent *bev)
  673. {
  674. return bufferevent_remove_from_rate_limit_group_internal_(bev, 1);
  675. }
  676. int
  677. bufferevent_remove_from_rate_limit_group_internal_(struct bufferevent *bev,
  678. int unsuspend)
  679. {
  680. struct bufferevent_private *bevp = BEV_UPCAST(bev);
  681. BEV_LOCK(bev);
  682. if (bevp->rate_limiting && bevp->rate_limiting->group) {
  683. struct bufferevent_rate_limit_group *g =
  684. bevp->rate_limiting->group;
  685. LOCK_GROUP(g);
  686. bevp->rate_limiting->group = NULL;
  687. --g->n_members;
  688. LIST_REMOVE(bevp, rate_limiting->next_in_group);
  689. UNLOCK_GROUP(g);
  690. }
  691. if (unsuspend) {
  692. bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW_GROUP);
  693. bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW_GROUP);
  694. }
  695. BEV_UNLOCK(bev);
  696. return 0;
  697. }
  698. /* ===
  699. * API functions to expose rate limits.
  700. *
  701. * Don't use these from inside Libevent; they're meant to be for use by
  702. * the program.
  703. * === */
  704. /* Mostly you don't want to use this function from inside libevent;
  705. * bufferevent_get_read_max_() is more likely what you want*/
  706. ev_ssize_t
  707. bufferevent_get_read_limit(struct bufferevent *bev)
  708. {
  709. ev_ssize_t r;
  710. struct bufferevent_private *bevp;
  711. BEV_LOCK(bev);
  712. bevp = BEV_UPCAST(bev);
  713. if (bevp->rate_limiting && bevp->rate_limiting->cfg) {
  714. bufferevent_update_buckets(bevp);
  715. r = bevp->rate_limiting->limit.read_limit;
  716. } else {
  717. r = EV_SSIZE_MAX;
  718. }
  719. BEV_UNLOCK(bev);
  720. return r;
  721. }
  722. /* Mostly you don't want to use this function from inside libevent;
  723. * bufferevent_get_write_max_() is more likely what you want*/
  724. ev_ssize_t
  725. bufferevent_get_write_limit(struct bufferevent *bev)
  726. {
  727. ev_ssize_t r;
  728. struct bufferevent_private *bevp;
  729. BEV_LOCK(bev);
  730. bevp = BEV_UPCAST(bev);
  731. if (bevp->rate_limiting && bevp->rate_limiting->cfg) {
  732. bufferevent_update_buckets(bevp);
  733. r = bevp->rate_limiting->limit.write_limit;
  734. } else {
  735. r = EV_SSIZE_MAX;
  736. }
  737. BEV_UNLOCK(bev);
  738. return r;
  739. }
  740. int
  741. bufferevent_set_max_single_read(struct bufferevent *bev, size_t size)
  742. {
  743. struct bufferevent_private *bevp;
  744. BEV_LOCK(bev);
  745. bevp = BEV_UPCAST(bev);
  746. if (size == 0 || size > EV_SSIZE_MAX)
  747. bevp->max_single_read = MAX_SINGLE_READ_DEFAULT;
  748. else
  749. bevp->max_single_read = size;
  750. BEV_UNLOCK(bev);
  751. return 0;
  752. }
  753. int
  754. bufferevent_set_max_single_write(struct bufferevent *bev, size_t size)
  755. {
  756. struct bufferevent_private *bevp;
  757. BEV_LOCK(bev);
  758. bevp = BEV_UPCAST(bev);
  759. if (size == 0 || size > EV_SSIZE_MAX)
  760. bevp->max_single_write = MAX_SINGLE_WRITE_DEFAULT;
  761. else
  762. bevp->max_single_write = size;
  763. BEV_UNLOCK(bev);
  764. return 0;
  765. }
  766. ev_ssize_t
  767. bufferevent_get_max_single_read(struct bufferevent *bev)
  768. {
  769. ev_ssize_t r;
  770. BEV_LOCK(bev);
  771. r = BEV_UPCAST(bev)->max_single_read;
  772. BEV_UNLOCK(bev);
  773. return r;
  774. }
  775. ev_ssize_t
  776. bufferevent_get_max_single_write(struct bufferevent *bev)
  777. {
  778. ev_ssize_t r;
  779. BEV_LOCK(bev);
  780. r = BEV_UPCAST(bev)->max_single_write;
  781. BEV_UNLOCK(bev);
  782. return r;
  783. }
  784. ev_ssize_t
  785. bufferevent_get_max_to_read(struct bufferevent *bev)
  786. {
  787. ev_ssize_t r;
  788. BEV_LOCK(bev);
  789. r = bufferevent_get_read_max_(BEV_UPCAST(bev));
  790. BEV_UNLOCK(bev);
  791. return r;
  792. }
  793. ev_ssize_t
  794. bufferevent_get_max_to_write(struct bufferevent *bev)
  795. {
  796. ev_ssize_t r;
  797. BEV_LOCK(bev);
  798. r = bufferevent_get_write_max_(BEV_UPCAST(bev));
  799. BEV_UNLOCK(bev);
  800. return r;
  801. }
  802. const struct ev_token_bucket_cfg *
  803. bufferevent_get_token_bucket_cfg(const struct bufferevent *bev) {
  804. struct bufferevent_private *bufev_private = BEV_UPCAST(bev);
  805. struct ev_token_bucket_cfg *cfg;
  806. BEV_LOCK(bev);
  807. if (bufev_private->rate_limiting) {
  808. cfg = bufev_private->rate_limiting->cfg;
  809. } else {
  810. cfg = NULL;
  811. }
  812. BEV_UNLOCK(bev);
  813. return cfg;
  814. }
  815. /* Mostly you don't want to use this function from inside libevent;
  816. * bufferevent_get_read_max_() is more likely what you want*/
  817. ev_ssize_t
  818. bufferevent_rate_limit_group_get_read_limit(
  819. struct bufferevent_rate_limit_group *grp)
  820. {
  821. ev_ssize_t r;
  822. LOCK_GROUP(grp);
  823. r = grp->rate_limit.read_limit;
  824. UNLOCK_GROUP(grp);
  825. return r;
  826. }
  827. /* Mostly you don't want to use this function from inside libevent;
  828. * bufferevent_get_write_max_() is more likely what you want. */
  829. ev_ssize_t
  830. bufferevent_rate_limit_group_get_write_limit(
  831. struct bufferevent_rate_limit_group *grp)
  832. {
  833. ev_ssize_t r;
  834. LOCK_GROUP(grp);
  835. r = grp->rate_limit.write_limit;
  836. UNLOCK_GROUP(grp);
  837. return r;
  838. }
  839. int
  840. bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr)
  841. {
  842. int r = 0;
  843. ev_ssize_t old_limit, new_limit;
  844. struct bufferevent_private *bevp;
  845. BEV_LOCK(bev);
  846. bevp = BEV_UPCAST(bev);
  847. EVUTIL_ASSERT(bevp->rate_limiting && bevp->rate_limiting->cfg);
  848. old_limit = bevp->rate_limiting->limit.read_limit;
  849. new_limit = (bevp->rate_limiting->limit.read_limit -= decr);
  850. if (old_limit > 0 && new_limit <= 0) {
  851. bufferevent_suspend_read_(bev, BEV_SUSPEND_BW);
  852. if (event_add(&bevp->rate_limiting->refill_bucket_event,
  853. &bevp->rate_limiting->cfg->tick_timeout) < 0)
  854. r = -1;
  855. } else if (old_limit <= 0 && new_limit > 0) {
  856. if (!(bevp->write_suspended & BEV_SUSPEND_BW))
  857. event_del(&bevp->rate_limiting->refill_bucket_event);
  858. bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
  859. }
  860. BEV_UNLOCK(bev);
  861. return r;
  862. }
  863. int
  864. bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr)
  865. {
  866. /* XXXX this is mostly copy-and-paste from
  867. * bufferevent_decrement_read_limit */
  868. int r = 0;
  869. ev_ssize_t old_limit, new_limit;
  870. struct bufferevent_private *bevp;
  871. BEV_LOCK(bev);
  872. bevp = BEV_UPCAST(bev);
  873. EVUTIL_ASSERT(bevp->rate_limiting && bevp->rate_limiting->cfg);
  874. old_limit = bevp->rate_limiting->limit.write_limit;
  875. new_limit = (bevp->rate_limiting->limit.write_limit -= decr);
  876. if (old_limit > 0 && new_limit <= 0) {
  877. bufferevent_suspend_write_(bev, BEV_SUSPEND_BW);
  878. if (event_add(&bevp->rate_limiting->refill_bucket_event,
  879. &bevp->rate_limiting->cfg->tick_timeout) < 0)
  880. r = -1;
  881. } else if (old_limit <= 0 && new_limit > 0) {
  882. if (!(bevp->read_suspended & BEV_SUSPEND_BW))
  883. event_del(&bevp->rate_limiting->refill_bucket_event);
  884. bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
  885. }
  886. BEV_UNLOCK(bev);
  887. return r;
  888. }
  889. int
  890. bufferevent_rate_limit_group_decrement_read(
  891. struct bufferevent_rate_limit_group *grp, ev_ssize_t decr)
  892. {
  893. int r = 0;
  894. ev_ssize_t old_limit, new_limit;
  895. LOCK_GROUP(grp);
  896. old_limit = grp->rate_limit.read_limit;
  897. new_limit = (grp->rate_limit.read_limit -= decr);
  898. if (old_limit > 0 && new_limit <= 0) {
  899. bev_group_suspend_reading_(grp);
  900. } else if (old_limit <= 0 && new_limit > 0) {
  901. bev_group_unsuspend_reading_(grp);
  902. }
  903. UNLOCK_GROUP(grp);
  904. return r;
  905. }
  906. int
  907. bufferevent_rate_limit_group_decrement_write(
  908. struct bufferevent_rate_limit_group *grp, ev_ssize_t decr)
  909. {
  910. int r = 0;
  911. ev_ssize_t old_limit, new_limit;
  912. LOCK_GROUP(grp);
  913. old_limit = grp->rate_limit.write_limit;
  914. new_limit = (grp->rate_limit.write_limit -= decr);
  915. if (old_limit > 0 && new_limit <= 0) {
  916. bev_group_suspend_writing_(grp);
  917. } else if (old_limit <= 0 && new_limit > 0) {
  918. bev_group_unsuspend_writing_(grp);
  919. }
  920. UNLOCK_GROUP(grp);
  921. return r;
  922. }
  923. void
  924. bufferevent_rate_limit_group_get_totals(struct bufferevent_rate_limit_group *grp,
  925. ev_uint64_t *total_read_out, ev_uint64_t *total_written_out)
  926. {
  927. EVUTIL_ASSERT(grp != NULL);
  928. if (total_read_out)
  929. *total_read_out = grp->total_read;
  930. if (total_written_out)
  931. *total_written_out = grp->total_written;
  932. }
  933. void
  934. bufferevent_rate_limit_group_reset_totals(struct bufferevent_rate_limit_group *grp)
  935. {
  936. grp->total_read = grp->total_written = 0;
  937. }
  938. int
  939. bufferevent_ratelim_init_(struct bufferevent_private *bev)
  940. {
  941. bev->rate_limiting = NULL;
  942. bev->max_single_read = MAX_SINGLE_READ_DEFAULT;
  943. bev->max_single_write = MAX_SINGLE_WRITE_DEFAULT;
  944. return 0;
  945. }