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