small API change: do no longer pass rarely needed GNUNET_SCHEDULER_TaskContext to...
[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   LOG (GNUNET_ERROR_TYPE_DEBUG,
44        "Initializing bandwidth of %u Bps\n",
45        (unsigned int) bytes_per_second);
46   ret.value__ = htonl (bytes_per_second);
47   return ret;
48 }
49
50
51 /**
52  * Compute the MIN of two bandwidth values.
53  *
54  * @param b1 first value
55  * @param b2 second value
56  * @return the min of b1 and b2
57  */
58 struct GNUNET_BANDWIDTH_Value32NBO
59 GNUNET_BANDWIDTH_value_min (struct GNUNET_BANDWIDTH_Value32NBO b1,
60                             struct GNUNET_BANDWIDTH_Value32NBO b2)
61 {
62   return
63       GNUNET_BANDWIDTH_value_init (GNUNET_MIN
64                                    (ntohl (b1.value__),
65                                     ntohl (b2.value__)));
66 }
67
68
69 /**
70  * Compute the MAX of two bandwidth values.
71  *
72  * @param b1 first value
73  * @param b2 second value
74  * @return the min of b1 and b2
75  */
76 struct GNUNET_BANDWIDTH_Value32NBO
77 GNUNET_BANDWIDTH_value_max (struct GNUNET_BANDWIDTH_Value32NBO b1,
78                             struct GNUNET_BANDWIDTH_Value32NBO b2)
79 {
80   return
81       GNUNET_BANDWIDTH_value_init (GNUNET_MAX
82                                    (ntohl (b1.value__),
83                                     ntohl (b2.value__)));
84 }
85
86
87 /**
88  * At the given bandwidth, calculate how much traffic will be
89  * available until the given deadline.
90  *
91  * @param bps bandwidth
92  * @param deadline when is the deadline
93  * @return number of bytes available at bps until deadline
94  */
95 uint64_t
96 GNUNET_BANDWIDTH_value_get_available_until (struct GNUNET_BANDWIDTH_Value32NBO bps,
97                                             struct GNUNET_TIME_Relative deadline)
98 {
99   uint64_t b;
100
101   b = ntohl (bps.value__);
102   LOG (GNUNET_ERROR_TYPE_DEBUG,
103        "Bandwidth has %llu bytes available until deadline in %s\n",
104        (unsigned long long) ((b * deadline.rel_value_us + 500000LL) / 1000000LL),
105        GNUNET_STRINGS_relative_time_to_string (deadline, GNUNET_YES));
106   return (b * deadline.rel_value_us + 500000LL) / 1000000LL;
107 }
108
109
110 /**
111  * At the given bandwidth, calculate how long it would take for
112  * @a size bytes to be transmitted.
113  *
114  * @param bps bandwidth
115  * @param size number of bytes we want to have available
116  * @return how long it would take
117  */
118 struct GNUNET_TIME_Relative
119 GNUNET_BANDWIDTH_value_get_delay_for (struct GNUNET_BANDWIDTH_Value32NBO bps,
120                                       uint64_t size)
121 {
122   uint64_t b;
123   struct GNUNET_TIME_Relative ret;
124
125   b = ntohl (bps.value__);
126   if (0 == b)
127   {
128     LOG (GNUNET_ERROR_TYPE_DEBUG,
129          "Bandwidth suggests delay of infinity (zero bandwidth)\n");
130     return GNUNET_TIME_UNIT_FOREVER_REL;
131   }
132   ret.rel_value_us = size * 1000LL * 1000LL / b;
133   LOG (GNUNET_ERROR_TYPE_DEBUG,
134        "Bandwidth suggests delay of %s for %llu bytes of traffic\n",
135        GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES),
136        (unsigned long long) size);
137   return ret;
138 }
139
140
141 /**
142  * Task run whenever we hit the bandwidth limit for a tracker.
143  *
144  * @param cls the `struct GNUNET_BANDWIDTH_Tracker`
145  */
146 static void
147 excess_trigger (void *cls)
148 {
149   struct GNUNET_BANDWIDTH_Tracker *av = cls;
150
151   av->excess_task = NULL;
152
153   if (NULL != av->excess_cb)
154     av->excess_cb (av->excess_cb_cls);
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   /* negative current_consumption means that we have savings */
181   max_carry = av->available_bytes_per_s__ * av->max_carry_s__;
182   if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
183     max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
184   left_bytes = max_carry + current_consumption;
185   /* left_bytes now contains the number of bytes needed until
186      we have more savings than allowed */
187   if (left_bytes < 0)
188   {
189     /* having excess already */
190     delay = GNUNET_TIME_UNIT_ZERO;
191   }
192   else
193   {
194     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
195                                            left_bytes);
196     delay = GNUNET_TIME_relative_divide (delay,
197                                          av->available_bytes_per_s__);
198   }
199   if (NULL != av->excess_task)
200     GNUNET_SCHEDULER_cancel (av->excess_task);
201   av->excess_task = GNUNET_SCHEDULER_add_delayed (delay,
202                                                   &excess_trigger,
203                                                   av);
204 }
205
206
207 /**
208  * Initialize bandwidth tracker.  Note that in addition to the
209  * 'max_carry_s' limit, we also always allow at least
210  * #GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
211  * bytes-per-second limit is so small that within 'max_carry_s' not
212  * even #GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
213  * ignored and replaced by #GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
214  * bytes).
215  *
216  * To stop notifications about updates and excess callbacks use
217  * #GNUNET_BANDWIDTH_tracker_notification_stop().
218  *
219  * @param av tracker to initialize
220  * @param update_cb callback to notify a client about the tracker being updated
221  * @param update_cb_cls cls for the callback
222  * @param bytes_per_second_limit initial limit to assume
223  * @param max_carry_s maximum number of seconds unused bandwidth
224  *        may accumulate before it expires
225  * @param excess_cb callback to notify if we have excess bandwidth
226  * @param excess_cb_cls closure for @a excess_cb
227  */
228 void
229 GNUNET_BANDWIDTH_tracker_init2 (struct GNUNET_BANDWIDTH_Tracker *av,
230                                 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
231                                 void *update_cb_cls,
232                                 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
233                                 uint32_t max_carry_s,
234                                 GNUNET_BANDWIDTH_ExcessNotificationCallback excess_cb,
235                                 void *excess_cb_cls)
236 {
237   av->update_cb = update_cb;
238   av->update_cb_cls = update_cb_cls;
239   av->consumption_since_last_update__ = 0;
240   av->last_update__ = GNUNET_TIME_absolute_get ();
241   av->available_bytes_per_s__ = ntohl (bytes_per_second_limit.value__);
242   av->max_carry_s__ = max_carry_s;
243   av->excess_cb = excess_cb;
244   av->excess_cb_cls = excess_cb_cls;
245   LOG (GNUNET_ERROR_TYPE_DEBUG,
246        "Tracker %p initialized with %u Bps and max carry %u\n",
247        av,
248        (unsigned int) av->available_bytes_per_s__,
249        (unsigned int) max_carry_s);
250   update_excess (av);
251 }
252
253
254 /**
255  * Initialize bandwidth tracker.  Note that in addition to the
256  * 'max_carry_s' limit, we also always allow at least
257  * GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
258  * bytes-per-second limit is so small that within 'max_carry_s' not
259  * even GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
260  * ignored and replaced by GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
261  * bytes).
262  *
263  * @param av tracker to initialize
264  * @param update_cb callback to notify a client about the tracker being updated
265  * @param update_cb_cls cls for the callback
266  * @param bytes_per_second_limit initial limit to assume
267  * @param max_carry_s maximum number of seconds unused bandwidth
268  *        may accumulate before it expires
269  */
270 void
271 GNUNET_BANDWIDTH_tracker_init (struct GNUNET_BANDWIDTH_Tracker *av,
272                                GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
273                                void *update_cb_cls,
274                                struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
275                                uint32_t max_carry_s)
276 {
277   GNUNET_BANDWIDTH_tracker_init2 (av, update_cb,
278                                   update_cb_cls,
279                                   bytes_per_second_limit,
280                                   max_carry_s,
281                                   NULL, NULL);
282 }
283
284
285 /**
286  * Stop notifying about tracker updates and excess notifications
287  *
288  * @param av the respective trackers
289  */
290 void
291 GNUNET_BANDWIDTH_tracker_notification_stop (struct GNUNET_BANDWIDTH_Tracker *av)
292 {
293   if (NULL != av->excess_task)
294     GNUNET_SCHEDULER_cancel (av->excess_task);
295   av->excess_task = NULL;
296   av->excess_cb = NULL;
297   av->excess_cb_cls = NULL;
298   av->update_cb = NULL;
299   av->update_cb_cls = NULL;
300 }
301
302
303
304 /**
305  * Update the tracker, looking at the current time and
306  * bandwidth consumption data.
307  *
308  * @param av tracker to update
309  */
310 static void
311 update_tracker (struct GNUNET_BANDWIDTH_Tracker *av)
312 {
313   struct GNUNET_TIME_Absolute now;
314   struct GNUNET_TIME_Relative delta;
315   uint64_t delta_time;
316   uint64_t delta_avail;
317   uint64_t left_bytes;
318   uint64_t max_carry;
319
320   now = GNUNET_TIME_absolute_get ();
321   delta_time = now.abs_value_us - av->last_update__.abs_value_us;
322   delta_avail =
323       (delta_time * ((unsigned long long) av->available_bytes_per_s__) +
324        500000LL) / 1000000LL;
325   av->consumption_since_last_update__ -= delta_avail;
326   av->last_update__ = now;
327   if (av->consumption_since_last_update__ < 0)
328   {
329     left_bytes = -av->consumption_since_last_update__;
330     max_carry = av->available_bytes_per_s__ * av->max_carry_s__;
331     if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
332       max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
333     if (max_carry > left_bytes)
334       av->consumption_since_last_update__ = -left_bytes;
335     else
336       av->consumption_since_last_update__ = -max_carry;
337   }
338   delta.rel_value_us = delta_time;
339   LOG (GNUNET_ERROR_TYPE_DEBUG,
340        "Tracker %p updated, have %u Bps, last update was %s ago\n", av,
341        (unsigned int) av->available_bytes_per_s__,
342        GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES));
343 }
344
345
346 /**
347  * Notify the tracker that a certain number of bytes of bandwidth have
348  * been consumed.  Note that it is legal to consume bytes even if not
349  * enough bandwidth is available (in that case,
350  * #GNUNET_BANDWIDTH_tracker_get_delay may return non-zero delay values
351  * even for a size of zero for a while).
352  *
353  * @param av tracker to update
354  * @param size number of bytes consumed
355  * @return #GNUNET_YES if this consumption is above the limit
356  */
357 int
358 GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av,
359                                   ssize_t size)
360 {
361   int64_t nc;
362
363   LOG (GNUNET_ERROR_TYPE_DEBUG,
364        "Tracker %p consumes %d bytes\n",
365        av,
366        (int) size);
367   if (size > 0)
368   {
369     nc = av->consumption_since_last_update__ + size;
370     if (nc < av->consumption_since_last_update__)
371     {
372       GNUNET_break (0);
373       return GNUNET_SYSERR;
374     }
375     av->consumption_since_last_update__ = nc;
376     update_tracker (av);
377     update_excess (av);
378     if (av->consumption_since_last_update__ > 0)
379     {
380       LOG (GNUNET_ERROR_TYPE_DEBUG,
381            "Tracker %p consumption %llu bytes above limit\n", av,
382            (unsigned long long) av->consumption_since_last_update__);
383       return GNUNET_YES;
384     }
385   }
386   else
387   {
388     av->consumption_since_last_update__ += size;
389     update_excess (av);
390   }
391   return GNUNET_NO;
392 }
393
394
395 /**
396  * Compute how long we should wait until consuming 'size'
397  * bytes of bandwidth in order to stay within the given
398  * quota.
399  *
400  * @param av tracker to query
401  * @param size number of bytes we would like to consume
402  * @return time in ms to wait for consumption to be OK
403  */
404 struct GNUNET_TIME_Relative
405 GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av,
406                                     size_t size)
407 {
408   struct GNUNET_TIME_Relative ret;
409   int64_t bytes_needed;
410
411   if (0 == av->available_bytes_per_s__)
412   {
413     LOG (GNUNET_ERROR_TYPE_DEBUG,
414          "Tracker %p delay is infinity\n", av);
415     return GNUNET_TIME_UNIT_FOREVER_REL;
416   }
417   update_tracker (av);
418   bytes_needed = size + av->consumption_since_last_update__;
419   if (bytes_needed <= 0)
420   {
421     LOG (GNUNET_ERROR_TYPE_DEBUG,
422          "Tracker %p delay for %u bytes is zero\n", av,
423          (unsigned int) size);
424     return GNUNET_TIME_UNIT_ZERO;
425   }
426   ret.rel_value_us =
427       (1000LL * 1000LL * bytes_needed) /
428       (unsigned long long) av->available_bytes_per_s__;
429   LOG (GNUNET_ERROR_TYPE_DEBUG,
430        "Tracker %p delay for %u bytes is %s\n",
431        av, (unsigned int) size,
432        GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
433   return ret;
434 }
435
436
437 /**
438  * Compute how many bytes are available for consumption right now.
439  * quota.
440  *
441  * @param av tracker to query
442  * @return number of bytes available for consumption right now
443  */
444 int64_t
445 GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av)
446 {
447   struct GNUNET_BANDWIDTH_Value32NBO bps;
448   uint64_t avail;
449   int64_t used;
450
451   update_tracker (av);
452   bps = GNUNET_BANDWIDTH_value_init (av->available_bytes_per_s__);
453   avail =
454       GNUNET_BANDWIDTH_value_get_available_until (bps,
455                                                   GNUNET_TIME_absolute_get_duration
456                                                   (av->last_update__));
457   used = av->consumption_since_last_update__;
458   LOG (GNUNET_ERROR_TYPE_DEBUG,
459        "Tracker %p available bandwidth is %lld bytes\n", av,
460        (long long) (int64_t) (avail - used));
461   return (int64_t) (avail - used);
462 }
463
464
465 /**
466  * Update quota of bandwidth tracker.
467  *
468  * @param av tracker to initialize
469  * @param bytes_per_second_limit new limit to assume
470  */
471 void
472 GNUNET_BANDWIDTH_tracker_update_quota (struct GNUNET_BANDWIDTH_Tracker *av,
473                                        struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit)
474 {
475   uint32_t old_limit;
476   uint32_t new_limit;
477
478   new_limit = ntohl (bytes_per_second_limit.value__);
479   LOG (GNUNET_ERROR_TYPE_DEBUG,
480        "Tracker %p bandwidth changed to %u Bps\n", av,
481        (unsigned int) new_limit);
482   update_tracker (av);
483   old_limit = av->available_bytes_per_s__;
484   av->available_bytes_per_s__ = new_limit;
485   if (NULL != av->update_cb)
486     av->update_cb (av->update_cb_cls);
487   if (old_limit > new_limit)
488     update_tracker (av);        /* maximum excess might be less now */
489   update_excess (av);
490 }
491
492
493 /* end of bandwidth.c */