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