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