docu
[oweals/gnunet.git] / src / ats / gnunet-service-ats_addresses_simplistic.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_addresses_simplistic.h
23  * @brief ats simplistic ressource assignment
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-simplistic",__VA_ARGS__)
33
34 /**
35  * ATS simplistic solver
36  *
37  * Assigns in and outbound bandwidth equally for all addresses in specific
38  * network type (WAN, LAN) based on configured in and outbound quota for this
39  * network.
40  *
41  * For each peer only a single is selected and marked as "active" in the address
42  * struct.
43  *
44  * E.g.:
45  *
46  * You have the networks WAN and LAN and quotas
47  * WAN_TOTAL_IN, WAN_TOTAL_OUT
48  * LAN_TOTAL_IN, LAN_TOTAL_OUT
49  *
50  * If you have x addresses in the network segment LAN, the quotas are
51  * QUOTA_PER_ADDRESS = LAN_TOTAL_OUT / x
52  *
53  * Quotas are automatically recalculated and reported back when addresses are
54  * - requested
55  *
56  */
57
58 #define PREF_AGING_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
59 #define PREF_AGING_FACTOR 0.95
60
61 #define DEFAULT_PREFERENCE 1.0
62 #define MIN_UPDATE_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
63
64 /**
65  * A handle for the simplistic solver
66  */
67 struct GAS_SIMPLISTIC_Handle
68 {
69   /**
70    * Statistics handle
71    */
72
73   struct GNUNET_STATISTICS_Handle *stats;
74
75   /**
76    * Total number of addresses for solver
77    */
78   unsigned int total_addresses;
79
80   /**
81    * Number of active addresses for solver
82    */
83   unsigned int active_addresses;
84
85   /**
86    * Networks array
87    */
88   struct Network *network_entries;
89
90   /**
91    * Number of networks
92    */
93   unsigned int networks;
94
95   /**
96    * Callback
97    */
98   GAS_bandwidth_changed_cb bw_changed;
99
100   /**
101    * Callback cls
102    */
103   void *bw_changed_cls;
104
105   struct GNUNET_CONTAINER_MultiHashMap *prefs;
106
107   struct PreferenceClient *pc_head;
108   struct PreferenceClient *pc_tail;
109 };
110
111 struct Network
112 {
113   /**
114    * ATS network type
115    */
116   unsigned int type;
117
118   /**
119    * Network description
120    */
121   char *desc;
122
123   /**
124    * Total inbound quota
125    *
126    */
127   unsigned long long total_quota_in;
128
129   /**
130    * Total outbound quota
131    *
132    */
133   unsigned long long total_quota_out;
134
135   /**
136    * Number of active addresses for this network
137    */
138   unsigned int active_addresses;
139
140   /**
141    * Number of total addresses for this network
142    */
143   unsigned int total_addresses;
144
145   /**
146    * String for statistics total addresses
147    */
148   char *stat_total;
149
150   /**
151    * String for statistics active addresses
152    */
153   char *stat_active;
154
155   struct AddressWrapper *head;
156   struct AddressWrapper *tail;
157 };
158
159 struct AddressWrapper
160 {
161   struct AddressWrapper *next;
162   struct AddressWrapper *prev;
163
164   struct ATS_Address *addr;
165 };
166
167
168 struct PreferenceClient
169 {
170   struct PreferenceClient *prev;
171   struct PreferenceClient *next;
172   void *client;
173
174   double f_total[GNUNET_ATS_PreferenceCount];
175
176   struct PreferencePeer *p_head;
177   struct PreferencePeer *p_tail;
178 };
179
180
181 struct PreferencePeer
182 {
183   struct PreferencePeer *next;
184   struct PreferencePeer *prev;
185   struct PreferenceClient *client;
186   struct GAS_SIMPLISTIC_Handle *s;
187   struct GNUNET_PeerIdentity id;
188
189   double f[GNUNET_ATS_PreferenceCount];
190   double f_rel[GNUNET_ATS_PreferenceCount];
191   double f_rel_total;
192
193   GNUNET_SCHEDULER_TaskIdentifier aging_task;
194 };
195
196 /**
197  * Get the prefered address for a specific peer
198  *
199  * @param solver the solver handle
200  * @param addresses the address hashmap containing all addresses
201  * @param peer the identity of the peer
202  */
203 const struct ATS_Address *
204 GAS_simplistic_get_preferred_address (void *solver,
205                                struct GNUNET_CONTAINER_MultiHashMap * addresses,
206                                const struct GNUNET_PeerIdentity *peer);
207
208 /**
209  * Init the simplistic problem solving component
210  *
211  * Quotas:
212  * network[i] contains the network type as type GNUNET_ATS_NetworkType[i]
213  * out_quota[i] contains outbound quota for network type i
214  * in_quota[i] contains inbound quota for network type i
215  *
216  * Example
217  * network = {GNUNET_ATS_NET_UNSPECIFIED, GNUNET_ATS_NET_LOOPBACK, GNUNET_ATS_NET_LAN, GNUNET_ATS_NET_WAN, GNUNET_ATS_NET_WLAN}
218  * network[2]   == GNUNET_ATS_NET_LAN
219  * out_quota[2] == 65353
220  * in_quota[2]  == 65353
221  *
222  * @param cfg configuration handle
223  * @param stats the GNUNET_STATISTICS handle
224  * @param network array of GNUNET_ATS_NetworkType with length dest_length
225  * @param out_quota array of outbound quotas
226  * @param in_quota array of outbound quota
227  * @param dest_length array length for quota arrays
228  * @param bw_changed_cb callback for changed bandwidth amounts
229  * @param bw_changed_cb_cls cls for callback
230  * @return handle for the solver on success, NULL on fail
231  */
232 void *
233 GAS_simplistic_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
234                      const struct GNUNET_STATISTICS_Handle *stats,
235                      int *network,
236                      unsigned long long *out_quota,
237                      unsigned long long *in_quota,
238                      int dest_length,
239                      GAS_bandwidth_changed_cb bw_changed_cb,
240                      void *bw_changed_cb_cls)
241 {
242   int c;
243   struct GAS_SIMPLISTIC_Handle *s = GNUNET_malloc (sizeof (struct GAS_SIMPLISTIC_Handle));
244   struct Network * cur;
245   char * net_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
246
247
248   s->stats = (struct GNUNET_STATISTICS_Handle *) stats;
249   s->bw_changed = bw_changed_cb;
250   s->bw_changed_cls = bw_changed_cb_cls;
251   s->networks = dest_length;
252   s->network_entries = GNUNET_malloc (dest_length * sizeof (struct Network));
253   s->active_addresses = 0;
254   s->total_addresses = 0;
255   s->prefs = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
256
257   for (c = 0; c < dest_length; c++)
258   {
259       cur = &s->network_entries[c];
260       cur->total_addresses = 0;
261       cur->active_addresses = 0;
262       cur->type = network[c];
263       cur->total_quota_in = in_quota[c];
264       cur->total_quota_out = out_quota[c];
265       cur->desc = net_str[c];
266       GNUNET_asprintf (&cur->stat_total, "# ATS addresses %s total", cur->desc);
267       GNUNET_asprintf (&cur->stat_active, "# ATS active addresses %s total", cur->desc);
268   }
269   return s;
270 }
271
272 static int
273 free_pref (void *cls,
274            const struct GNUNET_HashCode * key,
275            void *value)
276 {
277   float *v = value;
278   GNUNET_free (v);
279   return GNUNET_OK;
280 }
281
282 /**
283  * Shutdown the simplistic problem solving component
284  *
285  * @param solver the respective handle to shutdown
286  */
287 void
288 GAS_simplistic_done (void *solver)
289 {
290   struct GAS_SIMPLISTIC_Handle *s = solver;
291   struct PreferenceClient *pc;
292   struct PreferenceClient *next_pc;
293   struct PreferencePeer *p;
294   struct PreferencePeer *next_p;
295   struct AddressWrapper *cur;
296   struct AddressWrapper *next;
297   int c;
298   GNUNET_assert (s != NULL);
299
300   for (c = 0; c < s->networks; c++)
301   {
302       if (s->network_entries[c].total_addresses > 0)
303       {
304         LOG (GNUNET_ERROR_TYPE_ERROR,
305                     "Had %u addresses for network `%s' not deleted during shutdown\n",
306                     s->network_entries[c].total_addresses,
307                     s->network_entries[c].desc);
308         GNUNET_break (0);
309       }
310
311       if (s->network_entries[c].active_addresses > 0)
312       {
313         LOG (GNUNET_ERROR_TYPE_ERROR,
314                     "Had %u active addresses for network `%s' not deleted during shutdown\n",
315                     s->network_entries[c].active_addresses,
316                     s->network_entries[c].desc);
317         GNUNET_break (0);
318       }
319
320       next = s->network_entries[c].head;
321       while (NULL != (cur = next))
322       {
323           next = cur->next;
324           GNUNET_CONTAINER_DLL_remove (s->network_entries[c].head,
325                                        s->network_entries[c].tail,
326                                        cur);
327           GNUNET_free (cur);
328       }
329       GNUNET_free (s->network_entries[c].stat_total);
330       GNUNET_free (s->network_entries[c].stat_active);
331   }
332   if (s->total_addresses > 0)
333   {
334     LOG (GNUNET_ERROR_TYPE_ERROR,
335                 "Had %u addresses not deleted during shutdown\n",
336                 s->total_addresses);
337     GNUNET_break (0);
338   }
339   if (s->active_addresses > 0)
340   {
341     LOG (GNUNET_ERROR_TYPE_ERROR,
342                 "Had %u active addresses not deleted during shutdown\n",
343                 s->active_addresses);
344     GNUNET_break (0);
345   }
346   GNUNET_free (s->network_entries);
347
348   next_pc = s->pc_head;
349   while (NULL != (pc = next_pc))
350   {
351       next_pc = pc->next;
352       GNUNET_CONTAINER_DLL_remove (s->pc_head, s->pc_tail, pc);
353       next_p = pc->p_head;
354       while (NULL != (p = next_p))
355       {
356           next_p = p->next;
357           if (GNUNET_SCHEDULER_NO_TASK != p->aging_task)
358           {
359                 GNUNET_SCHEDULER_cancel(p->aging_task);
360                 p->aging_task = GNUNET_SCHEDULER_NO_TASK;
361           }
362           GNUNET_CONTAINER_DLL_remove (pc->p_head, pc->p_tail, p);
363           GNUNET_free (p);
364       }
365       GNUNET_free (pc);
366   }
367
368   GNUNET_CONTAINER_multihashmap_iterate (s->prefs, &free_pref, NULL);
369   GNUNET_CONTAINER_multihashmap_destroy (s->prefs);
370   GNUNET_free (s);
371 }
372
373
374 /**
375  * Test if bandwidth is available in this network
376  *
377  * @param s the solver handle
378  * @param net the network type to update
379  * @return GNUNET_YES or GNUNET_NO
380  */
381
382 static int
383 bw_available_in_network (struct Network *net)
384 {
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 the quotas for a network type
407  *
408  * @param s the solver handle
409  * @param net the network type to update
410  * @param address_except address excluded from notifcation, since we suggest
411  * this address
412  */
413 static void
414 update_quota_per_network (struct GAS_SIMPLISTIC_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 total_prefs; /* Important: has to be double not float due to precision */
425   double cur_pref; /* Important: has to be double not float due to precision */
426   double *t = NULL; /* Important: has to be double not float due to precision */
427
428   unsigned long long assigned_quota_in = 0;
429   unsigned long long assigned_quota_out = 0;
430   struct AddressWrapper *cur;
431
432   LOG (GNUNET_ERROR_TYPE_DEBUG,
433               "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
434               net->desc, net->active_addresses, net->total_quota_in, net->total_quota_in);
435
436   if (net->active_addresses == 0)
437     return; /* no addresses to update */
438
439   /* Idea TODO
440    *
441    * Assign every peer in network minimum Bandwidth
442    * Distribute bandwidth left according to preference
443    */
444
445   if ((net->active_addresses * min_bw) > net->total_quota_in)
446   {
447     GNUNET_break (0);
448     return;
449   }
450   if ((net->active_addresses * min_bw) > net->total_quota_out)
451   {
452     GNUNET_break (0);
453     return;
454   }
455
456   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
457   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
458   LOG (GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
459               remaining_quota_in, remaining_quota_out);
460   total_prefs = 0.0;
461   for (cur = net->head; NULL != cur; cur = cur->next)
462   {
463       if (GNUNET_YES == cur->addr->active)
464       {
465         t = GNUNET_CONTAINER_multihashmap_get (s->prefs, &cur->addr->peer.hashPubKey);
466         if (NULL == t)
467                 total_prefs += DEFAULT_PREFERENCE;
468         else
469          {
470                         total_prefs += (*t);
471          }
472       }
473   }
474   for (cur = net->head; NULL != cur; cur = cur->next)
475   {
476      if (GNUNET_YES == cur->addr->active)
477      {
478        cur_pref = 0.0;
479        t = GNUNET_CONTAINER_multihashmap_get (s->prefs, &cur->addr->peer.hashPubKey);
480        if (NULL == t)
481          cur_pref = DEFAULT_PREFERENCE;
482        else
483          cur_pref = (*t);
484        assigned_quota_in = min_bw + ((cur_pref / total_prefs) * remaining_quota_in);
485        assigned_quota_out = min_bw + ((cur_pref / total_prefs) * remaining_quota_out);
486
487        LOG (GNUNET_ERROR_TYPE_DEBUG,
488                    "New quota for peer `%s' with preference (cur/total) %.3f/%.3f (in/out): %llu / %llu\n",
489                    GNUNET_i2s (&cur->addr->peer),
490                    cur_pref, total_prefs,
491                    assigned_quota_in, assigned_quota_out);
492      }
493      else
494      {
495        assigned_quota_in = 0;
496        assigned_quota_out = 0;
497      }
498
499      quota_in_used += assigned_quota_in;
500      quota_out_used += assigned_quota_out;
501      /* Prevent overflow due to rounding errors */
502      if (assigned_quota_in > UINT32_MAX)
503        assigned_quota_in = UINT32_MAX;
504      if (assigned_quota_out > UINT32_MAX)
505        assigned_quota_out = UINT32_MAX;
506
507      /* Compare to current bandwidth assigned */
508      if ((assigned_quota_in != ntohl(cur->addr->assigned_bw_in.value__)) ||
509          (assigned_quota_out != ntohl(cur->addr->assigned_bw_out.value__)))
510      {
511        cur->addr->assigned_bw_in.value__ = htonl (assigned_quota_in);
512        cur->addr->assigned_bw_out.value__ = htonl (assigned_quota_out);
513        /* Notify on change */
514        if ((GNUNET_YES == cur->addr->active) && (cur->addr != address_except))
515          s->bw_changed (s->bw_changed_cls, cur->addr);
516      }
517
518   }
519   LOG (GNUNET_ERROR_TYPE_DEBUG,
520                           "Total bandwidth assigned is (in/out): %llu /%llu\n",
521                           quota_in_used,
522                           quota_out_used);
523   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
524   {
525       LOG (GNUNET_ERROR_TYPE_ERROR,
526                             "Total outbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
527                             net->active_addresses,
528                             quota_out_used,
529                             net->total_quota_out);
530   }
531   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
532   {
533       LOG (GNUNET_ERROR_TYPE_ERROR,
534                             "Total inbound bandwidth assigned is larger than allowed (used/allowed) for %u active addresses: %llu / %llu\n",
535                             net->active_addresses,
536                             quota_in_used,
537                             net->total_quota_in);
538   }
539 }
540
541 static void
542 update_all_networks (struct GAS_SIMPLISTIC_Handle *s)
543 {
544         int i;
545         for (i = 0; i < s->networks; i++)
546                 update_quota_per_network (s, &s->network_entries[i], NULL);
547
548 }
549
550 static void
551 addresse_increment (struct GAS_SIMPLISTIC_Handle *s,
552                                 struct Network *net,
553                                 int total,
554                                 int active)
555 {
556   if (GNUNET_YES == total)
557   {
558       s->total_addresses ++;
559       net->total_addresses ++;
560       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
561       GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
562   }
563   if (GNUNET_YES == active)
564   {
565     net->active_addresses ++;
566     s->active_addresses ++;
567     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1, GNUNET_NO);
568     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
569   }
570
571 }
572
573 static int
574 addresse_decrement (struct GAS_SIMPLISTIC_Handle *s,
575                     struct Network *net,
576                     int total,
577                     int active)
578 {
579   int res = GNUNET_OK;
580   if (GNUNET_YES == total)
581   {
582     if (s->total_addresses < 1)
583     {
584       GNUNET_break (0);
585       res = GNUNET_SYSERR;
586     }
587     else
588     {
589       s->total_addresses --;
590       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
591     }
592     if (net->total_addresses < 1)
593     {
594       GNUNET_break (0);
595       res = GNUNET_SYSERR;
596     }
597     else
598     {
599       net->total_addresses --;
600       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
601     }
602   }
603
604   if (GNUNET_YES == active)
605   {
606     if (net->active_addresses < 1)
607     {
608       GNUNET_break (0);
609       res = GNUNET_SYSERR;
610     }
611     else
612     {
613       net->active_addresses --;
614       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
615     }
616     if (s->active_addresses < 1)
617     {
618       GNUNET_break (0);
619       res = GNUNET_SYSERR;
620     }
621     else
622     {
623       s->active_addresses --;
624       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
625     }
626   }
627   return res;
628 }
629
630
631 /**
632  * Add a single address to the solve
633  *
634  * @param solver the solver Handle
635  * @param addresses the address hashmap containing all addresses
636  * @param address the address to add
637  */
638 void
639 GAS_simplistic_address_add (void *solver, struct GNUNET_CONTAINER_MultiHashMap * addresses, struct ATS_Address *address)
640 {
641   struct GAS_SIMPLISTIC_Handle *s = solver;
642   struct Network *net = NULL;
643   struct AddressWrapper *aw = NULL;
644
645   GNUNET_assert (NULL != s);
646   int c;
647   for (c = 0; c < s->networks; c++)
648   {
649       net = &s->network_entries[c];
650       if (address->atsp_network_type == net->type)
651           break;
652   }
653   if (NULL == net)
654   {
655     GNUNET_break (0);
656     return;
657   }
658
659   aw = GNUNET_malloc (sizeof (struct AddressWrapper));
660   aw->addr = address;
661   GNUNET_CONTAINER_DLL_insert (net->head, net->tail, aw);
662   addresse_increment (s, net, GNUNET_YES, GNUNET_NO);
663   aw->addr->solver_information = net;
664
665
666   LOG (GNUNET_ERROR_TYPE_DEBUG, "After adding address now total %u and active %u addresses in network `%s'\n",
667       net->total_addresses,
668       net->active_addresses,
669       net->desc);
670 }
671
672 /**
673  * Remove an address from the solver
674  *
675  * @param solver the solver handle
676  * @param addresses the address hashmap containing all addresses
677  * @param address the address to remove
678  * @param session_only delete only session not whole address
679  */
680 void
681 GAS_simplistic_address_delete (void *solver,
682     struct GNUNET_CONTAINER_MultiHashMap * addresses,
683     struct ATS_Address *address, int session_only)
684 {
685   struct GAS_SIMPLISTIC_Handle *s = solver;
686   struct Network *net;
687   struct AddressWrapper *aw;
688
689   /* Remove an adress completely, we have to:
690    * - Remove from specific network
691    * - Decrease number of total addresses
692    * - If active:
693    *   - decrease number of active addreses
694    *   - update quotas
695    */
696
697   net = (struct Network *) address->solver_information;
698
699   if (GNUNET_NO == session_only)
700   {
701     LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
702         (GNUNET_NO == address->active) ? "inactive" : "active",
703         address, GNUNET_i2s (&address->peer),
704         net->desc, net->total_addresses, net->active_addresses);
705
706     /* Remove address */
707     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
708     for (aw = net->head; NULL != aw; aw = aw->next)
709     {
710         if (aw->addr == address)
711           break;
712     }
713     if (NULL == aw )
714     {
715         GNUNET_break (0);
716         return;
717     }
718     GNUNET_CONTAINER_DLL_remove (net->head, net->tail, aw);
719     GNUNET_free (aw);
720   }
721   else
722   {
723       /* Remove session only: remove if active and update */
724       LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
725           (GNUNET_NO == address->active) ? "inactive" : "active",
726           address, GNUNET_i2s (&address->peer),
727           net->desc, net->total_addresses, net->active_addresses);
728   }
729
730   if (GNUNET_YES == address->active)
731   {
732       /* Address was active, remove from network and update quotas*/
733       address->active = GNUNET_NO;
734       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
735         GNUNET_break (0);
736       update_quota_per_network (s, net, NULL);
737   }
738   LOG (GNUNET_ERROR_TYPE_DEBUG, "After deleting address now total %u and active %u addresses in network `%s'\n",
739       net->total_addresses,
740       net->active_addresses,
741       net->desc);
742
743 }
744
745 static struct Network *
746 find_network (struct GAS_SIMPLISTIC_Handle *s, uint32_t type)
747 {
748   int c;
749   for (c = 0 ; c < s->networks; c++)
750   {
751       if (s->network_entries[c].type == type)
752         return &s->network_entries[c];
753   }
754   return NULL;
755 }
756
757 /**
758  * Updates a single address in the solve
759  *
760  * @param solver the solver Handle
761  * @param addresses the address hashmap containing all addresses
762  * @param address the update address
763  * @param session the new session (if changed otherwise current)
764  * @param in_use the new address in use state (if changed otherwise current)
765  * @param atsi the latest ATS information
766  * @param atsi_count the atsi count
767  */
768 void
769 GAS_simplistic_address_update (void *solver,
770                               struct GNUNET_CONTAINER_MultiHashMap *addresses,
771                               struct ATS_Address *address,
772                               uint32_t session,
773                               int in_use,
774                               const struct GNUNET_ATS_Information *atsi,
775                               uint32_t atsi_count)
776 {
777   struct ATS_Address *new;
778   struct GAS_SIMPLISTIC_Handle *s = (struct GAS_SIMPLISTIC_Handle *) solver;
779   int i;
780   uint32_t value;
781   uint32_t type;
782   int save_active = GNUNET_NO;
783   struct Network *new_net = NULL;
784   for (i = 0; i < atsi_count; i++)
785   {
786     type = ntohl (atsi[i].type);
787     value = ntohl (atsi[i].value);
788     switch (type)
789     {
790     case GNUNET_ATS_UTILIZATION_UP:
791       //if (address->atsp_utilization_out.value__ != atsi[i].value)
792
793       break;
794     case GNUNET_ATS_UTILIZATION_DOWN:
795       //if (address->atsp_utilization_in.value__ != atsi[i].value)
796
797       break;
798     case GNUNET_ATS_QUALITY_NET_DELAY:
799       //if (address->atsp_latency.rel_value != value)
800
801       break;
802     case GNUNET_ATS_QUALITY_NET_DISTANCE:
803       //if (address->atsp_distance != value)
804
805       break;
806     case GNUNET_ATS_COST_WAN:
807       //if (address->atsp_cost_wan != value)
808
809       break;
810     case GNUNET_ATS_COST_LAN:
811       //if (address->atsp_cost_lan != value)
812
813       break;
814     case GNUNET_ATS_COST_WLAN:
815       //if (address->atsp_cost_wlan != value)
816
817       break;
818     case GNUNET_ATS_NETWORK_TYPE:
819       if (address->atsp_network_type != value)
820       {
821
822         LOG (GNUNET_ERROR_TYPE_DEBUG, "Network type changed, moving %s address from `%s' to `%s'\n",
823             (GNUNET_YES == address->active) ? "active" : "inactive",
824             GNUNET_ATS_print_network_type(address->atsp_network_type),
825             GNUNET_ATS_print_network_type(value));
826
827         save_active = address->active;
828         /* remove from old network */
829         GAS_simplistic_address_delete (solver, addresses, address, GNUNET_NO);
830
831         /* set new network type */
832         address->atsp_network_type = value;
833         new_net = find_network (solver, value);
834         address->solver_information = new_net;
835         if (address->solver_information == NULL)
836         {
837             GNUNET_break (0);
838             address->atsp_network_type = GNUNET_ATS_NET_UNSPECIFIED;
839             return;
840         }
841
842         /* Add to new network and update*/
843         GAS_simplistic_address_add (solver, addresses, address);
844         if (GNUNET_YES == save_active)
845         {
846           /* check if bandwidth available in new network */
847           if (GNUNET_YES == (bw_available_in_network (new_net)))
848           {
849               /* Suggest updated address */
850               address->active = GNUNET_YES;
851               addresse_increment (s, new_net, GNUNET_NO, GNUNET_YES);
852               update_quota_per_network (solver, new_net, NULL);
853           }
854           else
855           {
856             LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough bandwidth in new network, suggesting alternative address ..\n");
857
858             /* Set old address to zero bw */
859             address->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0);
860             address->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0);
861             s->bw_changed  (s->bw_changed_cls, address);
862
863             /* Find new address to suggest since no bandwidth in network*/
864             new = (struct ATS_Address *) GAS_simplistic_get_preferred_address (s, addresses, &address->peer);
865             if (NULL != new)
866             {
867                 /* Have an alternative address to suggest */
868                 s->bw_changed  (s->bw_changed_cls, new);
869             }
870
871           }
872         }
873       }
874       break;
875     case GNUNET_ATS_ARRAY_TERMINATOR:
876       break;
877     default:
878       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
879                   "Received unsupported ATS type %u\n", type);
880       GNUNET_break (0);
881       break;
882
883     }
884
885   }
886   if (address->session_id != session)
887   {
888       LOG (GNUNET_ERROR_TYPE_DEBUG,
889                   "Session changed from %u to %u\n", address->session_id, session);
890       address->session_id = session;
891   }
892   if (address->used != in_use)
893   {
894       LOG (GNUNET_ERROR_TYPE_DEBUG,
895                   "Usage changed from %u to %u\n", address->used, in_use);
896       address->used = in_use;
897   }
898
899 }
900
901
902
903 /**
904  * Find a "good" address to use for a peer.  If we already have an existing
905  * address, we stick to it.  Otherwise, we pick by lowest distance and then
906  * by lowest latency.
907  *
908  * @param cls the 'struct ATS_Address**' where we store the result
909  * @param key unused
910  * @param value another 'struct ATS_Address*' to consider using
911  * @return GNUNET_OK (continue to iterate)
912  */
913 static int
914 find_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
915 {
916   struct ATS_Address **previous_p = cls;
917   struct ATS_Address *current = (struct ATS_Address *) value;
918   struct ATS_Address *previous = *previous_p;
919   struct GNUNET_TIME_Absolute now;
920   struct Network *net = (struct Network *) current->solver_information;
921
922   now = GNUNET_TIME_absolute_get();
923
924   if (current->blocked_until.abs_value == GNUNET_TIME_absolute_max (now, current->blocked_until).abs_value)
925   {
926     /* This address is blocked for suggestion */
927     LOG (GNUNET_ERROR_TYPE_DEBUG,
928                 "Address %p blocked for suggestion for %llu ms \n",
929                 current,
930                 GNUNET_TIME_absolute_get_difference(now, current->blocked_until).rel_value);
931     return GNUNET_OK;
932   }
933
934   if (GNUNET_NO == bw_available_in_network (net))
935     return GNUNET_OK; /* There's no bandwidth available in this network */
936
937   if (NULL != previous)
938   {
939     if ((0 == strcmp (previous->plugin, "tcp")) &&
940         (0 == strcmp (current->plugin, "tcp")))
941     {
942       if ((0 != previous->addr_len) &&
943           (0 == current->addr_len))
944       {
945         /* saved address was an outbound address, but we have an inbound address */
946         *previous_p = current;
947         return GNUNET_OK;
948       }
949       if (0 == previous->addr_len)
950       {
951         /* saved address was an inbound address, so do not overwrite */
952         return GNUNET_OK;
953       }
954     }
955   }
956
957   if (NULL == previous)
958   {
959     *previous_p = current;
960     return GNUNET_OK;
961   }
962   if ((ntohl (previous->assigned_bw_in.value__) == 0) &&
963       (ntohl (current->assigned_bw_in.value__) > 0))
964   {
965     /* stick to existing connection */
966     *previous_p = current;
967     return GNUNET_OK;
968   }
969   if (previous->atsp_distance > current->atsp_distance)
970   {
971     /* user shorter distance */
972     *previous_p = current;
973     return GNUNET_OK;
974   }
975   if (previous->atsp_latency.rel_value > current->atsp_latency.rel_value)
976   {
977     /* user lower latency */
978     *previous_p = current;
979     return GNUNET_OK;
980   }
981   /* don't care */
982   return GNUNET_OK;
983 }
984
985 static int
986 find_active_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
987 {
988   struct ATS_Address * dest = (struct ATS_Address *) (*(struct ATS_Address **)cls);
989   struct ATS_Address * aa = (struct ATS_Address *) value;
990
991   if (GNUNET_YES == aa->active)
992   {
993       if (dest != NULL)
994       {
995           /* should never happen */
996           LOG (GNUNET_ERROR_TYPE_ERROR, "Multiple active addresses for peer `%s'\n", GNUNET_i2s (&aa->peer));
997           GNUNET_break (0);
998           return GNUNET_NO;
999       }
1000       dest = aa;
1001   }
1002   return GNUNET_OK;
1003 }
1004
1005 static struct ATS_Address *
1006 find_active_address (void *solver,
1007                      struct GNUNET_CONTAINER_MultiHashMap * addresses,
1008                      const struct GNUNET_PeerIdentity *peer)
1009 {
1010   struct ATS_Address * dest = NULL;
1011
1012   GNUNET_CONTAINER_multihashmap_get_multiple(addresses,
1013        &peer->hashPubKey,
1014        &find_active_address_it, &dest);
1015   return dest;
1016 }
1017
1018 /**
1019  * Get the prefered address for a specific peer
1020  *
1021  * @param solver the solver handle
1022  * @param addresses the address hashmap containing all addresses
1023  * @param peer the identity of the peer
1024  */
1025 const struct ATS_Address *
1026 GAS_simplistic_get_preferred_address (void *solver,
1027                                struct GNUNET_CONTAINER_MultiHashMap * addresses,
1028                                const struct GNUNET_PeerIdentity *peer)
1029 {
1030   struct GAS_SIMPLISTIC_Handle *s = solver;
1031   struct Network *net_prev;
1032   struct Network *net_cur;
1033   struct ATS_Address *cur;
1034   struct ATS_Address *prev;
1035
1036   GNUNET_assert (s != NULL);
1037   cur = NULL;
1038   /* Get address with: stick to current address, lower distance, lower latency */
1039   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
1040                                               &find_address_it, &cur);
1041   if (NULL == cur)
1042   {
1043     LOG (GNUNET_ERROR_TYPE_DEBUG, "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
1044     return NULL;
1045   }
1046
1047   LOG (GNUNET_ERROR_TYPE_DEBUG, "Suggesting %s address %p for peer `%s'\n",
1048       (GNUNET_NO == cur->active) ? "inactive" : "active",
1049       cur, GNUNET_i2s (peer));
1050   net_cur = (struct Network *) cur->solver_information;
1051   if (GNUNET_YES == cur->active)
1052   {
1053       /* This address was selected previously, so no need to update quotas */
1054       return cur;
1055   }
1056
1057   /* This address was not active, so we have to:
1058    *
1059    * - mark previous active address as not active
1060    * - update quota for previous address network
1061    * - update quota for this address network
1062    */
1063
1064   prev = find_active_address (s, addresses, peer);
1065   if (NULL != prev)
1066   {
1067       net_prev = (struct Network *) prev->solver_information;
1068       prev->active = GNUNET_NO; /* No active any longer */
1069       prev->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
1070       prev->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
1071       s->bw_changed (s->bw_changed_cls, prev); /* notify about bw change, REQUIRED? */
1072       if (GNUNET_SYSERR == addresse_decrement (s, net_prev, GNUNET_NO, GNUNET_YES))
1073         GNUNET_break (0);
1074       update_quota_per_network (s, net_prev, NULL);
1075   }
1076
1077   if (GNUNET_NO == (bw_available_in_network (cur->solver_information)))
1078   {
1079     GNUNET_break (0); /* This should never happen*/
1080     return NULL;
1081   }
1082
1083   cur->active = GNUNET_YES;
1084   addresse_increment(s, net_cur, GNUNET_NO, GNUNET_YES);
1085   update_quota_per_network (s, net_cur, cur);
1086
1087   return cur;
1088 }
1089
1090 static void
1091 recalculate_preferences (struct PreferencePeer *p)
1092 {
1093         struct GAS_SIMPLISTIC_Handle *s = p->s;
1094         struct PreferencePeer *p_cur;
1095         struct PreferenceClient *c_cur = p->client;
1096         double p_rel_global;
1097   double *dest;
1098   int kind;
1099   int rkind;
1100   int clients;
1101
1102   /**
1103    * Idea:
1104    *
1105    * We have:
1106    * Set of clients c
1107    * Set of peers p_i in P
1108    * Set of preference kinds k
1109    * A preference value f_k_p_i with an unknown range
1110    *
1111    * We get:
1112    * A client specific relative preference f_p_i_rel [1..2] for all peers
1113    *
1114    * For every client c
1115    * {
1116    *   For every preference kind k:
1117    *   {
1118    *     We remember for the preference f_p_i for each peer p_i.
1119    *     We have a default preference value f_p_i = 0
1120    *     We have a sum of all preferences f_t = sum (f_p_i)
1121    *     So we can calculate a relative preference value fr_p_i:
1122    *
1123    *     f_k_p_i_rel = (f_t + f_p_i) / f_t
1124    *     f_k_p_i_rel = [1..2], default 1.0
1125    *    }
1126    *    f_p_i_rel = sum (f_k_p_i_rel) / #k
1127    * }
1128    *
1129    **/
1130
1131   /* For this client: for all preferences, except TERMINATOR */
1132   for (kind = GNUNET_ATS_PREFERENCE_END + 1 ; kind < GNUNET_ATS_PreferenceCount; kind ++)
1133   {
1134           /* Recalcalculate total preference for this quality kind over all peers*/
1135           c_cur->f_total[kind] = 0;
1136           for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
1137                 c_cur->f_total[kind] += p_cur->f[kind];
1138
1139           LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p has total preference for %s of %.3f\n",
1140                         c_cur->client,
1141               GNUNET_ATS_print_preference_type (kind),
1142               c_cur->f_total[kind]);
1143
1144           /* Recalcalculate relative preference for all peers */
1145           for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
1146           {
1147             /* Calculate relative preference for specific kind */
1148                 if (0.0 == c_cur->f_total[kind])
1149                 {
1150                                 /* No one has preference, so set default preference */
1151                                 p_cur->f_rel[kind] = DEFAULT_PREFERENCE;
1152                 }
1153                 else
1154                 {
1155                                 p_cur->f_rel[kind] = (c_cur->f_total[kind] + p_cur->f[kind]) / c_cur->f_total[kind];
1156                 }
1157             LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p: peer `%s' has relative preference for %s of %.3f\n",
1158                         c_cur->client,
1159                 GNUNET_i2s (&p_cur->id),
1160                 GNUNET_ATS_print_preference_type (kind),
1161                 p_cur->f_rel[kind]);
1162
1163             /* Calculate peer relative preference */
1164             /* Start with kind = 1 to exclude terminator */
1165             p_cur->f_rel_total = 0;
1166             for (rkind = GNUNET_ATS_PREFERENCE_END + 1; rkind < GNUNET_ATS_PreferenceCount; rkind ++)
1167             {
1168                 p_cur->f_rel_total += p_cur->f_rel[rkind];
1169             }
1170             p_cur->f_rel_total /=  (GNUNET_ATS_PreferenceCount - 1.0); /* -1 due to terminator */
1171             LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p: peer `%s' has total relative preference of %.3f\n",
1172                         c_cur->client,
1173                 GNUNET_i2s (&p_cur->id),
1174                 p_cur->f_rel_total);
1175           }
1176   }
1177
1178   /* Calculcate global total relative peer preference over all clients */
1179   p_rel_global = 0.0;
1180   clients = 0;
1181   for (c_cur = s->pc_head; NULL != c_cur; c_cur = c_cur->next)
1182   {
1183       for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
1184           if (0 == memcmp (&p_cur->id, &p->id, sizeof (p_cur->id)))
1185               break;
1186       if (NULL != p_cur)
1187       {
1188           clients++;
1189           p_rel_global += p_cur->f_rel_total;
1190       }
1191   }
1192   p_rel_global /= clients;
1193   LOG (GNUNET_ERROR_TYPE_DEBUG, "Global preference value for peer `%s': %.3f\n",
1194       GNUNET_i2s (&p->id), p_rel_global);
1195
1196   /* Update global map */
1197   if (NULL != (dest = GNUNET_CONTAINER_multihashmap_get(s->prefs, &p->id.hashPubKey)))
1198       (*dest) = p_rel_global;
1199   else
1200   {
1201       dest = GNUNET_malloc (sizeof (double));
1202       (*dest) = p_rel_global;
1203       GNUNET_CONTAINER_multihashmap_put(s->prefs,
1204           &p->id.hashPubKey,
1205           dest,
1206           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1207   }
1208 }
1209
1210 static void
1211 update_preference (struct PreferencePeer *p,
1212                                                                          enum GNUNET_ATS_PreferenceKind kind,
1213                                                          float score_f)
1214 {
1215         double score = score_f;
1216
1217   /* Update preference value according to type */
1218   switch (kind) {
1219     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1220     case GNUNET_ATS_PREFERENCE_LATENCY:
1221       p->f[kind] = (p->f[kind] + score) / 2;
1222       break;
1223     case GNUNET_ATS_PREFERENCE_END:
1224       break;
1225     default:
1226       break;
1227   }
1228   recalculate_preferences(p);
1229   update_all_networks (p->s);
1230 }
1231
1232
1233 static void
1234 preference_aging (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1235 {
1236         int i;
1237         double *t = NULL;
1238         double backup;
1239         struct PreferencePeer *p = cls;
1240         GNUNET_assert (NULL != p);
1241
1242
1243         p->aging_task = GNUNET_SCHEDULER_NO_TASK;
1244
1245   LOG (GNUNET_ERROR_TYPE_DEBUG, "Aging preferences for peer `%s'\n",
1246                 GNUNET_i2s (&p->id));
1247
1248   /* Issue for aging :
1249    *
1250    * Not for every peer preference values are set by default, so reducing the
1251    * absolute preference value does not help for aging because it does not have
1252    * influence on the relative values.
1253    *
1254    * So we have to reduce the relative value to have an immediate impact on
1255    * quota calculation. In addition we cannot call recalculate_preferences here
1256    * but instead reduce the absolute value to have an aging impact on future
1257    * calls to change_preference where recalculate_preferences is called
1258    *
1259    */
1260   /* Aging absolute values: */
1261   for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
1262   {
1263                 if (p->f[i] > 1.0)
1264                 {
1265                         backup = p->f[i];
1266                         p->f[i] *= PREF_AGING_FACTOR;
1267                         LOG (GNUNET_ERROR_TYPE_DEBUG, "Aged preference for peer `%s' from %.3f to %.3f\n",
1268                         GNUNET_i2s (&p->id), backup, p->f[i]);
1269                 }
1270   }
1271   /* Updating relative value */
1272   t = GNUNET_CONTAINER_multihashmap_get (p->s->prefs, &p->id.hashPubKey);
1273   if (NULL == t)
1274   {
1275         GNUNET_break (0);
1276   }
1277   else
1278   {
1279                 if ((*t) > 1.0)
1280                         (*t) = (*t) * PREF_AGING_FACTOR;
1281                 else
1282                         (*t) = 1.0;
1283                 update_all_networks (p->s);
1284   }
1285   p->aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL,
1286                 &preference_aging, p);
1287 }
1288
1289
1290 /**
1291  * Changes the preferences for a peer in the problem
1292  *
1293  * @param solver the solver handle
1294  * @param client the client with this preference
1295  * @param peer the peer to change the preference for
1296  * @param kind the kind to change the preference
1297  * @param score the score
1298  */
1299 void
1300 GAS_simplistic_address_change_preference (void *solver,
1301                                    void *client,
1302                                    const struct GNUNET_PeerIdentity *peer,
1303                                    enum GNUNET_ATS_PreferenceKind kind,
1304                                    float score_f)
1305 {
1306   static struct GNUNET_TIME_Absolute next_update;
1307   struct GAS_SIMPLISTIC_Handle *s = solver;
1308   struct PreferenceClient *c_cur;
1309   struct PreferencePeer *p_cur;
1310   int i;
1311
1312   GNUNET_assert (NULL != solver);
1313   GNUNET_assert (NULL != client);
1314   GNUNET_assert (NULL != peer);
1315
1316   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p changes preference for peer `%s' %s %f\n",
1317                                 client,
1318                                 GNUNET_i2s (peer),
1319                                 GNUNET_ATS_print_preference_type (kind),
1320                                 score_f);
1321
1322   if (kind >= GNUNET_ATS_PreferenceCount)
1323   {
1324       GNUNET_break (0);
1325       return;
1326   }
1327
1328   /* Find preference client */
1329   for (c_cur = s->pc_head; NULL != c_cur; c_cur = c_cur->next)
1330   {
1331       if (client == c_cur->client)
1332         break;
1333   }
1334   /* Not found: create new preference client */
1335   if (NULL == c_cur)
1336   {
1337     c_cur = GNUNET_malloc (sizeof (struct PreferenceClient));
1338     c_cur->client = client;
1339     GNUNET_CONTAINER_DLL_insert (s->pc_head, s->pc_tail, c_cur);
1340   }
1341
1342   /* Find entry for peer */
1343   for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
1344     if (0 == memcmp (&p_cur->id, peer, sizeof (p_cur->id)))
1345         break;
1346
1347   /* Not found: create new peer entry */
1348   if (NULL == p_cur)
1349   {
1350       p_cur = GNUNET_malloc (sizeof (struct PreferencePeer));
1351       p_cur->s = s;
1352       p_cur->client = c_cur;
1353       p_cur->id = (*peer);
1354       for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
1355       {
1356         /* Default value per peer absolut preference for a quality:
1357          * No value set, so absolute preference 0 */
1358         p_cur->f[i] = 0.0;
1359         /* Default value per peer relative preference for a quality: 1.0 */
1360         p_cur->f_rel[i] = DEFAULT_PREFERENCE;
1361       }
1362       p_cur->aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL, &preference_aging, p_cur);
1363       GNUNET_CONTAINER_DLL_insert (c_cur->p_head, c_cur->p_tail, p_cur);
1364   }
1365
1366   update_preference (p_cur, kind, score_f);
1367
1368   /* FIXME: We should update quotas if UPDATE_INTERVAL is reached */
1369   if (GNUNET_TIME_absolute_get().abs_value > next_update.abs_value)
1370   {
1371       /* update quotas*/
1372       next_update = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1373                                               MIN_UPDATE_INTERVAL);
1374   }
1375 }
1376
1377 /* end of gnunet-service-ats_addresses_simplistic.c */