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