change time multiplication/division API to long long to avoid accidental range reduction
[oweals/gnunet.git] / src / util / bandwidth.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2010, 2013 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file util/bandwidth.c
23  * @brief functions related to bandwidth (unit)
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28
29
30 #define LOG(kind,...) GNUNET_log_from (kind, "util-bandwidth", __VA_ARGS__)
31
32 /**
33  * Create a new bandwidth value.
34  *
35  * @param bytes_per_second value to create
36  * @return the new bandwidth value
37  */
38 struct GNUNET_BANDWIDTH_Value32NBO
39 GNUNET_BANDWIDTH_value_init (uint32_t bytes_per_second)
40 {
41   struct GNUNET_BANDWIDTH_Value32NBO ret;
42
43   ret.value__ = htonl (bytes_per_second);
44   return ret;
45 }
46
47
48 /**
49  * Compute the MIN of two bandwidth values.
50  *
51  * @param b1 first value
52  * @param b2 second value
53  * @return the min of b1 and b2
54  */
55 struct GNUNET_BANDWIDTH_Value32NBO
56 GNUNET_BANDWIDTH_value_min (struct GNUNET_BANDWIDTH_Value32NBO b1,
57                             struct GNUNET_BANDWIDTH_Value32NBO b2)
58 {
59   return
60       GNUNET_BANDWIDTH_value_init (GNUNET_MIN
61                                    (ntohl (b1.value__),
62                                     ntohl (b2.value__)));
63 }
64
65
66 /**
67  * Compute the MAX of two bandwidth values.
68  *
69  * @param b1 first value
70  * @param b2 second value
71  * @return the min of b1 and b2
72  */
73 struct GNUNET_BANDWIDTH_Value32NBO
74 GNUNET_BANDWIDTH_value_max (struct GNUNET_BANDWIDTH_Value32NBO b1,
75                             struct GNUNET_BANDWIDTH_Value32NBO b2)
76 {
77   return
78       GNUNET_BANDWIDTH_value_init (GNUNET_MAX
79                                    (ntohl (b1.value__),
80                                     ntohl (b2.value__)));
81 }
82
83
84 /**
85  * At the given bandwidth, calculate how much traffic will be
86  * available until the given deadline.
87  *
88  * @param bps bandwidth
89  * @param deadline when is the deadline
90  * @return number of bytes available at bps until deadline
91  */
92 uint64_t
93 GNUNET_BANDWIDTH_value_get_available_until (struct GNUNET_BANDWIDTH_Value32NBO bps,
94                                             struct GNUNET_TIME_Relative deadline)
95 {
96   uint64_t b;
97
98   b = ntohl (bps.value__);
99   LOG (GNUNET_ERROR_TYPE_DEBUG,
100        "Bandwidth has %llu bytes available until deadline in %s\n",
101        (unsigned long long) ((b * deadline.rel_value_us + 500000LL) / 1000000LL),
102        GNUNET_STRINGS_relative_time_to_string (deadline, GNUNET_YES));
103   return (b * deadline.rel_value_us + 500000LL) / 1000000LL;
104 }
105
106
107 /**
108  * At the given bandwidth, calculate how long it would take for
109  * @a size bytes to be transmitted.
110  *
111  * @param bps bandwidth
112  * @param size number of bytes we want to have available
113  * @return how long it would take
114  */
115 struct GNUNET_TIME_Relative
116 GNUNET_BANDWIDTH_value_get_delay_for (struct GNUNET_BANDWIDTH_Value32NBO bps,
117                                       uint64_t size)
118 {
119   uint64_t b;
120   struct GNUNET_TIME_Relative ret;
121
122   b = ntohl (bps.value__);
123   if (0 == b)
124   {
125     LOG (GNUNET_ERROR_TYPE_DEBUG,
126          "Bandwidth suggests delay of infinity (zero bandwidth)\n");
127     return GNUNET_TIME_UNIT_FOREVER_REL;
128   }
129   ret.rel_value_us = size * 1000LL * 1000LL / b;
130   LOG (GNUNET_ERROR_TYPE_DEBUG,
131        "Bandwidth suggests delay of %s for %llu bytes of traffic\n",
132        GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES),
133        (unsigned long long) size);
134   return ret;
135 }
136
137
138 /**
139  * Task run whenever we hit the bandwidth limit for a tracker.
140  *
141  * @param cls the `struct GNUNET_BANDWIDTH_Tracker`
142  */
143 static void
144 excess_trigger (void *cls)
145 {
146   struct GNUNET_BANDWIDTH_Tracker *av = cls;
147
148   av->excess_task = NULL;
149   if (NULL != av->excess_cb)
150   {
151     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
152                 "Notifying application about excess bandwidth\n");
153     av->excess_cb (av->excess_cb_cls);
154   }
155 }
156
157
158 /**
159  * Recalculate when we might need to call the excess callback.
160  */
161 static void
162 update_excess (struct GNUNET_BANDWIDTH_Tracker *av)
163 {
164   struct GNUNET_TIME_Relative delay;
165   struct GNUNET_TIME_Absolute now;
166   uint64_t delta_time;
167   uint64_t delta_avail;
168   int64_t left_bytes;
169   uint64_t max_carry;
170   int64_t current_consumption;
171
172   if (NULL == av->excess_cb)
173     return; /* nothing to do */
174   now = GNUNET_TIME_absolute_get ();
175   delta_time = now.abs_value_us - av->last_update__.abs_value_us;
176   delta_avail =
177       (delta_time * ((unsigned long long) av->available_bytes_per_s__) +
178        500000LL) / 1000000LL;
179   current_consumption = av->consumption_since_last_update__ - delta_avail;
180   if (current_consumption > av->consumption_since_last_update__)
181   {
182     /* integer underflow, cap! */
183     current_consumption = INT64_MIN;
184   }
185   /* negative current_consumption means that we have savings */
186   max_carry = ((uint64_t) av->available_bytes_per_s__) * av->max_carry_s__;
187   if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
188     max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
189   if (max_carry > INT64_MAX)
190     max_carry = INT64_MAX;
191   left_bytes = current_consumption + max_carry;
192   if (left_bytes < current_consumption)
193   {
194     /* integer overflow, cap! */
195     left_bytes = INT64_MAX;
196   }
197   /* left_bytes now contains the number of bytes needed until
198      we have more savings than allowed */
199   if (left_bytes < 0)
200   {
201     /* having excess already */
202     delay = GNUNET_TIME_UNIT_ZERO;
203   }
204   else
205   {
206     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
207                                            left_bytes);
208     delay = GNUNET_TIME_relative_divide (delay,
209                                          av->available_bytes_per_s__);
210   }
211   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
212               "At %llu bps it will take us %s for %lld bytes to reach excess threshold\n",
213               (unsigned long long) av->available_bytes_per_s__,
214               GNUNET_STRINGS_relative_time_to_string (delay,
215                                                       GNUNET_NO),
216               (long long) left_bytes);
217   if (NULL != av->excess_task)
218     GNUNET_SCHEDULER_cancel (av->excess_task);
219   av->excess_task = GNUNET_SCHEDULER_add_delayed (delay,
220                                                   &excess_trigger,
221                                                   av);
222 }
223
224
225 /**
226  * Initialize bandwidth tracker.  Note that in addition to the
227  * 'max_carry_s' limit, we also always allow at least
228  * #GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
229  * bytes-per-second limit is so small that within 'max_carry_s' not
230  * even #GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
231  * ignored and replaced by #GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
232  * bytes).
233  *
234  * To stop notifications about updates and excess callbacks use
235  * #GNUNET_BANDWIDTH_tracker_notification_stop().
236  *
237  * @param av tracker to initialize
238  * @param update_cb callback to notify a client about the tracker being updated
239  * @param update_cb_cls cls for the callback
240  * @param bytes_per_second_limit initial limit to assume
241  * @param max_carry_s maximum number of seconds unused bandwidth
242  *        may accumulate before it expires
243  * @param excess_cb callback to notify if we have excess bandwidth
244  * @param excess_cb_cls closure for @a excess_cb
245  */
246 void
247 GNUNET_BANDWIDTH_tracker_init2 (struct GNUNET_BANDWIDTH_Tracker *av,
248                                 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
249                                 void *update_cb_cls,
250                                 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
251                                 uint32_t max_carry_s,
252                                 GNUNET_BANDWIDTH_ExcessNotificationCallback excess_cb,
253                                 void *excess_cb_cls)
254 {
255   av->update_cb = update_cb;
256   av->update_cb_cls = update_cb_cls;
257   av->consumption_since_last_update__ = 0;
258   av->last_update__ = GNUNET_TIME_absolute_get ();
259   av->available_bytes_per_s__ = ntohl (bytes_per_second_limit.value__);
260   av->max_carry_s__ = max_carry_s;
261   av->excess_cb = excess_cb;
262   av->excess_cb_cls = excess_cb_cls;
263   LOG (GNUNET_ERROR_TYPE_DEBUG,
264        "Tracker %p initialized with %u Bps and max carry %u\n",
265        av,
266        (unsigned int) av->available_bytes_per_s__,
267        (unsigned int) max_carry_s);
268   update_excess (av);
269 }
270
271
272 /**
273  * Initialize bandwidth tracker.  Note that in addition to the
274  * 'max_carry_s' limit, we also always allow at least
275  * #GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
276  * bytes-per-second limit is so small that within 'max_carry_s' not
277  * even #GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
278  * ignored and replaced by #GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
279  * bytes).
280  *
281  * @param av tracker to initialize
282  * @param update_cb callback to notify a client about the tracker being updated
283  * @param update_cb_cls cls for the callback
284  * @param bytes_per_second_limit initial limit to assume
285  * @param max_carry_s maximum number of seconds unused bandwidth
286  *        may accumulate before it expires
287  */
288 void
289 GNUNET_BANDWIDTH_tracker_init (struct GNUNET_BANDWIDTH_Tracker *av,
290                                GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
291                                void *update_cb_cls,
292                                struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
293                                uint32_t max_carry_s)
294 {
295   GNUNET_BANDWIDTH_tracker_init2 (av, update_cb,
296                                   update_cb_cls,
297                                   bytes_per_second_limit,
298                                   max_carry_s,
299                                   NULL, NULL);
300 }
301
302
303 /**
304  * Stop notifying about tracker updates and excess notifications
305  *
306  * @param av the respective trackers
307  */
308 void
309 GNUNET_BANDWIDTH_tracker_notification_stop (struct GNUNET_BANDWIDTH_Tracker *av)
310 {
311   if (NULL != av->excess_task)
312     GNUNET_SCHEDULER_cancel (av->excess_task);
313   av->excess_task = NULL;
314   av->excess_cb = NULL;
315   av->excess_cb_cls = NULL;
316   av->update_cb = NULL;
317   av->update_cb_cls = NULL;
318 }
319
320
321 /**
322  * Update the tracker, looking at the current time and
323  * bandwidth consumption data.
324  *
325  * @param av tracker to update
326  */
327 static void
328 update_tracker (struct GNUNET_BANDWIDTH_Tracker *av)
329 {
330   struct GNUNET_TIME_Absolute now;
331   struct GNUNET_TIME_Relative delta;
332   uint64_t delta_time;
333   uint64_t delta_avail;
334   uint64_t left_bytes;
335   uint64_t max_carry;
336
337   now = GNUNET_TIME_absolute_get ();
338   delta_time = now.abs_value_us - av->last_update__.abs_value_us;
339   delta_avail =
340       (delta_time * ((unsigned long long) av->available_bytes_per_s__) +
341        500000LL) / 1000000LL;
342   av->consumption_since_last_update__ -= delta_avail;
343   av->last_update__ = now;
344   if (av->consumption_since_last_update__ < 0)
345   {
346     left_bytes = - av->consumption_since_last_update__;
347     max_carry = ((unsigned long long) av->available_bytes_per_s__) *
348                 av->max_carry_s__;
349     if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
350       max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
351     if (max_carry > INT64_MAX)
352       max_carry = INT64_MAX;
353     if (max_carry > left_bytes)
354       av->consumption_since_last_update__ = - left_bytes;
355     else
356       av->consumption_since_last_update__ = - max_carry;
357   }
358   delta.rel_value_us = delta_time;
359   LOG (GNUNET_ERROR_TYPE_DEBUG,
360        "Tracker %p updated, consumption at %lld at %u Bps, last update was %s ago\n",
361        av,
362        (long long) av->consumption_since_last_update__,
363        (unsigned int) av->available_bytes_per_s__,
364        GNUNET_STRINGS_relative_time_to_string (delta,
365                                                GNUNET_YES));
366 }
367
368
369 /**
370  * Notify the tracker that a certain number of bytes of bandwidth have
371  * been consumed.  Note that it is legal to consume bytes even if not
372  * enough bandwidth is available (in that case,
373  * #GNUNET_BANDWIDTH_tracker_get_delay may return non-zero delay values
374  * even for a size of zero for a while).
375  *
376  * @param av tracker to update
377  * @param size number of bytes consumed
378  * @return #GNUNET_YES if this consumption is above the limit
379  */
380 int
381 GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av,
382                                   ssize_t size)
383 {
384   int64_t nc;
385
386   LOG (GNUNET_ERROR_TYPE_DEBUG,
387        "Tracker %p consumes %d bytes\n",
388        av,
389        (int) size);
390   if (size > 0)
391   {
392     nc = av->consumption_since_last_update__ + size;
393     if (nc < av->consumption_since_last_update__)
394     {
395       /* integer overflow, very bad */
396       GNUNET_break (0);
397       return GNUNET_SYSERR;
398     }
399     av->consumption_since_last_update__ = nc;
400     update_tracker (av);
401     update_excess (av);
402     if (av->consumption_since_last_update__ > 0)
403     {
404       LOG (GNUNET_ERROR_TYPE_DEBUG,
405            "Tracker %p consumption %llu bytes above limit\n",
406            av,
407            (unsigned long long) av->consumption_since_last_update__);
408       return GNUNET_YES;
409     }
410   }
411   else
412   {
413     nc = av->consumption_since_last_update__ + size;
414     if (nc > av->consumption_since_last_update__)
415     {
416       /* integer underflow, very bad */
417       GNUNET_break (0);
418       return GNUNET_SYSERR;
419     }
420     av->consumption_since_last_update__ = nc;
421     update_excess (av);
422   }
423   return GNUNET_NO;
424 }
425
426
427 /**
428  * Compute how long we should wait until consuming 'size'
429  * bytes of bandwidth in order to stay within the given
430  * quota.
431  *
432  * @param av tracker to query
433  * @param size number of bytes we would like to consume
434  * @return time in ms to wait for consumption to be OK
435  */
436 struct GNUNET_TIME_Relative
437 GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av,
438                                     size_t size)
439 {
440   struct GNUNET_TIME_Relative ret;
441   int64_t bytes_needed;
442
443   if (0 == av->available_bytes_per_s__)
444   {
445     LOG (GNUNET_ERROR_TYPE_DEBUG,
446          "Tracker %p delay is infinity\n", av);
447     return GNUNET_TIME_UNIT_FOREVER_REL;
448   }
449   update_tracker (av);
450   bytes_needed = size + av->consumption_since_last_update__;
451   if (bytes_needed <= 0)
452   {
453     LOG (GNUNET_ERROR_TYPE_DEBUG,
454          "Tracker %p delay for %u bytes is zero\n", av,
455          (unsigned int) size);
456     return GNUNET_TIME_UNIT_ZERO;
457   }
458   ret.rel_value_us =
459       (1000LL * 1000LL * bytes_needed) /
460       (unsigned long long) av->available_bytes_per_s__;
461   LOG (GNUNET_ERROR_TYPE_DEBUG,
462        "Tracker %p delay for %u bytes is %s\n",
463        av,
464        (unsigned int) size,
465        GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
466   return ret;
467 }
468
469
470 /**
471  * Compute how many bytes are available for consumption right now.
472  * quota.
473  *
474  * @param av tracker to query
475  * @return number of bytes available for consumption right now
476  */
477 int64_t
478 GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av)
479 {
480   struct GNUNET_BANDWIDTH_Value32NBO bps;
481   uint64_t avail;
482   int64_t used;
483
484   update_tracker (av);
485   bps = GNUNET_BANDWIDTH_value_init (av->available_bytes_per_s__);
486   avail =
487       GNUNET_BANDWIDTH_value_get_available_until (bps,
488                                                   GNUNET_TIME_absolute_get_duration
489                                                   (av->last_update__));
490   used = av->consumption_since_last_update__;
491   LOG (GNUNET_ERROR_TYPE_DEBUG,
492        "Tracker %p available bandwidth is %lld bytes\n", av,
493        (long long) (int64_t) (avail - used));
494   return (int64_t) (avail - used);
495 }
496
497
498 /**
499  * Update quota of bandwidth tracker.
500  *
501  * @param av tracker to initialize
502  * @param bytes_per_second_limit new limit to assume
503  */
504 void
505 GNUNET_BANDWIDTH_tracker_update_quota (struct GNUNET_BANDWIDTH_Tracker *av,
506                                        struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit)
507 {
508   uint32_t old_limit;
509   uint32_t new_limit;
510
511   new_limit = ntohl (bytes_per_second_limit.value__);
512   LOG (GNUNET_ERROR_TYPE_DEBUG,
513        "Tracker %p bandwidth changed to %u Bps\n", av,
514        (unsigned int) new_limit);
515   update_tracker (av);
516   old_limit = av->available_bytes_per_s__;
517   av->available_bytes_per_s__ = new_limit;
518   if (NULL != av->update_cb)
519     av->update_cb (av->update_cb_cls);
520   if (old_limit > new_limit)
521     update_tracker (av);        /* maximum excess might be less now */
522   update_excess (av);
523 }
524
525
526 /* end of bandwidth.c */