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