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