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