big ATS refactoring, no serious semantic changes should stem from this
[oweals/gnunet.git] / src / ats / plugin_ats_proportional.c
1 /*
2  This file is part of GNUnet.
3  (C) 2011-2014 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 #define PROPORTIONALITY_FACTOR 2.0
214
215 /**
216  * A handle for the proportional solver
217  */
218 struct GAS_PROPORTIONAL_Handle
219 {
220    struct GNUNET_ATS_PluginEnvironment *env;
221
222   /**
223    * Statistics handle
224    */
225   struct GNUNET_STATISTICS_Handle *stats;
226
227   /**
228    * Hashmap containing all valid addresses
229    */
230   struct GNUNET_CONTAINER_MultiPeerMap *addresses;
231
232   /**
233    * Pending address requests
234    */
235   struct GNUNET_CONTAINER_MultiPeerMap *requests;
236
237   /**
238    * Bandwidth changed callback
239    */
240   GAS_bandwidth_changed_cb bw_changed;
241
242   /**
243    * Bandwidth changed callback cls
244    */
245   void *bw_changed_cls;
246
247   /**
248    * ATS function to get preferences
249    */
250   GAS_get_preferences get_preferences;
251
252   /**
253    * Closure for ATS function to get preferences
254    */
255   void *get_preferences_cls;
256
257   /**
258    * ATS function to get properties
259    */
260   GAS_get_properties get_properties;
261
262   /**
263    * Closure for ATS function to get properties
264    */
265   void *get_properties_cls;
266
267   /**
268    * Bulk lock
269    */
270   int bulk_lock;
271
272   /**
273    * Number of changes while solver was locked
274    */
275   int bulk_requests;
276
277   /**
278    * Total number of addresses for solver
279    */
280   unsigned int total_addresses;
281
282   /**
283    * Number of active addresses for solver
284    */
285   unsigned int active_addresses;
286
287   /**
288    * Networks array
289    */
290   struct Network *network_entries;
291
292   /**
293    * Number of networks
294    */
295   unsigned int network_count;
296
297   /**
298    * Proportionality factor
299    */
300   double prop_factor;
301
302   /**
303    * Stability factor
304    */
305   double stability_factor;
306 };
307
308 /**
309  * Representation of a network
310  */
311 struct Network
312 {
313   /**
314    * ATS network type
315    */
316   unsigned int type;
317
318   /**
319    * Network description
320    */
321   const char *desc;
322
323   /**
324    * Total inbound quota
325    */
326   unsigned long long total_quota_in;
327
328   /**
329    * Total outbound quota
330    */
331   unsigned long long total_quota_out;
332
333   /**
334    * Number of active addresses for this network
335    */
336   unsigned int active_addresses;
337
338   /**
339    * Number of total addresses for this network
340    */
341   unsigned int total_addresses;
342
343   /**
344    * String for statistics total addresses
345    */
346   char *stat_total;
347
348   /**
349    * String for statistics active addresses
350    */
351   char *stat_active;
352
353   /**
354    * Linked list of addresses in this network: head
355    */
356   struct AddressWrapper *head;
357
358   /**
359    * Linked list of addresses in this network: tail
360    */
361   struct AddressWrapper *tail;
362 };
363
364 /**
365  * Address information stored in the solver
366  */
367 struct AddressSolverInformation
368 {
369   /**
370    * Network scope this address is in
371    */
372   struct Network *network;
373
374   /**
375    * Inbound quota
376    */
377   uint32_t calculated_quota_in;
378
379   /**
380    * Outbound quota
381    */
382   uint32_t calculated_quota_out;
383
384   /**
385    * When was this address activated
386    */
387   struct GNUNET_TIME_Absolute activated;
388
389 };
390
391 /**
392  * Wrapper for addresses to store them in network's linked list
393  */
394 struct AddressWrapper
395 {
396   /**
397    * Next in DLL
398    */
399   struct AddressWrapper *next;
400
401   /**
402    * Previous in DLL
403    */
404   struct AddressWrapper *prev;
405
406   /**
407    * The address
408    */
409   struct ATS_Address *addr;
410 };
411
412
413 /**
414  * Function used to unload the plugin.
415  *
416  * @param cls return value from #libgnunet_plugin_ats_proportional_init()
417  */
418 void *
419 libgnunet_plugin_ats_proportional_done (void *cls)
420 {
421   struct GAS_PROPORTIONAL_Handle *s = cls;
422   struct AddressWrapper *cur;
423   struct AddressWrapper *next;
424   int c;
425
426   for (c = 0; c < s->network_count; c++)
427   {
428     if (s->network_entries[c].total_addresses > 0)
429     {
430       LOG(GNUNET_ERROR_TYPE_DEBUG,
431           "Had %u addresses for network `%s' not deleted during shutdown\n",
432           s->network_entries[c].total_addresses, s->network_entries[c].desc);
433       //GNUNET_break(0);
434     }
435
436     if (s->network_entries[c].active_addresses > 0)
437     {
438       LOG(GNUNET_ERROR_TYPE_DEBUG,
439           "Had %u active addresses for network `%s' not deleted during shutdown\n",
440           s->network_entries[c].active_addresses, s->network_entries[c].desc);
441       //GNUNET_break(0);
442     }
443
444     next = s->network_entries[c].head;
445     while (NULL != (cur = next))
446     {
447       next = cur->next;
448       GNUNET_CONTAINER_DLL_remove(s->network_entries[c].head,
449           s->network_entries[c].tail, cur);
450       GNUNET_free_non_null (cur->addr->solver_information);
451       GNUNET_free(cur);
452     }
453     GNUNET_free(s->network_entries[c].stat_total);
454     GNUNET_free(s->network_entries[c].stat_active);
455   }
456   if (s->total_addresses > 0)
457   {
458     LOG(GNUNET_ERROR_TYPE_DEBUG,
459         "Had %u addresses not deleted during shutdown\n", s->total_addresses);
460     // GNUNET_break(0);
461   }
462   if (s->active_addresses > 0)
463   {
464     LOG(GNUNET_ERROR_TYPE_DEBUG,
465         "Had %u active addresses not deleted during shutdown\n",
466         s->active_addresses);
467     // GNUNET_break (0);
468   }
469   GNUNET_free (s->network_entries);
470   GNUNET_CONTAINER_multipeermap_destroy (s->requests);
471   GNUNET_free (s);
472   return NULL;
473 }
474
475
476 /**
477  * Test if bandwidth is available in this network to add an additional address
478  *
479  * @param net the network type to update
480  * @return #GNUNET_YES or #GNUNET_NO
481  */
482 static int
483 is_bandwidth_available_in_network (struct Network *net)
484 {
485   GNUNET_assert(NULL != net);
486   unsigned int na = net->active_addresses + 1;
487   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
488   if (((net->total_quota_in / na) > min_bw)
489       && ((net->total_quota_out / na) > min_bw))
490   {
491     LOG(GNUNET_ERROR_TYPE_DEBUG,
492         "Enough bandwidth available for %u active addresses in network `%s'\n",
493         na, net->desc);
494
495     return GNUNET_YES;
496   }
497   LOG(GNUNET_ERROR_TYPE_DEBUG,
498       "Not enough bandwidth available for %u active addresses in network `%s'\n",
499       na, net->desc);
500   return GNUNET_NO;
501 }
502
503
504 /**
505  * Update bandwidth assigned to peers in this network
506  *
507  * @param s the solver handle
508  * @param net the network type to update
509  * this address
510  */
511 static void
512 distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
513                       struct Network *net)
514 {
515   struct AddressSolverInformation *asi;
516   struct AddressWrapper *cur_address;
517   unsigned long long remaining_quota_in = 0;
518   unsigned long long quota_out_used = 0;
519   unsigned long long remaining_quota_out = 0;
520   unsigned long long quota_in_used = 0;
521   int count_addresses;
522   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
523   double relative_peer_prefence;
524   double sum_relative_peer_prefences; /* Important: has to be double not float due to precision */
525   double cur_pref; /* Important: has to be double not float due to precision */
526   double peer_weight;
527   double total_weight;
528   const double *peer_relative_prefs = NULL; /* Important: has to be double not float due to precision */
529
530   uint32_t assigned_quota_in = 0;
531   uint32_t assigned_quota_out = 0;
532
533
534   LOG (GNUNET_ERROR_TYPE_INFO,
535        "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
536        net->desc,
537        net->active_addresses,
538        net->total_quota_in,
539        net->total_quota_in);
540
541   if (net->active_addresses == 0)
542   {
543     return; /* no addresses to update */
544   }
545
546   /* Idea
547    * Assign every peer in network minimum Bandwidth
548    * Distribute bandwidth left according to preference
549    */
550
551   if ((net->active_addresses * min_bw) > net->total_quota_in)
552   {
553     GNUNET_break(0);
554     return;
555   }
556   if ((net->active_addresses * min_bw) > net->total_quota_out)
557   {
558     GNUNET_break(0);
559     return;
560   }
561
562   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
563   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
564   LOG(GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
565       remaining_quota_in, remaining_quota_out);
566   sum_relative_peer_prefences = 0.0;
567
568   /* Calculate sum of relative preference for active addresses in this network */
569   count_addresses = 0;
570   for (cur_address = net->head; NULL != cur_address; cur_address = cur_address->next)
571   {
572     if (GNUNET_YES != cur_address->addr->active)
573       continue;
574
575     GNUNET_assert( NULL != (peer_relative_prefs = s->get_preferences (s->get_preferences_cls,
576         &cur_address->addr->peer)));
577     relative_peer_prefence = 0.0;
578     relative_peer_prefence += peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
579     sum_relative_peer_prefences += relative_peer_prefence;
580     count_addresses ++;
581   }
582
583   if (count_addresses != net->active_addresses)
584   {
585     GNUNET_break (0);
586     LOG (GNUNET_ERROR_TYPE_WARNING,
587          "%s: Counted %u active addresses, but network says to have %u active addresses\n",
588          net->desc, count_addresses, net->active_addresses);
589     for (cur_address = net->head; NULL != cur_address; cur_address = cur_address->next)
590     {
591       if (GNUNET_YES != cur_address->addr->active)
592         continue;
593
594       LOG (GNUNET_ERROR_TYPE_WARNING,
595            "Active: `%s' `%s' length %u\n",
596            GNUNET_i2s (&cur_address->addr->peer),
597            cur_address->addr->plugin,
598            cur_address->addr->addr_len);
599     }
600   }
601
602   LOG (GNUNET_ERROR_TYPE_INFO,
603       "Total relative preference %.3f for %u addresses in network %s\n",
604       sum_relative_peer_prefences, net->active_addresses, net->desc);
605
606   for (cur_address = net->head; NULL != cur_address; cur_address = cur_address->next)
607   {
608     if (GNUNET_YES == cur_address->addr->active)
609     {
610       GNUNET_assert( NULL != (peer_relative_prefs =
611           s->get_preferences (s->get_preferences_cls, &cur_address->addr->peer)));
612
613       cur_pref = peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
614       total_weight = net->active_addresses +
615           s->prop_factor * sum_relative_peer_prefences;
616       peer_weight = (1.0 + (s->prop_factor * cur_pref));
617
618       assigned_quota_in = min_bw
619           + ((peer_weight / total_weight) * remaining_quota_in);
620       assigned_quota_out = min_bw
621           + ((peer_weight / total_weight) * remaining_quota_out);
622
623       LOG (GNUNET_ERROR_TYPE_INFO,
624           "New quota for peer `%s' with weight (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
625           GNUNET_i2s (&cur_address->addr->peer), peer_weight, total_weight,
626           assigned_quota_in, assigned_quota_out);
627     }
628     else
629     {
630       assigned_quota_in = 0;
631       assigned_quota_out = 0;
632     }
633
634     quota_in_used += assigned_quota_in;
635     quota_out_used += assigned_quota_out;
636     /* Prevent overflow due to rounding errors */
637     if (assigned_quota_in > UINT32_MAX)
638       assigned_quota_in = UINT32_MAX;
639     if (assigned_quota_out > UINT32_MAX)
640       assigned_quota_out = UINT32_MAX;
641
642     /* Compare to current bandwidth assigned */
643     asi = cur_address->addr->solver_information;
644     asi->calculated_quota_in = assigned_quota_in;
645     asi->calculated_quota_out = assigned_quota_out;
646   }
647   LOG(GNUNET_ERROR_TYPE_DEBUG,
648       "Total bandwidth assigned is (in/out): %llu /%llu\n", quota_in_used,
649       quota_out_used);
650   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
651   {
652     LOG(GNUNET_ERROR_TYPE_ERROR,
653         "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
654         net->active_addresses, quota_out_used, net->total_quota_out);
655   }
656   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
657   {
658     LOG(GNUNET_ERROR_TYPE_ERROR,
659         "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
660         net->active_addresses, quota_in_used, net->total_quota_in);
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 array.
684  */
685 static int
686 find_property_index (uint32_t type)
687 {
688   int existing_types[] = GNUNET_ATS_QualityProperties;
689   int c;
690
691   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
692     if (existing_types[c] == type)
693       return c;
694   return GNUNET_SYSERR;
695 }
696
697
698 /**
699  * Find a "good" address to use for a peer by iterating over the addresses for this peer.
700  * If we already have an existing address, we stick to it.
701  * Otherwise, we pick by lowest distance and then by lowest latency.
702  *
703  * @param cls the `struct FindBestAddressCtx *' where we store the result
704  * @param key unused
705  * @param value another `struct ATS_Address*` to consider using
706  * @return #GNUNET_OK (continue to iterate)
707  */
708 static int
709 find_best_address_it (void *cls,
710                       const struct GNUNET_PeerIdentity *key,
711                       void *value)
712 {
713   struct FindBestAddressCtx *ctx = cls;
714   struct ATS_Address *current = value;
715   struct ATS_Address *current_best = current;
716   struct AddressSolverInformation *asi;
717   struct GNUNET_TIME_Relative active_time;
718   struct GNUNET_TIME_Relative min_active_time;
719   const double *norm_prop_cur;
720   const double *norm_prop_best;
721   double best_delay;
722   double best_distance;
723   double cur_delay;
724   double cur_distance;
725   int index;
726
727   current_best = NULL;
728   asi = current->solver_information;
729   if (NULL == asi)
730   {
731     GNUNET_break (0);
732     return GNUNET_OK;
733   }
734
735   if (GNUNET_NO == is_bandwidth_available_in_network (asi->network))
736   {
737     return GNUNET_OK; /* There's no bandwidth available in this network */
738   }
739
740   if (NULL != ctx->best)
741   {
742     /* Compare current addresses with denominated 'best' address */
743     current_best = ctx->best;
744   }
745   else
746   {
747     /* We do not have a 'best' address so take this address */
748     LOG (GNUNET_ERROR_TYPE_DEBUG,
749          "Setting initial address %p\n",
750          current);
751     current_best = current;
752     goto end;
753   }
754
755   if (GNUNET_YES == current->active)
756   {
757     GNUNET_assert (asi->activated.abs_value_us != GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us);
758     active_time = GNUNET_TIME_absolute_get_duration (asi->activated);
759     min_active_time.rel_value_us =  ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) *
760         ctx->s->stability_factor;
761     if (active_time.rel_value_us <= min_active_time.rel_value_us)
762     {
763       /* Keep active address for stability reasons */
764       ctx->best = current;
765       return GNUNET_NO;
766     }
767   }
768
769   /* Now compare ATS information */
770   norm_prop_cur = ctx->s->get_properties (ctx->s->get_properties_cls,
771       (const struct ATS_Address *) current);
772   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
773   cur_distance = norm_prop_cur[index];
774   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
775   cur_delay = norm_prop_cur[index];
776
777   norm_prop_best = ctx->s->get_properties (ctx->s->get_properties_cls,
778       (const struct ATS_Address *) ctx->best);
779   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
780   best_distance = norm_prop_best[index];
781   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
782   best_delay = norm_prop_best[index];
783
784   /* user shorter distance */
785   if (cur_distance < best_distance)
786   {
787     if (GNUNET_NO == ctx->best->active)
788     {
789       current_best = current; /* Use current */
790     }
791     else if ((best_distance / cur_distance) > ctx->s->stability_factor)
792     {
793       /* Best and active address performs worse  */
794       current_best = current;
795     }
796   }
797   else
798   {
799     /* Use current best */
800     current_best = ctx->best;
801   }
802
803   /* User connection with less delay */
804   if (cur_delay < best_delay)
805   {
806
807     if (GNUNET_NO == ctx->best->active)
808     {
809       current_best = current; /* Use current */
810     }
811     else if ((best_delay / cur_delay) > ctx->s->stability_factor)
812     {
813       /* Best and active address performs worse  */
814       current_best = current;
815     }
816   }
817   else
818   {
819     /* Use current best */
820     current_best = ctx->best;
821   }
822
823 end:
824   ctx->best = current_best;
825   return GNUNET_OK;
826 }
827
828
829 /**
830  * Find the currently best address for a peer from the set of addresses available
831  * or return NULL of no address is available
832  *
833  * @param s the proportional handle
834  * @param addresses the address hashmap
835  * @param id the peer id
836  * @return the address or NULL
837  */
838 struct ATS_Address *
839 get_best_address (struct GAS_PROPORTIONAL_Handle *s,
840                   struct GNUNET_CONTAINER_MultiPeerMap *addresses,
841                   const struct GNUNET_PeerIdentity *id)
842 {
843   struct FindBestAddressCtx fba_ctx;
844
845   fba_ctx.best = NULL;
846   fba_ctx.s = s;
847   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
848                                               id,
849                                               &find_best_address_it,
850                                               &fba_ctx);
851   return fba_ctx.best;
852 }
853
854
855 /**
856  * Hashmap Iterator to find current active address for peer
857  *
858  * @param cls last active address
859  * @param key peer's key
860  * @param value address to check
861  * @return #GNUNET_NO on double active address else #GNUNET_YES;
862  */
863 static int
864 get_active_address_it (void *cls,
865                        const struct GNUNET_PeerIdentity *key,
866                        void *value)
867 {
868   struct ATS_Address **dest = cls;
869   struct ATS_Address *aa = (struct ATS_Address *) value;
870
871   LOG (GNUNET_ERROR_TYPE_INFO,
872          "Checking address %p\n", aa);
873
874   if (GNUNET_YES == aa->active)
875   {
876   LOG (GNUNET_ERROR_TYPE_INFO,
877          "Address %p is active\n", aa);
878     if (NULL != (*dest))
879     {
880       /* should never happen */
881       LOG (GNUNET_ERROR_TYPE_ERROR,
882            "Multiple active addresses for peer `%s'\n",
883            GNUNET_i2s (&aa->peer));
884       GNUNET_break(0);
885       return GNUNET_NO;
886     }
887     (*dest) = aa;
888
889   }
890   return GNUNET_OK;
891 }
892
893
894 /**
895  * Find current active address for peer
896  *
897  * @param solver the solver handle
898  * @param addresses the address set
899  * @param peer the peer
900  * @return active address or NULL
901  */
902 static struct ATS_Address *
903 get_active_address (void *solver,
904                     const struct GNUNET_CONTAINER_MultiPeerMap * addresses,
905                     const struct GNUNET_PeerIdentity *peer)
906 {
907   static struct ATS_Address * dest = NULL;
908
909   dest = NULL;
910   GNUNET_CONTAINER_multipeermap_get_multiple (addresses, peer,
911                                               &get_active_address_it, &dest);
912   return dest;
913 }
914
915
916 /**
917  * Lookup network struct by type
918  *
919  * @param s the solver handle
920  * @param type the network type
921  * @return the network struct
922  */
923 static struct Network *
924 get_network (struct GAS_PROPORTIONAL_Handle *s, uint32_t type)
925 {
926   int c;
927   for (c = 0; c < s->network_count; c++)
928   {
929     if (s->network_entries[c].type == type)
930       return &s->network_entries[c];
931   }
932   return NULL ;
933 }
934
935
936 /**
937  * Increase address count in network
938  *
939  * @param s the solver handle
940  * @param net the network type
941  * @param total increase total addresses
942  * @param active increase active addresses
943  */
944 static void
945 address_increment (struct GAS_PROPORTIONAL_Handle *s,
946                     struct Network *net,
947                     int total,
948                     int active)
949 {
950   if (GNUNET_YES == total)
951   {
952     s->total_addresses++;
953     net->total_addresses++;
954     GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
955     GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
956   }
957   if (GNUNET_YES == active)
958   {
959     net->active_addresses++;
960     s->active_addresses++;
961     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1,
962         GNUNET_NO);
963     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
964   }
965
966 }
967
968
969 /**
970  * Decrease address count in network
971  *
972  * @param s the solver handle
973  * @param net the network type
974  * @param total decrease total addresses
975  * @param active decrease active addresses
976  */
977 static int
978 addresse_decrement (struct GAS_PROPORTIONAL_Handle *s,
979                     struct Network *net,
980                     int total,
981                     int active)
982 {
983   int res = GNUNET_OK;
984
985   if (GNUNET_YES == total)
986   {
987     if (s->total_addresses < 1)
988     {
989       GNUNET_break(0);
990       res = GNUNET_SYSERR;
991     }
992     else
993     {
994       s->total_addresses--;
995       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
996           GNUNET_NO);
997     }
998     if (net->total_addresses < 1)
999     {
1000       GNUNET_break(0);
1001       res = GNUNET_SYSERR;
1002     }
1003     else
1004     {
1005       net->total_addresses--;
1006       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
1007     }
1008   }
1009
1010   if (GNUNET_YES == active)
1011   {
1012     if (net->active_addresses < 1)
1013     {
1014       GNUNET_break(0);
1015       res = GNUNET_SYSERR;
1016     }
1017     else
1018     {
1019       net->active_addresses--;
1020       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
1021     }
1022     if (s->active_addresses < 1)
1023     {
1024       GNUNET_break(0);
1025       res = GNUNET_SYSERR;
1026     }
1027     else
1028     {
1029       s->active_addresses--;
1030       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
1031           GNUNET_NO);
1032     }
1033   }
1034   return res;
1035 }
1036
1037
1038 /**
1039  * Compares addresses
1040  *
1041  * @param a address a
1042  * @param b address b
1043  * @return GNUNET_YES if equal, GNUNET_NO else
1044  */
1045 static int
1046 address_eq (struct ATS_Address *a, struct ATS_Address *b)
1047 {
1048   GNUNET_assert (NULL != a);
1049   GNUNET_assert (NULL != b);
1050   if (0 != strcmp(a->plugin, b->plugin))
1051     return GNUNET_NO;
1052   if (a->addr_len != b->addr_len)
1053     return GNUNET_NO;
1054   if (0 != memcmp (a->addr, b->addr, b->addr_len))
1055     return GNUNET_NO;
1056   if (a->session_id != b->session_id)
1057     return GNUNET_NO;
1058   return GNUNET_YES;
1059 }
1060
1061
1062 /**
1063  * Notify bandwidth changes to addresses
1064  *
1065  * @param s solver handle
1066  * @param net the network to propagate changes in
1067  */
1068 static void
1069 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
1070                      struct Network *net)
1071 {
1072   struct AddressWrapper *cur;
1073   struct AddressSolverInformation *asi;
1074   for (cur = net->head; NULL != cur; cur = cur->next)
1075   {
1076       asi = cur->addr->solver_information;
1077       if ( (cur->addr->assigned_bw_in != asi->calculated_quota_in) ||
1078            (cur->addr->assigned_bw_out != asi->calculated_quota_out) )
1079       {
1080         cur->addr->assigned_bw_in = asi->calculated_quota_in;
1081         cur->addr->assigned_bw_out = asi->calculated_quota_out;
1082
1083         /* Reset for next iteration */
1084         asi->calculated_quota_in = 0;
1085         asi->calculated_quota_out = 0;
1086         LOG (GNUNET_ERROR_TYPE_DEBUG,
1087             "Bandwidth for %s address %p for peer `%s' changed to %u/%u\n",
1088             (GNUNET_NO == cur->addr->active) ? "inactive" : "active",
1089             cur->addr,
1090             GNUNET_i2s (&cur->addr->peer),
1091             cur->addr->assigned_bw_in,
1092             cur->addr->assigned_bw_out);
1093
1094         /* Notify on change */
1095         if ((GNUNET_YES == cur->addr->active))
1096         {
1097           s->bw_changed (s->bw_changed_cls, cur->addr);
1098         }
1099       }
1100   }
1101 }
1102
1103
1104 /**
1105  * Distribibute bandwidth
1106  *
1107  * @param s the solver handle
1108  * @param n the network, can be NULL for all network
1109  */
1110 static void
1111 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
1112                                  struct Network *n)
1113 {
1114   if (GNUNET_YES == s->bulk_lock)
1115   {
1116     s->bulk_requests++;
1117     return;
1118   }
1119
1120   if (NULL != n)
1121   {
1122     LOG (GNUNET_ERROR_TYPE_INFO,
1123         "Redistributing bandwidth in network %s with %u active and %u total addresses\n",
1124         GNUNET_ATS_print_network_type(n->type),
1125         n->active_addresses, n->total_addresses);
1126
1127     if (NULL != s->env->info_cb)
1128       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
1129           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1130
1131     /* Distribute  */
1132     distribute_bandwidth(s, n);
1133
1134     if (NULL != s->env->info_cb)
1135       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
1136           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1137     if (NULL != s->env->info_cb)
1138       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1139           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1140
1141     /* Do propagation */
1142     propagate_bandwidth (s, n);
1143
1144     if (NULL != s->env->info_cb)
1145       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1146           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1147   }
1148   else
1149   {
1150     int i;
1151     if (NULL != s->env->info_cb)
1152       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
1153           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1154     for (i = 0; i < s->network_count; i++)
1155     {
1156       /* Distribute */
1157       distribute_bandwidth(s, &s->network_entries[i]);
1158     }
1159
1160     if (NULL != s->env->info_cb)
1161       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
1162           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1163     if (NULL != s->env->info_cb)
1164       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1165           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1166     for (i = 0; i < s->network_count; i++)
1167     {
1168       /* Do propagation */
1169       propagate_bandwidth(s, &s->network_entries[i]);
1170     }
1171     if (NULL != s->env->info_cb)
1172       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1173           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1174   }
1175 }
1176
1177
1178 /**
1179  * Update active address for a peer:
1180  * Check if active address exists and what the best address is, if addresses
1181  * are different switch
1182  *
1183  * @param s solver handle
1184  * @param peer the peer to check
1185  * return the new address or NULL if no update was performed
1186   */
1187 static struct ATS_Address *
1188 update_active_address (struct GAS_PROPORTIONAL_Handle *s,
1189                        const struct GNUNET_PeerIdentity *peer)
1190 {
1191   struct ATS_Address *best_address;
1192   struct ATS_Address *current_address;
1193   struct AddressSolverInformation *asi;
1194   struct Network *net;
1195
1196   LOG (GNUNET_ERROR_TYPE_INFO,
1197        "Updating active address for peer `%s'\n",
1198        GNUNET_i2s (peer));
1199
1200   /* Find active address */
1201   current_address = get_active_address (s,
1202                                         s->addresses,
1203                                         peer);
1204
1205   LOG (GNUNET_ERROR_TYPE_INFO,
1206        "Peer `%s' has active address %p\n",
1207        GNUNET_i2s (peer),
1208        current_address);
1209
1210   /* Find best address */
1211   best_address = get_best_address (s,
1212                                    s->addresses,
1213                                    peer);
1214   LOG (GNUNET_ERROR_TYPE_INFO,
1215        "Peer `%s' has best address %p\n",
1216        GNUNET_i2s (peer),
1217        best_address);
1218
1219   if (NULL != current_address)
1220   {
1221     if ( (NULL == best_address) ||
1222          ( (NULL != best_address) &&
1223            (GNUNET_NO == address_eq (current_address,
1224                                      best_address)) ) )
1225     {
1226       /* We switch to a new address (or to none),
1227          mark old address as inactive */
1228       LOG (GNUNET_ERROR_TYPE_INFO,
1229            "Disabling previous %s address %p for peer `%s'\n",
1230            (GNUNET_NO == current_address->active) ? "inactive" : "active",
1231            current_address,
1232            GNUNET_i2s (peer));
1233
1234       asi = current_address->solver_information;
1235       GNUNET_assert (NULL != asi);
1236
1237       net = asi->network;
1238       asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1239       current_address->active = GNUNET_NO; /* No active any longer */
1240       current_address->assigned_bw_in = 0; /* no bandwidth assigned */
1241       current_address->assigned_bw_out = 0; /* no bandwidth assigned */
1242
1243       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1244         GNUNET_break(0);
1245
1246       /* Update network of previous address */
1247       distribute_bandwidth_in_network (s, net);
1248     }
1249     if (NULL == best_address)
1250     {
1251       /* We previously had an active address, but now we cannot suggest one
1252        * Therefore we have to disconnect the peer */
1253       LOG (GNUNET_ERROR_TYPE_INFO,
1254            "Disconnecting peer `%s' with previous address %p\n",
1255            GNUNET_i2s (peer),
1256            current_address);
1257       s->bw_changed (s->bw_changed_cls,
1258                      current_address);
1259     }
1260   }
1261   if (NULL == best_address)
1262   {
1263     LOG (GNUNET_ERROR_TYPE_INFO,
1264          "Cannot suggest address for peer `%s'\n",
1265          GNUNET_i2s (peer));
1266     return NULL;
1267   }
1268
1269   LOG (GNUNET_ERROR_TYPE_INFO,
1270        "Suggesting new address %p for peer `%s'\n",
1271        best_address,
1272        GNUNET_i2s (peer));
1273
1274   if ( (NULL != current_address) &&
1275        (GNUNET_YES == address_eq (best_address, current_address)) )
1276   {
1277     GNUNET_break (GNUNET_NO != current_address->active);
1278     return best_address; /* Same same */
1279   }
1280
1281   asi = best_address->solver_information;
1282   GNUNET_assert (NULL != asi);
1283   net = asi->network;
1284
1285   /* Mark address as active */
1286   asi->activated = GNUNET_TIME_absolute_get ();
1287   best_address->active = GNUNET_YES;
1288   address_increment (s, net, GNUNET_NO, GNUNET_YES);
1289   LOG (GNUNET_ERROR_TYPE_INFO,
1290        "Address %p for peer `%s' is now active\n",
1291        best_address,
1292        GNUNET_i2s (peer));
1293   /* Distribute bandwidth */
1294   distribute_bandwidth_in_network (s, net);
1295   return best_address;
1296 }
1297
1298
1299 /**
1300  * Changes the preferences for a peer in the problem
1301  *
1302  * @param solver the solver handle
1303  * @param peer the peer to change the preference for
1304  * @param kind the kind to change the preference
1305  * @param pref_rel the normalized preference value for this kind over all clients
1306  */
1307 static void
1308 GAS_proportional_address_change_preference (void *solver,
1309                                             const struct GNUNET_PeerIdentity *peer,
1310                                             enum GNUNET_ATS_PreferenceKind kind,
1311                                             double pref_rel)
1312 {
1313   struct GAS_PROPORTIONAL_Handle *s = solver;
1314   struct ATS_Address *best_address;
1315   struct ATS_Address *active_address;
1316   struct AddressSolverInformation *asi;
1317
1318   if (GNUNET_NO ==
1319       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1320     return; /* Peer is not requested */
1321
1322   /* This peer is requested, find best address */
1323   active_address = get_active_address (s, s->addresses, peer);
1324   best_address = update_active_address (s, peer);
1325
1326   if ((NULL != best_address) && ((NULL != active_address) &&
1327       (GNUNET_YES == address_eq (active_address, best_address))))
1328   {
1329     asi = best_address->solver_information;
1330     GNUNET_assert (NULL != asi);
1331
1332     /* We sticked to the same address, therefore redistribute  */
1333     distribute_bandwidth_in_network (s, asi->network);
1334   }
1335 }
1336
1337
1338 /**
1339  * Get application feedback for a peer
1340  *
1341  * @param solver the solver handle
1342  * @param application the application
1343  * @param peer the peer to change the preference for
1344  * @param scope the time interval for this feedback: [now - scope .. now]
1345  * @param kind the kind to change the preference
1346  * @param score the score
1347  */
1348 static void
1349 GAS_proportional_address_preference_feedback (void *solver,
1350                                               void *application,
1351                                               const struct GNUNET_PeerIdentity *peer,
1352                                               const struct GNUNET_TIME_Relative scope,
1353                                               enum GNUNET_ATS_PreferenceKind kind,
1354                                               double score)
1355 {
1356   struct GAS_PROPORTIONAL_Handle *s = solver;
1357
1358   GNUNET_assert(NULL != peer);
1359   GNUNET_assert(NULL != s);
1360 }
1361
1362
1363 /**
1364  * Get the preferred address for a specific peer
1365  *
1366  * @param solver the solver handle
1367  * @param peer the identity of the peer
1368  * @return best address
1369  */
1370 static const struct ATS_Address *
1371 GAS_proportional_get_preferred_address (void *solver,
1372                                         const struct GNUNET_PeerIdentity *peer)
1373 {
1374   struct GAS_PROPORTIONAL_Handle *s = solver;
1375   const struct ATS_Address *best_address;
1376
1377   /* Add to list of pending requests */
1378   if (GNUNET_NO ==
1379       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1380   {
1381     GNUNET_assert (GNUNET_OK ==
1382                    GNUNET_CONTAINER_multipeermap_put (s->requests,
1383                                                      peer,
1384                                                      NULL,
1385             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1386     LOG (GNUNET_ERROR_TYPE_INFO,
1387          "Start suggesting addresses for peer `%s'\n",
1388          GNUNET_i2s (peer));
1389   }
1390
1391   best_address = update_active_address (s, peer);
1392   if (s->bulk_lock > 0)
1393     return NULL; /* Do not suggest since bulk lock is pending */
1394
1395   return best_address;
1396 }
1397
1398
1399 /**
1400  * Stop notifying about address and bandwidth changes for this peer
1401  *
1402  * @param solver the solver handle
1403  * @param peer the peer
1404  */
1405 static void
1406 GAS_proportional_stop_get_preferred_address (void *solver,
1407                                              const struct GNUNET_PeerIdentity *peer)
1408 {
1409   struct GAS_PROPORTIONAL_Handle *s = solver;
1410   struct ATS_Address *cur;
1411   struct AddressSolverInformation *asi;
1412   struct Network *cur_net;
1413
1414   if (GNUNET_YES ==
1415       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1416   {
1417     GNUNET_assert (GNUNET_OK ==
1418                    GNUNET_CONTAINER_multipeermap_remove (s->requests,
1419                                                          peer,
1420                                                          NULL));
1421     LOG (GNUNET_ERROR_TYPE_INFO,
1422          "Stop suggesting addresses for peer `%s'\n",
1423          GNUNET_i2s (peer));
1424   }
1425
1426   cur = get_active_address (s,
1427                             s->addresses,
1428                             peer);
1429   if (NULL != cur)
1430   {
1431     LOG (GNUNET_ERROR_TYPE_INFO,
1432          "Disabling %s address %p for peer `%s'\n",
1433          (GNUNET_NO == cur->active) ? "inactive" : "active",
1434          cur,
1435          GNUNET_i2s (&cur->peer));
1436
1437     /* Disabling current address */
1438     asi = cur->solver_information;
1439     cur_net = asi->network ;
1440     asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1441     cur->active = GNUNET_NO; /* No active any longer */
1442     cur->assigned_bw_in = 0; /* no bandwidth assigned */
1443     cur->assigned_bw_out = 0; /* no bandwidth assigned */
1444
1445     if (GNUNET_SYSERR ==
1446         addresse_decrement (s, cur_net, GNUNET_NO, GNUNET_YES))
1447       GNUNET_break(0);
1448
1449     distribute_bandwidth_in_network (s, cur_net);
1450   }
1451 }
1452
1453
1454 /**
1455  * Remove an address from the solver
1456  *
1457  * @param solver the solver handle
1458  * @param address the address to remove
1459  * @param session_only delete only session not whole address
1460  */
1461 static void
1462 GAS_proportional_address_delete (void *solver,
1463                                  struct ATS_Address *address,
1464                                  int session_only)
1465 {
1466   struct GAS_PROPORTIONAL_Handle *s = solver;
1467   struct Network *net;
1468   struct AddressWrapper *aw;
1469   struct AddressSolverInformation *asi;
1470
1471   /* Remove an adress completely, we have to:
1472    * - Remove from specific network
1473    * - Decrease number of total addresses
1474    * - If active:
1475    *   - decrease number of active addreses
1476    *   - update quotas
1477    */
1478   asi = address->solver_information;
1479
1480   if (NULL == asi)
1481   {
1482     GNUNET_break (0);
1483     return;
1484   }
1485   net = asi->network;
1486
1487   if (GNUNET_NO == session_only)
1488   {
1489     LOG (GNUNET_ERROR_TYPE_INFO,
1490          "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1491          (GNUNET_NO == address->active) ? "inactive" : "active",
1492          address,
1493          GNUNET_i2s (&address->peer),
1494          net->desc,
1495          net->total_addresses,
1496          net->active_addresses);
1497
1498     /* Remove address */
1499     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
1500     for (aw = net->head; NULL != aw; aw = aw->next)
1501     {
1502       if (aw->addr == address)
1503         break;
1504     }
1505     if (NULL == aw)
1506     {
1507       GNUNET_break(0);
1508       return;
1509     }
1510     GNUNET_CONTAINER_DLL_remove (net->head,
1511                                  net->tail,
1512                                  aw);
1513     GNUNET_free (aw);
1514   }
1515   else
1516   {
1517     /* Remove session only: remove if active and update */
1518     LOG (GNUNET_ERROR_TYPE_INFO,
1519          "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1520          (GNUNET_NO == address->active) ? "inactive" : "active",
1521          address,
1522          GNUNET_i2s (&address->peer),
1523          net->desc,
1524          net->total_addresses,
1525          net->active_addresses);
1526   }
1527
1528   if (GNUNET_YES == address->active)
1529   {
1530     /* Address was active, remove from network and update quotas*/
1531     address->active = GNUNET_NO;
1532     address->assigned_bw_in = 0;
1533     address->assigned_bw_out = 0;
1534     asi->calculated_quota_in = 0;
1535     asi->calculated_quota_out = 0;
1536
1537     if (GNUNET_SYSERR ==
1538         addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1539       GNUNET_break(0);
1540     distribute_bandwidth_in_network (s, net);
1541
1542     if (NULL ==
1543         update_active_address (s, &address->peer))
1544     {
1545       /* No alternative address found, disconnect peer */
1546       LOG (GNUNET_ERROR_TYPE_INFO,
1547            "Disconnecting peer `%s' after deleting previous address %p\n",
1548            GNUNET_i2s (&address->peer),
1549            address);
1550       s->bw_changed (s->bw_changed_cls,
1551                      address);
1552     }
1553   }
1554   if (GNUNET_NO == session_only)
1555   {
1556     GNUNET_free_non_null (address->solver_information);
1557     address->solver_information = NULL;
1558   }
1559
1560   LOG (GNUNET_ERROR_TYPE_INFO,
1561        "After deleting address now total %u and active %u addresses in network `%s'\n",
1562        net->total_addresses,
1563        net->active_addresses,
1564        net->desc);
1565 }
1566
1567
1568 /**
1569  * Start a bulk operation
1570  *
1571  * @param solver the solver
1572  */
1573 static void
1574 GAS_proportional_bulk_start (void *solver)
1575 {
1576   struct GAS_PROPORTIONAL_Handle *s = solver;
1577
1578   LOG (GNUNET_ERROR_TYPE_DEBUG,
1579        "Locking solver for bulk operation ...\n");
1580   GNUNET_assert (NULL != solver);
1581   s->bulk_lock++;
1582 }
1583
1584
1585 /**
1586  * Bulk operation done
1587  */
1588 static void
1589 GAS_proportional_bulk_stop (void *solver)
1590 {
1591   struct GAS_PROPORTIONAL_Handle *s = solver;
1592
1593   LOG (GNUNET_ERROR_TYPE_DEBUG,
1594        "Unlocking solver from bulk operation ...\n");
1595   if (s->bulk_lock < 1)
1596   {
1597     GNUNET_break(0);
1598     return;
1599   }
1600   s->bulk_lock--;
1601   if ((0 == s->bulk_lock) && (0 < s->bulk_requests))
1602   {
1603     LOG(GNUNET_ERROR_TYPE_INFO, "No lock pending, recalculating\n");
1604     distribute_bandwidth_in_network (s, NULL);
1605     s->bulk_requests = 0;
1606   }
1607 }
1608
1609
1610 /**
1611  * Add a new single address to a network
1612  *
1613  * @param solver the solver Handle
1614  * @param address the address to add
1615  * @param network network type of this address
1616  */
1617 static void
1618 GAS_proportional_address_add (void *solver,
1619                               struct ATS_Address *address,
1620                               uint32_t network);
1621
1622
1623 /**
1624  * Transport properties for this address have changed
1625  *
1626  * @param solver solver handle
1627  * @param address the address
1628  * @param type the ATSI type in HBO
1629  * @param abs_value the absolute value of the property
1630  * @param rel_value the normalized value
1631  */
1632 static void
1633 GAS_proportional_address_property_changed (void *solver,
1634                                            struct ATS_Address *address,
1635                                            uint32_t type,
1636                                            uint32_t abs_value,
1637                                            double rel_value)
1638 {
1639   struct GAS_PROPORTIONAL_Handle *s = solver;
1640   struct Network *n;
1641   struct AddressSolverInformation *asi;
1642   struct ATS_Address *best_address;
1643   struct ATS_Address *active_address;
1644
1645   asi = address->solver_information;
1646   if (NULL == asi)
1647   {
1648     GNUNET_break(0);
1649     return;
1650   }
1651
1652   n = asi->network;
1653   if (NULL == n)
1654   {
1655     GNUNET_break(0);
1656     return;
1657   }
1658
1659   LOG(GNUNET_ERROR_TYPE_INFO,
1660       "Property `%s' for peer `%s' address %p changed to %.2f \n",
1661       GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1662       address, rel_value);
1663
1664   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1665     return; /* Peer is not requested */
1666
1667   /* This peer is requested, find active and best address */
1668   active_address = get_active_address(s, s->addresses, &address->peer);
1669   best_address = update_active_address (s,
1670                                         &address->peer);
1671
1672   if ((NULL != best_address) && ((NULL != active_address) &&
1673       (GNUNET_YES == address_eq (active_address, best_address))))
1674   {
1675     asi = best_address->solver_information;
1676     GNUNET_assert (NULL != asi);
1677
1678     /* We sticked to the same address, therefore redistribute  */
1679     distribute_bandwidth_in_network (s, asi->network);
1680   }
1681 }
1682
1683
1684 /**
1685  * Add a new single address to a network
1686  *
1687  * @param solver the solver Handle
1688  * @param address the address to add
1689  * @param network network type of this address
1690  */
1691 static void
1692 GAS_proportional_address_add (void *solver,
1693                               struct ATS_Address *address,
1694                               uint32_t network)
1695 {
1696   struct GAS_PROPORTIONAL_Handle *s = solver;
1697   struct Network *net = NULL;
1698   struct AddressWrapper *aw = NULL;
1699   struct AddressSolverInformation *asi;
1700
1701   GNUNET_assert(NULL != s);
1702   net = get_network (s, network);
1703   if (NULL == net)
1704   {
1705     GNUNET_break(0);
1706
1707     LOG(GNUNET_ERROR_TYPE_ERROR,
1708         "Unknown network %u `%s' for new address %p for peer `%s'\n",
1709         network, GNUNET_ATS_print_network_type(network),
1710         address, GNUNET_i2s(&address->peer));
1711
1712     return;
1713   }
1714
1715   aw = GNUNET_new (struct AddressWrapper);
1716   aw->addr = address;
1717   GNUNET_CONTAINER_DLL_insert(net->head, net->tail, aw);
1718   address_increment (s, net, GNUNET_YES, GNUNET_NO);
1719
1720   asi = GNUNET_new (struct AddressSolverInformation);
1721   asi->network = net;
1722   asi->calculated_quota_in = 0;
1723   asi->calculated_quota_out = 0;
1724   aw->addr->solver_information = asi;
1725
1726   LOG(GNUNET_ERROR_TYPE_INFO,
1727       "Adding new address %p for peer `%s', now total %u and active %u addresses in network `%s'\n",
1728       address, GNUNET_i2s(&address->peer), net->total_addresses, net->active_addresses, net->desc);
1729
1730   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1731     return; /* Peer is not requested */
1732
1733   /* This peer is requested, find best address */
1734   update_active_address (s, &address->peer);
1735 }
1736
1737
1738
1739 /**
1740  * Function invoked when the plugin is loaded.
1741  *
1742  * @param[in,out] cls the `struct GNUNET_ATS_PluginEnvironment *` to use;
1743  *            modified to return the API functions (ugh).
1744  * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure
1745  */
1746 void *
1747 libgnunet_plugin_ats_proportional_init (void *cls)
1748 {
1749   struct GNUNET_ATS_PluginEnvironment *env = cls;
1750   struct GAS_PROPORTIONAL_Handle *s;
1751   struct Network * cur;
1752   float f_tmp;
1753   int c;
1754
1755   GNUNET_assert (NULL != env);
1756   GNUNET_assert (NULL != env->cfg);
1757   GNUNET_assert (NULL != env->bandwidth_changed_cb);
1758   GNUNET_assert (NULL != env->get_preferences);
1759   GNUNET_assert (NULL != env->get_property);
1760
1761   s = GNUNET_new (struct GAS_PROPORTIONAL_Handle);
1762   s->env = env;
1763   env->sf.s_add = &GAS_proportional_address_add;
1764   env->sf.s_address_update_property = &GAS_proportional_address_property_changed;
1765   env->sf.s_get = &GAS_proportional_get_preferred_address;
1766   env->sf.s_get_stop = &GAS_proportional_stop_get_preferred_address;
1767   env->sf.s_pref = &GAS_proportional_address_change_preference;
1768   env->sf.s_feedback = &GAS_proportional_address_preference_feedback;
1769   env->sf.s_del = &GAS_proportional_address_delete;
1770   env->sf.s_bulk_start = &GAS_proportional_bulk_start;
1771   env->sf.s_bulk_stop = &GAS_proportional_bulk_stop;
1772
1773   s->stats = (struct GNUNET_STATISTICS_Handle *) env->stats;
1774   s->bw_changed = env->bandwidth_changed_cb;
1775   s->bw_changed_cls = env->bw_changed_cb_cls;
1776   s->get_preferences = env->get_preferences;
1777   s->get_preferences_cls = env->get_preference_cls;
1778   s->get_properties = env->get_property;
1779   s->get_properties_cls = env->get_property_cls;
1780   s->network_count = env->network_count;
1781   s->network_entries = GNUNET_malloc (env->network_count * sizeof (struct Network));
1782
1783   /* Init */
1784   s->active_addresses = 0;
1785   s->total_addresses = 0;
1786   s->bulk_lock = GNUNET_NO;
1787   s->addresses = env->addresses;
1788   s->requests = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1789
1790   s->stability_factor = PROP_STABILITY_FACTOR;
1791   if (GNUNET_SYSERR !=
1792       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1793                                             "PROP_STABILITY_FACTOR", &f_tmp))
1794   {
1795     if ((f_tmp < 1.0) || (f_tmp > 2.0))
1796     {
1797       LOG (GNUNET_ERROR_TYPE_ERROR,
1798            _("Invalid %s configuration %f \n"),
1799            "PROP_STABILITY_FACTOR",
1800            f_tmp);
1801     }
1802     else
1803     {
1804       s->stability_factor = f_tmp;
1805       LOG (GNUNET_ERROR_TYPE_INFO,
1806            "Using %s of %.3f\n",
1807            "PROP_STABILITY_FACTOR", f_tmp);
1808     }
1809   }
1810
1811   s->prop_factor = PROPORTIONALITY_FACTOR;
1812   if (GNUNET_SYSERR !=
1813       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1814                                             "PROP_PROPORTIONALITY_FACTOR",
1815                                             &f_tmp))
1816   {
1817     if (f_tmp < 1.0)
1818     {
1819       LOG (GNUNET_ERROR_TYPE_ERROR,
1820            _("Invalid %s configuration %f \n"),
1821            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1822     }
1823     else
1824     {
1825       s->prop_factor = f_tmp;
1826       LOG (GNUNET_ERROR_TYPE_INFO,
1827            "Using %s of %.3f\n",
1828            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1829     }
1830   }
1831
1832   for (c = 0; c < env->network_count; c++)
1833   {
1834     cur = &s->network_entries[c];
1835     cur->type = env->networks[c];
1836     cur->total_quota_in = env->in_quota[c];
1837     cur->total_quota_out = env->out_quota[c];
1838     cur->desc = GNUNET_ATS_print_network_type (c);
1839     GNUNET_asprintf (&cur->stat_total,
1840                      "# ATS addresses %s total",
1841                      cur->desc);
1842     GNUNET_asprintf (&cur->stat_active,
1843                      "# ATS active addresses %s total",
1844                      cur->desc);
1845     LOG (GNUNET_ERROR_TYPE_INFO,
1846          "Added network %u `%s' (%llu/%llu)\n",
1847          c,
1848          cur->desc,
1849          cur->total_quota_in,
1850          cur->total_quota_out);
1851   }
1852   return s;
1853 }
1854
1855
1856 /* end of plugin_ats_proportional.c */