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