-clarify API
[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     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       peer_relative_prefs = s->env->get_preferences (s->env->cls,
581                                                      &cur_address->addr->peer);
582
583       cur_pref = peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
584       total_weight = net->active_addresses +
585           s->prop_factor * sum_relative_peer_prefences;
586       peer_weight = (1.0 + (s->prop_factor * cur_pref));
587
588       assigned_quota_in = min_bw
589           + ((peer_weight / total_weight) * remaining_quota_in);
590       assigned_quota_out = min_bw
591           + ((peer_weight / total_weight) * remaining_quota_out);
592
593       LOG (GNUNET_ERROR_TYPE_INFO,
594           "New quota for peer `%s' with weight (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
595           GNUNET_i2s (&cur_address->addr->peer), peer_weight, total_weight,
596           assigned_quota_in, assigned_quota_out);
597     }
598     else
599     {
600       assigned_quota_in = 0;
601       assigned_quota_out = 0;
602     }
603
604     quota_in_used += assigned_quota_in;
605     quota_out_used += assigned_quota_out;
606     /* Prevent overflow due to rounding errors */
607     if (assigned_quota_in > UINT32_MAX)
608       assigned_quota_in = UINT32_MAX;
609     if (assigned_quota_out > UINT32_MAX)
610       assigned_quota_out = UINT32_MAX;
611
612     /* Compare to current bandwidth assigned */
613     asi = cur_address->addr->solver_information;
614     asi->calculated_quota_in = assigned_quota_in;
615     asi->calculated_quota_out = assigned_quota_out;
616   }
617   LOG(GNUNET_ERROR_TYPE_DEBUG,
618       "Total bandwidth assigned is (in/out): %llu /%llu\n", quota_in_used,
619       quota_out_used);
620   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
621   {
622     LOG(GNUNET_ERROR_TYPE_ERROR,
623         "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
624         net->active_addresses, quota_out_used, net->total_quota_out);
625   }
626   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
627   {
628     LOG(GNUNET_ERROR_TYPE_ERROR,
629         "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
630         net->active_addresses, quota_in_used, net->total_quota_in);
631   }
632 }
633
634
635 /**
636  * Context for finding the best address* Linked list of addresses in this network: head
637  */
638 struct FindBestAddressCtx
639 {
640   /**
641    * The solver handle
642    */
643   struct GAS_PROPORTIONAL_Handle *s;
644
645   /**
646    * The currently best address
647    */
648   struct ATS_Address *best;
649 };
650
651
652 /**
653  * Find index of a ATS property type in the array.
654  */
655 static int
656 find_property_index (uint32_t type)
657 {
658   int existing_types[] = GNUNET_ATS_QualityProperties;
659   int c;
660
661   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
662     if (existing_types[c] == type)
663       return c;
664   return GNUNET_SYSERR;
665 }
666
667
668 /**
669  * Find a "good" address to use for a peer by iterating over the addresses for this peer.
670  * If we already have an existing address, we stick to it.
671  * Otherwise, we pick by lowest distance and then by lowest latency.
672  *
673  * @param cls the `struct FindBestAddressCtx *' where we store the result
674  * @param key unused
675  * @param value another `struct ATS_Address*` to consider using
676  * @return #GNUNET_OK (continue to iterate)
677  */
678 static int
679 find_best_address_it (void *cls,
680                       const struct GNUNET_PeerIdentity *key,
681                       void *value)
682 {
683   struct FindBestAddressCtx *ctx = cls;
684   struct ATS_Address *current = value;
685   struct ATS_Address *current_best = current;
686   struct AddressSolverInformation *asi;
687   struct GNUNET_TIME_Relative active_time;
688   struct GNUNET_TIME_Relative min_active_time;
689   double best_delay;
690   double best_distance;
691   double cur_delay;
692   double cur_distance;
693   int index;
694
695   current_best = NULL;
696   asi = current->solver_information;
697   if (NULL == asi)
698   {
699     GNUNET_break (0);
700     return GNUNET_OK;
701   }
702
703   if (GNUNET_NO == is_bandwidth_available_in_network (asi->network))
704   {
705     return GNUNET_OK; /* There's no bandwidth available in this network */
706   }
707
708   if (NULL != ctx->best)
709   {
710     /* Compare current addresses with denominated 'best' address */
711     current_best = ctx->best;
712   }
713   else
714   {
715     /* We do not have a 'best' address so take this address */
716     LOG (GNUNET_ERROR_TYPE_DEBUG,
717          "Setting initial address %p\n",
718          current);
719     current_best = current;
720     goto end;
721   }
722
723   if (GNUNET_YES == current->active)
724   {
725     GNUNET_assert (asi->activated.abs_value_us != GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us);
726     active_time = GNUNET_TIME_absolute_get_duration (asi->activated);
727     min_active_time.rel_value_us =  ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) *
728         ctx->s->stability_factor;
729     if (active_time.rel_value_us <= min_active_time.rel_value_us)
730     {
731       /* Keep active address for stability reasons */
732       ctx->best = current;
733       return GNUNET_NO;
734     }
735   }
736
737   /* Now compare ATS information */
738   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
739   cur_distance = current->atsin[index].norm;
740   best_distance = ctx->best->atsin[index].norm;
741   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
742   cur_delay = current->atsin[index].norm;
743   best_delay = ctx->best->atsin[index].norm;
744
745   /* user shorter distance */
746   if (cur_distance < best_distance)
747   {
748     if (GNUNET_NO == ctx->best->active)
749     {
750       current_best = current; /* Use current */
751     }
752     else if ((best_distance / cur_distance) > ctx->s->stability_factor)
753     {
754       /* Best and active address performs worse  */
755       current_best = current;
756     }
757   }
758   else
759   {
760     /* Use current best */
761     current_best = ctx->best;
762   }
763
764   /* User connection with less delay */
765   if (cur_delay < best_delay)
766   {
767
768     if (GNUNET_NO == ctx->best->active)
769     {
770       current_best = current; /* Use current */
771     }
772     else if ((best_delay / cur_delay) > ctx->s->stability_factor)
773     {
774       /* Best and active address performs worse  */
775       current_best = current;
776     }
777   }
778   else
779   {
780     /* Use current best */
781     current_best = ctx->best;
782   }
783
784 end:
785   ctx->best = current_best;
786   return GNUNET_OK;
787 }
788
789
790 /**
791  * Find the currently best address for a peer from the set of addresses available
792  * or return NULL of no address is available
793  *
794  * @param s the proportional handle
795  * @param addresses the address hashmap
796  * @param id the peer id
797  * @return the address or NULL
798  */
799 struct ATS_Address *
800 get_best_address (struct GAS_PROPORTIONAL_Handle *s,
801                   struct GNUNET_CONTAINER_MultiPeerMap *addresses,
802                   const struct GNUNET_PeerIdentity *id)
803 {
804   struct FindBestAddressCtx fba_ctx;
805
806   fba_ctx.best = NULL;
807   fba_ctx.s = s;
808   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
809                                               id,
810                                               &find_best_address_it,
811                                               &fba_ctx);
812   return fba_ctx.best;
813 }
814
815
816 /**
817  * Hashmap Iterator to find current active address for peer
818  *
819  * @param cls last active address
820  * @param key peer's key
821  * @param value address to check
822  * @return #GNUNET_NO on double active address else #GNUNET_YES;
823  */
824 static int
825 get_active_address_it (void *cls,
826                        const struct GNUNET_PeerIdentity *key,
827                        void *value)
828 {
829   struct ATS_Address **dest = cls;
830   struct ATS_Address *aa = (struct ATS_Address *) value;
831
832   LOG (GNUNET_ERROR_TYPE_INFO,
833          "Checking address %p\n", aa);
834
835   if (GNUNET_YES == aa->active)
836   {
837   LOG (GNUNET_ERROR_TYPE_INFO,
838          "Address %p is active\n", aa);
839     if (NULL != (*dest))
840     {
841       /* should never happen */
842       LOG (GNUNET_ERROR_TYPE_ERROR,
843            "Multiple active addresses for peer `%s'\n",
844            GNUNET_i2s (&aa->peer));
845       GNUNET_break(0);
846       return GNUNET_NO;
847     }
848     (*dest) = aa;
849
850   }
851   return GNUNET_OK;
852 }
853
854
855 /**
856  * Find current active address for peer
857  *
858  * @param solver the solver handle
859  * @param addresses the address set
860  * @param peer the peer
861  * @return active address or NULL
862  */
863 static struct ATS_Address *
864 get_active_address (void *solver,
865                     const struct GNUNET_CONTAINER_MultiPeerMap * addresses,
866                     const struct GNUNET_PeerIdentity *peer)
867 {
868   static struct ATS_Address *dest;
869
870   dest = NULL;
871   GNUNET_CONTAINER_multipeermap_get_multiple (addresses, peer,
872                                               &get_active_address_it,
873                                               &dest);
874   return dest;
875 }
876
877
878 /**
879  * Lookup network struct by type
880  *
881  * @param s the solver handle
882  * @param type the network type
883  * @return the network struct
884  */
885 static struct Network *
886 get_network (struct GAS_PROPORTIONAL_Handle *s,
887              enum GNUNET_ATS_Network_Type type)
888 {
889   if (type >= s->env->network_count)
890   {
891     GNUNET_break (0);
892     return NULL;
893   }
894   return &s->network_entries[type];
895 }
896
897
898 /**
899  * Increase address count in network
900  *
901  * @param s the solver handle
902  * @param net the network type
903  * @param total increase total addresses
904  * @param active increase active addresses
905  */
906 static void
907 address_increment (struct GAS_PROPORTIONAL_Handle *s,
908                     struct Network *net,
909                     int total,
910                     int active)
911 {
912   if (GNUNET_YES == total)
913   {
914     s->total_addresses++;
915     net->total_addresses++;
916     GNUNET_STATISTICS_update (s->env->stats,
917                               "# ATS addresses total", 1, GNUNET_NO);
918     GNUNET_STATISTICS_update (s->env->stats,
919                               net->stat_total, 1, GNUNET_NO);
920   }
921   if (GNUNET_YES == active)
922   {
923     net->active_addresses++;
924     s->active_addresses++;
925     GNUNET_STATISTICS_update (s->env->stats,
926                               "# ATS active addresses total", 1,
927         GNUNET_NO);
928     GNUNET_STATISTICS_update (s->env->stats,
929                               net->stat_active, 1, GNUNET_NO);
930   }
931
932 }
933
934
935 /**
936  * Decrease address count in network
937  *
938  * @param s the solver handle
939  * @param net the network type
940  * @param total decrease total addresses
941  * @param active decrease active addresses
942  */
943 static int
944 addresse_decrement (struct GAS_PROPORTIONAL_Handle *s,
945                     struct Network *net,
946                     int total,
947                     int active)
948 {
949   int res = GNUNET_OK;
950
951   if (GNUNET_YES == total)
952   {
953     if (s->total_addresses < 1)
954     {
955       GNUNET_break(0);
956       res = GNUNET_SYSERR;
957     }
958     else
959     {
960       s->total_addresses--;
961       GNUNET_STATISTICS_update (s->env->stats,
962                                 "# ATS addresses total", -1,
963           GNUNET_NO);
964     }
965     if (net->total_addresses < 1)
966     {
967       GNUNET_break(0);
968       res = GNUNET_SYSERR;
969     }
970     else
971     {
972       net->total_addresses--;
973       GNUNET_STATISTICS_update (s->env->stats,
974                                 net->stat_total, -1, GNUNET_NO);
975     }
976   }
977
978   if (GNUNET_YES == active)
979   {
980     if (net->active_addresses < 1)
981     {
982       GNUNET_break(0);
983       res = GNUNET_SYSERR;
984     }
985     else
986     {
987       net->active_addresses--;
988       GNUNET_STATISTICS_update (s->env->stats,
989                                 net->stat_active, -1, GNUNET_NO);
990     }
991     if (s->active_addresses < 1)
992     {
993       GNUNET_break(0);
994       res = GNUNET_SYSERR;
995     }
996     else
997     {
998       s->active_addresses--;
999       GNUNET_STATISTICS_update (s->env->stats,
1000                                 "# ATS addresses total", -1,
1001           GNUNET_NO);
1002     }
1003   }
1004   return res;
1005 }
1006
1007
1008 /**
1009  * Compares addresses
1010  *
1011  * @param a address a
1012  * @param b address b
1013  * @return GNUNET_YES if equal, GNUNET_NO else
1014  */
1015 static int
1016 address_eq (struct ATS_Address *a, struct ATS_Address *b)
1017 {
1018   GNUNET_assert (NULL != a);
1019   GNUNET_assert (NULL != b);
1020   if (0 != strcmp(a->plugin, b->plugin))
1021     return GNUNET_NO;
1022   if (a->addr_len != b->addr_len)
1023     return GNUNET_NO;
1024   if (0 != memcmp (a->addr, b->addr, b->addr_len))
1025     return GNUNET_NO;
1026   if (a->session_id != b->session_id)
1027     return GNUNET_NO;
1028   return GNUNET_YES;
1029 }
1030
1031
1032 /**
1033  * Notify bandwidth changes to addresses
1034  *
1035  * @param s solver handle
1036  * @param net the network to propagate changes in
1037  */
1038 static void
1039 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
1040                      struct Network *net)
1041 {
1042   struct AddressWrapper *cur;
1043   struct AddressSolverInformation *asi;
1044
1045   for (cur = net->head; NULL != cur; cur = cur->next)
1046   {
1047       asi = cur->addr->solver_information;
1048       if ( (cur->addr->assigned_bw_in != asi->calculated_quota_in) ||
1049            (cur->addr->assigned_bw_out != asi->calculated_quota_out) )
1050       {
1051         cur->addr->assigned_bw_in = asi->calculated_quota_in;
1052         cur->addr->assigned_bw_out = asi->calculated_quota_out;
1053
1054         /* Reset for next iteration */
1055         asi->calculated_quota_in = 0;
1056         asi->calculated_quota_out = 0;
1057         LOG (GNUNET_ERROR_TYPE_DEBUG,
1058             "Bandwidth for %s address %p for peer `%s' changed to %u/%u\n",
1059             (GNUNET_NO == cur->addr->active) ? "inactive" : "active",
1060             cur->addr,
1061             GNUNET_i2s (&cur->addr->peer),
1062             cur->addr->assigned_bw_in,
1063             cur->addr->assigned_bw_out);
1064
1065         /* Notify on change */
1066         if ((GNUNET_YES == cur->addr->active))
1067         {
1068           s->env->bandwidth_changed_cb (s->env->cls,
1069                                         cur->addr);
1070         }
1071       }
1072   }
1073 }
1074
1075
1076 /**
1077  * Distribibute bandwidth
1078  *
1079  * @param s the solver handle
1080  * @param n the network, can be NULL for all network
1081  */
1082 static void
1083 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
1084                                  struct Network *n)
1085 {
1086   if (GNUNET_YES == s->bulk_lock)
1087   {
1088     s->bulk_requests++;
1089     return;
1090   }
1091
1092   if (NULL != n)
1093   {
1094     LOG (GNUNET_ERROR_TYPE_INFO,
1095         "Redistributing bandwidth in network %s with %u active and %u total addresses\n",
1096         GNUNET_ATS_print_network_type(n->type),
1097         n->active_addresses, n->total_addresses);
1098
1099     s->env->info_cb (s->env->cls,
1100                      GAS_OP_SOLVE_START,
1101                      GAS_STAT_SUCCESS,
1102                      GAS_INFO_PROP_SINGLE);
1103
1104     /* Distribute  */
1105     distribute_bandwidth(s, n);
1106
1107     s->env->info_cb (s->env->cls,
1108                      GAS_OP_SOLVE_STOP,
1109                      GAS_STAT_SUCCESS,
1110                      GAS_INFO_PROP_SINGLE);
1111     s->env->info_cb (s->env->cls,
1112                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1113                      GAS_STAT_SUCCESS,
1114                      GAS_INFO_PROP_SINGLE);
1115
1116     /* Do propagation */
1117     propagate_bandwidth (s, n);
1118
1119     s->env->info_cb (s->env->cls,
1120                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1121                      GAS_STAT_SUCCESS,
1122                      GAS_INFO_PROP_SINGLE);
1123   }
1124   else
1125   {
1126     int i;
1127     s->env->info_cb (s->env->cls,
1128                      GAS_OP_SOLVE_START,
1129                      GAS_STAT_SUCCESS,
1130                      GAS_INFO_PROP_ALL);
1131     for (i = 0; i < s->network_count; i++)
1132     {
1133       /* Distribute */
1134       distribute_bandwidth(s, &s->network_entries[i]);
1135     }
1136
1137     s->env->info_cb (s->env->cls,
1138                      GAS_OP_SOLVE_STOP,
1139                      GAS_STAT_SUCCESS,
1140                      GAS_INFO_PROP_ALL);
1141     s->env->info_cb (s->env->cls,
1142                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1143                      GAS_STAT_SUCCESS,
1144                      GAS_INFO_PROP_ALL);
1145     for (i = 0; i < s->network_count; i++)
1146     {
1147       /* Do propagation */
1148       propagate_bandwidth(s, &s->network_entries[i]);
1149     }
1150     s->env->info_cb (s->env->cls,
1151                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1152                      GAS_STAT_SUCCESS,
1153                      GAS_INFO_PROP_ALL);
1154   }
1155 }
1156
1157
1158 /**
1159  * Update active address for a peer:
1160  * Check if active address exists and what the best address is, if addresses
1161  * are different switch
1162  *
1163  * @param s solver handle
1164  * @param peer the peer to check
1165  * return the new address or NULL if no update was performed
1166   */
1167 static struct ATS_Address *
1168 update_active_address (struct GAS_PROPORTIONAL_Handle *s,
1169                        const struct GNUNET_PeerIdentity *peer)
1170 {
1171   struct ATS_Address *best_address;
1172   struct ATS_Address *current_address;
1173   struct AddressSolverInformation *asi;
1174   struct Network *net;
1175
1176   LOG (GNUNET_ERROR_TYPE_INFO,
1177        "Updating active address for peer `%s'\n",
1178        GNUNET_i2s (peer));
1179
1180   /* Find active address */
1181   current_address = get_active_address (s,
1182                                         s->addresses,
1183                                         peer);
1184
1185   LOG (GNUNET_ERROR_TYPE_INFO,
1186        "Peer `%s' has active address %p\n",
1187        GNUNET_i2s (peer),
1188        current_address);
1189
1190   /* Find best address */
1191   best_address = get_best_address (s,
1192                                    s->addresses,
1193                                    peer);
1194   LOG (GNUNET_ERROR_TYPE_INFO,
1195        "Peer `%s' has best address %p\n",
1196        GNUNET_i2s (peer),
1197        best_address);
1198
1199   if (NULL != current_address)
1200   {
1201     if ( (NULL == best_address) ||
1202          ( (NULL != best_address) &&
1203            (GNUNET_NO == address_eq (current_address,
1204                                      best_address)) ) )
1205     {
1206       /* We switch to a new address (or to none),
1207          mark old address as inactive */
1208       LOG (GNUNET_ERROR_TYPE_INFO,
1209            "Disabling previous %s address %p for peer `%s'\n",
1210            (GNUNET_NO == current_address->active) ? "inactive" : "active",
1211            current_address,
1212            GNUNET_i2s (peer));
1213
1214       asi = current_address->solver_information;
1215       GNUNET_assert (NULL != asi);
1216
1217       net = asi->network;
1218       asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1219       current_address->active = GNUNET_NO; /* No active any longer */
1220       current_address->assigned_bw_in = 0; /* no bandwidth assigned */
1221       current_address->assigned_bw_out = 0; /* no bandwidth assigned */
1222
1223       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1224         GNUNET_break(0);
1225
1226       /* Update network of previous address */
1227       distribute_bandwidth_in_network (s, net);
1228     }
1229     if (NULL == best_address)
1230     {
1231       /* We previously had an active address, but now we cannot suggest one
1232        * Therefore we have to disconnect the peer */
1233       LOG (GNUNET_ERROR_TYPE_INFO,
1234            "Disconnecting peer `%s' with previous address %p\n",
1235            GNUNET_i2s (peer),
1236            current_address);
1237       s->env->bandwidth_changed_cb (s->env->cls,
1238                                     current_address);
1239     }
1240   }
1241   if (NULL == best_address)
1242   {
1243     LOG (GNUNET_ERROR_TYPE_INFO,
1244          "Cannot suggest address for peer `%s'\n",
1245          GNUNET_i2s (peer));
1246     return NULL;
1247   }
1248
1249   LOG (GNUNET_ERROR_TYPE_INFO,
1250        "Suggesting new address %p for peer `%s'\n",
1251        best_address,
1252        GNUNET_i2s (peer));
1253
1254   if ( (NULL != current_address) &&
1255        (GNUNET_YES == address_eq (best_address, current_address)) )
1256   {
1257     GNUNET_break (GNUNET_NO != current_address->active);
1258     return best_address; /* Same same */
1259   }
1260
1261   asi = best_address->solver_information;
1262   GNUNET_assert (NULL != asi);
1263   net = asi->network;
1264
1265   /* Mark address as active */
1266   asi->activated = GNUNET_TIME_absolute_get ();
1267   best_address->active = GNUNET_YES;
1268   address_increment (s, net, GNUNET_NO, GNUNET_YES);
1269   LOG (GNUNET_ERROR_TYPE_INFO,
1270        "Address %p for peer `%s' is now active\n",
1271        best_address,
1272        GNUNET_i2s (peer));
1273   /* Distribute bandwidth */
1274   distribute_bandwidth_in_network (s, net);
1275   return best_address;
1276 }
1277
1278
1279 /**
1280  * Changes the preferences for a peer in the problem
1281  *
1282  * @param solver the solver handle
1283  * @param peer the peer to change the preference for
1284  * @param kind the kind to change the preference
1285  * @param pref_rel the normalized preference value for this kind over all clients
1286  */
1287 static void
1288 GAS_proportional_address_change_preference (void *solver,
1289                                             const struct GNUNET_PeerIdentity *peer,
1290                                             enum GNUNET_ATS_PreferenceKind kind,
1291                                             double pref_rel)
1292 {
1293   struct GAS_PROPORTIONAL_Handle *s = solver;
1294   struct ATS_Address *best_address;
1295   struct ATS_Address *active_address;
1296   struct AddressSolverInformation *asi;
1297
1298   if (GNUNET_NO ==
1299       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1300     return; /* Peer is not requested */
1301
1302   /* This peer is requested, find best address */
1303   active_address = get_active_address (s, s->addresses, peer);
1304   best_address = update_active_address (s, peer);
1305
1306   if ((NULL != best_address) && ((NULL != active_address) &&
1307       (GNUNET_YES == address_eq (active_address, best_address))))
1308   {
1309     asi = best_address->solver_information;
1310     GNUNET_assert (NULL != asi);
1311
1312     /* We sticked to the same address, therefore redistribute  */
1313     distribute_bandwidth_in_network (s, asi->network);
1314   }
1315 }
1316
1317
1318 /**
1319  * Get application feedback for a peer
1320  *
1321  * @param solver the solver handle
1322  * @param application the application
1323  * @param peer the peer to change the preference for
1324  * @param scope the time interval for this feedback: [now - scope .. now]
1325  * @param kind the kind to change the preference
1326  * @param score the score
1327  */
1328 static void
1329 GAS_proportional_address_preference_feedback (void *solver,
1330                                               struct GNUNET_SERVER_Client *application,
1331                                               const struct GNUNET_PeerIdentity *peer,
1332                                               const struct GNUNET_TIME_Relative scope,
1333                                               enum GNUNET_ATS_PreferenceKind kind,
1334                                               double score)
1335 {
1336   struct GAS_PROPORTIONAL_Handle *s = solver;
1337
1338   GNUNET_assert(NULL != peer);
1339   GNUNET_assert(NULL != s);
1340 }
1341
1342
1343 /**
1344  * Get the preferred address for a specific peer
1345  *
1346  * @param solver the solver handle
1347  * @param peer the identity of the peer
1348  * @return best address
1349  */
1350 static const struct ATS_Address *
1351 GAS_proportional_get_preferred_address (void *solver,
1352                                         const struct GNUNET_PeerIdentity *peer)
1353 {
1354   struct GAS_PROPORTIONAL_Handle *s = solver;
1355   const struct ATS_Address *best_address;
1356
1357   /* Add to list of pending requests */
1358   if (GNUNET_NO ==
1359       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1360   {
1361     GNUNET_assert (GNUNET_OK ==
1362                    GNUNET_CONTAINER_multipeermap_put (s->requests,
1363                                                      peer,
1364                                                      NULL,
1365             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1366     LOG (GNUNET_ERROR_TYPE_INFO,
1367          "Start suggesting addresses for peer `%s'\n",
1368          GNUNET_i2s (peer));
1369   }
1370
1371   best_address = update_active_address (s, peer);
1372   if (s->bulk_lock > 0)
1373     return NULL; /* Do not suggest since bulk lock is pending */
1374
1375   return best_address;
1376 }
1377
1378
1379 /**
1380  * Stop notifying about address and bandwidth changes for this peer
1381  *
1382  * @param solver the solver handle
1383  * @param peer the peer
1384  */
1385 static void
1386 GAS_proportional_stop_get_preferred_address (void *solver,
1387                                              const struct GNUNET_PeerIdentity *peer)
1388 {
1389   struct GAS_PROPORTIONAL_Handle *s = solver;
1390   struct ATS_Address *cur;
1391   struct AddressSolverInformation *asi;
1392   struct Network *cur_net;
1393
1394   if (GNUNET_YES ==
1395       GNUNET_CONTAINER_multipeermap_contains (s->requests, peer))
1396   {
1397     GNUNET_assert (GNUNET_OK ==
1398                    GNUNET_CONTAINER_multipeermap_remove (s->requests,
1399                                                          peer,
1400                                                          NULL));
1401     LOG (GNUNET_ERROR_TYPE_INFO,
1402          "Stop suggesting addresses for peer `%s'\n",
1403          GNUNET_i2s (peer));
1404   }
1405
1406   cur = get_active_address (s,
1407                             s->addresses,
1408                             peer);
1409   if (NULL != cur)
1410   {
1411     LOG (GNUNET_ERROR_TYPE_INFO,
1412          "Disabling %s address %p for peer `%s'\n",
1413          (GNUNET_NO == cur->active) ? "inactive" : "active",
1414          cur,
1415          GNUNET_i2s (&cur->peer));
1416
1417     /* Disabling current address */
1418     asi = cur->solver_information;
1419     cur_net = asi->network ;
1420     asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1421     cur->active = GNUNET_NO; /* No active any longer */
1422     cur->assigned_bw_in = 0; /* no bandwidth assigned */
1423     cur->assigned_bw_out = 0; /* no bandwidth assigned */
1424
1425     if (GNUNET_SYSERR ==
1426         addresse_decrement (s, cur_net, GNUNET_NO, GNUNET_YES))
1427       GNUNET_break(0);
1428
1429     distribute_bandwidth_in_network (s, cur_net);
1430   }
1431 }
1432
1433
1434 /**
1435  * Remove an address from the solver
1436  *
1437  * @param solver the solver handle
1438  * @param address the address to remove
1439  * @param session_only delete only session not whole address
1440  */
1441 static void
1442 GAS_proportional_address_delete (void *solver,
1443                                  struct ATS_Address *address,
1444                                  int session_only)
1445 {
1446   struct GAS_PROPORTIONAL_Handle *s = solver;
1447   struct Network *net;
1448   struct AddressWrapper *aw;
1449   struct AddressSolverInformation *asi;
1450
1451   /* Remove an adress completely, we have to:
1452    * - Remove from specific network
1453    * - Decrease number of total addresses
1454    * - If active:
1455    *   - decrease number of active addreses
1456    *   - update quotas
1457    */
1458   asi = address->solver_information;
1459
1460   if (NULL == asi)
1461   {
1462     GNUNET_break (0);
1463     return;
1464   }
1465   net = asi->network;
1466
1467   if (GNUNET_NO == session_only)
1468   {
1469     LOG (GNUNET_ERROR_TYPE_INFO,
1470          "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1471          (GNUNET_NO == address->active) ? "inactive" : "active",
1472          address,
1473          GNUNET_i2s (&address->peer),
1474          net->desc,
1475          net->total_addresses,
1476          net->active_addresses);
1477
1478     /* Remove address */
1479     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
1480     for (aw = net->head; NULL != aw; aw = aw->next)
1481     {
1482       if (aw->addr == address)
1483         break;
1484     }
1485     if (NULL == aw)
1486     {
1487       GNUNET_break(0);
1488       return;
1489     }
1490     GNUNET_CONTAINER_DLL_remove (net->head,
1491                                  net->tail,
1492                                  aw);
1493     GNUNET_free (aw);
1494   }
1495   else
1496   {
1497     /* Remove session only: remove if active and update */
1498     LOG (GNUNET_ERROR_TYPE_INFO,
1499          "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1500          (GNUNET_NO == address->active) ? "inactive" : "active",
1501          address,
1502          GNUNET_i2s (&address->peer),
1503          net->desc,
1504          net->total_addresses,
1505          net->active_addresses);
1506   }
1507
1508   if (GNUNET_YES == address->active)
1509   {
1510     /* Address was active, remove from network and update quotas*/
1511     address->active = GNUNET_NO;
1512     address->assigned_bw_in = 0;
1513     address->assigned_bw_out = 0;
1514     asi->calculated_quota_in = 0;
1515     asi->calculated_quota_out = 0;
1516
1517     if (GNUNET_SYSERR ==
1518         addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1519       GNUNET_break(0);
1520     distribute_bandwidth_in_network (s, net);
1521
1522     if (NULL ==
1523         update_active_address (s, &address->peer))
1524     {
1525       /* No alternative address found, disconnect peer */
1526       LOG (GNUNET_ERROR_TYPE_INFO,
1527            "Disconnecting peer `%s' after deleting previous address %p\n",
1528            GNUNET_i2s (&address->peer),
1529            address);
1530       s->env->bandwidth_changed_cb (s->env->cls,
1531                                     address);
1532     }
1533   }
1534   if (GNUNET_NO == session_only)
1535   {
1536     GNUNET_free_non_null (address->solver_information);
1537     address->solver_information = NULL;
1538   }
1539
1540   LOG (GNUNET_ERROR_TYPE_INFO,
1541        "After deleting address now total %u and active %u addresses in network `%s'\n",
1542        net->total_addresses,
1543        net->active_addresses,
1544        net->desc);
1545 }
1546
1547
1548 /**
1549  * Start a bulk operation
1550  *
1551  * @param solver the solver
1552  */
1553 static void
1554 GAS_proportional_bulk_start (void *solver)
1555 {
1556   struct GAS_PROPORTIONAL_Handle *s = solver;
1557
1558   LOG (GNUNET_ERROR_TYPE_DEBUG,
1559        "Locking solver for bulk operation ...\n");
1560   GNUNET_assert (NULL != solver);
1561   s->bulk_lock++;
1562 }
1563
1564
1565 /**
1566  * Bulk operation done
1567  */
1568 static void
1569 GAS_proportional_bulk_stop (void *solver)
1570 {
1571   struct GAS_PROPORTIONAL_Handle *s = solver;
1572
1573   LOG (GNUNET_ERROR_TYPE_DEBUG,
1574        "Unlocking solver from bulk operation ...\n");
1575   if (s->bulk_lock < 1)
1576   {
1577     GNUNET_break(0);
1578     return;
1579   }
1580   s->bulk_lock--;
1581   if ((0 == s->bulk_lock) && (0 < s->bulk_requests))
1582   {
1583     LOG(GNUNET_ERROR_TYPE_INFO, "No lock pending, recalculating\n");
1584     distribute_bandwidth_in_network (s, NULL);
1585     s->bulk_requests = 0;
1586   }
1587 }
1588
1589
1590 /**
1591  * Add a new single address to a network
1592  *
1593  * @param solver the solver Handle
1594  * @param address the address to add
1595  * @param network network type of this address
1596  */
1597 static void
1598 GAS_proportional_address_add (void *solver,
1599                               struct ATS_Address *address,
1600                               uint32_t network);
1601
1602
1603 /**
1604  * Transport properties for this address have changed
1605  *
1606  * @param solver solver handle
1607  * @param address the address
1608  * @param type the ATSI type in HBO
1609  * @param abs_value the absolute value of the property
1610  * @param rel_value the normalized value
1611  */
1612 static void
1613 GAS_proportional_address_property_changed (void *solver,
1614                                            struct ATS_Address *address,
1615                                            enum GNUNET_ATS_Property type,
1616                                            uint32_t abs_value,
1617                                            double rel_value)
1618 {
1619   struct GAS_PROPORTIONAL_Handle *s = solver;
1620   struct Network *n;
1621   struct AddressSolverInformation *asi;
1622   struct ATS_Address *best_address;
1623   struct ATS_Address *active_address;
1624
1625   asi = address->solver_information;
1626   if (NULL == asi)
1627   {
1628     GNUNET_break(0);
1629     return;
1630   }
1631
1632   n = asi->network;
1633   if (NULL == n)
1634   {
1635     GNUNET_break(0);
1636     return;
1637   }
1638
1639   LOG(GNUNET_ERROR_TYPE_INFO,
1640       "Property `%s' for peer `%s' address %p changed to %.2f \n",
1641       GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1642       address, rel_value);
1643
1644   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1645     return; /* Peer is not requested */
1646
1647   /* This peer is requested, find active and best address */
1648   active_address = get_active_address(s, s->addresses, &address->peer);
1649   best_address = update_active_address (s,
1650                                         &address->peer);
1651
1652   if ((NULL != best_address) && ((NULL != active_address) &&
1653       (GNUNET_YES == address_eq (active_address, best_address))))
1654   {
1655     asi = best_address->solver_information;
1656     GNUNET_assert (NULL != asi);
1657
1658     /* We sticked to the same address, therefore redistribute  */
1659     distribute_bandwidth_in_network (s, asi->network);
1660   }
1661 }
1662
1663
1664 /**
1665  * Add a new single address to a network
1666  *
1667  * @param solver the solver Handle
1668  * @param address the address to add
1669  * @param network network type of this address
1670  */
1671 static void
1672 GAS_proportional_address_add (void *solver,
1673                               struct ATS_Address *address,
1674                               enum GNUNET_ATS_Network_Type network)
1675 {
1676   struct GAS_PROPORTIONAL_Handle *s = solver;
1677   struct Network *net;
1678   struct AddressWrapper *aw;
1679   struct AddressSolverInformation *asi;
1680
1681   net = get_network (s, network);
1682   if (NULL == net)
1683   {
1684     GNUNET_break (0);
1685     LOG (GNUNET_ERROR_TYPE_ERROR,
1686          "Unknown network %u `%s' for new address %p for peer `%s'\n",
1687          network,
1688          GNUNET_ATS_print_network_type (network),
1689          address,
1690          GNUNET_i2s (&address->peer));
1691     return;
1692   }
1693
1694   aw = GNUNET_new (struct AddressWrapper);
1695   aw->addr = address;
1696   GNUNET_CONTAINER_DLL_insert(net->head, net->tail, aw);
1697   address_increment (s, net, GNUNET_YES, GNUNET_NO);
1698
1699   asi = GNUNET_new (struct AddressSolverInformation);
1700   asi->network = net;
1701   asi->calculated_quota_in = 0;
1702   asi->calculated_quota_out = 0;
1703   aw->addr->solver_information = asi;
1704
1705   LOG(GNUNET_ERROR_TYPE_INFO,
1706       "Adding new address %p for peer `%s', now total %u and active %u addresses in network `%s'\n",
1707       address, GNUNET_i2s(&address->peer), net->total_addresses, net->active_addresses, net->desc);
1708
1709   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1710     return; /* Peer is not requested */
1711
1712   /* This peer is requested, find best address */
1713   update_active_address (s, &address->peer);
1714 }
1715
1716
1717
1718 /**
1719  * Function invoked when the plugin is loaded.
1720  *
1721  * @param[in,out] cls the `struct GNUNET_ATS_PluginEnvironment *` to use;
1722  *            modified to return the API functions (ugh).
1723  * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure
1724  */
1725 void *
1726 libgnunet_plugin_ats_proportional_init (void *cls)
1727 {
1728   static struct GNUNET_ATS_SolverFunctions sf;
1729   struct GNUNET_ATS_PluginEnvironment *env = cls;
1730   struct GAS_PROPORTIONAL_Handle *s;
1731   struct Network * cur;
1732   float f_tmp;
1733   int c;
1734
1735   GNUNET_assert (NULL != env);
1736   GNUNET_assert (NULL != env->cfg);
1737   GNUNET_assert (NULL != env->bandwidth_changed_cb);
1738   GNUNET_assert (NULL != env->get_preferences);
1739
1740   s = GNUNET_new (struct GAS_PROPORTIONAL_Handle);
1741   s->env = env;
1742   sf.cls = s;
1743   sf.s_add = &GAS_proportional_address_add;
1744   sf.s_address_update_property = &GAS_proportional_address_property_changed;
1745   sf.s_get = &GAS_proportional_get_preferred_address;
1746   sf.s_get_stop = &GAS_proportional_stop_get_preferred_address;
1747   sf.s_pref = &GAS_proportional_address_change_preference;
1748   sf.s_feedback = &GAS_proportional_address_preference_feedback;
1749   sf.s_del = &GAS_proportional_address_delete;
1750   sf.s_bulk_start = &GAS_proportional_bulk_start;
1751   sf.s_bulk_stop = &GAS_proportional_bulk_stop;
1752
1753   s->network_entries = GNUNET_malloc (env->network_count * sizeof (struct Network));
1754
1755   /* Init */
1756   s->active_addresses = 0;
1757   s->total_addresses = 0;
1758   s->bulk_lock = GNUNET_NO;
1759   s->addresses = env->addresses;
1760   s->requests = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
1761
1762   s->stability_factor = PROP_STABILITY_FACTOR;
1763   if (GNUNET_SYSERR !=
1764       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1765                                             "PROP_STABILITY_FACTOR", &f_tmp))
1766   {
1767     if ((f_tmp < 1.0) || (f_tmp > 2.0))
1768     {
1769       LOG (GNUNET_ERROR_TYPE_ERROR,
1770            _("Invalid %s configuration %f \n"),
1771            "PROP_STABILITY_FACTOR",
1772            f_tmp);
1773     }
1774     else
1775     {
1776       s->stability_factor = f_tmp;
1777       LOG (GNUNET_ERROR_TYPE_INFO,
1778            "Using %s of %.3f\n",
1779            "PROP_STABILITY_FACTOR", f_tmp);
1780     }
1781   }
1782
1783   s->prop_factor = PROPORTIONALITY_FACTOR;
1784   if (GNUNET_SYSERR !=
1785       GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
1786                                             "PROP_PROPORTIONALITY_FACTOR",
1787                                             &f_tmp))
1788   {
1789     if (f_tmp < 1.0)
1790     {
1791       LOG (GNUNET_ERROR_TYPE_ERROR,
1792            _("Invalid %s configuration %f \n"),
1793            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1794     }
1795     else
1796     {
1797       s->prop_factor = f_tmp;
1798       LOG (GNUNET_ERROR_TYPE_INFO,
1799            "Using %s of %.3f\n",
1800            "PROP_PROPORTIONALITY_FACTOR", f_tmp);
1801     }
1802   }
1803
1804   for (c = 0; c < env->network_count; c++)
1805   {
1806     cur = &s->network_entries[c];
1807     cur->type = c;
1808     cur->total_quota_in = env->in_quota[c];
1809     cur->total_quota_out = env->out_quota[c];
1810     cur->desc = GNUNET_ATS_print_network_type (c);
1811     GNUNET_asprintf (&cur->stat_total,
1812                      "# ATS addresses %s total",
1813                      cur->desc);
1814     GNUNET_asprintf (&cur->stat_active,
1815                      "# ATS active addresses %s total",
1816                      cur->desc);
1817     LOG (GNUNET_ERROR_TYPE_INFO,
1818          "Added network %u `%s' (%llu/%llu)\n",
1819          c,
1820          cur->desc,
1821          cur->total_quota_in,
1822          cur->total_quota_out);
1823   }
1824   return &sf;
1825 }
1826
1827
1828 /* end of plugin_ats_proportional.c */