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