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