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