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