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