docu for address selection
[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-service-ats_addresses.h"
31
32 #define PROP_STABILITY_FACTOR 1.25
33
34
35 #define LOG(kind,...) GNUNET_log_from (kind, "ats-proportional",__VA_ARGS__)
36
37
38 /**
39  *
40  * NOTE: Do not change this documentation. This documentation is based
41  * on gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
42  * use build_txt.sh to generate plaintext output
43  *
44  * ATS addresses : proportional solver
45  *
46  *    The proportional solver ("proportional") distributes the available
47  *    bandwidth fair over all the addresses influenced by the
48  *    preference values. For each available network type an in- and
49  *    outbound quota is configured and the bandwidth available in
50  *    these networks is distributed over the addresses.  The solver
51  *    first assigns every addresses the minimum amount of bandwidth
52  *    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT and then distributes the
53  *    remaining bandwidth available according to the preference
54  *    values. For each peer only a single address gets bandwidth
55  *    assigned and only one address marked as active.  The most
56  *    important functionality for the solver is implemented in: *
57  *    find_address_it is an hashmap iterator returning the prefered
58  *    address for an peer * update_quota_per_network distributes
59  *    available bandwidth for a network over active addresses
60  *
61  *    Changes to addresses automatically have an impact on the the
62  *    bandwidth assigned to other addresses in the same network since
63  *    the solver distributes the remaining bandwidth over the
64  *    addresses in the network.  When changes to the addresses occur,
65  *    the solver first performs the changes, like adding or deleting
66  *    addresses, and then updates bandwidth assignment for the
67  *    affected network. Bandwidth assignment is only recalculated on
68  *    demand when an address is requested by a client for a peer or
69  *    when the addresses available have changed or an address changed
70  *    the network it is located in. When the bandwidth assignment has
71  *    changed the callback is called with the new bandwidth
72  *    assignments. The bandwidth distribution for a network is
73  *    recalculated due to: * address suggestion requests * address
74  *    deletions * address switching networks during address update *
75  *    preference changes
76  *
77  *     3.1 Data structures used
78  *
79  *    For each ATS network (e.g. WAN, LAN, loopback) a struct Network
80  *    is used to specify network related information as total adresses
81  *    and active addresses in this network and the configured in- and
82  *    outbound quota. Each network also contains a list of addresses
83  *    added to the solver located in this network. The proportional
84  *    solver uses the addresses' solver_information field to store the
85  *    proportional network it belongs to for each address.
86  *
87  *     3.2 Initializing
88  *
89  *    When the proportional solver is initialized the solver creates a
90  *    new solver handle and initializes the network structures with
91  *    the quotas passed from addresses and returns the handle solver.
92  *
93  *     3.3 Adding an address
94  *
95  *    When a new address is added to the solver using s_add, a lookup
96  *    for the network for this address is done and the address is
97  *    enqueued in in the linked list of the network.
98  *
99  *     3.4 Updating an address
100  *
101  *    The main purpose of address updates is to update the ATS
102  *    information for addresse selection. Important for the proportional
103  *    solver is when an address switches network it is located
104  *    in. This is common because addresses added by transport's
105  *    validation mechanism are commonly located in
106  *    GNUNET_ATS_NET_UNSPECIFIED. Addresses in validation are located
107  *    in this network type and only if a connection is successful on
108  *    return of payload data transport switches to the real network
109  *    the address is located in.  When an address changes networks it
110  *    is first of all removed from the old network using the solver
111  *    API function #GAS_proportional_address_delete() and the network in
112  *    the address struct is updated. A lookup for the respective new
113  *    proportional network is done and stored in the addresse's
114  *    solver_information field. Next the address is re-added to the
115  *    solver using the solver API function
116  *    #GAS_proportional_address_add(). If the address was marked as in
117  *    active, the solver checks if bandwidth is available in the
118  *    network and if yes sets the address to active and updates the
119  *    bandwidth distribution in this network. If no bandwidth is
120  *    available it sets the bandwidth for this address to 0 and tries
121  *    to suggest an alternative address. If an alternative address was
122  *    found, addresses' callback is called for this address.
123  *
124  *     3.5 Deleting an address
125  *
126  *    When an address is removed from the solver, it removes the
127  *    respective address from the network and if the address was
128  *    marked as active, it updates the bandwidth distribution for this
129  *    network.
130  *
131  *     3.6 Requesting addresses
132  *
133  *    When an address is requested for a peer the solver performs a
134  *    lookup for the peer entry in addresses address hashmap and
135  *    selects the best address.  The selection of the most suitable
136  *    address is done in the find_address_it hashmap iterator
137  *    described in detail in section 3.7. If no address is returned,
138  *    no address can be suggested at the moment. If the address
139  *    returned is marked as active, the solver can return this
140  *    address. If the address is not marked as active, the solver
141  *    checks if another address belongign to this peer is marked as
142  *    active and marks the address as inactive, updates the bandwidth
143  *    for this address to 0, call the bandwidth changed callback for
144  *    this address due to the change and updates quota assignment for
145  *    the addresse's network. the now in-active address is belonging
146  *    to. The solver marks the new address as active and updates the
147  *    bandwidth assignment for this network.
148  *
149  *     3.7 Choosing addresses
150  *
151  *    Choosing the best possible address for suggestion is done by
152  *    iterating over all addresses of a peer stored in addresses'
153  *    hashmap and using the hashmap iterator find_address_it to select
154  *    the best available address.  Several checks are done when an
155  *    address is selected. First if this address is currently blocked
156  *    by addresses from being suggested. An address is blocked for the
157  *    duration of ATS_BLOCKING_DELTA when it is suggested to
158  *    transport. Next it is checked if at least
159  *    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT bytes bandwidth is available
160  *    in the addresse's network, because suggesting an address without
161  *    bandwidth does not make sense. This also ensures that all active
162  *    addresses in this network get at least the minimum amount of
163  *    bandwidth assigned. In the next step the solver ensures that for
164  *    tcp connections inbound connections are prefered over outbound
165  *    connections. In the next stet the solver ensures that
166  *    connections are prefered in the following order: * connections
167  *    are already established and have bandwidth assigned *
168  *    connections with a shorter distance * connectes have a shorter
169  *    latency
170  *
171  *     3.8 Changing preferences
172  *
173  *     3.9 Shutdown
174  *
175  *    During shutdown all network entries and aging processes are
176  *    destroyed and freed.
177  *
178  *
179  * OLD DOCUMENTATION
180  *
181  * This solver assigns in and outbound bandwidth equally for all
182  * addresses in specific network type (WAN, LAN) based on configured
183  * in and outbound quota for this network.
184  *
185  * The solver is notified by addresses about changes to the addresses
186  * and recalculates the bandwith assigned if required. The solver
187  * notifies addresses by calling the GAS_bandwidth_changed_cb
188  * callback.
189  *
190  * - Initialization
191  *
192  *
193  *
194  *
195  * For each peer only a single is selected and marked as "active" in the address
196  * struct.
197  *
198  * E.g.:
199  *
200  * You have the networks WAN and LAN and quotas
201  * WAN_TOTAL_IN, WAN_TOTAL_OUT
202  * LAN_TOTAL_IN, LAN_TOTAL_OUT
203  *
204  * If you have x addresses in the network segment LAN, the quotas are
205  * QUOTA_PER_ADDRESS = LAN_TOTAL_OUT / x
206  *
207  * Quotas are automatically recalculated and reported back when addresses are
208  * - requested
209  *
210  */
211
212 #define PROPORTIONALITY_FACTOR 2.0
213
214 /**
215  * A handle for the proportional solver
216  */
217 struct GAS_PROPORTIONAL_Handle
218 {
219    struct GNUNET_ATS_PluginEnvironment *env;
220
221   /**
222    * Statistics handle
223    */
224   struct GNUNET_STATISTICS_Handle *stats;
225
226   /**
227    * Hashmap containing all valid addresses
228    */
229   struct GNUNET_CONTAINER_MultiPeerMap *addresses;
230
231   /**
232    * Pending address requests
233    */
234   struct GNUNET_CONTAINER_MultiPeerMap *requests;
235
236   /**
237    * Bandwidth changed callback
238    */
239   GAS_bandwidth_changed_cb bw_changed;
240
241   /**
242    * Bandwidth changed callback cls
243    */
244   void *bw_changed_cls;
245
246   /**
247    * ATS function to get preferences
248    */
249   GAS_get_preferences get_preferences;
250
251   /**
252    * Closure for ATS function to get preferences
253    */
254   void *get_preferences_cls;
255
256   /**
257    * ATS function to get properties
258    */
259   GAS_get_properties get_properties;
260
261   /**
262    * Closure for ATS function to get properties
263    */
264   void *get_properties_cls;
265
266   /**
267    * Bulk lock
268    */
269   int bulk_lock;
270
271   /**
272    * Number of changes while solver was locked
273    */
274   int bulk_requests;
275
276   /**
277    * Total number of addresses for solver
278    */
279   unsigned int total_addresses;
280
281   /**
282    * Number of active addresses for solver
283    */
284   unsigned int active_addresses;
285
286   /**
287    * Networks array
288    */
289   struct Network *network_entries;
290
291   /**
292    * Number of networks
293    */
294   unsigned int network_count;
295
296   /**
297    * Proportionality factor
298    */
299   double prop_factor;
300
301   /**
302    * Stability factor
303    */
304   double stability_factor;
305 };
306
307 /**
308  * Representation of a network
309  */
310 struct Network
311 {
312   /**
313    * ATS network type
314    */
315   unsigned int type;
316
317   /**
318    * Network description
319    */
320   char *desc;
321
322   /**
323    * Total inbound quota
324    *
325    */
326   unsigned long long total_quota_in;
327
328   /**
329    * Total outbound quota
330    *
331    */
332   unsigned long long total_quota_out;
333
334   /**
335    * Number of active addresses for this network
336    */
337   unsigned int active_addresses;
338
339   /**
340    * Number of total addresses for this network
341    */
342   unsigned int total_addresses;
343
344   /**
345    * String for statistics total addresses
346    */
347   char *stat_total;
348
349   /**
350    * String for statistics active addresses
351    */
352   char *stat_active;
353
354   /**
355    * FIXME.
356    */
357   struct AddressWrapper *head;
358
359   /**
360    * FIXME.
361    */
362   struct AddressWrapper *tail;
363 };
364
365 /**
366  * Address information stored in the solver
367  */
368 struct AddressSolverInformation
369 {
370   struct Network *network;
371
372   /**
373    * Inbound quota
374    *
375    */
376   unsigned long long calculated_quota_in_NBO;
377
378   /**
379    * Outbound quota
380    *
381    */
382   unsigned long long calculated_quota_out_NBO;
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   GNUNET_assert(s != NULL);
427   for (c = 0; c < s->network_count; c++)
428   {
429     if (s->network_entries[c].total_addresses > 0)
430     {
431       LOG(GNUNET_ERROR_TYPE_DEBUG,
432           "Had %u addresses for network `%s' not deleted during shutdown\n",
433           s->network_entries[c].total_addresses, s->network_entries[c].desc);
434       //GNUNET_break(0);
435     }
436
437     if (s->network_entries[c].active_addresses > 0)
438     {
439       LOG(GNUNET_ERROR_TYPE_DEBUG,
440           "Had %u active addresses for network `%s' not deleted during shutdown\n",
441           s->network_entries[c].active_addresses, s->network_entries[c].desc);
442       //GNUNET_break(0);
443     }
444
445     next = s->network_entries[c].head;
446     while (NULL != (cur = next))
447     {
448       next = cur->next;
449       GNUNET_CONTAINER_DLL_remove(s->network_entries[c].head,
450           s->network_entries[c].tail, cur);
451       GNUNET_free_non_null (cur->addr->solver_information);
452       GNUNET_free(cur);
453     }
454     GNUNET_free(s->network_entries[c].stat_total);
455     GNUNET_free(s->network_entries[c].stat_active);
456   }
457   if (s->total_addresses > 0)
458   {
459     LOG(GNUNET_ERROR_TYPE_DEBUG,
460         "Had %u addresses not deleted during shutdown\n", s->total_addresses);
461     // GNUNET_break(0);
462   }
463   if (s->active_addresses > 0)
464   {
465     LOG(GNUNET_ERROR_TYPE_DEBUG,
466         "Had %u active addresses not deleted during shutdown\n",
467         s->active_addresses);
468     // GNUNET_break (0);
469   }
470   GNUNET_free (s->network_entries);
471   GNUNET_CONTAINER_multipeermap_destroy (s->requests);
472   GNUNET_free (s);
473   return NULL;
474 }
475
476
477 /**
478  * Test if bandwidth is available in this network to add an additional address
479  *
480  * @param net the network type to update
481  * @return #GNUNET_YES or #GNUNET_NO
482  */
483 static int
484 is_bandwidth_available_in_network (struct Network *net)
485 {
486   GNUNET_assert(NULL != net);
487   unsigned int na = net->active_addresses + 1;
488   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
489   if (((net->total_quota_in / na) > min_bw)
490       && ((net->total_quota_out / na) > min_bw))
491   {
492     LOG(GNUNET_ERROR_TYPE_DEBUG,
493         "Enough bandwidth available for %u active addresses in network `%s'\n",
494         na, net->desc);
495
496     return GNUNET_YES;
497   }
498   LOG(GNUNET_ERROR_TYPE_DEBUG,
499       "Not enough bandwidth available for %u active addresses in network `%s'\n",
500       na, net->desc);
501   return GNUNET_NO;
502 }
503
504
505 /**
506  * Update bandwidth assigned to peers in this network
507  *
508  * @param s the solver handle
509  * @param net the network type to update
510  * this address
511  */
512 static void
513 distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
514     struct Network *net)
515 {
516   struct AddressSolverInformation *asi;
517   struct AddressWrapper *cur_address;
518
519   unsigned long long remaining_quota_in = 0;
520   unsigned long long quota_out_used = 0;
521   unsigned long long remaining_quota_out = 0;
522   unsigned long long quota_in_used = 0;
523   int count_addresses;
524   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
525   double relative_peer_prefence;
526   double sum_relative_peer_prefences; /* Important: has to be double not float due to precision */
527   double cur_pref; /* Important: has to be double not float due to precision */
528   double peer_weight;
529   double total_weight;
530   const double *peer_relative_prefs = NULL; /* Important: has to be double not float due to precision */
531
532   unsigned long long assigned_quota_in = 0;
533   unsigned long long assigned_quota_out = 0;
534
535
536   LOG(GNUNET_ERROR_TYPE_INFO,
537       "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
538       net->desc, net->active_addresses, 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, "Active: `%s' `%s' length %u\n",
595           GNUNET_i2s (&cur_address->addr->peer), cur_address->addr->plugin,
596           cur_address->addr->addr_len);
597     }
598   }
599
600   LOG (GNUNET_ERROR_TYPE_INFO,
601       "Total relative preference %.3f for %u addresses in network %s\n",
602       sum_relative_peer_prefences, net->active_addresses, net->desc);
603
604   for (cur_address = net->head; NULL != cur_address; cur_address = cur_address->next)
605   {
606     if (GNUNET_YES == cur_address->addr->active)
607     {
608       GNUNET_assert( NULL != (peer_relative_prefs =
609           s->get_preferences (s->get_preferences_cls, &cur_address->addr->peer)));
610
611       cur_pref = peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
612       total_weight = net->active_addresses +
613           s->prop_factor * sum_relative_peer_prefences;
614       peer_weight = (1.0 + (s->prop_factor * cur_pref));
615
616       assigned_quota_in = min_bw
617           + ((peer_weight / total_weight) * remaining_quota_in);
618       assigned_quota_out = min_bw
619           + ((peer_weight / total_weight) * remaining_quota_out);
620
621       LOG (GNUNET_ERROR_TYPE_INFO,
622           "New quota for peer `%s' with weight (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
623           GNUNET_i2s (&cur_address->addr->peer), peer_weight, total_weight,
624           assigned_quota_in, assigned_quota_out);
625     }
626     else
627     {
628       assigned_quota_in = 0;
629       assigned_quota_out = 0;
630     }
631
632     quota_in_used += assigned_quota_in;
633     quota_out_used += assigned_quota_out;
634     /* Prevent overflow due to rounding errors */
635     if (assigned_quota_in > UINT32_MAX)
636       assigned_quota_in = UINT32_MAX;
637     if (assigned_quota_out > UINT32_MAX)
638       assigned_quota_out = UINT32_MAX;
639
640     /* Compare to current bandwidth assigned */
641     asi = cur_address->addr->solver_information;
642     asi->calculated_quota_in_NBO = htonl (assigned_quota_in);
643     asi->calculated_quota_out_NBO = htonl (assigned_quota_out);
644   }
645   LOG(GNUNET_ERROR_TYPE_DEBUG,
646       "Total bandwidth assigned is (in/out): %llu /%llu\n", quota_in_used,
647       quota_out_used);
648   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
649   {
650     LOG(GNUNET_ERROR_TYPE_ERROR,
651         "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
652         net->active_addresses, quota_out_used, net->total_quota_out);
653   }
654   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
655   {
656     LOG(GNUNET_ERROR_TYPE_ERROR,
657         "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
658         net->active_addresses, quota_in_used, net->total_quota_in);
659   }
660 }
661
662
663 /**
664  * FIXME.
665  */
666 struct FindBestAddressCtx
667 {
668   struct GAS_PROPORTIONAL_Handle *s;
669   struct ATS_Address *best;
670 };
671
672
673 /**
674  * FIXME.
675  */
676 static int
677 find_property_index (uint32_t type)
678 {
679   int existing_types[] = GNUNET_ATS_QualityProperties;
680   int c;
681
682   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
683     if (existing_types[c] == type)
684       return c;
685   return GNUNET_SYSERR;
686 }
687
688
689 /**
690  * Find a "good" address to use for a peer by iterating over the addresses for this peer.
691  * If we already have an existing address, we stick to it.
692  * Otherwise, we pick by lowest distance and then by lowest latency.
693  *
694  * @param cls the `struct FindBestAddressCtx *' where we store the result
695  * @param key unused
696  * @param value another `struct ATS_Address*` to consider using
697  * @return #GNUNET_OK (continue to iterate)
698  */
699 static int
700 find_best_address_it (void *cls,
701                       const struct GNUNET_PeerIdentity *key,
702                       void *value)
703 {
704   struct FindBestAddressCtx *ctx = cls;
705   struct ATS_Address *current = value;
706   struct ATS_Address *current_best = current;
707   struct GNUNET_TIME_Absolute now;
708   struct AddressSolverInformation *asi;
709   struct GNUNET_TIME_Relative active_time;
710   struct GNUNET_TIME_Relative min_active_time;
711   const double *norm_prop_cur;
712   const double *norm_prop_best;
713   double best_delay;
714   double best_distance;
715   double cur_delay;
716   double cur_distance;
717   int index;
718
719   current_best = NULL;
720   asi = current->solver_information;
721   now = GNUNET_TIME_absolute_get ();
722
723   if ((current->active == GNUNET_NO)
724       && (current->blocked_until.abs_value_us
725           == GNUNET_TIME_absolute_max (now, current->blocked_until).abs_value_us))
726   {
727     /* This address is blocked for suggestion */
728     LOG (GNUNET_ERROR_TYPE_DEBUG,
729          "Address %p blocked for suggestion for %s \n",
730          current,
731          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (now, current->blocked_until),
732                                                  GNUNET_YES));
733     return GNUNET_OK;
734   }
735   if (NULL == asi)
736   {
737     GNUNET_break (0);
738     return GNUNET_OK;
739   }
740
741   if (GNUNET_NO == is_bandwidth_available_in_network (asi->network))
742   {
743     return GNUNET_OK; /* There's no bandwidth available in this network */
744   }
745
746   if (NULL != ctx->best)
747   {
748     /* Compare current addresses with denominated 'best' address */
749     current_best = ctx->best;
750   }
751   else
752   {
753     /* We do not have a 'best' address so take this address */
754     LOG (GNUNET_ERROR_TYPE_DEBUG,
755          "Setting initial address %p\n",
756          current);
757     current_best = current;
758     goto end;
759   }
760
761   if (GNUNET_YES == current->active)
762   {
763     GNUNET_assert (asi->activated.abs_value_us != GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us);
764     active_time = GNUNET_TIME_absolute_get_duration (asi->activated);
765     min_active_time.rel_value_us =  ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) *
766         PROP_STABILITY_FACTOR;
767     if (active_time.rel_value_us <= min_active_time.rel_value_us)
768     {
769       /* Keep active address for stability reasons */
770       ctx->best = current;
771       return GNUNET_NO;
772     }
773   }
774
775   /* Now compare ATS information */
776   norm_prop_cur = ctx->s->get_properties (ctx->s->get_properties_cls,
777       (const struct ATS_Address *) current);
778   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
779   cur_distance = norm_prop_cur[index];
780   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
781   cur_delay = norm_prop_cur[index];
782
783   norm_prop_best = ctx->s->get_properties (ctx->s->get_properties_cls,
784       (const struct ATS_Address *) ctx->best);
785   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
786   best_distance = norm_prop_best[index];
787   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
788   best_delay = norm_prop_best[index];
789
790   /* user shorter distance */
791   if (cur_distance < best_distance)
792   {
793
794     if (GNUNET_NO == ctx->best->active)
795     {
796       current_best = current; /* Use current */
797     }
798     else if ((best_distance / cur_distance) > ctx->s->stability_factor)
799     {
800       /* Best and active address performs worse  */
801       current_best = current;
802     }
803   }
804   else
805   {
806     /* Use current best */
807     current_best = ctx->best;
808   }
809
810   /* User connection with less delay */
811   if (cur_delay < best_delay)
812   {
813
814     if (GNUNET_NO == ctx->best->active)
815     {
816       current_best = current; /* Use current */
817     }
818     else if ((best_delay / cur_delay) > ctx->s->stability_factor)
819     {
820       /* Best and active address performs worse  */
821       current_best = current;
822     }
823   }
824   else
825   {
826     /* Use current best */
827     current_best = ctx->best;
828   }
829
830 end:
831   ctx->best = current_best;
832   return GNUNET_OK;
833 }
834
835
836 /**
837  * Find the currently best address for a peer from the set of addresses available
838  * or return NULL of no address is available
839  *
840  * @param s the proportional handle
841  * @param addresses the address hashmap
842  * @param id the peer id
843  * @return the address or NULL
844  */
845 struct ATS_Address *
846 get_best_address (struct GAS_PROPORTIONAL_Handle *s,
847                   struct GNUNET_CONTAINER_MultiPeerMap *addresses,
848                   const struct GNUNET_PeerIdentity *id)
849 {
850   struct FindBestAddressCtx fba_ctx;
851
852   fba_ctx.best = NULL;
853   fba_ctx.s = s;
854   GNUNET_CONTAINER_multipeermap_get_multiple (addresses, id,
855                                               &find_best_address_it, &fba_ctx);
856
857   return fba_ctx.best;
858 }
859
860
861 /**
862  * Hashmap Iterator to find current active address for peer
863  *
864  * @param cls last active address
865  * @param key peer's key
866  * @param value address to check
867  * @return #GNUNET_NO on double active address else #GNUNET_YES;
868  */
869 static int
870 get_active_address_it (void *cls,
871                        const struct GNUNET_PeerIdentity *key,
872                        void *value)
873 {
874   struct ATS_Address **dest = cls;
875   struct ATS_Address *aa = (struct ATS_Address *) value;
876
877   if (GNUNET_YES == aa->active)
878   {
879
880     if (NULL != (*dest))
881     {
882       /* should never happen */
883       LOG (GNUNET_ERROR_TYPE_ERROR,
884            "Multiple active addresses for peer `%s'\n",
885            GNUNET_i2s (&aa->peer));
886       GNUNET_break(0);
887       return GNUNET_NO;
888     }
889     (*dest) = aa;
890   }
891   return GNUNET_OK;
892 }
893
894
895 /**
896  * Find current active address for peer
897  *
898  * @param solver the solver handle
899  * @param addresses the address set
900  * @param peer the peer
901  * @return active address or NULL
902  */
903 static struct ATS_Address *
904 get_active_address (void *solver,
905                     const struct GNUNET_CONTAINER_MultiPeerMap * addresses,
906                     const struct GNUNET_PeerIdentity *peer)
907 {
908   struct ATS_Address * dest = NULL;
909
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  * FIXME.  Degermanize.
938  */
939 static void
940 addresse_increment (struct GAS_PROPORTIONAL_Handle *s,
941                     struct Network *net,
942                     int total,
943                     int active)
944 {
945   if (GNUNET_YES == total)
946   {
947     s->total_addresses++;
948     net->total_addresses++;
949     GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
950     GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
951   }
952   if (GNUNET_YES == active)
953   {
954     net->active_addresses++;
955     s->active_addresses++;
956     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1,
957         GNUNET_NO);
958     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
959   }
960
961 }
962
963
964 /**
965  * FIXME.  Degermanize.
966  */
967 static int
968 addresse_decrement (struct GAS_PROPORTIONAL_Handle *s,
969                     struct Network *net,
970                     int total,
971                     int active)
972 {
973   int res = GNUNET_OK;
974
975   if (GNUNET_YES == total)
976   {
977     if (s->total_addresses < 1)
978     {
979       GNUNET_break(0);
980       res = GNUNET_SYSERR;
981     }
982     else
983     {
984       s->total_addresses--;
985       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
986           GNUNET_NO);
987     }
988     if (net->total_addresses < 1)
989     {
990       GNUNET_break(0);
991       res = GNUNET_SYSERR;
992     }
993     else
994     {
995       net->total_addresses--;
996       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
997     }
998   }
999
1000   if (GNUNET_YES == active)
1001   {
1002     if (net->active_addresses < 1)
1003     {
1004       GNUNET_break(0);
1005       res = GNUNET_SYSERR;
1006     }
1007     else
1008     {
1009       net->active_addresses--;
1010       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
1011     }
1012     if (s->active_addresses < 1)
1013     {
1014       GNUNET_break(0);
1015       res = GNUNET_SYSERR;
1016     }
1017     else
1018     {
1019       s->active_addresses--;
1020       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
1021           GNUNET_NO);
1022     }
1023   }
1024   return res;
1025 }
1026
1027
1028 /**
1029  * FIXME.
1030  */
1031 static int
1032 address_eq (struct ATS_Address *a, struct ATS_Address *b)
1033 {
1034   GNUNET_assert (NULL != a);
1035   GNUNET_assert (NULL != b);
1036   if (0 != strcmp(a->plugin, b->plugin))
1037     return GNUNET_NO;
1038   if (a->addr_len != b->addr_len)
1039     return GNUNET_NO;
1040   if (0 != memcmp (a->addr, b->addr, b->addr_len))
1041     return GNUNET_NO;
1042   if (a->session_id != b->session_id)
1043     return GNUNET_NO;
1044   return GNUNET_YES;
1045 }
1046
1047
1048 /**
1049  * FIXME.
1050  */
1051 static void
1052 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
1053                      struct Network *net)
1054 {
1055   struct AddressWrapper *cur;
1056   struct AddressSolverInformation *asi;
1057   for (cur = net->head; NULL != cur; cur = cur->next)
1058   {
1059       asi = cur->addr->solver_information;
1060       if ( (cur->addr->assigned_bw_in.value__ != asi->calculated_quota_in_NBO) ||
1061            (cur->addr->assigned_bw_out.value__ != asi->calculated_quota_out_NBO) )
1062       {
1063         cur->addr->assigned_bw_in.value__ = asi->calculated_quota_in_NBO;
1064         cur->addr->assigned_bw_out.value__ = asi->calculated_quota_out_NBO;
1065
1066         /* Reset for next iteration */
1067         asi->calculated_quota_in_NBO = htonl (0);
1068         asi->calculated_quota_out_NBO = htonl (0);
1069
1070         LOG (GNUNET_ERROR_TYPE_DEBUG,
1071             "Bandwidth for %s address %p for peer `%s' changed to %u/%u\n",
1072             (GNUNET_NO == cur->addr->active) ? "inactive" : "active",
1073             cur->addr,
1074             GNUNET_i2s (&cur->addr->peer),
1075             ntohl (cur->addr->assigned_bw_in.value__),
1076             ntohl (cur->addr->assigned_bw_out.value__ ));
1077
1078         /* Notify on change */
1079         if ((GNUNET_YES == cur->addr->active))
1080         {
1081           s->bw_changed (s->bw_changed_cls, cur->addr);
1082         }
1083       }
1084   }
1085 }
1086
1087
1088 /**
1089  * Distribibute bandwidth
1090  *
1091  * @param s the solver handle
1092  * @param n the network, can be NULL for all network
1093  * @param address_except do not notify for this address
1094  */
1095 static void
1096 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
1097                                  struct Network *n)
1098 {
1099   if (GNUNET_YES == s->bulk_lock)
1100   {
1101     s->bulk_requests++;
1102     return;
1103   }
1104
1105   if (NULL != n)
1106   {
1107     LOG (GNUNET_ERROR_TYPE_INFO,
1108         "Redistributing bandwidth in network %s with %u active and %u total addresses\n",
1109         GNUNET_ATS_print_network_type(n->type),
1110         n->active_addresses, n->total_addresses);
1111
1112     if (NULL != s->env->info_cb)
1113       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
1114           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1115
1116     /* Distribute  */
1117     distribute_bandwidth(s, n);
1118
1119     if (NULL != s->env->info_cb)
1120       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
1121           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1122     if (NULL != s->env->info_cb)
1123       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1124           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1125
1126     /* Do propagation */
1127     propagate_bandwidth (s, n);
1128
1129     if (NULL != s->env->info_cb)
1130       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1131           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
1132   }
1133   else
1134   {
1135     int i;
1136     if (NULL != s->env->info_cb)
1137       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
1138           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1139     for (i = 0; i < s->network_count; i++)
1140     {
1141       /* Distribute */
1142       distribute_bandwidth(s, &s->network_entries[i]);
1143     }
1144
1145     if (NULL != s->env->info_cb)
1146       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
1147           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1148     if (NULL != s->env->info_cb)
1149       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1150           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1151     for (i = 0; i < s->network_count; i++)
1152     {
1153       /* Do propagation */
1154       propagate_bandwidth(s, &s->network_entries[i]);
1155     }
1156     if (NULL != s->env->info_cb)
1157       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1158           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
1159   }
1160 }
1161
1162
1163 /**
1164  * FIXME
1165  */
1166 static const struct ATS_Address *
1167 update_active_address (struct GAS_PROPORTIONAL_Handle *s,
1168                        const struct GNUNET_PeerIdentity *peer)
1169 {
1170   struct ATS_Address *best_address;
1171   struct ATS_Address *current_address;
1172   struct AddressSolverInformation *asi;
1173   struct Network *net;
1174
1175   LOG (GNUNET_ERROR_TYPE_INFO,
1176        "Updating active address for peer `%s'\n",
1177        GNUNET_i2s (peer));
1178
1179   /* Find active address */
1180   current_address = get_active_address (s, s->addresses, peer);
1181   /* Find best address */
1182   best_address = get_best_address (s,s->addresses, peer);
1183
1184   if (NULL != current_address)
1185   {
1186     if ((NULL == best_address) || ((NULL != best_address) &&
1187         (GNUNET_NO == address_eq (current_address, best_address))))
1188     {
1189       /* We switch to a new address, mark old address as inactive */
1190       LOG (GNUNET_ERROR_TYPE_INFO,
1191           "Disabling previous %s address %p for peer `%s'\n",
1192           (GNUNET_NO == current_address->active) ? "inactive" : "active",
1193           current_address,
1194           GNUNET_i2s (peer));
1195
1196       asi = current_address->solver_information;
1197       GNUNET_assert (NULL != asi);
1198
1199       net = asi->network;
1200       asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1201       current_address->active = GNUNET_NO; /* No active any longer */
1202       current_address->assigned_bw_in = BANDWIDTH_ZERO; /* no bandwidth assigned */
1203       current_address->assigned_bw_out = BANDWIDTH_ZERO; /* no bandwidth assigned */
1204
1205       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1206         GNUNET_break(0);
1207
1208       /* Update network of previous address */
1209       distribute_bandwidth_in_network (s, net);
1210     }
1211     if (NULL == best_address)
1212     {
1213       /* We previously had an active address, but now we cannot suggest one
1214        * Therefore we have to disconnect the peer */
1215
1216       LOG (GNUNET_ERROR_TYPE_INFO,
1217           "Disconnecting peer `%s' with previous %s address %p\n",
1218           GNUNET_i2s (peer),
1219           (GNUNET_NO == current_address->active) ? "inactive" : "active",
1220           current_address);
1221       s->bw_changed (s->bw_changed_cls, current_address);
1222     }
1223   }
1224
1225   if (NULL == best_address)
1226   {
1227     LOG (GNUNET_ERROR_TYPE_INFO, "Cannot suggest address for peer `%s'\n",
1228         GNUNET_i2s (peer));
1229     return NULL ;
1230   }
1231
1232   LOG (GNUNET_ERROR_TYPE_INFO, "Suggesting %s address %p for peer `%s'\n",
1233       (GNUNET_NO == best_address->active) ? "inactive" : "active", best_address,
1234       GNUNET_i2s (peer));
1235
1236   if ((NULL != current_address) &&
1237       (GNUNET_YES == address_eq (best_address, current_address)))
1238   {
1239     if (current_address->active == GNUNET_NO)
1240       GNUNET_break (0); /* Should never happen */
1241     return best_address; /* Same same */
1242   }
1243
1244   asi = best_address->solver_information;
1245   GNUNET_assert (NULL != asi);
1246   net = asi->network;
1247
1248   /* Mark address as active */
1249   asi->activated = GNUNET_TIME_absolute_get();
1250   best_address->active = GNUNET_YES;
1251   addresse_increment (s, net, GNUNET_NO, GNUNET_YES);
1252
1253   /* Distribute bandwidth */
1254   distribute_bandwidth_in_network (s, net);
1255   return best_address;
1256 }
1257
1258
1259 /**
1260  * Changes the preferences for a peer in the problem
1261  *
1262  * @param solver the solver handle
1263  * @param peer the peer to change the preference for
1264  * @param kind the kind to change the preference
1265  * @param pref_rel the normalized preference value for this kind over all clients
1266  */
1267 static void
1268 GAS_proportional_address_change_preference (void *solver,
1269                                             const struct GNUNET_PeerIdentity *peer,
1270                                             enum GNUNET_ATS_PreferenceKind kind,
1271                                             double pref_rel)
1272 {
1273   struct GAS_PROPORTIONAL_Handle *s = solver;
1274   struct ATS_Address *best_address;
1275   struct ATS_Address *active_address;
1276   struct AddressSolverInformation *asi;
1277
1278   GNUNET_assert(NULL != s);
1279   GNUNET_assert(NULL != peer);
1280
1281   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1282     return; /* Peer is not requested */
1283
1284   /* This peer is requested, find best address */
1285   active_address = get_active_address(s, s->addresses, peer);
1286   best_address = (struct ATS_Address *) update_active_address (s, peer);
1287
1288   if ((NULL != best_address) && ((NULL != active_address) &&
1289       (GNUNET_YES == address_eq (active_address, best_address))))
1290   {
1291     asi = best_address->solver_information;
1292     GNUNET_assert (NULL != asi);
1293
1294     /* We sticked to the same address, therefore redistribute  */
1295     distribute_bandwidth_in_network (s, asi->network);
1296   }
1297 }
1298
1299
1300 /**
1301  * Get application feedback for a peer
1302  *
1303  * @param solver the solver handle
1304  * @param application the application
1305  * @param peer the peer to change the preference for
1306  * @param scope the time interval for this feedback: [now - scope .. now]
1307  * @param kind the kind to change the preference
1308  * @param score the score
1309  */
1310 static void
1311 GAS_proportional_address_preference_feedback (void *solver,
1312                                               void *application,
1313                                               const struct GNUNET_PeerIdentity *peer,
1314                                               const struct GNUNET_TIME_Relative scope,
1315                                               enum GNUNET_ATS_PreferenceKind kind,
1316                                               double score)
1317 {
1318   struct GAS_PROPORTIONAL_Handle *s = solver;
1319
1320   GNUNET_assert(NULL != peer);
1321   GNUNET_assert(NULL != s);
1322 }
1323
1324
1325 /**
1326  * Get the preferred address for a specific peer
1327  *
1328  * @param solver the solver handle
1329  * @param peer the identity of the peer
1330  * @return FIXME
1331  */
1332 static const struct ATS_Address *
1333 GAS_proportional_get_preferred_address (void *solver,
1334                                         const struct GNUNET_PeerIdentity *peer)
1335 {
1336   struct GAS_PROPORTIONAL_Handle *s = solver;
1337   const struct ATS_Address *best_address;
1338
1339
1340   GNUNET_assert(s != NULL);
1341   GNUNET_assert(peer != NULL);
1342
1343   /* Add to list of pending requests */
1344   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1345   {
1346     GNUNET_assert(
1347         GNUNET_OK == GNUNET_CONTAINER_multipeermap_put (s->requests, peer, NULL,
1348             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1349     LOG (GNUNET_ERROR_TYPE_INFO, "Start suggesting addresses for peer `%s'\n",
1350           GNUNET_i2s (peer));
1351   }
1352
1353   best_address = update_active_address (s, peer);
1354   if (s->bulk_lock > 0)
1355     return NULL; /* Do not suggest since bulk lock is pending */
1356
1357   return best_address;
1358 }
1359
1360
1361 /**
1362  * Stop notifying about address and bandwidth changes for this peer
1363  *
1364  * @param solver the solver handle
1365  * @param peer the peer
1366  */
1367 static void
1368 GAS_proportional_stop_get_preferred_address (void *solver,
1369                                              const struct GNUNET_PeerIdentity *peer)
1370 {
1371   struct GAS_PROPORTIONAL_Handle *s = solver;
1372   struct ATS_Address *cur;
1373   struct AddressSolverInformation *asi;
1374   struct Network *cur_net;
1375
1376   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1377     GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove (s->requests,
1378         peer, NULL));
1379
1380   cur = get_active_address (s, s->addresses, peer);
1381   if (NULL != cur)
1382   {
1383     LOG(GNUNET_ERROR_TYPE_INFO,
1384         "Disabling %s address %p for peer `%s'\n",
1385         (GNUNET_NO == cur->active) ? "inactive" : "active", cur,
1386         GNUNET_i2s (&cur->peer));
1387
1388     /* Disabling current address */
1389     asi = cur->solver_information;
1390     cur_net = asi->network ;
1391     asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1392     cur->active = GNUNET_NO; /* No active any longer */
1393     cur->assigned_bw_in = BANDWIDTH_ZERO; /* no bandwidth assigned */
1394     cur->assigned_bw_out = BANDWIDTH_ZERO; /* no bandwidth assigned */
1395
1396     if (GNUNET_SYSERR == addresse_decrement (s, cur_net, GNUNET_NO, GNUNET_YES))
1397       GNUNET_break(0);
1398
1399     distribute_bandwidth_in_network (s, cur_net );
1400   }
1401   return;
1402 }
1403
1404
1405 /**
1406  * Remove an address from the solver
1407  *
1408  * @param solver the solver handle
1409  * @param address the address to remove
1410  * @param session_only delete only session not whole address
1411  */
1412 static void
1413 GAS_proportional_address_delete (void *solver,
1414                                  struct ATS_Address *address,
1415                                  int session_only)
1416 {
1417   struct GAS_PROPORTIONAL_Handle *s = solver;
1418   struct Network *net;
1419   struct AddressWrapper *aw;
1420   struct AddressSolverInformation *asi;
1421
1422   /* Remove an adress completely, we have to:
1423    * - Remove from specific network
1424    * - Decrease number of total addresses
1425    * - If active:
1426    *   - decrease number of active addreses
1427    *   - update quotas
1428    */
1429   asi = address->solver_information;
1430
1431   if (NULL == asi)
1432   {
1433     GNUNET_break (0);
1434     return;
1435   }
1436   net = asi->network;
1437
1438   if (GNUNET_NO == session_only)
1439   {
1440     LOG(GNUNET_ERROR_TYPE_INFO,
1441         "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1442         (GNUNET_NO == address->active) ? "inactive" : "active", address,
1443         GNUNET_i2s (&address->peer), net->desc, net->total_addresses,
1444         net->active_addresses);
1445
1446     /* Remove address */
1447     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
1448     for (aw = net->head; NULL != aw; aw = aw->next)
1449     {
1450       if (aw->addr == address)
1451         break;
1452     }
1453     if (NULL == aw)
1454     {
1455       GNUNET_break(0);
1456       return;
1457     }
1458     GNUNET_CONTAINER_DLL_remove(net->head, net->tail, aw);
1459     GNUNET_free(aw);
1460   }
1461   else
1462   {
1463     /* Remove session only: remove if active and update */
1464     LOG(GNUNET_ERROR_TYPE_INFO,
1465         "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1466         (GNUNET_NO == address->active) ? "inactive" : "active", address,
1467         GNUNET_i2s (&address->peer), net->desc, net->total_addresses,
1468         net->active_addresses);
1469   }
1470
1471   if (GNUNET_YES == address->active)
1472   {
1473     /* Address was active, remove from network and update quotas*/
1474     address->active = GNUNET_NO;
1475     address->assigned_bw_in = BANDWIDTH_ZERO;
1476     address->assigned_bw_out = BANDWIDTH_ZERO;
1477     asi->calculated_quota_in_NBO = htonl (0);
1478     asi->calculated_quota_out_NBO = htonl (0);
1479
1480     if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1481       GNUNET_break(0);
1482     distribute_bandwidth_in_network (s, net);
1483
1484     if (NULL == update_active_address (s, &address->peer))
1485     {
1486       /* No alternative address found, disconnect peer */
1487       LOG (GNUNET_ERROR_TYPE_INFO,
1488           "Disconnecting peer `%s' after deleting previous %s address %p\n",
1489           GNUNET_i2s (&address->peer),
1490           (GNUNET_NO == address->active) ? "inactive" : "active",
1491               address);
1492       s->bw_changed (s->bw_changed_cls, address);
1493     }
1494   }
1495   if (GNUNET_NO == session_only)
1496   {
1497     GNUNET_free_non_null (address->solver_information);
1498     address->solver_information = NULL;
1499   }
1500
1501   LOG(GNUNET_ERROR_TYPE_INFO,
1502       "After deleting address now total %u and active %u addresses in network `%s'\n",
1503       net->total_addresses, net->active_addresses, net->desc);
1504
1505 }
1506
1507
1508 /**
1509  * Start a bulk operation
1510  *
1511  * @param solver the solver
1512  */
1513 static void
1514 GAS_proportional_bulk_start (void *solver)
1515 {
1516   struct GAS_PROPORTIONAL_Handle *s = solver;
1517
1518   LOG (GNUNET_ERROR_TYPE_DEBUG,
1519        "Locking solver for bulk operation ...\n");
1520   GNUNET_assert(NULL != solver);
1521   s->bulk_lock++;
1522 }
1523
1524
1525 /**
1526  * Bulk operation done
1527  */
1528 static void
1529 GAS_proportional_bulk_stop (void *solver)
1530 {
1531   struct GAS_PROPORTIONAL_Handle *s = solver;
1532
1533   LOG (GNUNET_ERROR_TYPE_DEBUG,
1534        "Unlocking solver from bulk operation ...\n");
1535   GNUNET_assert(NULL != solver);
1536
1537   if (s->bulk_lock < 1)
1538   {
1539     GNUNET_break(0);
1540     return;
1541   }
1542   s->bulk_lock--;
1543   if ((0 == s->bulk_lock) && (0 < s->bulk_requests))
1544   {
1545     LOG(GNUNET_ERROR_TYPE_INFO, "No lock pending, recalculating\n");
1546     distribute_bandwidth_in_network (s, NULL);
1547     s->bulk_requests = 0;
1548   }
1549 }
1550
1551
1552 /**
1553  * Add a new single address to a network
1554  *
1555  * @param solver the solver Handle
1556  * @param address the address to add
1557  * @param network network type of this address
1558  */
1559 static void
1560 GAS_proportional_address_add (void *solver,
1561                               struct ATS_Address *address,
1562                               uint32_t network);
1563
1564
1565 /**
1566  * Transport properties for this address have changed
1567  *
1568  * @param solver solver handle
1569  * @param address the address
1570  * @param type the ATSI type in HBO
1571  * @param abs_value the absolute value of the property
1572  * @param rel_value the normalized value
1573  */
1574 static void
1575 GAS_proportional_address_property_changed (void *solver,
1576                                            struct ATS_Address *address,
1577                                            uint32_t type,
1578                                            uint32_t abs_value,
1579                                            double rel_value)
1580 {
1581   struct GAS_PROPORTIONAL_Handle *s = solver;
1582   struct Network *n;
1583   struct AddressSolverInformation *asi;
1584   struct ATS_Address *best_address;
1585   struct ATS_Address *active_address;
1586
1587   GNUNET_assert(NULL != s);
1588   GNUNET_assert(NULL != address);
1589   asi = address->solver_information;
1590   if (NULL == asi)
1591   {
1592     GNUNET_break(0);
1593     return;
1594   }
1595
1596   n = asi->network;
1597   if (NULL == n)
1598   {
1599     GNUNET_break(0);
1600     return;
1601   }
1602
1603   LOG(GNUNET_ERROR_TYPE_INFO,
1604       "Property `%s' for peer `%s' address %p changed to %.2f \n",
1605       GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1606       address, rel_value);
1607
1608   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1609     return; /* Peer is not requested */
1610
1611   /* This peer is requested, find active and best address */
1612   active_address = get_active_address(s, s->addresses, &address->peer);
1613   best_address = (struct ATS_Address *) update_active_address (s, &address->peer);
1614
1615   if ((NULL != best_address) && ((NULL != active_address) &&
1616       (GNUNET_YES == address_eq (active_address, best_address))))
1617   {
1618     asi = best_address->solver_information;
1619     GNUNET_assert (NULL != asi);
1620
1621     /* We sticked to the same address, therefore redistribute  */
1622     distribute_bandwidth_in_network (s, asi->network);
1623   }
1624 }
1625
1626 /**
1627  * Transport session for this address has changed
1628  *
1629  * NOTE: values in addresses are already updated
1630  *
1631  * @param solver solver handle
1632  * @param address the address
1633  * @param cur_session the current session
1634  * @param new_session the new session
1635  */
1636 static void
1637 GAS_proportional_address_session_changed (void *solver,
1638                                           struct ATS_Address *address,
1639                                           uint32_t cur_session,
1640                                           uint32_t new_session)
1641 {
1642   struct GAS_PROPORTIONAL_Handle *s = solver;
1643   struct ATS_Address *best_address;
1644   struct ATS_Address *active_address;
1645   struct AddressSolverInformation *asi;
1646
1647   if (cur_session != new_session)
1648   {
1649     LOG (GNUNET_ERROR_TYPE_DEBUG,
1650          "Session changed from %u to %u\n",
1651          cur_session,
1652          new_session);
1653   }
1654
1655   if (NULL == address->solver_information)
1656   {
1657     GNUNET_break (0);
1658     return;
1659   }
1660
1661   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1662     return; /* Peer is not requested */
1663
1664   /* This peer is requested, find active and best address */
1665   active_address = get_active_address(s, s->addresses, &address->peer);
1666   best_address = (struct ATS_Address *) update_active_address (s, &address->peer);
1667
1668   if ((NULL != best_address) && ((NULL != active_address) &&
1669       (GNUNET_YES == address_eq (active_address, best_address))))
1670   {
1671     asi = best_address->solver_information;
1672     GNUNET_assert (NULL != asi);
1673
1674     /* We sticked to the same address, therefore redistribute  */
1675     distribute_bandwidth_in_network (s, asi->network);
1676   }
1677 }
1678
1679
1680 /**
1681  * Usage for this address has changed
1682  *
1683  * NOTE: values in addresses are already updated
1684  *
1685  * @param solver solver handle
1686  * @param address the address
1687  * @param in_use usage state
1688  */
1689 static void
1690 GAS_proportional_address_inuse_changed (void *solver,
1691                                         struct ATS_Address *address,
1692                                         int in_use)
1693 {
1694   struct GAS_PROPORTIONAL_Handle *s = solver;
1695   struct Network *n;
1696   struct AddressSolverInformation *asi;
1697   struct ATS_Address *best_address;
1698   struct ATS_Address *active_address;
1699
1700   GNUNET_assert(NULL != s);
1701   GNUNET_assert(NULL != address);
1702   asi = address->solver_information;
1703   if (NULL == asi)
1704   {
1705     GNUNET_break(0);
1706     return;
1707   }
1708
1709   n = asi->network;
1710   if (NULL == n)
1711   {
1712     GNUNET_break(0);
1713     return;
1714   }
1715
1716   LOG(GNUNET_ERROR_TYPE_INFO,
1717       "Usage of peer `%s' address %p changed to %s \n",
1718       GNUNET_i2s (&address->peer), address,
1719       (GNUNET_YES == in_use) ? "YES" : "NO");
1720
1721   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1722     return; /* Peer is not requested */
1723
1724   /* This peer is requested, find active and best address */
1725   active_address = get_active_address(s, s->addresses, &address->peer);
1726   best_address = (struct ATS_Address *) update_active_address (s, &address->peer);
1727
1728   if ((NULL != best_address) && ((NULL != active_address) &&
1729       (GNUNET_YES == address_eq (active_address, best_address))))
1730   {
1731     asi = best_address->solver_information;
1732     GNUNET_assert (NULL != asi);
1733
1734     /* We sticked to the same address, therefore redistribute  */
1735     distribute_bandwidth_in_network (s, asi->network);
1736   }
1737 }
1738
1739 /**
1740  * Network scope for this address has changed
1741  *
1742  * NOTE: values in addresses are already updated
1743  *
1744  * @param solver solver handle
1745  * @param address the address
1746  * @param current_network the current network
1747  * @param new_network the new network
1748  */
1749 static void
1750 GAS_proportional_address_change_network (void *solver,
1751                                          struct ATS_Address *address,
1752                                          uint32_t current_network,
1753                                          uint32_t new_network)
1754 {
1755   struct GAS_PROPORTIONAL_Handle *s = solver;
1756   struct AddressSolverInformation *asi;
1757   int save_active = GNUNET_NO;
1758
1759   if (current_network == new_network)
1760   {
1761     GNUNET_break(0);
1762     return;
1763   }
1764
1765   asi = address->solver_information;
1766   if (NULL == asi)
1767   {
1768     GNUNET_break(0);
1769     return;
1770   }
1771
1772   /* Network changed */
1773   LOG(GNUNET_ERROR_TYPE_DEBUG,
1774       "Network type changed, moving %s address from `%s' to `%s'\n",
1775       (GNUNET_YES == address->active) ? "active" : "inactive",
1776       GNUNET_ATS_print_network_type (current_network),
1777       GNUNET_ATS_print_network_type (new_network));
1778
1779
1780   /* Start bulk to prevent disconnect */
1781   GAS_proportional_bulk_start(s);
1782
1783   save_active = address->active;
1784
1785   /* Disable and assign no bandwidth */
1786   address->active = GNUNET_NO;
1787   address->assigned_bw_in = BANDWIDTH_ZERO; /* no bandwidth assigned */
1788   address->assigned_bw_out = BANDWIDTH_ZERO; /* no bandwidth assigned */
1789
1790   /* Remove from old network */
1791   GAS_proportional_address_delete (solver, address, GNUNET_NO);
1792
1793   /* Set new network type */
1794   if (NULL == get_network (solver, new_network))
1795   {
1796     /* Address changed to invalid network... */
1797     LOG(GNUNET_ERROR_TYPE_ERROR,
1798         _("Invalid network type `%u' `%s': Disconnect!\n"), new_network,
1799         GNUNET_ATS_print_network_type (new_network));
1800     s->bw_changed (s->bw_changed_cls, address);
1801   }
1802   else
1803   {
1804     /* Add to new network and update*/
1805     GAS_proportional_address_add (solver, address, new_network);
1806   }
1807   GAS_proportional_bulk_stop (s);
1808
1809   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1810     return; /* Peer is not requested */
1811
1812   /* Find new address to suggest */
1813   if (GNUNET_YES == save_active)
1814   {
1815     /* No address available, therefore disconnect */
1816     if (NULL == update_active_address (s, &address->peer))
1817       s->bw_changed (s->bw_changed_cls, address);
1818   }
1819
1820 }
1821
1822 /**
1823  * Add a new single address to a network
1824  *
1825  * @param solver the solver Handle
1826  * @param address the address to add
1827  * @param network network type of this address
1828  */
1829 static void
1830 GAS_proportional_address_add (void *solver,
1831                               struct ATS_Address *address,
1832                               uint32_t network)
1833 {
1834   struct GAS_PROPORTIONAL_Handle *s = solver;
1835   struct Network *net = NULL;
1836   struct AddressWrapper *aw = NULL;
1837   struct AddressSolverInformation *asi;
1838
1839   GNUNET_assert(NULL != s);
1840   net = get_network (s, network);
1841   if (NULL == net)
1842   {
1843     GNUNET_break(0);
1844
1845     LOG(GNUNET_ERROR_TYPE_ERROR,
1846         "Unknown network %u `%s' for new address %p for peer `%s'\n",
1847         network, GNUNET_ATS_print_network_type(network),
1848         address, GNUNET_i2s(&address->peer));
1849
1850     return;
1851   }
1852
1853   aw = GNUNET_new (struct AddressWrapper);
1854   aw->addr = address;
1855   GNUNET_CONTAINER_DLL_insert(net->head, net->tail, aw);
1856   addresse_increment (s, net, GNUNET_YES, GNUNET_NO);
1857
1858   asi = GNUNET_new (struct AddressSolverInformation);
1859   asi->network = net;
1860   asi->calculated_quota_in_NBO = htonl (0);
1861   asi->calculated_quota_out_NBO = htonl (0);
1862   aw->addr->solver_information = asi;
1863
1864   LOG(GNUNET_ERROR_TYPE_INFO,
1865       "Adding new address %p for peer `%s', now total %u and active %u addresses in network `%s'\n",
1866       address, GNUNET_i2s(&address->peer), net->total_addresses, net->active_addresses, net->desc);
1867
1868   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1869     return; /* Peer is not requested */
1870
1871   /* This peer is requested, find best address */
1872   update_active_address (s, &address->peer);
1873 }
1874
1875
1876
1877 /**
1878  * Function invoked when the plugin is loaded.
1879  *
1880  * @param cls[in,out] the `struct GNUNET_ATS_PluginEnvironment *` to use;
1881  *            modified to return the API functions (ugh).
1882  * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure
1883  */
1884 void *
1885 libgnunet_plugin_ats_proportional_init (void *cls)
1886 {
1887   struct GNUNET_ATS_PluginEnvironment *env = cls;
1888   struct GAS_PROPORTIONAL_Handle *s;
1889   struct Network * cur;
1890   char * net_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
1891   float f_tmp;
1892   int c;
1893
1894   GNUNET_assert (NULL != env);
1895   GNUNET_assert (NULL != env->cfg);
1896   GNUNET_assert (NULL != env->bandwidth_changed_cb);
1897   GNUNET_assert (NULL != env->get_preferences);
1898   GNUNET_assert (NULL != env->get_property);
1899
1900   s = GNUNET_new (struct GAS_PROPORTIONAL_Handle);
1901   s->env = env;
1902   env->sf.s_add = &GAS_proportional_address_add;
1903   env->sf.s_address_update_property = &GAS_proportional_address_property_changed;
1904   env->sf.s_address_update_session = &GAS_proportional_address_session_changed;
1905   env->sf.s_address_update_inuse = &GAS_proportional_address_inuse_changed;
1906   env->sf.s_address_update_network = &GAS_proportional_address_change_network;
1907   env->sf.s_get = &GAS_proportional_get_preferred_address;
1908   env->sf.s_get_stop = &GAS_proportional_stop_get_preferred_address;
1909   env->sf.s_pref = &GAS_proportional_address_change_preference;
1910   env->sf.s_feedback = &GAS_proportional_address_preference_feedback;
1911   env->sf.s_del = &GAS_proportional_address_delete;
1912   env->sf.s_bulk_start = &GAS_proportional_bulk_start;
1913   env->sf.s_bulk_stop = &GAS_proportional_bulk_stop;
1914
1915   s->stats = (struct GNUNET_STATISTICS_Handle *) env->stats;
1916   s->bw_changed = env->bandwidth_changed_cb;
1917   s->bw_changed_cls = env->bw_changed_cb_cls;
1918   s->get_preferences = env->get_preferences;
1919   s->get_preferences_cls = env->get_preference_cls;
1920   s->get_properties = env->get_property;
1921   s->get_properties_cls = env->get_property_cls;
1922   s->network_count = env->network_count;
1923   s->network_entries = GNUNET_malloc (env->network_count * sizeof (struct Network));
1924
1925   /* Init */
1926   s->active_addresses = 0;
1927   s->total_addresses = 0;
1928   s->bulk_lock = GNUNET_NO;
1929   s->addresses = env->addresses;
1930   s->requests = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1931
1932   s->stability_factor = PROP_STABILITY_FACTOR;
1933   if (GNUNET_SYSERR !=
1934       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1935                                             "PROP_STABILITY_FACTOR", &f_tmp))
1936   {
1937     if ((f_tmp < 1.0) || (f_tmp > 2.0))
1938     {
1939       LOG (GNUNET_ERROR_TYPE_ERROR,
1940            _("Invalid %s configuration %f \n"),
1941            "PROP_STABILITY_FACTOR",
1942            f_tmp);
1943     }
1944     else
1945     {
1946       s->stability_factor = f_tmp;
1947       LOG (GNUNET_ERROR_TYPE_INFO,
1948            "Using %s of %.3f\n",
1949            "PROP_STABILITY_FACTOR", f_tmp);
1950     }
1951   }
1952
1953   s->prop_factor = PROPORTIONALITY_FACTOR;
1954   if (GNUNET_SYSERR !=
1955       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1956                                             "PROP_STABILITY_FACTOR", &f_tmp))
1957   {
1958     if (f_tmp < 1.0)
1959     {
1960       LOG (GNUNET_ERROR_TYPE_ERROR,
1961            _("Invalid %s configuration %f \n"),
1962            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1963     }
1964     else
1965     {
1966       s->prop_factor = f_tmp;
1967       LOG (GNUNET_ERROR_TYPE_INFO,
1968            "Using %s of %.3f\n",
1969            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1970     }
1971   }
1972
1973   for (c = 0; c < env->network_count; c++)
1974   {
1975     cur = &s->network_entries[c];
1976     cur->total_addresses = 0;
1977     cur->active_addresses = 0;
1978     cur->type = env->networks[c];
1979     cur->total_quota_in = env->in_quota[c];
1980     cur->total_quota_out = env->out_quota[c];
1981     cur->desc = net_str[c];
1982     GNUNET_asprintf (&cur->stat_total,
1983         "# ATS addresses %s total", cur->desc);
1984     GNUNET_asprintf (&cur->stat_active,
1985         "# ATS active addresses %s total", cur->desc);
1986     LOG (GNUNET_ERROR_TYPE_INFO,
1987          "Added network %u `%s' (%llu/%llu)\n",
1988         c, cur->desc, cur->total_quota_in, cur->total_quota_out);
1989   }
1990   return s;
1991 }
1992
1993
1994 /* end of plugin_ats_proportional.c */