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