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