added simulation
[oweals/gnunet.git] / src / ats / gnunet-service-ats_normalization.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_normalization.c
23  * @brief ats service address: management of ATS properties and preferences normalization
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_ats_service.h"
29 #include "gnunet-service-ats_addresses.h"
30 #include "gnunet-service-ats_normalization.h"
31
32 #define LOG(kind,...) GNUNET_log_from (kind, "ats-normalization",__VA_ARGS__)
33
34 /**
35  * Preference client
36  */
37 struct PreferenceClient
38 {
39   /**
40    * Next in DLL
41    */
42   struct PreferenceClient *prev;
43
44   /**
45    * Next in DLL
46    */
47
48   struct PreferenceClient *next;
49
50   /**
51    * Client handle
52    */
53   void *client;
54
55   /**
56    * Total preference for this peer
57    */
58   double f_abs_sum[GNUNET_ATS_PreferenceCount];
59
60   /**
61    * List of peer preferences for this client
62    */
63
64   /**
65    * Head of peer list
66    */
67   struct PreferencePeer *p_head;
68
69   /**
70    * Tail of peer list
71    */
72   struct PreferencePeer *p_tail;
73 };
74
75 /**
76  * Preference peer
77  */
78 struct PreferencePeer
79 {
80   /**
81    * Next in DLL
82    */
83   struct PreferencePeer *next;
84
85   /**
86    * Previous in DLL
87    */
88   struct PreferencePeer *prev;
89
90   /**
91    * Client
92    */
93   struct PreferenceClient *client;
94
95   /**
96    * Peer id
97    */
98   struct GNUNET_PeerIdentity id;
99
100   /**
101    * Absolute preference values
102    */
103   double f_abs[GNUNET_ATS_PreferenceCount];
104
105   /**
106    * Relative preference values
107    */
108   double f_rel[GNUNET_ATS_PreferenceCount];
109
110   struct GNUNET_TIME_Absolute next_aging[GNUNET_ATS_PreferenceCount];
111 };
112
113 /**
114  * Relative preferences for a peer
115  */
116 struct PeerRelative
117 {
118   /**
119    * Relative preference values
120    */
121   double f_rel[GNUNET_ATS_PreferenceCount];
122
123   /**
124    * Peer id
125    */
126   struct GNUNET_PeerIdentity id;
127 };
128
129 /**
130  * Callback to call on changing preference values
131  */
132 static GAS_Normalization_preference_changed_cb pref_changed_cb;
133
134 /**
135  * Closure for callback to call on changing preference values
136  */
137 static void *pref_changed_cb_cls;
138
139 /**
140  * Callback to call on changing property values
141  */
142 GAS_Normalization_property_changed_cb prop_ch_cb;
143
144 /**
145  * Closure for callback to call on changing property values
146  */
147 void *prop_ch_cb_cls;
148
149 /**
150  * Hashmap to store peer information for preference normalization
151  */
152 static struct GNUNET_CONTAINER_MultiPeerMap *preference_peers;
153
154 /**
155  * Hashmap to store peer information for property normalization
156  * FIXME: this map is not used!
157  */
158 static struct GNUNET_CONTAINER_MultiPeerMap *property_peers;
159
160 /**
161  * Clients in DLL: head
162  */
163 static struct PreferenceClient *pc_head;
164
165 /**
166  * Clients in DLL: tail
167  */
168 static struct PreferenceClient *pc_tail;
169
170 /**
171  * Default values
172  */
173 static struct PeerRelative defvalues;
174
175 static GNUNET_SCHEDULER_TaskIdentifier aging_task;
176
177 /**
178  * Application Preference Normalization
179  */
180
181 /**
182  * Update a peer
183  * @param id peer id
184  * @param kind the kind
185  * @return the new relative preference
186  */
187 static double
188 update_peers (struct GNUNET_PeerIdentity *id,
189     enum GNUNET_ATS_PreferenceKind kind)
190 {
191   struct PreferenceClient *c_cur;
192   struct PreferencePeer *p_cur;
193   struct PeerRelative *rp;
194   double f_rel_total;
195   double backup;
196   unsigned int count;
197
198   f_rel_total = 0.0;
199   count = 0;
200
201   /* For all clients */
202   for (c_cur = pc_head; NULL != c_cur; c_cur = c_cur->next)
203   {
204     /* Find peer with id */
205     for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
206     {
207       if (0 == memcmp (id, &p_cur->id, sizeof(struct GNUNET_PeerIdentity)))
208         break;
209     }
210     if (NULL != p_cur)
211     {
212       /* Found peer with id */
213       f_rel_total += p_cur->f_rel[kind];
214       count++;
215     }
216   }
217
218   /* Find a client */
219   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
220       "%u clients have a total relative preference for peer `%s''s `%s' of %.3f\n",
221       count, GNUNET_i2s (id), GNUNET_ATS_print_preference_type (kind),
222       f_rel_total);
223   if (NULL != (rp = GNUNET_CONTAINER_multipeermap_get (preference_peers, id)))
224   {
225     backup = rp->f_rel[kind];
226     if (0 < count)
227     {
228       rp->f_rel[kind] = f_rel_total / count;
229     }
230     else
231     {
232       rp->f_rel[kind] = DEFAULT_REL_PREFERENCE;
233     }
234   }
235   else
236   {
237     return DEFAULT_REL_PREFERENCE;
238   }
239
240   if ((backup != rp->f_rel[kind]) && (NULL != pref_changed_cb))
241   {
242     pref_changed_cb (pref_changed_cb_cls, &rp->id, kind, rp->f_rel[kind]);
243   }
244
245   return rp->f_rel[kind];
246 }
247
248 /**
249  * Recalculate preference for a specific ATS property
250  *
251  * @param c the preference client
252  * @param p the peer
253  * @param kind the preference kind
254  * @return the result
255  */
256 static double
257 recalculate_rel_preferences (struct PreferenceClient *c,
258     struct PreferencePeer *p, enum GNUNET_ATS_PreferenceKind kind)
259 {
260   struct PreferencePeer *p_cur;
261   struct PeerRelative *rp;
262   double backup;
263   double res;
264   double ret;
265
266   /* For this client: sum preferences to total preference */
267   c->f_abs_sum[kind] = 0;
268   for (p_cur = c->p_head; NULL != p_cur; p_cur = p_cur->next)
269     c->f_abs_sum[kind] += p_cur->f_abs[kind];
270   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
271       "Client %p has total preference for %s of %.3f\n", c->client,
272       GNUNET_ATS_print_preference_type (kind), c->f_abs_sum[kind]);
273
274   ret = DEFAULT_REL_PREFERENCE;
275   /* For all peers: calculate relative preference */
276   for (p_cur = c->p_head; NULL != p_cur; p_cur = p_cur->next)
277   {
278     /* Calculate relative preference for specific kind */
279     backup = p_cur->f_rel[kind];
280     if (DEFAULT_ABS_PREFERENCE == c->f_abs_sum[kind])
281       /* No peer has a preference for this property,
282        * so set default preference */
283       p_cur->f_rel[kind] = DEFAULT_REL_PREFERENCE;
284     else
285       p_cur->f_rel[kind] = (c->f_abs_sum[kind] + p_cur->f_abs[kind])
286           / c->f_abs_sum[kind];
287
288     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
289         "Client %p: peer `%s' has relative preference for %s of %.3f\n",
290         c->client, GNUNET_i2s (&p_cur->id),
291         GNUNET_ATS_print_preference_type (kind), p_cur->f_rel[kind]);
292
293     if (p_cur->f_rel[kind] != backup)
294     {
295       /* Value changed, recalculate */
296       res = update_peers (&p_cur->id, kind);
297       if (0 == memcmp (&p->id, &p_cur->id, sizeof(struct GNUNET_PeerIdentity)))
298         ret = res;
299     }
300     else
301     {
302       /* Value did not chang, return old value*/
303       GNUNET_assert(
304           NULL != (rp = GNUNET_CONTAINER_multipeermap_get (preference_peers, &p->id)));
305       ret = rp->f_rel[kind];
306     }
307   }
308   return ret;
309 }
310
311 /**
312  * Update the absolute preference value for a peer
313  * @param c the client
314  * @param p the peer
315  * @param kind the preference kind
316  * @param score_abs the absolute value
317  * @return the new relative preference value
318  */
319 static double
320 update_preference (struct PreferenceClient *c, struct PreferencePeer *p,
321     enum GNUNET_ATS_PreferenceKind kind, float score_abs)
322 {
323   double score = score_abs;
324
325   /* Update preference value according to type */
326   switch (kind)
327   {
328   case GNUNET_ATS_PREFERENCE_BANDWIDTH:
329   case GNUNET_ATS_PREFERENCE_LATENCY:
330     p->f_abs[kind] = (p->f_abs[kind] + score) / 2;
331     p->next_aging[kind] = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
332         PREF_AGING_INTERVAL);
333     break;
334   case GNUNET_ATS_PREFERENCE_END:
335     break;
336   default:
337     break;
338   }
339   return recalculate_rel_preferences (c, p, kind);
340 }
341
342 /**
343  * Reduce absolute preferences since they got old
344  *
345  * @param cls the PreferencePeer
346  * @param tc context
347  */
348 static void
349 preference_aging (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
350 {
351   struct PreferencePeer *p;
352   struct PreferenceClient *cur_client;
353   int i;
354   int values_to_update;
355   double backup;
356
357   aging_task = GNUNET_SCHEDULER_NO_TASK;
358   values_to_update = 0;
359   cur_client = NULL;
360
361   for (cur_client = pc_head; NULL != cur_client; cur_client = cur_client->next)
362   {
363     for (p = cur_client->p_head; NULL != p; p = p->next)
364     {
365       /* Aging absolute values: */
366       for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
367       {
368         if (0
369             == GNUNET_TIME_absolute_get_remaining (p->next_aging[i]).rel_value_us)
370         {
371           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
372               "Aging preference for peer `%s'\n", GNUNET_i2s (&p->id));
373           backup = p->f_abs[i];
374           if (p->f_abs[i] > DEFAULT_ABS_PREFERENCE)
375             p->f_abs[i] *= PREF_AGING_FACTOR;
376           if (p->f_abs[i] <= DEFAULT_ABS_PREFERENCE + PREF_EPSILON)
377             p->f_abs[i] = DEFAULT_ABS_PREFERENCE;
378           if ((p->f_abs[i] != DEFAULT_ABS_PREFERENCE)
379               && (backup != p->f_abs[i]))
380           {
381             GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
382                 "Aged preference for peer `%s' from %.3f to %.3f\n",
383                 GNUNET_i2s (&p->id), backup, p->f_abs[i]);
384             recalculate_rel_preferences (p->client, p, i);
385             p->next_aging[i] = GNUNET_TIME_absolute_add (
386                 GNUNET_TIME_absolute_get (), PREF_AGING_INTERVAL);
387             values_to_update++;
388           }
389         }
390       }
391     }
392   }
393
394   if (values_to_update > 0)
395   {
396     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
397         "Rescheduling aging task due to %u elements to age\n",
398         values_to_update);
399     aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL,
400         &preference_aging, NULL );
401   }
402   else
403     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
404         "No values to age left, not rescheduling aging task\n");
405
406 }
407
408 /**
409  * Normalize an updated preference value
410  *
411  * @param src the client with this preference
412  * @param peer the peer to change the preference for
413  * @param kind the kind to change the preference
414  * @param score_abs the normalized score
415  */
416 void
417 GAS_normalization_normalize_preference (void *src,
418     const struct GNUNET_PeerIdentity *peer, enum GNUNET_ATS_PreferenceKind kind,
419     float score_abs)
420 {
421   struct PreferenceClient *c_cur;
422   struct PreferencePeer *p_cur;
423   struct PeerRelative *r_cur;
424   int i;
425
426   GNUNET_assert(NULL != src);
427   GNUNET_assert(NULL != peer);
428
429   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
430       "Client %p changes preference for peer `%s' for `%s' to %.2f\n", src,
431       GNUNET_i2s (peer), GNUNET_ATS_print_preference_type (kind), score_abs);
432
433   if (kind >= GNUNET_ATS_PreferenceCount)
434   {
435     GNUNET_break(0);
436     return;
437   }
438
439   /* Find preference client */
440   for (c_cur = pc_head; NULL != c_cur; c_cur = c_cur->next)
441   {
442     if (src == c_cur->client)
443       break;
444   }
445   /* Not found: create new preference client */
446   if (NULL == c_cur)
447   {
448     c_cur = GNUNET_malloc (sizeof (struct PreferenceClient));
449     c_cur->client = src;
450     GNUNET_CONTAINER_DLL_insert(pc_head, pc_tail, c_cur);
451     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding new client %p \n", c_cur);
452   }
453
454   /* Find entry for peer */
455   for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
456     if (0 == memcmp (&p_cur->id, peer, sizeof(p_cur->id)))
457       break;
458
459   /* Not found: create new peer entry */
460   if (NULL == p_cur)
461   {
462     p_cur = GNUNET_malloc (sizeof (struct PreferencePeer));
463     p_cur->client = c_cur;
464     p_cur->id = (*peer);
465     for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
466     {
467       /* Default value per peer absolut preference for a quality:
468        * No value set, so absolute preference 0 */
469       p_cur->f_abs[i] = DEFAULT_ABS_PREFERENCE;
470       /* Default value per peer relative preference for a quality: 1.0 */
471       p_cur->f_rel[i] = DEFAULT_REL_PREFERENCE;
472       p_cur->next_aging[i] = GNUNET_TIME_UNIT_FOREVER_ABS;
473     }
474     GNUNET_CONTAINER_DLL_insert(c_cur->p_head, c_cur->p_tail, p_cur);
475   }
476
477   if (NULL == GNUNET_CONTAINER_multipeermap_get (preference_peers, peer))
478   {
479     r_cur = GNUNET_malloc (sizeof (struct PeerRelative));
480     r_cur->id = (*peer);
481     for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
482       r_cur->f_rel[i] = DEFAULT_REL_PREFERENCE;
483     GNUNET_CONTAINER_multipeermap_put (preference_peers, &r_cur->id, r_cur,
484         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
485   }
486
487   if (GNUNET_SCHEDULER_NO_TASK == aging_task)
488     aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL,
489         &preference_aging, NULL );
490
491   update_preference (c_cur, p_cur, kind, score_abs);
492 }
493
494 /**
495  * Get the normalized preference values for a specific peer or
496  * the default values if
497  *
498  * @param id the peer
499  * @return pointer to the values, can be indexed with GNUNET_ATS_PreferenceKind,
500  * default preferences if peer does not exist
501  */
502 const double *
503 GAS_normalization_get_preferences_by_peer (const struct GNUNET_PeerIdentity *id)
504 {
505   GNUNET_assert(NULL != preference_peers);
506   GNUNET_assert(NULL != id);
507
508   struct PeerRelative *rp;
509   if (NULL == (rp = GNUNET_CONTAINER_multipeermap_get (preference_peers, id)))
510   {
511     return defvalues.f_rel;
512   }
513   return rp->f_rel;
514 }
515
516 /**
517  * Get the normalized preference values for a specific client and peer
518  *
519  * @param client client
520  * @param peer the peer
521  * @param pref the preference type
522  * @return the value
523  */
524 const double
525 GAS_normalization_get_preferences_by_client (const void *client,
526     struct GNUNET_PeerIdentity *peer, enum GNUNET_ATS_PreferenceKind pref)
527 {
528   struct PreferenceClient *c_cur;
529   struct PreferencePeer *p_cur;
530
531   /* Find preference client */
532   for (c_cur = pc_head; NULL != c_cur; c_cur = c_cur->next)
533   {
534     if (client == c_cur->client)
535       break;
536   }
537   if (NULL == c_cur)
538     return -1.0;
539
540   for (p_cur = c_cur->p_head; NULL != p_cur; p_cur = p_cur->next)
541   {
542     if (0 == memcmp (peer, &p_cur->id, sizeof (struct GNUNET_PeerIdentity)))
543       break;
544   }
545   if (NULL == p_cur)
546     return DEFAULT_REL_PREFERENCE; /* Not found, return default */
547
548   return p_cur->f_rel[pref];
549 }
550
551 /**
552  * Get the normalized properties values for a specific peer or
553  * the default values if
554  *
555  * @param address the address
556  * @return pointer to the values, can be indexed with GNUNET_ATS_PreferenceKind,
557  * default preferences if peer does not exist
558  */
559 const double *
560 GAS_normalization_get_properties (struct ATS_Address *address)
561 {
562   static double norm_values[GNUNET_ATS_QualityPropertiesCount];
563   int i;
564
565   GNUNET_assert(NULL != address);
566
567   for (i = 0; i < GNUNET_ATS_QualityPropertiesCount; i++)
568   {
569     if ((address->atsin[i].norm >= 1.0) && (address->atsin[i].norm <= 2.0))
570       norm_values[i] = address->atsin[i].norm;
571     else
572       norm_values[i] = DEFAULT_REL_QUALITY;
573   }
574   return norm_values;
575 }
576
577 /**
578  * Quality Normalization
579  */
580
581 struct Property
582 {
583   uint32_t prop_type;
584   uint32_t atsi_type;
585   uint32_t min;
586   uint32_t max;
587 };
588
589 struct Property properties[GNUNET_ATS_QualityPropertiesCount];
590
591 /**
592  * Normalize a specific ATS type with the values in queue
593  * @param address the address
594  * @param atsi the ats information
595  * @return the new average or GNUNET_ATS_VALUE_UNDEFINED
596  */
597
598 uint32_t
599 property_average (struct ATS_Address *address,
600     const struct GNUNET_ATS_Information *atsi)
601 {
602   struct GAS_NormalizationInfo *ni;
603   uint32_t current_type;
604   uint32_t current_val;
605   uint32_t res;
606   uint64_t sum;
607   uint32_t count;
608   unsigned int c1;
609   unsigned int index;
610   unsigned int props[] = GNUNET_ATS_QualityProperties;
611
612   /* Average the values of this property */
613   current_type = ntohl (atsi->type);
614   current_val = ntohl (atsi->value);
615
616   for (c1 = 0; c1 < GNUNET_ATS_QualityPropertiesCount; c1++)
617   {
618     if (current_type == props[c1])
619       break;
620   }
621   if (c1 == GNUNET_ATS_QualityPropertiesCount)
622   {
623     GNUNET_break(0);
624     return GNUNET_ATS_VALUE_UNDEFINED;
625   }
626   index = c1;
627
628   ni = &address->atsin[index];
629   ni->atsi_abs[ni->avg_queue_index] = current_val;
630   ni->avg_queue_index++;
631   if (GAS_normalization_queue_length == ni->avg_queue_index)
632     ni->avg_queue_index = 0;
633
634   count = 0;
635   sum = 0;
636   for (c1 = 0; c1 < GAS_normalization_queue_length; c1++)
637   {
638     if (GNUNET_ATS_VALUE_UNDEFINED != ni->atsi_abs[c1])
639     {
640       count++;
641       if (GNUNET_ATS_VALUE_UNDEFINED > (sum + ni->atsi_abs[c1]))
642         sum += ni->atsi_abs[c1];
643       else
644       {
645         sum = GNUNET_ATS_VALUE_UNDEFINED - 1;
646         GNUNET_break(0);
647       }
648     }
649   }
650   GNUNET_assert(0 != count);
651   res = sum / count;
652   LOG(GNUNET_ERROR_TYPE_DEBUG,
653       "New average of `%s' created by adding %u from %u elements: %u\n",
654       GNUNET_ATS_print_property_type (current_type), current_val, count, res,
655       sum);
656   ni->avg = res;
657   return res;
658 }
659
660 struct FindMinMaxCtx
661 {
662   struct Property *p;
663   uint32_t min;
664   uint32_t max;
665 };
666
667 static int
668 find_min_max_it (void *cls, const struct GNUNET_PeerIdentity *h, void *k)
669 {
670   struct FindMinMaxCtx *find_res = cls;
671   struct ATS_Address *a = k;
672
673   if (a->atsin[find_res->p->prop_type].avg > find_res->max)
674     find_res->max = a->atsin[find_res->p->prop_type].avg;
675
676   if (a->atsin[find_res->p->prop_type].avg < find_res->min)
677     find_res->min = a->atsin[find_res->p->prop_type].avg;
678
679   return GNUNET_OK;
680 }
681
682 static int
683 normalize_address (void *cls, const struct GNUNET_PeerIdentity *h, void *k)
684 {
685   struct Property *p = cls;
686   struct ATS_Address *address = k;
687
688   double delta;
689   uint32_t avg_value = address->atsin[p->prop_type].avg;
690
691   delta = p->max - p->min;
692   address->atsin[p->prop_type].norm = (delta + (avg_value - p->min)) / (delta);
693
694   LOG(GNUNET_ERROR_TYPE_DEBUG,
695       "Normalize `%s' address %p's '%s' with value %u to range [%u..%u] = %.3f\n",
696       GNUNET_i2s (&address->peer), address,
697       GNUNET_ATS_print_property_type (p->atsi_type),
698       address->atsin[p->prop_type].avg, p->min, p->max,
699       address->atsin[p->prop_type].norm);
700
701   if (NULL != prop_ch_cb)
702     prop_ch_cb (prop_ch_cb_cls, address, p->atsi_type,
703         address->atsin[p->prop_type].norm);
704
705   return GNUNET_OK;
706 }
707
708 /**
709  * Normalize avg_value to a range of values between [1.0, 2.0]
710  * based on min max values currently known.
711  *
712  * @param addresses the address hashmap
713  * @param p the property
714  * @param address the address
715  * @param avg_value the value to normalize
716  */
717 static void
718 property_normalize (struct GNUNET_CONTAINER_MultiPeerMap *addresses,
719     struct Property *p, struct ATS_Address *address, uint32_t avg_value)
720 {
721   struct FindMinMaxCtx find_ctx;
722   int addr_count;
723   int limits_changed;
724
725   find_ctx.p = p;
726   find_ctx.max = 0;
727   find_ctx.min = UINT32_MAX;
728   addr_count = GNUNET_CONTAINER_multipeermap_iterate (addresses,
729       &find_min_max_it, &find_ctx);
730   if (0 == addr_count)
731   {
732     GNUNET_break(0);
733     return;
734   }
735
736   limits_changed = GNUNET_NO;
737   if (find_ctx.max != p->max)
738   {
739     LOG(GNUNET_ERROR_TYPE_DEBUG,
740         "Normalizing %s: new maximum %u -> recalculate all values\n",
741         GNUNET_ATS_print_property_type (p->atsi_type), find_ctx.max);
742     p->max = find_ctx.max;
743     limits_changed = GNUNET_YES;
744   }
745
746   if ((find_ctx.min != p->min) && (find_ctx.min < p->max))
747   {
748     LOG(GNUNET_ERROR_TYPE_DEBUG,
749         "Normalizing %s: new minimum %u -> recalculate all values\n",
750         GNUNET_ATS_print_property_type (p->atsi_type), find_ctx.min,
751         find_ctx.max);
752     p->min = find_ctx.min;
753     limits_changed = GNUNET_YES;
754   }
755   else if (find_ctx.min == p->max)
756   {
757     /* Only one value, so minimum has to be 0 */
758     p->min = 0;
759   }
760
761   /* Normalize the values of this property */
762   if (GNUNET_NO == limits_changed)
763   {
764     /* normalize just this  address */
765     normalize_address (p, &address->peer, address);
766     return;
767   }
768   else
769   {
770     /* limits changed, normalize all addresses */
771     GNUNET_CONTAINER_multipeermap_iterate (addresses, &normalize_address, p);
772     return;
773   }
774 }
775
776 /**
777  * Update and normalize atsi performance information
778  *
779  * @param addresses hashmap containing all addresses
780  * @param address the address to update
781  * @param atsi the array of performance information
782  * @param atsi_count the number of atsi information in the array
783  */
784 void
785 GAS_normalization_normalize_property (
786     struct GNUNET_CONTAINER_MultiPeerMap *addresses,
787     struct ATS_Address *address, const struct GNUNET_ATS_Information *atsi,
788     uint32_t atsi_count)
789 {
790   struct Property *cur_prop;
791   int c1;
792   int c2;
793   uint32_t current_type;
794   uint32_t current_val;
795   unsigned int existing_properties[] = GNUNET_ATS_QualityProperties;
796
797   GNUNET_assert(NULL != address);
798   GNUNET_assert(NULL != atsi);
799
800   LOG(GNUNET_ERROR_TYPE_DEBUG, "Updating %u elements for peer `%s'\n",
801       atsi_count, GNUNET_i2s (&address->peer));
802
803   for (c1 = 0; c1 < atsi_count; c1++)
804   {
805     current_type = ntohl (atsi[c1].type);
806
807     for (c2 = 0; c2 < GNUNET_ATS_QualityPropertiesCount; c2++)
808     {
809       /* Check if type is valid */
810       if (current_type == existing_properties[c2])
811         break;
812     }
813     if (GNUNET_ATS_QualityPropertiesCount == c2)
814     {
815       /* Invalid property, continue with next element */
816       continue;
817     }
818     /* Averaging */
819     current_val = property_average (address, &atsi[c1]);
820     if (GNUNET_ATS_VALUE_UNDEFINED == current_val)
821     {
822       GNUNET_break(0);
823       continue;
824     }
825
826     /* Normalizing */
827     /* Check min, max */
828     cur_prop = &properties[c2];
829     property_normalize (addresses, cur_prop, address, current_val);
830   }
831 }
832
833 static void
834 free_client (struct PreferenceClient *pc)
835 {
836   struct PreferencePeer *next_p;
837   struct PreferencePeer *p;
838   next_p = pc->p_head;
839   while (NULL != (p = next_p))
840   {
841     next_p = p->next;
842     GNUNET_CONTAINER_DLL_remove(pc->p_head, pc->p_tail, p);
843     GNUNET_free(p);
844   }
845   GNUNET_free(pc);
846 }
847
848 /**
849  * A performance client disconnected
850  *
851  * @param client the client
852  */
853
854 void
855 GAS_normalization_preference_client_disconnect (void *client)
856 {
857   struct PreferenceClient *c_cur;
858   /* Find preference client */
859
860   for (c_cur = pc_head; NULL != c_cur; c_cur = c_cur->next)
861   {
862     if (client == c_cur->client)
863       break;
864   }
865   if (NULL == c_cur)
866     return;
867
868   GNUNET_CONTAINER_DLL_remove(pc_head, pc_tail, c_cur);
869   free_client (c_cur);
870 }
871
872 /**
873  * Start the normalization component
874  *
875  * @param pref_ch_cb callback to call on relative preference changing
876  * @param pref_ch_cb_cls cls for the preference callback
877  * @param property_ch_cb callback to call on relative property changing
878  * @param property_ch_cb_cls cls for the property callback
879  */
880 void
881 GAS_normalization_start (GAS_Normalization_preference_changed_cb pref_ch_cb,
882     void *pref_ch_cb_cls, GAS_Normalization_property_changed_cb property_ch_cb,
883     void *property_ch_cb_cls)
884 {
885   int c1;
886   int i;
887   preference_peers = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
888   property_peers = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
889   unsigned int existing_properties[] = GNUNET_ATS_QualityProperties;
890
891   for (c1 = 0; c1 < GNUNET_ATS_QualityPropertiesCount; c1++)
892   {
893     properties[c1].prop_type = c1;
894     properties[c1].atsi_type = existing_properties[c1];
895     properties[c1].min = 0;
896     properties[c1].max = 0;
897   }
898
899   pref_changed_cb = pref_ch_cb;
900   pref_changed_cb_cls = pref_ch_cb_cls;
901   prop_ch_cb = property_ch_cb;
902   prop_ch_cb_cls = pref_ch_cb_cls;
903
904   pc_head = NULL;
905   pc_tail = NULL;
906
907   for (i = 0; i < GNUNET_ATS_PreferenceCount; i++)
908     defvalues.f_rel[i] = DEFAULT_REL_PREFERENCE;
909   aging_task = GNUNET_SCHEDULER_NO_TASK;
910   return;
911 }
912
913 /**
914  * Free a peer
915  *
916  * @param cls unused
917  * @param key the key
918  * @param value RelativePeer
919  * @return #GNUNET_OK to continue
920  */
921 static int
922 free_peer (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
923 {
924   struct PeerRelative *rp = value;
925   if (GNUNET_YES
926       == GNUNET_CONTAINER_multipeermap_remove (preference_peers, key, value))
927     GNUNET_free(rp);
928   else
929     GNUNET_break(0);
930   return GNUNET_OK;
931 }
932
933 /**
934  * Stop the normalization component and free all items
935  */
936 void
937 GAS_normalization_stop ()
938 {
939   struct PreferenceClient *pc;
940   struct PreferenceClient *next_pc;
941
942   if (GNUNET_SCHEDULER_NO_TASK != aging_task)
943   {
944     GNUNET_SCHEDULER_cancel (aging_task);
945     aging_task = GNUNET_SCHEDULER_NO_TASK;
946   }
947
948   next_pc = pc_head;
949   while (NULL != (pc = next_pc))
950   {
951     next_pc = pc->next;
952     GNUNET_CONTAINER_DLL_remove(pc_head, pc_tail, pc);
953     free_client (pc);
954   }
955
956   GNUNET_CONTAINER_multipeermap_iterate (preference_peers, &free_peer, NULL );
957   GNUNET_CONTAINER_multipeermap_destroy (preference_peers);
958   GNUNET_CONTAINER_multipeermap_destroy (property_peers);
959   return;
960 }
961
962 /* end of gnunet-service-ats_normalization.c */