Various changes:
[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 GNUNET_TIME_Absolute now;
717   struct AddressSolverInformation *asi;
718   struct GNUNET_TIME_Relative active_time;
719   struct GNUNET_TIME_Relative min_active_time;
720   const double *norm_prop_cur;
721   const double *norm_prop_best;
722   double best_delay;
723   double best_distance;
724   double cur_delay;
725   double cur_distance;
726   int index;
727
728   current_best = NULL;
729   asi = current->solver_information;
730   now = GNUNET_TIME_absolute_get ();
731
732   if ((current->active == GNUNET_NO)
733       && (current->blocked_until.abs_value_us
734           == GNUNET_TIME_absolute_max (now, current->blocked_until).abs_value_us))
735   {
736     /* This address is blocked for suggestion */
737     LOG (GNUNET_ERROR_TYPE_DEBUG,
738          "Address %p blocked for suggestion for %s \n",
739          current,
740          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (now, current->blocked_until),
741                                                  GNUNET_YES));
742     return GNUNET_OK;
743   }
744   if (NULL == asi)
745   {
746     GNUNET_break (0);
747     return GNUNET_OK;
748   }
749
750   if (GNUNET_NO == is_bandwidth_available_in_network (asi->network))
751   {
752     return GNUNET_OK; /* There's no bandwidth available in this network */
753   }
754
755   if (NULL != ctx->best)
756   {
757     /* Compare current addresses with denominated 'best' address */
758     current_best = ctx->best;
759   }
760   else
761   {
762     /* We do not have a 'best' address so take this address */
763     LOG (GNUNET_ERROR_TYPE_DEBUG,
764          "Setting initial address %p\n",
765          current);
766     current_best = current;
767     goto end;
768   }
769
770   if (GNUNET_YES == current->active)
771   {
772     GNUNET_assert (asi->activated.abs_value_us != GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us);
773     active_time = GNUNET_TIME_absolute_get_duration (asi->activated);
774     min_active_time.rel_value_us =  ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) *
775         ctx->s->stability_factor;
776     if (active_time.rel_value_us <= min_active_time.rel_value_us)
777     {
778       /* Keep active address for stability reasons */
779       ctx->best = current;
780       return GNUNET_NO;
781     }
782   }
783
784   /* Now compare ATS information */
785   norm_prop_cur = ctx->s->get_properties (ctx->s->get_properties_cls,
786       (const struct ATS_Address *) current);
787   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
788   cur_distance = norm_prop_cur[index];
789   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
790   cur_delay = norm_prop_cur[index];
791
792   norm_prop_best = ctx->s->get_properties (ctx->s->get_properties_cls,
793       (const struct ATS_Address *) ctx->best);
794   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
795   best_distance = norm_prop_best[index];
796   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
797   best_delay = norm_prop_best[index];
798
799   /* user shorter distance */
800   if (cur_distance < best_distance)
801   {
802     if (GNUNET_NO == ctx->best->active)
803     {
804       current_best = current; /* Use current */
805     }
806     else if ((best_distance / cur_distance) > ctx->s->stability_factor)
807     {
808       /* Best and active address performs worse  */
809       current_best = current;
810     }
811   }
812   else
813   {
814     /* Use current best */
815     current_best = ctx->best;
816   }
817
818   /* User connection with less delay */
819   if (cur_delay < best_delay)
820   {
821
822     if (GNUNET_NO == ctx->best->active)
823     {
824       current_best = current; /* Use current */
825     }
826     else if ((best_delay / cur_delay) > ctx->s->stability_factor)
827     {
828       /* Best and active address performs worse  */
829       current_best = current;
830     }
831   }
832   else
833   {
834     /* Use current best */
835     current_best = ctx->best;
836   }
837
838 end:
839   ctx->best = current_best;
840   return GNUNET_OK;
841 }
842
843
844 /**
845  * Find the currently best address for a peer from the set of addresses available
846  * or return NULL of no address is available
847  *
848  * @param s the proportional handle
849  * @param addresses the address hashmap
850  * @param id the peer id
851  * @return the address or NULL
852  */
853 struct ATS_Address *
854 get_best_address (struct GAS_PROPORTIONAL_Handle *s,
855                   struct GNUNET_CONTAINER_MultiPeerMap *addresses,
856                   const struct GNUNET_PeerIdentity *id)
857 {
858   struct FindBestAddressCtx fba_ctx;
859
860   fba_ctx.best = NULL;
861   fba_ctx.s = s;
862   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
863                                               id,
864                                               &find_best_address_it,
865                                               &fba_ctx);
866   return fba_ctx.best;
867 }
868
869
870 /**
871  * Hashmap Iterator to find current active address for peer
872  *
873  * @param cls last active address
874  * @param key peer's key
875  * @param value address to check
876  * @return #GNUNET_NO on double active address else #GNUNET_YES;
877  */
878 static int
879 get_active_address_it (void *cls,
880                        const struct GNUNET_PeerIdentity *key,
881                        void *value)
882 {
883   struct ATS_Address **dest = cls;
884   struct ATS_Address *aa = (struct ATS_Address *) value;
885
886   LOG (GNUNET_ERROR_TYPE_INFO,
887          "Checking address %p\n", aa);
888
889   if (GNUNET_YES == aa->active)
890   {
891   LOG (GNUNET_ERROR_TYPE_INFO,
892          "Address %p is active\n", aa);
893     if (NULL != (*dest))
894     {
895       /* should never happen */
896       LOG (GNUNET_ERROR_TYPE_ERROR,
897            "Multiple active addresses for peer `%s'\n",
898            GNUNET_i2s (&aa->peer));
899       GNUNET_break(0);
900       return GNUNET_NO;
901     }
902     (*dest) = aa;
903
904   }
905   return GNUNET_OK;
906 }
907
908
909 /**
910  * Find current active address for peer
911  *
912  * @param solver the solver handle
913  * @param addresses the address set
914  * @param peer the peer
915  * @return active address or NULL
916  */
917 static struct ATS_Address *
918 get_active_address (void *solver,
919                     const struct GNUNET_CONTAINER_MultiPeerMap * addresses,
920                     const struct GNUNET_PeerIdentity *peer)
921 {
922   static struct ATS_Address * dest = NULL;
923
924   dest = NULL;
925   GNUNET_CONTAINER_multipeermap_get_multiple (addresses, peer,
926                                               &get_active_address_it, &dest);
927   return dest;
928 }
929
930
931 /**
932  * Lookup network struct by type
933  *
934  * @param s the solver handle
935  * @param type the network type
936  * @return the network struct
937  */
938 static struct Network *
939 get_network (struct GAS_PROPORTIONAL_Handle *s, uint32_t type)
940 {
941   int c;
942   for (c = 0; c < s->network_count; c++)
943   {
944     if (s->network_entries[c].type == type)
945       return &s->network_entries[c];
946   }
947   return NULL ;
948 }
949
950
951 /**
952  * Increase address count in network
953  *
954  * @param s the solver handle
955  * @param net the network type
956  * @param total increase total addresses
957  * @param active increase active addresses
958  */
959 static void
960 address_increment (struct GAS_PROPORTIONAL_Handle *s,
961                     struct Network *net,
962                     int total,
963                     int active)
964 {
965   if (GNUNET_YES == total)
966   {
967     s->total_addresses++;
968     net->total_addresses++;
969     GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
970     GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
971   }
972   if (GNUNET_YES == active)
973   {
974     net->active_addresses++;
975     s->active_addresses++;
976     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1,
977         GNUNET_NO);
978     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
979   }
980
981 }
982
983
984 /**
985  * Decrease address count in network
986  *
987  * @param s the solver handle
988  * @param net the network type
989  * @param total decrease total addresses
990  * @param active decrease active addresses
991  */
992 static int
993 addresse_decrement (struct GAS_PROPORTIONAL_Handle *s,
994                     struct Network *net,
995                     int total,
996                     int active)
997 {
998   int res = GNUNET_OK;
999
1000   if (GNUNET_YES == total)
1001   {
1002     if (s->total_addresses < 1)
1003     {
1004       GNUNET_break(0);
1005       res = GNUNET_SYSERR;
1006     }
1007     else
1008     {
1009       s->total_addresses--;
1010       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
1011           GNUNET_NO);
1012     }
1013     if (net->total_addresses < 1)
1014     {
1015       GNUNET_break(0);
1016       res = GNUNET_SYSERR;
1017     }
1018     else
1019     {
1020       net->total_addresses--;
1021       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
1022     }
1023   }
1024
1025   if (GNUNET_YES == active)
1026   {
1027     if (net->active_addresses < 1)
1028     {
1029       GNUNET_break(0);
1030       res = GNUNET_SYSERR;
1031     }
1032     else
1033     {
1034       net->active_addresses--;
1035       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
1036     }
1037     if (s->active_addresses < 1)
1038     {
1039       GNUNET_break(0);
1040       res = GNUNET_SYSERR;
1041     }
1042     else
1043     {
1044       s->active_addresses--;
1045       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
1046           GNUNET_NO);
1047     }
1048   }
1049   return res;
1050 }
1051
1052
1053 /**
1054  * Compares addresses
1055  *
1056  * @param a address a
1057  * @param b address b
1058  * @return GNUNET_YES if equal, GNUNET_NO else
1059  */
1060 static int
1061 address_eq (struct ATS_Address *a, struct ATS_Address *b)
1062 {
1063   GNUNET_assert (NULL != a);
1064   GNUNET_assert (NULL != b);
1065   if (0 != strcmp(a->plugin, b->plugin))
1066     return GNUNET_NO;
1067   if (a->addr_len != b->addr_len)
1068     return GNUNET_NO;
1069   if (0 != memcmp (a->addr, b->addr, b->addr_len))
1070     return GNUNET_NO;
1071   if (a->session_id != b->session_id)
1072     return GNUNET_NO;
1073   return GNUNET_YES;
1074 }
1075
1076
1077 /**
1078  * Notify bandwidth changes to addresses
1079  *
1080  * @param s solver handle
1081  * @param net the network to propagate changes in
1082  */
1083 static void
1084 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
1085                      struct Network *net)
1086 {
1087   struct AddressWrapper *cur;
1088   struct AddressSolverInformation *asi;
1089   for (cur = net->head; NULL != cur; cur = cur->next)
1090   {
1091       asi = cur->addr->solver_information;
1092       if ( (cur->addr->assigned_bw_in != asi->calculated_quota_in) ||
1093            (cur->addr->assigned_bw_out != asi->calculated_quota_out) )
1094       {
1095         cur->addr->assigned_bw_in = asi->calculated_quota_in;
1096         cur->addr->assigned_bw_out = asi->calculated_quota_out;
1097
1098         /* Reset for next iteration */
1099         asi->calculated_quota_in = 0;
1100         asi->calculated_quota_out = 0;
1101         LOG (GNUNET_ERROR_TYPE_DEBUG,
1102             "Bandwidth for %s address %p for peer `%s' changed to %u/%u\n",
1103             (GNUNET_NO == cur->addr->active) ? "inactive" : "active",
1104             cur->addr,
1105             GNUNET_i2s (&cur->addr->peer),
1106             cur->addr->assigned_bw_in,
1107             cur->addr->assigned_bw_out);
1108
1109         /* Notify on change */
1110         if ((GNUNET_YES == cur->addr->active))
1111         {
1112           s->bw_changed (s->bw_changed_cls, cur->addr);
1113         }
1114       }
1115   }
1116 }
1117
1118
1119 /**
1120  * Distribibute bandwidth
1121  *
1122  * @param s the solver handle
1123  * @param n the network, can be NULL for all network
1124  */
1125 static void
1126 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
1127                                  struct Network *n)
1128 {
1129   if (GNUNET_YES == s->bulk_lock)
1130   {
1131     s->bulk_requests++;
1132     return;
1133   }
1134
1135   if (NULL != n)
1136   {
1137     LOG (GNUNET_ERROR_TYPE_INFO,
1138         "Redistributing bandwidth in network %s with %u active and %u total addresses\n",
1139         GNUNET_ATS_print_network_type(n->type),
1140         n->active_addresses, n->total_addresses);
1141
1142     if (NULL != s->env->info_cb)
1143       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
1144           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1145
1146     /* Distribute  */
1147     distribute_bandwidth(s, n);
1148
1149     if (NULL != s->env->info_cb)
1150       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
1151           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1152     if (NULL != s->env->info_cb)
1153       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1154           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1155
1156     /* Do propagation */
1157     propagate_bandwidth (s, n);
1158
1159     if (NULL != s->env->info_cb)
1160       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1161           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1162   }
1163   else
1164   {
1165     int i;
1166     if (NULL != s->env->info_cb)
1167       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
1168           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1169     for (i = 0; i < s->network_count; i++)
1170     {
1171       /* Distribute */
1172       distribute_bandwidth(s, &s->network_entries[i]);
1173     }
1174
1175     if (NULL != s->env->info_cb)
1176       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
1177           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1178     if (NULL != s->env->info_cb)
1179       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1180           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1181     for (i = 0; i < s->network_count; i++)
1182     {
1183       /* Do propagation */
1184       propagate_bandwidth(s, &s->network_entries[i]);
1185     }
1186     if (NULL != s->env->info_cb)
1187       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1188           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1189   }
1190 }
1191
1192
1193 /**
1194  * Update active address for a peer:
1195  * Check if active address exists and what the best address is, if addresses
1196  * are different switch
1197  *
1198  * @param s solver handle
1199  * @param peer the peer to check
1200  * return the new address or NULL if no update was performed
1201   */
1202 static struct ATS_Address *
1203 update_active_address (struct GAS_PROPORTIONAL_Handle *s,
1204                        const struct GNUNET_PeerIdentity *peer)
1205 {
1206   struct ATS_Address *best_address;
1207   struct ATS_Address *current_address;
1208   struct AddressSolverInformation *asi;
1209   struct Network *net;
1210
1211   LOG (GNUNET_ERROR_TYPE_INFO,
1212        "Updating active address for peer `%s'\n",
1213        GNUNET_i2s (peer));
1214
1215   /* Find active address */
1216   current_address = get_active_address (s,
1217                                         s->addresses,
1218                                         peer);
1219
1220   LOG (GNUNET_ERROR_TYPE_INFO,
1221        "Peer `%s' has active address %p\n",
1222        GNUNET_i2s (peer),
1223        current_address);
1224
1225   /* Find best address */
1226   best_address = get_best_address (s,
1227                                    s->addresses,
1228                                    peer);
1229   LOG (GNUNET_ERROR_TYPE_INFO,
1230        "Peer `%s' has best address %p\n",
1231        GNUNET_i2s (peer),
1232        best_address);
1233
1234   if (NULL != current_address)
1235   {
1236     if ( (NULL == best_address) ||
1237          ( (NULL != best_address) &&
1238            (GNUNET_NO == address_eq (current_address,
1239                                      best_address)) ) )
1240     {
1241       /* We switch to a new address (or to none),
1242          mark old address as inactive */
1243       LOG (GNUNET_ERROR_TYPE_INFO,
1244            "Disabling previous %s address %p for peer `%s'\n",
1245            (GNUNET_NO == current_address->active) ? "inactive" : "active",
1246            current_address,
1247            GNUNET_i2s (peer));
1248
1249       asi = current_address->solver_information;
1250       GNUNET_assert (NULL != asi);
1251
1252       net = asi->network;
1253       asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1254       current_address->active = GNUNET_NO; /* No active any longer */
1255       current_address->assigned_bw_in = 0; /* no bandwidth assigned */
1256       current_address->assigned_bw_out = 0; /* no bandwidth assigned */
1257
1258       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1259         GNUNET_break(0);
1260
1261       /* Update network of previous address */
1262       distribute_bandwidth_in_network (s, net);
1263     }
1264     if (NULL == best_address)
1265     {
1266       /* We previously had an active address, but now we cannot suggest one
1267        * Therefore we have to disconnect the peer */
1268       LOG (GNUNET_ERROR_TYPE_INFO,
1269            "Disconnecting peer `%s' with previous address %p\n",
1270            GNUNET_i2s (peer),
1271            current_address);
1272       s->bw_changed (s->bw_changed_cls,
1273                      current_address);
1274     }
1275   }
1276   if (NULL == best_address)
1277   {
1278     LOG (GNUNET_ERROR_TYPE_INFO,
1279          "Cannot suggest address for peer `%s'\n",
1280          GNUNET_i2s (peer));
1281     return NULL;
1282   }
1283
1284   LOG (GNUNET_ERROR_TYPE_INFO,
1285        "Suggesting new address %p for peer `%s'\n",
1286        best_address,
1287        GNUNET_i2s (peer));
1288
1289   if ( (NULL != current_address) &&
1290        (GNUNET_YES == address_eq (best_address, current_address)) )
1291   {
1292     GNUNET_break (GNUNET_NO != current_address->active);
1293     return best_address; /* Same same */
1294   }
1295
1296   asi = best_address->solver_information;
1297   GNUNET_assert (NULL != asi);
1298   net = asi->network;
1299
1300   /* Mark address as active */
1301   asi->activated = GNUNET_TIME_absolute_get ();
1302   best_address->active = GNUNET_YES;
1303   address_increment (s, net, GNUNET_NO, GNUNET_YES);
1304   LOG (GNUNET_ERROR_TYPE_INFO,
1305        "Address %p for peer `%s' is now active\n",
1306        best_address,
1307        GNUNET_i2s (peer));
1308   /* Distribute bandwidth */
1309   distribute_bandwidth_in_network (s, net);
1310   return best_address;
1311 }
1312
1313
1314 /**
1315  * Changes the preferences for a peer in the problem
1316  *
1317  * @param solver the solver handle
1318  * @param peer the peer to change the preference for
1319  * @param kind the kind to change the preference
1320  * @param pref_rel the normalized preference value for this kind over all clients
1321  */
1322 static void
1323 GAS_proportional_address_change_preference (void *solver,
1324                                             const struct GNUNET_PeerIdentity *peer,
1325                                             enum GNUNET_ATS_PreferenceKind kind,
1326                                             double pref_rel)
1327 {
1328   struct GAS_PROPORTIONAL_Handle *s = solver;
1329   struct ATS_Address *best_address;
1330   struct ATS_Address *active_address;
1331   struct AddressSolverInformation *asi;
1332
1333   if (GNUNET_NO ==
1334       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1335     return; /* Peer is not requested */
1336
1337   /* This peer is requested, find best address */
1338   active_address = get_active_address (s, s->addresses, peer);
1339   best_address = update_active_address (s, peer);
1340
1341   if ((NULL != best_address) && ((NULL != active_address) &&
1342       (GNUNET_YES == address_eq (active_address, best_address))))
1343   {
1344     asi = best_address->solver_information;
1345     GNUNET_assert (NULL != asi);
1346
1347     /* We sticked to the same address, therefore redistribute  */
1348     distribute_bandwidth_in_network (s, asi->network);
1349   }
1350 }
1351
1352
1353 /**
1354  * Get application feedback for a peer
1355  *
1356  * @param solver the solver handle
1357  * @param application the application
1358  * @param peer the peer to change the preference for
1359  * @param scope the time interval for this feedback: [now - scope .. now]
1360  * @param kind the kind to change the preference
1361  * @param score the score
1362  */
1363 static void
1364 GAS_proportional_address_preference_feedback (void *solver,
1365                                               void *application,
1366                                               const struct GNUNET_PeerIdentity *peer,
1367                                               const struct GNUNET_TIME_Relative scope,
1368                                               enum GNUNET_ATS_PreferenceKind kind,
1369                                               double score)
1370 {
1371   struct GAS_PROPORTIONAL_Handle *s = solver;
1372
1373   GNUNET_assert(NULL != peer);
1374   GNUNET_assert(NULL != s);
1375 }
1376
1377
1378 /**
1379  * Get the preferred address for a specific peer
1380  *
1381  * @param solver the solver handle
1382  * @param peer the identity of the peer
1383  * @return best address
1384  */
1385 static const struct ATS_Address *
1386 GAS_proportional_get_preferred_address (void *solver,
1387                                         const struct GNUNET_PeerIdentity *peer)
1388 {
1389   struct GAS_PROPORTIONAL_Handle *s = solver;
1390   const struct ATS_Address *best_address;
1391
1392   /* Add to list of pending requests */
1393   if (GNUNET_NO ==
1394       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1395   {
1396     GNUNET_assert (GNUNET_OK ==
1397                    GNUNET_CONTAINER_multipeermap_put (s->requests,
1398                                                      peer,
1399                                                      NULL,
1400             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1401     LOG (GNUNET_ERROR_TYPE_INFO,
1402          "Start suggesting addresses for peer `%s'\n",
1403          GNUNET_i2s (peer));
1404   }
1405
1406   best_address = update_active_address (s, peer);
1407   if (s->bulk_lock > 0)
1408     return NULL; /* Do not suggest since bulk lock is pending */
1409
1410   return best_address;
1411 }
1412
1413
1414 /**
1415  * Stop notifying about address and bandwidth changes for this peer
1416  *
1417  * @param solver the solver handle
1418  * @param peer the peer
1419  */
1420 static void
1421 GAS_proportional_stop_get_preferred_address (void *solver,
1422                                              const struct GNUNET_PeerIdentity *peer)
1423 {
1424   struct GAS_PROPORTIONAL_Handle *s = solver;
1425   struct ATS_Address *cur;
1426   struct AddressSolverInformation *asi;
1427   struct Network *cur_net;
1428
1429   if (GNUNET_YES ==
1430       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1431   {
1432     GNUNET_assert (GNUNET_OK ==
1433                    GNUNET_CONTAINER_multipeermap_remove (s->requests,
1434                                                          peer,
1435                                                          NULL));
1436     LOG (GNUNET_ERROR_TYPE_INFO,
1437          "Stop suggesting addresses for peer `%s'\n",
1438          GNUNET_i2s (peer));
1439   }
1440
1441   cur = get_active_address (s,
1442                             s->addresses,
1443                             peer);
1444   if (NULL != cur)
1445   {
1446     LOG (GNUNET_ERROR_TYPE_INFO,
1447          "Disabling %s address %p for peer `%s'\n",
1448          (GNUNET_NO == cur->active) ? "inactive" : "active",
1449          cur,
1450          GNUNET_i2s (&cur->peer));
1451
1452     /* Disabling current address */
1453     asi = cur->solver_information;
1454     cur_net = asi->network ;
1455     asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1456     cur->active = GNUNET_NO; /* No active any longer */
1457     cur->assigned_bw_in = 0; /* no bandwidth assigned */
1458     cur->assigned_bw_out = 0; /* no bandwidth assigned */
1459
1460     if (GNUNET_SYSERR ==
1461         addresse_decrement (s, cur_net, GNUNET_NO, GNUNET_YES))
1462       GNUNET_break(0);
1463
1464     distribute_bandwidth_in_network (s, cur_net);
1465   }
1466 }
1467
1468
1469 /**
1470  * Remove an address from the solver
1471  *
1472  * @param solver the solver handle
1473  * @param address the address to remove
1474  * @param session_only delete only session not whole address
1475  */
1476 static void
1477 GAS_proportional_address_delete (void *solver,
1478                                  struct ATS_Address *address,
1479                                  int session_only)
1480 {
1481   struct GAS_PROPORTIONAL_Handle *s = solver;
1482   struct Network *net;
1483   struct AddressWrapper *aw;
1484   struct AddressSolverInformation *asi;
1485
1486   /* Remove an adress completely, we have to:
1487    * - Remove from specific network
1488    * - Decrease number of total addresses
1489    * - If active:
1490    *   - decrease number of active addreses
1491    *   - update quotas
1492    */
1493   asi = address->solver_information;
1494
1495   if (NULL == asi)
1496   {
1497     GNUNET_break (0);
1498     return;
1499   }
1500   net = asi->network;
1501
1502   if (GNUNET_NO == session_only)
1503   {
1504     LOG (GNUNET_ERROR_TYPE_INFO,
1505          "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1506          (GNUNET_NO == address->active) ? "inactive" : "active",
1507          address,
1508          GNUNET_i2s (&address->peer),
1509          net->desc,
1510          net->total_addresses,
1511          net->active_addresses);
1512
1513     /* Remove address */
1514     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
1515     for (aw = net->head; NULL != aw; aw = aw->next)
1516     {
1517       if (aw->addr == address)
1518         break;
1519     }
1520     if (NULL == aw)
1521     {
1522       GNUNET_break(0);
1523       return;
1524     }
1525     GNUNET_CONTAINER_DLL_remove (net->head,
1526                                  net->tail,
1527                                  aw);
1528     GNUNET_free (aw);
1529   }
1530   else
1531   {
1532     /* Remove session only: remove if active and update */
1533     LOG (GNUNET_ERROR_TYPE_INFO,
1534          "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1535          (GNUNET_NO == address->active) ? "inactive" : "active",
1536          address,
1537          GNUNET_i2s (&address->peer),
1538          net->desc,
1539          net->total_addresses,
1540          net->active_addresses);
1541   }
1542
1543   if (GNUNET_YES == address->active)
1544   {
1545     /* Address was active, remove from network and update quotas*/
1546     address->active = GNUNET_NO;
1547     address->assigned_bw_in = 0;
1548     address->assigned_bw_out = 0;
1549     asi->calculated_quota_in = 0;
1550     asi->calculated_quota_out = 0;
1551
1552     if (GNUNET_SYSERR ==
1553         addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1554       GNUNET_break(0);
1555     distribute_bandwidth_in_network (s, net);
1556
1557     if (NULL ==
1558         update_active_address (s, &address->peer))
1559     {
1560       /* No alternative address found, disconnect peer */
1561       LOG (GNUNET_ERROR_TYPE_INFO,
1562            "Disconnecting peer `%s' after deleting previous address %p\n",
1563            GNUNET_i2s (&address->peer),
1564            address);
1565       s->bw_changed (s->bw_changed_cls,
1566                      address);
1567     }
1568   }
1569   if (GNUNET_NO == session_only)
1570   {
1571     GNUNET_free_non_null (address->solver_information);
1572     address->solver_information = NULL;
1573   }
1574
1575   LOG (GNUNET_ERROR_TYPE_INFO,
1576        "After deleting address now total %u and active %u addresses in network `%s'\n",
1577        net->total_addresses,
1578        net->active_addresses,
1579        net->desc);
1580 }
1581
1582
1583 /**
1584  * Start a bulk operation
1585  *
1586  * @param solver the solver
1587  */
1588 static void
1589 GAS_proportional_bulk_start (void *solver)
1590 {
1591   struct GAS_PROPORTIONAL_Handle *s = solver;
1592
1593   LOG (GNUNET_ERROR_TYPE_DEBUG,
1594        "Locking solver for bulk operation ...\n");
1595   GNUNET_assert (NULL != solver);
1596   s->bulk_lock++;
1597 }
1598
1599
1600 /**
1601  * Bulk operation done
1602  */
1603 static void
1604 GAS_proportional_bulk_stop (void *solver)
1605 {
1606   struct GAS_PROPORTIONAL_Handle *s = solver;
1607
1608   LOG (GNUNET_ERROR_TYPE_DEBUG,
1609        "Unlocking solver from bulk operation ...\n");
1610   if (s->bulk_lock < 1)
1611   {
1612     GNUNET_break(0);
1613     return;
1614   }
1615   s->bulk_lock--;
1616   if ((0 == s->bulk_lock) && (0 < s->bulk_requests))
1617   {
1618     LOG(GNUNET_ERROR_TYPE_INFO, "No lock pending, recalculating\n");
1619     distribute_bandwidth_in_network (s, NULL);
1620     s->bulk_requests = 0;
1621   }
1622 }
1623
1624
1625 /**
1626  * Add a new single address to a network
1627  *
1628  * @param solver the solver Handle
1629  * @param address the address to add
1630  * @param network network type of this address
1631  */
1632 static void
1633 GAS_proportional_address_add (void *solver,
1634                               struct ATS_Address *address,
1635                               uint32_t network);
1636
1637
1638 /**
1639  * Transport properties for this address have changed
1640  *
1641  * @param solver solver handle
1642  * @param address the address
1643  * @param type the ATSI type in HBO
1644  * @param abs_value the absolute value of the property
1645  * @param rel_value the normalized value
1646  */
1647 static void
1648 GAS_proportional_address_property_changed (void *solver,
1649                                            struct ATS_Address *address,
1650                                            uint32_t type,
1651                                            uint32_t abs_value,
1652                                            double rel_value)
1653 {
1654   struct GAS_PROPORTIONAL_Handle *s = solver;
1655   struct Network *n;
1656   struct AddressSolverInformation *asi;
1657   struct ATS_Address *best_address;
1658   struct ATS_Address *active_address;
1659
1660   asi = address->solver_information;
1661   if (NULL == asi)
1662   {
1663     GNUNET_break(0);
1664     return;
1665   }
1666
1667   n = asi->network;
1668   if (NULL == n)
1669   {
1670     GNUNET_break(0);
1671     return;
1672   }
1673
1674   LOG(GNUNET_ERROR_TYPE_INFO,
1675       "Property `%s' for peer `%s' address %p changed to %.2f \n",
1676       GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1677       address, rel_value);
1678
1679   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1680     return; /* Peer is not requested */
1681
1682   /* This peer is requested, find active and best address */
1683   active_address = get_active_address(s, s->addresses, &address->peer);
1684   best_address = update_active_address (s,
1685                                         &address->peer);
1686
1687   if ((NULL != best_address) && ((NULL != active_address) &&
1688       (GNUNET_YES == address_eq (active_address, best_address))))
1689   {
1690     asi = best_address->solver_information;
1691     GNUNET_assert (NULL != asi);
1692
1693     /* We sticked to the same address, therefore redistribute  */
1694     distribute_bandwidth_in_network (s, asi->network);
1695   }
1696 }
1697
1698 /**
1699  * Transport session for this address has changed
1700  *
1701  * NOTE: values in addresses are already updated
1702  *
1703  * @param solver solver handle
1704  * @param address the address
1705  * @param cur_session the current session
1706  * @param new_session the new session
1707  */
1708 static void
1709 GAS_proportional_address_session_changed (void *solver,
1710                                           struct ATS_Address *address,
1711                                           uint32_t cur_session,
1712                                           uint32_t new_session)
1713 {
1714   struct GAS_PROPORTIONAL_Handle *s = solver;
1715   struct ATS_Address *best_address;
1716   struct ATS_Address *active_address;
1717   struct AddressSolverInformation *asi;
1718
1719   if (cur_session != new_session)
1720   {
1721     LOG (GNUNET_ERROR_TYPE_DEBUG,
1722          "Session changed from %u to %u\n",
1723          cur_session,
1724          new_session);
1725   }
1726
1727   if (NULL == address->solver_information)
1728   {
1729     GNUNET_break (0);
1730     return;
1731   }
1732
1733   if (GNUNET_NO ==
1734       GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1735     return; /* Peer is not requested */
1736
1737   /* This peer is requested, find active and best address */
1738   active_address = get_active_address (s, s->addresses, &address->peer);
1739   best_address = update_active_address (s, &address->peer);
1740
1741   if ((NULL != best_address) && ((NULL != active_address) &&
1742       (GNUNET_YES == address_eq (active_address, best_address))))
1743   {
1744     asi = best_address->solver_information;
1745     GNUNET_assert (NULL != asi);
1746
1747     /* We sticked to the same address, therefore redistribute  */
1748     distribute_bandwidth_in_network (s, asi->network);
1749   }
1750 }
1751
1752
1753 /**
1754  * Network scope for this address has changed
1755  *
1756  * NOTE: values in addresses are already updated
1757  *
1758  * @param solver solver handle
1759  * @param address the address
1760  * @param current_network the current network
1761  * @param new_network the new network
1762  */
1763 static void
1764 GAS_proportional_address_change_network (void *solver,
1765                                          struct ATS_Address *address,
1766                                          uint32_t current_network,
1767                                          uint32_t new_network)
1768 {
1769   struct GAS_PROPORTIONAL_Handle *s = solver;
1770   struct AddressSolverInformation *asi;
1771   int save_active = GNUNET_NO;
1772
1773   if (current_network == new_network)
1774   {
1775     GNUNET_break(0);
1776     return;
1777   }
1778
1779   asi = address->solver_information;
1780   if (NULL == asi)
1781   {
1782     GNUNET_break(0);
1783     return;
1784   }
1785
1786   /* Network changed */
1787   LOG(GNUNET_ERROR_TYPE_DEBUG,
1788       "Network type changed, moving %s address from `%s' to `%s'\n",
1789       (GNUNET_YES == address->active) ? "active" : "inactive",
1790       GNUNET_ATS_print_network_type (current_network),
1791       GNUNET_ATS_print_network_type (new_network));
1792
1793
1794   /* Start bulk to prevent disconnect */
1795   GAS_proportional_bulk_start(s);
1796
1797   save_active = address->active;
1798
1799   /* Disable and assign no bandwidth */
1800   address->active = GNUNET_NO;
1801   address->assigned_bw_in = 0; /* no bandwidth assigned */
1802   address->assigned_bw_out = 0; /* no bandwidth assigned */
1803
1804   /* Remove from old network */
1805   GAS_proportional_address_delete (solver, address, GNUNET_NO);
1806
1807   /* Set new network type */
1808   if (NULL == get_network (solver, new_network))
1809   {
1810     /* Address changed to invalid network... */
1811     LOG(GNUNET_ERROR_TYPE_ERROR,
1812         _("Invalid network type `%u' `%s': Disconnect!\n"), new_network,
1813         GNUNET_ATS_print_network_type (new_network));
1814     s->bw_changed (s->bw_changed_cls, address);
1815   }
1816   else
1817   {
1818     /* Add to new network and update*/
1819     GAS_proportional_address_add (solver, address, new_network);
1820   }
1821   GAS_proportional_bulk_stop (s);
1822
1823   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1824     return; /* Peer is not requested */
1825
1826   /* Find new address to suggest */
1827   if (GNUNET_YES == save_active)
1828   {
1829     /* No address available, therefore disconnect */
1830     if (NULL == update_active_address (s, &address->peer))
1831       s->bw_changed (s->bw_changed_cls, address);
1832   }
1833
1834 }
1835
1836 /**
1837  * Add a new single address to a network
1838  *
1839  * @param solver the solver Handle
1840  * @param address the address to add
1841  * @param network network type of this address
1842  */
1843 static void
1844 GAS_proportional_address_add (void *solver,
1845                               struct ATS_Address *address,
1846                               uint32_t network)
1847 {
1848   struct GAS_PROPORTIONAL_Handle *s = solver;
1849   struct Network *net = NULL;
1850   struct AddressWrapper *aw = NULL;
1851   struct AddressSolverInformation *asi;
1852
1853   GNUNET_assert(NULL != s);
1854   net = get_network (s, network);
1855   if (NULL == net)
1856   {
1857     GNUNET_break(0);
1858
1859     LOG(GNUNET_ERROR_TYPE_ERROR,
1860         "Unknown network %u `%s' for new address %p for peer `%s'\n",
1861         network, GNUNET_ATS_print_network_type(network),
1862         address, GNUNET_i2s(&address->peer));
1863
1864     return;
1865   }
1866
1867   aw = GNUNET_new (struct AddressWrapper);
1868   aw->addr = address;
1869   GNUNET_CONTAINER_DLL_insert(net->head, net->tail, aw);
1870   address_increment (s, net, GNUNET_YES, GNUNET_NO);
1871
1872   asi = GNUNET_new (struct AddressSolverInformation);
1873   asi->network = net;
1874   asi->calculated_quota_in = 0;
1875   asi->calculated_quota_out = 0;
1876   aw->addr->solver_information = asi;
1877
1878   LOG(GNUNET_ERROR_TYPE_INFO,
1879       "Adding new address %p for peer `%s', now total %u and active %u addresses in network `%s'\n",
1880       address, GNUNET_i2s(&address->peer), net->total_addresses, net->active_addresses, net->desc);
1881
1882   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1883     return; /* Peer is not requested */
1884
1885   /* This peer is requested, find best address */
1886   update_active_address (s, &address->peer);
1887 }
1888
1889
1890
1891 /**
1892  * Function invoked when the plugin is loaded.
1893  *
1894  * @param[in,out] cls the `struct GNUNET_ATS_PluginEnvironment *` to use;
1895  *            modified to return the API functions (ugh).
1896  * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure
1897  */
1898 void *
1899 libgnunet_plugin_ats_proportional_init (void *cls)
1900 {
1901   struct GNUNET_ATS_PluginEnvironment *env = cls;
1902   struct GAS_PROPORTIONAL_Handle *s;
1903   struct Network * cur;
1904   float f_tmp;
1905   int c;
1906
1907   GNUNET_assert (NULL != env);
1908   GNUNET_assert (NULL != env->cfg);
1909   GNUNET_assert (NULL != env->bandwidth_changed_cb);
1910   GNUNET_assert (NULL != env->get_preferences);
1911   GNUNET_assert (NULL != env->get_property);
1912
1913   s = GNUNET_new (struct GAS_PROPORTIONAL_Handle);
1914   s->env = env;
1915   env->sf.s_add = &GAS_proportional_address_add;
1916   env->sf.s_address_update_property = &GAS_proportional_address_property_changed;
1917   env->sf.s_address_update_session = &GAS_proportional_address_session_changed;
1918   env->sf.s_address_update_network = &GAS_proportional_address_change_network;
1919   env->sf.s_get = &GAS_proportional_get_preferred_address;
1920   env->sf.s_get_stop = &GAS_proportional_stop_get_preferred_address;
1921   env->sf.s_pref = &GAS_proportional_address_change_preference;
1922   env->sf.s_feedback = &GAS_proportional_address_preference_feedback;
1923   env->sf.s_del = &GAS_proportional_address_delete;
1924   env->sf.s_bulk_start = &GAS_proportional_bulk_start;
1925   env->sf.s_bulk_stop = &GAS_proportional_bulk_stop;
1926
1927   s->stats = (struct GNUNET_STATISTICS_Handle *) env->stats;
1928   s->bw_changed = env->bandwidth_changed_cb;
1929   s->bw_changed_cls = env->bw_changed_cb_cls;
1930   s->get_preferences = env->get_preferences;
1931   s->get_preferences_cls = env->get_preference_cls;
1932   s->get_properties = env->get_property;
1933   s->get_properties_cls = env->get_property_cls;
1934   s->network_count = env->network_count;
1935   s->network_entries = GNUNET_malloc (env->network_count * sizeof (struct Network));
1936
1937   /* Init */
1938   s->active_addresses = 0;
1939   s->total_addresses = 0;
1940   s->bulk_lock = GNUNET_NO;
1941   s->addresses = env->addresses;
1942   s->requests = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1943
1944   s->stability_factor = PROP_STABILITY_FACTOR;
1945   if (GNUNET_SYSERR !=
1946       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1947                                             "PROP_STABILITY_FACTOR", &f_tmp))
1948   {
1949     if ((f_tmp < 1.0) || (f_tmp > 2.0))
1950     {
1951       LOG (GNUNET_ERROR_TYPE_ERROR,
1952            _("Invalid %s configuration %f \n"),
1953            "PROP_STABILITY_FACTOR",
1954            f_tmp);
1955     }
1956     else
1957     {
1958       s->stability_factor = f_tmp;
1959       LOG (GNUNET_ERROR_TYPE_INFO,
1960            "Using %s of %.3f\n",
1961            "PROP_STABILITY_FACTOR", f_tmp);
1962     }
1963   }
1964
1965   s->prop_factor = PROPORTIONALITY_FACTOR;
1966   if (GNUNET_SYSERR !=
1967       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1968                                             "PROP_PROPORTIONALITY_FACTOR",
1969                                             &f_tmp))
1970   {
1971     if (f_tmp < 1.0)
1972     {
1973       LOG (GNUNET_ERROR_TYPE_ERROR,
1974            _("Invalid %s configuration %f \n"),
1975            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1976     }
1977     else
1978     {
1979       s->prop_factor = f_tmp;
1980       LOG (GNUNET_ERROR_TYPE_INFO,
1981            "Using %s of %.3f\n",
1982            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1983     }
1984   }
1985
1986   for (c = 0; c < env->network_count; c++)
1987   {
1988     cur = &s->network_entries[c];
1989     cur->type = env->networks[c];
1990     cur->total_quota_in = env->in_quota[c];
1991     cur->total_quota_out = env->out_quota[c];
1992     cur->desc = GNUNET_ATS_print_network_type (c);
1993     GNUNET_asprintf (&cur->stat_total,
1994                      "# ATS addresses %s total",
1995                      cur->desc);
1996     GNUNET_asprintf (&cur->stat_active,
1997                      "# ATS active addresses %s total",
1998                      cur->desc);
1999     LOG (GNUNET_ERROR_TYPE_INFO,
2000          "Added network %u `%s' (%llu/%llu)\n",
2001          c,
2002          cur->desc,
2003          cur->total_quota_in,
2004          cur->total_quota_out);
2005   }
2006   return s;
2007 }
2008
2009
2010 /* end of plugin_ats_proportional.c */