adding additional INFO
[oweals/gnunet.git] / src / ats / libgnunet_plugin_ats_ril.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/libgnunet_plugin_ats_ril.c
23  * @brief ATS reinforcement learning solver
24  * @author Fabian Oehlmann
25  * @author Matthias Wachs
26  */
27 #include "libgnunet_plugin_ats_ril.h"
28
29 #define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__)
30
31 #define RIL_ACTION_INVALID -1
32 #define RIL_FEATURES_ADDRESS_COUNT (3 + GNUNET_ATS_QualityPropertiesCount)
33 #define RIL_FEATURES_NETWORK_COUNT 4
34
35 #define RIL_DEFAULT_STEP_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 3000)
36 #define RIL_DEFAULT_ALGORITHM RIL_ALGO_Q
37 #define RIL_DEFAULT_DISCOUNT_FACTOR 0.5
38 #define RIL_DEFAULT_GRADIENT_STEP_SIZE 0.4
39 #define RIL_DEFAULT_TRACE_DECAY 0.6
40 #define RIL_EXPLORE_RATIO 0.1
41
42 /**
43  * ATS reinforcement learning solver
44  *
45  * General description
46  */
47
48 /**
49  * The actions, how an agent can manipulate the current assignment. I.e. how the bandwidth can be
50  * changed for the currently chosen address. Not depicted in the enum are the actions of switching
51  * to a particular address. The action of switching to address with index i is depicted by the
52  * number (RIL_ACTION_TYPE_NUM + i).
53  */
54 enum RIL_Action_Type
55 {
56   RIL_ACTION_NOTHING = 0,
57   RIL_ACTION_BW_IN_DBL = 1,
58   RIL_ACTION_BW_IN_HLV = 2,
59   RIL_ACTION_BW_IN_INC = 3,
60   RIL_ACTION_BW_IN_DEC = 4,
61   RIL_ACTION_BW_OUT_DBL = 5,
62   RIL_ACTION_BW_OUT_HLV = 6,
63   RIL_ACTION_BW_OUT_INC = 7,
64   RIL_ACTION_BW_OUT_DEC = 8,
65   RIL_ACTION_TYPE_NUM = 9
66 };
67
68 enum RIL_Algorithm
69 {
70   RIL_ALGO_SARSA = 0,
71   RIL_ALGO_Q = 1
72 };
73
74 enum RIL_E_Modification
75 {
76   RIL_E_SET,
77   RIL_E_ZERO,
78   RIL_E_ACCUMULATE,
79   RIL_E_REPLACE
80 };
81
82 /**
83  * Global learning parameters
84  */
85 struct RIL_Learning_Parameters
86 {
87   /**
88    * The TD-algorithm to use
89    */
90   enum RIL_Algorithm algorithm;
91
92   /**
93    * Learning discount factor in the TD-update
94    */
95   float gamma;
96
97   /**
98    * Gradient-descent step-size
99    */
100   float alpha;
101
102   /**
103    * Trace-decay factor for eligibility traces
104    */
105   float lambda;
106 };
107
108 /**
109  * Wrapper for addresses to store them in agent's linked list
110  */
111 struct RIL_Address_Wrapped
112 {
113   /**
114    * Next in DLL
115    */
116   struct RIL_Address_Wrapped *next;
117
118   /**
119    * Previous in DLL
120    */
121   struct RIL_Address_Wrapped *prev;
122
123   /**
124    * The address
125    */
126   struct ATS_Address *address_naked;
127 };
128
129 struct RIL_Peer_Agent
130 {
131   /**
132    * Next agent in solver's linked list
133    */
134   struct RIL_Peer_Agent *next;
135
136   /**
137    * Previous agent in solver's linked list
138    */
139   struct RIL_Peer_Agent *prev;
140
141   /**
142    * Environment handle
143    */
144   struct GAS_RIL_Handle *envi;
145
146   /**
147    * Peer ID
148    */
149   struct GNUNET_PeerIdentity peer;
150
151   /**
152    * Whether the agent is active or not
153    */
154   int is_active;
155
156   /**
157    * Number of performed time-steps
158    */
159   unsigned long long step_count;
160
161   /**
162    * Experience matrix W
163    */
164   double ** W;
165
166   /**
167    * Number of rows of W / Number of state-vector features
168    */
169   unsigned int m;
170
171   /**
172    * Number of columns of W / Number of actions
173    */
174   unsigned int n;
175
176   /**
177    * Last perceived state feature vector
178    */
179   double * s_old;
180
181   /**
182    * Last chosen action
183    */
184   int a_old;
185
186   /**
187    * Eligibility trace vector
188    */
189   double * e;
190
191   /**
192    * Address in use
193    */
194   struct ATS_Address * address_inuse;
195
196   /**
197    * Head of addresses DLL
198    */
199   struct RIL_Address_Wrapped * addresses_head;
200
201   /**
202    * Tail of addresses DLL
203    */
204   struct RIL_Address_Wrapped * addresses_tail;
205
206   /**
207    * Inbound bandwidth assigned by the agent
208    */
209   unsigned long long bw_in;
210
211   /**
212    * Outbound bandwidth assigned by the agent
213    */
214   unsigned long long bw_out;
215 };
216
217 struct RIL_Network
218 {
219   /**
220    * ATS network type
221    */
222   enum GNUNET_ATS_Network_Type type;
223
224   /**
225    * Total available inbound bandwidth
226    */
227   unsigned long long bw_in_available;
228
229   /**
230    * Total assigned outbound bandwidth
231    */
232   unsigned long long bw_in_assigned;
233
234   /**
235    * Total available outbound bandwidth
236    */
237   unsigned long long bw_out_available;
238
239   /**
240    * Total assigned outbound bandwidth
241    */
242   unsigned long long bw_out_assigned;
243 };
244
245 /**
246  * A handle for the reinforcement learning solver
247  */
248 struct GAS_RIL_Handle
249 {
250   /**
251    *
252    */
253   struct GNUNET_ATS_PluginEnvironment *plugin_envi;
254
255   /**
256    * Statistics handle
257    */
258   struct GNUNET_STATISTICS_Handle *stats;
259
260   /**
261    * Number of performed epochs
262    */
263   unsigned long long epoch_count;
264
265   /**
266    * Number of performed steps
267    */
268   unsigned long long step_count;
269
270   /**
271    * Interval time between steps in milliseconds //TODO? Future Work: Heterogeneous stepping among agents
272    */
273   struct GNUNET_TIME_Relative step_time;
274
275   /**
276    * Task identifier of the next time-step to be executed
277    */
278   GNUNET_SCHEDULER_TaskIdentifier next_step;
279
280   /**
281    * Lock for bulk operations
282    */
283   int bulk_lock;
284
285   /**
286    * Number of changes during a lock
287    */
288   int bulk_changes;
289
290   /**
291    * Learning parameters
292    */
293   struct RIL_Learning_Parameters parameters;
294
295   /**
296    * Array of networks with global assignment state
297    */
298   struct RIL_Network * network_entries;
299
300   /**
301    * Networks count
302    */
303   unsigned int networks_count;
304
305   /**
306    * List of active peer-agents
307    */
308   struct RIL_Peer_Agent * agents_head;
309   struct RIL_Peer_Agent * agents_tail;
310 };
311
312 /*
313  *  Private functions
314  *  ---------------------------
315  */
316
317 /**
318  * Estimate the current action-value for state s and action a
319  *
320  * @param agent agent performing the estimation
321  * @param state s
322  * @param action a
323  * @return estimation value
324  */
325 static double
326 agent_estimate_q (struct RIL_Peer_Agent *agent, double *state, int action)
327 {
328   int i;
329   double result = 0;
330
331   for (i = 0; i < agent->m; i++)
332   {
333     result += state[i] * agent->W[action][i];
334   }
335
336   return result;
337 }
338
339 /**
340  * Decide whether to do exploration (i.e. taking a new action) or exploitation (i.e. taking the
341  * currently estimated best action) in the current step
342  *
343  * @param agent agent performing the step
344  * @return yes, if exploring
345  */
346 static int
347 agent_decide_exploration (struct RIL_Peer_Agent *agent)
348 {
349   //TODO? Future Work: Improve exploration/exploitation trade-off by different mechanisms than e-greedy
350   /*
351    * An e-greedy replacement could be based on the accuracy of the prediction of the Q-value
352    */
353   double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
354       UINT32_MAX) / (double) UINT32_MAX;
355
356 if  (r < RIL_EXPLORE_RATIO)
357   {
358     return GNUNET_YES;
359   }
360   return GNUNET_NO;
361 }
362
363   /**
364    * Get the index of the address in the agent's list.
365    *
366    * @param agent agent handle
367    * @param address address handle
368    * @return the index, starting with zero
369    */
370 static int
371 agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
372 {
373   int i;
374   struct RIL_Address_Wrapped *cur;
375
376   i = -1;
377   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
378   {
379     i++;
380     if (cur->address_naked == address)
381     {
382       return i;
383     }
384   }
385
386   return i;
387 }
388
389 /**
390  * Gets the wrapped address from the agent's list
391  *
392  * @param agent agent handle
393  * @param address address handle
394  * @return wrapped address
395  */
396 static struct RIL_Address_Wrapped *
397 agent_address_get (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
398 {
399   struct RIL_Address_Wrapped *cur;
400
401   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
402   {
403     if (cur->address_naked == address)
404     {
405       return cur;
406     }
407   }
408
409   return NULL ;
410 }
411
412 /**
413  * Gets the action, with the maximal estimated Q-value (i.e. the one currently estimated to bring the
414  * most reward in the future)
415  *
416  * @param agent agent performing the calculation
417  * @param state the state from which to take the action
418  * @return the action promising most future reward
419  */
420 static int
421 agent_get_action_best (struct RIL_Peer_Agent *agent, double *state)
422 {
423   int i;
424   int max_i = RIL_ACTION_INVALID;
425   double cur_q;
426   double max_q = -DBL_MAX;
427
428   for (i = 0; i < agent->n; i++)
429   {
430     cur_q = agent_estimate_q (agent, state, i);
431     if (cur_q > max_q)
432     {
433       max_q = cur_q;
434       max_i = i;
435     }
436   }
437
438   GNUNET_assert(RIL_ACTION_INVALID != max_i);
439
440   return max_i;
441 }
442
443 /**
444  * Gets any action, to explore the action space from that state
445  *
446  * @param agent agent performing the calculation
447  * @param state the state from which to take the action
448  * @return any action
449  */
450 static int
451 agent_get_action_explore (struct RIL_Peer_Agent *agent, double *state)
452 {
453   // TODO?: Future Work: Choose the action for exploration, which has been explored the least in this state
454   return GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, agent->n);
455 }
456
457 /**
458  * Updates the weights (i.e. coefficients) of the weight vector in matrix W for action a
459  *
460  * @param agent the agent performing the update
461  * @param reward the reward received for the last action
462  * @param s_next the new state, the last step got the agent into
463  * @param a_prime the new
464  */
465 static void
466 agent_update_weights (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime)
467 {
468   int i;
469   double delta;
470   double *theta = agent->W[agent->a_old];
471
472   delta = reward + agent_estimate_q (agent, s_next, a_prime)
473       - agent_estimate_q (agent, agent->s_old, agent->a_old);
474   for (i = 0; i < agent->m; i++)
475   {
476     theta[i] += agent->envi->parameters.alpha * delta * (agent->e)[i];
477   }
478 }
479
480 /**
481  * Changes the eligibility trace vector e in various manners:
482  * RIL_E_ACCUMULATE - adds 1 to each component as in accumulating eligibility traces
483  * RIL_E_REPLACE - resets each component to 1 as in replacing traces
484  * RIL_E_SET - multiplies e with gamma and lambda as in the update rule
485  * RIL_E_ZERO - sets e to 0 as in Watkin's Q-learning algorithm when exploring and when initializing
486  *
487  * @param agent the agent handle
488  * @param mod the kind of modification
489  */
490 static void
491 agent_modify_eligibility (struct RIL_Peer_Agent *agent, enum RIL_E_Modification mod)
492 {
493   int i;
494   double *e = agent->e;
495   double gamma = agent->envi->parameters.gamma;
496   double lambda = agent->envi->parameters.lambda;
497
498   for (i = 0; i < agent->m; i++)
499   {
500     switch (mod)
501     {
502     case RIL_E_ACCUMULATE:
503       e[i] += 1;
504       break;
505     case RIL_E_REPLACE:
506       e[i] = 1;
507       break;
508     case RIL_E_SET:
509       e[i] = gamma * lambda;
510       break;
511     case RIL_E_ZERO:
512       e[i] = 0;
513       break;
514     }
515   }
516 }
517
518 static void ril_inform (struct GAS_RIL_Handle *solver,
519     enum GAS_Solver_Operation op, enum GAS_Solver_Status stat)
520 {
521   if (NULL != solver->plugin_envi->info_cb)
522     solver->plugin_envi->info_cb (solver->plugin_envi->info_cb_cls, op, stat, GAS_INFO_NONE);
523 }
524
525 /**
526  * Changes the active assignment suggestion of the handler and invokes the bw_changed callback to
527  * notify ATS of its new decision
528  *
529  * @param solver solver handle
530  * @param agent agent handle
531  * @param new_address the address which is to be used
532  * @param new_bw_in the new amount of inbound bandwidth set for this address
533  * @param new_bw_out the new amount of outbound bandwidth set for this address
534  * @param silent disables invocation of the bw_changed callback, if GNUNET_YES
535  */
536 static void
537 envi_set_active_suggestion (struct GAS_RIL_Handle *solver,
538     struct RIL_Peer_Agent *agent,
539     struct ATS_Address *new_address,
540     unsigned long long new_bw_in,
541     unsigned long long new_bw_out,
542     int silent)
543 {
544   int notify = GNUNET_NO;
545
546   LOG(GNUNET_ERROR_TYPE_DEBUG, "set_active_suggestion()\n");
547
548   //address change
549   if (agent->address_inuse != new_address)
550   {
551     if (NULL != agent->address_inuse)
552     {
553       agent->address_inuse->active = GNUNET_NO;
554       agent->address_inuse->assigned_bw_in.value__ = htonl (0);
555       agent->address_inuse->assigned_bw_out.value__ = htonl (0);
556     }
557     if (NULL != new_address)
558     {
559       LOG(GNUNET_ERROR_TYPE_DEBUG, "set address active: %s\n", agent->is_active ? "yes" : "no");
560       new_address->active = agent->is_active;
561       new_address->assigned_bw_in.value__ = htonl (agent->bw_in);
562       new_address->assigned_bw_out.value__ = htonl (agent->bw_out);
563     }
564     notify |= GNUNET_YES;
565   }
566
567   if (new_address)
568   {
569     //activity change
570     if (new_address->active != agent->is_active)
571     {
572       new_address->active = agent->is_active;
573     }
574
575     //bw change
576     if (agent->bw_in != new_bw_in)
577     {
578       agent->bw_in = new_bw_in;
579       new_address->assigned_bw_in.value__ = htonl (new_bw_out);
580       notify |= GNUNET_YES;
581     }
582     if (agent->bw_out != new_bw_out)
583     {
584       agent->bw_out = new_bw_out;
585       new_address->assigned_bw_out.value__ = htonl (new_bw_out);
586       notify |= GNUNET_YES;
587     }
588   }
589
590   if (notify && agent->is_active && (GNUNET_NO == silent))
591   {
592     if (new_address)
593     {
594       solver->plugin_envi->bandwidth_changed_cb (solver->plugin_envi->bw_changed_cb_cls,
595           new_address);
596     }
597     else if (agent->address_inuse)
598     {
599       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_in.value__));
600       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_out.value__));
601       agent->bw_in = 0;
602       agent->bw_out = 0;
603       //disconnect
604       solver->plugin_envi->bandwidth_changed_cb (solver->plugin_envi->bw_changed_cb_cls,
605           agent->address_inuse);
606     }
607   }
608   agent->address_inuse = new_address;
609 }
610
611 /**
612  * Allocates a state vector and fills it with the features present
613  * @param solver the solver handle
614  * @param agent the agent handle
615  * @return pointer to the state vector
616  */
617 static double *
618 envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
619 {
620   int i;
621   int k;
622   struct RIL_Network *net;
623   double *state = GNUNET_malloc (sizeof (double) * agent->m);
624   struct RIL_Address_Wrapped *cur_address;
625   const double *properties;
626
627   for (i = 0; i < solver->networks_count; i++)
628   {
629     net = &solver->network_entries[i];
630     state[i * RIL_FEATURES_NETWORK_COUNT + 0] = (double) net->bw_in_assigned;
631     state[i * RIL_FEATURES_NETWORK_COUNT + 1] = (double) net->bw_in_available;
632     state[i * RIL_FEATURES_NETWORK_COUNT + 2] = (double) net->bw_out_assigned;
633     state[i * RIL_FEATURES_NETWORK_COUNT + 3] = (double) net->bw_out_available;
634   }
635
636   i = i * RIL_FEATURES_NETWORK_COUNT; //first address feature
637
638   for (cur_address = agent->addresses_head; NULL != cur_address; cur_address = cur_address->next)
639   {
640     state[i++] = cur_address->address_naked->active;
641     state[i++] = cur_address->address_naked->active ? agent->bw_in : 0;
642     state[i++] = cur_address->address_naked->active ? agent->bw_out : 0;
643     properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
644         cur_address->address_naked);
645     for (k = 0; k < GNUNET_ATS_QualityPropertiesCount; k++)
646     {
647       state[i++] = properties[k];
648     }
649   }
650
651   return state;
652 }
653
654 /**
655  * For all networks a peer has an address in, this gets the maximum bandwidth which could
656  * theoretically be available in one of the networks. This is used for bandwidth normalization.
657  *
658  * @param agent the agent handle
659  * @param direction_in whether the inbound bandwidth should be considered. Returns the maximum outbound bandwidth if GNUNET_NO
660  */
661 static long long unsigned
662 ril_get_max_bw (struct RIL_Peer_Agent *agent, int direction_in)
663 {
664   /*
665    * get the maximum bandwidth possible for a peer, e.g. among all addresses which addresses'
666    * network could provide the maximum bandwidth if all that bandwidth was used on that one peer.
667    */
668   int max = 0;
669   struct RIL_Address_Wrapped *cur;
670   struct RIL_Network *net;
671
672   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
673   {
674     net = cur->address_naked->solver_information;
675     if (direction_in)
676     {
677       if (net->bw_in_available > max)
678       {
679         max = net->bw_in_available;
680       }
681     }
682     else
683     {
684       if (net->bw_out_available > max)
685       {
686         max = net->bw_out_available;
687       }
688     }
689   }
690   return max;
691 }
692
693 /**
694  * Get the index of the quality-property in question
695  *
696  * @param type the quality property type
697  * @return the index
698  */
699 static int
700 ril_find_property_index (uint32_t type)
701 {
702   int existing_types[] = GNUNET_ATS_QualityProperties;
703   int c;
704   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
705     if (existing_types[c] == type)
706       return c;
707   return GNUNET_SYSERR;
708 }
709
710 static double
711 envi_reward_global (struct GAS_RIL_Handle *solver)
712 {
713   int i;
714   unsigned int in_available = 0;
715   unsigned int out_available = 0;
716   unsigned int in_assigned = 0;
717   unsigned int out_assigned = 0;
718   double ratio_in;
719   double ratio_out;
720
721   for (i = 0; i < solver->networks_count; i++)
722   {
723     in_available += solver->network_entries[i].bw_in_available;
724     in_assigned += solver->network_entries[i].bw_in_assigned;
725     out_available += solver->network_entries[i].bw_out_available;
726     out_assigned += solver->network_entries[i].bw_out_assigned;
727   }
728
729   ratio_in = ((double) in_assigned) / ((double) in_available);
730   ratio_out = ((double) out_assigned) / ((double) out_available);
731
732   return ((ratio_in + ratio_out) * 0.5) + 1;
733 }
734
735 static double
736 envi_reward_local (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
737 {
738   //TODO! add utilization
739
740   const double *preferences;
741   const double *properties;
742   int prop_index;
743   double pref_match = 0;
744   double bw_norm;
745
746   preferences = solver->plugin_envi->get_preferences (solver->plugin_envi->get_preference_cls,
747       &agent->peer);
748   properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
749       agent->address_inuse);
750
751   //preference matching from latency and bandwidth
752   prop_index = ril_find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
753   pref_match += 1 - (preferences[GNUNET_ATS_PREFERENCE_LATENCY] * (3 - properties[prop_index])); //invert property as we want to maximize for lower latencies
754   bw_norm = GNUNET_MAX(2, (((
755                     ((double) agent->bw_in / (double) ril_get_max_bw(agent, GNUNET_YES)) +
756                     ((double) agent->bw_out / (double) ril_get_max_bw(agent, GNUNET_NO))
757                 ) / 2
758             ) + 1));
759
760   pref_match += 1 - (preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] * bw_norm);
761
762   return pref_match * 0.5;
763 }
764
765 /**
766  * Gets the reward for the last performed step, which is calculated in equal
767  * parts from the local (the peer specific) and the global (for all peers
768  * identical) reward.
769  *
770  * @param solver the solver handle
771  * @param agent the agent handle
772  * @return the reward
773  */
774 static double
775 envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
776 {
777   struct RIL_Network *net;
778   double reward = 0;
779
780   //punish overutilization
781   net = agent->address_inuse->solver_information;
782   if ((net->bw_in_assigned > net->bw_in_available) || (net->bw_out_assigned > net->bw_out_available))
783   {
784     return -1;
785   }
786
787   reward += envi_reward_global (solver);
788   reward += envi_reward_local (solver, agent);
789   return reward * 0.5;
790 }
791
792 /**
793  * Doubles the bandwidth for the active address
794  *
795  * @param solver solver handle
796  * @param agent agent handle
797  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth
798  */
799 static void
800 envi_action_bw_double (struct GAS_RIL_Handle *solver,
801     struct RIL_Peer_Agent *agent,
802     int direction_in)
803 {
804   if (direction_in)
805   {
806     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in * 2,
807         agent->bw_out, GNUNET_NO);
808   }
809   else
810   {
811     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
812         agent->bw_out * 2, GNUNET_NO);
813   }
814 }
815
816 /**
817  * Cuts the bandwidth for the active address in half. The least amount of bandwidth suggested, is
818  * the minimum bandwidth for a peer, in order to not invoke a disconnect.
819  *
820  * @param solver solver handle
821  * @param agent agent handle
822  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
823  * bandwidth
824  */
825 static void
826 envi_action_bw_halven (struct GAS_RIL_Handle *solver,
827     struct RIL_Peer_Agent *agent,
828     int direction_in)
829 {
830   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
831   unsigned long long new_bw;
832
833   if (direction_in)
834   {
835     new_bw = agent->bw_in / 2;
836     if (new_bw < min_bw)
837       new_bw = min_bw;
838     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
839         GNUNET_NO);
840   }
841   else
842   {
843     new_bw = agent->bw_out / 2;
844     if (new_bw < min_bw)
845       new_bw = min_bw;
846     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
847         GNUNET_NO);
848   }
849 }
850
851 /**
852  * Increases the bandwidth by 5 times the minimum bandwidth for the active address.
853  *
854  * @param solver solver handle
855  * @param agent agent handle
856  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
857  * bandwidth
858  */
859 static void
860 envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
861 {
862   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
863
864   if (direction_in)
865   {
866     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in + (5 * min_bw),
867         agent->bw_out, GNUNET_NO);
868   }
869   else
870   {
871     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
872         agent->bw_out + (5 * min_bw), GNUNET_NO);
873   }
874 }
875
876 /**
877  * Decreases the bandwidth by 5 times the minimum bandwidth for the active address. The least amount
878  * of bandwidth suggested, is the minimum bandwidth for a peer, in order to not invoke a disconnect.
879  *
880  * @param solver solver handle
881  * @param agent agent handle
882  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
883  * bandwidth
884  */
885 static void
886 envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
887 {
888   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
889   unsigned long long new_bw;
890
891   if (direction_in)
892   {
893     new_bw = agent->bw_in - (5 * min_bw);
894     if (new_bw < min_bw)
895       new_bw = min_bw;
896     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
897         GNUNET_NO);
898   }
899   else
900   {
901     new_bw = agent->bw_out - (5 * min_bw);
902     if (new_bw < min_bw)
903       new_bw = min_bw;
904     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
905         GNUNET_NO);
906   }
907 }
908
909 /**
910  * Switches to the address given by its index
911  *
912  * @param solver solver handle
913  * @param agent agent handle
914  * @param address_index index of the address as it is saved in the agent's list, starting with zero
915  */
916 static void
917 envi_action_address_switch (struct GAS_RIL_Handle *solver,
918     struct RIL_Peer_Agent *agent,
919     unsigned int address_index)
920 {
921   struct RIL_Address_Wrapped *cur;
922   int i = 0;
923
924   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
925   {
926     if (i == address_index)
927     {
928       envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out,
929           GNUNET_NO);
930       return;
931     }
932
933     i++;
934   }
935
936   //no address with address_index exists, in this case this action should not be callable
937   GNUNET_assert(GNUNET_NO);
938 }
939
940 /**
941  * Puts the action into effect by calling the according function
942  *
943  * @param solver the solver handle
944  * @param agent the action handle
945  * @param action the action to perform by the solver
946  */
947 static void
948 envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
949 {
950   int address_index;
951
952   switch (action)
953   {
954   case RIL_ACTION_NOTHING:
955     break;
956   case RIL_ACTION_BW_IN_DBL:
957     envi_action_bw_double (solver, agent, GNUNET_YES);
958     break;
959   case RIL_ACTION_BW_IN_HLV:
960     envi_action_bw_halven (solver, agent, GNUNET_YES);
961     break;
962   case RIL_ACTION_BW_IN_INC:
963     envi_action_bw_inc (solver, agent, GNUNET_YES);
964     break;
965   case RIL_ACTION_BW_IN_DEC:
966     envi_action_bw_dec (solver, agent, GNUNET_YES);
967     break;
968   case RIL_ACTION_BW_OUT_DBL:
969     envi_action_bw_double (solver, agent, GNUNET_NO);
970     break;
971   case RIL_ACTION_BW_OUT_HLV:
972     envi_action_bw_halven (solver, agent, GNUNET_NO);
973     break;
974   case RIL_ACTION_BW_OUT_INC:
975     envi_action_bw_inc (solver, agent, GNUNET_NO);
976     break;
977   case RIL_ACTION_BW_OUT_DEC:
978     envi_action_bw_dec (solver, agent, GNUNET_NO);
979     break;
980   default:
981     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
982     {
983       address_index = action - RIL_ACTION_TYPE_NUM;
984
985       GNUNET_assert(address_index >= 0);
986       GNUNET_assert(
987           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
988
989       envi_action_address_switch (solver, agent, address_index);
990       break;
991     }
992     // error - action does not exist
993     GNUNET_assert(GNUNET_NO);
994   }
995 }
996
997 /**
998  * Performs one step of the Markov Decision Process. Other than in the literature the step starts
999  * after having done the last action a_old. It observes the new state s_next and the reward
1000  * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
1001  * next action is put into effect.
1002  *
1003  * @param agent the agent performing the step
1004  */
1005 static void
1006 agent_step (struct RIL_Peer_Agent *agent)
1007 {
1008   int a_next = RIL_ACTION_INVALID;
1009   double *s_next;
1010   double reward;
1011
1012   s_next = envi_get_state (agent->envi, agent);
1013   reward = envi_get_reward (agent->envi, agent);
1014
1015   LOG(GNUNET_ERROR_TYPE_DEBUG, "agent_step() with algorithm %s\n",
1016       agent->envi->parameters.algorithm ? "Q" : "SARSA");
1017
1018   switch (agent->envi->parameters.algorithm)
1019   {
1020   case RIL_ALGO_SARSA:
1021     agent_modify_eligibility (agent, RIL_E_SET);
1022     if (agent_decide_exploration (agent))
1023     {
1024       a_next = agent_get_action_explore (agent, s_next);
1025     }
1026     else
1027     {
1028       a_next = agent_get_action_best (agent, s_next);
1029     }
1030     if (RIL_ACTION_INVALID != agent->a_old)
1031     {
1032       //updates weights with selected action (on-policy), if not first step
1033       agent_update_weights (agent, reward, s_next, a_next);
1034     }
1035     break;
1036
1037   case RIL_ALGO_Q:
1038     a_next = agent_get_action_best (agent, s_next);
1039     if (RIL_ACTION_INVALID != agent->a_old)
1040     {
1041       //updates weights with best action, disregarding actually selected action (off-policy), if not first step
1042       agent_update_weights (agent, reward, s_next, a_next);
1043     }
1044     if (agent_decide_exploration (agent))
1045     {
1046       a_next = agent_get_action_explore (agent, s_next);
1047       agent_modify_eligibility (agent, RIL_E_ZERO);
1048     }
1049     else
1050     {
1051       a_next = agent_get_action_best (agent, s_next);
1052       agent_modify_eligibility (agent, RIL_E_SET);
1053     }
1054     break;
1055   }
1056
1057   GNUNET_assert(RIL_ACTION_INVALID != a_next);
1058
1059   agent_modify_eligibility (agent, RIL_E_ACCUMULATE);
1060
1061   envi_do_action (agent->envi, agent, a_next);
1062
1063   GNUNET_free(agent->s_old);
1064   agent->s_old = s_next;
1065   agent->a_old = a_next;
1066
1067   agent->step_count += 1;
1068 }
1069
1070 /**
1071  * Triggers one epoch of agent decisions
1072  * @param solver
1073  */
1074 static int
1075 ril_epoch (struct GAS_RIL_Handle *solver)
1076 {
1077   //TODO! add multiple steps per epoch
1078   struct RIL_Peer_Agent *cur;
1079
1080   if (GNUNET_YES == solver->bulk_lock)
1081   {
1082     solver->bulk_changes ++;
1083     return GNUNET_NO;
1084   }
1085
1086   ril_inform(solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS);
1087   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1088   {
1089     if (cur->is_active && cur->address_inuse)
1090     {
1091       agent_step (cur);
1092     }
1093   }
1094   ril_inform(solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS);
1095
1096   return GNUNET_YES;
1097 }
1098
1099 /**
1100  * Cycles through all agents and lets the active ones do a step. Schedules the next step.
1101  *
1102  * @param cls the solver handle
1103  * @param tc the task context for the scheduler
1104  */
1105 static void
1106 ril_periodic_step (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1107 {
1108   struct GAS_RIL_Handle *solver = cls;
1109
1110   LOG(GNUNET_ERROR_TYPE_DEBUG, "RIL step number %d\n", solver->step_count);
1111
1112   ril_epoch(solver);
1113
1114   solver->epoch_count += 1;
1115   solver->next_step = GNUNET_SCHEDULER_add_delayed (solver->step_time, &ril_periodic_step, solver);
1116 }
1117
1118 /**
1119  * Initialize an agent without addresses and its knowledge base
1120  *
1121  * @param s ril solver
1122  * @param peer the one in question
1123  * @return handle to the new agent
1124  */
1125 static struct RIL_Peer_Agent *
1126 agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
1127 {
1128   int i;
1129   struct GAS_RIL_Handle * solver = s;
1130   struct RIL_Peer_Agent * agent = GNUNET_malloc (sizeof (struct RIL_Peer_Agent));
1131
1132   agent->envi = solver;
1133   agent->peer = *peer;
1134   agent->step_count = 0;
1135   agent->is_active = GNUNET_NO;
1136   agent->n = RIL_ACTION_TYPE_NUM;
1137   agent->m = solver->networks_count * RIL_FEATURES_NETWORK_COUNT;
1138   agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1139   for (i = 0; i < agent->n; i++)
1140   {
1141     agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1142   }
1143   agent->a_old = RIL_ACTION_INVALID;
1144   agent->s_old = envi_get_state (solver, agent);
1145   agent->e = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1146   agent_modify_eligibility (agent, RIL_E_ZERO);
1147
1148   GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, agent);
1149
1150   return agent;
1151 }
1152
1153 /**
1154  * Deallocate agent
1155  *
1156  * @param solver the solver handle
1157  * @param agent the agent to retire
1158  */
1159 static void
1160 agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1161 {
1162   int i;
1163
1164   for (i = 0; i < agent->n; i++)
1165   {
1166     GNUNET_free(agent->W[i]);
1167   }
1168   GNUNET_free(agent->W);
1169   GNUNET_free(agent->e);
1170   GNUNET_free(agent->s_old);
1171   GNUNET_free(agent);
1172 }
1173
1174 /**
1175  * Returns the agent for a peer
1176  *
1177  * @param solver the solver handle
1178  * @param peer the identity of the peer
1179  * @param create whether or not to create an agent, if none is allocated yet
1180  * @return the agent
1181  */
1182 static struct RIL_Peer_Agent *
1183 ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
1184 {
1185   struct RIL_Peer_Agent *cur;
1186
1187   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1188   {
1189     if (0 == memcmp (peer, &cur->peer, sizeof(struct GNUNET_PeerIdentity)))
1190     {
1191       return cur;
1192     }
1193   }
1194
1195   if (create)
1196   {
1197     return agent_init (solver, peer);
1198   }
1199   return NULL ;
1200 }
1201
1202 /**
1203  * Lookup network struct by type
1204  *
1205  * @param s the solver handle
1206  * @param type the network type
1207  * @return the network struct
1208  */
1209 static struct RIL_Network *
1210 ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
1211 {
1212   int i;
1213
1214   for (i = 0; i < s->networks_count; i++)
1215   {
1216     if (s->network_entries[i].type == type)
1217     {
1218       return &s->network_entries[i];
1219     }
1220   }
1221   return NULL ;
1222 }
1223
1224 /**
1225  * Determine whether at least the minimum bandwidth is set for the network. Otherwise the network is
1226  * considered inactive and not used. Addresses in an inactive network are ignored.
1227  *
1228  * @param solver solver handle
1229  * @param network the network type
1230  * @return whether or not the network is considered active
1231  */
1232 static int
1233 ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1234 {
1235   struct RIL_Network *net;
1236   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1237
1238   net = ril_get_network (solver, network);
1239   if (net->bw_out_available < min_bw)
1240     return GNUNET_NO;
1241   return GNUNET_YES;
1242 }
1243
1244 /**
1245  * Cuts a slice out of a vector of elements. This is used to decrease the size of the matrix storing
1246  * the reward function approximation. It copies the memory, which is not cut, to the new vector,
1247  * frees the memory of the old vector, and redirects the pointer to the new one.
1248  *
1249  * @param old pointer to the pointer to the first element of the vector
1250  * @param element_size byte size of the vector elements
1251  * @param hole_start the first element to cut out
1252  * @param hole_length the number of elements to cut out
1253  * @param old_length the length of the old vector
1254  */
1255 static void
1256 ril_cut_from_vector (void **old,
1257     size_t element_size,
1258     unsigned int hole_start,
1259     unsigned int hole_length,
1260     unsigned int old_length)
1261 {
1262   char *tmpptr;
1263   char *oldptr = (char *) *old;
1264   size_t size;
1265   unsigned int bytes_before;
1266   unsigned int bytes_hole;
1267   unsigned int bytes_after;
1268
1269   GNUNET_assert(old_length > hole_length);
1270   GNUNET_assert(old_length >= (hole_start + hole_length));
1271
1272   size = element_size * (old_length - hole_length);
1273
1274   bytes_before = element_size * hole_start;
1275   bytes_hole = element_size * hole_length;
1276   bytes_after = element_size * (old_length - hole_start - hole_length);
1277
1278   if (0 == size)
1279   {
1280     tmpptr = NULL;
1281   }
1282   else
1283   {
1284     tmpptr = GNUNET_malloc (size);
1285     memcpy (tmpptr, oldptr, bytes_before);
1286     memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
1287   }
1288   if (NULL != *old)
1289   {
1290     GNUNET_free(*old);
1291   }
1292   *old = (void *) tmpptr;
1293 }
1294
1295 /*
1296  *  Solver API functions
1297  *  ---------------------------
1298  */
1299
1300 /**
1301  * Change relative preference for quality in solver
1302  *
1303  * @param solver the solver handle
1304  * @param peer the peer to change the preference for
1305  * @param kind the kind to change the preference
1306  * @param pref_rel the normalized preference value for this kind over all clients
1307  */
1308 void
1309 GAS_ril_address_change_preference (void *solver,
1310     const struct GNUNET_PeerIdentity *peer,
1311     enum GNUNET_ATS_PreferenceKind kind,
1312     double pref_rel)
1313 {
1314   LOG(GNUNET_ERROR_TYPE_DEBUG,
1315       "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
1316       GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);
1317
1318   ril_epoch(solver);
1319 }
1320
1321 /**
1322  * Entry point for the plugin
1323  *
1324  * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment'
1325  */
1326 void *
1327 libgnunet_plugin_ats_ril_init (void *cls)
1328 {
1329   struct GNUNET_ATS_PluginEnvironment *env = cls;
1330   struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
1331   struct RIL_Network * cur;
1332   int c;
1333   unsigned long long tmp;
1334   char *string;
1335
1336   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_init() Initializing RIL solver\n");
1337
1338   GNUNET_assert(NULL != env);
1339   GNUNET_assert(NULL != env->cfg);
1340   GNUNET_assert(NULL != env->stats);
1341   GNUNET_assert(NULL != env->bandwidth_changed_cb);
1342   GNUNET_assert(NULL != env->get_preferences);
1343   GNUNET_assert(NULL != env->get_property);
1344
1345   if (GNUNET_OK
1346       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME", &solver->step_time))
1347   {
1348     solver->step_time = RIL_DEFAULT_STEP_TIME;
1349   }
1350   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string)
1351       && NULL != string && 0 == strcmp (string, "SARSA"))
1352   {
1353     solver->parameters.algorithm = RIL_ALGO_SARSA;
1354   }
1355   else
1356   {
1357     solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
1358   }
1359   if (GNUNET_OK
1360       == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", "RIL_DISCOUNT_FACTOR", &tmp))
1361   {
1362     solver->parameters.gamma = (double) tmp / 100;
1363   }
1364   else
1365   {
1366     solver->parameters.gamma = RIL_DEFAULT_DISCOUNT_FACTOR;
1367   }
1368   if (GNUNET_OK
1369       == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", "RIL_GRADIENT_STEP_SIZE", &tmp))
1370   {
1371     solver->parameters.alpha = (double) tmp / 100;
1372   }
1373   else
1374   {
1375     solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
1376   }
1377   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", "RIL_TRACE_DECAY", &tmp))
1378   {
1379     solver->parameters.lambda = (double) tmp / 100;
1380   }
1381   else
1382   {
1383     solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
1384   }
1385
1386   env->sf.s_add = &GAS_ril_address_add;
1387   env->sf.s_address_update_property = &GAS_ril_address_property_changed;
1388   env->sf.s_address_update_session = &GAS_ril_address_session_changed;
1389   env->sf.s_address_update_inuse = &GAS_ril_address_inuse_changed;
1390   env->sf.s_address_update_network = &GAS_ril_address_change_network;
1391   env->sf.s_get = &GAS_ril_get_preferred_address;
1392   env->sf.s_get_stop = &GAS_ril_stop_get_preferred_address;
1393   env->sf.s_pref = &GAS_ril_address_change_preference;
1394   env->sf.s_feedback = &GAS_ril_address_preference_feedback;
1395   env->sf.s_del = &GAS_ril_address_delete;
1396   env->sf.s_bulk_start = &GAS_ril_bulk_start;
1397   env->sf.s_bulk_stop = &GAS_ril_bulk_stop;
1398
1399   solver->plugin_envi = env;
1400   solver->networks_count = env->network_count;
1401   solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Network));
1402   solver->step_count = 0;
1403
1404   for (c = 0; c < env->network_count; c++)
1405   {
1406     cur = &solver->network_entries[c];
1407     cur->type = env->networks[c];
1408     cur->bw_in_available = env->in_quota[c];
1409     cur->bw_in_assigned = 0;
1410     cur->bw_out_available = env->out_quota[c];
1411     cur->bw_out_assigned = 0;
1412   }
1413
1414   solver->next_step = GNUNET_SCHEDULER_add_delayed (
1415       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_millisecond_ (), 1000),
1416       &ril_periodic_step, solver);
1417
1418   return solver;
1419 }
1420
1421 /**
1422  * Exit point for the plugin
1423  *
1424  * @param cls the solver handle
1425  */
1426 void *
1427 libgnunet_plugin_ats_ril_done (void *cls)
1428 {
1429   struct GAS_RIL_Handle *s = cls;
1430   struct RIL_Peer_Agent *cur_agent;
1431   struct RIL_Peer_Agent *next_agent;
1432
1433   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");
1434
1435   cur_agent = s->agents_head;
1436   while (NULL != cur_agent)
1437   {
1438     next_agent = cur_agent->next;
1439     GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
1440     agent_die (s, cur_agent);
1441     cur_agent = next_agent;
1442   }
1443
1444   GNUNET_SCHEDULER_cancel (s->next_step);
1445   GNUNET_free(s->network_entries);
1446   GNUNET_free(s);
1447
1448   return NULL ;
1449 }
1450
1451 /**
1452  * Add a new address for a peer to the solver
1453  *
1454  * The address is already contained in the addresses hashmap!
1455  *
1456  * @param solver the solver Handle
1457  * @param address the address to add
1458  * @param network network type of this address
1459  */
1460 void
1461 GAS_ril_address_add (void *solver, struct ATS_Address *address, uint32_t network)
1462 {
1463   struct GAS_RIL_Handle *s = solver;
1464   struct RIL_Peer_Agent *agent;
1465   struct RIL_Address_Wrapped *address_wrapped;
1466   struct RIL_Network *net;
1467   unsigned int m_new;
1468   unsigned int m_old;
1469   unsigned int n_new;
1470   unsigned int n_old;
1471   int i;
1472   unsigned int zero;
1473   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1474
1475   net = ril_get_network (s, network);
1476   address->solver_information = net;
1477
1478   if (!ril_network_is_active (s, network))
1479   {
1480     LOG(GNUNET_ERROR_TYPE_DEBUG,
1481         "API_address_add() Did not add %s address %p for peer '%s', network does not have enough bandwidth\n",
1482         address->plugin, address->addr, GNUNET_i2s (&address->peer));
1483     return;
1484   }
1485
1486   agent = ril_get_agent (s, &address->peer, GNUNET_YES);
1487
1488   //add address
1489   address_wrapped = GNUNET_malloc (sizeof (struct RIL_Address_Wrapped));
1490   address_wrapped->address_naked = address;
1491   GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);
1492
1493   //increase size of W
1494   m_new = agent->m + RIL_FEATURES_ADDRESS_COUNT;
1495   m_old = agent->m;
1496   n_new = agent->n + 1;
1497   n_old = agent->n;
1498
1499   GNUNET_array_grow(agent->W, agent->n, n_new);
1500   for (i = 0; i < n_new; i++)
1501   {
1502     if (i < n_old)
1503     {
1504       agent->m = m_old;
1505       GNUNET_array_grow(agent->W[i], agent->m, m_new);
1506     }
1507     else
1508     {
1509       zero = 0;
1510       GNUNET_array_grow(agent->W[i], zero, m_new);
1511     }
1512   }
1513
1514   //increase size of old state vector
1515   agent->m = m_old;
1516   GNUNET_array_grow(agent->s_old, agent->m, m_new);
1517
1518   agent->m = m_old;
1519   GNUNET_array_grow(agent->e, agent->m, m_new);
1520
1521   if (NULL == agent->address_inuse)
1522   {
1523     net->bw_in_assigned += min_bw;
1524     net->bw_out_assigned += min_bw;
1525     envi_set_active_suggestion (s, agent, address, min_bw, min_bw, GNUNET_NO);
1526   }
1527
1528   ril_epoch(s);
1529
1530   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %p for peer '%s'\n",
1531       address->active ? "active" : "inactive", address->plugin, address->addr,
1532       GNUNET_i2s (&address->peer));
1533 }
1534
1535 /**
1536  * Delete an address in the solver
1537  *
1538  * The address is not contained in the address hashmap anymore!
1539  *
1540  * @param solver the solver handle
1541  * @param address the address to remove
1542  * @param session_only delete only session not whole address
1543  */
1544 void
1545 GAS_ril_address_delete (void *solver, struct ATS_Address *address, int session_only)
1546 {
1547   struct GAS_RIL_Handle *s = solver;
1548   struct RIL_Peer_Agent *agent;
1549   struct RIL_Address_Wrapped *address_wrapped;
1550   int address_was_used = address->active;
1551   int address_index;
1552   unsigned int m_new;
1553   unsigned int n_new;
1554   int i;
1555   struct RIL_Network *net;
1556   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1557
1558   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_delete() Delete %s%s %s address %p for peer '%s'\n",
1559       session_only ? "session for " : "", address->active ? "active" : "inactive", address->plugin,
1560       address->addr, GNUNET_i2s (&address->peer));
1561
1562   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1563   if (NULL == agent)
1564   {
1565     net = address->solver_information;
1566     GNUNET_assert(!ril_network_is_active (s, net->type));
1567     LOG(GNUNET_ERROR_TYPE_DEBUG,
1568         "No agent allocated for peer yet, since address was in inactive network\n");
1569     return;
1570   }
1571
1572   address_index = agent_address_get_index (agent, address);
1573   address_wrapped = agent_address_get (agent, address);
1574
1575   if (NULL == address_wrapped)
1576   {
1577     net = address->solver_information;
1578     GNUNET_assert(!ril_network_is_active (s, net->type));
1579     LOG(GNUNET_ERROR_TYPE_DEBUG,
1580         "Address not considered by agent, address was in inactive network\n");
1581     return;
1582   }
1583
1584   GNUNET_CONTAINER_DLL_remove(agent->addresses_head, agent->addresses_tail, address_wrapped);
1585   GNUNET_free(address_wrapped);
1586
1587   //decrease W
1588   m_new = agent->m - RIL_FEATURES_ADDRESS_COUNT;
1589   n_new = agent->n - 1;
1590
1591   for (i = 0; i < agent->n; i++)
1592   {
1593     ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
1594         ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1595             + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1596   }
1597   GNUNET_free(agent->W[RIL_ACTION_TYPE_NUM + address_index]);
1598   ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
1599       1, agent->n);
1600   //correct last action
1601   if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
1602   {
1603     agent->a_old -= 1;
1604   }
1605   else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
1606   {
1607     agent->a_old = RIL_ACTION_INVALID;
1608   }
1609   //decrease old state vector and eligibility vector
1610   ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
1611       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1612           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1613   ril_cut_from_vector ((void **) &agent->e, sizeof(double),
1614       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1615           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1616   agent->m = m_new;
1617   agent->n = n_new;
1618
1619   LOG(GNUNET_ERROR_TYPE_DEBUG, "address was used: %s\n", address_was_used ? "yes" : "no");
1620
1621   if (address_was_used)
1622   {
1623     net = address->solver_information;
1624     net->bw_in_assigned -= agent->bw_in;
1625     net->bw_out_assigned -= agent->bw_out;
1626
1627     if (NULL != agent->addresses_head) //if peer has an address left, use it
1628     {
1629       LOG(GNUNET_ERROR_TYPE_DEBUG, "address left: %p\n",
1630           agent->addresses_head->address_naked->addr);
1631       //TODO? check if network/bandwidth update can be done more clever/elegant at different function
1632       envi_set_active_suggestion (s, agent, agent->addresses_head->address_naked, min_bw, min_bw,
1633           GNUNET_NO);
1634       net = agent->addresses_head->address_naked->solver_information;
1635       net->bw_in_assigned -= min_bw;
1636       net->bw_out_assigned -= min_bw;
1637     }
1638     else
1639     {
1640       LOG(GNUNET_ERROR_TYPE_DEBUG, "no address left => disconnect\n");
1641
1642       envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
1643     }
1644   }
1645
1646   ril_epoch(solver);
1647
1648   LOG(GNUNET_ERROR_TYPE_DEBUG, "Address deleted\n");
1649 }
1650
1651 /**
1652  * Update the properties of an address in the solver
1653  *
1654  * @param solver solver handle
1655  * @param address the address
1656  * @param type the ATSI type in HBO
1657  * @param abs_value the absolute value of the property
1658  * @param rel_value the normalized value
1659  */
1660 void
1661 GAS_ril_address_property_changed (void *solver,
1662     struct ATS_Address *address,
1663     uint32_t type,
1664     uint32_t abs_value,
1665     double rel_value)
1666 {
1667   LOG(GNUNET_ERROR_TYPE_DEBUG,
1668       "API_address_property_changed() Property '%s' for peer '%s' address %p changed "
1669           "to %.2f \n", GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1670       address->addr, rel_value);
1671
1672   ril_epoch(solver);
1673 }
1674
1675 /**
1676  * Update the session of an address in the solver
1677  *
1678  * NOTE: values in addresses are already updated
1679  *
1680  * @param solver solver handle
1681  * @param address the address
1682  * @param cur_session the current session
1683  * @param new_session the new session
1684  */
1685 void
1686 GAS_ril_address_session_changed (void *solver,
1687     struct ATS_Address *address,
1688     uint32_t cur_session,
1689     uint32_t new_session)
1690 {
1691   /*
1692    * TODO? Future Work: Potentially add session activity as a feature in state vector
1693    */
1694   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_session_changed()\n");
1695 }
1696
1697 /**
1698  * Notify the solver that an address is (not) actively used by transport
1699  * to communicate with a remote peer
1700  *
1701  * NOTE: values in addresses are already updated
1702  *
1703  * @param solver solver handle
1704  * @param address the address
1705  * @param in_use usage state
1706  */
1707 void
1708 GAS_ril_address_inuse_changed (void *solver, struct ATS_Address *address, int in_use)
1709 {
1710   /* Nothing to do here.
1711    * Possible TODO? Future Work: Use usage as state vector
1712    */
1713   LOG(GNUNET_ERROR_TYPE_DEBUG,
1714       "API_address_inuse_changed() Usage for %s address of peer '%s' changed to %s\n",
1715       address->plugin, GNUNET_i2s (&address->peer), (GNUNET_YES == in_use) ? "USED" : "UNUSED");
1716 }
1717
1718 /**
1719  * Notify solver that the network an address is located in has changed
1720  *
1721  * NOTE: values in addresses are already updated
1722  *
1723  * @param solver solver handle
1724  * @param address the address
1725  * @param current_network the current network
1726  * @param new_network the new network
1727  */
1728 void
1729 GAS_ril_address_change_network (void *solver,
1730     struct ATS_Address *address,
1731     uint32_t current_network,
1732     uint32_t new_network)
1733 {
1734   struct GAS_RIL_Handle *s = solver;
1735   struct RIL_Peer_Agent *agent;
1736   struct RIL_Network *net;
1737   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1738
1739   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_change_network() Network type changed, moving "
1740       "%s address of peer %s from '%s' to '%s'\n",
1741       (GNUNET_YES == address->active) ? "active" : "inactive", GNUNET_i2s (&address->peer),
1742       GNUNET_ATS_print_network_type (current_network), GNUNET_ATS_print_network_type (new_network));
1743
1744   if (address->active && !ril_network_is_active (solver, new_network))
1745   {
1746     GAS_ril_address_delete (solver, address, GNUNET_NO);
1747     return;
1748   }
1749
1750   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1751   if (NULL == agent)
1752   {
1753     GNUNET_assert(!ril_network_is_active (solver, current_network));
1754
1755     GAS_ril_address_add (s, address, new_network);
1756     return;
1757   }
1758
1759   net = ril_get_network (s, current_network);
1760   net->bw_in_assigned -= agent->bw_in;
1761   net->bw_out_assigned -= agent->bw_out;
1762
1763   net = ril_get_network (s, new_network);
1764   net->bw_in_assigned -= min_bw;
1765   net->bw_out_assigned -= min_bw;
1766   address->solver_information = net;
1767 }
1768
1769 /**
1770  * Give feedback about the current assignment
1771  *
1772  * @param solver the solver handle
1773  * @param application the application
1774  * @param peer the peer to change the preference for
1775  * @param scope the time interval for this feedback: [now - scope .. now]
1776  * @param kind the kind to change the preference
1777  * @param score the score
1778  */
1779 void
1780 GAS_ril_address_preference_feedback (void *solver,
1781     void *application,
1782     const struct GNUNET_PeerIdentity *peer,
1783     const struct GNUNET_TIME_Relative scope,
1784     enum GNUNET_ATS_PreferenceKind kind,
1785     double score)
1786 {
1787   LOG(GNUNET_ERROR_TYPE_DEBUG,
1788       "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
1789           "preference %s for %d seconds\n", GNUNET_i2s (peer), "UNKNOWN",
1790       GNUNET_ATS_print_preference_type (kind), scope.rel_value_us / 1000000);
1791 }
1792
1793 /**
1794  * Start a bulk operation
1795  *
1796  * @param solver the solver
1797  */
1798 void
1799 GAS_ril_bulk_start (void *solver)
1800 {
1801   struct GAS_RIL_Handle *s = solver;
1802
1803   LOG (GNUNET_ERROR_TYPE_DEBUG, "API_bulk_start() Locking solver for bulk operation ...\n");
1804
1805   s->bulk_lock++;
1806 }
1807
1808 /**
1809  * Bulk operation done
1810  *
1811  * @param solver the solver handle
1812  */
1813 void
1814 GAS_ril_bulk_stop (void *solver)
1815 {
1816   /* TODO! trigger "recalculation" after bulk / trigger "recalculation" after changes (address or preference)
1817    * that has to be properly thought through, not when your mind is blocked completely
1818    */
1819   struct GAS_RIL_Handle *s = solver;
1820
1821   LOG (GNUNET_ERROR_TYPE_DEBUG, "API_bulk_stop() Releasing solver from bulk operation ...\n");
1822
1823   if (s->bulk_lock < 1)
1824   {
1825     GNUNET_break (0);
1826     return;
1827   }
1828   s->bulk_lock--;
1829
1830   if (0 < s->bulk_changes)
1831   {
1832     ril_epoch (solver);
1833     s->bulk_changes = 0;
1834   }
1835 }
1836
1837 /**
1838  * Tell solver to notify ATS if the address to use changes for a specific
1839  * peer using the bandwidth changed callback
1840  *
1841  * The solver must only notify about changes for peers with pending address
1842  * requests!
1843  *
1844  * @param solver the solver handle
1845  * @param peer the identity of the peer
1846  */
1847 const struct ATS_Address *
1848 GAS_ril_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
1849 {
1850   /*
1851    * activate agent, return currently chosen address
1852    */
1853   struct GAS_RIL_Handle *s = solver;
1854   struct RIL_Peer_Agent *agent;
1855   struct RIL_Network *net;
1856
1857   agent = ril_get_agent (s, peer, GNUNET_YES);
1858
1859   agent->is_active = GNUNET_YES;
1860
1861   if (agent->address_inuse)
1862   {
1863     net = agent->address_inuse->solver_information;
1864     net->bw_in_assigned += agent->bw_in;
1865     net->bw_out_assigned += agent->bw_out;
1866   }
1867   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
1868       GNUNET_YES);
1869
1870   if (agent->address_inuse)
1871   {
1872     LOG(GNUNET_ERROR_TYPE_DEBUG,
1873         "API_get_preferred_address() Activated agent for peer '%s' with %s address %p\n",
1874         GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
1875   }
1876   else
1877   {
1878     LOG(GNUNET_ERROR_TYPE_DEBUG,
1879         "API_get_preferred_address() Activated agent for peer '%s', but no address available\n",
1880         GNUNET_i2s (peer));
1881   }
1882
1883   ril_epoch(s);
1884
1885   return agent->address_inuse;
1886 }
1887
1888 /**
1889  * Tell solver stop notifying ATS about changes for this peers
1890  *
1891  * The solver must only notify about changes for peers with pending address
1892  * requests!
1893  *
1894  * @param solver the solver handle
1895  * @param peer the peer
1896  */
1897 void
1898 GAS_ril_stop_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
1899 {
1900   struct GAS_RIL_Handle *s = solver;
1901   struct RIL_Peer_Agent *agent;
1902   struct RIL_Network *net;
1903
1904   agent = ril_get_agent (s, peer, GNUNET_NO);
1905
1906   if (NULL == agent)
1907   {
1908     GNUNET_break(0);
1909     return;
1910   }
1911   if (GNUNET_NO == agent->is_active)
1912   {
1913     GNUNET_break(0);
1914     return;
1915   }
1916
1917   agent->is_active = GNUNET_NO;
1918   if (agent->address_inuse)
1919   {
1920     net = agent->address_inuse->solver_information;
1921     net->bw_in_assigned -= agent->bw_in;
1922     net->bw_out_assigned -= agent->bw_out;
1923   }
1924   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
1925       GNUNET_YES);
1926
1927   ril_epoch(s);
1928
1929   LOG(GNUNET_ERROR_TYPE_DEBUG,
1930       "API_stop_get_preferred_address() Paused agent for peer '%s' with %s address\n",
1931       GNUNET_i2s (peer), agent->address_inuse->plugin);
1932 }
1933
1934 /* end of libgnunet_plugin_ats_ril.c */