no suggest to cancel
[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 remaining_quota_in = 0;
406   unsigned long long quota_out_used = 0;
407
408   unsigned long long remaining_quota_out = 0;
409   unsigned long long quota_in_used = 0;
410   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
411   float total_prefs;
412   float cur_pref;
413   float *t = NULL;
414
415   unsigned long long quota_in = 0;
416   unsigned long long quota_out = 0;
417   struct AddressWrapper *cur;
418
419   LOG (GNUNET_ERROR_TYPE_DEBUG,
420               "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n",
421               net->desc, net->active_addresses, quota_in, quota_out);
422
423   if (net->active_addresses == 0)
424     return; /* no addresses to update */
425
426   /* Idea TODO
427    *
428    * Assign every peer in network minimum Bandwidth
429    * Distribute bandwidth left according to preference
430    */
431
432   if ((net->active_addresses * min_bw) > net->total_quota_in)
433   {
434     GNUNET_break (0);
435     return;
436   }
437   if ((net->active_addresses * min_bw) > net->total_quota_out)
438   {
439     GNUNET_break (0);
440     return;
441   }
442
443   remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw);
444   remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw);
445   LOG (GNUNET_ERROR_TYPE_DEBUG, "Remaining bandwidth : (in/out): %llu/%llu \n",
446               remaining_quota_in, remaining_quota_out);
447   total_prefs = 0.0;
448   for (cur = net->head; NULL != cur; cur = cur->next)
449   {
450       if (GNUNET_YES == cur->addr->active)
451       {
452         t = GNUNET_CONTAINER_multihashmap_get (s->prefs, &cur->addr->peer.hashPubKey);
453         if (NULL == t)
454           total_prefs += DEFAULT_PREFERENCE;
455         else
456           total_prefs += (*t);
457       }
458   }
459   for (cur = net->head; NULL != cur; cur = cur->next)
460   {
461      if (GNUNET_YES == cur->addr->active)
462      {
463        cur_pref = 0.0;
464        t = GNUNET_CONTAINER_multihashmap_get (s->prefs, &cur->addr->peer.hashPubKey);
465        if (NULL == t)
466          cur_pref = DEFAULT_PREFERENCE;
467        else
468          cur_pref = (*t);
469        quota_in = min_bw + (cur_pref / total_prefs) * (float) remaining_quota_in;
470        quota_out = min_bw + (cur_pref / total_prefs) * (float) remaining_quota_out;
471
472        LOG (GNUNET_ERROR_TYPE_DEBUG,
473                    "New quota for peer `%s' with preference (cur/total) %.3f/%.3f (in/out): %llu /%llu\n",
474                    GNUNET_i2s (&cur->addr->peer),
475                    cur_pref, total_prefs,
476                    quota_in, quota_out);
477      }
478      else
479      {
480        quota_in = 0;
481        quota_out = 0;
482      }
483
484      quota_in_used += quota_in;
485      quota_out_used += quota_out;
486      /* Prevent overflow due to rounding errors */
487      if (quota_in > UINT32_MAX)
488        quota_in = UINT32_MAX;
489      if (quota_out > UINT32_MAX)
490        quota_out = UINT32_MAX;
491
492      /* Compare to current bandwidth assigned */
493      if ((quota_in != ntohl(cur->addr->assigned_bw_in.value__)) ||
494          (quota_out != ntohl(cur->addr->assigned_bw_out.value__)))
495      {
496        cur->addr->assigned_bw_in.value__ = htonl (quota_in);
497        cur->addr->assigned_bw_out.value__ = htonl (quota_out);
498        /* Notify on change */
499        if ((GNUNET_YES == cur->addr->active) && (cur->addr != address_except))
500          s->bw_changed (s->bw_changed_cls, cur->addr);
501      }
502
503   }
504   LOG (GNUNET_ERROR_TYPE_DEBUG,
505                           "Total bandwidth assigned is (in/out): %llu /%llu\n",
506                           quota_in_used,
507                           quota_out_used);
508   if (quota_out_used > net->total_quota_out + 1) /* +1 is required due to rounding errors */
509   {
510       GNUNET_break (0);
511       LOG (GNUNET_ERROR_TYPE_WARNING,
512                             "Total inbound bandwidth assigned is larget than allowed  %llu /%llu\n",
513                             quota_out_used,
514                             quota_out);
515   }
516   if (quota_in_used > net->total_quota_in + 1) /* +1 is required due to rounding errors */
517   {
518       GNUNET_break (0);
519       LOG (GNUNET_ERROR_TYPE_WARNING,
520                             "Total inbound bandwidth assigned is larget than allowed  %llu /%llu\n",
521                             quota_in_used,
522                             quota_in);
523   }
524 }
525
526 static void
527 addresse_increment (struct GAS_SIMPLISTIC_Handle *s,
528                                 struct Network *net,
529                                 int total,
530                                 int active)
531 {
532   if (GNUNET_YES == total)
533   {
534       s->total_addresses ++;
535       net->total_addresses ++;
536       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", 1, GNUNET_NO);
537       GNUNET_STATISTICS_update (s->stats, net->stat_total, 1, GNUNET_NO);
538   }
539   if (GNUNET_YES == active)
540   {
541     net->active_addresses ++;
542     s->active_addresses ++;
543     GNUNET_STATISTICS_update (s->stats, "# ATS active addresses total", 1, GNUNET_NO);
544     GNUNET_STATISTICS_update (s->stats, net->stat_active, 1, GNUNET_NO);
545   }
546
547 }
548
549 static int
550 addresse_decrement (struct GAS_SIMPLISTIC_Handle *s,
551                     struct Network *net,
552                     int total,
553                     int active)
554 {
555   int res = GNUNET_OK;
556   if (GNUNET_YES == total)
557   {
558     if (s->total_addresses < 1)
559     {
560       GNUNET_break (0);
561       res = GNUNET_SYSERR;
562     }
563     else
564     {
565       s->total_addresses --;
566       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
567     }
568     if (net->total_addresses < 1)
569     {
570       GNUNET_break (0);
571       res = GNUNET_SYSERR;
572     }
573     else
574     {
575       net->total_addresses --;
576       GNUNET_STATISTICS_update (s->stats, net->stat_total, -1, GNUNET_NO);
577     }
578   }
579
580   if (GNUNET_YES == active)
581   {
582     if (net->active_addresses < 1)
583     {
584       GNUNET_break (0);
585       res = GNUNET_SYSERR;
586     }
587     else
588     {
589       net->active_addresses --;
590       GNUNET_STATISTICS_update (s->stats, net->stat_active, -1, GNUNET_NO);
591     }
592     if (s->active_addresses < 1)
593     {
594       GNUNET_break (0);
595       res = GNUNET_SYSERR;
596     }
597     else
598     {
599       s->active_addresses --;
600       GNUNET_STATISTICS_update (s->stats, "# ATS addresses total", -1, GNUNET_NO);
601     }
602   }
603   return res;
604 }
605
606
607 /**
608  * Add a single address to the solve
609  *
610  * @param solver the solver Handle
611  * @param addresses the address hashmap containing all addresses
612  * @param address the address to add
613  */
614 void
615 GAS_simplistic_address_add (void *solver, struct GNUNET_CONTAINER_MultiHashMap * addresses, struct ATS_Address *address)
616 {
617   struct GAS_SIMPLISTIC_Handle *s = solver;
618   struct Network *net = NULL;
619   struct AddressWrapper *aw = NULL;
620
621   GNUNET_assert (NULL != s);
622   int c;
623   for (c = 0; c < s->networks; c++)
624   {
625       net = &s->network_entries[c];
626       if (address->atsp_network_type == net->type)
627           break;
628   }
629   if (NULL == net)
630   {
631     GNUNET_break (0);
632     return;
633   }
634
635   aw = GNUNET_malloc (sizeof (struct AddressWrapper));
636   aw->addr = address;
637   GNUNET_CONTAINER_DLL_insert (net->head, net->tail, aw);
638   addresse_increment (s, net, GNUNET_YES, GNUNET_NO);
639   aw->addr->solver_information = net;
640
641
642   LOG (GNUNET_ERROR_TYPE_DEBUG, "After adding address now total %u and active %u addresses in network `%s'\n",
643       net->total_addresses,
644       net->active_addresses,
645       net->desc);
646 }
647
648 /**
649  * Remove an address from the solver
650  *
651  * @param solver the solver handle
652  * @param addresses the address hashmap containing all addresses
653  * @param address the address to remove
654  * @param session_only delete only session not whole address
655  */
656 void
657 GAS_simplistic_address_delete (void *solver,
658     struct GNUNET_CONTAINER_MultiHashMap * addresses,
659     struct ATS_Address *address, int session_only)
660 {
661   struct GAS_SIMPLISTIC_Handle *s = solver;
662   struct Network *net;
663   struct AddressWrapper *aw;
664
665   /* Remove an adress completely, we have to:
666    * - Remove from specific network
667    * - Decrease number of total addresses
668    * - If active:
669    *   - decrease number of active addreses
670    *   - update quotas
671    */
672
673   net = (struct Network *) address->solver_information;
674
675   if (GNUNET_NO == session_only)
676   {
677     LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s address %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
678         (GNUNET_NO == address->active) ? "inactive" : "active",
679         address, GNUNET_i2s (&address->peer),
680         net->desc, net->total_addresses, net->active_addresses);
681
682     /* Remove address */
683     addresse_decrement (s, net, GNUNET_YES, GNUNET_NO);
684     for (aw = net->head; NULL != aw; aw = aw->next)
685     {
686         if (aw->addr == address)
687           break;
688     }
689     if (NULL == aw )
690     {
691         GNUNET_break (0);
692         return;
693     }
694     GNUNET_CONTAINER_DLL_remove (net->head, net->tail, aw);
695     GNUNET_free (aw);
696   }
697   else
698   {
699       /* Remove session only: remove if active and update */
700       LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting %s session %p for peer `%s' from network `%s' (total: %u/ active: %u)\n",
701           (GNUNET_NO == address->active) ? "inactive" : "active",
702           address, GNUNET_i2s (&address->peer),
703           net->desc, net->total_addresses, net->active_addresses);
704   }
705
706   if (GNUNET_YES == address->active)
707   {
708       /* Address was active, remove from network and update quotas*/
709       address->active = GNUNET_NO;
710       if (GNUNET_SYSERR == addresse_decrement (s, net, GNUNET_NO, GNUNET_YES))
711         GNUNET_break (0);
712       update_quota_per_network (s, net, NULL);
713   }
714   LOG (GNUNET_ERROR_TYPE_DEBUG, "After deleting address now total %u and active %u addresses in network `%s'\n",
715       net->total_addresses,
716       net->active_addresses,
717       net->desc);
718
719 }
720
721 static struct Network *
722 find_network (struct GAS_SIMPLISTIC_Handle *s, uint32_t type)
723 {
724   int c;
725   for (c = 0 ; c < s->networks; c++)
726   {
727       if (s->network_entries[c].type == type)
728         return &s->network_entries[c];
729   }
730   return NULL;
731 }
732
733 /**
734  * Updates a single address in the solve
735  *
736  * @param solver the solver Handle
737  * @param addresses the address hashmap containing all addresses
738  * @param address the update address
739  * @param session the new session (if changed otherwise current)
740  * @param in_use the new address in use state (if changed otherwise current)
741  * @param atsi the latest ATS information
742  * @param atsi_count the atsi count
743  */
744 void
745 GAS_simplistic_address_update (void *solver,
746                               struct GNUNET_CONTAINER_MultiHashMap *addresses,
747                               struct ATS_Address *address,
748                               uint32_t session,
749                               int in_use,
750                               const struct GNUNET_ATS_Information *atsi,
751                               uint32_t atsi_count)
752 {
753   struct ATS_Address *new;
754   struct GAS_SIMPLISTIC_Handle *s = (struct GAS_SIMPLISTIC_Handle *) solver;
755   int i;
756   uint32_t value;
757   uint32_t type;
758   int save_active = GNUNET_NO;
759   struct Network *new_net = NULL;
760   for (i = 0; i < atsi_count; i++)
761   {
762     type = ntohl (atsi[i].type);
763     value = ntohl (atsi[i].value);
764     switch (type)
765     {
766     case GNUNET_ATS_UTILIZATION_UP:
767       //if (address->atsp_utilization_out.value__ != atsi[i].value)
768
769       break;
770     case GNUNET_ATS_UTILIZATION_DOWN:
771       //if (address->atsp_utilization_in.value__ != atsi[i].value)
772
773       break;
774     case GNUNET_ATS_QUALITY_NET_DELAY:
775       //if (address->atsp_latency.rel_value != value)
776
777       break;
778     case GNUNET_ATS_QUALITY_NET_DISTANCE:
779       //if (address->atsp_distance != value)
780
781       break;
782     case GNUNET_ATS_COST_WAN:
783       //if (address->atsp_cost_wan != value)
784
785       break;
786     case GNUNET_ATS_COST_LAN:
787       //if (address->atsp_cost_lan != value)
788
789       break;
790     case GNUNET_ATS_COST_WLAN:
791       //if (address->atsp_cost_wlan != value)
792
793       break;
794     case GNUNET_ATS_NETWORK_TYPE:
795       if (address->atsp_network_type != value)
796       {
797
798         LOG (GNUNET_ERROR_TYPE_DEBUG, "Network type changed, moving %s address from `%s' to `%s'\n",
799             (GNUNET_YES == address->active) ? "active" : "inactive",
800             GNUNET_ATS_print_network_type(address->atsp_network_type),
801             GNUNET_ATS_print_network_type(value));
802
803         save_active = address->active;
804         /* remove from old network */
805         GAS_simplistic_address_delete (solver, addresses, address, GNUNET_NO);
806
807         /* set new network type */
808         address->atsp_network_type = value;
809         new_net = find_network (solver, value);
810         address->solver_information = new_net;
811         if (address->solver_information == NULL)
812         {
813             GNUNET_break (0);
814             address->atsp_network_type = GNUNET_ATS_NET_UNSPECIFIED;
815             return;
816         }
817
818         /* Add to new network and update*/
819         GAS_simplistic_address_add (solver, addresses, address);
820         if (GNUNET_YES == save_active)
821         {
822           /* check if bandwidth available in new network */
823           if (GNUNET_YES == (bw_available_in_network (new_net)))
824           {
825               /* Suggest updated address */
826               address->active = GNUNET_YES;
827               addresse_increment (s, new_net, GNUNET_NO, GNUNET_YES);
828               update_quota_per_network (solver, new_net, NULL);
829           }
830           else
831           {
832             LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough bandwidth in new network, suggesting alternative address ..\n");
833
834             /* Set old address to zero bw */
835             address->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0);
836             address->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0);
837             s->bw_changed  (s->bw_changed_cls, address);
838
839             /* Find new address to suggest since no bandwidth in network*/
840             new = (struct ATS_Address *) GAS_simplistic_get_preferred_address (s, addresses, &address->peer);
841             if (NULL != new)
842             {
843                 /* Have an alternative address to suggest */
844                 s->bw_changed  (s->bw_changed_cls, new);
845             }
846
847           }
848         }
849       }
850       break;
851     case GNUNET_ATS_ARRAY_TERMINATOR:
852       break;
853     default:
854       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
855                   "Received unsupported ATS type %u\n", type);
856       GNUNET_break (0);
857       break;
858
859     }
860
861   }
862   if (address->session_id != session)
863   {
864       LOG (GNUNET_ERROR_TYPE_DEBUG,
865                   "Session changed from %u to %u\n", address->session_id, session);
866       address->session_id = session;
867   }
868   if (address->used != in_use)
869   {
870       LOG (GNUNET_ERROR_TYPE_DEBUG,
871                   "Usage changed from %u to %u\n", address->used, in_use);
872       address->used = in_use;
873   }
874
875 }
876
877
878
879 /**
880  * Find a "good" address to use for a peer.  If we already have an existing
881  * address, we stick to it.  Otherwise, we pick by lowest distance and then
882  * by lowest latency.
883  *
884  * @param cls the 'struct ATS_Address**' where we store the result
885  * @param key unused
886  * @param value another 'struct ATS_Address*' to consider using
887  * @return GNUNET_OK (continue to iterate)
888  */
889 static int
890 find_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
891 {
892   struct ATS_Address **previous_p = cls;
893   struct ATS_Address *current = (struct ATS_Address *) value;
894   struct ATS_Address *previous = *previous_p;
895   struct GNUNET_TIME_Absolute now;
896   struct Network *net = (struct Network *) current->solver_information;
897
898   now = GNUNET_TIME_absolute_get();
899
900   if (current->blocked_until.abs_value == GNUNET_TIME_absolute_max (now, current->blocked_until).abs_value)
901   {
902     /* This address is blocked for suggestion */
903     LOG (GNUNET_ERROR_TYPE_DEBUG,
904                 "Address %p blocked for suggestion for %llu ms \n",
905                 current,
906                 GNUNET_TIME_absolute_get_difference(now, current->blocked_until).rel_value);
907     return GNUNET_OK;
908   }
909
910   if (GNUNET_NO == bw_available_in_network (net))
911     return GNUNET_OK; /* There's no bandwidth available in this network */
912
913   if (NULL != previous)
914   {
915     if ((0 == strcmp (previous->plugin, "tcp")) &&
916         (0 == strcmp (current->plugin, "tcp")))
917     {
918       if ((0 != previous->addr_len) &&
919           (0 == current->addr_len))
920       {
921         /* saved address was an outbound address, but we have an inbound address */
922         *previous_p = current;
923         return GNUNET_OK;
924       }
925       if (0 == previous->addr_len)
926       {
927         /* saved address was an inbound address, so do not overwrite */
928         return GNUNET_OK;
929       }
930     }
931   }
932
933   if (NULL == previous)
934   {
935     *previous_p = current;
936     return GNUNET_OK;
937   }
938   if ((ntohl (previous->assigned_bw_in.value__) == 0) &&
939       (ntohl (current->assigned_bw_in.value__) > 0))
940   {
941     /* stick to existing connection */
942     *previous_p = current;
943     return GNUNET_OK;
944   }
945   if (previous->atsp_distance > current->atsp_distance)
946   {
947     /* user shorter distance */
948     *previous_p = current;
949     return GNUNET_OK;
950   }
951   if (previous->atsp_latency.rel_value > current->atsp_latency.rel_value)
952   {
953     /* user lower latency */
954     *previous_p = current;
955     return GNUNET_OK;
956   }
957   /* don't care */
958   return GNUNET_OK;
959 }
960
961 static int
962 find_active_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
963 {
964   struct ATS_Address * dest = (struct ATS_Address *) (*(struct ATS_Address **)cls);
965   struct ATS_Address * aa = (struct ATS_Address *) value;
966
967   if (GNUNET_YES == aa->active)
968   {
969       if (dest != NULL)
970       {
971           /* should never happen */
972           LOG (GNUNET_ERROR_TYPE_ERROR, "Multiple active addresses for peer `%s'\n", GNUNET_i2s (&aa->peer));
973           GNUNET_break (0);
974           return GNUNET_NO;
975       }
976       dest = aa;
977   }
978   return GNUNET_OK;
979 }
980
981 static struct ATS_Address *
982 find_active_address (void *solver,
983                      struct GNUNET_CONTAINER_MultiHashMap * addresses,
984                      const struct GNUNET_PeerIdentity *peer)
985 {
986   struct ATS_Address * dest = NULL;
987
988   GNUNET_CONTAINER_multihashmap_get_multiple(addresses,
989        &peer->hashPubKey,
990        &find_active_address_it, &dest);
991   return dest;
992 }
993
994 /**
995  * Get the prefered address for a specific peer
996  *
997  * @param solver the solver handle
998  * @param addresses the address hashmap containing all addresses
999  * @param peer the identity of the peer
1000  */
1001 const struct ATS_Address *
1002 GAS_simplistic_get_preferred_address (void *solver,
1003                                struct GNUNET_CONTAINER_MultiHashMap * addresses,
1004                                const struct GNUNET_PeerIdentity *peer)
1005 {
1006   struct GAS_SIMPLISTIC_Handle *s = solver;
1007   struct Network *net_prev;
1008   struct Network *net_cur;
1009   struct ATS_Address *cur;
1010   struct ATS_Address *prev;
1011
1012   GNUNET_assert (s != NULL);
1013   cur = NULL;
1014   /* Get address with: stick to current address, lower distance, lower latency */
1015   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
1016                                               &find_address_it, &cur);
1017   if (NULL == cur)
1018   {
1019     LOG (GNUNET_ERROR_TYPE_DEBUG, "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
1020     return NULL;
1021   }
1022
1023   LOG (GNUNET_ERROR_TYPE_DEBUG, "Suggesting %s address %p for peer `%s'\n",
1024       (GNUNET_NO == cur->active) ? "inactive" : "active",
1025       cur, GNUNET_i2s (peer));
1026   net_cur = (struct Network *) cur->solver_information;
1027   if (GNUNET_YES == cur->active)
1028   {
1029       /* This address was selected previously, so no need to update quotas */
1030       return cur;
1031   }
1032
1033   /* This address was not active, so we have to:
1034    *
1035    * - mark previous active address as not active
1036    * - update quota for previous address network
1037    * - update quota for this address network
1038    */
1039
1040   prev = find_active_address (s, addresses, peer);
1041   if (NULL != prev)
1042   {
1043       net_prev = (struct Network *) prev->solver_information;
1044       prev->active = GNUNET_NO; /* No active any longer */
1045       prev->assigned_bw_in = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
1046       prev->assigned_bw_out = GNUNET_BANDWIDTH_value_init (0); /* no bw assigned */
1047       s->bw_changed (s->bw_changed_cls, prev); /* notify about bw change, REQUIRED? */
1048       if (GNUNET_SYSERR == addresse_decrement (s, net_prev, GNUNET_NO, GNUNET_YES))
1049         GNUNET_break (0);
1050       update_quota_per_network (s, net_prev, NULL);
1051   }
1052
1053   if (GNUNET_NO == (bw_available_in_network (cur->solver_information)))
1054   {
1055     GNUNET_break (0); /* This should never happen*/
1056     return NULL;
1057   }
1058
1059   cur->active = GNUNET_YES;
1060   addresse_increment(s, net_cur, GNUNET_NO, GNUNET_YES);
1061   update_quota_per_network (s, net_cur, cur);
1062
1063   return cur;
1064 }
1065
1066 /**
1067  * Changes the preferences for a peer in the problem
1068  *
1069  * @param solver the solver handle
1070  * @param client the client with this preference
1071  * @param peer the peer to change the preference for
1072  * @param kind the kind to change the preference
1073  * @param score the score
1074  */
1075 void
1076 GAS_simplistic_address_change_preference (void *solver,
1077                                    void *client,
1078                                    const struct GNUNET_PeerIdentity *peer,
1079                                    enum GNUNET_ATS_PreferenceKind kind,
1080                                    float score)
1081 {
1082   static struct GNUNET_TIME_Absolute next_update;
1083   struct GAS_SIMPLISTIC_Handle *s = solver;
1084   struct PreferenceClient *cur;
1085   struct PreferencePeer *p;
1086   int i;
1087   int clients;
1088   float p_rel_global;
1089   float *dest;
1090
1091
1092   GNUNET_assert (NULL != solver);
1093   GNUNET_assert (NULL != client);
1094   GNUNET_assert (NULL != peer);
1095
1096   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p changes preference for peer `%s' %s %f\n",
1097                                 client,
1098                                 GNUNET_i2s (peer),
1099                                 GNUNET_ATS_print_preference_type (kind),
1100                                 score);
1101
1102   if (kind >= GNUNET_ATS_PreferenceCount)
1103   {
1104       GNUNET_break (0);
1105       return;
1106   }
1107
1108   /**
1109    * Idea:
1110    *
1111    * We have:
1112    * Set of clients c
1113    * Set of peers p_i in P
1114    * Set of preference kinds k
1115    * A preference value f_k_p_i with an unknown range
1116    *
1117    * We get:
1118    * A client specific relative preference f_p_i_rel [1..2] for all peers
1119    *
1120    * For every client c
1121    * {
1122    *   For every preference kind k:
1123    *   {
1124    *     We remember for the preference f_p_i for each peer p_i.
1125    *     We have a default preference value f_p_i = 0
1126    *     We have a sum of all preferences f_t = sum (f_p_i)
1127    *     So we can calculate a relative preference value fr_p_i:
1128    *
1129    *     f_k_p_i_rel = (f_t + f_p_i) / f_t
1130    *     f_k_p_i_rel = [1..2], default 1.0
1131    *    }
1132    *    f_p_i_rel = sum (f_k_p_i_rel) / #k
1133    * }
1134    *
1135    **/
1136
1137   /* Find preference client */
1138   for (cur = s->pc_head; NULL != cur; cur = cur->next)
1139   {
1140       if (client == cur->client)
1141         break;
1142   }
1143   /* Not found: create new preference client */
1144   if (NULL == cur)
1145   {
1146     cur = GNUNET_malloc (sizeof (struct PreferenceClient));
1147     cur->client = client;
1148     GNUNET_CONTAINER_DLL_insert (s->pc_head, s->pc_tail, cur);
1149   }
1150
1151   /* Find entry for peer */
1152   for (p = cur->p_head; NULL != p; p = p->next)
1153     if (0 == memcmp (&p->id, peer, sizeof (p->id)))
1154         break;
1155
1156   /* Not found: create new peer entry */
1157   if (NULL == p)
1158   {
1159       p = GNUNET_malloc (sizeof (struct PreferencePeer));
1160       p->id = (*peer);
1161       for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
1162       {
1163         /* Default value per peer absolut preference for a quality:
1164          * No value set, so absolute preference 0 */
1165         p->f[i] = 0.0;
1166         /* Default value per peer relative preference for a quality: 1.0 */
1167         p->f_rel[i] = DEFAULT_PREFERENCE;
1168       }
1169       GNUNET_CONTAINER_DLL_insert (cur->p_head, cur->p_tail, p);
1170   }
1171
1172   /* Update preference value according to type */
1173   switch (kind) {
1174     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1175     case GNUNET_ATS_PREFERENCE_LATENCY:
1176       p->f[kind] = (p->f[kind] + score) / 2;
1177       break;
1178     case GNUNET_ATS_PREFERENCE_END:
1179       break;
1180     default:
1181       break;
1182   }
1183
1184   /* Recalcalculate total preference for this quality kind over all peers*/
1185   cur->f_total[kind] = 0;
1186   for (p = cur->p_head; NULL != p; p = p->next)
1187     cur->f_total[kind] += p->f[kind];
1188
1189   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p has total preference for %s of %.3f\n",
1190       cur->client,
1191       GNUNET_ATS_print_preference_type (kind),
1192       cur->f_total[kind]);
1193
1194   /* Recalcalculate relative preference for all peers */
1195   for (p = cur->p_head; NULL != p; p = p->next)
1196   {
1197     /* Calculate relative preference for specific kind */
1198     p->f_rel[kind] = (cur->f_total[kind] + p->f[kind]) / cur->f_total[kind];
1199     LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p: peer `%s' has relative preference for %s of %.3f\n",
1200         cur->client,
1201         GNUNET_i2s (&p->id),
1202         GNUNET_ATS_print_preference_type (kind),
1203         p->f_rel[kind]);
1204
1205     /* Calculate peer relative preference
1206      * Start with i = 1 to exclude terminator */
1207     p->f_rel_total = 0;
1208     for (i = 1; i < GNUNET_ATS_PreferenceCount; i ++)
1209     {
1210         p->f_rel_total += p->f_rel[i];
1211     }
1212     p->f_rel_total /=  (GNUNET_ATS_PreferenceCount - 1.0); /* -1 due to terminator */
1213     LOG (GNUNET_ERROR_TYPE_DEBUG, "Client %p: peer `%s' has total relative preference of %.3f\n",
1214         cur->client,
1215         GNUNET_i2s (&p->id),
1216         p->f_rel_total);
1217   }
1218
1219   /* Calculcate global total relative peer preference over all clients */
1220   p_rel_global = 0.0;
1221   clients = 0;
1222   for (cur = s->pc_head; NULL != cur; cur = cur->next)
1223   {
1224       for (p = cur->p_head; NULL != p; p = p->next)
1225           if (0 == memcmp (&p->id, peer, sizeof (p->id)))
1226               break;
1227       if (NULL != p)
1228       {
1229           clients++;
1230           p_rel_global += p->f_rel_total;
1231       }
1232   }
1233   p_rel_global /= clients;
1234   LOG (GNUNET_ERROR_TYPE_DEBUG, "Global preference value for peer `%s': %.3f\n",
1235       GNUNET_i2s (peer), p_rel_global);
1236
1237   /* Update global map */
1238   /* FIXME: We should update all peers since they have influence on each other */
1239   if (NULL != (dest = GNUNET_CONTAINER_multihashmap_get(s->prefs, &peer->hashPubKey)))
1240       (*dest) = p_rel_global;
1241   else
1242   {
1243       dest = GNUNET_malloc (sizeof (float));
1244       (*dest) = p_rel_global;
1245       GNUNET_CONTAINER_multihashmap_put(s->prefs,
1246           &peer->hashPubKey,
1247           dest,
1248           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1249   }
1250
1251   /* FIXME: We should update quotas if UPDATE_INTERVAL is reached */
1252   if (GNUNET_TIME_absolute_get().abs_value > next_update.abs_value)
1253   {
1254       /* update quotas*/
1255       next_update = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
1256                                               MIN_UPDATE_INTERVAL);
1257   }
1258
1259 }
1260
1261 /* end of gnunet-service-ats_addresses_simplistic.c */