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