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