cleaning up address_decrement
[oweals/gnunet.git] / src / ats / plugin_ats_proportional.c
1 /*
2  This file is part of GNUnet.
3  Copyright (C) 2011-2015 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/plugin_ats_proportional.c
23  * @brief ATS proportional solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_ats_plugin.h"
30 #include "gnunet_ats_service.h"
31 #include "gnunet-service-ats_addresses.h"
32
33 #define PROP_STABILITY_FACTOR 1.25
34
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "ats-proportional",__VA_ARGS__)
37
38
39 /**
40  *
41  * NOTE: Do not change this documentation. This documentation is based
42  * on gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
43  * use build_txt.sh to generate plaintext output
44  *
45  * ATS addresses : proportional solver
46  *
47  *    The proportional solver ("proportional") distributes the available
48  *    bandwidth fair over all the addresses influenced by the
49  *    preference values. For each available network type an in- and
50  *    outbound quota is configured and the bandwidth available in
51  *    these networks is distributed over the addresses.  The solver
52  *    first assigns every addresses the minimum amount of bandwidth
53  *    #GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT and then distributes the
54  *    remaining bandwidth available according to the preference
55  *    values. For each peer only a single address gets bandwidth
56  *    assigned and only one address marked as active.  The most
57  *    important functionality for the solver is implemented in: *
58  *    find_address_it is an hashmap iterator returning the prefered
59  *    address for an peer * update_quota_per_network distributes
60  *    available bandwidth for a network over active addresses
61  *
62  *    Changes to addresses automatically have an impact on the the
63  *    bandwidth assigned to other addresses in the same network since
64  *    the solver distributes the remaining bandwidth over the
65  *    addresses in the network.  When changes to the addresses occur,
66  *    the solver first performs the changes, like adding or deleting
67  *    addresses, and then updates bandwidth assignment for the
68  *    affected network. Bandwidth assignment is only recalculated on
69  *    demand when an address is requested by a client for a peer or
70  *    when the addresses available have changed or an address changed
71  *    the network it is located in. When the bandwidth assignment has
72  *    changed the callback is called with the new bandwidth
73  *    assignments. The bandwidth distribution for a network is
74  *    recalculated due to: * address suggestion requests * address
75  *    deletions * address switching networks during address update *
76  *    preference changes
77  *
78  *     3.1 Data structures used
79  *
80  *    For each ATS network (e.g. WAN, LAN, loopback) a struct Network
81  *    is used to specify network related information as total adresses
82  *    and active addresses in this network and the configured in- and
83  *    outbound quota. Each network also contains a list of addresses
84  *    added to the solver located in this network. The proportional
85  *    solver uses the addresses' solver_information field to store the
86  *    proportional network it belongs to for each address.
87  *
88  *     3.2 Initializing
89  *
90  *    When the proportional solver is initialized the solver creates a
91  *    new solver handle and initializes the network structures with
92  *    the quotas passed from addresses and returns the handle solver.
93  *
94  *     3.3 Adding an address
95  *
96  *    When a new address is added to the solver using s_add, a lookup
97  *    for the network for this address is done and the address is
98  *    enqueued in in the linked list of the network.
99  *
100  *     3.4 Updating an address
101  *
102  *    The main purpose of address updates is to update the ATS
103  *    information for addresse selection. Important for the proportional
104  *    solver is when an address switches network it is located
105  *    in. This is common because addresses added by transport's
106  *    validation mechanism are commonly located in
107  *    #GNUNET_ATS_NET_UNSPECIFIED. Addresses in validation are located
108  *    in this network type and only if a connection is successful on
109  *    return of payload data transport switches to the real network
110  *    the address is located in.  When an address changes networks it
111  *    is first of all removed from the old network using the solver
112  *    API function #GAS_proportional_address_delete() and the network in
113  *    the address struct is updated. A lookup for the respective new
114  *    proportional network is done and stored in the addresse's
115  *    solver_information field. Next the address is re-added to the
116  *    solver using the solver API function
117  *    #GAS_proportional_address_add(). If the address was marked as in
118  *    active, the solver checks if bandwidth is available in the
119  *    network and if yes sets the address to active and updates the
120  *    bandwidth distribution in this network. If no bandwidth is
121  *    available it sets the bandwidth for this address to 0 and tries
122  *    to suggest an alternative address. If an alternative address was
123  *    found, addresses' callback is called for this address.
124  *
125  *     3.5 Deleting an address
126  *
127  *    When an address is removed from the solver, it removes the
128  *    respective address from the network and if the address was
129  *    marked as active, it updates the bandwidth distribution for this
130  *    network.
131  *
132  *     3.6 Requesting addresses
133  *
134  *    When an address is requested for a peer the solver performs a
135  *    lookup for the peer entry in addresses address hashmap and
136  *    selects the best address.  The selection of the most suitable
137  *    address is done in the find_address_it hashmap iterator
138  *    described in detail in section 3.7. If no address is returned,
139  *    no address can be suggested at the moment. If the address
140  *    returned is marked as active, the solver can return this
141  *    address. If the address is not marked as active, the solver
142  *    checks if another address belongign to this peer is marked as
143  *    active and marks the address as inactive, updates the bandwidth
144  *    for this address to 0, call the bandwidth changed callback for
145  *    this address due to the change and updates quota assignment for
146  *    the addresse's network. the now in-active address is belonging
147  *    to. The solver marks the new address as active and updates the
148  *    bandwidth assignment for this network.
149  *
150  *     3.7 Choosing addresses
151  *
152  *    Choosing the best possible address for suggestion is done by
153  *    iterating over all addresses of a peer stored in addresses'
154  *    hashmap and using the hashmap iterator find_address_it to select
155  *    the best available address.  Several checks are done when an
156  *    address is selected. First if this address is currently blocked
157  *    by addresses from being suggested. An address is blocked for the
158  *    duration of #ATS_BLOCKING_DELTA when it is suggested to
159  *    transport. Next it is checked if at least
160  *    #GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT bytes bandwidth is available
161  *    in the addresse's network, because suggesting an address without
162  *    bandwidth does not make sense. This also ensures that all active
163  *    addresses in this network get at least the minimum amount of
164  *    bandwidth assigned. In the next step the solver ensures that for
165  *    tcp connections inbound connections are prefered over outbound
166  *    connections. In the next stet the solver ensures that
167  *    connections are prefered in the following order: * connections
168  *    are already established and have bandwidth assigned *
169  *    connections with a shorter distance * connectes have a shorter
170  *    latency
171  *
172  *     3.8 Changing preferences
173  *
174  *     3.9 Shutdown
175  *
176  *    During shutdown all network entries and aging processes are
177  *    destroyed and freed.
178  *
179  *
180  * OLD DOCUMENTATION
181  *
182  * This solver assigns in and outbound bandwidth equally for all
183  * addresses in specific network type (WAN, LAN) based on configured
184  * in and outbound quota for this network.
185  *
186  * The solver is notified by addresses about changes to the addresses
187  * and recalculates the bandwith assigned if required. The solver
188  * notifies addresses by calling the GAS_bandwidth_changed_cb
189  * callback.
190  *
191  * - Initialization
192  *
193  *
194  *
195  *
196  * For each peer only a single is selected and marked as "active" in the address
197  * struct.
198  *
199  * E.g.:
200  *
201  * You have the networks WAN and LAN and quotas
202  * WAN_TOTAL_IN, WAN_TOTAL_OUT
203  * LAN_TOTAL_IN, LAN_TOTAL_OUT
204  *
205  * If you have x addresses in the network segment LAN, the quotas are
206  * QUOTA_PER_ADDRESS = LAN_TOTAL_OUT / x
207  *
208  * Quotas are automatically recalculated and reported back when addresses are
209  * - requested
210  *
211  */
212
213 /**
214  * Default value to assume for the proportionality factor,
215  * if none is given in the configuration.
216  */
217 #define PROPORTIONALITY_FACTOR 2.0
218
219
220 /**
221  * Address information stored for the proportional solver in the
222  * `solver_information` member of `struct GNUNET_ATS_Address`.
223  *
224  * They are also stored in the respective `struct Network`'s linked
225  * list.
226  */
227 struct AddressWrapper
228 {
229   /**
230    * Next in DLL
231    */
232   struct AddressWrapper *next;
233
234   /**
235    * Previous in DLL
236    */
237   struct AddressWrapper *prev;
238
239   /**
240    * The address
241    */
242   struct ATS_Address *addr;
243
244     /**
245    * Network scope this address is in
246    */
247   struct Network *network;
248
249   /**
250    * Inbound quota
251    */
252   uint32_t calculated_quota_in;
253
254   /**
255    * Outbound quota
256    */
257   uint32_t calculated_quota_out;
258
259   /**
260    * When was this address activated
261    */
262   struct GNUNET_TIME_Absolute activated;
263
264 };
265
266
267 /**
268  * Representation of a network
269  */
270 struct Network
271 {
272   /**
273    * Network description
274    */
275   const char *desc;
276
277   /**
278    * String for statistics total addresses
279    */
280   char *stat_total;
281
282   /**
283    * String for statistics active addresses
284    */
285   char *stat_active;
286
287   /**
288    * Linked list of addresses in this network: head
289    */
290   struct AddressWrapper *head;
291
292   /**
293    * Linked list of addresses in this network: tail
294    */
295   struct AddressWrapper *tail;
296
297   /**
298    * Total inbound quota
299    */
300   unsigned long long total_quota_in;
301
302   /**
303    * Total outbound quota
304    */
305   unsigned long long total_quota_out;
306
307   /**
308    * ATS network type
309    */
310   enum GNUNET_ATS_Network_Type type;
311
312   /**
313    * Number of active addresses for this network
314    */
315   unsigned int active_addresses;
316
317   /**
318    * Number of total addresses for this network
319    */
320   unsigned int total_addresses;
321
322 };
323
324
325 /**
326  * A handle for the proportional solver
327  */
328 struct GAS_PROPORTIONAL_Handle
329 {
330
331   /**
332    * Our execution environment.
333    */
334   struct GNUNET_ATS_PluginEnvironment *env;
335
336   /**
337    * Networks array
338    */
339   struct Network *network_entries;
340
341   /**
342    * Proportionality factor
343    */
344   double prop_factor;
345
346   /**
347    * Stability factor
348    */
349   double stability_factor;
350
351   /**
352    * Bulk lock counter. If zero, we are not locked.
353    */
354   unsigned int bulk_lock;
355
356   /**
357    * Number of changes made while solver was locked.  We really only
358    * use 0/non-zero to check on unlock if we have to run the update.
359    */
360   unsigned int bulk_requests;
361
362   /**
363    * Number of active addresses for solver
364    */
365   unsigned int active_addresses;
366
367   /**
368    * Number of networks in @a network_entries
369    */
370   unsigned int network_count;
371 };
372
373
374 /**
375  * Function used to unload the plugin.
376  *
377  * @param cls return value from #libgnunet_plugin_ats_proportional_init()
378  */
379 void *
380 libgnunet_plugin_ats_proportional_done (void *cls)
381 {
382   struct GNUNET_ATS_SolverFunctions *sf = cls;
383   struct GAS_PROPORTIONAL_Handle *s = sf->cls;
384   struct AddressWrapper *cur;
385   struct AddressWrapper *next;
386   unsigned int c;
387
388   for (c = 0; c < s->network_count; c++)
389   {
390     if (s->network_entries[c].total_addresses > 0)
391     {
392       LOG (GNUNET_ERROR_TYPE_DEBUG,
393            "Had %u addresses for network `%s' not deleted during shutdown\n",
394            s->network_entries[c].total_addresses,
395            s->network_entries[c].desc);
396       //GNUNET_break(0);
397     }
398
399     if (s->network_entries[c].active_addresses > 0)
400     {
401       LOG (GNUNET_ERROR_TYPE_DEBUG,
402            "Had %u active addresses for network `%s' not deleted during shutdown\n",
403            s->network_entries[c].active_addresses,
404            s->network_entries[c].desc);
405       //GNUNET_break(0);
406     }
407
408     next = s->network_entries[c].head;
409     while (NULL != (cur = next))
410     {
411       next = cur->next;
412       GNUNET_CONTAINER_DLL_remove (s->network_entries[c].head,
413                                    s->network_entries[c].tail,
414                                    cur);
415       GNUNET_free_non_null (cur->addr->solver_information);
416       GNUNET_free(cur);
417     }
418     GNUNET_free (s->network_entries[c].stat_total);
419     GNUNET_free (s->network_entries[c].stat_active);
420   }
421   if (s->active_addresses > 0)
422   {
423     LOG (GNUNET_ERROR_TYPE_DEBUG,
424          "Had %u active addresses not deleted during shutdown\n",
425          s->active_addresses);
426     // GNUNET_break (0);
427   }
428   GNUNET_free (s->network_entries);
429   GNUNET_free (s);
430   return NULL;
431 }
432
433
434 /**
435  * Test if bandwidth is available in this network to add an additional address
436  *
437  * @param net the network type to update
438  * @return #GNUNET_YES or #GNUNET_NO
439  */
440 static int
441 is_bandwidth_available_in_network (struct Network *net)
442 {
443   unsigned int na = net->active_addresses + 1;
444   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
445
446   if (((net->total_quota_in / na) > min_bw)
447       && ((net->total_quota_out / na) > min_bw))
448   {
449     LOG (GNUNET_ERROR_TYPE_DEBUG,
450          "Enough bandwidth available for %u active addresses in network `%s'\n",
451          na,
452          net->desc);
453
454     return GNUNET_YES;
455   }
456   LOG (GNUNET_ERROR_TYPE_DEBUG,
457        "Not enough bandwidth available for %u active addresses in network `%s'\n",
458        na,
459        net->desc);
460   return GNUNET_NO;
461 }
462
463
464 /**
465  * Update bandwidth assigned to peers in this network
466  *
467  * @param s the solver handle
468  * @param net the network type to update
469  * this address
470  */
471 static void
472 distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
473                       struct Network *net)
474 {
475   struct AddressWrapper *aw;
476   unsigned long long remaining_quota_in = 0;
477   unsigned long long quota_out_used = 0;
478   unsigned long long remaining_quota_out = 0;
479   unsigned long long quota_in_used = 0;
480   int count_addresses;
481   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
482   double relative_peer_prefence;
483   double sum_relative_peer_prefences; /* Important: has to be double not float due to precision */
484   double cur_pref; /* Important: has to be double not float due to precision */
485   double peer_weight;
486   double total_weight;
487   const double *peer_relative_prefs = NULL; /* Important: has to be double not float due to precision */
488
489   uint32_t assigned_quota_in = 0;
490   uint32_t assigned_quota_out = 0;
491
492
493   LOG (GNUNET_ERROR_TYPE_INFO,
494        "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
495        net->desc,
496        net->active_addresses,
497        net->total_quota_in,
498        net->total_quota_in);
499
500   if (net->active_addresses == 0)
501   {
502     return; /* no addresses to update */
503   }
504
505   /* Idea
506    * Assign every peer in network minimum Bandwidth
507    * Distribute bandwidth left according to preference
508    */
509
510   if ((net->active_addresses * min_bw) > net->total_quota_in)
511   {
512     GNUNET_break(0);
513     return;
514   }
515   if ((net->active_addresses * min_bw) > net->total_quota_out)
516   {
517     GNUNET_break(0);
518     return;
519   }
520
521   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
522   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
523   LOG(GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
524       remaining_quota_in, remaining_quota_out);
525   sum_relative_peer_prefences = 0.0;
526
527   /* Calculate sum of relative preference for active addresses in this network */
528   count_addresses = 0;
529   for (aw = net->head; NULL != aw; aw = aw->next)
530   {
531     if (GNUNET_YES != aw->addr->active)
532       continue;
533
534     peer_relative_prefs = s->env->get_preferences (s->env->cls,
535                                                    &aw->addr->peer);
536     relative_peer_prefence = 0.0;
537     relative_peer_prefence += peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
538     sum_relative_peer_prefences += relative_peer_prefence;
539     count_addresses ++;
540   }
541
542   if (count_addresses != net->active_addresses)
543   {
544     GNUNET_break (0);
545     LOG (GNUNET_ERROR_TYPE_WARNING,
546          "%s: Counted %u active addresses, but network says to have %u active addresses\n",
547          net->desc, count_addresses, net->active_addresses);
548     for (aw = net->head; NULL != aw; aw = aw->next)
549     {
550       if (GNUNET_YES != aw->addr->active)
551         continue;
552
553       LOG (GNUNET_ERROR_TYPE_WARNING,
554            "Active: `%s' `%s' length %u\n",
555            GNUNET_i2s (&aw->addr->peer),
556            aw->addr->plugin,
557            aw->addr->addr_len);
558     }
559   }
560
561   LOG (GNUNET_ERROR_TYPE_INFO,
562       "Total relative preference %.3f for %u addresses in network %s\n",
563       sum_relative_peer_prefences, net->active_addresses, net->desc);
564
565   for (aw = net->head; NULL != aw; aw = aw->next)
566   {
567     if (GNUNET_YES == aw->addr->active)
568     {
569       peer_relative_prefs = s->env->get_preferences (s->env->cls,
570                                                      &aw->addr->peer);
571
572       cur_pref = peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH];
573       total_weight = net->active_addresses +
574           s->prop_factor * sum_relative_peer_prefences;
575       peer_weight = (1.0 + (s->prop_factor * cur_pref));
576
577       assigned_quota_in = min_bw
578           + ((peer_weight / total_weight) * remaining_quota_in);
579       assigned_quota_out = min_bw
580           + ((peer_weight / total_weight) * remaining_quota_out);
581
582       LOG (GNUNET_ERROR_TYPE_INFO,
583           "New quota for peer `%s' with weight (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
584           GNUNET_i2s (&aw->addr->peer), peer_weight, total_weight,
585           assigned_quota_in, assigned_quota_out);
586     }
587     else
588     {
589       assigned_quota_in = 0;
590       assigned_quota_out = 0;
591     }
592
593     quota_in_used += assigned_quota_in;
594     quota_out_used += assigned_quota_out;
595     /* Prevent overflow due to rounding errors */
596     if (assigned_quota_in > UINT32_MAX)
597       assigned_quota_in = UINT32_MAX;
598     if (assigned_quota_out > UINT32_MAX)
599       assigned_quota_out = UINT32_MAX;
600
601     /* Compare to current bandwidth assigned */
602     aw->calculated_quota_in = assigned_quota_in;
603     aw->calculated_quota_out = assigned_quota_out;
604   }
605   LOG(GNUNET_ERROR_TYPE_DEBUG,
606       "Total bandwidth assigned is (in/out): %llu /%llu\n", quota_in_used,
607       quota_out_used);
608   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
609   {
610     LOG(GNUNET_ERROR_TYPE_ERROR,
611         "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
612         net->active_addresses, quota_out_used, net->total_quota_out);
613   }
614   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
615   {
616     LOG(GNUNET_ERROR_TYPE_ERROR,
617         "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
618         net->active_addresses, quota_in_used, net->total_quota_in);
619   }
620 }
621
622
623 /**
624  * Context for finding the best address* Linked list of addresses in this network: head
625  */
626 struct FindBestAddressCtx
627 {
628   /**
629    * The solver handle
630    */
631   struct GAS_PROPORTIONAL_Handle *s;
632
633   /**
634    * The currently best address
635    */
636   struct ATS_Address *best;
637 };
638
639
640 /**
641  * Find index of a ATS property type in the array.
642  */
643 static int
644 find_property_index (uint32_t type)
645 {
646   int existing_types[] = GNUNET_ATS_QualityProperties;
647   int c;
648
649   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
650     if (existing_types[c] == type)
651       return c;
652   return GNUNET_SYSERR;
653 }
654
655
656 /**
657  * Find a "good" address to use for a peer by iterating over the addresses for this peer.
658  * If we already have an existing address, we stick to it.
659  * Otherwise, we pick by lowest distance and then by lowest latency.
660  *
661  * @param cls the `struct FindBestAddressCtx *' where we store the result
662  * @param key unused
663  * @param value another `struct ATS_Address*` to consider using
664  * @return #GNUNET_OK (continue to iterate)
665  */
666 static int
667 find_best_address_it (void *cls,
668                       const struct GNUNET_PeerIdentity *key,
669                       void *value)
670 {
671   struct FindBestAddressCtx *ctx = cls;
672   struct ATS_Address *current = value;
673   struct ATS_Address *current_best = current;
674   struct AddressWrapper *asi;
675   struct GNUNET_TIME_Relative active_time;
676   struct GNUNET_TIME_Relative min_active_time;
677   double best_delay;
678   double best_distance;
679   double cur_delay;
680   double cur_distance;
681   int index;
682
683   current_best = NULL;
684   asi = current->solver_information;
685   if (NULL == asi)
686   {
687     GNUNET_break (0);
688     return GNUNET_OK;
689   }
690
691   if (GNUNET_NO == is_bandwidth_available_in_network (asi->network))
692   {
693     return GNUNET_OK; /* There's no bandwidth available in this network */
694   }
695
696   if (NULL != ctx->best)
697   {
698     /* Compare current addresses with denominated 'best' address */
699     current_best = ctx->best;
700   }
701   else
702   {
703     /* We do not have a 'best' address so take this address */
704     LOG (GNUNET_ERROR_TYPE_DEBUG,
705          "Setting initial address %p\n",
706          current);
707     current_best = current;
708     goto end;
709   }
710
711   if (GNUNET_YES == current->active)
712   {
713     GNUNET_assert (asi->activated.abs_value_us != GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us);
714     active_time = GNUNET_TIME_absolute_get_duration (asi->activated);
715     min_active_time.rel_value_us =  ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) *
716         ctx->s->stability_factor;
717     if (active_time.rel_value_us <= min_active_time.rel_value_us)
718     {
719       /* Keep active address for stability reasons */
720       ctx->best = current;
721       return GNUNET_NO;
722     }
723   }
724
725   /* Now compare ATS information */
726   index = find_property_index (GNUNET_ATS_QUALITY_NET_DISTANCE);
727   cur_distance = current->atsin[index].norm;
728   best_distance = ctx->best->atsin[index].norm;
729   index = find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
730   cur_delay = current->atsin[index].norm;
731   best_delay = ctx->best->atsin[index].norm;
732
733   /* user shorter distance */
734   if (cur_distance < best_distance)
735   {
736     if (GNUNET_NO == ctx->best->active)
737     {
738       current_best = current; /* Use current */
739     }
740     else if ((best_distance / cur_distance) > ctx->s->stability_factor)
741     {
742       /* Best and active address performs worse  */
743       current_best = current;
744     }
745   }
746   else
747   {
748     /* Use current best */
749     current_best = ctx->best;
750   }
751
752   /* User connection with less delay */
753   if (cur_delay < best_delay)
754   {
755
756     if (GNUNET_NO == ctx->best->active)
757     {
758       current_best = current; /* Use current */
759     }
760     else if ((best_delay / cur_delay) > ctx->s->stability_factor)
761     {
762       /* Best and active address performs worse  */
763       current_best = current;
764     }
765   }
766   else
767   {
768     /* Use current best */
769     current_best = ctx->best;
770   }
771
772 end:
773   ctx->best = current_best;
774   return GNUNET_OK;
775 }
776
777
778 /**
779  * Find the currently best address for a peer from the set of addresses available
780  * or return NULL of no address is available
781  *
782  * @param s the proportional handle
783  * @param addresses the address hashmap
784  * @param id the peer id
785  * @return the address or NULL
786  */
787 struct ATS_Address *
788 get_best_address (struct GAS_PROPORTIONAL_Handle *s,
789                   struct GNUNET_CONTAINER_MultiPeerMap *addresses,
790                   const struct GNUNET_PeerIdentity *id)
791 {
792   struct FindBestAddressCtx fba_ctx;
793
794   fba_ctx.best = NULL;
795   fba_ctx.s = s;
796   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
797                                               id,
798                                               &find_best_address_it,
799                                               &fba_ctx);
800   return fba_ctx.best;
801 }
802
803
804 /**
805  * Hashmap Iterator to find current active address for peer
806  *
807  * @param cls last active address
808  * @param key peer's key
809  * @param value address to check
810  * @return #GNUNET_NO on double active address else #GNUNET_YES;
811  */
812 static int
813 get_active_address_it (void *cls,
814                        const struct GNUNET_PeerIdentity *key,
815                        void *value)
816 {
817   struct ATS_Address **dest = cls;
818   struct ATS_Address *aa = (struct ATS_Address *) value;
819
820   LOG (GNUNET_ERROR_TYPE_INFO,
821          "Checking address %p\n", aa);
822
823   if (GNUNET_YES == aa->active)
824   {
825   LOG (GNUNET_ERROR_TYPE_INFO,
826          "Address %p is active\n", aa);
827     if (NULL != (*dest))
828     {
829       /* should never happen */
830       LOG (GNUNET_ERROR_TYPE_ERROR,
831            "Multiple active addresses for peer `%s'\n",
832            GNUNET_i2s (&aa->peer));
833       GNUNET_break(0);
834       return GNUNET_NO;
835     }
836     (*dest) = aa;
837
838   }
839   return GNUNET_OK;
840 }
841
842
843 /**
844  * Find current active address for peer
845  *
846  * @param solver the solver handle
847  * @param addresses the address set
848  * @param peer the peer
849  * @return active address or NULL
850  */
851 static struct ATS_Address *
852 get_active_address (void *solver,
853                     const struct GNUNET_CONTAINER_MultiPeerMap * addresses,
854                     const struct GNUNET_PeerIdentity *peer)
855 {
856   static struct ATS_Address *dest;
857
858   dest = NULL;
859   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
860                                               peer,
861                                               &get_active_address_it,
862                                               &dest);
863   return dest;
864 }
865
866
867 /**
868  * Lookup network struct by type
869  *
870  * @param s the solver handle
871  * @param type the network type
872  * @return the network struct
873  */
874 static struct Network *
875 get_network (struct GAS_PROPORTIONAL_Handle *s,
876              enum GNUNET_ATS_Network_Type type)
877 {
878   if (type >= s->env->network_count)
879   {
880     GNUNET_break (0);
881     return NULL;
882   }
883   return &s->network_entries[type];
884 }
885
886
887 /**
888  * Decrease address count in network
889  *
890  * @param s the solver handle
891  * @param net the network type
892  */
893 static void
894 address_decrement_active (struct GAS_PROPORTIONAL_Handle *s,
895                           struct Network *net)
896 {
897   if (net->active_addresses < 1)
898   {
899     GNUNET_break (0);
900   }
901   else
902   {
903     net->active_addresses--;
904     GNUNET_STATISTICS_update (s->env->stats,
905                               net->stat_active, -1, GNUNET_NO);
906   }
907   if (s->active_addresses < 1)
908   {
909     GNUNET_break (0);
910   }
911   else
912   {
913     s->active_addresses--;
914     GNUNET_STATISTICS_update (s->env->stats,
915                               "# ATS addresses total",
916                               -1,
917                               GNUNET_NO);
918   }
919 }
920
921
922 /**
923  * Compares addresses
924  *
925  * @param a address a
926  * @param b address b
927  * @return GNUNET_YES if equal, GNUNET_NO else
928  */
929 static int
930 address_eq (struct ATS_Address *a, struct ATS_Address *b)
931 {
932   GNUNET_assert (NULL != a);
933   GNUNET_assert (NULL != b);
934   if (0 != strcmp(a->plugin, b->plugin))
935     return GNUNET_NO;
936   if (a->addr_len != b->addr_len)
937     return GNUNET_NO;
938   if (0 != memcmp (a->addr, b->addr, b->addr_len))
939     return GNUNET_NO;
940   if (a->session_id != b->session_id)
941     return GNUNET_NO;
942   return GNUNET_YES;
943 }
944
945
946 /**
947  * Notify bandwidth changes to addresses
948  *
949  * @param s solver handle
950  * @param net the network to propagate changes in
951  */
952 static void
953 propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s,
954                      struct Network *net)
955 {
956   struct AddressWrapper *cur;
957
958   for (cur = net->head; NULL != cur; cur = cur->next)
959   {
960       if ( (cur->addr->assigned_bw_in != cur->calculated_quota_in) ||
961            (cur->addr->assigned_bw_out != cur->calculated_quota_out) )
962       {
963         cur->addr->assigned_bw_in = cur->calculated_quota_in;
964         cur->addr->assigned_bw_out = cur->calculated_quota_out;
965
966         /* Reset for next iteration */
967         cur->calculated_quota_in = 0;
968         cur->calculated_quota_out = 0;
969         LOG (GNUNET_ERROR_TYPE_DEBUG,
970             "Bandwidth for %s address %p for peer `%s' changed to %u/%u\n",
971             (GNUNET_NO == cur->addr->active) ? "inactive" : "active",
972             cur->addr,
973             GNUNET_i2s (&cur->addr->peer),
974             cur->addr->assigned_bw_in,
975             cur->addr->assigned_bw_out);
976
977         /* Notify on change */
978         if ((GNUNET_YES == cur->addr->active))
979         {
980           s->env->bandwidth_changed_cb (s->env->cls,
981                                         cur->addr);
982         }
983       }
984   }
985 }
986
987
988 /**
989  * Distribibute bandwidth
990  *
991  * @param s the solver handle
992  * @param n the network, can be NULL for all network
993  */
994 static void
995 distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s,
996                                  struct Network *n)
997 {
998   if (GNUNET_YES == s->bulk_lock)
999   {
1000     s->bulk_requests++;
1001     return;
1002   }
1003
1004   if (NULL != n)
1005   {
1006     LOG (GNUNET_ERROR_TYPE_INFO,
1007         "Redistributing bandwidth in network %s with %u active and %u total addresses\n",
1008          GNUNET_ATS_print_network_type(n->type),
1009          n->active_addresses,
1010          n->total_addresses);
1011
1012     s->env->info_cb (s->env->cls,
1013                      GAS_OP_SOLVE_START,
1014                      GAS_STAT_SUCCESS,
1015                      GAS_INFO_PROP_SINGLE);
1016
1017     /* Distribute  */
1018     distribute_bandwidth(s, n);
1019
1020     s->env->info_cb (s->env->cls,
1021                      GAS_OP_SOLVE_STOP,
1022                      GAS_STAT_SUCCESS,
1023                      GAS_INFO_PROP_SINGLE);
1024     s->env->info_cb (s->env->cls,
1025                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1026                      GAS_STAT_SUCCESS,
1027                      GAS_INFO_PROP_SINGLE);
1028
1029     /* Do propagation */
1030     propagate_bandwidth (s, n);
1031
1032     s->env->info_cb (s->env->cls,
1033                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1034                      GAS_STAT_SUCCESS,
1035                      GAS_INFO_PROP_SINGLE);
1036   }
1037   else
1038   {
1039     int i;
1040     s->env->info_cb (s->env->cls,
1041                      GAS_OP_SOLVE_START,
1042                      GAS_STAT_SUCCESS,
1043                      GAS_INFO_PROP_ALL);
1044     for (i = 0; i < s->network_count; i++)
1045     {
1046       /* Distribute */
1047       distribute_bandwidth(s, &s->network_entries[i]);
1048     }
1049
1050     s->env->info_cb (s->env->cls,
1051                      GAS_OP_SOLVE_STOP,
1052                      GAS_STAT_SUCCESS,
1053                      GAS_INFO_PROP_ALL);
1054     s->env->info_cb (s->env->cls,
1055                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1056                      GAS_STAT_SUCCESS,
1057                      GAS_INFO_PROP_ALL);
1058     for (i = 0; i < s->network_count; i++)
1059     {
1060       /* Do propagation */
1061       propagate_bandwidth(s, &s->network_entries[i]);
1062     }
1063     s->env->info_cb (s->env->cls,
1064                      GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1065                      GAS_STAT_SUCCESS,
1066                      GAS_INFO_PROP_ALL);
1067   }
1068 }
1069
1070
1071 /**
1072  * Update active address for a peer:
1073  * Check if active address exists and what the best address is, if addresses
1074  * are different switch
1075  *
1076  * @param s solver handle
1077  * @param peer the peer to check
1078  * return the new address or NULL if no update was performed
1079   */
1080 static struct ATS_Address *
1081 update_active_address (struct GAS_PROPORTIONAL_Handle *s,
1082                        const struct GNUNET_PeerIdentity *peer)
1083 {
1084   struct ATS_Address *best_address;
1085   struct ATS_Address *current_address;
1086   struct AddressWrapper *asi;
1087   struct Network *net;
1088
1089   LOG (GNUNET_ERROR_TYPE_INFO,
1090        "Updating active address for peer `%s'\n",
1091        GNUNET_i2s (peer));
1092
1093   /* Find active address */
1094   current_address = get_active_address (s,
1095                                         s->env->addresses,
1096                                         peer);
1097
1098   LOG (GNUNET_ERROR_TYPE_INFO,
1099        "Peer `%s' has active address %p\n",
1100        GNUNET_i2s (peer),
1101        current_address);
1102
1103   /* Find best address */
1104   best_address = get_best_address (s,
1105                                    s->env->addresses,
1106                                    peer);
1107   LOG (GNUNET_ERROR_TYPE_INFO,
1108        "Peer `%s' has best address %p\n",
1109        GNUNET_i2s (peer),
1110        best_address);
1111
1112   if (NULL != current_address)
1113   {
1114     GNUNET_assert (GNUNET_YES == current_address->active);
1115     if ( (NULL == best_address) ||
1116          ( (NULL != best_address) &&
1117            (GNUNET_NO == address_eq (current_address,
1118                                      best_address)) ) )
1119     {
1120       /* We switch to a new address (or to none),
1121          mark old address as inactive */
1122       LOG (GNUNET_ERROR_TYPE_INFO,
1123            "Disabling previous %s address %p for peer `%s'\n",
1124            (GNUNET_NO == current_address->active) ? "inactive" : "active",
1125            current_address,
1126            GNUNET_i2s (peer));
1127
1128       asi = current_address->solver_information;
1129       net = asi->network;
1130       asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1131       current_address->active = GNUNET_NO; /* No active any longer */
1132       current_address->assigned_bw_in = 0; /* no bandwidth assigned */
1133       current_address->assigned_bw_out = 0; /* no bandwidth assigned */
1134       address_decrement_active (s, net);
1135       distribute_bandwidth_in_network (s, net);
1136     }
1137     if (NULL == best_address)
1138     {
1139       /* We previously had an active address, but now we cannot suggest one
1140        * Therefore we have to disconnect the peer */
1141       LOG (GNUNET_ERROR_TYPE_INFO,
1142            "Disconnecting peer `%s' with previous address %p\n",
1143            GNUNET_i2s (peer),
1144            current_address);
1145       s->env->bandwidth_changed_cb (s->env->cls,
1146                                     current_address);
1147     }
1148   }
1149   if (NULL == best_address)
1150   {
1151     LOG (GNUNET_ERROR_TYPE_INFO,
1152          "Cannot suggest address for peer `%s'\n",
1153          GNUNET_i2s (peer));
1154     return NULL;
1155   }
1156
1157   LOG (GNUNET_ERROR_TYPE_INFO,
1158        "Suggesting new address %p for peer `%s'\n",
1159        best_address,
1160        GNUNET_i2s (peer));
1161
1162   if ( (NULL != current_address) &&
1163        (GNUNET_YES == address_eq (best_address, current_address)) )
1164   {
1165     GNUNET_break (GNUNET_NO != current_address->active);
1166     return best_address; /* Same same */
1167   }
1168
1169   asi = best_address->solver_information;
1170   GNUNET_assert (NULL != asi);
1171   net = asi->network;
1172
1173   /* Mark address as active */
1174   asi->activated = GNUNET_TIME_absolute_get ();
1175   best_address->active = GNUNET_YES;
1176
1177   net->active_addresses++;
1178   s->active_addresses++;
1179   GNUNET_STATISTICS_update (s->env->stats,
1180                             "# ATS active addresses total",
1181                             1,
1182                             GNUNET_NO);
1183   GNUNET_STATISTICS_update (s->env->stats,
1184                             net->stat_active,
1185                             1,
1186                             GNUNET_NO);
1187   LOG (GNUNET_ERROR_TYPE_INFO,
1188        "Address %p for peer `%s' is now active\n",
1189        best_address,
1190        GNUNET_i2s (peer));
1191   /* Distribute bandwidth */
1192   distribute_bandwidth_in_network (s, net);
1193   return best_address;
1194 }
1195
1196
1197 /**
1198  * Changes the preferences for a peer in the problem
1199  *
1200  * @param solver the solver handle
1201  * @param peer the peer to change the preference for
1202  * @param kind the kind to change the preference
1203  * @param pref_rel the normalized preference value for this kind over all clients
1204  */
1205 static void
1206 GAS_proportional_address_change_preference (void *solver,
1207                                             const struct GNUNET_PeerIdentity *peer,
1208                                             enum GNUNET_ATS_PreferenceKind kind,
1209                                             double pref_rel)
1210 {
1211   struct GAS_PROPORTIONAL_Handle *s = solver;
1212   struct ATS_Address *best_address;
1213   struct ATS_Address *active_address;
1214   struct AddressWrapper *asi;
1215
1216   if (0 ==
1217       s->env->get_connectivity (s->env->cls,
1218                                 peer))
1219     return; /* Peer is not requested */
1220
1221   /* This peer is requested, find best address */
1222   active_address = get_active_address (s,
1223                                        s->env->addresses,
1224                                        peer);
1225   best_address = update_active_address (s, peer);
1226
1227   if ((NULL != best_address) && ((NULL != active_address) &&
1228       (GNUNET_YES == address_eq (active_address, best_address))))
1229   {
1230     asi = best_address->solver_information;
1231     GNUNET_assert (NULL != asi);
1232
1233     /* We sticked to the same address, therefore redistribute  */
1234     distribute_bandwidth_in_network (s, asi->network);
1235   }
1236 }
1237
1238
1239 /**
1240  * Get application feedback for a peer
1241  *
1242  * @param solver the solver handle
1243  * @param application the application
1244  * @param peer the peer to change the preference for
1245  * @param scope the time interval for this feedback: [now - scope .. now]
1246  * @param kind the kind to change the preference
1247  * @param score the score
1248  */
1249 static void
1250 GAS_proportional_address_preference_feedback (void *solver,
1251                                               struct GNUNET_SERVER_Client *application,
1252                                               const struct GNUNET_PeerIdentity *peer,
1253                                               const struct GNUNET_TIME_Relative scope,
1254                                               enum GNUNET_ATS_PreferenceKind kind,
1255                                               double score)
1256 {
1257   struct GAS_PROPORTIONAL_Handle *s = solver;
1258
1259   GNUNET_assert(NULL != peer);
1260   GNUNET_assert(NULL != s);
1261 }
1262
1263
1264 /**
1265  * Get the preferred address for a specific peer
1266  *
1267  * @param solver the solver handle
1268  * @param peer the identity of the peer
1269  * @return best address
1270  */
1271 static const struct ATS_Address *
1272 GAS_proportional_get_preferred_address (void *solver,
1273                                         const struct GNUNET_PeerIdentity *peer)
1274 {
1275   struct GAS_PROPORTIONAL_Handle *s = solver;
1276   const struct ATS_Address *best_address;
1277
1278   best_address = update_active_address (s, peer);
1279   if (s->bulk_lock > 0)
1280     return NULL;
1281   return best_address;
1282 }
1283
1284
1285 /**
1286  * Stop notifying about address and bandwidth changes for this peer
1287  *
1288  * @param solver the solver handle
1289  * @param peer the peer
1290  */
1291 static void
1292 GAS_proportional_stop_get_preferred_address (void *solver,
1293                                              const struct GNUNET_PeerIdentity *peer)
1294 {
1295   struct GAS_PROPORTIONAL_Handle *s = solver;
1296   struct ATS_Address *cur;
1297   struct AddressWrapper *asi;
1298   struct Network *cur_net;
1299
1300   cur = get_active_address (s,
1301                             s->env->addresses,
1302                             peer);
1303   if (NULL != cur)
1304   {
1305     LOG (GNUNET_ERROR_TYPE_INFO,
1306          "Disabling %s address %p for peer `%s'\n",
1307          (GNUNET_NO == cur->active) ? "inactive" : "active",
1308          cur,
1309          GNUNET_i2s (&cur->peer));
1310
1311     /* Disabling current address */
1312     asi = cur->solver_information;
1313     cur_net = asi->network;
1314     asi->activated = GNUNET_TIME_UNIT_ZERO_ABS;
1315     cur->active = GNUNET_NO; /* No active any longer */
1316     cur->assigned_bw_in = 0; /* no bandwidth assigned */
1317     cur->assigned_bw_out = 0; /* no bandwidth assigned */
1318
1319     address_decrement_active (s, cur_net);
1320
1321     distribute_bandwidth_in_network (s, cur_net);
1322   }
1323 }
1324
1325
1326 /**
1327  * Start a bulk operation
1328  *
1329  * @param solver the solver
1330  */
1331 static void
1332 GAS_proportional_bulk_start (void *solver)
1333 {
1334   struct GAS_PROPORTIONAL_Handle *s = solver;
1335
1336   LOG (GNUNET_ERROR_TYPE_DEBUG,
1337        "Locking solver for bulk operation ...\n");
1338   GNUNET_assert (NULL != solver);
1339   s->bulk_lock++;
1340 }
1341
1342
1343 /**
1344  * Bulk operation done
1345  */
1346 static void
1347 GAS_proportional_bulk_stop (void *solver)
1348 {
1349   struct GAS_PROPORTIONAL_Handle *s = solver;
1350
1351   LOG (GNUNET_ERROR_TYPE_DEBUG,
1352        "Unlocking solver from bulk operation ...\n");
1353   if (s->bulk_lock < 1)
1354   {
1355     GNUNET_break(0);
1356     return;
1357   }
1358   s->bulk_lock--;
1359   if ((0 == s->bulk_lock) && (0 < s->bulk_requests))
1360   {
1361     LOG (GNUNET_ERROR_TYPE_INFO,
1362          "No lock pending, recalculating\n");
1363     distribute_bandwidth_in_network (s, NULL);
1364     s->bulk_requests = 0;
1365   }
1366 }
1367
1368
1369 /**
1370  * Transport properties for this address have changed
1371  *
1372  * @param solver solver handle
1373  * @param address the address
1374  * @param type the ATSI type in HBO
1375  * @param abs_value the absolute value of the property
1376  * @param rel_value the normalized value
1377  */
1378 static void
1379 GAS_proportional_address_property_changed (void *solver,
1380                                            struct ATS_Address *address,
1381                                            enum GNUNET_ATS_Property type,
1382                                            uint32_t abs_value,
1383                                            double rel_value)
1384 {
1385   struct GAS_PROPORTIONAL_Handle *s = solver;
1386   struct Network *n;
1387   struct AddressWrapper *asi;
1388   struct ATS_Address *best_address;
1389   struct ATS_Address *active_address;
1390
1391   asi = address->solver_information;
1392   if (NULL == asi)
1393   {
1394     GNUNET_break(0);
1395     return;
1396   }
1397
1398   n = asi->network;
1399   if (NULL == n)
1400   {
1401     GNUNET_break(0);
1402     return;
1403   }
1404
1405   LOG (GNUNET_ERROR_TYPE_INFO,
1406        "Property `%s' for peer `%s' address %p changed to %.2f \n",
1407        GNUNET_ATS_print_property_type (type),
1408        GNUNET_i2s (&address->peer),
1409        address,
1410        rel_value);
1411
1412   if (0 ==
1413       s->env->get_connectivity (s->env->cls,
1414                                 &address->peer))
1415     return; /* Peer is not requested */
1416
1417   /* This peer is requested, find active and best address */
1418   active_address = get_active_address(s,
1419                                       s->env->addresses,
1420                                       &address->peer);
1421   best_address = update_active_address (s,
1422                                         &address->peer);
1423
1424   if ((NULL != best_address) && ((NULL != active_address) &&
1425       (GNUNET_YES == address_eq (active_address, best_address))))
1426   {
1427     asi = best_address->solver_information;
1428     GNUNET_assert (NULL != asi);
1429
1430     /* We sticked to the same address, therefore redistribute  */
1431     distribute_bandwidth_in_network (s, asi->network);
1432   }
1433 }
1434
1435
1436 /**
1437  * Add a new single address to a network
1438  *
1439  * @param solver the solver Handle
1440  * @param address the address to add
1441  * @param network network type of this address
1442  */
1443 static void
1444 GAS_proportional_address_add (void *solver,
1445                               struct ATS_Address *address,
1446                               enum GNUNET_ATS_Network_Type network)
1447 {
1448   struct GAS_PROPORTIONAL_Handle *s = solver;
1449   struct Network *net;
1450   struct AddressWrapper *aw;
1451
1452   net = get_network (s,
1453                      network);
1454   if (NULL == net)
1455   {
1456     GNUNET_break (0);
1457     return;
1458   }
1459
1460   aw = GNUNET_new (struct AddressWrapper);
1461   aw->addr = address;
1462   GNUNET_CONTAINER_DLL_insert (net->head,
1463                                net->tail,
1464                                aw);
1465   net->total_addresses++;
1466   GNUNET_STATISTICS_update (s->env->stats,
1467                             "# ATS addresses total",
1468                             1,
1469                             GNUNET_NO);
1470   GNUNET_STATISTICS_update (s->env->stats,
1471                             net->stat_total,
1472                             1,
1473                             GNUNET_NO);
1474   aw->network = net;
1475   address->solver_information = aw;
1476
1477   LOG (GNUNET_ERROR_TYPE_INFO,
1478        "Adding new address %p for peer `%s', now total %u and active %u addresses in network `%s'\n",
1479        address,
1480        GNUNET_i2s (&address->peer),
1481        net->total_addresses,
1482        net->active_addresses,
1483        net->desc);
1484
1485   if (0 ==
1486       s->env->get_connectivity (s->env->cls,
1487                                 &address->peer))
1488     return; /* Peer is not requested */
1489
1490   /* This peer is requested, find best address */
1491   update_active_address (s,
1492                          &address->peer);
1493 }
1494
1495
1496 /**
1497  * Remove an address from the solver. To do so, we:
1498  * - Removed it from specific network
1499  * - Decrease the number of total addresses
1500  * - If active:
1501  *   - decrease number of active addreses
1502  *   - update quotas
1503  *
1504  * @param solver the solver handle
1505  * @param address the address to remove
1506  */
1507 static void
1508 GAS_proportional_address_delete (void *solver,
1509                                  struct ATS_Address *address)
1510 {
1511   struct GAS_PROPORTIONAL_Handle *s = solver;
1512   struct AddressWrapper *aw = address->solver_information;
1513   struct Network *net = aw->network;
1514
1515   LOG (GNUNET_ERROR_TYPE_DEBUG,
1516        "Deleting %s address for peer `%s' from network `%s' (total: %u/active: %u)\n",
1517        (GNUNET_NO == address->active) ? "inactive" : "active",
1518        GNUNET_i2s (&address->peer),
1519        net->desc,
1520        net->total_addresses,
1521        net->active_addresses);
1522
1523   /* Remove address */
1524   GNUNET_CONTAINER_DLL_remove (net->head,
1525                                net->tail,
1526                                aw);
1527   GNUNET_assert (net->total_addresses > 0);
1528   net->total_addresses--;
1529   GNUNET_STATISTICS_update (s->env->stats,
1530                             net->stat_total,
1531                             -1,
1532                             GNUNET_NO);
1533   if (GNUNET_YES == address->active)
1534   {
1535     /* Address was active, remove from network and update quotas*/
1536     address->active = GNUNET_NO;
1537     address->assigned_bw_in = 0;
1538     address->assigned_bw_out = 0;
1539     address_decrement_active (s, net);
1540     /* FIXME: this may trigger the solver unnecessarily,
1541        especially if update_active_address() succeeds! */
1542     distribute_bandwidth_in_network (s, net);
1543
1544     if (NULL ==
1545         update_active_address (s,
1546                                &address->peer))
1547     {
1548       /* No alternative address found, disconnect peer */
1549       LOG (GNUNET_ERROR_TYPE_INFO,
1550            "Disconnecting peer `%s' after deleting previous address %p\n",
1551            GNUNET_i2s (&address->peer),
1552            address);
1553       s->env->bandwidth_changed_cb (s->env->cls,
1554                                     address);
1555     }
1556   }
1557   GNUNET_free (aw);
1558   address->solver_information = NULL;
1559   LOG (GNUNET_ERROR_TYPE_DEBUG,
1560        "After deleting address now total %u and active %u addresses in network `%s'\n",
1561        net->total_addresses,
1562        net->active_addresses,
1563        net->desc);
1564 }
1565
1566
1567 /**
1568  * Function invoked when the plugin is loaded.
1569  *
1570  * @param[in,out] cls the `struct GNUNET_ATS_PluginEnvironment *` to use;
1571  *            modified to return the API functions (ugh).
1572  * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure
1573  */
1574 void *
1575 libgnunet_plugin_ats_proportional_init (void *cls)
1576 {
1577   static struct GNUNET_ATS_SolverFunctions sf;
1578   struct GNUNET_ATS_PluginEnvironment *env = cls;
1579   struct GAS_PROPORTIONAL_Handle *s;
1580   struct Network * cur;
1581   float f_tmp;
1582   unsigned int c;
1583
1584   s = GNUNET_new (struct GAS_PROPORTIONAL_Handle);
1585   s->env = env;
1586   sf.cls = s;
1587   sf.s_add = &GAS_proportional_address_add;
1588   sf.s_address_update_property = &GAS_proportional_address_property_changed;
1589   sf.s_get = &GAS_proportional_get_preferred_address;
1590   sf.s_get_stop = &GAS_proportional_stop_get_preferred_address;
1591   sf.s_pref = &GAS_proportional_address_change_preference;
1592   sf.s_feedback = &GAS_proportional_address_preference_feedback;
1593   sf.s_del = &GAS_proportional_address_delete;
1594   sf.s_bulk_start = &GAS_proportional_bulk_start;
1595   sf.s_bulk_stop = &GAS_proportional_bulk_stop;
1596   s->stability_factor = PROP_STABILITY_FACTOR;
1597   if (GNUNET_SYSERR !=
1598       GNUNET_CONFIGURATION_get_value_float (env->cfg,
1599                                             "ats",
1600                                             "PROP_STABILITY_FACTOR",
1601                                             &f_tmp))
1602   {
1603     if ((f_tmp < 1.0) || (f_tmp > 2.0))
1604     {
1605       LOG (GNUNET_ERROR_TYPE_ERROR,
1606            _("Invalid %s configuration %f \n"),
1607            "PROP_STABILITY_FACTOR",
1608            f_tmp);
1609     }
1610     else
1611     {
1612       s->stability_factor = f_tmp;
1613       LOG (GNUNET_ERROR_TYPE_INFO,
1614            "Using %s of %.3f\n",
1615            "PROP_STABILITY_FACTOR",
1616            f_tmp);
1617     }
1618   }
1619   s->prop_factor = PROPORTIONALITY_FACTOR;
1620   if (GNUNET_SYSERR !=
1621       GNUNET_CONFIGURATION_get_value_float (env->cfg,
1622                                             "ats",
1623                                             "PROP_PROPORTIONALITY_FACTOR",
1624                                             &f_tmp))
1625   {
1626     if (f_tmp < 1.0)
1627     {
1628       LOG (GNUNET_ERROR_TYPE_ERROR,
1629            _("Invalid %s configuration %f\n"),
1630            "PROP_PROPORTIONALITY_FACTOR",
1631            f_tmp);
1632     }
1633     else
1634     {
1635       s->prop_factor = f_tmp;
1636       LOG (GNUNET_ERROR_TYPE_INFO,
1637            "Using %s of %.3f\n",
1638            "PROP_PROPORTIONALITY_FACTOR"
1639            , f_tmp);
1640     }
1641   }
1642
1643   s->network_entries = GNUNET_malloc (env->network_count *
1644                                       sizeof (struct Network));
1645   for (c = 0; c < env->network_count; c++)
1646   {
1647     cur = &s->network_entries[c];
1648     cur->type = c;
1649     cur->total_quota_in = env->in_quota[c];
1650     cur->total_quota_out = env->out_quota[c];
1651     cur->desc = GNUNET_ATS_print_network_type (c);
1652     GNUNET_asprintf (&cur->stat_total,
1653                      "# ATS addresses %s total",
1654                      cur->desc);
1655     GNUNET_asprintf (&cur->stat_active,
1656                      "# ATS active addresses %s total",
1657                      cur->desc);
1658     LOG (GNUNET_ERROR_TYPE_INFO,
1659          "Added network %u `%s' (%llu/%llu)\n",
1660          c,
1661          cur->desc,
1662          cur->total_quota_in,
1663          cur->total_quota_out);
1664   }
1665   return &sf;
1666 }
1667
1668
1669 /* end of plugin_ats_proportional.c */