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