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