splitting up calculation and notification for proportional solver to ensure measureme...
[oweals/gnunet.git] / src / ats / libgnunet_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/libgnunet_plugin_ats_proportional.c
23  * @brief ATS proportional solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "libgnunet_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 PREF_AGING_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
207 #define PREF_AGING_FACTOR 0.95
208
209 #define DEFAULT_REL_PREFERENCE 1.0
210 #define DEFAULT_ABS_PREFERENCE 0.0
211 #define MIN_UPDATE_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
212
213 /**
214  * A handle for the proportional solver
215  */
216 struct GAS_PROPORTIONAL_Handle
217 {
218    struct GNUNET_ATS_PluginEnvironment *env;
219
220   /**
221    * Statistics handle
222    */
223   struct GNUNET_STATISTICS_Handle *stats;
224
225   /**
226    * Hashmap containing all valid addresses
227    */
228   const struct GNUNET_CONTAINER_MultiPeerMap *addresses;
229
230   /**
231    * Pending address requests
232    */
233   struct GNUNET_CONTAINER_MultiPeerMap *requests;
234
235   /**
236    * Bandwidth changed callback
237    */
238   GAS_bandwidth_changed_cb bw_changed;
239
240   /**
241    * Bandwidth changed callback cls
242    */
243   void *bw_changed_cls;
244
245   /**
246    * ATS function to get preferences
247    */
248   GAS_get_preferences get_preferences;
249
250   /**
251    * Closure for ATS function to get preferences
252    */
253   void *get_preferences_cls;
254
255   /**
256    * ATS function to get properties
257    */
258   GAS_get_properties get_properties;
259
260   /**
261    * Closure for ATS function to get properties
262    */
263   void *get_properties_cls;
264
265   /**
266    * Bulk lock
267    */
268   int bulk_lock;
269
270   /**
271    * Number of changes while solver was locked
272    */
273   int bulk_requests;
274
275   /**
276    * Total number of addresses for solver
277    */
278   unsigned int total_addresses;
279
280   /**
281    * Number of active addresses for solver
282    */
283   unsigned int active_addresses;
284
285   /**
286    * Networks array
287    */
288   struct Network *network_entries;
289
290   /**
291    * Number of networks
292    */
293   unsigned int network_count;
294
295 };
296
297 /**
298  * Representation of a network
299  */
300 struct Network
301 {
302   /**
303    * ATS network type
304    */
305   unsigned int type;
306
307   /**
308    * Network description
309    */
310   char *desc;
311
312   /**
313    * Total inbound quota
314    *
315    */
316   unsigned long long total_quota_in;
317
318   /**
319    * Total outbound quota
320    *
321    */
322   unsigned long long total_quota_out;
323
324   /**
325    * Number of active addresses for this network
326    */
327   unsigned int active_addresses;
328
329   /**
330    * Number of total addresses for this network
331    */
332   unsigned int total_addresses;
333
334   /**
335    * String for statistics total addresses
336    */
337   char *stat_total;
338
339   /**
340    * String for statistics active addresses
341    */
342   char *stat_active;
343
344   struct AddressWrapper *head;
345   struct AddressWrapper *tail;
346 };
347
348 /**
349  * Address information stored in the solver
350  */
351 struct AddressSolverInformation
352 {
353   struct Network *network;
354
355   /**
356    * Inbound quota
357    *
358    */
359   unsigned long long calculated_quota_in_NBO;
360
361   /**
362    * Outbound quota
363    *
364    */
365   unsigned long long calculated_quota_out_NBO;
366
367
368 };
369
370 /**
371  * Wrapper for addresses to store them in network's linked list
372  */
373 struct AddressWrapper
374 {
375   /**
376    * Next in DLL
377    */
378   struct AddressWrapper *next;
379
380   /**
381    * Previous in DLL
382    */
383   struct AddressWrapper *prev;
384
385   /**
386    * The address
387    */
388   struct ATS_Address *addr;
389 };
390
391 /**
392  *  Important solver functions
393  *  ---------------------------
394  */
395
396 void *
397 libgnunet_plugin_ats_proportional_init (void *cls)
398 {
399   struct GNUNET_ATS_PluginEnvironment *env = cls;
400   struct GAS_PROPORTIONAL_Handle *s;
401   struct Network * cur;
402   char * net_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
403   int c;
404
405   GNUNET_assert (NULL != env);
406   GNUNET_assert(NULL != env->cfg);
407   GNUNET_assert(NULL != env->stats);
408   GNUNET_assert(NULL != env->bandwidth_changed_cb);
409   GNUNET_assert(NULL != env->get_preferences);
410   GNUNET_assert(NULL != env->get_property);
411
412   s = GNUNET_malloc (sizeof (struct GAS_PROPORTIONAL_Handle));
413   s->env = env;
414   env->sf.s_add = &GAS_proportional_address_add;
415   env->sf.s_address_update_property = &GAS_proportional_address_property_changed;
416   env->sf.s_address_update_session = &GAS_proportional_address_session_changed;
417   env->sf.s_address_update_inuse = &GAS_proportional_address_inuse_changed;
418   env->sf.s_address_update_network = &GAS_proportional_address_change_network;
419   env->sf.s_get = &GAS_proportional_get_preferred_address;
420   env->sf.s_get_stop = &GAS_proportional_stop_get_preferred_address;
421   env->sf.s_pref = &GAS_proportional_address_change_preference;
422   env->sf.s_feedback = &GAS_proportional_address_preference_feedback;
423   env->sf.s_del = &GAS_proportional_address_delete;
424   env->sf.s_bulk_start = &GAS_proportional_bulk_start;
425   env->sf.s_bulk_stop = &GAS_proportional_bulk_stop;
426
427   s->stats = (struct GNUNET_STATISTICS_Handle *) env->stats;
428   s->bw_changed = env->bandwidth_changed_cb;
429   s->bw_changed_cls = env->bw_changed_cb_cls;
430   s->get_preferences = env->get_preferences;
431   s->get_preferences_cls = env->get_preference_cls;
432   s->get_properties = env->get_property;
433   s->get_properties_cls = env->get_property_cls;
434   s->network_count = env->network_count;
435   s->network_entries = GNUNET_malloc (env->network_count * sizeof (struct Network));
436
437   /* Init */
438   s->active_addresses = 0;
439   s->total_addresses = 0;
440   s->bulk_lock = GNUNET_NO;
441   s->addresses = env->addresses;
442   s->requests = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
443
444   for (c = 0; c < env->network_count; c++)
445   {
446     cur = &s->network_entries[c];
447     cur->total_addresses = 0;
448     cur->active_addresses = 0;
449     cur->type = env->networks[c];
450     cur->total_quota_in = env->in_quota[c];
451     cur->total_quota_out = env->out_quota[c];
452     cur->desc = net_str[c];
453     GNUNET_asprintf (&cur->stat_total,
454         "# ATS addresses %s total", cur->desc);
455     GNUNET_asprintf (&cur->stat_active,
456         "# ATS active addresses %s total", cur->desc);
457     LOG (GNUNET_ERROR_TYPE_INFO, "Added network %u `%s' %p\n", c, cur->desc, s);
458   }
459   return s;
460 }
461
462 void *
463 libgnunet_plugin_ats_proportional_done (void *cls)
464 {
465   struct GAS_PROPORTIONAL_Handle *s = cls;
466   struct AddressWrapper *cur;
467   struct AddressWrapper *next;
468   int c;
469   GNUNET_assert(s != NULL);
470   for (c = 0; c < s->network_count; c++)
471   {
472     if (s->network_entries[c].total_addresses > 0)
473     {
474       LOG(GNUNET_ERROR_TYPE_DEBUG,
475           "Had %u addresses for network `%s' not deleted during shutdown\n",
476           s->network_entries[c].total_addresses, s->network_entries[c].desc);
477       GNUNET_break(0);
478     }
479
480     if (s->network_entries[c].active_addresses > 0)
481     {
482       LOG(GNUNET_ERROR_TYPE_ERROR,
483           "Had %u active addresses for network `%s' not deleted during shutdown\n",
484           s->network_entries[c].active_addresses, s->network_entries[c].desc);
485       GNUNET_break(0);
486     }
487
488     next = s->network_entries[c].head;
489     while (NULL != (cur = next))
490     {
491       next = cur->next;
492       GNUNET_CONTAINER_DLL_remove(s->network_entries[c].head,
493           s->network_entries[c].tail, cur);
494       GNUNET_free(cur);
495     }
496     GNUNET_free(s->network_entries[c].stat_total);
497     GNUNET_free(s->network_entries[c].stat_active);
498   }
499   if (s->total_addresses > 0)
500   {
501     LOG(GNUNET_ERROR_TYPE_ERROR,
502         "Had %u addresses not deleted during shutdown\n", s->total_addresses);
503     GNUNET_break(0);
504   }
505   if (s->active_addresses > 0)
506   {
507     LOG(GNUNET_ERROR_TYPE_ERROR,
508         "Had %u active addresses not deleted during shutdown\n",
509         s->active_addresses);
510     GNUNET_break (0);
511   }
512   GNUNET_free (s->network_entries);
513   GNUNET_CONTAINER_multipeermap_destroy (s->requests);
514   GNUNET_free (s);
515   return NULL;
516 }
517
518
519 /**
520  * Test if bandwidth is available in this network to add an additional address
521  *
522  * @param net the network type to update
523  * @return GNUNET_YES or GNUNET_NO
524  */
525 static int
526 is_bandwidth_available_in_network (struct Network *net)
527 {
528   GNUNET_assert(NULL != net);
529   unsigned int na = net->active_addresses + 1;
530   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
531   if (((net->total_quota_in / na) > min_bw)
532       && ((net->total_quota_out / na) > min_bw))
533   {
534     LOG(GNUNET_ERROR_TYPE_DEBUG,
535         "Enough bandwidth available for %u active addresses in network `%s'\n",
536         na, net->desc);
537
538     return GNUNET_YES;
539   }
540   LOG(GNUNET_ERROR_TYPE_DEBUG,
541       "Not enough bandwidth available for %u active addresses in network `%s'\n",
542       na, net->desc);
543   return GNUNET_NO;
544 }
545
546 /**
547  * Update bandwidth assigned to peers in this network
548  *
549  * @param s the solver handle
550  * @param net the network type to update
551  * @param address_except address excluded from notification, since we suggest
552  * this address
553  */
554 static void
555 distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
556     struct Network *net, struct ATS_Address *address_except)
557 {
558   struct AddressSolverInformation *asi;
559   struct AddressWrapper *cur;
560
561   unsigned long long remaining_quota_in = 0;
562   unsigned long long quota_out_used = 0;
563   unsigned long long remaining_quota_out = 0;
564   unsigned long long quota_in_used = 0;
565   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
566   double peer_prefs;
567   double total_prefs; /* Important: has to be double not float due to precision */
568   double cur_pref; /* Important: has to be double not float due to precision */
569   const double *t = NULL; /* Important: has to be double not float due to precision */
570   int c;
571   unsigned long long assigned_quota_in = 0;
572   unsigned long long assigned_quota_out = 0;
573
574
575   LOG(GNUNET_ERROR_TYPE_DEBUG,
576       "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
577       net->desc, net->active_addresses, net->total_quota_in,
578       net->total_quota_in);
579
580   if (net->active_addresses == 0)
581     return; /* no addresses to update */
582
583   /* Idea
584    * Assign every peer in network minimum Bandwidth
585    * Distribute bandwidth left according to preference
586    */
587
588   if ((net->active_addresses * min_bw) > net->total_quota_in)
589   {
590     GNUNET_break(0);
591     return;
592   }
593   if ((net->active_addresses * min_bw) > net->total_quota_out)
594   {
595     GNUNET_break(0);
596     return;
597   }
598
599   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
600   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
601   LOG(GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
602       remaining_quota_in, remaining_quota_out);
603   total_prefs = 0.0;
604   for (cur = net->head; NULL != cur; cur = cur->next)
605   {
606     if (GNUNET_YES == cur->addr->active)
607     {
608       GNUNET_assert(
609           NULL != (t = s->get_preferences (s->get_preferences_cls, &cur->addr->peer)));
610
611       peer_prefs = 0.0;
612       for (c = 0; c < GNUNET_ATS_PreferenceCount; c++)
613       {
614         if (c != GNUNET_ATS_PREFERENCE_END)
615         {
616           //fprintf (stderr, "VALUE[%u] %s %.3f \n", c, GNUNET_i2s (&cur->addr->peer), t[c]);
617           peer_prefs += t[c];
618         }
619       }
620       total_prefs += (peer_prefs / (GNUNET_ATS_PreferenceCount - 1));
621     }
622   }
623   for (cur = net->head; NULL != cur; cur = cur->next)
624   {
625     if (GNUNET_YES == cur->addr->active)
626     {
627       cur_pref = 0.0;
628       GNUNET_assert(
629           NULL != (t = s->get_preferences (s->get_preferences_cls, &cur->addr->peer)));
630
631       for (c = 0; c < GNUNET_ATS_PreferenceCount; c++)
632       {
633         if (c != GNUNET_ATS_PREFERENCE_END)
634           cur_pref += t[c];
635       }
636       cur_pref /= 2;
637
638       assigned_quota_in = min_bw
639           + ((cur_pref / total_prefs) * remaining_quota_in);
640       assigned_quota_out = min_bw
641           + ((cur_pref / total_prefs) * remaining_quota_out);
642
643       LOG(GNUNET_ERROR_TYPE_DEBUG,
644           "New quota for peer `%s' with preference (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
645           GNUNET_i2s (&cur->addr->peer), cur_pref, total_prefs,
646           assigned_quota_in, assigned_quota_out);
647     }
648     else
649     {
650       assigned_quota_in = 0;
651       assigned_quota_out = 0;
652     }
653
654     quota_in_used += assigned_quota_in;
655     quota_out_used += assigned_quota_out;
656     /* Prevent overflow due to rounding errors */
657     if (assigned_quota_in > UINT32_MAX)
658       assigned_quota_in = UINT32_MAX;
659     if (assigned_quota_out > UINT32_MAX)
660       assigned_quota_out = UINT32_MAX;
661
662     /* Compare to current bandwidth assigned */
663     asi = cur->addr->solver_information;
664     asi->calculated_quota_in_NBO = htonl (assigned_quota_in);
665     asi->calculated_quota_out_NBO = htonl (assigned_quota_out);
666   }
667   LOG(GNUNET_ERROR_TYPE_DEBUG,
668       "Total bandwidth assigned is (in/out): %llu /%llu\n", quota_in_used,
669       quota_out_used);
670   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
671   {
672     LOG(GNUNET_ERROR_TYPE_ERROR,
673         "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
674         net->active_addresses, quota_out_used, net->total_quota_out);
675   }
676   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
677   {
678     LOG(GNUNET_ERROR_TYPE_ERROR,
679         "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
680         net->active_addresses, quota_in_used, net->total_quota_in);
681   }
682 }
683
684 struct FindBestAddressCtx
685 {
686   struct GAS_PROPORTIONAL_Handle *s;
687   struct ATS_Address *best;
688 };
689
690 static int
691 find_property_index (uint32_t type)
692 {
693   int existing_types[] = GNUNET_ATS_QualityProperties;
694   int c;
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  * Find a "good" address to use for a peer by iterating over the addresses for this peer.
703  * If we already have an existing address, we stick to it.
704  * Otherwise, we pick by lowest distance and then by lowest latency.
705  *
706  * @param cls the 'struct ATS_Address**' where we store the result
707  * @param key unused
708  * @param value another 'struct ATS_Address*' to consider using
709  * @return GNUNET_OK (continue to iterate)
710  */
711 static int
712 find_best_address_it (void *cls,
713                       const struct GNUNET_PeerIdentity *key,
714                       void *value)
715 {
716   struct FindBestAddressCtx *fba_ctx = (struct FindBestAddressCtx *) cls;
717   struct ATS_Address *current = (struct ATS_Address *) value;
718   struct GNUNET_TIME_Absolute now;
719   struct AddressSolverInformation *asi;
720   const double *norm_prop_cur;
721   const double *norm_prop_prev;
722   int index;
723
724   asi = current->solver_information;
725   now = GNUNET_TIME_absolute_get ();
726
727   if (current->blocked_until.abs_value_us
728       == GNUNET_TIME_absolute_max (now, current->blocked_until).abs_value_us)
729   {
730     /* This address is blocked for suggestion */
731     LOG(GNUNET_ERROR_TYPE_DEBUG, "Address %p blocked for suggestion for %s \n",
732         current,
733         GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (now, current->blocked_until), GNUNET_YES));
734     return GNUNET_OK;
735   }
736   if (GNUNET_NO == is_bandwidth_available_in_network (asi->network))
737     return GNUNET_OK; /* There's no bandwidth available in this network */
738   if (NULL != fba_ctx->best)
739   {
740     GNUNET_assert(NULL != fba_ctx->best->plugin);
741     GNUNET_assert(NULL != current->plugin);
742     if (0 == strcmp (fba_ctx->best->plugin, current->plugin))
743     {
744       if ((0 != fba_ctx->best->addr_len) && (0 == current->addr_len))
745       {
746         /* saved address was an outbound address, but we have an inbound address */
747         fba_ctx->best = current;
748         return GNUNET_OK;
749       }
750       if (0 == fba_ctx->best->addr_len)
751       {
752         /* saved address was an inbound address, so do not overwrite */
753         return GNUNET_OK;
754       }
755     }
756   }
757   if (NULL == fba_ctx->best)
758   {
759     fba_ctx->best = current;
760     return GNUNET_OK;
761   }
762   if ((ntohl (fba_ctx->best->assigned_bw_in.value__) == 0)
763       && (ntohl (current->assigned_bw_in.value__) > 0))
764   {
765     /* stick to existing connection */
766     fba_ctx->best = current;
767     return GNUNET_OK;
768   }
769
770   norm_prop_cur = fba_ctx->s->get_properties (fba_ctx->s->get_properties_cls,
771       (const struct ATS_Address *) current);
772   norm_prop_prev = fba_ctx->s->get_properties (fba_ctx->s->get_properties_cls,
773       (const struct ATS_Address *) fba_ctx->best);
774   /*
775    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s previous %.2f current %.2f\n",
776    "DISTANCE", norm_prop_cur[1], norm_prop_cur[1]);
777    */
778   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
779   if (GNUNET_SYSERR == index)
780   {
781     GNUNET_break(0);
782     return GNUNET_OK;
783   }
784   if (norm_prop_cur[index] < norm_prop_prev[index])
785   {
786     /* user shorter distance */
787     fba_ctx->best = current;
788     return GNUNET_OK;
789   }
790   /*
791    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s previous %.2f current %.2f\n",
792    "DELAY", norm_prop_cur[1], norm_prop_cur[1]);
793    */
794   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
795   if (GNUNET_SYSERR == index)
796   {
797     GNUNET_break(0);
798     return GNUNET_OK;
799   }
800   if (norm_prop_cur[index] < norm_prop_prev[index])
801   {
802     /* user shorter delay */
803     fba_ctx->best = current;
804     return GNUNET_OK;
805   }
806
807   /* don't care */
808   return GNUNET_OK;
809 }
810
811 /**
812  *  Helper functions
813  *  ---------------------------
814  */
815 static void
816 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
817     struct Network *net, struct ATS_Address *address_except)
818 {
819   struct AddressWrapper *cur;
820   struct AddressSolverInformation *asi;
821   for (cur = net->head; NULL != cur; cur = cur->next)
822   {
823       asi = cur->addr->solver_information;
824       if ( (cur->addr->assigned_bw_in.value__ != asi->calculated_quota_in_NBO) ||
825            (cur->addr->assigned_bw_out.value__ != asi->calculated_quota_out_NBO) )
826       {
827         cur->addr->assigned_bw_in.value__ = asi->calculated_quota_in_NBO;
828         cur->addr->assigned_bw_out.value__ = asi->calculated_quota_in_NBO;
829         /* Notify on change */
830         if ((GNUNET_YES == cur->addr->active) && (cur->addr != address_except))
831           s->bw_changed (s->bw_changed_cls, cur->addr);
832       }
833   }
834 }
835
836 /**
837  * Distribibute bandwidth
838  *
839  * @param s the solver handle
840  * @param n the network, can be NULL for all network
841  * @param address_except do not notify for this address
842  */
843 static void
844 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
845     struct Network *n, struct ATS_Address *address_except)
846 {
847   if (GNUNET_YES == s->bulk_lock)
848   {
849     s->bulk_requests++;
850     return;
851   }
852
853   if (NULL != n)
854   {
855     if (NULL != s->env->info_cb)
856       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
857           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
858     distribute_bandwidth(s, n, address_except);
859     if (NULL != s->env->info_cb)
860       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
861           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
862     if (NULL != s->env->info_cb)
863       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
864           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
865     propagate_bandwidth(s, n, address_except);
866     if (NULL != s->env->info_cb)
867       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
868           GAS_STAT_SUCCESS, GAS_INFO_PROP_SINGLE);
869   }
870   else
871   {
872     int i;
873     if (NULL != s->env->info_cb)
874       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_START,
875           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
876     for (i = 0; i < s->network_count; i++)
877       distribute_bandwidth(s, &s->network_entries[i], NULL);
878     if (NULL != s->env->info_cb)
879       s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_STOP,
880           GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
881     for (i = 0; i < s->network_count; i++)
882     {
883       if (NULL != s->env->info_cb)
884         s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
885             GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
886       propagate_bandwidth(s, &s->network_entries[i], address_except);
887       if (NULL != s->env->info_cb)
888         s->env->info_cb(s->env->info_cb_cls, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
889             GAS_STAT_SUCCESS, GAS_INFO_PROP_ALL);
890     }
891   }
892 }
893
894 /**
895  * Lookup network struct by type
896  *
897  * @param s the solver handle
898  * @param type the network type
899  * @return the network struct
900  */
901 static struct Network *
902 get_network (struct GAS_PROPORTIONAL_Handle *s, uint32_t type)
903 {
904   int c;
905   for (c = 0; c < s->network_count; c++)
906   {
907     if (s->network_entries[c].type == type)
908       return &s->network_entries[c];
909   }
910   return NULL ;
911 }
912
913 /**
914  * Hashmap Iterator to find current active address for peer
915  *
916  * @param cls last active address
917  * @param key peer's key
918  * @param value address to check
919  * @return #GNUNET_NO on double active address else #GNUNET_YES;
920  */
921 static int
922 get_active_address_it (void *cls,
923                        const struct GNUNET_PeerIdentity *key,
924                        void *value)
925 {
926   struct ATS_Address **dest = cls;
927   struct ATS_Address *aa = (struct ATS_Address *) value;
928
929   if (GNUNET_YES == aa->active)
930   {
931
932     if (NULL != (*dest))
933     {
934       /* should never happen */
935       LOG(GNUNET_ERROR_TYPE_ERROR, "Multiple active addresses for peer `%s'\n",
936           GNUNET_i2s (&aa->peer));
937       GNUNET_break(0);
938       return GNUNET_NO;
939     }
940     (*dest) = aa;
941   }
942   return GNUNET_OK;
943 }
944
945 /**
946  * Find current active address for peer
947  *
948  * @param solver the solver handle
949  * @param addresses the address set
950  * @param peer the peer
951  * @return active address or NULL
952  */
953 static struct ATS_Address *
954 get_active_address (void *solver,
955                     const struct GNUNET_CONTAINER_MultiPeerMap * addresses,
956                     const struct GNUNET_PeerIdentity *peer)
957 {
958   struct ATS_Address * dest = NULL;
959
960   GNUNET_CONTAINER_multipeermap_get_multiple (addresses, peer,
961                                               &get_active_address_it, &dest);
962   return dest;
963 }
964
965
966 static void
967 addresse_increment (struct GAS_PROPORTIONAL_Handle *s, struct Network *net,
968     int total, int active)
969 {
970   if (GNUNET_YES == total)
971   {
972     s->total_addresses++;
973     net->total_addresses++;
974     GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
975     GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
976   }
977   if (GNUNET_YES == active)
978   {
979     net->active_addresses++;
980     s->active_addresses++;
981     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1,
982         GNUNET_NO);
983     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
984   }
985
986 }
987
988
989 static int
990 addresse_decrement (struct GAS_PROPORTIONAL_Handle *s, struct Network *net,
991     int total, int active)
992 {
993   int res = GNUNET_OK;
994   if (GNUNET_YES == total)
995   {
996     if (s->total_addresses < 1)
997     {
998       GNUNET_break(0);
999       res = GNUNET_SYSERR;
1000     }
1001     else
1002     {
1003       s->total_addresses--;
1004       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
1005           GNUNET_NO);
1006     }
1007     if (net->total_addresses < 1)
1008     {
1009       GNUNET_break(0);
1010       res = GNUNET_SYSERR;
1011     }
1012     else
1013     {
1014       net->total_addresses--;
1015       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
1016     }
1017   }
1018
1019   if (GNUNET_YES == active)
1020   {
1021     if (net->active_addresses < 1)
1022     {
1023       GNUNET_break(0);
1024       res = GNUNET_SYSERR;
1025     }
1026     else
1027     {
1028       net->active_addresses--;
1029       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
1030     }
1031     if (s->active_addresses < 1)
1032     {
1033       GNUNET_break(0);
1034       res = GNUNET_SYSERR;
1035     }
1036     else
1037     {
1038       s->active_addresses--;
1039       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1,
1040           GNUNET_NO);
1041     }
1042   }
1043   return res;
1044 }
1045
1046 /**
1047  *  Solver API functions
1048  *  ---------------------------
1049  */
1050
1051 /**
1052  * Changes the preferences for a peer in the problem
1053  *
1054  * @param solver the solver handle
1055  * @param peer the peer to change the preference for
1056  * @param kind the kind to change the preference
1057  * @param pref_rel the normalized preference value for this kind over all clients
1058  */
1059 void
1060 GAS_proportional_address_change_preference (void *solver,
1061                                             const struct GNUNET_PeerIdentity *peer,
1062                                             enum GNUNET_ATS_PreferenceKind kind,
1063                                             double pref_rel)
1064 {
1065   struct GAS_PROPORTIONAL_Handle *s = solver;
1066   GNUNET_assert(NULL != solver);
1067   GNUNET_assert(NULL != peer);
1068
1069   distribute_bandwidth_in_network (s, NULL, NULL);
1070 }
1071
1072
1073 /**
1074  * Get application feedback for a peer
1075  *
1076  * @param solver the solver handle
1077  * @param application the application
1078  * @param peer the peer to change the preference for
1079  * @param scope the time interval for this feedback: [now - scope .. now]
1080  * @param kind the kind to change the preference
1081  * @param score the score
1082  */
1083 void
1084 GAS_proportional_address_preference_feedback (void *solver, void *application,
1085     const struct GNUNET_PeerIdentity *peer,
1086     const struct GNUNET_TIME_Relative scope,
1087     enum GNUNET_ATS_PreferenceKind kind, double score)
1088 {
1089   struct GAS_PROPORTIONAL_Handle *s = solver;
1090   GNUNET_assert(NULL != solver);
1091   GNUNET_assert(NULL != peer);
1092
1093   GNUNET_assert(NULL != s);
1094   GNUNET_break(0);
1095 }
1096
1097 /**
1098  * Get the preferred address for a specific peer
1099  *
1100  * @param solver the solver handle
1101  * @param peer the identity of the peer
1102  */
1103 const struct ATS_Address *
1104 GAS_proportional_get_preferred_address (void *solver,
1105     const struct GNUNET_PeerIdentity *peer)
1106 {
1107   struct GAS_PROPORTIONAL_Handle *s = solver;
1108   struct Network *net_prev;
1109   struct Network *net_cur;
1110   struct ATS_Address *prev;
1111   struct FindBestAddressCtx fba_ctx;
1112   struct AddressSolverInformation *asi;
1113   struct AddressSolverInformation *asi_prev;
1114
1115   GNUNET_assert(s != NULL);
1116   GNUNET_assert(peer != NULL);
1117
1118   /* Add to list of pending requests */
1119   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (s->requests,
1120                                                            peer))
1121   {
1122     GNUNET_assert (GNUNET_OK ==
1123                    GNUNET_CONTAINER_multipeermap_put (s->requests,
1124                                                       peer, NULL,
1125                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1126   }
1127
1128   /* Get address with: stick to current address, lower distance, lower latency */
1129   fba_ctx.s = s;
1130   fba_ctx.best = NULL;
1131
1132   GNUNET_CONTAINER_multipeermap_get_multiple (s->addresses, peer,
1133                                               &find_best_address_it, &fba_ctx);
1134   if (NULL == fba_ctx.best)
1135   {
1136     LOG(GNUNET_ERROR_TYPE_INFO, "Cannot suggest address for peer `%s'\n",
1137         GNUNET_i2s (peer));
1138     return NULL ;
1139   }
1140
1141   LOG(GNUNET_ERROR_TYPE_INFO, "Suggesting %s address %p for peer `%s'\n",
1142       (GNUNET_NO == fba_ctx.best->active) ? "inactive" : "active", fba_ctx.best,
1143       GNUNET_i2s (peer));
1144   asi = fba_ctx.best->solver_information;
1145   net_cur = asi->network ;
1146   if (NULL == fba_ctx.best)
1147   {
1148     LOG(GNUNET_ERROR_TYPE_ERROR,
1149         "Trying to suggesting unknown address peer `%s'\n", GNUNET_i2s (peer));
1150     GNUNET_break(0);
1151     return NULL ;
1152   }
1153   if (GNUNET_YES == fba_ctx.best->active)
1154   {
1155     /* This address was selected previously, so no need to update quotas */
1156     return fba_ctx.best;
1157   }
1158
1159   /* This address was not active, so we have to:
1160    *
1161    * - mark previous active address as not active
1162    * - update quota for previous address network
1163    * - update quota for this address network
1164    */
1165   prev = get_active_address (s, s->addresses, peer);
1166   if (NULL != prev)
1167   {
1168     asi_prev = prev->solver_information;
1169     net_prev = (struct Network *) asi_prev->network;
1170     prev->active = GNUNET_NO; /* No active any longer */
1171     prev->assigned_bw_in = BANDWIDTH_ZERO; /* no bandwidth assigned */
1172     prev->assigned_bw_out = BANDWIDTH_ZERO; /* no bandwidth assigned */
1173     if (GNUNET_SYSERR == addresse_decrement (s, net_prev, GNUNET_NO, GNUNET_YES))
1174       GNUNET_break(0);
1175     distribute_bandwidth_in_network (s, net_prev, NULL);
1176   }
1177
1178   if (GNUNET_NO == (is_bandwidth_available_in_network (net_cur)))
1179   {
1180     GNUNET_break(0); /* This should never happen*/
1181     return NULL ;
1182   }
1183
1184   fba_ctx.best->active = GNUNET_YES;
1185   addresse_increment (s, net_cur, GNUNET_NO, GNUNET_YES);
1186   distribute_bandwidth_in_network (s, net_cur, fba_ctx.best);
1187   return fba_ctx.best;
1188 }
1189
1190 /**
1191  * Stop notifying about address and bandwidth changes for this peer
1192  *
1193  * @param solver the solver handle
1194  * @param peer the peer
1195  */
1196 void
1197 GAS_proportional_stop_get_preferred_address (void *solver,
1198     const struct GNUNET_PeerIdentity *peer)
1199 {
1200   struct GAS_PROPORTIONAL_Handle *s = solver;
1201   struct ATS_Address *cur;
1202   struct AddressSolverInformation *asi;
1203   struct Network *cur_net;
1204
1205   if (GNUNET_YES
1206       == GNUNET_CONTAINER_multipeermap_contains (s->requests,
1207                                                  peer))
1208     GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove (s->requests, peer,
1209                                           NULL));
1210
1211   cur = get_active_address (s,
1212                             s->addresses, peer);
1213   if (NULL != cur)
1214   {
1215     /* Disabling current address */
1216     asi = cur->solver_information;
1217     cur_net = asi->network ;
1218     cur->active = GNUNET_NO; /* No active any longer */
1219     cur->assigned_bw_in = BANDWIDTH_ZERO; /* no bandwidth assigned */
1220     cur->assigned_bw_out = BANDWIDTH_ZERO; /* no bandwidth assigned */
1221     if (GNUNET_SYSERR == addresse_decrement (s, cur_net, GNUNET_NO, GNUNET_YES))
1222       GNUNET_break(0);
1223     distribute_bandwidth_in_network (s, cur_net, NULL );
1224   }
1225   return;
1226 }
1227
1228 /**
1229  * Remove an address from the solver
1230  *
1231  * @param solver the solver handle
1232  * @param address the address to remove
1233  * @param session_only delete only session not whole address
1234  */
1235 void
1236 GAS_proportional_address_delete (void *solver, struct ATS_Address *address,
1237     int session_only)
1238 {
1239   struct GAS_PROPORTIONAL_Handle *s = solver;
1240   struct Network *net;
1241   struct AddressWrapper *aw;
1242   struct AddressSolverInformation *asi;
1243   const struct ATS_Address *new_address;
1244
1245
1246   /* Remove an adress completely, we have to:
1247    * - Remove from specific network
1248    * - Decrease number of total addresses
1249    * - If active:
1250    *   - decrease number of active addreses
1251    *   - update quotas
1252    */
1253   asi = address->solver_information;
1254   net = asi->network;
1255
1256   if (GNUNET_NO == session_only)
1257   {
1258     LOG(GNUNET_ERROR_TYPE_INFO,
1259         "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1260         (GNUNET_NO == address->active) ? "inactive" : "active", address,
1261         GNUNET_i2s (&address->peer), net->desc, net->total_addresses,
1262         net->active_addresses);
1263
1264     /* Remove address */
1265     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
1266     for (aw = net->head; NULL != aw; aw = aw->next)
1267     {
1268       if (aw->addr == address)
1269         break;
1270     }
1271     if (NULL == aw)
1272     {
1273       GNUNET_break(0);
1274       return;
1275     }
1276     GNUNET_CONTAINER_DLL_remove(net->head, net->tail, aw);
1277     GNUNET_free(aw);
1278   }
1279   else
1280   {
1281     /* Remove session only: remove if active and update */
1282     LOG(GNUNET_ERROR_TYPE_INFO,
1283         "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1284         (GNUNET_NO == address->active) ? "inactive" : "active", address,
1285         GNUNET_i2s (&address->peer), net->desc, net->total_addresses,
1286         net->active_addresses);
1287   }
1288
1289   if (GNUNET_YES == address->active)
1290   {
1291     /* Address was active, remove from network and update quotas*/
1292     address->active = GNUNET_NO;
1293     address->assigned_bw_in = BANDWIDTH_ZERO;
1294     address->assigned_bw_out = BANDWIDTH_ZERO;
1295
1296     if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1297       GNUNET_break(0);
1298     distribute_bandwidth_in_network (s, net, NULL);
1299     if (NULL == (new_address = GAS_proportional_get_preferred_address (s, &address->peer)))
1300     {
1301       /* No alternative address found, disconnect peer */
1302       s->bw_changed (s->bw_changed_cls, address);
1303     }
1304     else
1305     {
1306       s->bw_changed (s->bw_changed_cls, (struct ATS_Address *) new_address);
1307     }
1308   }
1309   LOG(GNUNET_ERROR_TYPE_INFO,
1310       "After deleting address now total %u and active %u addresses in network `%s'\n",
1311       net->total_addresses, net->active_addresses, net->desc);
1312
1313 }
1314
1315 /**
1316  * Start a bulk operation
1317  *
1318  * @param solver the solver
1319  */
1320 void
1321 GAS_proportional_bulk_start (void *solver)
1322 {
1323   LOG(GNUNET_ERROR_TYPE_DEBUG, "Locking solver for bulk operation ...\n");
1324   struct GAS_PROPORTIONAL_Handle *s = (struct GAS_PROPORTIONAL_Handle *) solver;
1325
1326   GNUNET_assert(NULL != solver);
1327   s->bulk_lock++;
1328 }
1329
1330
1331 /**
1332  * Bulk operation done
1333  */
1334 void
1335 GAS_proportional_bulk_stop (void *solver)
1336 {
1337   LOG(GNUNET_ERROR_TYPE_DEBUG, "Unlocking solver from bulk operation ...\n");
1338
1339   struct GAS_PROPORTIONAL_Handle *s = (struct GAS_PROPORTIONAL_Handle *) solver;
1340   GNUNET_assert(NULL != solver);
1341
1342   if (s->bulk_lock < 1)
1343   {
1344     GNUNET_break(0);
1345     return;
1346   }
1347   s->bulk_lock--;
1348   if ((0 == s->bulk_lock) && (0 < s->bulk_requests))
1349   {
1350     LOG(GNUNET_ERROR_TYPE_DEBUG, "No lock pending, recalculating\n");
1351     distribute_bandwidth_in_network (s, NULL, NULL);
1352     s->bulk_requests = 0;
1353   }
1354 }
1355
1356
1357 /**
1358  * Add a new single address to a network
1359  *
1360  * @param solver the solver Handle
1361  * @param address the address to add
1362  * @param network network type of this address
1363  */
1364 void
1365 GAS_proportional_address_add (void *solver, struct ATS_Address *address,
1366     uint32_t network);
1367
1368 /**
1369  * Transport properties for this address have changed
1370  *
1371  * @param solver solver handle
1372  * @param address the address
1373  * @param type the ATSI type in HBO
1374  * @param abs_value the absolute value of the property
1375  * @param rel_value the normalized value
1376  */
1377 void
1378 GAS_proportional_address_property_changed (void *solver,
1379     struct ATS_Address *address, uint32_t type, uint32_t abs_value,
1380     double rel_value)
1381 {
1382   struct GAS_PROPORTIONAL_Handle *s;
1383   struct Network *n;
1384   struct AddressSolverInformation *asi;
1385
1386   GNUNET_assert(NULL != solver);
1387   GNUNET_assert(NULL != address);
1388
1389   s = (struct GAS_PROPORTIONAL_Handle *) solver;
1390   asi = address->solver_information;
1391   n = asi->network;
1392
1393   if (NULL == n)
1394   {
1395     GNUNET_break(0);
1396     return;
1397   }
1398
1399   LOG(GNUNET_ERROR_TYPE_DEBUG,
1400       "Property `%s' for peer `%s' address %p changed to %.2f \n",
1401       GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1402       address, rel_value);
1403   switch (type)
1404   {
1405   case GNUNET_ATS_UTILIZATION_OUT:
1406   case GNUNET_ATS_UTILIZATION_IN:
1407   case GNUNET_ATS_UTILIZATION_PAYLOAD_IN:
1408   case GNUNET_ATS_UTILIZATION_PAYLOAD_OUT:
1409   case GNUNET_ATS_QUALITY_NET_DELAY:
1410   case GNUNET_ATS_QUALITY_NET_DISTANCE:
1411   case GNUNET_ATS_COST_WAN:
1412   case GNUNET_ATS_COST_LAN:
1413   case GNUNET_ATS_COST_WLAN:
1414     distribute_bandwidth_in_network (s, n, NULL);
1415     break;
1416   }
1417 }
1418
1419 /**
1420  * Transport session for this address has changed
1421  *
1422  * NOTE: values in addresses are already updated
1423  *
1424  * @param solver solver handle
1425  * @param address the address
1426  * @param cur_session the current session
1427  * @param new_session the new session
1428  */
1429 void
1430 GAS_proportional_address_session_changed (void *solver,
1431     struct ATS_Address *address, uint32_t cur_session, uint32_t new_session)
1432 {
1433   if (cur_session != new_session)
1434   {
1435     LOG(GNUNET_ERROR_TYPE_DEBUG, "Session changed from %u to %u\n", cur_session,
1436         new_session);
1437   }
1438 }
1439
1440 /**
1441  * Usage for this address has changed
1442  *
1443  * NOTE: values in addresses are already updated
1444  *
1445  * @param solver solver handle
1446  * @param address the address
1447  * @param in_use usage state
1448  */
1449 void
1450 GAS_proportional_address_inuse_changed (void *solver,
1451     struct ATS_Address *address, int in_use)
1452 {
1453   LOG(GNUNET_ERROR_TYPE_DEBUG, "Usage changed to %s\n",
1454       (GNUNET_YES == in_use) ? "USED" : "UNUSED");
1455 }
1456
1457 /**
1458  * Network scope for this address has changed
1459  *
1460  * NOTE: values in addresses are already updated
1461  *
1462  * @param solver solver handle
1463  * @param address the address
1464  * @param current_network the current network
1465  * @param new_network the new network
1466  */
1467 void
1468 GAS_proportional_address_change_network (void *solver,
1469     struct ATS_Address *address, uint32_t current_network, uint32_t new_network)
1470 {
1471   struct GAS_PROPORTIONAL_Handle *s = (struct GAS_PROPORTIONAL_Handle *) solver;
1472   struct AddressSolverInformation *asi;
1473   int save_active = GNUNET_NO;
1474
1475   struct Network *new_net = NULL;
1476
1477   if (current_network == new_network)
1478   {
1479     GNUNET_break(0);
1480     return;
1481   }
1482
1483   /* Network changed */
1484   LOG(GNUNET_ERROR_TYPE_DEBUG,
1485       "Network type changed, moving %s address from `%s' to `%s'\n",
1486       (GNUNET_YES == address->active) ? "active" : "inactive",
1487       GNUNET_ATS_print_network_type (current_network),
1488       GNUNET_ATS_print_network_type (new_network));
1489
1490   save_active = address->active;
1491
1492   /* Disable and assign no bandwidth */
1493   address->active = GNUNET_NO;
1494   address->assigned_bw_in = BANDWIDTH_ZERO; /* no bandwidth assigned */
1495   address->assigned_bw_out = BANDWIDTH_ZERO; /* no bandwidth assigned */
1496
1497   /* Remove from old network */
1498   GAS_proportional_address_delete (solver, address, GNUNET_NO);
1499
1500   /* Set new network type */
1501   if (NULL == (new_net = get_network (solver, new_network)))
1502   {
1503     /* Address changed to invalid network... */
1504     LOG(GNUNET_ERROR_TYPE_ERROR,
1505         _("Invalid network type `%u' `%s': Disconnect!\n"), new_network,
1506         GNUNET_ATS_print_network_type (new_network));
1507
1508     /* Find new address to suggest since no bandwidth in network*/
1509     if (NULL == GAS_proportional_get_preferred_address (s, &address->peer))
1510     {
1511       /* No alternative address found, disconnect peer */
1512       s->bw_changed (s->bw_changed_cls, address);
1513     }
1514     return;
1515   }
1516
1517   /* Add to new network and update*/
1518   asi = address->solver_information;
1519   asi->network = new_net;
1520   GAS_proportional_address_add (solver, address, new_network);
1521   if (GNUNET_YES == save_active)
1522   {
1523     /* check if bandwidth available in new network */
1524     if (GNUNET_YES == (is_bandwidth_available_in_network (new_net)))
1525     {
1526       /* Assign bandwidth to updated address */
1527       address->active = GNUNET_YES;
1528       addresse_increment (s, new_net, GNUNET_NO, GNUNET_YES);
1529       distribute_bandwidth_in_network (solver, new_net, NULL);
1530     }
1531     else
1532     {
1533       LOG(GNUNET_ERROR_TYPE_DEBUG,
1534           "Not enough bandwidth in new network, suggesting alternative address ..\n");
1535       /* Find new address to suggest since no bandwidth in network*/
1536       if (NULL == GAS_proportional_get_preferred_address (s, &address->peer))
1537       {
1538         /* No alternative address found, disconnect peer */
1539         s->bw_changed (s->bw_changed_cls, address);
1540       }
1541     }
1542   }
1543 }
1544
1545 /**
1546  * Add a new single address to a network
1547  *
1548  * @param solver the solver Handle
1549  * @param address the address to add
1550  * @param network network type of this address
1551  */
1552 void
1553 GAS_proportional_address_add (void *solver, struct ATS_Address *address,
1554     uint32_t network)
1555 {
1556   struct GAS_PROPORTIONAL_Handle *s = solver;
1557   struct Network *net = NULL;
1558   struct AddressWrapper *aw = NULL;
1559   struct AddressSolverInformation *asi;
1560
1561   GNUNET_assert(NULL != s);
1562   net = get_network (s, network);
1563   if (NULL == net)
1564   {
1565     GNUNET_break(0);
1566     return;
1567   }
1568
1569   aw = GNUNET_malloc (sizeof (struct AddressWrapper));
1570   aw->addr = address;
1571   GNUNET_CONTAINER_DLL_insert(net->head, net->tail, aw);
1572   addresse_increment (s, net, GNUNET_YES, GNUNET_NO);
1573
1574   asi = GNUNET_malloc (sizeof (struct AddressSolverInformation));
1575   asi->network = net;
1576   asi->calculated_quota_in_NBO = 0;
1577   asi->calculated_quota_out_NBO = 0;
1578   aw->addr->solver_information = asi;
1579
1580   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (s->requests, &address->peer))
1581   {
1582     if (NULL == get_active_address (s, s->addresses, &address->peer))
1583     {
1584       if (NULL != GAS_proportional_get_preferred_address (s, &address->peer))
1585           s->bw_changed (s->bw_changed_cls, (struct ATS_Address *) address);
1586     }
1587   }
1588
1589   LOG(GNUNET_ERROR_TYPE_INFO,
1590       "Adding new address %p for peer `%s', now total %u and active %u addresses in network `%s'\n",
1591       address, GNUNET_i2s(&address->peer), net->total_addresses, net->active_addresses, net->desc);
1592 }
1593
1594
1595 /* end of gnunet-service-ats-solver_proportional.c */