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