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