psyc: in-order message delivery
[oweals/gnunet.git] / src / ats / plugin_ats_mlp.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/plugin_ats_mlp.c
23  * @brief ats mlp problem solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27
28 #include "plugin_ats_mlp.h"
29
30
31 /**
32  *
33  * NOTE: Do not modify this documentation. This documentation is based on
34  * gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
35  * use build_txt.sh to generate plaintext output
36  *
37  *    The MLP solver (mlp) tries to finds an optimal bandwidth assignmentby
38  *    optimizing an mixed integer programming problem. The MLP solver uses a
39  *    number of constraints to find the best adddress for a peer and an optimal
40  *    bandwidth assignment. mlp uses the GNU Linear Programming Kit to solve the
41  *    MLP problem.
42  *
43  *    We defined a constraint system to find an optimal bandwidth assignment.
44  *    This constraint system uses as an input data addresses, bandwidth quotas,
45  *    preferences and quality values. This constraint system is stored in an
46  *    matrix based equotation system.
47  *
48  *   5 Using GLPK
49  *
50  *    A (M)LP problem consists of a target function to optimizes, constraints
51  *    and rows and columns. FIXME GLP uses three arrays to index the matrix: two
52  *    integer arrays storing the row and column indices in the matrix and an
53  *    float array to store the coeeficient.
54  *
55  *    To solve the problem we first find an initial solution for the LP problem
56  *    using the LP solver and then find an MLP solution based on this solution
57  *    using the MLP solver.
58  *
59  *    Solving (M)LP problems has the property that finding an initial solution
60  *    for the LP problem is computationally expensive and finding the MLP
61  *    solution is cheaper. This is especially interesting an existing LP
62  *    solution can be reused if only coefficients in the matrix have changed
63  *    (addresses updated). Only when the problem size changes (addresses added
64  *    or deleted) a new LP solution has to be found.
65  *
66  *    Intended usage
67  *    The mlp solver solves the bandwidth assignment problem only on demand when
68  *    an address suggestion is requested. When an address is requested mlp the
69  *    solves the mlp problem and if the active address or the bandwidth assigned
70  *    changes it calls the callback to addresses. The mlp solver gets notified
71  *    about new addresses (adding sessions), removed addresses (address
72  *    deletions) and address updates. To benefit from the mlp properties
73  *    mentioned in section 5 the solver rembers if since the last solution
74  *    addresses were added or deleted (problem size changed, problem has to be
75  *    rebuild and solved from sratch) or if addresses were updated and the
76  *    existing solution can be reused.
77  *
78  *     5.1 Input data
79  *
80  *    The quotas for each network segment are passed by addresses. MLP can be
81  *    adapted using configuration settings and uses the following parameters:
82  *      * MLP_MAX_DURATION:
83  *        Maximum duration for a MLP solution procees (default: 3 sec.)
84  *      * MLP_MAX_ITERATIONS:
85  *        Maximum number of iterations for a MLP solution process (default:
86  *        1024)
87  *      * MLP_MIN_CONNECTIONS:
88  *        Minimum number of desired connections (default: 4)
89  *      * MLP_MIN_BANDWIDTH:
90  *        Minimum amount of bandwidth assigned to an address (default: 1024)
91  *      * MLP_COEFFICIENT_D:
92  *        Diversity coefficient (default: 1.0)
93  *      * MLP_COEFFICIENT_R:
94  *        Relativity coefficient (default: 1.0)
95  *      * MLP_COEFFICIENT_U:
96  *        Utilization coefficient (default: 1.0)
97  *      * MLP_COEFFICIENT_D:
98  *        Diversity coefficient (default: 1.0)
99  *      * MLP_COEFFICIENT_QUALITY_DELAY:
100  *        Quality delay coefficient (default: 1.0)
101  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
102  *        Quality distance coefficient (default: 1.0)
103  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
104  *        Quality distance coefficient (default: 1.0)
105  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
106  *        Quality distance coefficient (default: 1.0)
107  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
108  *        Quality distance coefficient (default: 1.0)
109  *
110  *     5.2 Data structures used
111  *
112  *    mlp has for each known peer a struct ATS_Peer containing information about
113  *    a specific peer. The address field solver_information contains information
114  *    about the mlp properties of this address.
115  *
116  *     5.3 Initializing
117  *
118  *    During initialization mlp initializes the GLPK libray used to solve the
119  *    MLP problem: it initializes the glpk environment and creates an initial LP
120  *    problem. Next it loads the configuration values from the configuration or
121  *    uses the default values configured in -addresses_mlp.h. The quotas used
122  *    are given by addresses but may have to be adjusted. mlp uses a upper limit
123  *    for the bandwidth assigned called BIG M and a minimum amount of bandwidth
124  *    an address gets assigned as well as a minium desired number of
125  *    connections. If the configured quota is bigger than BIG M, it is reduced
126  *    to BIG M. If the configured quota is smaller than MLP_MIN_CONNECTIONS
127  *    *MLP_MIN_BANDWIDTH it is increased to this value.
128  *
129  *     5.4 Shutdown
130
131  */
132
133 #define LOG(kind,...) GNUNET_log_from (kind, "ats-mlp",__VA_ARGS__)
134
135 /**
136  * Print debug output for mlp problem creation
137  */
138 #define DEBUG_MLP_PROBLEM_CREATION GNUNET_NO
139
140
141 /**
142  * Maximize bandwidth assigned
143  *
144  * This option can be used to test if problem can be solved at all without
145  * optimizing for utility, diversity or relativity
146  *
147  */
148 #define MAXIMIZE_FOR_BANDWIDTH_ASSIGNED GNUNET_NO
149
150 /**
151  * Intercept GLPK terminal output
152  * @param info the mlp handle
153  * @param s the string to print
154  * @return 0: glpk prints output on terminal, 0 != surpress output
155  */
156 static int
157 mlp_term_hook (void *info, const char *s)
158 {
159   /* Not needed atm struct MLP_information *mlp = info; */
160   LOG (GNUNET_ERROR_TYPE_ERROR, "%s", s);
161   return 1;
162 }
163
164
165 /**
166  * Reset peers for next problem creation
167  *
168  * @param cls not used
169  * @param key the key
170  * @param value ATS_Peer
171  * @return GNUNET_OK
172  */
173 static int
174 reset_peers (void *cls,
175              const struct GNUNET_PeerIdentity *key,
176              void *value)
177  {
178    struct ATS_Peer *peer = value;
179    peer->processed = GNUNET_NO;
180    return GNUNET_OK;
181  }
182
183 /**
184  * Delete the MLP problem and free the constrain matrix
185  *
186  * @param mlp the MLP handle
187  */
188 static void
189 mlp_delete_problem (struct GAS_MLP_Handle *mlp)
190 {
191   int c;
192   if (mlp == NULL)
193     return;
194   if (mlp->p.prob != NULL)
195   {
196     glp_delete_prob(mlp->p.prob);
197     mlp->p.prob = NULL;
198   }
199
200   /* delete row index */
201   if (mlp->p.ia != NULL)
202   {
203     GNUNET_free (mlp->p.ia);
204     mlp->p.ia = NULL;
205   }
206
207   /* delete column index */
208   if (mlp->p.ja != NULL)
209   {
210     GNUNET_free (mlp->p.ja);
211     mlp->p.ja = NULL;
212   }
213
214   /* delete coefficients */
215   if (mlp->p.ar != NULL)
216   {
217     GNUNET_free (mlp->p.ar);
218     mlp->p.ar = NULL;
219   }
220   mlp->p.ci = 0;
221   mlp->p.prob = NULL;
222
223   mlp->p.c_d = MLP_UNDEFINED;
224   mlp->p.c_r = MLP_UNDEFINED;
225   mlp->p.r_c2 = MLP_UNDEFINED;
226   mlp->p.r_c4 = MLP_UNDEFINED;
227   mlp->p.r_c6 = MLP_UNDEFINED;
228   mlp->p.r_c9 = MLP_UNDEFINED;
229   for (c = 0; c < mlp->pv.m_q ; c ++)
230     mlp->p.r_q[c] = MLP_UNDEFINED;
231   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c ++)
232     mlp->p.r_quota[c] = MLP_UNDEFINED;
233   mlp->p.ci = MLP_UNDEFINED;
234
235
236   GNUNET_CONTAINER_multipeermap_iterate (mlp->requested_peers,
237                                          &reset_peers, NULL);
238 }
239
240
241 /**
242  * Translate ATS properties to text
243  * Just intended for debugging
244  *
245  * @param ats_index the ATS index
246  * @return string with result
247  */
248 const char *
249 mlp_ats_to_string (int ats_index)
250 {
251   switch (ats_index) {
252     case GNUNET_ATS_ARRAY_TERMINATOR:
253       return "GNUNET_ATS_ARRAY_TERMINATOR";
254     case GNUNET_ATS_UTILIZATION_OUT:
255       return "GNUNET_ATS_UTILIZATION_OUT";
256     case GNUNET_ATS_UTILIZATION_IN:
257       return "GNUNET_ATS_UTILIZATION_IN";
258     case GNUNET_ATS_UTILIZATION_PAYLOAD_OUT:
259       return "GNUNET_ATS_UTILIZATION_PAYLOAD_OUT";
260     case GNUNET_ATS_UTILIZATION_PAYLOAD_IN:
261       return "GNUNET_ATS_UTILIZATION_PAYLOAD_IN";
262     case GNUNET_ATS_COST_LAN:
263       return "GNUNET_ATS_COST_LAN";
264     case GNUNET_ATS_COST_WAN:
265       return "GNUNET_ATS_COST_LAN";
266     case GNUNET_ATS_COST_WLAN:
267       return "GNUNET_ATS_COST_WLAN";
268     case GNUNET_ATS_NETWORK_TYPE:
269       return "GNUNET_ATS_NETWORK_TYPE";
270     case GNUNET_ATS_QUALITY_NET_DELAY:
271       return "GNUNET_ATS_QUALITY_NET_DELAY";
272     case GNUNET_ATS_QUALITY_NET_DISTANCE:
273       return "GNUNET_ATS_QUALITY_NET_DISTANCE";
274     default:
275       GNUNET_break (0);
276       return "unknown";
277   }
278 }
279
280 /**
281  * Translate glpk status error codes to text
282  * @param retcode return code
283  * @return string with result
284  */
285 const char *
286 mlp_status_to_string (int retcode)
287 {
288   switch (retcode) {
289     case GLP_UNDEF:
290       return "solution is undefined";
291     case GLP_FEAS:
292       return "solution is feasible";
293     case GLP_INFEAS:
294       return "solution is infeasible";
295     case GLP_NOFEAS:
296       return "no feasible solution exists";
297     case GLP_OPT:
298       return "solution is optimal";
299     case GLP_UNBND:
300       return "solution is unbounded";
301     default:
302       GNUNET_break (0);
303       return "unknown error";
304   }
305 }
306
307 /**
308  * Translate glpk solver error codes to text
309  * @param retcode return code
310  * @return string with result
311  */
312 const char *
313 mlp_solve_to_string (int retcode)
314 {
315   switch (retcode) {
316     case 0:
317       return "ok";
318     case GLP_EBADB:
319       return "invalid basis";
320     case GLP_ESING:
321       return "singular matrix";
322     case GLP_ECOND:
323       return "ill-conditioned matrix";
324     case GLP_EBOUND:
325       return "invalid bounds";
326     case GLP_EFAIL:
327       return "solver failed";
328     case GLP_EOBJLL:
329       return "objective lower limit reached";
330     case GLP_EOBJUL:
331       return "objective upper limit reached";
332     case GLP_EITLIM:
333       return "iteration limit exceeded";
334     case GLP_ETMLIM:
335       return "time limit exceeded";
336     case GLP_ENOPFS:
337       return "no primal feasible solution";
338     case GLP_ENODFS:
339       return "no dual feasible solution";
340     case GLP_EROOT:
341       return "root LP optimum not provided";
342     case GLP_ESTOP:
343       return "search terminated by application";
344     case GLP_EMIPGAP:
345       return "relative mip gap tolerance reached";
346     case GLP_ENOFEAS:
347       return "no dual feasible solution";
348     case GLP_ENOCVG:
349       return "no convergence";
350     case GLP_EINSTAB:
351       return "numerical instability";
352     case GLP_EDATA:
353       return "invalid data";
354     case GLP_ERANGE:
355       return "result out of range";
356     default:
357       GNUNET_break (0);
358       return "unknown error";
359   }
360 }
361
362 /**
363  * Extract an ATS performance info from an address
364  *
365  * @param address the address
366  * @param type the type to extract in HBO
367  * @return the value in HBO or GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
368  */
369 static int
370 get_performance_info (struct ATS_Address *address, uint32_t type)
371 {
372   int c1;
373   GNUNET_assert (NULL != address);
374
375   if ((NULL == address->atsi) || (0 == address->atsi_count))
376     return GNUNET_ATS_VALUE_UNDEFINED;
377
378   for (c1 = 0; c1 < address->atsi_count; c1++)
379   {
380     if (ntohl (address->atsi[c1].type) == type)
381       return ntohl (address->atsi[c1].value);
382   }
383   return GNUNET_ATS_VALUE_UNDEFINED;
384 }
385
386
387 struct CountContext
388 {
389   const struct GNUNET_CONTAINER_MultiPeerMap *map;
390   int result;
391 };
392
393 static int
394 mlp_create_problem_count_addresses_it (void *cls,
395                                        const struct GNUNET_PeerIdentity *key,
396                                        void *value)
397 {
398   struct CountContext *cctx = cls;
399
400   /* Check if we have to add this peer due to a pending request */
401   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (cctx->map, key))
402     cctx->result++;
403   return GNUNET_OK;
404 }
405
406
407 static int
408 mlp_create_problem_count_addresses (const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers,
409                                     const struct GNUNET_CONTAINER_MultiPeerMap *addresses)
410 {
411   struct CountContext cctx;
412
413   cctx.map = requested_peers;
414   cctx.result = 0;
415   GNUNET_CONTAINER_multipeermap_iterate (addresses,
416            &mlp_create_problem_count_addresses_it, &cctx);
417   return cctx.result;
418 }
419
420
421 static int
422 mlp_create_problem_count_peers_it (void *cls,
423                                    const struct GNUNET_PeerIdentity *key,
424                                    void *value)
425 {
426   struct CountContext *cctx = cls;
427
428   /* Check if we have to addresses for the requested peer */
429   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (cctx->map, key))
430     cctx->result++;
431   return GNUNET_OK;
432 }
433
434
435 static int
436 mlp_create_problem_count_peers (const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers,
437     const struct GNUNET_CONTAINER_MultiPeerMap *addresses)
438 {
439   struct CountContext cctx;
440
441   cctx.map = addresses;
442   cctx.result = 0;
443   GNUNET_CONTAINER_multipeermap_iterate (requested_peers,
444            &mlp_create_problem_count_peers_it, &cctx);
445   return cctx.result;
446 }
447
448
449 /**
450  * Updates an existing value in the matrix
451  *
452  * Extract the row, updates the value and updates the row in the problem
453  *
454  * @param p the mlp problem
455  * @param row the row to create the value in
456  * @param col the column to create the value in
457  * @param val the value to set
458  * @param line calling line for debbuging
459  * @return GNUNET_YES value changed, GNUNET_NO value did not change, GNUNET_SYSERR
460  * on error
461  */
462 static int
463 mlp_create_problem_update_value (struct MLP_Problem *p,
464                               int row, int col, double val,
465                               int line)
466 {
467   int c_cols;
468   int c_elems;
469   int c1;
470   int res;
471   int found;
472   double *val_array;
473   int *ind_array;
474
475   GNUNET_assert (NULL != p);
476   GNUNET_assert (NULL != p->prob);
477
478   /* Get number of columns and prepare data structure */
479   c_cols = glp_get_num_cols(p->prob);
480   if (0 >= c_cols)
481     return GNUNET_SYSERR;
482
483   val_array = GNUNET_malloc ((c_cols +1)* sizeof (double));
484   GNUNET_assert (NULL != val_array);
485   ind_array = GNUNET_malloc ((c_cols+1) * sizeof (int));
486   GNUNET_assert (NULL != ind_array);
487   /* Extract the row */
488
489   /* Update the value */
490   c_elems = glp_get_mat_row (p->prob, row, ind_array, val_array);
491   found = GNUNET_NO;
492   for (c1 = 1; c1 < (c_elems+1); c1++)
493   {
494     if (ind_array[c1] == col)
495     {
496       found = GNUNET_YES;
497       break;
498     }
499   }
500   if (GNUNET_NO == found)
501   {
502     ind_array[c_elems+1] = col;
503     val_array[c_elems+1] = val;
504     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P] Setting value in [%s : %s] to `%.2f'\n",
505         glp_get_row_name (p->prob, row), glp_get_col_name (p->prob, col),
506         val);
507     glp_set_mat_row (p->prob, row, c_elems+1, ind_array, val_array);
508     GNUNET_free (ind_array);
509     GNUNET_free (val_array);
510     return GNUNET_YES;
511   }
512   else
513   {
514     /* Update value */
515     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P] Updating value in [%s : %s] from `%.2f' to `%.2f'\n",
516         glp_get_row_name (p->prob, row), glp_get_col_name (p->prob, col),
517         val_array[c1], val);
518     if (val != val_array[c1])
519       res = GNUNET_YES;
520     else
521       res = GNUNET_NO;
522     val_array[c1] = val;
523     /* Update the row in the matrix */
524     glp_set_mat_row (p->prob, row, c_elems, ind_array, val_array);
525   }
526
527   GNUNET_free (ind_array);
528   GNUNET_free (val_array);
529   return res;
530 }
531
532 /**
533  * Creates a new value in the matrix
534  *
535  * Sets the row and column index in the problem array and increments the
536  * position field
537  *
538  * @param p the mlp problem
539  * @param row the row to create the value in
540  * @param col the column to create the value in
541  * @param val the value to set
542  * @param line calling line for debbuging
543  */
544 static void
545 mlp_create_problem_set_value (struct MLP_Problem *p,
546                               int row, int col, double val,
547                               int line)
548 {
549   if ((p->ci) >= p->num_elements)
550   {
551     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Request for index %u bigger than array size of %u\n",
552         line, p->ci + 1, p->num_elements);
553     GNUNET_break (0);
554     return;
555   }
556   if ((0 == row) || (0 == col))
557     GNUNET_break (0);
558   p->ia[p->ci] = row ;
559   p->ja[p->ci] = col;
560   p->ar[p->ci] = val;
561 #if  DEBUG_MLP_PROBLEM_CREATION
562   LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Set value [%u,%u] in index %u ==  %.2f\n",
563       line, p->ia[p->ci], p->ja[p->ci], p->ci, p->ar[p->ci]);
564 #endif
565   p->ci++;
566 }
567
568 static int
569 mlp_create_problem_create_column (struct MLP_Problem *p, char *name,
570     unsigned int type, unsigned int bound, double lb, double ub,
571     double coef)
572 {
573   int col = glp_add_cols (p->prob, 1);
574   glp_set_col_name (p->prob, col, name);
575   glp_set_col_bnds (p->prob, col, bound, lb, ub);
576   glp_set_col_kind (p->prob, col, type);
577   glp_set_obj_coef (p->prob, col, coef);
578 #if  DEBUG_MLP_PROBLEM_CREATION
579   LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added column [%u] `%s': %.2f\n",
580       col, name, coef);
581 #endif
582   return col;
583 }
584
585 static int
586 mlp_create_problem_create_constraint (struct MLP_Problem *p, char *name,
587     unsigned int bound, double lb, double ub)
588 {
589   char * op;
590   int row = glp_add_rows (p->prob, 1);
591   /* set row name */
592   glp_set_row_name (p->prob, row, name);
593   /* set row bounds: <= 0 */
594   glp_set_row_bnds (p->prob, row, bound, lb, ub);
595   switch (bound)
596   {
597     case GLP_UP:
598             GNUNET_asprintf(&op, "-inf <= x <= %.2f", ub);
599             break;
600     case GLP_DB:
601             GNUNET_asprintf(&op, "%.2f <= x <= %.2f", lb, ub);
602             break;
603     case GLP_FX:
604             GNUNET_asprintf(&op, "%.2f == x == %.2f", lb, ub);
605             break;
606     case GLP_LO:
607             GNUNET_asprintf(&op, "%.2f <= x <= inf", lb);
608             break;
609     default:
610             GNUNET_asprintf(&op, "ERROR");
611             break;
612   }
613 #if  DEBUG_MLP_PROBLEM_CREATION
614     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added row [%u] `%s': %s\n",
615         row, name, op);
616 #endif
617   GNUNET_free (op);
618   return row;
619 }
620
621 /**
622  * Create the
623  * - address columns b and n
624  * - address dependent constraint rows c1, c3
625  * - peer dependent rows c2 and c9
626  * - Set address dependent entries in problem matrix as well
627  */
628 static int
629 mlp_create_problem_add_address_information (void *cls,
630                                             const struct GNUNET_PeerIdentity *key,
631                                             void *value)
632 {
633   struct GAS_MLP_Handle *mlp = cls;
634   struct MLP_Problem *p = &mlp->p;
635   struct ATS_Address *address = value;
636   struct ATS_Peer *peer;
637   struct MLP_information *mlpi;
638   char *name;
639   const double *props;
640   uint32_t addr_net;
641   int c;
642
643   /* Check if we have to add this peer due to a pending request */
644   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains(mlp->requested_peers, key))
645     return GNUNET_OK;
646
647   mlpi = address->solver_information;
648   if (NULL == mlpi)
649   {
650       fprintf (stderr, "%s %p\n",GNUNET_i2s (&address->peer), address);
651       GNUNET_break (0);
652       return GNUNET_OK;
653   }
654
655   /* Get peer */
656   peer = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, key);
657   if (peer->processed == GNUNET_NO)
658   {
659       /* Add peer dependent constraints */
660       /* Add constraint c2 */
661       GNUNET_asprintf(&name, "c2_%s", GNUNET_i2s(&address->peer));
662       peer->r_c2 = mlp_create_problem_create_constraint (p, name, GLP_FX, 1.0, 1.0);
663       GNUNET_free (name);
664       /* Add constraint c9 */
665       GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&address->peer));
666       peer->r_c9 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
667       GNUNET_free (name);
668       /* c 9) set coefficient */
669       mlp_create_problem_set_value (p, peer->r_c9, p->c_r, -peer->f, __LINE__);
670       peer->processed = GNUNET_YES;
671   }
672
673   /* Reset addresses' solver information */
674   mlpi->c_b = 0;
675   mlpi->c_n = 0;
676   mlpi->n = 0;
677   mlpi->r_c1 = 0;
678   mlpi->r_c3 = 0;
679
680   /* Add bandwidth column */
681   GNUNET_asprintf (&name, "b_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
682 #if TEST_MAX_BW_ASSIGNMENT
683   mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 1.0);
684 #else
685   mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0);
686 #endif
687
688   GNUNET_free (name);
689
690   /* Add usage column */
691   GNUNET_asprintf (&name, "n_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
692   mlpi->c_n = mlp_create_problem_create_column (p, name, GLP_IV, GLP_DB, 0.0, 1.0, 0.0);
693   GNUNET_free (name);
694
695   /* Add address dependent constraints */
696   /* Add constraint c1) bandwidth capping
697    * b_t  + (-M) * n_t <= 0
698    * */
699   GNUNET_asprintf(&name, "c1_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
700   mlpi->r_c1 = mlp_create_problem_create_constraint (p, name, GLP_UP, 0.0, 0.0);
701   GNUNET_free (name);
702
703   /*  c1) set b = 1 coefficient */
704   mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_b, 1, __LINE__);
705   /*  c1) set n = -M coefficient */
706   mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_n, -mlp->pv.BIG_M, __LINE__);
707
708   /* Add constraint c 3) minimum bandwidth
709    * b_t + (-n_t * b_min) >= 0
710    * */
711   GNUNET_asprintf(&name, "c3_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
712   mlpi->r_c3 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
713   GNUNET_free (name);
714
715   /*  c3) set b = 1 coefficient */
716   mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_b, 1, __LINE__);
717   /*  c3) set n = -b_min coefficient */
718   mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_n, - ((double )mlp->pv.b_min), __LINE__);
719
720
721   /* Set coefficient entries in invariant rows */
722   /* c 4) minimum connections */
723   mlp_create_problem_set_value (p, p->r_c4, mlpi->c_n, 1, __LINE__);
724   /* c 6) maximize diversity */
725   mlp_create_problem_set_value (p, p->r_c6, mlpi->c_n, 1, __LINE__);
726   /* c 2) 1 address peer peer */
727   mlp_create_problem_set_value (p, peer->r_c2, mlpi->c_n, 1, __LINE__);
728   /* c 9) relativity */
729   mlp_create_problem_set_value (p, peer->r_c9, mlpi->c_b, 1, __LINE__);
730   /* c 8) utility */
731   mlp_create_problem_set_value (p, p->r_c8, mlpi->c_b, 1, __LINE__);
732
733   /* c 10) obey network specific quotas
734    * (1)*b_1 + ... + (1)*b_m <= quota_n
735    */
736   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
737   {
738     addr_net = get_performance_info (address, GNUNET_ATS_NETWORK_TYPE);
739     if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
740     {
741       GNUNET_break (0);
742       addr_net = GNUNET_ATS_NET_UNSPECIFIED;
743     }
744
745     if (mlp->pv.quota_index[c] == addr_net)
746     {
747       mlp_create_problem_set_value (p, p->r_quota[c], mlpi->c_b, 1, __LINE__);
748       break;
749     }
750   }
751
752   /* c 7) Optimize quality */
753   /* For all quality metrics, set quality of this address */
754   props = mlp->get_properties (mlp->get_properties_cls, address);
755   for (c = 0; c < mlp->pv.m_q; c++)
756     mlp_create_problem_set_value (p, p->r_q[c], mlpi->c_b, props[c], __LINE__);
757
758   return GNUNET_OK;
759 }
760
761 /**
762  * Create the invariant columns c4, c6, c10, c8, c7
763  */
764 static void
765 mlp_create_problem_add_invariant_rows (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
766 {
767   char *name;
768   int c;
769
770   /* Row for c4) minimum connection */
771   /* Number of minimum connections is min(|Peers|, n_min) */
772   p->r_c4 = mlp_create_problem_create_constraint (p, "c4", GLP_LO, (mlp->pv.n_min > p->num_peers) ? p->num_peers : mlp->pv.n_min, 0.0);
773
774   /* Add row for c6) */
775   p->r_c6 = mlp_create_problem_create_constraint (p, "c6", GLP_FX, 0.0, 0.0);
776   /* c6 )Setting -D */
777   mlp_create_problem_set_value (p, p->r_c6, p->c_d, -1, __LINE__);
778
779   /* Add rows for c 10) */
780   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
781   {
782     char * text;
783     GNUNET_asprintf(&text, "c10_quota_ats_%s",
784         GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]));
785     p->r_quota[c] = mlp_create_problem_create_constraint (p, text, GLP_DB, 0.0, mlp->pv.quota_out[c]);
786     GNUNET_free (text);
787   }
788
789   /* Adding rows for c 8) */
790   p->r_c8 = mlp_create_problem_create_constraint (p, "c8", GLP_FX, 0.0, 0.0);
791   /* -u */
792   mlp_create_problem_set_value (p, p->r_c8, p->c_u, -1, __LINE__);
793
794   /* c 7) For all quality metrics */
795   for (c = 0; c < mlp->pv.m_q; c++)
796   {
797     GNUNET_asprintf(&name, "c7_q%i_%s", c, mlp_ats_to_string(mlp->pv.q[c]));
798     p->r_q[c] = mlp_create_problem_create_constraint (p, name, GLP_FX, 0.0, 0.0);
799     GNUNET_free (name);
800     mlp_create_problem_set_value (p, p->r_q[c], p->c_q[c], -1, __LINE__);
801   }
802 }
803
804
805 /**
806  * Create the invariant columns d, u, r, q0 ... qm
807  */
808 static void
809 mlp_create_problem_add_invariant_columns (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
810 {
811   char *name;
812   int c;
813
814 #if TEST_MAX_BW_ASSIGNMENT
815   mlp->pv.co_D = 0.0;
816   mlp->pv.co_U = 0.0;
817
818 #endif
819   //mlp->pv.co_R = 0.0;
820
821   /* Diversity d column  */
822   p->c_d = mlp_create_problem_create_column (p, "d", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_D);
823
824   /* Utilization u column  */
825   p->c_u = mlp_create_problem_create_column (p, "u", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_U);
826
827   /* Relativity r column  */
828   p->c_r = mlp_create_problem_create_column (p, "r", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_R);
829
830   /* Quality metric columns */
831   for (c = 0; c < mlp->pv.m_q; c++)
832   {
833     GNUNET_asprintf (&name, "q_%u", mlp->pv.q[c]);
834 #if TEST_MAX_BW_ASSIGNMENT
835     p->c_q[c] = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0);
836 #else
837     p->c_q[c] = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_Q[c]);
838 #endif
839     GNUNET_free (name);
840   }
841 }
842
843
844 /**
845  * Create the MLP problem
846  *
847  * @param mlp the MLP handle
848  * @return GNUNET_OK or GNUNET_SYSERR
849  */
850 static int
851 mlp_create_problem (struct GAS_MLP_Handle *mlp)
852 {
853   struct MLP_Problem *p = &mlp->p;
854   int res = GNUNET_OK;
855
856   GNUNET_assert (p->prob == NULL);
857   GNUNET_assert (p->ia == NULL);
858   GNUNET_assert (p->ja == NULL);
859   GNUNET_assert (p->ar == NULL);
860   /* Reset MLP problem struct */
861
862   /* create the glpk problem */
863   p->prob = glp_create_prob ();
864   GNUNET_assert (NULL != p->prob);
865   p->num_peers = mlp_create_problem_count_peers (mlp->requested_peers, mlp->addresses);
866   p->num_addresses = mlp_create_problem_count_addresses (mlp->requested_peers, mlp->addresses);
867
868   /* Create problem matrix: 10 * #addresses + #q * #addresses + #q, + #peer + 2 + 1 */
869   p->num_elements = (10 * p->num_addresses + mlp->pv.m_q * p->num_addresses +
870       mlp->pv.m_q + p->num_peers + 2 + 1);
871   LOG (GNUNET_ERROR_TYPE_DEBUG,
872        "Rebuilding problem for %u peer(s) and %u addresse(s) and %u quality metrics == %u elements\n",
873        p->num_peers,
874        p->num_addresses,
875        mlp->pv.m_q,
876        p->num_elements);
877
878   /* Set a problem name */
879   glp_set_prob_name (p->prob, "GNUnet ATS bandwidth distribution");
880   /* Set optimization direction to maximize */
881   glp_set_obj_dir (p->prob, GLP_MAX);
882
883   /* Create problem matrix */
884   /* last +1 caused by glpk index starting with one: [1..elements]*/
885   p->ci = 1;
886   /* row index */
887   p->ia = GNUNET_malloc (p->num_elements * sizeof (int));
888   /* column index */
889   p->ja = GNUNET_malloc (p->num_elements * sizeof (int));
890   /* coefficient */
891   p->ar = GNUNET_malloc (p->num_elements * sizeof (double));
892
893   if ((NULL == p->ia) || (NULL == p->ja) || (NULL == p->ar))
894   {
895       LOG (GNUNET_ERROR_TYPE_ERROR, _("Problem size too large, cannot allocate memory!\n"));
896       return GNUNET_SYSERR;
897   }
898
899   /* Adding invariant columns */
900   mlp_create_problem_add_invariant_columns (mlp, p);
901
902   /* Adding address independent constraint rows */
903   mlp_create_problem_add_invariant_rows (mlp, p);
904
905   /* Adding address dependent columns constraint rows */
906   GNUNET_CONTAINER_multipeermap_iterate (mlp->addresses,
907                                          &mlp_create_problem_add_address_information,
908                                          mlp);
909
910   /* Load the matrix */
911   LOG (GNUNET_ERROR_TYPE_DEBUG, "Loading matrix\n");
912   glp_load_matrix(p->prob, (p->ci)-1, p->ia, p->ja, p->ar);
913
914   return res;
915 }
916
917 /**
918  * Solves the LP problem
919  *
920  * @param mlp the MLP Handle
921  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
922  */
923 static int
924 mlp_solve_lp_problem (struct GAS_MLP_Handle *mlp)
925 {
926   int res = 0;
927
928   res = glp_simplex(mlp->p.prob, &mlp->control_param_lp);
929   if (0 == res)
930           LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem: 0x%02X %s\n", res, mlp_solve_to_string(res));
931   else
932           LOG (GNUNET_ERROR_TYPE_WARNING, "Solving LP problem failed: 0x%02X %s\n", res, mlp_solve_to_string(res));
933
934   /* Analyze problem status  */
935   res = glp_get_status (mlp->p.prob);
936   switch (res) {
937     /* solution is optimal */
938     case GLP_OPT:
939     /* solution is feasible */
940     case GLP_FEAS:
941       LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem: 0x%02X %s\n",
942           res, mlp_status_to_string(res));
943       return GNUNET_OK;
944     /* Problem was ill-defined, no way to handle that */
945     default:
946       LOG (GNUNET_ERROR_TYPE_WARNING, "Solving LP problem failed, no solution: 0x%02X %s\n",
947           res, mlp_status_to_string(res));
948       return GNUNET_SYSERR;
949   }
950 }
951
952
953 /**
954  * Solves the MLP problem
955  *
956  * @param mlp the MLP Handle
957  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
958  */
959 int
960 mlp_solve_mlp_problem (struct GAS_MLP_Handle *mlp)
961 {
962   int res = 0;
963   res = glp_intopt(mlp->p.prob, &mlp->control_param_mlp);
964   if (0 == res)
965           LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving MLP problem: 0x%02X %s\n", res, mlp_solve_to_string(res));
966   else
967           LOG (GNUNET_ERROR_TYPE_WARNING, "Solving MLP problem failed: 0x%02X %s\n", res, mlp_solve_to_string(res));
968   /* Analyze problem status  */
969   res = glp_mip_status(mlp->p.prob);
970   switch (res) {
971     /* solution is optimal */
972     case GLP_OPT:
973     /* solution is feasible */
974     case GLP_FEAS:
975       LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving MLP problem: 0x%02X %s\n", res, mlp_status_to_string(res));
976       return GNUNET_OK;
977     /* Problem was ill-defined, no way to handle that */
978     default:
979       LOG (GNUNET_ERROR_TYPE_WARNING,"Solving MLP problem failed, 0x%02X %s\n\n", res, mlp_status_to_string(res));
980       return GNUNET_SYSERR;
981   }
982 }
983
984 /**
985  * Propagates the results when MLP problem was solved
986  *
987  * @param cls the MLP handle
988  * @param key the peer identity
989  * @param value the address
990  * @return #GNUNET_OK to continue
991  */
992 int
993 mlp_propagate_results (void *cls,
994                        const struct GNUNET_PeerIdentity *key,
995                        void *value)
996 {
997   struct GAS_MLP_Handle *mlp = cls;
998   struct ATS_Address *address;
999   struct MLP_information *mlpi;
1000   double mlp_bw_in = MLP_NaN;
1001   double mlp_bw_out = MLP_NaN;
1002   double mlp_use = MLP_NaN;
1003
1004   /* Check if we have to add this peer due to a pending request */
1005   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mlp->requested_peers,
1006                                                            key))
1007   {
1008     return GNUNET_OK;
1009   }
1010   address = value;
1011   GNUNET_assert (address->solver_information != NULL);
1012   mlpi = address->solver_information;
1013
1014   mlp_bw_in = glp_mip_col_val(mlp->p.prob, mlpi->c_b);/* FIXME */
1015   if (mlp_bw_in > (double) UINT32_MAX)
1016   {
1017       LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
1018       mlp_bw_in = (double) UINT32_MAX;
1019   }
1020   mlp_bw_out = glp_mip_col_val(mlp->p.prob, mlpi->c_b);
1021   if (mlp_bw_out > (double) UINT32_MAX)
1022   {
1023       LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
1024       mlp_bw_out = (double) UINT32_MAX;
1025   }
1026   mlp_use = glp_mip_col_val(mlp->p.prob, mlpi->c_n);
1027
1028   /*
1029    * Debug: solution
1030    * LOG (GNUNET_ERROR_TYPE_INFO, "MLP result address: `%s' `%s' length %u session %u, mlp use %f\n",
1031    *    GNUNET_i2s(&address->peer), address->plugin,
1032    *    address->addr_len, address->session_id);
1033    */
1034
1035   if (GLP_YES == mlp_use)
1036   {
1037     /* This address was selected by the solver to be used */
1038     mlpi->n = GNUNET_YES;
1039     if (GNUNET_NO == address->active)
1040     {
1041             /* Address was not used before, enabling address */
1042       LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : enabling address\n",
1043           (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1044       address->active = GNUNET_YES;
1045       address->assigned_bw_in.value__ = htonl (mlp_bw_in);
1046       mlpi->b_in.value__ = htonl(mlp_bw_in);
1047       address->assigned_bw_out.value__ = htonl (mlp_bw_out);
1048       mlpi->b_out.value__ = htonl(mlp_bw_out);
1049       if ((NULL == mlp->exclude_peer) || (0 != memcmp (&address->peer, mlp->exclude_peer, sizeof (address->peer))))
1050         mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
1051       return GNUNET_OK;
1052     }
1053     else if (GNUNET_YES == address->active)
1054     {
1055       /* Address was used before, check for bandwidth change */
1056       if ((mlp_bw_out != ntohl(address->assigned_bw_out.value__)) ||
1057               (mlp_bw_in != ntohl(address->assigned_bw_in.value__)))
1058       {
1059           LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : bandwidth changed\n",
1060               (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1061           address->assigned_bw_in.value__ = htonl (mlp_bw_in);
1062           mlpi->b_in.value__ = htonl(mlp_bw_in);
1063           address->assigned_bw_out.value__ = htonl (mlp_bw_out);
1064           mlpi->b_out.value__ = htonl(mlp_bw_out);
1065           if ((NULL == mlp->exclude_peer) || (0 != memcmp (&address->peer, mlp->exclude_peer, sizeof (address->peer))))
1066             mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
1067           return GNUNET_OK;
1068       }
1069     }
1070     else
1071       GNUNET_break (0);
1072   }
1073   else if (GLP_NO == mlp_use)
1074   {
1075     /* This address was selected by the solver to be not used */
1076     mlpi->n = GNUNET_NO;
1077     if (GNUNET_NO == address->active)
1078     {
1079       /* Address was not used before, nothing to do */
1080       LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : no change\n",
1081           (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1082       return GNUNET_OK;
1083     }
1084     else if (GNUNET_YES == address->active)
1085     {
1086     /* Address was used before, disabling address */
1087     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : disabling address\n",
1088         (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1089       address->active = GNUNET_NO;
1090       /* Set bandwidth to 0 */
1091       address->assigned_bw_in = BANDWIDTH_ZERO;
1092       mlpi->b_in.value__ = htonl(mlp_bw_in);
1093       address->assigned_bw_out = BANDWIDTH_ZERO;
1094       mlpi->b_out.value__ = htonl(mlp_bw_out);
1095       //mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
1096       return GNUNET_OK;
1097     }
1098     else
1099       GNUNET_break (0);
1100   }
1101   else
1102     GNUNET_break (0);
1103
1104   return GNUNET_OK;
1105 }
1106
1107 static void notify (struct GAS_MLP_Handle *mlp,
1108     enum GAS_Solver_Operation op,
1109     enum GAS_Solver_Status stat,
1110     enum GAS_Solver_Additional_Information add)
1111 {
1112   if (NULL != mlp->env->info_cb)
1113     mlp->env->info_cb (mlp->env->info_cb_cls, op, stat, add);
1114 }
1115 /**
1116  * Solves the MLP problem
1117  *
1118  * @param solver the MLP Handle
1119  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
1120  */
1121 int
1122 GAS_mlp_solve_problem (void *solver)
1123 {
1124   struct GAS_MLP_Handle *mlp = solver;
1125   char *filename;
1126   int res_lp = 0;
1127   int res_mip = 0;
1128
1129   struct GNUNET_TIME_Absolute start_total;
1130   struct GNUNET_TIME_Absolute start_cur_op;
1131   struct GNUNET_TIME_Relative dur_total;
1132   struct GNUNET_TIME_Relative dur_setup;
1133   struct GNUNET_TIME_Relative dur_lp;
1134   struct GNUNET_TIME_Relative dur_mlp;
1135
1136   GNUNET_assert(NULL != solver);
1137
1138   if (GNUNET_YES == mlp->stat_bulk_lock)
1139     {
1140       mlp->stat_bulk_requests++;
1141       return GNUNET_NO;
1142     }
1143   notify(mlp, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS,
1144       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1145   start_total = GNUNET_TIME_absolute_get();
1146
1147   if (0 == GNUNET_CONTAINER_multipeermap_size(mlp->requested_peers))
1148     {
1149       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1150       return GNUNET_OK; /* No pending requests */
1151     }
1152   if (0 == GNUNET_CONTAINER_multipeermap_size(mlp->addresses))
1153     {
1154       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1155       return GNUNET_OK; /* No addresses available */
1156     }
1157
1158   if ((GNUNET_NO == mlp->stat_mlp_prob_changed)
1159       && (GNUNET_NO == mlp->stat_mlp_prob_updated))
1160     {
1161       LOG(GNUNET_ERROR_TYPE_DEBUG, "No changes to problem\n");
1162       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1163       return GNUNET_OK;
1164     }
1165   if (GNUNET_YES == mlp->stat_mlp_prob_changed)
1166     {
1167       LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem size changed, rebuilding\n");
1168       notify(mlp, GAS_OP_SOLVE_SETUP_START, GAS_STAT_SUCCESS, GAS_INFO_FULL);
1169       mlp_delete_problem(mlp);
1170       if (GNUNET_SYSERR == mlp_create_problem(mlp))
1171         {
1172           notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_FAIL, GAS_INFO_FULL);
1173           return GNUNET_SYSERR;
1174         }
1175       notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_SUCCESS, GAS_INFO_FULL);
1176       mlp->control_param_lp.presolve = GLP_YES;
1177       mlp->control_param_mlp.presolve = GNUNET_NO; /* No presolver, we have LP solution */
1178     }
1179   else
1180     {
1181       LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem was updated, resolving\n");
1182     }
1183
1184   dur_setup = GNUNET_TIME_absolute_get_duration (start_total);
1185
1186   /* Run LP solver */
1187   notify(mlp, GAS_OP_SOLVE_MLP_LP_START, GAS_STAT_SUCCESS,
1188       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1189   LOG(GNUNET_ERROR_TYPE_DEBUG,
1190       "Running LP solver %s\n",
1191       (GLP_YES == mlp->control_param_lp.presolve)? "with presolver": "without presolver");
1192   start_cur_op = GNUNET_TIME_absolute_get();
1193
1194   /* Solve LP */
1195   mlp->control_param_lp.presolve = GLP_YES;
1196   res_lp = mlp_solve_lp_problem(mlp);
1197
1198   dur_lp = GNUNET_TIME_absolute_get_duration (start_cur_op);
1199   notify(mlp, GAS_OP_SOLVE_MLP_LP_STOP,
1200       (GNUNET_OK == res_lp) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1201       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1202
1203
1204   /* Run MLP solver */
1205   if (GNUNET_OK == res_lp)
1206   {
1207     LOG(GNUNET_ERROR_TYPE_DEBUG, "Running MLP solver \n");
1208     notify(mlp, GAS_OP_SOLVE_MLP_MLP_START, GAS_STAT_SUCCESS,
1209         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1210     start_cur_op = GNUNET_TIME_absolute_get();
1211
1212     /* Solve MIP */
1213     //mlp->control_param_mlp.presolve = GNUNET_YES;
1214     res_mip = mlp_solve_mlp_problem(mlp);
1215
1216     dur_mlp = GNUNET_TIME_absolute_get_duration (start_cur_op);
1217     dur_total = GNUNET_TIME_absolute_get_duration (start_total);
1218
1219     notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP,
1220         (GNUNET_OK == res_mip) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1221         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1222   }
1223   else
1224   {
1225     /* Do not execute mip solver since lp solution is invalid */
1226     dur_mlp = GNUNET_TIME_UNIT_ZERO;
1227     dur_total = GNUNET_TIME_absolute_get_duration (start_total);
1228     notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP, GAS_STAT_FAIL,
1229         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1230     res_mip = GNUNET_SYSERR;
1231   }
1232
1233
1234   /* Notify about end */
1235   notify(mlp, GAS_OP_SOLVE_STOP,
1236       ((GNUNET_OK == res_mip) && (GNUNET_OK == res_mip)) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1237       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1238
1239   LOG (GNUNET_ERROR_TYPE_DEBUG,
1240       "Execution time for %s solve: (total/setup/lp/mlp) : %llu %llu %llu %llu\n",
1241       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? "full" : "updated",
1242       (unsigned long long) dur_total.rel_value_us,
1243       (unsigned long long) dur_setup.rel_value_us,
1244       (unsigned long long) dur_lp.rel_value_us,
1245       (unsigned long long) dur_mlp.rel_value_us);
1246
1247   /* Save stats */
1248   mlp->ps.lp_res = res_lp;
1249   mlp->ps.mip_res = res_mip;
1250   mlp->ps.lp_presolv = mlp->control_param_lp.presolve;
1251   mlp->ps.mip_presolv = mlp->control_param_mlp.presolve;
1252   mlp->ps.p_cols = glp_get_num_cols(mlp->p.prob);
1253   mlp->ps.p_rows = glp_get_num_rows(mlp->p.prob);
1254   mlp->ps.p_elements = mlp->p.num_elements;
1255
1256   /* Propagate result*/
1257   notify(mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1258       (GNUNET_OK == res_lp) && (GNUNET_OK == res_mip) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1259       GAS_INFO_NONE);
1260   if ((GNUNET_OK == res_lp) && (GNUNET_OK == res_mip))
1261     {
1262       GNUNET_CONTAINER_multipeermap_iterate(mlp->addresses,
1263           &mlp_propagate_results, mlp);
1264     }
1265   notify(mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1266       (GNUNET_OK == res_lp) && (GNUNET_OK == res_mip) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1267       GAS_INFO_NONE);
1268
1269   struct GNUNET_TIME_Absolute time = GNUNET_TIME_absolute_get();
1270   if ( (GNUNET_YES == mlp->opt_dump_solution_all) ||
1271       (mlp->opt_dump_solution_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != res_mip))) )
1272     {
1273       /* Write problem to disk */
1274       GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.lp", mlp->p.num_peers,
1275           mlp->p.num_addresses, time.abs_value_us);
1276       LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped problem to file: `%s' \n", filename);
1277       glp_write_lp (mlp->p.prob, NULL, filename);
1278       GNUNET_free(filename);
1279     }
1280   if ( (mlp->opt_dump_solution_all) ||
1281       (mlp->opt_dump_solution_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != res_mip))) )
1282   {
1283     /* Write solution to disk */
1284     GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.sol", mlp->p.num_peers,
1285         mlp->p.num_addresses, time.abs_value_us);
1286     glp_print_mip(mlp->p.prob, filename);
1287     LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped solution to file: `%s' \n", filename);
1288     GNUNET_free(filename);
1289   }
1290
1291   /* Reset change and update marker */
1292   mlp->control_param_lp.presolve = GLP_NO;
1293   mlp->stat_mlp_prob_updated = GNUNET_NO;
1294   mlp->stat_mlp_prob_changed = GNUNET_NO;
1295
1296   if ((GNUNET_OK == res_lp) && (GNUNET_OK == res_mip))
1297     return GNUNET_OK;
1298   else
1299     return GNUNET_SYSERR;
1300 }
1301
1302 /**
1303  * Add a single address to the solve
1304  *
1305  * @param solver the solver Handle
1306  * @param address the address to add
1307  * @param network network type of this address
1308  */
1309 void
1310 GAS_mlp_address_add (void *solver,
1311                     struct ATS_Address *address,
1312                     uint32_t network)
1313 {
1314   struct GAS_MLP_Handle *mlp = solver;
1315   struct ATS_Peer *p;
1316
1317   GNUNET_assert (NULL != solver);
1318   GNUNET_assert (NULL != address);
1319
1320   if (GNUNET_ATS_NetworkTypeCount <= network)
1321   {
1322    GNUNET_break (0);
1323    return;
1324   }
1325
1326   if (NULL == address->solver_information)
1327   {
1328       address->solver_information = GNUNET_new (struct MLP_information);
1329   }
1330   else
1331       LOG (GNUNET_ERROR_TYPE_ERROR,
1332            _("Adding address for peer `%s' multiple times\n"),
1333            GNUNET_i2s(&address->peer));
1334
1335   /* Is this peer included in the problem? */
1336   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1337                                                       &address->peer)))
1338   {
1339     LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding address for peer `%s' without address request \n", GNUNET_i2s(&address->peer));
1340     return;
1341   }
1342
1343   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding address for peer `%s' with address request \n", GNUNET_i2s(&address->peer));
1344   /* Problem size changed: new address for peer with pending request */
1345   mlp->stat_mlp_prob_changed = GNUNET_YES;
1346   if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1347     GAS_mlp_solve_problem (solver);
1348 }
1349
1350
1351 /**
1352  * Transport properties for this address have changed
1353  *
1354  * @param solver solver handle
1355  * @param address the address
1356  * @param type the ATSI type in HBO
1357  * @param abs_value the absolute value of the property
1358  * @param rel_value the normalized value
1359  */
1360 void
1361 GAS_mlp_address_property_changed (void *solver,
1362                                   struct ATS_Address *address,
1363                                   uint32_t type,
1364                                   uint32_t abs_value,
1365                                   double rel_value)
1366 {
1367   struct MLP_information *mlpi = address->solver_information;
1368   struct GAS_MLP_Handle *mlp = solver;
1369   struct ATS_Peer *p;
1370   int c1;
1371   int type_index;
1372
1373   GNUNET_assert (NULL != solver);
1374   GNUNET_assert (NULL != address);
1375
1376   if (NULL == mlpi)
1377   {
1378       LOG (GNUNET_ERROR_TYPE_ERROR,
1379           _("Updating address property `%s' for peer `%s' %p not added before\n"),
1380           GNUNET_ATS_print_property_type (type),
1381           GNUNET_i2s(&address->peer),
1382           address);
1383       GNUNET_break (0);
1384       return;
1385   }
1386
1387   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1388                                                       &address->peer)))
1389   {
1390     /* Peer is not requested, so no need to update problem */
1391     return;
1392   }
1393   LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating property `%s' address for peer `%s'\n",
1394       GNUNET_ATS_print_property_type (type),
1395       GNUNET_i2s(&address->peer));
1396
1397   /* Find row index */
1398   type_index = -1;
1399   for (c1 = 0; c1 < mlp->pv.m_q; c1++)
1400   {
1401     if (type == mlp->pv.q[c1])
1402     {
1403       type_index = c1;
1404       break;
1405     }
1406   }
1407   if (-1 == type_index)
1408   {
1409     GNUNET_break (0);
1410     return; /* quality index not found */
1411   }
1412
1413   /* Update c7) [r_q[index]][c_b] = f_q * q_averaged[type_index] */
1414   if (GNUNET_YES == mlp_create_problem_update_value (&mlp->p,
1415       mlp->p.r_q[type_index], mlpi->c_b, rel_value, __LINE__))
1416   {
1417     mlp->stat_mlp_prob_updated = GNUNET_YES;
1418     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1419       GAS_mlp_solve_problem (solver);
1420   }
1421 }
1422
1423
1424 /**
1425  * Transport session for this address has changed
1426  *
1427  * NOTE: values in addresses are already updated
1428  *
1429  * @param solver solver handle
1430  * @param address the address
1431  * @param cur_session the current session
1432  * @param new_session the new session
1433  */
1434 void
1435 GAS_mlp_address_session_changed (void *solver,
1436                                   struct ATS_Address *address,
1437                                   uint32_t cur_session,
1438                                   uint32_t new_session)
1439 {
1440   /* Nothing to do here */
1441   return;
1442 }
1443
1444
1445 /**
1446  * Transport session for this address has changed
1447  *
1448  * NOTE: values in addresses are already updated
1449  *
1450  * @param solver solver handle
1451  * @param address the address
1452  * @param in_use usage state
1453  */
1454 void
1455 GAS_mlp_address_inuse_changed (void *solver,
1456                                struct ATS_Address *address,
1457                                int in_use)
1458 {
1459   /* Nothing to do here */
1460   return;
1461 }
1462
1463
1464 /**
1465  * Network scope for this address has changed
1466  *
1467  * NOTE: values in addresses are already updated
1468  *
1469  * @param solver solver handle
1470  * @param address the address
1471  * @param current_network the current network
1472  * @param new_network the new network
1473  */
1474 void
1475 GAS_mlp_address_change_network (void *solver,
1476                                struct ATS_Address *address,
1477                                uint32_t current_network,
1478                                uint32_t new_network)
1479 {
1480   struct MLP_information *mlpi = address->solver_information;
1481   struct GAS_MLP_Handle *mlp = solver;
1482   struct ATS_Peer *p;
1483   int nets_avail[] = GNUNET_ATS_NetworkType;
1484   int c1;
1485
1486   GNUNET_assert (NULL != solver);
1487   GNUNET_assert (NULL != address);
1488
1489   if (GNUNET_ATS_NetworkTypeCount <= new_network)
1490   {
1491    GNUNET_break (0);
1492    return;
1493   }
1494
1495   if (NULL == mlpi)
1496   {
1497     GNUNET_break (0);
1498     return;
1499   }
1500
1501   if (mlpi->c_b == MLP_UNDEFINED)
1502     return; /* This address is not yet in the matrix*/
1503
1504   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1505                                                       &address->peer)))
1506   {
1507     /* Peer is not requested, so no need to update problem */
1508     GNUNET_break (0);
1509     return;
1510   }
1511
1512   if (current_network == new_network)
1513   {
1514     GNUNET_break (0);
1515     return;
1516   }
1517
1518   for (c1 = 0; c1 < GNUNET_ATS_NetworkTypeCount ; c1 ++)
1519   {
1520     if (nets_avail[c1] == new_network)
1521       break;
1522   }
1523
1524   if (GNUNET_ATS_NetworkTypeCount == c1)
1525   {
1526     /* Invalid network */
1527     GNUNET_break (0);
1528     return;
1529   }
1530
1531   LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating network for peer `%s' from `%s' to `%s'\n",
1532       GNUNET_i2s (&address->peer),
1533       GNUNET_ATS_print_network_type(current_network),
1534       GNUNET_ATS_print_network_type(new_network));
1535
1536   for (c1 = 0; c1 < GNUNET_ATS_NetworkTypeCount; c1++)
1537   {
1538     if (mlp->pv.quota_index[c1] == current_network)
1539     {
1540       /* Remove from old network */
1541       mlp_create_problem_update_value (&mlp->p,
1542           mlp->p.r_quota[c1],
1543           mlpi->c_b, 0.0, __LINE__);
1544       break;
1545     }
1546   }
1547
1548   for (c1 = 0; c1 < GNUNET_ATS_NetworkTypeCount; c1++)
1549   {
1550     if (mlp->pv.quota_index[c1] == new_network)
1551     {
1552       /* Remove from old network */
1553       if (GNUNET_SYSERR == mlp_create_problem_update_value (&mlp->p,
1554           mlp->p.r_quota[c1],
1555           mlpi->c_b, 1.0, __LINE__))
1556       {
1557         /* This quota did not exist in the problem, recreate */
1558         GNUNET_break (0);
1559       }
1560       break;
1561     }
1562   }
1563
1564   mlp->stat_mlp_prob_changed = GNUNET_YES;
1565 }
1566
1567
1568 /**
1569  * Deletes a single address in the MLP problem
1570  *
1571  * The MLP problem has to be recreated and the problem has to be resolved
1572  *
1573  * @param solver the MLP Handle
1574  * @param address the address to delete
1575  * @param session_only delete only session not whole address
1576  */
1577 void
1578 GAS_mlp_address_delete (void *solver,
1579     struct ATS_Address *address,
1580     int session_only)
1581 {
1582   struct ATS_Peer *p;
1583   struct GAS_MLP_Handle *mlp = solver;
1584   struct MLP_information *mlpi;
1585   int was_active;
1586
1587   GNUNET_assert (NULL != solver);
1588   GNUNET_assert (NULL != address);
1589
1590   mlpi = address->solver_information;
1591   if ((GNUNET_NO == session_only) && (NULL != mlpi))
1592   {
1593     /* Remove full address */
1594     GNUNET_free (mlpi);
1595     address->solver_information = NULL;
1596   }
1597   was_active = address->active;
1598   address->active = GNUNET_NO;
1599   address->assigned_bw_in = BANDWIDTH_ZERO;
1600   address->assigned_bw_out = BANDWIDTH_ZERO;
1601
1602   /* Is this peer included in the problem? */
1603   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1604                                                       &address->peer)))
1605   {
1606     LOG (GNUNET_ERROR_TYPE_INFO, "Deleting %s for peer `%s' without address request \n",
1607         (session_only == GNUNET_YES) ? "session" : "address",
1608         GNUNET_i2s(&address->peer));
1609     return;
1610   }
1611   LOG (GNUNET_ERROR_TYPE_INFO, "Deleting %s for peer `%s' with address request \n",
1612       (session_only == GNUNET_YES) ? "session" : "address",
1613       GNUNET_i2s(&address->peer));
1614
1615   /* Problem size changed: new address for peer with pending request */
1616   mlp->stat_mlp_prob_changed = GNUNET_YES;
1617   if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1618   {
1619     GAS_mlp_solve_problem (solver);
1620   }
1621   if (GNUNET_YES == was_active)
1622   {
1623     if (NULL == GAS_mlp_get_preferred_address (solver, &address->peer))
1624     {
1625       /* No alternative address, disconnecting peer */
1626       mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
1627     }
1628   }
1629
1630   return;
1631 }
1632
1633
1634 /**
1635  * Find the active address in the set of addresses of a peer
1636  * @param cls destination
1637  * @param key peer id
1638  * @param value address
1639  * @return GNUNET_OK
1640  */
1641 static int
1642 mlp_get_preferred_address_it (void *cls,
1643                               const struct GNUNET_PeerIdentity *key,
1644                               void *value)
1645 {
1646   static int counter = 0;
1647   struct ATS_Address **aa = cls;
1648   struct ATS_Address *addr = value;
1649   struct MLP_information *mlpi = addr->solver_information;
1650
1651   if (mlpi == NULL)
1652     return GNUNET_YES;
1653
1654   /*
1655    * Debug output
1656    * GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1657    *           "MLP [%u] Peer `%s' %s length %u session %u active %s mlp active %s\n",
1658    *           counter, GNUNET_i2s (&addr->peer), addr->plugin, addr->addr_len, addr->session_id,
1659    *           (GNUNET_YES == addr->active) ? "active" : "inactive",
1660    *           (GNUNET_YES == mlpi->n) ? "active" : "inactive");
1661    */
1662
1663   if (GNUNET_YES == mlpi->n)
1664   {
1665
1666     (*aa) = addr;
1667     (*aa)->assigned_bw_in = mlpi->b_in;
1668     (*aa)->assigned_bw_out = mlpi->b_out;
1669     return GNUNET_NO;
1670   }
1671   counter ++;
1672   return GNUNET_YES;
1673 }
1674
1675
1676 static double
1677 get_peer_pref_value (struct GAS_MLP_Handle *mlp, const struct GNUNET_PeerIdentity *peer)
1678 {
1679   double res;
1680   const double *preferences = NULL;
1681   int c;
1682   preferences = mlp->get_preferences (mlp->get_preferences_cls, peer);
1683
1684   res = 0.0;
1685   for (c = 0; c < GNUNET_ATS_PreferenceCount; c++)
1686   {
1687     if (c != GNUNET_ATS_PREFERENCE_END)
1688     {
1689       //fprintf (stderr, "VALUE[%u] %s %.3f \n", c, GNUNET_i2s (&cur->addr->peer), t[c]);
1690       res += preferences[c];
1691     }
1692   }
1693   res /= (GNUNET_ATS_PreferenceCount -1);
1694   return res;
1695 }
1696
1697
1698 /**
1699  * Get the preferred address for a specific peer
1700  *
1701  * @param solver the MLP Handle
1702  * @param peer the peer
1703  * @return suggested address
1704  */
1705 const struct ATS_Address *
1706 GAS_mlp_get_preferred_address (void *solver,
1707                                const struct GNUNET_PeerIdentity *peer)
1708 {
1709   struct GAS_MLP_Handle *mlp = solver;
1710   struct ATS_Peer *p;
1711   struct ATS_Address *res;
1712
1713   GNUNET_assert (NULL != solver);
1714   GNUNET_assert (NULL != peer);
1715
1716   LOG (GNUNET_ERROR_TYPE_DEBUG, "Getting preferred address for `%s'\n",
1717       GNUNET_i2s (peer));
1718
1719   /* Is this peer included in the problem? */
1720   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1721                                                       peer)))
1722     {
1723       LOG (GNUNET_ERROR_TYPE_INFO, "Adding peer `%s' to list of requested_peers with requests\n",
1724           GNUNET_i2s (peer));
1725
1726       p = GNUNET_new (struct ATS_Peer);
1727       p->id = (*peer);
1728       p->f = get_peer_pref_value (mlp, peer);
1729       GNUNET_CONTAINER_multipeermap_put (mlp->requested_peers,
1730                                          peer, p,
1731                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1732
1733       /* Added new peer, we have to rebuild problem before solving */
1734       mlp->stat_mlp_prob_changed = GNUNET_YES;
1735
1736       if ((GNUNET_YES == mlp->opt_mlp_auto_solve)&&
1737           (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(mlp->addresses,
1738                                                                 peer)))
1739       {
1740         mlp->exclude_peer = peer;
1741         GAS_mlp_solve_problem (mlp);
1742         mlp->exclude_peer = NULL;
1743       }
1744   }
1745   /* Get prefered address */
1746   res = NULL;
1747   GNUNET_CONTAINER_multipeermap_get_multiple (mlp->addresses, peer,
1748                                               mlp_get_preferred_address_it, &res);
1749   return res;
1750 }
1751
1752
1753 /**
1754  * Start a bulk operation
1755  *
1756  * @param solver the solver
1757  */
1758 void
1759 GAS_mlp_bulk_start (void *solver)
1760 {
1761   LOG (GNUNET_ERROR_TYPE_DEBUG, "Locking solver for bulk operation ...\n");
1762   struct GAS_MLP_Handle *s = (struct GAS_MLP_Handle *) solver;
1763
1764   GNUNET_assert (NULL != solver);
1765
1766   s->stat_bulk_lock ++;
1767 }
1768
1769 void
1770 GAS_mlp_bulk_stop (void *solver)
1771 {
1772   LOG (GNUNET_ERROR_TYPE_DEBUG, "Unlocking solver from bulk operation ...\n");
1773
1774   struct GAS_MLP_Handle *s = (struct GAS_MLP_Handle *) solver;
1775   GNUNET_assert (NULL != solver);
1776
1777   if (s->stat_bulk_lock < 1)
1778   {
1779     GNUNET_break (0);
1780     return;
1781   }
1782   s->stat_bulk_lock --;
1783
1784   if (0 < s->stat_bulk_requests)
1785   {
1786     GAS_mlp_solve_problem (solver);
1787     s->stat_bulk_requests= 0;
1788   }
1789 }
1790
1791
1792
1793 /**
1794  * Stop notifying about address and bandwidth changes for this peer
1795  *
1796  * @param solver the MLP handle
1797  * @param peer the peer
1798  */
1799 void
1800 GAS_mlp_stop_get_preferred_address (void *solver,
1801                                      const struct GNUNET_PeerIdentity *peer)
1802 {
1803   struct GAS_MLP_Handle *mlp = solver;
1804   struct ATS_Peer *p = NULL;
1805
1806   GNUNET_assert (NULL != solver);
1807   GNUNET_assert (NULL != peer);
1808   if (NULL != (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer)))
1809   {
1810     GNUNET_CONTAINER_multipeermap_remove (mlp->requested_peers, peer, p);
1811     GNUNET_free (p);
1812
1813     mlp->stat_mlp_prob_changed = GNUNET_YES;
1814     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1815     {
1816       GAS_mlp_solve_problem (solver);
1817     }
1818   }
1819 }
1820
1821
1822 /**
1823  * Changes the preferences for a peer in the MLP problem
1824  *
1825  * @param solver the MLP Handle
1826  * @param peer the peer
1827  * @param kind the kind to change the preference
1828  * @param pref_rel the relative score
1829  */
1830 void
1831 GAS_mlp_address_change_preference (void *solver,
1832                    const struct GNUNET_PeerIdentity *peer,
1833                    enum GNUNET_ATS_PreferenceKind kind,
1834                    double pref_rel)
1835 {
1836   struct GAS_MLP_Handle *mlp = solver;
1837   struct ATS_Peer *p = NULL;
1838
1839   LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing preference for address for peer `%s' to %.2f\n",
1840       GNUNET_i2s(peer), pref_rel);
1841
1842   GNUNET_STATISTICS_update (mlp->stats,"# LP address preference changes", 1, GNUNET_NO);
1843   /* Update the constraints with changed preferences */
1844
1845   /* Update quality constraint c7 */
1846
1847   /* Update relativity constraint c9 */
1848   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer)))
1849   {
1850     LOG (GNUNET_ERROR_TYPE_ERROR, "Updating preference for unknown peer `%s'\n", GNUNET_i2s(peer));
1851     return;
1852   }
1853   p->f = get_peer_pref_value (mlp, peer);
1854   /*
1855   LOG (GNUNET_ERROR_TYPE_ERROR, "PEER PREF: %s %.2f\n",
1856       GNUNET_i2s(peer), p->f);*/
1857   mlp_create_problem_update_value (&mlp->p, p->r_c9, mlp->p.c_r, -p->f, __LINE__);
1858
1859   /* Problem size changed: new address for peer with pending request */
1860   mlp->stat_mlp_prob_updated = GNUNET_YES;
1861   if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1862     GAS_mlp_solve_problem (solver);
1863   return;
1864 }
1865
1866
1867 /**
1868  * Get application feedback for a peer
1869  *
1870  * @param solver the solver handle
1871  * @param application the application
1872  * @param peer the peer to change the preference for
1873  * @param scope the time interval for this feedback: [now - scope .. now]
1874  * @param kind the kind to change the preference
1875  * @param score the score
1876  */
1877 void
1878 GAS_mlp_address_preference_feedback (void *solver,
1879                                     void *application,
1880                                     const struct GNUNET_PeerIdentity *peer,
1881                                     const struct GNUNET_TIME_Relative scope,
1882                                     enum GNUNET_ATS_PreferenceKind kind,
1883                                     double score)
1884 {
1885   struct GAS_PROPORTIONAL_Handle *s = solver;
1886   GNUNET_assert (NULL != solver);
1887   GNUNET_assert (NULL != peer);
1888
1889   GNUNET_assert (NULL != s);
1890 }
1891
1892
1893 static int
1894 mlp_free_peers (void *cls,
1895                 const struct GNUNET_PeerIdentity *key, void *value)
1896 {
1897   struct GNUNET_CONTAINER_MultiPeerMap *map = cls;
1898   struct ATS_Peer *p = value;
1899
1900   GNUNET_CONTAINER_multipeermap_remove (map, key, value);
1901   GNUNET_free (p);
1902
1903   return GNUNET_OK;
1904 }
1905
1906
1907 /**
1908  * Shutdown the MLP problem solving component
1909  *
1910  * @param cls the solver handle
1911  * @return NULL
1912  */
1913 void *
1914 libgnunet_plugin_ats_mlp_done (void *cls)
1915 {
1916   struct GAS_MLP_Handle *mlp = cls;
1917   GNUNET_assert (mlp != NULL);
1918
1919   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down mlp solver\n");
1920   mlp_delete_problem (mlp);
1921
1922   GNUNET_CONTAINER_multipeermap_iterate (mlp->requested_peers,
1923                                          &mlp_free_peers,
1924                                          mlp->requested_peers);
1925   GNUNET_CONTAINER_multipeermap_destroy (mlp->requested_peers);
1926   mlp->requested_peers = NULL;
1927
1928   /* Clean up GLPK environment */
1929   glp_free_env();
1930   GNUNET_free (mlp);
1931
1932   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutdown down of mlp solver complete\n");
1933   return NULL;
1934 }
1935
1936
1937 void *
1938 libgnunet_plugin_ats_mlp_init (void *cls)
1939 {
1940   struct GNUNET_ATS_PluginEnvironment *env = cls;
1941   struct GAS_MLP_Handle * mlp = GNUNET_new (struct GAS_MLP_Handle);
1942
1943   double D;
1944   double R;
1945   double U;
1946   unsigned long long tmp;
1947   unsigned int b_min;
1948   unsigned int n_min;
1949   int c;
1950   int c2;
1951   int found;
1952
1953   struct GNUNET_TIME_Relative max_duration;
1954   long long unsigned int max_iterations;
1955
1956   GNUNET_assert (NULL != env->cfg);
1957   GNUNET_assert (NULL != env->addresses);
1958   GNUNET_assert (NULL != env->bandwidth_changed_cb);
1959   GNUNET_assert (NULL != env->get_preferences);
1960   GNUNET_assert (NULL != env->get_property);
1961
1962   /* Init GLPK environment */
1963   int res = glp_init_env();
1964   switch (res) {
1965     case 0:
1966       LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
1967           "initialization successful");
1968       break;
1969     case 1:
1970       LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
1971           "environment is already initialized");
1972       break;
1973     case 2:
1974       LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
1975           "initialization failed (insufficient memory)");
1976       GNUNET_free(mlp);
1977       return NULL;
1978       break;
1979     case 3:
1980       LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
1981           "initialization failed (unsupported programming model)");
1982       GNUNET_free(mlp);
1983       return NULL;
1984       break;
1985     default:
1986       break;
1987   }
1988
1989   mlp->opt_dump_problem_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
1990      "ats", "MLP_DUMP_PROBLEM_ALL");
1991   if (GNUNET_SYSERR == mlp->opt_dump_problem_all)
1992    mlp->opt_dump_problem_all = GNUNET_NO;
1993
1994   mlp->opt_dump_solution_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
1995      "ats", "MLP_DUMP_SOLUTION_ALL");
1996   if (GNUNET_SYSERR == mlp->opt_dump_solution_all)
1997    mlp->opt_dump_solution_all = GNUNET_NO;
1998
1999   mlp->opt_dump_problem_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2000      "ats", "MLP_DUMP_PROBLEM_ON_FAIL");
2001   if (GNUNET_SYSERR == mlp->opt_dump_problem_on_fail)
2002    mlp->opt_dump_problem_on_fail = GNUNET_NO;
2003
2004   mlp->opt_dump_solution_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2005      "ats", "MLP_DUMP_SOLUTION_ON_FAIL");
2006   if (GNUNET_SYSERR == mlp->opt_dump_solution_on_fail)
2007    mlp->opt_dump_solution_on_fail = GNUNET_NO;
2008
2009   mlp->opt_glpk_verbose = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2010      "ats", "MLP_GLPK_VERBOSE");
2011   if (GNUNET_SYSERR == mlp->opt_glpk_verbose)
2012    mlp->opt_glpk_verbose = GNUNET_NO;
2013
2014   mlp->pv.BIG_M = (double) BIG_M_VALUE;
2015
2016   /* Get timeout for iterations */
2017   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(env->cfg, "ats",
2018       "MLP_MAX_DURATION", &max_duration))
2019   {
2020     max_duration = MLP_MAX_EXEC_DURATION;
2021   }
2022
2023   /* Get maximum number of iterations */
2024   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats",
2025       "MLP_MAX_ITERATIONS", &max_iterations))
2026   {
2027     max_iterations = MLP_MAX_ITERATIONS;
2028   }
2029
2030   /* Get diversity coefficient from configuration */
2031   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg,
2032       "ats", "MLP_COEFFICIENT_D", &tmp))
2033     D = (double) tmp / 100;
2034   else
2035     D = DEFAULT_D;
2036
2037   /* Get proportionality coefficient from configuration */
2038   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg,
2039       "ats", "MLP_COEFFICIENT_R", &tmp))
2040     R = (double) tmp / 100;
2041   else
2042     R = DEFAULT_R;
2043
2044   /* Get utilization coefficient from configuration */
2045   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg,
2046       "ats", "MLP_COEFFICIENT_U", &tmp))
2047     U = (double) tmp / 100;
2048   else
2049     U = DEFAULT_U;
2050
2051   /* Get quality metric coefficients from configuration */
2052   int i_delay = MLP_NaN;
2053   int i_distance = MLP_NaN;
2054   int q[GNUNET_ATS_QualityPropertiesCount] = GNUNET_ATS_QualityProperties;
2055   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
2056   {
2057     /* initialize quality coefficients with default value 1.0 */
2058       mlp->pv.co_Q[c] = DEFAULT_QUALITY;
2059
2060     mlp->pv.q[c] = q[c];
2061     if (q[c] == GNUNET_ATS_QUALITY_NET_DELAY)
2062       i_delay = c;
2063     if (q[c] == GNUNET_ATS_QUALITY_NET_DISTANCE)
2064       i_distance = c;
2065   }
2066
2067   if ( (i_delay != MLP_NaN) &&
2068        (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2069           "MLP_COEFFICIENT_QUALITY_DELAY", &tmp)) )
2070     mlp->pv.co_Q[i_delay] = (double) tmp / 100;
2071   else
2072     mlp->pv.co_Q[i_delay] = DEFAULT_QUALITY;
2073
2074   if ( (i_distance != MLP_NaN) &&
2075         (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2076           "MLP_COEFFICIENT_QUALITY_DISTANCE", &tmp)) )
2077     mlp->pv.co_Q[i_distance] = (double) tmp / 100;
2078   else
2079     mlp->pv.co_Q[i_distance] = DEFAULT_QUALITY;
2080
2081   /* Get minimum bandwidth per used address from configuration */
2082   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2083                                                       "MLP_MIN_BANDWIDTH",
2084                                                       &tmp))
2085     b_min = tmp;
2086   else
2087   {
2088     b_min = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
2089   }
2090
2091   /* Get minimum number of connections from configuration */
2092   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2093                                                       "MLP_MIN_CONNECTIONS",
2094                                                       &tmp))
2095     n_min = tmp;
2096   else
2097     n_min = DEFAULT_MIN_CONNECTIONS;
2098
2099   /* Init network quotas */
2100   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
2101   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
2102   {
2103       found = GNUNET_NO;
2104       for (c2 = 0; c2 < env->network_count; c2++)
2105       {
2106           if (quotas[c] == env->networks[c2])
2107           {
2108               mlp->pv.quota_index[c] = env->networks[c2];
2109               mlp->pv.quota_out[c] = env->out_quota[c2];
2110               mlp->pv.quota_in[c] = env->in_quota[c2];
2111               found = GNUNET_YES;
2112               LOG (GNUNET_ERROR_TYPE_DEBUG,
2113                   "Quota for network `%s' (in/out) %llu/%llu\n",
2114                   GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2115                   mlp->pv.quota_out[c],
2116                   mlp->pv.quota_in[c]);
2117               break;
2118           }
2119       }
2120
2121       /* Check if defined quota could make problem unsolvable */
2122       if ((n_min * b_min) > mlp->pv.quota_out[c])
2123       {
2124         LOG (GNUNET_ERROR_TYPE_INFO,
2125             _("Adjusting inconsistent outbound quota configuration for network `%s', is %llu must be at least %llu\n"),
2126             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2127             mlp->pv.quota_out[c],
2128             (n_min * b_min));
2129         mlp->pv.quota_out[c] = (n_min * b_min);
2130       }
2131       if ((n_min * b_min) > mlp->pv.quota_in[c])
2132       {
2133         LOG (GNUNET_ERROR_TYPE_INFO,
2134             _("Adjusting inconsistent inbound quota configuration for network `%s', is %llu must be at least %llu\n"),
2135             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2136             mlp->pv.quota_in[c],
2137             (n_min * b_min));
2138         mlp->pv.quota_in[c] = (n_min * b_min);
2139       }
2140
2141       /* Check if bandwidth is too big to make problem solvable */
2142       if (mlp->pv.BIG_M < mlp->pv.quota_out[c])
2143       {
2144         LOG (GNUNET_ERROR_TYPE_INFO,
2145             _("Adjusting outbound quota configuration for network `%s'from %llu to %.0f\n"),
2146             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2147             mlp->pv.quota_out[c],
2148             mlp->pv.BIG_M);
2149         mlp->pv.quota_out[c] = mlp->pv.BIG_M ;
2150       }
2151       if (mlp->pv.BIG_M < mlp->pv.quota_in[c])
2152       {
2153         LOG (GNUNET_ERROR_TYPE_INFO, _("Adjusting inbound quota configuration for network `%s' from %llu to %.0f\n"),
2154             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2155             mlp->pv.quota_in[c],
2156             mlp->pv.BIG_M);
2157         mlp->pv.quota_in[c] = mlp->pv.BIG_M ;
2158       }
2159
2160       if (GNUNET_NO == found)
2161       {
2162         mlp->pv.quota_in[c] = ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
2163         mlp->pv.quota_out[c] = ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
2164         LOG (GNUNET_ERROR_TYPE_INFO, _("Using default quota configuration for network `%s' (in/out) %llu/%llu\n"),
2165             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2166             mlp->pv.quota_in[c],
2167             mlp->pv.quota_out[c]);
2168       }
2169   }
2170   mlp->env = env;
2171   env->sf.s_add = &GAS_mlp_address_add;
2172   env->sf.s_address_update_property = &GAS_mlp_address_property_changed;
2173   env->sf.s_address_update_session = &GAS_mlp_address_session_changed;
2174   env->sf.s_address_update_inuse = &GAS_mlp_address_inuse_changed;
2175   env->sf.s_address_update_network = &GAS_mlp_address_change_network;
2176   env->sf.s_get = &GAS_mlp_get_preferred_address;
2177   env->sf.s_get_stop = &GAS_mlp_stop_get_preferred_address;
2178   env->sf.s_pref = &GAS_mlp_address_change_preference;
2179   env->sf.s_feedback = &GAS_mlp_address_preference_feedback;
2180   env->sf.s_del = &GAS_mlp_address_delete;
2181   env->sf.s_bulk_start = &GAS_mlp_bulk_start;
2182   env->sf.s_bulk_stop = &GAS_mlp_bulk_stop;
2183
2184
2185   /* Assign options to handle */
2186   mlp->stats = (struct GNUNET_STATISTICS_Handle *) env->stats;
2187   mlp->addresses = env->addresses;
2188   mlp->bw_changed_cb = env->bandwidth_changed_cb;
2189   mlp->bw_changed_cb_cls = env->bw_changed_cb_cls;
2190   mlp->get_preferences =  env->get_preferences;
2191   mlp->get_preferences_cls = env->get_preference_cls;
2192   mlp->get_properties = env->get_property;
2193   mlp->get_properties_cls = env->get_property_cls;
2194   /* Setting MLP Input variables */
2195
2196   mlp->pv.co_D = D;
2197   mlp->pv.co_R = R;
2198   mlp->pv.co_U = U;
2199   mlp->pv.b_min = b_min;
2200   mlp->pv.n_min = n_min;
2201   mlp->pv.m_q = GNUNET_ATS_QualityPropertiesCount;
2202   mlp->stat_mlp_prob_changed = GNUNET_NO;
2203   mlp->stat_mlp_prob_updated = GNUNET_NO;
2204   mlp->opt_mlp_auto_solve = GNUNET_YES;
2205   mlp->requested_peers = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
2206   mlp->stat_bulk_requests = 0;
2207   mlp->stat_bulk_lock = 0;
2208
2209   /* Setup GLPK */
2210   /* Redirect GLPK output to GNUnet logging */
2211   glp_term_hook (&mlp_term_hook, (void *) mlp);
2212
2213   /* Init LP solving parameters */
2214   glp_init_smcp(&mlp->control_param_lp);
2215   mlp->control_param_lp.msg_lev = GLP_MSG_OFF;
2216   if (GNUNET_YES == mlp->opt_glpk_verbose)
2217     mlp->control_param_lp.msg_lev = GLP_MSG_ALL;
2218
2219   mlp->control_param_lp.it_lim = max_iterations;
2220   mlp->control_param_lp.tm_lim = max_duration.rel_value_us / 1000LL;
2221
2222   /* Init MLP solving parameters */
2223   glp_init_iocp(&mlp->control_param_mlp);
2224   mlp->control_param_mlp.msg_lev = GLP_MSG_OFF;
2225   if (GNUNET_YES == mlp->opt_glpk_verbose)
2226     mlp->control_param_mlp.msg_lev = GLP_MSG_ALL;
2227   mlp->control_param_mlp.tm_lim = max_duration.rel_value_us / 1000LL;
2228
2229   LOG (GNUNET_ERROR_TYPE_DEBUG, "solver ready\n");
2230
2231   return mlp;
2232 }
2233
2234 /* end of plugin_ats_mlp.c */