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