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