rename function
[oweals/gnunet.git] / src / ats / gnunet-service-ats-solver_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/gnunet-service-ats-solver_proportional.c
23  * @brief ATS proportional solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet-service-ats_addresses.h"
30 #include "gnunet_statistics_service.h"
31
32 #define LOG(kind,...) GNUNET_log_from (kind, "ats-proportional",__VA_ARGS__)
33
34 /**
35  *
36  * NOTE: Do not change this documentation. This documentation is based
37  * on gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
38  * use build_txt.sh to generate plaintext output
39  *
40  * ATS addresses : simplistic solver
41  *
42  *    The simplistic solver ("simplistic") distributes the available
43  *    bandwidth fair over all the addresses influenced by the
44  *    preference values. For each available network type an in- and
45  *    outbound quota is configured and the bandwidth available in
46  *    these networks is distributed over the addresses.  The solver
47  *    first assigns every addresses the minimum amount of bandwidth
48  *    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT and then distributes the
49  *    remaining bandwidth available according to the preference
50  *    values. For each peer only a single address gets bandwidth
51  *    assigned and only one address marked as active.  The most
52  *    important functionality for the solver is implemented in: *
53  *    find_address_it is an hashmap iterator returning the prefered
54  *    address for an peer * update_quota_per_network distributes
55  *    available bandwidth for a network over active addresses
56  *
57  *    Changes to addresses automatically have an impact on the the
58  *    bandwidth assigned to other addresses in the same network since
59  *    the solver distributes the remaining bandwidth over the
60  *    addresses in the network.  When changes to the addresses occur,
61  *    the solver first performs the changes, like adding or deleting
62  *    addresses, and then updates bandwidth assignment for the
63  *    affected network. Bandwidth assignment is only recalculated on
64  *    demand when an address is requested by a client for a peer or
65  *    when the addresses available have changed or an address changed
66  *    the network it is located in. When the bandwidth assignment has
67  *    changed the callback is called with the new bandwidth
68  *    assignments. The bandwidth distribution for a network is
69  *    recalculated due to: * address suggestion requests * address
70  *    deletions * address switching networks during address update *
71  *    preference changes
72  *
73  *     3.1 Data structures used
74  *
75  *    For each ATS network (e.g. WAN, LAN, loopback) a struct Network
76  *    is used to specify network related information as total adresses
77  *    and active addresses in this network and the configured in- and
78  *    outbound quota. Each network also contains a list of addresses
79  *    added to the solver located in this network. The simplistic
80  *    solver uses the addresses' solver_information field to store the
81  *    simplistic network it belongs to for each address.
82  *
83  *     3.2 Initializing
84  *
85  *    When the simplistic solver is initialized the solver creates a
86  *    new solver handle and initializes the network structures with
87  *    the quotas passed from addresses and returns the handle solver.
88  *
89  *     3.3 Adding an address
90  *
91  *    When a new address is added to the solver using s_add, a lookup
92  *    for the network for this address is done and the address is
93  *    enqueued in in the linked list of the network.
94  *
95  *     3.4 Updating an address
96  *
97  *    The main purpose of address updates is to update the ATS
98  *    information for addresse selection. Important for the simplistic
99  *    solver is when an address switches network it is located
100  *    in. This is common because addresses added by transport's
101  *    validation mechanism are commonly located in
102  *    GNUNET_ATS_NET_UNSPECIFIED. Addresses in validation are located
103  *    in this network type and only if a connection is successful on
104  *    return of payload data transport switches to the real network
105  *    the address is located in.  When an address changes networks it
106  *    is first of all removed from the old network using the solver
107  *    API function GAS_simplistic_address_delete and the network in
108  *    the address struct is updated. A lookup for the respective new
109  *    simplistic network is done and stored in the addresse's
110  *    solver_information field. Next the address is re-added to the
111  *    solver using the solver API function
112  *    GAS_simplistic_address_add. If the address was marked as in
113  *    active, the solver checks if bandwidth is available in the
114  *    network and if yes sets the address to active and updates the
115  *    bandwidth distribution in this network. If no bandwidth is
116  *    available it sets the bandwidth for this address to 0 and tries
117  *    to suggest an alternative address. If an alternative address was
118  *    found, addresses' callback is called for this address.
119  *
120  *     3.5 Deleting an address
121  *
122  *    When an address is removed from the solver, it removes the
123  *    respective address from the network and if the address was
124  *    marked as active, it updates the bandwidth distribution for this
125  *    network.
126  *
127  *     3.6 Requesting addresses
128  *
129  *    When an address is requested for a peer the solver performs a
130  *    lookup for the peer entry in addresses address hashmap and
131  *    selects the best address.  The selection of the most suitable
132  *    address is done in the find_address_it hashmap iterator
133  *    described in detail in section 3.7. If no address is returned,
134  *    no address can be suggested at the moment. If the address
135  *    returned is marked as active, the solver can return this
136  *    address. If the address is not marked as active, the solver
137  *    checks if another address belongign to this peer is marked as
138  *    active and marks the address as inactive, updates the bandwidth
139  *    for this address to 0, call the bandwidth changed callback for
140  *    this address due to the change and updates quota assignment for
141  *    the addresse's network. the now in-active address is belonging
142  *    to. The solver marks the new address as active and updates the
143  *    bandwidth assignment for this network.
144  *
145  *     3.7 Choosing addresses
146  *
147  *    Choosing the best possible address for suggestion is done by
148  *    iterating over all addresses of a peer stored in addresses'
149  *    hashmap and using the hashmap iterator find_address_it to select
150  *    the best available address.  Several checks are done when an
151  *    address is selected. First if this address is currently blocked
152  *    by addresses from being suggested. An address is blocked for the
153  *    duration of ATS_BLOCKING_DELTA when it is suggested to
154  *    transport. Next it is checked if at least
155  *    GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT bytes bandwidth is available
156  *    in the addresse's network, because suggesting an address without
157  *    bandwidth does not make sense. This also ensures that all active
158  *    addresses in this network get at least the minimum amount of
159  *    bandwidth assigned. In the next step the solver ensures that for
160  *    tcp connections inbound connections are prefered over outbound
161  *    connections. In the next stet the solver ensures that
162  *    connections are prefered in the following order: * connections
163  *    are already established and have bandwidth assigned *
164  *    connections with a shorter distance * connectes have a shorter
165  *    latency
166  *
167  *     3.8 Changing preferences
168  *
169  *     3.9 Shutdown
170  *
171  *    During shutdown all network entries and aging processes are
172  *    destroyed and freed.
173  *
174  *
175  * OLD DOCUMENTATION
176  *
177  * This solver assigns in and outbound bandwidth equally for all
178  * addresses in specific network type (WAN, LAN) based on configured
179  * in and outbound quota for this network.
180  *
181  * The solver is notified by addresses about changes to the addresses
182  * and recalculates the bandwith assigned if required. The solver
183  * notifies addresses by calling the GAS_bandwidth_changed_cb
184  * callback.
185  *
186  * - Initialization
187  *
188  *
189  *
190  *
191  * For each peer only a single is selected and marked as "active" in the address
192  * struct.
193  *
194  * E.g.:
195  *
196  * You have the networks WAN and LAN and quotas
197  * WAN_TOTAL_IN, WAN_TOTAL_OUT
198  * LAN_TOTAL_IN, LAN_TOTAL_OUT
199  *
200  * If you have x addresses in the network segment LAN, the quotas are
201  * QUOTA_PER_ADDRESS = LAN_TOTAL_OUT / x
202  *
203  * Quotas are automatically recalculated and reported back when addresses are
204  * - requested
205  *
206  */
207
208 #define PREF_AGING_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
209 #define PREF_AGING_FACTOR 0.95
210
211 #define DEFAULT_REL_PREFERENCE 1.0
212 #define DEFAULT_ABS_PREFERENCE 0.0
213 #define MIN_UPDATE_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
214
215
216 /**
217  * A handle for the proportional solver
218  */
219 struct GAS_PROPORTIONAL_Handle
220 {
221   /**
222    * Statistics handle
223    */
224
225   struct GNUNET_STATISTICS_Handle *stats;
226
227   /**
228    * Total number of addresses for solver
229    */
230   unsigned int total_addresses;
231
232   /**
233    * Number of active addresses for solver
234    */
235   unsigned int active_addresses;
236
237   /**
238    * Networks array
239    */
240   struct Network *network_entries;
241
242   /**
243    * Number of networks
244    */
245   unsigned int networks;
246
247   /**
248    * Callback
249    */
250   GAS_bandwidth_changed_cb bw_changed;
251
252   /**
253    * Callback cls
254    */
255   void *bw_changed_cls;
256
257   struct GNUNET_CONTAINER_MultiHashMap *prefs;
258
259   struct PreferenceClient *pc_head;
260   struct PreferenceClient *pc_tail;
261 };
262
263
264 /**
265  * Representation of a network
266  */
267 struct Network
268 {
269   /**
270    * ATS network type
271    */
272   unsigned int type;
273
274   /**
275    * Network description
276    */
277   char *desc;
278
279   /**
280    * Total inbound quota
281    *
282    */
283   unsigned long long total_quota_in;
284
285   /**
286    * Total outbound quota
287    *
288    */
289   unsigned long long total_quota_out;
290
291   /**
292    * Number of active addresses for this network
293    */
294   unsigned int active_addresses;
295
296   /**
297    * Number of total addresses for this network
298    */
299   unsigned int total_addresses;
300
301   /**
302    * String for statistics total addresses
303    */
304   char *stat_total;
305
306   /**
307    * String for statistics active addresses
308    */
309   char *stat_active;
310
311   struct AddressWrapper *head;
312   struct AddressWrapper *tail;
313 };
314
315
316 /**
317  * Wrapper for addresses to store them in network's linked list
318  */
319 struct AddressWrapper
320 {
321   /**
322    * Next in DLL
323    */
324   struct AddressWrapper *next;
325
326   /**
327    * Previous in DLL
328    */
329   struct AddressWrapper *prev;
330
331   /**
332    * The address
333    */
334   struct ATS_Address *addr;
335 };
336
337
338 /**
339  * Preference client
340  */
341 struct PreferenceClient
342 {
343   /**
344    * Next in DLL
345    */
346   struct PreferenceClient *prev;
347
348   /**
349    * Next in DLL
350    */
351
352   struct PreferenceClient *next;
353
354   /**
355    * Client handle
356    */
357   void *client;
358
359   /**
360    * Total preference for this peer
361    */
362   double f_total[GNUNET_ATS_PreferenceCount];
363
364   /**
365    * List of peer preferences for this client
366    */
367
368   /**
369    * Head of peer list
370    */
371   struct PreferencePeer *p_head;
372
373   /**
374    * Tail of peer list
375    */
376   struct PreferencePeer *p_tail;
377 };
378
379
380 /**
381  * Preference peer
382  */
383 struct PreferencePeer
384 {
385   /**
386    * Next in DLL
387    */
388   struct PreferencePeer *next;
389
390   /**
391    * Previous in DLL
392    */
393   struct PreferencePeer *prev;
394
395   /**
396    * Client
397    */
398   struct PreferenceClient *client;
399
400   /**
401    * Solver handle
402    */
403   struct GAS_PROPORTIONAL_Handle *s;
404
405   /**
406    * Peer id
407    */
408   struct GNUNET_PeerIdentity id;
409
410   /**
411    * Preference Values
412    */
413   double f[GNUNET_ATS_PreferenceCount];
414
415   /**
416    * Relative Preference Values
417    */
418   double f_rel[GNUNET_ATS_PreferenceCount];
419
420   /**
421    * Relative Total Preference Value
422    */
423   double f_rel_total;
424
425   GNUNET_SCHEDULER_TaskIdentifier aging_task;
426 };
427
428
429 /**
430  *  Important solver functions
431  *  ---------------------------
432  */
433
434 /**
435  * Test if bandwidth is available in this network to add an additional address
436  *
437  * @param net the network type to update
438  * @return GNUNET_YES or GNUNET_NO
439  */
440 static int
441 is_bandwidth_available_in_network (struct Network *net)
442 {
443   unsigned int na = net->active_addresses + 1;
444   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
445   if (((net->total_quota_in / na) > min_bw) &&
446       ((net->total_quota_out / na) > min_bw))
447   {
448     LOG (GNUNET_ERROR_TYPE_DEBUG,
449          "Enough bandwidth available for %u active addresses in network `%s'\n",
450          na,
451          net->desc);
452
453     return GNUNET_YES;
454   }
455     LOG (GNUNET_ERROR_TYPE_DEBUG,
456          "Not enough bandwidth available for %u active addresses in network `%s'\n",
457          na,
458          net->desc);
459   return GNUNET_NO;
460 }
461
462
463 /**
464  * Update bandwidth assigned to peers in this network
465  *
466  * @param s the solver handle
467  * @param net the network type to update
468  * @param address_except address excluded from notification, since we suggest
469  * this address
470  */
471 static void
472 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
473                           struct Network *net,
474                           struct ATS_Address *address_except)
475 {
476   unsigned long long remaining_quota_in = 0;
477   unsigned long long quota_out_used = 0;
478
479   unsigned long long remaining_quota_out = 0;
480   unsigned long long quota_in_used = 0;
481   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
482   double total_prefs; /* Important: has to be double not float due to precision */
483   double cur_pref; /* Important: has to be double not float due to precision */
484   double *t = NULL; /* Important: has to be double not float due to precision */
485
486   unsigned long long assigned_quota_in = 0;
487   unsigned long long assigned_quota_out = 0;
488   struct AddressWrapper *cur;
489
490   LOG (GNUNET_ERROR_TYPE_DEBUG,
491               "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
492               net->desc, net->active_addresses, net->total_quota_in, net->total_quota_in);
493
494   if (net->active_addresses == 0)
495     return; /* no addresses to update */
496
497   /* Idea
498    * Assign every peer in network minimum Bandwidth
499    * Distribute bandwidth left according to preference
500    */
501
502   if ((net->active_addresses * min_bw) > net->total_quota_in)
503   {
504     GNUNET_break (0);
505     return;
506   }
507   if ((net->active_addresses * min_bw) > net->total_quota_out)
508   {
509     GNUNET_break (0);
510     return;
511   }
512
513   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
514   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
515   LOG (GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
516               remaining_quota_in, remaining_quota_out);
517   total_prefs = 0.0;
518   for (cur = net->head; NULL != cur; cur = cur->next)
519   {
520       if (GNUNET_YES == cur->addr->active)
521       {
522         t = GNUNET_CONTAINER_multihashmap_get (s->prefs, &cur->addr->peer.hashPubKey);
523         if (NULL == t)
524                 total_prefs += DEFAULT_REL_PREFERENCE;
525         else
526          {
527                         total_prefs += (*t);
528          }
529       }
530   }
531   for (cur = net->head; NULL != cur; cur = cur->next)
532   {
533      if (GNUNET_YES == cur->addr->active)
534      {
535        cur_pref = 0.0;
536        t = GNUNET_CONTAINER_multihashmap_get (s->prefs, &cur->addr->peer.hashPubKey);
537        if (NULL == t)
538          cur_pref = DEFAULT_REL_PREFERENCE;
539        else
540          cur_pref = (*t);
541        assigned_quota_in = min_bw + ((cur_pref / total_prefs) * remaining_quota_in);
542        assigned_quota_out = min_bw + ((cur_pref / total_prefs) * remaining_quota_out);
543
544        LOG (GNUNET_ERROR_TYPE_DEBUG,
545                    "New quota for peer `%s' with preference (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
546                    GNUNET_i2s (&cur->addr->peer),
547                    cur_pref, total_prefs,
548                    assigned_quota_in, assigned_quota_out);
549      }
550      else
551      {
552        assigned_quota_in = 0;
553        assigned_quota_out = 0;
554      }
555
556      quota_in_used += assigned_quota_in;
557      quota_out_used += assigned_quota_out;
558      /* Prevent overflow due to rounding errors */
559      if (assigned_quota_in > UINT32_MAX)
560        assigned_quota_in = UINT32_MAX;
561      if (assigned_quota_out > UINT32_MAX)
562        assigned_quota_out = UINT32_MAX;
563
564      /* Compare to current bandwidth assigned */
565      if ((assigned_quota_in != ntohl(cur->addr->assigned_bw_in.value__)) ||
566          (assigned_quota_out != ntohl(cur->addr->assigned_bw_out.value__)))
567      {
568        cur->addr->assigned_bw_in.value__ = htonl (assigned_quota_in);
569        cur->addr->assigned_bw_out.value__ = htonl (assigned_quota_out);
570        /* Notify on change */
571        if ((GNUNET_YES == cur->addr->active) && (cur->addr != address_except))
572          s->bw_changed (s->bw_changed_cls, cur->addr);
573      }
574
575   }
576   LOG (GNUNET_ERROR_TYPE_DEBUG,
577                           "Total bandwidth assigned is (in/out): %llu /%llu\n",
578                           quota_in_used,
579                           quota_out_used);
580   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
581   {
582       LOG (GNUNET_ERROR_TYPE_ERROR,
583                             "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
584                             net->active_addresses,
585                             quota_out_used,
586                             net->total_quota_out);
587   }
588   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
589   {
590       LOG (GNUNET_ERROR_TYPE_ERROR,
591                             "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
592                             net->active_addresses,
593                             quota_in_used,
594                             net->total_quota_in);
595   }
596 }
597
598
599 /**
600  * Extract an ATS performance info from an address
601  *
602  * @param address the address
603  * @param type the type to extract in HBO
604  * @return the value in HBO or GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
605  */
606 static int
607 get_performance_info (struct ATS_Address *address, uint32_t type);
608
609 /**
610  * Find a "good" address to use for a peer by iterating over the addresses for this peer.
611  * If we already have an existing address, we stick to it.
612  * Otherwise, we pick by lowest distance and then by lowest latency.
613  *
614  * @param cls the 'struct ATS_Address**' where we store the result
615  * @param key unused
616  * @param value another 'struct ATS_Address*' to consider using
617  * @return GNUNET_OK (continue to iterate)
618  */
619 static int
620 find_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
621 {
622   struct ATS_Address **previous_p = cls;
623   struct ATS_Address *current = (struct ATS_Address *) value;
624   struct ATS_Address *previous = *previous_p;
625   struct GNUNET_TIME_Absolute now;
626   struct Network *net = (struct Network *) current->solver_information;
627   uint32_t p_distance_cur;
628   uint32_t p_distance_prev;
629   uint32_t p_delay_cur;
630   uint32_t p_delay_prev;
631
632   now = GNUNET_TIME_absolute_get();
633
634   if (current->blocked_until.abs_value == GNUNET_TIME_absolute_max (now, current->blocked_until).abs_value)
635   {
636     /* This address is blocked for suggestion */
637     LOG (GNUNET_ERROR_TYPE_DEBUG,
638                 "Address %p blocked for suggestion for %llu ms \n",
639                 current,
640                 GNUNET_TIME_absolute_get_difference(now, current->blocked_until).rel_value);
641     return GNUNET_OK;
642   }
643
644   if (GNUNET_NO == is_bandwidth_available_in_network (net))
645     return GNUNET_OK; /* There's no bandwidth available in this network */
646
647   if (NULL != previous)
648   {
649         GNUNET_assert (NULL != previous->plugin);
650         GNUNET_assert (NULL != current->plugin);
651     if (0 == strcmp (previous->plugin, current->plugin))
652     {
653       if ((0 != previous->addr_len) &&
654           (0 == current->addr_len))
655       {
656         /* saved address was an outbound address, but we have an inbound address */
657         *previous_p = current;
658         return GNUNET_OK;
659       }
660       if (0 == previous->addr_len)
661       {
662         /* saved address was an inbound address, so do not overwrite */
663         return GNUNET_OK;
664       }
665     }
666   }
667
668   if (NULL == previous)
669   {
670     *previous_p = current;
671     return GNUNET_OK;
672   }
673   if ((ntohl (previous->assigned_bw_in.value__) == 0) &&
674       (ntohl (current->assigned_bw_in.value__) > 0))
675   {
676     /* stick to existing connection */
677     *previous_p = current;
678     return GNUNET_OK;
679   }
680
681   p_distance_prev = get_performance_info (previous, GNUNET_ATS_QUALITY_NET_DISTANCE);
682   p_distance_cur = get_performance_info (current, GNUNET_ATS_QUALITY_NET_DISTANCE);
683   if ((p_distance_prev != GNUNET_ATS_VALUE_UNDEFINED) && (p_distance_cur != GNUNET_ATS_VALUE_UNDEFINED) &&
684                 (p_distance_prev > p_distance_cur))
685   {
686     /* user shorter distance */
687     *previous_p = current;
688     return GNUNET_OK;
689   }
690
691   p_delay_prev = get_performance_info (previous, GNUNET_ATS_QUALITY_NET_DELAY);
692   p_delay_cur = get_performance_info (current, GNUNET_ATS_QUALITY_NET_DELAY);
693   if ((p_delay_prev != GNUNET_ATS_VALUE_UNDEFINED) && (p_delay_cur != GNUNET_ATS_VALUE_UNDEFINED) &&
694                 (p_delay_prev > p_delay_cur))
695   {
696     /* user lower latency */
697     *previous_p = current;
698     return GNUNET_OK;
699   }
700
701   /* don't care */
702   return GNUNET_OK;
703 }
704
705 /**
706  *  Helper functions
707  *  ---------------------------
708  */
709
710 /**
711  * Update bandwidth assignment for all networks
712  *
713  * @param s the solver handle
714  */
715 static void
716 distribute_bandwidth_in_all_networks (struct GAS_PROPORTIONAL_Handle *s)
717 {
718         int i;
719         for (i = 0; i < s->networks; i++)
720                 distribute_bandwidth_in_network (s, &s->network_entries[i], NULL);
721
722 }
723
724
725 /**
726  * Lookup network struct by type
727  *
728  * @param s the solver handle
729  * @param type the network type
730  * @return the network struct
731  */
732 static struct Network *
733 get_network (struct GAS_PROPORTIONAL_Handle *s, uint32_t type)
734 {
735   int c;
736   for (c = 0 ; c < s->networks; c++)
737   {
738       if (s->network_entries[c].type == type)
739         return &s->network_entries[c];
740   }
741   return NULL;
742 }
743
744
745 /**
746  * Hashmap Iterator to find current active address for peer
747  *
748  * @param cls last active address
749  * @param key peer's key
750  * @param value address to check
751  * @return GNUNET_NO on double active address else GNUNET_YES
752  */
753 static int
754 get_active_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
755 {
756   struct ATS_Address * dest = (struct ATS_Address *) (*(struct ATS_Address **)cls);
757   struct ATS_Address * aa = (struct ATS_Address *) value;
758
759   if (GNUNET_YES == aa->active)
760   {
761       if (dest != NULL)
762       {
763           /* should never happen */
764           LOG (GNUNET_ERROR_TYPE_ERROR, "Multiple active addresses for peer `%s'\n", GNUNET_i2s (&aa->peer));
765           GNUNET_break (0);
766           return GNUNET_NO;
767       }
768       dest = aa;
769   }
770   return GNUNET_OK;
771 }
772
773
774 /**
775  * Find current active address for peer
776  *
777  * @param solver the solver handle
778  * @param addresses the address set
779  * @param peer the peer
780  * @return active address or NULL
781  */
782 static struct ATS_Address *
783 get_active_address (void *solver,
784                      struct GNUNET_CONTAINER_MultiHashMap * addresses,
785                      const struct GNUNET_PeerIdentity *peer)
786 {
787   struct ATS_Address * dest = NULL;
788
789   GNUNET_CONTAINER_multihashmap_get_multiple(addresses,
790        &peer->hashPubKey,
791        &get_active_address_it, &dest);
792   return dest;
793 }
794
795
796 static int
797 free_pref (void *cls,
798            const struct GNUNET_HashCode * key,
799            void *value)
800 {
801   float *v = value;
802   GNUNET_free (v);
803   return GNUNET_OK;
804 }
805
806
807 static void
808 addresse_increment (struct GAS_PROPORTIONAL_Handle *s,
809                                 struct Network *net,
810                                 int total,
811                                 int active)
812 {
813   if (GNUNET_YES == total)
814   {
815       s->total_addresses ++;
816       net->total_addresses ++;
817       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
818       GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
819   }
820   if (GNUNET_YES == active)
821   {
822     net->active_addresses ++;
823     s->active_addresses ++;
824     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1, GNUNET_NO);
825     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
826   }
827
828 }
829
830
831 static int
832 addresse_decrement (struct GAS_PROPORTIONAL_Handle *s,
833                     struct Network *net,
834                     int total,
835                     int active)
836 {
837   int res = GNUNET_OK;
838   if (GNUNET_YES == total)
839   {
840     if (s->total_addresses < 1)
841     {
842       GNUNET_break (0);
843       res = GNUNET_SYSERR;
844     }
845     else
846     {
847       s->total_addresses --;
848       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
849     }
850     if (net->total_addresses < 1)
851     {
852       GNUNET_break (0);
853       res = GNUNET_SYSERR;
854     }
855     else
856     {
857       net->total_addresses --;
858       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
859     }
860   }
861
862   if (GNUNET_YES == active)
863   {
864     if (net->active_addresses < 1)
865     {
866       GNUNET_break (0);
867       res = GNUNET_SYSERR;
868     }
869     else
870     {
871       net->active_addresses --;
872       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
873     }
874     if (s->active_addresses < 1)
875     {
876       GNUNET_break (0);
877       res = GNUNET_SYSERR;
878     }
879     else
880     {
881       s->active_addresses --;
882       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
883     }
884   }
885   return res;
886 }
887
888
889 /**
890  * Extract an ATS performance info from an address
891  *
892  * @param address the address
893  * @param type the type to extract in HBO
894  * @return the value in HBO or GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
895  */
896 static int
897 get_performance_info (struct ATS_Address *address, uint32_t type)
898 {
899         int c1;
900         GNUNET_assert (NULL != address);
901
902         if ((NULL == address->atsi) || (0 == address->atsi_count))
903                         return GNUNET_ATS_VALUE_UNDEFINED;
904
905         for (c1 = 0; c1 < address->atsi_count; c1++)
906         {
907                         if (ntohl(address->atsi[c1].type) == type)
908                                 return ntohl(address->atsi[c1].value);
909         }
910         return GNUNET_ATS_VALUE_UNDEFINED;
911 }
912
913
914
915 /**
916  *  Preference calculation
917  *  ---------------------------
918  */
919
920 static void
921 recalculate_preferences (struct PreferencePeer *p)
922 {
923         struct GAS_PROPORTIONAL_Handle *s = p->s;
924         struct PreferencePeer *p_cur;
925         struct PreferenceClient *c_cur = p->client;
926         double p_rel_global;
927   double *dest;
928   int kind;
929   int rkind;
930   int clients;
931
932   /**
933    * Idea:
934    *
935    * We have:
936    * Set of clients c
937    * Set of peers p_i in P
938    * Set of preference kinds k
939    * A preference value f_k_p_i with an unknown range
940    *
941    * We get:
942    * A client specific relative preference f_p_i_rel [1..2] for all peers
943    *
944    * For every client c
945    * {
946    *   For every preference kind k:
947    *   {
948    *     We remember for the preference f_p_i for each peer p_i.
949    *     We have a default preference value f_p_i = 0
950    *     We have a sum of all preferences f_t = sum (f_p_i)
951    *     So we can calculate a relative preference value fr_p_i:
952    *
953    *     f_k_p_i_ *  / f_t
954    *     f_k_p_i_rel = [1..2], default 1.0
955    *    }
956    *    f_p_i_rel = sum (f_k_p_i_rel) / count(k)
957    * }
958    *
959    **/
960
961   /* For this client: for all preferences, except TERMINATOR */
962   for (kind = GNUNET_ATS_PREFERENCE_END + 1 ; kind < GNUNET_ATS_PreferenceCount; kind ++)
963   {
964           /* Recalcalculate total preference for this kind of quality over all peers*/
965           c_cur->f_total[kind] = 0;
966           for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
967                 c_cur->f_total[kind] += p_cur->f[kind];
968
969           LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p has total preference for %s of %.3f\n",
970                         c_cur->client,
971               GNUNET_ATS_print_preference_type (kind),
972               c_cur->f_total[kind]);
973
974           /* Recalcalculate relative preference for all peers */
975           for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
976           {
977             /* Calculate relative preference for specific kind */
978                 if (0.0 == c_cur->f_total[kind])
979                 {
980                                 /* No one has preference, so set default preference */
981                                 p_cur->f_rel[kind] = DEFAULT_REL_PREFERENCE;
982                 }
983                 else
984                 {
985                                 p_cur->f_rel[kind] = (c_cur->f_total[kind] + p_cur->f[kind]) / c_cur->f_total[kind];
986                 }
987             LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p: peer `%s' has relative preference for %s of %.3f\n",
988                         c_cur->client,
989                 GNUNET_i2s (&p_cur->id),
990                 GNUNET_ATS_print_preference_type (kind),
991                 p_cur->f_rel[kind]);
992
993             /* Calculate peer relative preference */
994             /* Start with kind = 1 to exclude terminator */
995             p_cur->f_rel_total = 0;
996             for (rkind = GNUNET_ATS_PREFERENCE_END + 1; rkind < GNUNET_ATS_PreferenceCount; rkind ++)
997             {
998                 p_cur->f_rel_total += p_cur->f_rel[rkind];
999             }
1000             p_cur->f_rel_total /=  (GNUNET_ATS_PreferenceCount - 1.0); /* -1 due to terminator */
1001             LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p: peer `%s' has total relative preference of %.3f\n",
1002                         c_cur->client,
1003                 GNUNET_i2s (&p_cur->id),
1004                 p_cur->f_rel_total);
1005           }
1006   }
1007
1008   /* Calculcate global total relative peer preference over all clients */
1009   p_rel_global = 0.0;
1010   clients = 0;
1011   for (c_cur = s->pc_head; NULL != c_cur; c_cur = c_cur->next)
1012   {
1013       for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
1014           if (0 == memcmp (&p_cur->id, &p->id, sizeof (p_cur->id)))
1015               break;
1016       if (NULL != p_cur)
1017       {
1018           clients++;
1019           p_rel_global += p_cur->f_rel_total;
1020       }
1021   }
1022   p_rel_global /= clients;
1023   LOG (GNUNET_ERROR_TYPE_DEBUG, "Global preference value for peer `%s': %.3f\n",
1024       GNUNET_i2s (&p->id), p_rel_global);
1025
1026   /* Update global map */
1027   if (NULL != (dest = GNUNET_CONTAINER_multihashmap_get(s->prefs, &p->id.hashPubKey)))
1028       (*dest) = p_rel_global;
1029   else
1030   {
1031       dest = GNUNET_malloc (sizeof (double));
1032       (*dest) = p_rel_global;
1033       GNUNET_CONTAINER_multihashmap_put(s->prefs,
1034           &p->id.hashPubKey,
1035           dest,
1036           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1037   }
1038 }
1039
1040
1041 static void
1042 update_preference (struct PreferencePeer *p,
1043                                                                          enum GNUNET_ATS_PreferenceKind kind,
1044                                                          float score_f)
1045 {
1046         double score = score_f;
1047
1048   /* Update preference value according to type */
1049   switch (kind) {
1050     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1051     case GNUNET_ATS_PREFERENCE_LATENCY:
1052       p->f[kind] = (p->f[kind] + score) / 2;
1053       break;
1054     case GNUNET_ATS_PREFERENCE_END:
1055       break;
1056     default:
1057       break;
1058   }
1059   recalculate_preferences(p);
1060   distribute_bandwidth_in_all_networks (p->s);
1061 }
1062
1063
1064 static void
1065 preference_aging (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1066 {
1067         int i;
1068         double *t = NULL;
1069         double backup;
1070         struct PreferencePeer *p = cls;
1071         GNUNET_assert (NULL != p);
1072
1073
1074         p->aging_task = GNUNET_SCHEDULER_NO_TASK;
1075
1076   LOG (GNUNET_ERROR_TYPE_DEBUG, "Aging preferences for peer `%s'\n",
1077                 GNUNET_i2s (&p->id));
1078
1079   /* Issue for aging :
1080    *
1081    * Not for every peer preference values are set by default, so reducing the
1082    * absolute preference value does not help for aging because it does not have
1083    * influence on the relative values.
1084    *
1085    * So we have to reduce the relative value to have an immediate impact on
1086    * quota calculation. In addition we cannot call recalculate_preferences here
1087    * but instead reduce the absolute value to have an aging impact on future
1088    * calls to change_preference where recalculate_preferences is called
1089    *
1090    */
1091   /* Aging absolute values: */
1092   for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
1093   {
1094                 if (p->f[i] > DEFAULT_REL_PREFERENCE)
1095                 {
1096                         backup = p->f[i];
1097                         p->f[i] *= PREF_AGING_FACTOR;
1098                         LOG (GNUNET_ERROR_TYPE_DEBUG, "Aged preference for peer `%s' from %.3f to %.3f\n",
1099                         GNUNET_i2s (&p->id), backup, p->f[i]);
1100                 }
1101                 else
1102                         p->f[i] = DEFAULT_REL_PREFERENCE;
1103   }
1104   /* Updating relative value */
1105   t = GNUNET_CONTAINER_multihashmap_get (p->s->prefs, &p->id.hashPubKey);
1106   if (NULL == t)
1107   {
1108         GNUNET_break (0);
1109   }
1110   else
1111   {
1112                 if ((*t) > 1.0)
1113                         (*t) = (*t) * PREF_AGING_FACTOR;
1114                 else
1115                         (*t) = 1.0;
1116                 distribute_bandwidth_in_all_networks (p->s);
1117   }
1118   p->aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL,
1119                 &preference_aging, p);
1120 }
1121
1122
1123 /**
1124  * Changes the preferences for a peer in the problem
1125  *
1126  * @param solver the solver handle
1127  * @param client the client with this preference
1128  * @param peer the peer to change the preference for
1129  * @param kind the kind to change the preference
1130  * @param score the score
1131  */
1132 void
1133 GAS_simplistic_address_change_preference (void *solver,
1134                                    void *client,
1135                                    const struct GNUNET_PeerIdentity *peer,
1136                                    enum GNUNET_ATS_PreferenceKind kind,
1137                                    float score)
1138 {
1139   static struct GNUNET_TIME_Absolute next_update;
1140   struct GAS_PROPORTIONAL_Handle *s = solver;
1141   struct PreferenceClient *c_cur;
1142   struct PreferencePeer *p_cur;
1143   int i;
1144
1145   GNUNET_assert (NULL != solver);
1146   GNUNET_assert (NULL != client);
1147   GNUNET_assert (NULL != peer);
1148
1149   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p changes preference for peer `%s' %s %f\n",
1150                                 client,
1151                                 GNUNET_i2s (peer),
1152                                 GNUNET_ATS_print_preference_type (kind),
1153                                 score);
1154
1155   if (kind >= GNUNET_ATS_PreferenceCount)
1156   {
1157       GNUNET_break (0);
1158       return;
1159   }
1160
1161   /* Find preference client */
1162   for (c_cur = s->pc_head; NULL != c_cur; c_cur = c_cur->next)
1163   {
1164       if (client == c_cur->client)
1165         break;
1166   }
1167   /* Not found: create new preference client */
1168   if (NULL == c_cur)
1169   {
1170     c_cur = GNUNET_malloc (sizeof (struct PreferenceClient));
1171     c_cur->client = client;
1172     GNUNET_CONTAINER_DLL_insert (s->pc_head, s->pc_tail, c_cur);
1173   }
1174
1175   /* Find entry for peer */
1176   for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
1177     if (0 == memcmp (&p_cur->id, peer, sizeof (p_cur->id)))
1178         break;
1179
1180   /* Not found: create new peer entry */
1181   if (NULL == p_cur)
1182   {
1183       p_cur = GNUNET_malloc (sizeof (struct PreferencePeer));
1184       p_cur->s = s;
1185       p_cur->client = c_cur;
1186       p_cur->id = (*peer);
1187       for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
1188       {
1189         /* Default value per peer absolut preference for a quality:
1190          * No value set, so absolute preference 0 */
1191         p_cur->f[i] = DEFAULT_ABS_PREFERENCE;
1192         /* Default value per peer relative preference for a quality: 1.0 */
1193         p_cur->f_rel[i] = DEFAULT_REL_PREFERENCE;
1194       }
1195       p_cur->aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL, &preference_aging, p_cur);
1196       GNUNET_CONTAINER_DLL_insert (c_cur->p_head, c_cur->p_tail, p_cur);
1197   }
1198
1199   update_preference (p_cur, kind, score);
1200
1201   /* FIXME: We should update quotas if UPDATE_INTERVAL is reached */
1202   if (GNUNET_TIME_absolute_get().abs_value > next_update.abs_value)
1203   {
1204       /* update quotas*/
1205       next_update = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1206                                               MIN_UPDATE_INTERVAL);
1207   }
1208 }
1209
1210
1211 /**
1212  *  Solver API functions
1213  *  ---------------------------
1214  */
1215
1216 /**
1217  * Get the preferred address for a specific peer
1218  *
1219  * @param solver the solver handle
1220  * @param addresses the address hashmap containing all addresses
1221  * @param peer the identity of the peer
1222  */
1223 const struct ATS_Address *
1224 GAS_proportional_get_preferred_address (void *solver,
1225                                struct GNUNET_CONTAINER_MultiHashMap * addresses,
1226                                const struct GNUNET_PeerIdentity *peer)
1227 {
1228   struct GAS_PROPORTIONAL_Handle *s = solver;
1229   struct Network *net_prev;
1230   struct Network *net_cur;
1231   struct ATS_Address *cur;
1232   struct ATS_Address *prev;
1233
1234   GNUNET_assert (s != NULL);
1235   cur = NULL;
1236   /* Get address with: stick to current address, lower distance, lower latency */
1237   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
1238                                               &find_address_it, &cur);
1239   if (NULL == cur)
1240   {
1241     LOG (GNUNET_ERROR_TYPE_DEBUG, "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
1242     return NULL;
1243   }
1244
1245   LOG (GNUNET_ERROR_TYPE_DEBUG, "Suggesting %s address %p for peer `%s'\n",
1246       (GNUNET_NO == cur->active) ? "inactive" : "active",
1247       cur, GNUNET_i2s (peer));
1248   net_cur = (struct Network *) cur->solver_information;
1249   if (GNUNET_YES == cur->active)
1250   {
1251       /* This address was selected previously, so no need to update quotas */
1252       return cur;
1253   }
1254
1255   /* This address was not active, so we have to:
1256    *
1257    * - mark previous active address as not active
1258    * - update quota for previous address network
1259    * - update quota for this address network
1260    */
1261
1262   prev = get_active_address (s, addresses, peer);
1263   if (NULL != prev)
1264   {
1265       net_prev = (struct Network *) prev->solver_information;
1266       prev->active = GNUNET_NO; /* No active any longer */
1267       prev->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
1268       prev->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
1269       s->bw_changed (s->bw_changed_cls, prev); /* notify about bw change, REQUIRED? */
1270       if (GNUNET_SYSERR == addresse_decrement (s, net_prev, GNUNET_NO, GNUNET_YES))
1271         GNUNET_break (0);
1272       distribute_bandwidth_in_network (s, net_prev, NULL);
1273   }
1274
1275   if (GNUNET_NO == (is_bandwidth_available_in_network (cur->solver_information)))
1276   {
1277     GNUNET_break (0); /* This should never happen*/
1278     return NULL;
1279   }
1280
1281   cur->active = GNUNET_YES;
1282   addresse_increment(s, net_cur, GNUNET_NO, GNUNET_YES);
1283   distribute_bandwidth_in_network (s, net_cur, cur);
1284
1285   return cur;
1286 }
1287
1288
1289 /**
1290  * Stop notifying about address and bandwidth changes for this peer
1291  *
1292  * @param solver the solver handle
1293  * @param addresses address hashmap
1294  * @param peer the peer
1295  */
1296 void
1297 GAS_proportional_stop_get_preferred_address (void *solver,
1298                                      struct GNUNET_CONTAINER_MultiHashMap *addresses,
1299                                      const struct GNUNET_PeerIdentity *peer)
1300 {
1301         return;
1302 }
1303
1304
1305 /**
1306  * Remove an address from the solver
1307  *
1308  * @param solver the solver handle
1309  * @param addresses the address hashmap containing all addresses
1310  * @param address the address to remove
1311  * @param session_only delete only session not whole address
1312  */
1313 void
1314 GAS_proportional_address_delete (void *solver,
1315     struct GNUNET_CONTAINER_MultiHashMap * addresses,
1316     struct ATS_Address *address, int session_only)
1317 {
1318   struct GAS_PROPORTIONAL_Handle *s = solver;
1319   struct Network *net;
1320   struct AddressWrapper *aw;
1321
1322   /* Remove an adress completely, we have to:
1323    * - Remove from specific network
1324    * - Decrease number of total addresses
1325    * - If active:
1326    *   - decrease number of active addreses
1327    *   - update quotas
1328    */
1329
1330   net = (struct Network *) address->solver_information;
1331
1332   if (GNUNET_NO == session_only)
1333   {
1334     LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1335         (GNUNET_NO == address->active) ? "inactive" : "active",
1336         address, GNUNET_i2s (&address->peer),
1337         net->desc, net->total_addresses, net->active_addresses);
1338
1339     /* Remove address */
1340     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
1341     for (aw = net->head; NULL != aw; aw = aw->next)
1342     {
1343         if (aw->addr == address)
1344           break;
1345     }
1346     if (NULL == aw )
1347     {
1348         GNUNET_break (0);
1349         return;
1350     }
1351     GNUNET_CONTAINER_DLL_remove (net->head, net->tail, aw);
1352     GNUNET_free (aw);
1353   }
1354   else
1355   {
1356       /* Remove session only: remove if active and update */
1357       LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
1358           (GNUNET_NO == address->active) ? "inactive" : "active",
1359           address, GNUNET_i2s (&address->peer),
1360           net->desc, net->total_addresses, net->active_addresses);
1361   }
1362
1363   if (GNUNET_YES == address->active)
1364   {
1365       /* Address was active, remove from network and update quotas*/
1366       address->active = GNUNET_NO;
1367       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
1368         GNUNET_break (0);
1369       distribute_bandwidth_in_network (s, net, NULL);
1370   }
1371   LOG (GNUNET_ERROR_TYPE_DEBUG, "After deleting address now total %u and active %u addresses in network `%s'\n",
1372       net->total_addresses,
1373       net->active_addresses,
1374       net->desc);
1375
1376 }
1377
1378
1379 /**
1380  * Add a new single address to a network
1381  *
1382  * @param solver the solver Handle
1383  * @param addresses the address hashmap containing all addresses
1384  * @param address the address to add
1385  * @param network network type of this address
1386  */
1387 void
1388 GAS_proportional_address_add (void *solver,
1389                                                         struct GNUNET_CONTAINER_MultiHashMap *addresses,
1390                                                         struct ATS_Address *address,
1391                                                         uint32_t network);
1392
1393 /**
1394  * Updates a single address in the solver and checks previous values
1395  *
1396  * @param solver the solver Handle
1397  * @param addresses the address hashmap containing all addresses
1398  * @param address the update address
1399  * @param session the previous session
1400  * @param in_use the previous address in use state
1401  * @param prev_ats previous ATS information
1402  * @param prev_atsi_count the previous atsi count
1403  */
1404 void
1405 GAS_proportional_address_update (void *solver,
1406                               struct GNUNET_CONTAINER_MultiHashMap *addresses,
1407                               struct ATS_Address *address,
1408                               uint32_t session,
1409                               int in_use,
1410                               const struct GNUNET_ATS_Information *prev_ats,
1411                               uint32_t prev_atsi_count)
1412 {
1413   struct ATS_Address *new;
1414   struct GAS_PROPORTIONAL_Handle *s = (struct GAS_PROPORTIONAL_Handle *) solver;
1415   int i;
1416   uint32_t prev_value;
1417   uint32_t prev_type;
1418   uint32_t addr_net;
1419   int save_active = GNUNET_NO;
1420   struct Network *new_net = NULL;
1421
1422   /* Check updates to performance information */
1423   for (i = 0; i < prev_atsi_count; i++)
1424   {
1425     prev_type = ntohl (prev_ats[i].type);
1426     prev_value = ntohl (prev_ats[i].value);
1427     switch (prev_type)
1428     {
1429     case GNUNET_ATS_UTILIZATION_UP:
1430     case GNUNET_ATS_UTILIZATION_DOWN:
1431     case GNUNET_ATS_QUALITY_NET_DELAY:
1432     case GNUNET_ATS_QUALITY_NET_DISTANCE:
1433     case GNUNET_ATS_COST_WAN:
1434     case GNUNET_ATS_COST_LAN:
1435     case GNUNET_ATS_COST_WLAN:
1436         /* No actions required here*/
1437         break;
1438     case GNUNET_ATS_NETWORK_TYPE:
1439
1440       addr_net = get_performance_info (address, GNUNET_ATS_NETWORK_TYPE);
1441       if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
1442       {
1443         GNUNET_break (0);
1444         addr_net = GNUNET_ATS_NET_UNSPECIFIED;
1445       }
1446       if (addr_net != prev_value)
1447       {
1448         /* Network changed */
1449         LOG (GNUNET_ERROR_TYPE_DEBUG, "Network type changed, moving %s address from `%s' to `%s'\n",
1450             (GNUNET_YES == address->active) ? "active" : "inactive",
1451              GNUNET_ATS_print_network_type(prev_value),
1452              GNUNET_ATS_print_network_type(addr_net));
1453
1454         save_active = address->active;
1455         /* remove from old network */
1456         GAS_proportional_address_delete (solver, addresses, address, GNUNET_NO);
1457
1458         /* set new network type */
1459         new_net = get_network (solver, addr_net);
1460         address->solver_information = new_net;
1461
1462         /* Add to new network and update*/
1463         GAS_proportional_address_add (solver, addresses, address, addr_net);
1464         if (GNUNET_YES == save_active)
1465         {
1466           /* check if bandwidth available in new network */
1467           if (GNUNET_YES == (is_bandwidth_available_in_network (new_net)))
1468           {
1469               /* Suggest updated address */
1470               address->active = GNUNET_YES;
1471               addresse_increment (s, new_net, GNUNET_NO, GNUNET_YES);
1472               distribute_bandwidth_in_network (solver, new_net, NULL);
1473           }
1474           else
1475           {
1476             LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough bandwidth in new network, suggesting alternative address ..\n");
1477
1478             /* Set old address to zero bw */
1479             address->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0);
1480             address->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0);
1481             s->bw_changed  (s->bw_changed_cls, address);
1482
1483             /* Find new address to suggest since no bandwidth in network*/
1484             new = (struct ATS_Address *) GAS_proportional_get_preferred_address (s, addresses, &address->peer);
1485             if (NULL != new)
1486             {
1487                 /* Have an alternative address to suggest */
1488                 s->bw_changed  (s->bw_changed_cls, new);
1489             }
1490
1491           }
1492         }
1493       }
1494
1495       break;
1496     case GNUNET_ATS_ARRAY_TERMINATOR:
1497       break;
1498     default:
1499       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1500                   "Received unsupported ATS type %u\n", prev_type);
1501       GNUNET_break (0);
1502       break;
1503
1504     }
1505
1506   }
1507   if (address->session_id != session)
1508   {
1509       LOG (GNUNET_ERROR_TYPE_DEBUG,
1510                   "Session changed from %u to %u\n", session, address->session_id);
1511   }
1512   if (address->used != in_use)
1513   {
1514       LOG (GNUNET_ERROR_TYPE_DEBUG,
1515                   "Usage changed from %u to %u\n", in_use, address->used);
1516   }
1517
1518 }
1519
1520
1521 /**
1522  * Add a new single address to a network
1523  *
1524  * @param solver the solver Handle
1525  * @param addresses the address hashmap containing all addresses
1526  * @param address the address to add
1527  * @param network network type of this address
1528  */
1529 void
1530 GAS_proportional_address_add (void *solver,
1531                                                         struct GNUNET_CONTAINER_MultiHashMap *addresses,
1532                                                         struct ATS_Address *address,
1533                                                         uint32_t network)
1534 {
1535   struct GAS_PROPORTIONAL_Handle *s = solver;
1536   struct Network *net = NULL;
1537   struct AddressWrapper *aw = NULL;
1538   GNUNET_assert (NULL != s);
1539
1540   net = get_network (s, network);
1541   if (NULL == net)
1542   {
1543     GNUNET_break (0);
1544     return;
1545   }
1546
1547   aw = GNUNET_malloc (sizeof (struct AddressWrapper));
1548   aw->addr = address;
1549   GNUNET_CONTAINER_DLL_insert (net->head, net->tail, aw);
1550   addresse_increment (s, net, GNUNET_YES, GNUNET_NO);
1551   aw->addr->solver_information = net;
1552
1553   LOG (GNUNET_ERROR_TYPE_DEBUG, "After adding address now total %u and active %u addresses in network `%s'\n",
1554       net->total_addresses,
1555       net->active_addresses,
1556       net->desc);
1557 }
1558
1559
1560 /**
1561  * Init the proportional problem solver
1562  *
1563  * Quotas:
1564  * network[i] contains the network type as type GNUNET_ATS_NetworkType[i]
1565  * out_quota[i] contains outbound quota for network type i
1566  * in_quota[i] contains inbound quota for network type i
1567  *
1568  * Example
1569  * network = {GNUNET_ATS_NET_UNSPECIFIED, GNUNET_ATS_NET_LOOPBACK, GNUNET_ATS_NET_LAN, GNUNET_ATS_NET_WAN, GNUNET_ATS_NET_WLAN}
1570  * network[2]   == GNUNET_ATS_NET_LAN
1571  * out_quota[2] == 65353
1572  * in_quota[2]  == 65353
1573  *
1574  * @param cfg configuration handle
1575  * @param stats the GNUNET_STATISTICS handle
1576  * @param network array of GNUNET_ATS_NetworkType with length dest_length
1577  * @param out_quota array of outbound quotas
1578  * @param in_quota array of outbound quota
1579  * @param dest_length array length for quota arrays
1580  * @param bw_changed_cb callback for changed bandwidth amounts
1581  * @param bw_changed_cb_cls cls for callback
1582  * @return handle for the solver on success, NULL on fail
1583  */
1584 void *
1585 GAS_proportional_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1586                        const struct GNUNET_STATISTICS_Handle *stats,
1587                        int *network,
1588                        unsigned long long *out_quota,
1589                        unsigned long long *in_quota,
1590                        int dest_length,
1591                        GAS_bandwidth_changed_cb bw_changed_cb,
1592                        void *bw_changed_cb_cls)
1593 {
1594   int c;
1595   struct GAS_PROPORTIONAL_Handle *s = GNUNET_malloc (sizeof (struct GAS_PROPORTIONAL_Handle));
1596   struct Network * cur;
1597   char * net_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
1598
1599
1600   s->stats = (struct GNUNET_STATISTICS_Handle *) stats;
1601   s->bw_changed = bw_changed_cb;
1602   s->bw_changed_cls = bw_changed_cb_cls;
1603   s->networks = dest_length;
1604   s->network_entries = GNUNET_malloc (dest_length * sizeof (struct Network));
1605   s->active_addresses = 0;
1606   s->total_addresses = 0;
1607   s->prefs = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
1608
1609   for (c = 0; c < dest_length; c++)
1610   {
1611       cur = &s->network_entries[c];
1612       cur->total_addresses = 0;
1613       cur->active_addresses = 0;
1614       cur->type = network[c];
1615       cur->total_quota_in = in_quota[c];
1616       cur->total_quota_out = out_quota[c];
1617       cur->desc = net_str[c];
1618       GNUNET_asprintf (&cur->stat_total, "# ATS addresses %s total", cur->desc);
1619       GNUNET_asprintf (&cur->stat_active, "# ATS active addresses %s total", cur->desc);
1620   }
1621   return s;
1622 }
1623
1624
1625 /**
1626  * Shutdown the proportional problem solver
1627  *
1628  * @param solver the respective handle to shutdown
1629  */
1630 void
1631 GAS_proportional_done (void *solver)
1632 {
1633   struct GAS_PROPORTIONAL_Handle *s = solver;
1634   struct PreferenceClient *pc;
1635   struct PreferenceClient *next_pc;
1636   struct PreferencePeer *p;
1637   struct PreferencePeer *next_p;
1638   struct AddressWrapper *cur;
1639   struct AddressWrapper *next;
1640   int c;
1641   GNUNET_assert (s != NULL);
1642
1643   for (c = 0; c < s->networks; c++)
1644   {
1645       if (s->network_entries[c].total_addresses > 0)
1646       {
1647         LOG (GNUNET_ERROR_TYPE_ERROR,
1648                     "Had %u addresses for network `%s' not deleted during shutdown\n",
1649                     s->network_entries[c].total_addresses,
1650                     s->network_entries[c].desc);
1651         GNUNET_break (0);
1652       }
1653
1654       if (s->network_entries[c].active_addresses > 0)
1655       {
1656         LOG (GNUNET_ERROR_TYPE_ERROR,
1657                     "Had %u active addresses for network `%s' not deleted during shutdown\n",
1658                     s->network_entries[c].active_addresses,
1659                     s->network_entries[c].desc);
1660         GNUNET_break (0);
1661       }
1662
1663       next = s->network_entries[c].head;
1664       while (NULL != (cur = next))
1665       {
1666           next = cur->next;
1667           GNUNET_CONTAINER_DLL_remove (s->network_entries[c].head,
1668                                        s->network_entries[c].tail,
1669                                        cur);
1670           GNUNET_free (cur);
1671       }
1672       GNUNET_free (s->network_entries[c].stat_total);
1673       GNUNET_free (s->network_entries[c].stat_active);
1674   }
1675   if (s->total_addresses > 0)
1676   {
1677     LOG (GNUNET_ERROR_TYPE_ERROR,
1678                 "Had %u addresses not deleted during shutdown\n",
1679                 s->total_addresses);
1680     GNUNET_break (0);
1681   }
1682   if (s->active_addresses > 0)
1683   {
1684     LOG (GNUNET_ERROR_TYPE_ERROR,
1685                 "Had %u active addresses not deleted during shutdown\n",
1686                 s->active_addresses);
1687     GNUNET_break (0);
1688   }
1689   GNUNET_free (s->network_entries);
1690
1691   next_pc = s->pc_head;
1692   while (NULL != (pc = next_pc))
1693   {
1694       next_pc = pc->next;
1695       GNUNET_CONTAINER_DLL_remove (s->pc_head, s->pc_tail, pc);
1696       next_p = pc->p_head;
1697       while (NULL != (p = next_p))
1698       {
1699           next_p = p->next;
1700           if (GNUNET_SCHEDULER_NO_TASK != p->aging_task)
1701           {
1702                 GNUNET_SCHEDULER_cancel(p->aging_task);
1703                 p->aging_task = GNUNET_SCHEDULER_NO_TASK;
1704           }
1705           GNUNET_CONTAINER_DLL_remove (pc->p_head, pc->p_tail, p);
1706           GNUNET_free (p);
1707       }
1708       GNUNET_free (pc);
1709   }
1710
1711   GNUNET_CONTAINER_multihashmap_iterate (s->prefs, &free_pref, NULL);
1712   GNUNET_CONTAINER_multihashmap_destroy (s->prefs);
1713   GNUNET_free (s);
1714 }
1715
1716
1717 /* end of gnunet-service-ats-solver_proportional.c */