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