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