-further simplify
[oweals/gnunet.git] / src / ats / plugin_ats_proportional.c
1 /*
2  This file is part of GNUnet.
3  Copyright (C) 2011-2015 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 ats/plugin_ats_proportional.c
23  * @brief ATS proportional solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_ats_plugin.h"
30 #include "gnunet_ats_service.h"
31 #include "gnunet-service-ats_addresses.h"
32
33 #define PROP_STABILITY_FACTOR 1.25
34
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "ats-proportional",__VA_ARGS__)
37
38
39 /**
40  *
41  * NOTE: Do not change this documentation. This documentation is based
42  * on gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
43  * use build_txt.sh to generate plaintext output
44  *
45  * ATS addresses : proportional solver
46  *
47  *    The proportional solver ("proportional") distributes the available
48  *    bandwidth fair over all the addresses influenced by the
49  *    preference values. For each available network type an in- and
50  *    outbound quota is configured and the bandwidth available in
51  *    these networks is distributed over the addresses.  The solver
52  *    first assigns every addresses the minimum amount of bandwidth
53  *    #GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT and then distributes the
54  *    remaining bandwidth available according to the preference
55  *    values. For each peer only a single address gets bandwidth
56  *    assigned and only one address marked as active.  The most
57  *    important functionality for the solver is implemented in: *
58  *    find_address_it is an hashmap iterator returning the prefered
59  *    address for an peer * update_quota_per_network distributes
60  *    available bandwidth for a network over active addresses
61  *
62  *    Changes to addresses automatically have an impact on the the
63  *    bandwidth assigned to other addresses in the same network since
64  *    the solver distributes the remaining bandwidth over the
65  *    addresses in the network.  When changes to the addresses occur,
66  *    the solver first performs the changes, like adding or deleting
67  *    addresses, and then updates bandwidth assignment for the
68  *    affected network. Bandwidth assignment is only recalculated on
69  *    demand when an address is requested by a client for a peer or
70  *    when the addresses available have changed or an address changed
71  *    the network it is located in. When the bandwidth assignment has
72  *    changed the callback is called with the new bandwidth
73  *    assignments. The bandwidth distribution for a network is
74  *    recalculated due to: * address suggestion requests * address
75  *    deletions * address switching networks during address update *
76  *    preference changes
77  *
78  *     3.1 Data structures used
79  *
80  *    For each ATS network (e.g. WAN, LAN, loopback) a struct Network
81  *    is used to specify network related information as total adresses
82  *    and active addresses in this network and the configured in- and
83  *    outbound quota. Each network also contains a list of addresses
84  *    added to the solver located in this network. The proportional
85  *    solver uses the addresses' solver_information field to store the
86  *    proportional network it belongs to for each address.
87  *
88  *     3.2 Initializing
89  *
90  *    When the proportional solver is initialized the solver creates a
91  *    new solver handle and initializes the network structures with
92  *    the quotas passed from addresses and returns the handle solver.
93  *
94  *     3.3 Adding an address
95  *
96  *    When a new address is added to the solver using s_add, a lookup
97  *    for the network for this address is done and the address is
98  *    enqueued in in the linked list of the network.
99  *
100  *     3.4 Updating an address
101  *
102  *    The main purpose of address updates is to update the ATS
103  *    information for addresse selection. Important for the proportional
104  *    solver is when an address switches network it is located
105  *    in. This is common because addresses added by transport's
106  *    validation mechanism are commonly located in
107  *    #GNUNET_ATS_NET_UNSPECIFIED. Addresses in validation are located
108  *    in this network type and only if a connection is successful on
109  *    return of payload data transport switches to the real network
110  *    the address is located in.  When an address changes networks it
111  *    is first of all removed from the old network using the solver
112  *    API function #GAS_proportional_address_delete() and the network in
113  *    the address struct is updated. A lookup for the respective new
114  *    proportional network is done and stored in the addresse's
115  *    solver_information field. Next the address is re-added to the
116  *    solver using the solver API function
117  *    #GAS_proportional_address_add(). If the address was marked as in
118  *    active, the solver checks if bandwidth is available in the
119  *    network and if yes sets the address to active and updates the
120  *    bandwidth distribution in this network. If no bandwidth is
121  *    available it sets the bandwidth for this address to 0 and tries
122  *    to suggest an alternative address. If an alternative address was
123  *    found, addresses' callback is called for this address.
124  *
125  *     3.5 Deleting an address
126  *
127  *    When an address is removed from the solver, it removes the
128  *    respective address from the network and if the address was
129  *    marked as active, it updates the bandwidth distribution for this
130  *    network.
131  *
132  *     3.6 Requesting addresses
133  *
134  *    When an address is requested for a peer the solver performs a
135  *    lookup for the peer entry in addresses address hashmap and
136  *    selects the best address.  The selection of the most suitable
137  *    address is done in the find_address_it hashmap iterator
138  *    described in detail in section 3.7. If no address is returned,
139  *    no address can be suggested at the moment. If the address
140  *    returned is marked as active, the solver can return this
141  *    address. If the address is not marked as active, the solver
142  *    checks if another address belongign to this peer is marked as
143  *    active and marks the address as inactive, updates the bandwidth
144  *    for this address to 0, call the bandwidth changed callback for
145  *    this address due to the change and updates quota assignment for
146  *    the addresse's network. the now in-active address is belonging
147  *    to. The solver marks the new address as active and updates the
148  *    bandwidth assignment for this network.
149  *
150  *     3.7 Choosing addresses
151  *
152  *    Choosing the best possible address for suggestion is done by
153  *    iterating over all addresses of a peer stored in addresses'
154  *    hashmap and using the hashmap iterator find_address_it to select
155  *    the best available address.  Several checks are done when an
156  *    address is selected. First if this address is currently blocked
157  *    by addresses from being suggested. An address is blocked for the
158  *    duration of #ATS_BLOCKING_DELTA when it is suggested to
159  *    transport. Next it is checked if at least
160  *    #GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT bytes bandwidth is available
161  *    in the addresse's network, because suggesting an address without
162  *    bandwidth does not make sense. This also ensures that all active
163  *    addresses in this network get at least the minimum amount of
164  *    bandwidth assigned. In the next step the solver ensures that for
165  *    tcp connections inbound connections are prefered over outbound
166  *    connections. In the next stet the solver ensures that
167  *    connections are prefered in the following order: * connections
168  *    are already established and have bandwidth assigned *
169  *    connections with a shorter distance * connectes have a shorter
170  *    latency
171  *
172  *     3.8 Changing preferences
173  *
174  *     3.9 Shutdown
175  *
176  *    During shutdown all network entries and aging processes are
177  *    destroyed and freed.
178  *
179  *
180  * OLD DOCUMENTATION
181  *
182  * This solver assigns in and outbound bandwidth equally for all
183  * addresses in specific network type (WAN, LAN) based on configured
184  * in and outbound quota for this network.
185  *
186  * The solver is notified by addresses about changes to the addresses
187  * and recalculates the bandwith assigned if required. The solver
188  * notifies addresses by calling the GAS_bandwidth_changed_cb
189  * callback.
190  *
191  * - Initialization
192  *
193  *
194  *
195  *
196  * For each peer only a single is selected and marked as "active" in the address
197  * struct.
198  *
199  * E.g.:
200  *
201  * You have the networks WAN and LAN and quotas
202  * WAN_TOTAL_IN, WAN_TOTAL_OUT
203  * LAN_TOTAL_IN, LAN_TOTAL_OUT
204  *
205  * If you have x addresses in the network segment LAN, the quotas are
206  * QUOTA_PER_ADDRESS = LAN_TOTAL_OUT / x
207  *
208  * Quotas are automatically recalculated and reported back when addresses are
209  * - requested
210  *
211  */
212
213 /**
214  * Default value to assume for the proportionality factor,
215  * if none is given in the configuration.
216  */
217 #define PROPORTIONALITY_FACTOR 2.0
218
219
220 /**
221  * Address information stored for the proportional solver in the
222  * `solver_information` member of `struct GNUNET_ATS_Address`.
223  *
224  * They are also stored in the respective `struct Network`'s linked
225  * list.
226  */
227 struct AddressWrapper
228 {
229   /**
230    * Next in DLL
231    */
232   struct AddressWrapper *next;
233
234   /**
235    * Previous in DLL
236    */
237   struct AddressWrapper *prev;
238
239   /**
240    * The address
241    */
242   struct ATS_Address *addr;
243
244     /**
245    * Network scope this address is in
246    */
247   struct Network *network;
248
249   /**
250    * Inbound quota
251    */
252   uint32_t calculated_quota_in;
253
254   /**
255    * Outbound quota
256    */
257   uint32_t calculated_quota_out;
258
259   /**
260    * When was this address activated
261    */
262   struct GNUNET_TIME_Absolute activated;
263
264 };
265
266
267 /**
268  * Representation of a network
269  */
270 struct Network
271 {
272   /**
273    * Network description
274    */
275   const char *desc;
276
277   /**
278    * String for statistics total addresses
279    */
280   char *stat_total;
281
282   /**
283    * String for statistics active addresses
284    */
285   char *stat_active;
286
287   /**
288    * Linked list of addresses in this network: head
289    */
290   struct AddressWrapper *head;
291
292   /**
293    * Linked list of addresses in this network: tail
294    */
295   struct AddressWrapper *tail;
296
297   /**
298    * Total inbound quota
299    */
300   unsigned long long total_quota_in;
301
302   /**
303    * Total outbound quota
304    */
305   unsigned long long total_quota_out;
306
307   /**
308    * ATS network type
309    */
310   enum GNUNET_ATS_Network_Type type;
311
312   /**
313    * Number of active addresses for this network
314    */
315   unsigned int active_addresses;
316
317   /**
318    * Number of total addresses for this network
319    */
320   unsigned int total_addresses;
321
322 };
323
324
325 /**
326  * A handle for the proportional solver
327  */
328 struct GAS_PROPORTIONAL_Handle
329 {
330
331   /**
332    * Our execution environment.
333    */
334   struct GNUNET_ATS_PluginEnvironment *env;
335
336   /**
337    * Networks array
338    */
339   struct Network *network_entries;
340
341   /**
342    * Proportionality factor
343    */
344   double prop_factor;
345
346   /**
347    * Stability factor
348    */
349   double stability_factor;
350
351   /**
352    * Bulk lock counter. If zero, we are not locked.
353    */
354   unsigned int bulk_lock;
355
356   /**
357    * Number of changes made while solver was locked.  We really only
358    * use 0/non-zero to check on unlock if we have to run the update.
359    */
360   unsigned int bulk_requests;
361
362   /**
363    * Number of active addresses for solver
364    */
365   unsigned int active_addresses;
366
367   /**
368    * Number of networks in @a network_entries
369    */
370   unsigned int network_count;
371 };
372
373
374 /**
375  * Test if bandwidth is available in this network to add an additional address.
376  *
377  * @param net the network type to check
378  * @return #GNUNET_YES or #GNUNET_NO
379  */
380 static int
381 is_bandwidth_available_in_network (struct Network *net)
382 {
383   unsigned int na = net->active_addresses + 1;
384   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
385
386   if ( ((net->total_quota_in / na) > min_bw) &&
387        ((net->total_quota_out / na) > min_bw) )
388     return GNUNET_YES;
389   return GNUNET_NO;
390 }
391
392
393 /**
394  * Update bandwidth assigned to peers in this network
395  *
396  * @param s the solver handle
397  * @param net the network type to update
398  * this address
399  */
400 static void
401 distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
402                       struct Network *net)
403 {
404   struct AddressWrapper *aw;
405   unsigned long long remaining_quota_in = 0;
406   unsigned long long quota_out_used = 0;
407   unsigned long long remaining_quota_out = 0;
408   unsigned long long quota_in_used = 0;
409   int count_addresses;
410   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
411   double relative_peer_prefence;
412   double sum_relative_peer_prefences; /* Important: has to be double not float due to precision */
413   double cur_pref; /* Important: has to be double not float due to precision */
414   double peer_weight;
415   double total_weight;
416   const double *peer_relative_prefs = NULL; /* Important: has to be double not float due to precision */
417
418   uint32_t assigned_quota_in = 0;
419   uint32_t assigned_quota_out = 0;
420
421
422   LOG (GNUNET_ERROR_TYPE_INFO,
423        "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
424        net->desc,
425        net->active_addresses,
426        net->total_quota_in,
427        net->total_quota_in);
428
429   if (net->active_addresses == 0)
430   {
431     return; /* no addresses to update */
432   }
433
434   /* Idea
435    * Assign every peer in network minimum Bandwidth
436    * Distribute bandwidth left according to preference
437    */
438
439   if ((net->active_addresses * min_bw) > net->total_quota_in)
440   {
441     GNUNET_break(0);
442     return;
443   }
444   if ((net->active_addresses * min_bw) > net->total_quota_out)
445   {
446     GNUNET_break(0);
447     return;
448   }
449
450   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
451   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
452   LOG(GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
453       remaining_quota_in, remaining_quota_out);
454   sum_relative_peer_prefences = 0.0;
455
456   /* Calculate sum of relative preference for active addresses in this network */
457   count_addresses = 0;
458   for (aw = net->head; NULL != aw; aw = aw->next)
459   {
460     if (GNUNET_YES != aw->addr->active)
461       continue;
462
463     peer_relative_prefs = s->env->get_preferences (s->env->cls,
464                                                    &aw->addr->peer);
465     relative_peer_prefence = 0.0;
466     relative_peer_prefence += peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
467     sum_relative_peer_prefences += relative_peer_prefence;
468     count_addresses ++;
469   }
470
471   if (count_addresses != net->active_addresses)
472   {
473     GNUNET_break (0);
474     LOG (GNUNET_ERROR_TYPE_WARNING,
475          "%s: Counted %u active addresses, but network says to have %u active addresses\n",
476          net->desc,
477          count_addresses,
478          net->active_addresses);
479     for (aw = net->head; NULL != aw; aw = aw->next)
480     {
481       if (GNUNET_YES != aw->addr->active)
482         continue;
483
484       LOG (GNUNET_ERROR_TYPE_WARNING,
485            "Active: `%s' `%s' length %u\n",
486            GNUNET_i2s (&aw->addr->peer),
487            aw->addr->plugin,
488            aw->addr->addr_len);
489     }
490   }
491
492   LOG (GNUNET_ERROR_TYPE_INFO,
493        "Total relative preference %.3f for %u addresses in network %s\n",
494        sum_relative_peer_prefences,
495        net->active_addresses,
496        net->desc);
497
498   for (aw = net->head; NULL != aw; aw = aw->next)
499   {
500     if (GNUNET_YES == aw->addr->active)
501     {
502       peer_relative_prefs = s->env->get_preferences (s->env->cls,
503                                                      &aw->addr->peer);
504
505       cur_pref = peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
506       total_weight = net->active_addresses +
507           s->prop_factor * sum_relative_peer_prefences;
508       peer_weight = (1.0 + (s->prop_factor * cur_pref));
509
510       assigned_quota_in = min_bw
511           + ((peer_weight / total_weight) * remaining_quota_in);
512       assigned_quota_out = min_bw
513           + ((peer_weight / total_weight) * remaining_quota_out);
514
515       LOG (GNUNET_ERROR_TYPE_INFO,
516           "New quota for peer `%s' with weight (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
517           GNUNET_i2s (&aw->addr->peer),
518            peer_weight,
519            total_weight,
520           assigned_quota_in,
521            assigned_quota_out);
522     }
523     else
524     {
525       assigned_quota_in = 0;
526       assigned_quota_out = 0;
527     }
528
529     quota_in_used += assigned_quota_in;
530     quota_out_used += assigned_quota_out;
531     /* Prevent overflow due to rounding errors */
532     if (assigned_quota_in > UINT32_MAX)
533       assigned_quota_in = UINT32_MAX;
534     if (assigned_quota_out > UINT32_MAX)
535       assigned_quota_out = UINT32_MAX;
536
537     /* Store for later propagation */
538     aw->calculated_quota_in = assigned_quota_in;
539     aw->calculated_quota_out = assigned_quota_out;
540   }
541   LOG (GNUNET_ERROR_TYPE_DEBUG,
542        "Total bandwidth assigned is (in/out): %llu /%llu\n",
543        quota_in_used,
544        quota_out_used);
545   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
546   {
547     LOG (GNUNET_ERROR_TYPE_ERROR,
548          "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
549          net->active_addresses,
550          quota_out_used,
551          net->total_quota_out);
552   }
553   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
554   {
555     LOG (GNUNET_ERROR_TYPE_ERROR,
556          "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
557          net->active_addresses,
558          quota_in_used,
559          net->total_quota_in);
560   }
561 }
562
563
564 /**
565  * Notify ATS service of bandwidth changes to addresses.
566  *
567  * @param s solver handle
568  * @param net the network to propagate changes in
569  */
570 static void
571 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
572                      struct Network *net)
573 {
574   struct AddressWrapper *cur;
575
576   for (cur = net->head; NULL != cur; cur = cur->next)
577   {
578     if ( (cur->addr->assigned_bw_in == cur->calculated_quota_in) &&
579          (cur->addr->assigned_bw_out == cur->calculated_quota_out) )
580       continue;
581     cur->addr->assigned_bw_in = cur->calculated_quota_in;
582     cur->addr->assigned_bw_out = cur->calculated_quota_out;
583     if (GNUNET_YES == cur->addr->active)
584       s->env->bandwidth_changed_cb (s->env->cls,
585                                     cur->addr);
586   }
587 }
588
589
590 /**
591  * Distribute bandwidth.  The addresses have already been selected,
592  * this is merely distributed the bandwidth among the addresses.
593  *
594  * @param s the solver handle
595  * @param n the network, can be NULL for all networks
596  */
597 static void
598 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
599                                  struct Network *n)
600 {
601   unsigned int i;
602
603   if (GNUNET_YES == s->bulk_lock)
604   {
605     s->bulk_requests++;
606     return;
607   }
608   if (NULL != n)
609   {
610     LOG (GNUNET_ERROR_TYPE_DEBUG,
611         "Redistributing bandwidth in network %s with %u active and %u total addresses\n",
612          GNUNET_ATS_print_network_type(n->type),
613          n->active_addresses,
614          n->total_addresses);
615     s->env->info_cb (s->env->cls,
616                      GAS_OP_SOLVE_START,
617                      GAS_STAT_SUCCESS,
618                      GAS_INFO_PROP_SINGLE);
619     distribute_bandwidth(s,
620                          n);
621     s->env->info_cb (s->env->cls,
622                      GAS_OP_SOLVE_STOP,
623                      GAS_STAT_SUCCESS,
624                      GAS_INFO_PROP_SINGLE);
625     s->env->info_cb (s->env->cls,
626                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
627                      GAS_STAT_SUCCESS,
628                      GAS_INFO_PROP_SINGLE);
629     propagate_bandwidth (s,
630                          n);
631
632     s->env->info_cb (s->env->cls,
633                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
634                      GAS_STAT_SUCCESS,
635                      GAS_INFO_PROP_SINGLE);
636   }
637   else
638   {
639     s->env->info_cb (s->env->cls,
640                      GAS_OP_SOLVE_START,
641                      GAS_STAT_SUCCESS,
642                      GAS_INFO_PROP_ALL);
643     for (i = 0; i < s->network_count; i++)
644       distribute_bandwidth (s,
645                             &s->network_entries[i]);
646     s->env->info_cb (s->env->cls,
647                      GAS_OP_SOLVE_STOP,
648                      GAS_STAT_SUCCESS,
649                      GAS_INFO_PROP_ALL);
650     s->env->info_cb (s->env->cls,
651                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
652                      GAS_STAT_SUCCESS,
653                      GAS_INFO_PROP_ALL);
654     for (i = 0; i < s->network_count; i++)
655       propagate_bandwidth (s,
656                            &s->network_entries[i]);
657     s->env->info_cb (s->env->cls,
658                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
659                      GAS_STAT_SUCCESS,
660                      GAS_INFO_PROP_ALL);
661   }
662 }
663
664
665 /**
666  * Context for finding the best address* Linked list of addresses in this network: head
667  */
668 struct FindBestAddressCtx
669 {
670   /**
671    * The solver handle
672    */
673   struct GAS_PROPORTIONAL_Handle *s;
674
675   /**
676    * The currently best address
677    */
678   struct ATS_Address *best;
679 };
680
681
682 /**
683  * Find index of a ATS property type in the quality properties array.
684  *
685  * @param type ATS property type
686  * @return index in the quality array, #GNUNET_SYSERR if the type
687  *         was not a quality property
688  */
689 static int
690 find_quality_property_index (enum GNUNET_ATS_Property type)
691 {
692   enum GNUNET_ATS_Property existing_types[] = GNUNET_ATS_QualityProperties;
693   unsigned int c;
694
695   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
696     if (existing_types[c] == type)
697       return c;
698   GNUNET_break (0);
699   return GNUNET_SYSERR;
700 }
701
702
703 /**
704  * Find a "good" address to use for a peer by iterating over the
705  * addresses for this peer.  If we already have an existing address,
706  * we stick to it.  Otherwise, we pick by lowest distance and then by
707  * lowest latency.
708  *
709  * @param cls the `struct FindBestAddressCtx *' where we store the result
710  * @param key the peer we are trying to find the best address for
711  * @param value another `struct ATS_Address*` to consider using
712  * @return #GNUNET_OK (continue to iterate)
713  */
714 static int
715 find_best_address_it (void *cls,
716                       const struct GNUNET_PeerIdentity *key,
717                       void *value)
718 {
719   struct FindBestAddressCtx *ctx = cls;
720   struct ATS_Address *current = value;
721   struct AddressWrapper *asi = current->solver_information;
722   struct GNUNET_TIME_Relative active_time;
723   double best_delay;
724   double best_distance;
725   double cur_delay;
726   double cur_distance;
727   int index;
728
729   if (GNUNET_NO ==
730       is_bandwidth_available_in_network (asi->network))
731   {
732     /* There's no bandwidth available in this network,
733        so we cannot use this address. */
734     return GNUNET_OK;
735   }
736   if (GNUNET_YES == current->active)
737   {
738     active_time = GNUNET_TIME_absolute_get_duration (asi->activated);
739     if (active_time.rel_value_us <=
740         ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) * ctx->s->stability_factor)
741     {
742       /* Keep active address for stability reasons */
743       ctx->best = current;
744       return GNUNET_NO;
745     }
746   }
747   if (NULL == ctx->best)
748   {
749     /* We so far have nothing else, so go with it! */
750     ctx->best = current;
751     return GNUNET_OK;
752   }
753
754   /* Now compare ATS information */
755   index = find_quality_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
756   cur_distance = current->atsin[index].norm;
757   best_distance = ctx->best->atsin[index].norm;
758   index = find_quality_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
759   cur_delay = current->atsin[index].norm;
760   best_delay = ctx->best->atsin[index].norm;
761
762   /* user shorter distance */
763   if (cur_distance < best_distance)
764   {
765     if (GNUNET_NO == ctx->best->active)
766     {
767       /* Activity doesn't influence the equation, use current */
768       ctx->best = current;
769     }
770     else if ((best_distance / cur_distance) > ctx->s->stability_factor)
771     {
772       /* Distance change is significant, switch active address! */
773       ctx->best = current;
774     }
775   }
776
777   /* User connection with less delay */
778   if (cur_delay < best_delay)
779   {
780     if (GNUNET_NO == ctx->best->active)
781     {
782       /* Activity doesn't influence the equation, use current */
783       ctx->best = current;
784     }
785     else if ((best_delay / cur_delay) > ctx->s->stability_factor)
786     {
787       /* Latency change is significant, switch active address! */
788       ctx->best = current;
789     }
790   }
791   return GNUNET_OK;
792 }
793
794
795 /**
796  * Find the currently best address for a peer from the set of
797  * addresses available or return NULL of no address is available.
798  *
799  * @param s the proportional handle
800  * @param addresses the address hashmap
801  * @param id the peer id
802  * @return the address or NULL
803  */
804 struct ATS_Address *
805 get_best_address (struct GAS_PROPORTIONAL_Handle *s,
806                   struct GNUNET_CONTAINER_MultiPeerMap *addresses,
807                   const struct GNUNET_PeerIdentity *id)
808 {
809   struct FindBestAddressCtx fba_ctx;
810
811   fba_ctx.best = NULL;
812   fba_ctx.s = s;
813   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
814                                               id,
815                                               &find_best_address_it,
816                                               &fba_ctx);
817   return fba_ctx.best;
818 }
819
820
821 /**
822  * Decrease number of active addresses in network.
823  *
824  * @param s the solver handle
825  * @param net the network type
826  */
827 static void
828 address_decrement_active (struct GAS_PROPORTIONAL_Handle *s,
829                           struct Network *net)
830 {
831   GNUNET_assert (net->active_addresses > 0);
832   net->active_addresses--;
833   GNUNET_STATISTICS_update (s->env->stats,
834                             net->stat_active,
835                             -1,
836                             GNUNET_NO);
837   GNUNET_assert (s->active_addresses > 0);
838   s->active_addresses--;
839   GNUNET_STATISTICS_update (s->env->stats,
840                             "# ATS addresses total",
841                             -1,
842                             GNUNET_NO);
843 }
844
845
846 /**
847  * Address map iterator to find current active address for peer.
848  * Asserts that only one address is active per peer.
849  *
850  * @param cls last active address
851  * @param key peer's key
852  * @param value address to check
853  * @return #GNUNET_NO on double active address else #GNUNET_YES;
854  */
855 static int
856 get_active_address_it (void *cls,
857                        const struct GNUNET_PeerIdentity *key,
858                        void *value)
859 {
860   struct ATS_Address **dest = cls;
861   struct ATS_Address *aa = value;
862
863   if (GNUNET_YES != aa->active)
864     return GNUNET_OK;
865   GNUNET_assert (NULL == (*dest));
866   (*dest) = aa;
867   return GNUNET_OK;
868 }
869
870
871 /**
872  * Find current active address for peer
873  *
874  * @param s the solver handle
875  * @param peer the peer
876  * @return active address or NULL
877  */
878 static struct ATS_Address *
879 get_active_address (struct GAS_PROPORTIONAL_Handle *s,
880                     const struct GNUNET_PeerIdentity *peer)
881 {
882   struct ATS_Address *dest;
883
884   dest = NULL;
885   GNUNET_CONTAINER_multipeermap_get_multiple (s->env->addresses,
886                                               peer,
887                                               &get_active_address_it,
888                                               &dest);
889   return dest;
890 }
891
892
893 /**
894  * Update active address for a peer.  Check if active address exists
895  * and what the best address is, if addresses are different switch.
896  * Then reallocate bandwidth within the affected network scopes.
897  *
898  * @param s solver handle
899  * @param current_address the address currently active for the peer,
900  *        NULL for none
901  * @param peer the peer to check
902  */
903 static void
904 update_active_address (struct GAS_PROPORTIONAL_Handle *s,
905                        struct ATS_Address *current_address,
906                        const struct GNUNET_PeerIdentity *peer)
907 {
908   struct ATS_Address *best_address;
909   struct AddressWrapper *asi_cur;
910   struct AddressWrapper *asi_best;
911
912   best_address = get_best_address (s,
913                                    s->env->addresses,
914                                    peer);
915   if (NULL != best_address)
916     asi_best = best_address->solver_information;
917   else
918     asi_best = NULL;
919   if (current_address == best_address)
920     return; /* no changes */
921   if (NULL != current_address)
922   {
923     /* We switch to a new address (or to none);
924        mark old address as inactive. */
925     asi_cur = current_address->solver_information;
926     GNUNET_assert (GNUNET_YES == current_address->active);
927     LOG (GNUNET_ERROR_TYPE_INFO,
928          "Disabling previous active address for peer `%s'\n",
929          GNUNET_i2s (peer));
930     asi_cur->activated = GNUNET_TIME_UNIT_ZERO_ABS;
931     current_address->active = GNUNET_NO;
932     current_address->assigned_bw_in = 0;
933     current_address->assigned_bw_out = 0;
934     address_decrement_active (s,
935                               asi_cur->network);
936     if ( (NULL == best_address) ||
937          (asi_best->network != asi_cur->network) )
938       distribute_bandwidth_in_network (s,
939                                        asi_cur->network);
940     if (NULL == best_address)
941     {
942       /* We previously had an active address, but now we cannot
943        * suggest one.  Therefore we have to disconnect the peer.
944        * The above call to "distribute_bandwidth_in_network()
945        * does not see 'current_address' so we need to trigger
946        * the update here. */
947       LOG (GNUNET_ERROR_TYPE_DEBUG,
948            "Disconnecting peer `%s'.\n",
949            GNUNET_i2s (peer));
950       s->env->bandwidth_changed_cb (s->env->cls,
951                                     current_address);
952       return;
953     }
954   }
955   if (NULL == best_address)
956   {
957     /* We do not have a new address, so we are done. */
958     LOG (GNUNET_ERROR_TYPE_DEBUG,
959          "Cannot suggest address for peer `%s'\n",
960          GNUNET_i2s (peer));
961     return;
962   }
963   /* We do have a new address, activate it */
964   LOG (GNUNET_ERROR_TYPE_DEBUG,
965        "Suggesting new address %p for peer `%s'\n",
966        best_address,
967        GNUNET_i2s (peer));
968   /* Mark address as active */
969   best_address->active = GNUNET_YES;
970   asi_best->activated = GNUNET_TIME_absolute_get ();
971   asi_best->network->active_addresses++;
972   s->active_addresses++;
973   GNUNET_STATISTICS_update (s->env->stats,
974                             "# ATS active addresses total",
975                             1,
976                             GNUNET_NO);
977   GNUNET_STATISTICS_update (s->env->stats,
978                             asi_best->network->stat_active,
979                             1,
980                             GNUNET_NO);
981   LOG (GNUNET_ERROR_TYPE_INFO,
982        "Address %p for peer `%s' is now active\n",
983        best_address,
984        GNUNET_i2s (peer));
985   distribute_bandwidth_in_network (s,
986                                    asi_best->network);
987 }
988
989
990 /**
991  * The preferences for a peer in the problem changed.
992  *
993  * @param solver the solver handle
994  * @param peer the peer to change the preference for
995  * @param kind the kind to change the preference
996  * @param pref_rel the normalized preference value for this kind over all clients
997  */
998 static void
999 GAS_proportional_change_preference (void *solver,
1000                                     const struct GNUNET_PeerIdentity *peer,
1001                                     enum GNUNET_ATS_PreferenceKind kind,
1002                                     double pref_rel)
1003 {
1004   struct GAS_PROPORTIONAL_Handle *s = solver;
1005
1006   distribute_bandwidth_in_network (s,
1007                                    NULL);
1008 }
1009
1010
1011 /**
1012  * Get application feedback for a peer
1013  *
1014  * @param solver the solver handle
1015  * @param application the application
1016  * @param peer the peer to change the preference for
1017  * @param scope the time interval for this feedback: [now - scope .. now]
1018  * @param kind the kind to change the preference
1019  * @param score the score
1020  */
1021 static void
1022 GAS_proportional_feedback (void *solver,
1023                            struct GNUNET_SERVER_Client *application,
1024                            const struct GNUNET_PeerIdentity *peer,
1025                            const struct GNUNET_TIME_Relative scope,
1026                            enum GNUNET_ATS_PreferenceKind kind,
1027                            double score)
1028 {
1029   /* Proportional does not care about feedback */
1030 }
1031
1032
1033 /**
1034  * Get the preferred address for a specific peer
1035  *
1036  * @param solver the solver handle
1037  * @param peer the identity of the peer
1038  */
1039 static void
1040 GAS_proportional_start_get_address (void *solver,
1041                                     const struct GNUNET_PeerIdentity *peer)
1042 {
1043   struct GAS_PROPORTIONAL_Handle *s = solver;
1044
1045   update_active_address (s,
1046                          get_active_address (s,
1047                                              peer),
1048                          peer);
1049 }
1050
1051
1052 /**
1053  * Stop notifying about address and bandwidth changes for this peer
1054  *
1055  * @param solver the solver handle
1056  * @param peer the peer
1057  */
1058 static void
1059 GAS_proportional_stop_get_address (void *solver,
1060                                    const struct GNUNET_PeerIdentity *peer)
1061 {
1062   struct GAS_PROPORTIONAL_Handle *s = solver;
1063   struct ATS_Address *cur;
1064   struct AddressWrapper *asi;
1065
1066   cur = get_active_address (s,
1067                             peer);
1068   if (NULL == cur)
1069     return;
1070   asi = cur->solver_information;
1071   distribute_bandwidth_in_network (s,
1072                                    asi->network);
1073 }
1074
1075
1076 /**
1077  * Start a bulk operation
1078  *
1079  * @param solver the solver
1080  */
1081 static void
1082 GAS_proportional_bulk_start (void *solver)
1083 {
1084   struct GAS_PROPORTIONAL_Handle *s = solver;
1085
1086   LOG (GNUNET_ERROR_TYPE_DEBUG,
1087        "Locking solver for bulk operation ...\n");
1088   GNUNET_assert (NULL != solver);
1089   s->bulk_lock++;
1090 }
1091
1092
1093 /**
1094  * Bulk operation done.
1095  *
1096  * @param solver our `struct GAS_PROPORTIONAL_Handle *`
1097  */
1098 static void
1099 GAS_proportional_bulk_stop (void *solver)
1100 {
1101   struct GAS_PROPORTIONAL_Handle *s = solver;
1102
1103   LOG (GNUNET_ERROR_TYPE_DEBUG,
1104        "Unlocking solver from bulk operation ...\n");
1105   if (s->bulk_lock < 1)
1106   {
1107     GNUNET_break(0);
1108     return;
1109   }
1110   s->bulk_lock--;
1111   if ( (0 == s->bulk_lock) &&
1112        (0 < s->bulk_requests) )
1113   {
1114     LOG (GNUNET_ERROR_TYPE_INFO,
1115          "No lock pending, recalculating\n");
1116     distribute_bandwidth_in_network (s,
1117                                      NULL);
1118     s->bulk_requests = 0;
1119   }
1120 }
1121
1122
1123 /**
1124  * Transport properties for this address have changed
1125  *
1126  * @param solver solver handle
1127  * @param address the address
1128  * @param type the ATSI type in HBO
1129  * @param abs_value the absolute value of the property
1130  * @param rel_value the normalized value
1131  */
1132 static void
1133 GAS_proportional_address_property_changed (void *solver,
1134                                            struct ATS_Address *address,
1135                                            enum GNUNET_ATS_Property type,
1136                                            uint32_t abs_value,
1137                                            double rel_value)
1138 {
1139   struct GAS_PROPORTIONAL_Handle *s = solver;
1140   struct AddressWrapper *asi = address->solver_information;
1141
1142   distribute_bandwidth_in_network (s,
1143                                    asi->network);
1144 }
1145
1146
1147 /**
1148  * Add a new single address to a network
1149  *
1150  * @param solver the solver Handle
1151  * @param address the address to add
1152  * @param network network type of this address
1153  */
1154 static void
1155 GAS_proportional_address_add (void *solver,
1156                               struct ATS_Address *address,
1157                               enum GNUNET_ATS_Network_Type network)
1158 {
1159   struct GAS_PROPORTIONAL_Handle *s = solver;
1160   struct Network *net;
1161   struct AddressWrapper *aw;
1162
1163   GNUNET_assert (network < s->env->network_count);
1164   net = &s->network_entries[network];
1165   net->total_addresses++;
1166
1167   aw = GNUNET_new (struct AddressWrapper);
1168   aw->addr = address;
1169   aw->network = net;
1170   address->solver_information = aw;
1171   GNUNET_CONTAINER_DLL_insert (net->head,
1172                                net->tail,
1173                                aw);
1174   GNUNET_STATISTICS_update (s->env->stats,
1175                             "# ATS addresses total",
1176                             1,
1177                             GNUNET_NO);
1178   GNUNET_STATISTICS_update (s->env->stats,
1179                             net->stat_total,
1180                             1,
1181                             GNUNET_NO);
1182   if (0 !=
1183       s->env->get_connectivity (s->env->cls,
1184                                 &address->peer))
1185   {
1186     /* This peer is requested, find best address */
1187     update_active_address (s,
1188                            get_active_address (s,
1189                                                &address->peer),
1190                            &address->peer);
1191   }
1192   LOG (GNUNET_ERROR_TYPE_INFO,
1193        "Added new address for `%s', now total %u and active %u addresses in network `%s'\n",
1194        GNUNET_i2s (&address->peer),
1195        net->total_addresses,
1196        net->active_addresses,
1197        net->desc);
1198 }
1199
1200
1201 /**
1202  * Remove an address from the solver. To do so, we:
1203  * - Removed it from specific network
1204  * - Decrease the number of total addresses
1205  * - If active:
1206  *   - decrease number of active addreses
1207  *   - update quotas
1208  *
1209  * @param solver the solver handle
1210  * @param address the address to remove
1211  */
1212 static void
1213 GAS_proportional_address_delete (void *solver,
1214                                  struct ATS_Address *address)
1215 {
1216   struct GAS_PROPORTIONAL_Handle *s = solver;
1217   struct AddressWrapper *aw = address->solver_information;
1218   struct Network *net = aw->network;
1219
1220   LOG (GNUNET_ERROR_TYPE_DEBUG,
1221        "Deleting %s address for peer `%s' from network `%s' (total: %u/active: %u)\n",
1222        (GNUNET_NO == address->active) ? "inactive" : "active",
1223        GNUNET_i2s (&address->peer),
1224        net->desc,
1225        net->total_addresses,
1226        net->active_addresses);
1227
1228   GNUNET_CONTAINER_DLL_remove (net->head,
1229                                net->tail,
1230                                aw);
1231   GNUNET_assert (net->total_addresses > 0);
1232   net->total_addresses--;
1233   GNUNET_STATISTICS_update (s->env->stats,
1234                             net->stat_total,
1235                             -1,
1236                             GNUNET_NO);
1237   if (GNUNET_YES == address->active)
1238   {
1239     /* Address was active, remove from network and update quotas */
1240     update_active_address (s,
1241                            address,
1242                            &address->peer);
1243     distribute_bandwidth_in_network (s, net);
1244   }
1245   GNUNET_free (aw);
1246   address->solver_information = NULL;
1247   LOG (GNUNET_ERROR_TYPE_DEBUG,
1248        "After deleting address now total %u and active %u addresses in network `%s'\n",
1249        net->total_addresses,
1250        net->active_addresses,
1251        net->desc);
1252 }
1253
1254
1255 /**
1256  * Function invoked when the plugin is loaded.
1257  *
1258  * @param[in,out] cls the `struct GNUNET_ATS_PluginEnvironment *` to use;
1259  *            modified to return the API functions (ugh).
1260  * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure
1261  */
1262 void *
1263 libgnunet_plugin_ats_proportional_init (void *cls)
1264 {
1265   static struct GNUNET_ATS_SolverFunctions sf;
1266   struct GNUNET_ATS_PluginEnvironment *env = cls;
1267   struct GAS_PROPORTIONAL_Handle *s;
1268   struct Network * cur;
1269   float f_tmp;
1270   unsigned int c;
1271
1272   s = GNUNET_new (struct GAS_PROPORTIONAL_Handle);
1273   s->env = env;
1274   sf.cls = s;
1275   sf.s_add = &GAS_proportional_address_add;
1276   sf.s_address_update_property = &GAS_proportional_address_property_changed;
1277   sf.s_get = &GAS_proportional_start_get_address;
1278   sf.s_get_stop = &GAS_proportional_stop_get_address;
1279   sf.s_pref = &GAS_proportional_change_preference;
1280   sf.s_feedback = &GAS_proportional_feedback;
1281   sf.s_del = &GAS_proportional_address_delete;
1282   sf.s_bulk_start = &GAS_proportional_bulk_start;
1283   sf.s_bulk_stop = &GAS_proportional_bulk_stop;
1284   s->stability_factor = PROP_STABILITY_FACTOR;
1285   if (GNUNET_SYSERR !=
1286       GNUNET_CONFIGURATION_get_value_float (env->cfg,
1287                                             "ats",
1288                                             "PROP_STABILITY_FACTOR",
1289                                             &f_tmp))
1290   {
1291     if ((f_tmp < 1.0) || (f_tmp > 2.0))
1292     {
1293       LOG (GNUNET_ERROR_TYPE_ERROR,
1294            _("Invalid %s configuration %f \n"),
1295            "PROP_STABILITY_FACTOR",
1296            f_tmp);
1297     }
1298     else
1299     {
1300       s->stability_factor = f_tmp;
1301       LOG (GNUNET_ERROR_TYPE_INFO,
1302            "Using %s of %.3f\n",
1303            "PROP_STABILITY_FACTOR",
1304            f_tmp);
1305     }
1306   }
1307   s->prop_factor = PROPORTIONALITY_FACTOR;
1308   if (GNUNET_SYSERR !=
1309       GNUNET_CONFIGURATION_get_value_float (env->cfg,
1310                                             "ats",
1311                                             "PROP_PROPORTIONALITY_FACTOR",
1312                                             &f_tmp))
1313   {
1314     if (f_tmp < 1.0)
1315     {
1316       LOG (GNUNET_ERROR_TYPE_ERROR,
1317            _("Invalid %s configuration %f\n"),
1318            "PROP_PROPORTIONALITY_FACTOR",
1319            f_tmp);
1320     }
1321     else
1322     {
1323       s->prop_factor = f_tmp;
1324       LOG (GNUNET_ERROR_TYPE_INFO,
1325            "Using %s of %.3f\n",
1326            "PROP_PROPORTIONALITY_FACTOR",
1327            f_tmp);
1328     }
1329   }
1330
1331   s->network_entries = GNUNET_malloc (env->network_count *
1332                                       sizeof (struct Network));
1333   for (c = 0; c < env->network_count; c++)
1334   {
1335     cur = &s->network_entries[c];
1336     cur->type = c;
1337     cur->total_quota_in = env->in_quota[c];
1338     cur->total_quota_out = env->out_quota[c];
1339     cur->desc = GNUNET_ATS_print_network_type (c);
1340     GNUNET_asprintf (&cur->stat_total,
1341                      "# ATS addresses %s total",
1342                      cur->desc);
1343     GNUNET_asprintf (&cur->stat_active,
1344                      "# ATS active addresses %s total",
1345                      cur->desc);
1346     LOG (GNUNET_ERROR_TYPE_INFO,
1347          "Added network %u `%s' (%llu/%llu)\n",
1348          c,
1349          cur->desc,
1350          cur->total_quota_in,
1351          cur->total_quota_out);
1352   }
1353   return &sf;
1354 }
1355
1356
1357 /**
1358  * Function used to unload the plugin.
1359  *
1360  * @param cls return value from #libgnunet_plugin_ats_proportional_init()
1361  */
1362 void *
1363 libgnunet_plugin_ats_proportional_done (void *cls)
1364 {
1365   struct GNUNET_ATS_SolverFunctions *sf = cls;
1366   struct GAS_PROPORTIONAL_Handle *s = sf->cls;
1367   struct AddressWrapper *cur;
1368   struct AddressWrapper *next;
1369   unsigned int c;
1370
1371   for (c = 0; c < s->network_count; c++)
1372   {
1373     GNUNET_break (0 == s->network_entries[c].total_addresses);
1374     GNUNET_break (0 == s->network_entries[c].active_addresses);
1375     next = s->network_entries[c].head;
1376     while (NULL != (cur = next))
1377     {
1378       next = cur->next;
1379       GNUNET_CONTAINER_DLL_remove (s->network_entries[c].head,
1380                                    s->network_entries[c].tail,
1381                                    cur);
1382       GNUNET_free_non_null (cur->addr->solver_information);
1383       GNUNET_free(cur);
1384     }
1385     GNUNET_free (s->network_entries[c].stat_total);
1386     GNUNET_free (s->network_entries[c].stat_active);
1387   }
1388   GNUNET_break (0 == s->active_addresses);
1389   GNUNET_free (s->network_entries);
1390   GNUNET_free (s);
1391   return NULL;
1392 }
1393
1394
1395 /* end of plugin_ats_proportional.c */