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