- refactor to check messages from both enc systems
[oweals/gnunet.git] / src / util / bandwidth.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2010, 2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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  * @param tc scheduler context
146  */
147 static void
148 excess_trigger (void *cls,
149                 const struct GNUNET_SCHEDULER_TaskContext *tc)
150 {
151   struct GNUNET_BANDWIDTH_Tracker *av = cls;
152
153   av->excess_task = NULL;
154
155   if (NULL != av->excess_cb)
156     av->excess_cb (av->excess_cb_cls);
157 }
158
159
160 /**
161  * Recalculate when we might need to call the excess callback.
162  */
163 static void
164 update_excess (struct GNUNET_BANDWIDTH_Tracker *av)
165 {
166   struct GNUNET_TIME_Relative delay;
167   struct GNUNET_TIME_Absolute now;
168   uint64_t delta_time;
169   uint64_t delta_avail;
170   int64_t left_bytes;
171   uint64_t max_carry;
172   int64_t current_consumption;
173
174   if (NULL == av->excess_cb)
175     return; /* nothing to do */
176   now = GNUNET_TIME_absolute_get ();
177   delta_time = now.abs_value_us - av->last_update__.abs_value_us;
178   delta_avail =
179       (delta_time * ((unsigned long long) av->available_bytes_per_s__) +
180        500000LL) / 1000000LL;
181   current_consumption = av->consumption_since_last_update__ - delta_avail;
182   /* negative current_consumption means that we have savings */
183   max_carry = av->available_bytes_per_s__ * av->max_carry_s__;
184   if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
185     max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
186   left_bytes = max_carry + current_consumption;
187   /* left_bytes now contains the number of bytes needed until
188      we have more savings than allowed */
189   if (left_bytes < 0)
190   {
191     /* having excess already */
192     delay = GNUNET_TIME_UNIT_ZERO;
193   }
194   else
195   {
196     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
197                                            left_bytes);
198     delay = GNUNET_TIME_relative_divide (delay,
199                                          av->available_bytes_per_s__);
200   }
201   if (NULL != av->excess_task)
202     GNUNET_SCHEDULER_cancel (av->excess_task);
203   av->excess_task = GNUNET_SCHEDULER_add_delayed (delay,
204                                                   &excess_trigger,
205                                                   av);
206 }
207
208
209 /**
210  * Initialize bandwidth tracker.  Note that in addition to the
211  * 'max_carry_s' limit, we also always allow at least
212  * #GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
213  * bytes-per-second limit is so small that within 'max_carry_s' not
214  * even #GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
215  * ignored and replaced by #GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
216  * bytes).
217  *
218  * To stop notifications about updates and excess callbacks use
219  * #GNUNET_BANDWIDTH_tracker_notification_stop
220  *
221  * @param av tracker to initialize
222  * @param update_cb callback to notify a client about the tracker being updated
223  * @param update_cb_cls cls for the callback
224  * @param bytes_per_second_limit initial limit to assume
225  * @param max_carry_s maximum number of seconds unused bandwidth
226  *        may accumulate before it expires
227  * @param excess_cb callback to notify if we have excess bandwidth
228  * @param excess_cb_cls closure for @a excess_cb
229  */
230 void
231 GNUNET_BANDWIDTH_tracker_init2 (struct GNUNET_BANDWIDTH_Tracker *av,
232                                 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
233                                 void *update_cb_cls,
234                                 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
235                                 uint32_t max_carry_s,
236                                 GNUNET_BANDWIDTH_ExcessNotificationCallback excess_cb,
237                                 void *excess_cb_cls)
238 {
239   av->update_cb = update_cb;
240   av->update_cb_cls = update_cb_cls;
241   av->consumption_since_last_update__ = 0;
242   av->last_update__ = GNUNET_TIME_absolute_get ();
243   av->available_bytes_per_s__ = ntohl (bytes_per_second_limit.value__);
244   av->max_carry_s__ = max_carry_s;
245   av->excess_cb = excess_cb;
246   av->excess_cb_cls = excess_cb_cls;
247   LOG (GNUNET_ERROR_TYPE_DEBUG,
248        "Tracker %p initialized with %u Bps and max carry %u\n",
249        av,
250        (unsigned int) av->available_bytes_per_s__,
251        (unsigned int) max_carry_s);
252   update_excess (av);
253 }
254
255
256 /**
257  * Initialize bandwidth tracker.  Note that in addition to the
258  * 'max_carry_s' limit, we also always allow at least
259  * GNUNET_SERVER_MAX_MESSAGE_SIZE to accumulate.  So if the
260  * bytes-per-second limit is so small that within 'max_carry_s' not
261  * even GNUNET_SERVER_MAX_MESSAGE_SIZE is allowed to accumulate, it is
262  * ignored and replaced by GNUNET_SERVER_MAX_MESSAGE_SIZE (which is in
263  * bytes).
264  *
265  * @param av tracker to initialize
266  * @param update_cb callback to notify a client about the tracker being updated
267  * @param update_cb_cls cls for the callback
268  * @param bytes_per_second_limit initial limit to assume
269  * @param max_carry_s maximum number of seconds unused bandwidth
270  *        may accumulate before it expires
271  */
272 void
273 GNUNET_BANDWIDTH_tracker_init (struct GNUNET_BANDWIDTH_Tracker *av,
274                                GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
275                                void *update_cb_cls,
276                                struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
277                                uint32_t max_carry_s)
278 {
279   GNUNET_BANDWIDTH_tracker_init2 (av, update_cb,
280                                   update_cb_cls,
281                                   bytes_per_second_limit,
282                                   max_carry_s,
283                                   NULL, NULL);
284 }
285
286
287 /**
288  * Stop notifying about tracker updates and excess notifications
289  *
290  * @param av the respective trackers
291  */
292 void
293 GNUNET_BANDWIDTH_tracker_notification_stop (struct GNUNET_BANDWIDTH_Tracker *av)
294 {
295   if (NULL != av->excess_task)
296     GNUNET_SCHEDULER_cancel (av->excess_task);
297   av->excess_task = NULL;
298   av->excess_cb = NULL;
299   av->excess_cb_cls = NULL;
300   av->update_cb = NULL;
301   av->update_cb_cls = NULL;
302 }
303
304
305
306 /**
307  * Update the tracker, looking at the current time and
308  * bandwidth consumption data.
309  *
310  * @param av tracker to update
311  */
312 static void
313 update_tracker (struct GNUNET_BANDWIDTH_Tracker *av)
314 {
315   struct GNUNET_TIME_Absolute now;
316   struct GNUNET_TIME_Relative delta;
317   uint64_t delta_time;
318   uint64_t delta_avail;
319   uint64_t left_bytes;
320   uint64_t max_carry;
321
322   now = GNUNET_TIME_absolute_get ();
323   delta_time = now.abs_value_us - av->last_update__.abs_value_us;
324   delta_avail =
325       (delta_time * ((unsigned long long) av->available_bytes_per_s__) +
326        500000LL) / 1000000LL;
327   av->consumption_since_last_update__ -= delta_avail;
328   av->last_update__ = now;
329   if (av->consumption_since_last_update__ < 0)
330   {
331     left_bytes = -av->consumption_since_last_update__;
332     max_carry = av->available_bytes_per_s__ * av->max_carry_s__;
333     if (max_carry < GNUNET_SERVER_MAX_MESSAGE_SIZE)
334       max_carry = GNUNET_SERVER_MAX_MESSAGE_SIZE;
335     if (max_carry > left_bytes)
336       av->consumption_since_last_update__ = -left_bytes;
337     else
338       av->consumption_since_last_update__ = -max_carry;
339   }
340   delta.rel_value_us = delta_time;
341   LOG (GNUNET_ERROR_TYPE_DEBUG,
342        "Tracker %p updated, have %u Bps, last update was %s ago\n", av,
343        (unsigned int) av->available_bytes_per_s__,
344        GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES));
345 }
346
347
348 /**
349  * Notify the tracker that a certain number of bytes of bandwidth have
350  * been consumed.  Note that it is legal to consume bytes even if not
351  * enough bandwidth is available (in that case,
352  * #GNUNET_BANDWIDTH_tracker_get_delay may return non-zero delay values
353  * even for a size of zero for a while).
354  *
355  * @param av tracker to update
356  * @param size number of bytes consumed
357  * @return #GNUNET_YES if this consumption is above the limit
358  */
359 int
360 GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av,
361                                   ssize_t size)
362 {
363   int64_t nc;
364
365   LOG (GNUNET_ERROR_TYPE_DEBUG,
366        "Tracker %p consumes %d bytes\n",
367        av,
368        (int) size);
369   if (size > 0)
370   {
371     nc = av->consumption_since_last_update__ + size;
372     if (nc < av->consumption_since_last_update__)
373     {
374       GNUNET_break (0);
375       return GNUNET_SYSERR;
376     }
377     av->consumption_since_last_update__ = nc;
378     update_tracker (av);
379     update_excess (av);
380     if (av->consumption_since_last_update__ > 0)
381     {
382       LOG (GNUNET_ERROR_TYPE_DEBUG,
383            "Tracker %p consumption %llu bytes above limit\n", av,
384            (unsigned long long) av->consumption_since_last_update__);
385       return GNUNET_YES;
386     }
387   }
388   else
389   {
390     av->consumption_since_last_update__ += size;
391     update_excess (av);
392   }
393   return GNUNET_NO;
394 }
395
396
397 /**
398  * Compute how long we should wait until consuming 'size'
399  * bytes of bandwidth in order to stay within the given
400  * quota.
401  *
402  * @param av tracker to query
403  * @param size number of bytes we would like to consume
404  * @return time in ms to wait for consumption to be OK
405  */
406 struct GNUNET_TIME_Relative
407 GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av,
408                                     size_t size)
409 {
410   struct GNUNET_TIME_Relative ret;
411   int64_t bytes_needed;
412
413   if (0 == av->available_bytes_per_s__)
414   {
415     LOG (GNUNET_ERROR_TYPE_DEBUG,
416          "Tracker %p delay is infinity\n", av);
417     return GNUNET_TIME_UNIT_FOREVER_REL;
418   }
419   update_tracker (av);
420   bytes_needed = size + av->consumption_since_last_update__;
421   if (bytes_needed <= 0)
422   {
423     LOG (GNUNET_ERROR_TYPE_DEBUG,
424          "Tracker %p delay for %u bytes is zero\n", av,
425          (unsigned int) size);
426     return GNUNET_TIME_UNIT_ZERO;
427   }
428   ret.rel_value_us =
429       (1000LL * 1000LL * bytes_needed) /
430       (unsigned long long) av->available_bytes_per_s__;
431   LOG (GNUNET_ERROR_TYPE_DEBUG,
432        "Tracker %p delay for %u bytes is %s\n",
433        av, (unsigned int) size,
434        GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES));
435   return ret;
436 }
437
438
439 /**
440  * Compute how many bytes are available for consumption right now.
441  * quota.
442  *
443  * @param av tracker to query
444  * @return number of bytes available for consumption right now
445  */
446 int64_t
447 GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av)
448 {
449   struct GNUNET_BANDWIDTH_Value32NBO bps;
450   uint64_t avail;
451   int64_t used;
452
453   update_tracker (av);
454   bps = GNUNET_BANDWIDTH_value_init (av->available_bytes_per_s__);
455   avail =
456       GNUNET_BANDWIDTH_value_get_available_until (bps,
457                                                   GNUNET_TIME_absolute_get_duration
458                                                   (av->last_update__));
459   used = av->consumption_since_last_update__;
460   LOG (GNUNET_ERROR_TYPE_DEBUG,
461        "Tracker %p available bandwidth is %lld bytes\n", av,
462        (long long) (int64_t) (avail - used));
463   return (int64_t) (avail - used);
464 }
465
466
467 /**
468  * Update quota of bandwidth tracker.
469  *
470  * @param av tracker to initialize
471  * @param bytes_per_second_limit new limit to assume
472  */
473 void
474 GNUNET_BANDWIDTH_tracker_update_quota (struct GNUNET_BANDWIDTH_Tracker *av,
475                                        struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit)
476 {
477   uint32_t old_limit;
478   uint32_t new_limit;
479
480   new_limit = ntohl (bytes_per_second_limit.value__);
481   LOG (GNUNET_ERROR_TYPE_DEBUG,
482        "Tracker %p bandwidth changed to %u Bps\n", av,
483        (unsigned int) new_limit);
484   update_tracker (av);
485   old_limit = av->available_bytes_per_s__;
486   av->available_bytes_per_s__ = new_limit;
487   if (NULL != av->update_cb)
488     av->update_cb (av->update_cb_cls);
489   if (old_limit > new_limit)
490     update_tracker (av);        /* maximum excess might be less now */
491   update_excess (av);
492 }
493
494
495 /* end of bandwidth.c */