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