doxygen fixes
[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                 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 static void
416 mlp_create_problem_set_value (struct MLP_Problem *p,
417                                                                                                                         int row, int col, double val,
418                                                                                                                         int line)
419 {
420         if ((p->ci) >= p->num_elements)
421         {
422                 LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Request for index %u bigger than array size of %u\n",
423                                 line, p->ci + 1, p->num_elements);
424                 GNUNET_break (0);
425                 return;
426         }
427         if ((0 == row) || (0 == col))
428                 GNUNET_break (0);
429   p->ia[p->ci] = row ;
430   p->ja[p->ci] = col;
431   p->ar[p->ci] = val;
432 #if  DEBUG_MLP_PROBLEM_CREATION
433         LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Set value [%u,%u] in index %u ==  %.2f\n",
434                         line, p->ia[p->ci], p->ja[p->ci], p->ci, p->ar[p->ci]);
435 #endif
436   p->ci++;
437 }
438
439 static int
440 mlp_create_problem_create_column (struct MLP_Problem *p, char *name,
441                 unsigned int type, unsigned int bound, double lb, double ub,
442                 double coef)
443 {
444         int col = glp_add_cols (p->prob, 1);
445   glp_set_col_name (p->prob, col, name);
446   glp_set_col_bnds (p->prob, col, bound, lb, ub);
447   glp_set_col_kind (p->prob, col, type);
448   glp_set_obj_coef (p->prob, col, coef);
449 #if  DEBUG_MLP_PROBLEM_CREATION
450         LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added column [%u] `%s': %.2f\n",
451                         col, name, coef);
452 #endif
453   return col;
454 }
455
456 static int
457 mlp_create_problem_create_constraint (struct MLP_Problem *p, char *name,
458                 unsigned int bound, double lb, double ub)
459 {
460         char * op;
461   int row = glp_add_rows (p->prob, 1);
462   /* set row name */
463   glp_set_row_name (p->prob, row, name);
464   /* set row bounds: <= 0 */
465   glp_set_row_bnds (p->prob, row, bound, lb, ub);
466   switch (bound) {
467                 case GLP_UP:
468                         GNUNET_asprintf(&op, "-inf <= x <= %.2f", ub);
469                         break;
470                 case GLP_DB:
471                         GNUNET_asprintf(&op, "%.2f <= x <= %.2f", lb, ub);
472                         break;
473                 case GLP_FX:
474                         GNUNET_asprintf(&op, "%.2f == x == %.2f", lb, ub);
475                         break;
476                 case GLP_LO:
477                         GNUNET_asprintf(&op, "%.2f <= x <= inf", lb);
478                         break;
479                 default:
480                         GNUNET_asprintf(&op, "ERROR");
481                         break;
482         }
483 #if  DEBUG_MLP_PROBLEM_CREATION
484                 LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added row [%u] `%s': %s\n",
485                                 row, name, op);
486 #endif
487         GNUNET_free (op);
488         return row;
489 }
490
491 /**
492  * Create the
493  * - address columns b and n
494  * - address dependent constraint rows c1, c3
495  * - peer dependent rows c2 and c9
496  * - Set address dependent entries in problem matrix as well
497  */
498 static int
499 mlp_create_problem_add_address_information (void *cls, const struct GNUNET_HashCode *key, void *value)
500 {
501   struct GAS_MLP_Handle *mlp = cls;
502   struct MLP_Problem *p = &mlp->p;
503   struct ATS_Address *address = value;
504   struct ATS_Peer *peer;
505   struct MLP_information *mlpi;
506   char *name;
507   uint32_t addr_net;
508   int c;
509
510   /* Check if we have to add this peer due to a pending request */
511   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(mlp->peers, key))
512         return GNUNET_OK;
513
514   mlpi = address->solver_information;
515   if (NULL == mlpi)
516   {
517                 GNUNET_break (0);
518                 return GNUNET_OK;
519   }
520
521   /* Get peer */
522   peer = GNUNET_CONTAINER_multihashmap_get (mlp->peers, key);
523   if (peer->processed == GNUNET_NO)
524   {
525                 /* Add peer dependent constraints */
526                 /* Add constraint c2 */
527           GNUNET_asprintf(&name, "c2_%s", GNUNET_i2s(&address->peer));
528           peer->r_c2 = mlp_create_problem_create_constraint (p, name, GLP_FX, 1.0, 1.0);
529                 GNUNET_free (name);
530                 /* Add constraint c9 */
531           GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&address->peer));
532           peer->r_c9 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
533                 GNUNET_free (name);
534           /* c 9) set coefficient */
535                 mlp_create_problem_set_value (p, peer->r_c9, p->c_r, -peer->f, __LINE__);
536
537                 peer->processed = GNUNET_YES;
538   }
539
540   /* Reset addresses' solver information */
541   mlpi->c_b = 0;
542   mlpi->c_n = 0;
543   mlpi->n = 0;
544   mlpi->r_c1 = 0;
545   mlpi->r_c3 = 0;
546   for (c = 0; c < mlp->pv.m_q; c++)
547         mlpi->r_q[0] = 0;
548
549   /* Add bandwidth column */
550   GNUNET_asprintf (&name, "b_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
551 #if TEST_MAX_BW_ASSIGNMENT
552   mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 1.0);
553 #else
554   mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0);
555 #endif
556
557   GNUNET_free (name);
558
559   /* Add usage column */
560   GNUNET_asprintf (&name, "n_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
561   mlpi->c_n = mlp_create_problem_create_column (p, name, GLP_IV, GLP_DB, 0.0, 1.0, 0.0);
562   GNUNET_free (name);
563
564         /* Add address dependent constraints */
565         /* Add constraint c1) bandwidth capping
566    * b_t  + (-M) * n_t <= 0
567    * */
568   GNUNET_asprintf(&name, "c1_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
569   mlpi->r_c1 = mlp_create_problem_create_constraint (p, name, GLP_UP, 0.0, 0.0);
570         GNUNET_free (name);
571
572         /*  c1) set b = 1 coefficient */
573         mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_b, 1, __LINE__);
574         /*  c1) set n = -M coefficient */
575         mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_n, -mlp->pv.BIG_M, __LINE__);
576
577   /* Add constraint c 3) minimum bandwidth
578    * b_t + (-n_t * b_min) >= 0
579    * */
580   GNUNET_asprintf(&name, "c3_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
581         mlpi->r_c3 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
582         GNUNET_free (name);
583
584         /*  c3) set b = 1 coefficient */
585         mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_b, 1, __LINE__);
586         /*  c3) set n = -b_min coefficient */
587         mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_n, - ((double )mlp->pv.b_min), __LINE__);
588
589
590         /* Set coefficient entries in invariant rows */
591   /* c 4) minimum connections */
592         mlp_create_problem_set_value (p, p->r_c4, mlpi->c_n, 1, __LINE__);
593   /* c 6) maximize diversity */
594         mlp_create_problem_set_value (p, p->r_c6, mlpi->c_n, 1, __LINE__);
595   /* c 2) 1 address peer peer */
596         mlp_create_problem_set_value (p, peer->r_c2, mlpi->c_n, 1, __LINE__);
597   /* c 9) relativity */
598         mlp_create_problem_set_value (p, peer->r_c9, mlpi->c_b, 1, __LINE__);
599   /* c 8) utility */
600         mlp_create_problem_set_value (p, p->r_c8, mlpi->c_b, 1, __LINE__);
601
602   /* c 10) obey network specific quotas
603    * (1)*b_1 + ... + (1)*b_m <= quota_n
604    */
605   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
606   {
607         addr_net = get_performance_info (address, GNUNET_ATS_NETWORK_TYPE);
608         if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
609                 addr_net = GNUNET_ATS_NET_UNSPECIFIED;
610
611     if (mlp->pv.quota_index[c] == addr_net)
612     {
613                 mlp_create_problem_set_value (p, p->r_quota[c], mlpi->c_b, 1, __LINE__);
614       break;
615     }
616   }
617
618   /* c 7) Optimize quality */
619   /* For all quality metrics, set quality of this address */
620   for (c = 0; c < mlp->pv.m_q; c++)
621   {
622
623     mlp_create_problem_set_value (p, p->r_q[c], mlpi->c_b, mlpi->q_averaged[c], __LINE__);
624   }
625
626   return GNUNET_OK;
627 }
628
629 /**
630  * Create the invariant columns c4, c6, c10, c8, c7
631  */
632 static void
633 mlp_create_problem_add_invariant_rows (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
634 {
635   char *name;
636   int c;
637
638   /* Row for c4) minimum connection */
639   /* Number of minimum connections is min(|Peers|, n_min) */
640   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);
641
642   /* Add row for c6) */
643         p->r_c6 = mlp_create_problem_create_constraint (p, "c6", GLP_FX, 0.0, 0.0);
644   /* c6 )Setting -D */
645         mlp_create_problem_set_value (p, p->r_c6, p->c_d, -1, __LINE__);
646
647   /* Add rows for c 10) */
648   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
649   {
650       char * text;
651       GNUNET_asprintf(&text, "c10_quota_ats_%s", GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]));
652                 p->r_quota[c] = mlp_create_problem_create_constraint (p, text, GLP_DB, 0.0, mlp->pv.quota_out[c]);
653                 GNUNET_free (text);
654   }
655
656   /* Adding rows for c 8) */
657   p->r_c8 = mlp_create_problem_create_constraint (p, "c8", GLP_FX, 0.0, 0.0);
658   /* -u */
659         mlp_create_problem_set_value (p, p->r_c8, p->c_u, -1, __LINE__);
660
661         /* c 7) For all quality metrics */
662         for (c = 0; c < mlp->pv.m_q; c++)
663         {
664                 GNUNET_asprintf(&name, "c7_q%i_%s", c, mlp_ats_to_string(mlp->pv.q[c]));
665                 p->r_q[c] = mlp_create_problem_create_constraint (p, name, GLP_FX, 0.0, 0.0);
666                 GNUNET_free (name);
667                 mlp_create_problem_set_value (p, p->r_q[c], p->c_q[c], -1, __LINE__);
668         }
669 }
670
671
672 /**
673  * Create the invariant columns d, u, r, q0 ... qm
674  */
675 static void
676 mlp_create_problem_add_invariant_columns (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
677 {
678   char *name;
679   int c;
680
681 #if TEST_MAX_BW_ASSIGNMENT
682   mlp->pv.co_D = 0.0;
683   mlp->pv.co_U = 0.0;
684
685 #endif
686   //mlp->pv.co_R = 0.0;
687
688   /* Diversity d column  */
689   p->c_d = mlp_create_problem_create_column (p, "d", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_D);
690
691   /* Utilization u column  */
692   p->c_u = mlp_create_problem_create_column (p, "u", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_U);
693
694   /* Relativity r column  */
695   p->c_r = mlp_create_problem_create_column (p, "r", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_R);
696
697   /* Quality metric columns */
698   for (c = 0; c < mlp->pv.m_q; c++)
699   {
700     GNUNET_asprintf (&name, "q_%u", mlp->pv.q[c]);
701 #if TEST_MAX_BW_ASSIGNMENT
702         p->c_q[c] = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0);
703 #else
704         p->c_q[c] = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_Q[c]);
705 #endif
706         GNUNET_free (name);
707   }
708 }
709
710
711 /**
712  * Create the MLP problem
713  *
714  * @param mlp the MLP handle
715  * @param addresses the hashmap containing all adresses
716  * @return GNUNET_OK or GNUNET_SYSERR
717  */
718 static int
719 mlp_create_problem (struct GAS_MLP_Handle *mlp, struct GNUNET_CONTAINER_MultiHashMap * addresses)
720 {
721   struct MLP_Problem *p = &mlp->p;
722         int res = GNUNET_OK;
723
724   GNUNET_assert (p->prob == NULL);
725   GNUNET_assert (p->ia == NULL);
726   GNUNET_assert (p->ja == NULL);
727   GNUNET_assert (p->ar == NULL);
728   /* Reset MLP problem struct */
729
730   /* create the glpk problem */
731   p->prob = glp_create_prob ();
732   GNUNET_assert (NULL != p->prob);
733   p->num_peers = GNUNET_CONTAINER_multihashmap_size (mlp->peers);
734   p->num_addresses = mlp_create_problem_count_addresses (mlp->peers, addresses);
735
736   /* Create problem matrix: 10 * #addresses + #q * #addresses + #q, + #peer + 2 + 1 */
737   p->num_elements = (10 * p->num_addresses + mlp->pv.m_q * p->num_addresses +  mlp->pv.m_q + p->num_peers + 2 + 1);
738         LOG (GNUNET_ERROR_TYPE_DEBUG, "Rebuilding problem for %u peer(s) and %u addresse(s) and %u quality metrics == %u elements\n",
739                         p->num_peers, p->num_addresses, mlp->pv.m_q, p->num_elements);
740
741   /* Set a problem name */
742   glp_set_prob_name (p->prob, "GNUnet ATS bandwidth distribution");
743   /* Set optimization direction to maximize */
744   glp_set_obj_dir (p->prob, GLP_MAX);
745
746   /* Create problem matrix */
747   /* last +1 caused by glpk index starting with one: [1..elements]*/
748   p->ci = 1;
749   /* row index */
750   p->ia = GNUNET_malloc (p->num_elements * sizeof (int));
751   /* column index */
752   p->ja = GNUNET_malloc (p->num_elements * sizeof (int));
753   /* coefficient */
754   p->ar = GNUNET_malloc (p->num_elements * sizeof (double));
755
756   if ((NULL == p->ia) || (NULL == p->ja) || (NULL == p->ar))
757   {
758                 LOG (GNUNET_ERROR_TYPE_ERROR, _("Problem size too large, cannot allocate memory!\n"));
759                 return GNUNET_SYSERR;
760   }
761
762   /* Adding invariant columns */
763   mlp_create_problem_add_invariant_columns (mlp, p);
764
765   /* Adding address independent constraint rows */
766   mlp_create_problem_add_invariant_rows (mlp, p);
767
768   /* Adding address dependent columns constraint rows */
769   GNUNET_CONTAINER_multihashmap_iterate (addresses, &mlp_create_problem_add_address_information, mlp);
770
771   /* Load the matrix */
772         LOG (GNUNET_ERROR_TYPE_DEBUG, "Loading matrix\n");
773   glp_load_matrix(p->prob, (p->ci)-1, p->ia, p->ja, p->ar);
774
775   return res;
776 }
777
778 /**
779  * Solves the LP problem
780  *
781  * @param mlp the MLP Handle
782  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
783  */
784 static int
785 mlp_solve_lp_problem (struct GAS_MLP_Handle *mlp)
786 {
787         int res = 0;
788
789         res = glp_simplex(mlp->p.prob, &mlp->control_param_lp);
790         if (0 == res)
791                 LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem: 0x%02X %s\n", res, mlp_solve_to_string(res));
792         else
793                 LOG (GNUNET_ERROR_TYPE_WARNING, "Solving LP problem failed: 0x%02X %s\n", res, mlp_solve_to_string(res));
794
795   /* Analyze problem status  */
796   res = glp_get_status (mlp->p.prob);
797   switch (res) {
798     /* solution is optimal */
799     case GLP_OPT:
800     /* solution is feasible */
801     case GLP_FEAS:
802       LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem: 0x%02X %s\n",
803                 res, mlp_status_to_string(res));
804       return GNUNET_OK;
805     /* Problem was ill-defined, no way to handle that */
806     default:
807       LOG (GNUNET_ERROR_TYPE_WARNING, "Solving LP problem failed, no solution: 0x%02X %s\n",
808                 res, mlp_status_to_string(res));
809       return GNUNET_SYSERR;
810   }
811 }
812
813
814 /**
815  * Solves the MLP problem
816  *
817  * @param mlp the MLP Handle
818  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
819  */
820 int
821 mlp_solve_mlp_problem (struct GAS_MLP_Handle *mlp)
822 {
823         int res = 0;
824         res = glp_intopt(mlp->p.prob, &mlp->control_param_mlp);
825         if (0 == res)
826                 LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving MLP problem: 0x%02X %s\n", res, mlp_solve_to_string(res));
827         else
828                 LOG (GNUNET_ERROR_TYPE_WARNING, "Solving MLP problem failed: 0x%02X %s\n", res, mlp_solve_to_string(res));
829   /* Analyze problem status  */
830   res = glp_mip_status(mlp->p.prob);
831   switch (res) {
832     /* solution is optimal */
833     case GLP_OPT:
834     /* solution is feasible */
835     case GLP_FEAS:
836       LOG (GNUNET_ERROR_TYPE_DEBUG, "Solving MLP problem: 0x%02X %s\n", res, mlp_status_to_string(res));
837       return GNUNET_OK;
838     /* Problem was ill-defined, no way to handle that */
839     default:
840       LOG (GNUNET_ERROR_TYPE_WARNING,"Solving MLP problem failed, 0x%02X %s\n\n", res, mlp_status_to_string(res));
841       return GNUNET_SYSERR;
842   }
843 }
844
845
846 /**
847  * Propagates the results when MLP problem was solved
848  *
849  * @param cls the MLP handle
850  * @param key the peer identity
851  * @param value the address
852  * @return GNUNET_OK to continue
853  */
854 int
855 mlp_propagate_results (void *cls, const struct GNUNET_HashCode *key, void *value)
856 {
857         struct GAS_MLP_Handle *mlp = cls;
858         struct ATS_Address *address;
859         struct MLP_information *mlpi;
860         double mlp_bw_in = MLP_NaN;
861         double mlp_bw_out = MLP_NaN;
862         double mlp_use = MLP_NaN;
863
864   /* Check if we have to add this peer due to a pending request */
865   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(mlp->peers, key))
866         return GNUNET_OK;
867   address = value;
868   GNUNET_assert (address->solver_information != NULL);
869   mlpi = address->solver_information;
870
871   mlp_bw_in = glp_mip_col_val(mlp->p.prob, mlpi->c_b);/* FIXME */
872   if (mlp_bw_in > (double) UINT32_MAX)
873   {
874                 LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
875                 mlp_bw_in = (double) UINT32_MAX;
876   }
877   mlp_bw_out = glp_mip_col_val(mlp->p.prob, mlpi->c_b);
878   if (mlp_bw_out > (double) UINT32_MAX)
879   {
880                 LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
881                 mlp_bw_out = (double) UINT32_MAX;
882   }
883   mlp_use = glp_mip_col_val(mlp->p.prob, mlpi->c_n);
884
885
886
887   if ((GLP_YES == mlp_use) && (GNUNET_NO == address->active))
888   {
889         /* Address switch: Activate address*/
890         LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : enabling address\n", (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
891                 address->active = GNUNET_YES;
892                 address->assigned_bw_in.value__ = htonl (mlp_bw_in);
893                 mlpi->b_in.value__ = htonl(mlp_bw_in);
894                 address->assigned_bw_out.value__ = htonl (mlp_bw_out);
895                 mlpi->b_out.value__ = htonl(mlp_bw_out);
896                 mlpi->n = mlp_use;
897                 mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
898   }
899   else if ((GLP_NO == mlp_use) && (GNUNET_YES == address->active))
900   {
901                 /* Address switch: Disable address*/
902         LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : disabling address\n", (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
903                 address->active = GNUNET_NO;
904                 /* Set bandwidth to 0 */
905                 address->assigned_bw_in.value__ = htonl (0);
906                 mlpi->b_in.value__ = htonl(mlp_bw_in);
907                 address->assigned_bw_out.value__ = htonl (0);
908                 mlpi->b_out.value__ = htonl(mlp_bw_out);
909                 mlpi->n = mlp_use;
910                 mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
911   }
912   else if ((mlp_bw_out != ntohl(address->assigned_bw_out.value__)) ||
913                                  (mlp_bw_in != ntohl(address->assigned_bw_in.value__)))
914   {
915         /* Bandwidth changed */
916                 LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : bandwidth changed\n", (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
917                 address->assigned_bw_in.value__ = htonl (mlp_bw_in);
918                 mlpi->b_in.value__ = htonl(mlp_bw_in);
919                 address->assigned_bw_out.value__ = htonl (mlp_bw_out);
920                 mlpi->b_out.value__ = htonl(mlp_bw_out);
921                 mlpi->n = mlp_use;
922                 mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
923   }
924   else
925   {
926     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : no change\n", (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
927   }
928
929   return GNUNET_OK;
930 }
931
932
933
934 /**
935  * Solves the MLP problem
936  *
937  * @param solver the MLP Handle
938  * @param addresses the address hashmap
939  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
940  */
941 int
942 GAS_mlp_solve_problem (void *solver, struct GNUNET_CONTAINER_MultiHashMap * addresses)
943 {
944         struct GAS_MLP_Handle *mlp = solver;
945         char *filename;
946         int res_lp = 0;
947         int res_mip = 0;
948         struct GNUNET_TIME_Absolute start_build;
949         struct GNUNET_TIME_Relative duration_build;
950         struct GNUNET_TIME_Absolute start_lp;
951         struct GNUNET_TIME_Relative duration_lp;
952         struct GNUNET_TIME_Absolute start_mlp;
953         struct GNUNET_TIME_Relative duration_mlp;
954         GNUNET_assert (NULL != solver);
955
956         if ((GNUNET_NO == mlp->mlp_prob_changed) && (GNUNET_NO == mlp->mlp_prob_updated))
957         {
958                 LOG (GNUNET_ERROR_TYPE_DEBUG, "No changes to problem\n");
959                 return GNUNET_OK;
960         }
961
962         if (GNUNET_YES == mlp->mlp_prob_changed)
963         {
964                         LOG (GNUNET_ERROR_TYPE_DEBUG, "Problem size changed, rebuilding\n");
965                         mlp_delete_problem (mlp);
966                         start_build = GNUNET_TIME_absolute_get();
967                         if (GNUNET_SYSERR == mlp_create_problem (mlp, addresses))
968                                 return GNUNET_SYSERR;
969                         duration_build = GNUNET_TIME_absolute_get_duration (start_build);
970                         mlp->control_param_lp.presolve = GLP_YES;
971                         mlp->control_param_mlp.presolve = GNUNET_NO; /* No presolver, we have LP solution */
972         }
973         else
974         {
975                         LOG (GNUNET_ERROR_TYPE_DEBUG, "Problem was updated, resolving\n");
976                         duration_build.rel_value = 0;
977         }
978
979         /* Run LP solver */
980         LOG (GNUNET_ERROR_TYPE_DEBUG, "Running LP solver %s\n", (GLP_YES == mlp->control_param_lp.presolve)? "with presolver": "without presolver");
981         start_lp = GNUNET_TIME_absolute_get();
982         res_lp = mlp_solve_lp_problem (mlp);
983         duration_lp = GNUNET_TIME_absolute_get_duration (start_lp);
984
985
986   /* Run LP solver */
987         LOG (GNUNET_ERROR_TYPE_DEBUG, "Running MLP solver \n");
988         start_mlp = GNUNET_TIME_absolute_get();
989         res_mip = mlp_solve_mlp_problem (mlp);
990
991         duration_mlp = GNUNET_TIME_absolute_get_duration (start_mlp);
992
993         /* Save stats */
994         mlp->ps.lp_res = res_lp;
995         mlp->ps.mip_res = res_mip;
996         mlp->ps.build_dur = duration_build;
997         mlp->ps.lp_dur = duration_lp;
998         mlp->ps.mip_dur = duration_mlp;
999         mlp->ps.lp_presolv = mlp->control_param_lp.presolve;
1000         mlp->ps.mip_presolv = mlp->control_param_mlp.presolve;
1001         mlp->ps.p_cols = glp_get_num_cols (mlp->p.prob);
1002         mlp->ps.p_rows = glp_get_num_rows (mlp->p.prob);
1003         mlp->ps.p_elements = mlp->p.num_elements;
1004
1005         LOG (GNUNET_ERROR_TYPE_DEBUG, "Execution time: Build %llu ms, LP %llu ms,  MLP %llu ms\n",
1006                         (unsigned long long) duration_build.rel_value,
1007                         (unsigned long long) duration_lp.rel_value,
1008                         (unsigned long long) duration_mlp.rel_value);
1009
1010         /* Propagate result*/
1011         if ((GNUNET_OK == res_lp) && (GNUNET_OK == res_mip))
1012                 GNUNET_CONTAINER_multihashmap_iterate (addresses, &mlp_propagate_results, mlp);
1013
1014         struct GNUNET_TIME_Absolute time = GNUNET_TIME_absolute_get();
1015         if (GNUNET_YES == mlp->write_mip_mps)
1016         {
1017         /* Write problem and solution to disk */
1018         GNUNET_asprintf (&filename, "problem_p_%u_a%u_%llu.mps", mlp->p.num_peers, mlp->p.num_addresses, time.abs_value);
1019         glp_write_mps(mlp->p.prob, GLP_MPS_FILE, NULL, filename);
1020         GNUNET_free (filename);
1021         }
1022         if (GNUNET_YES == mlp->write_mip_sol)
1023         {
1024                 GNUNET_asprintf (&filename, "problem_p_%u_a%u_%llu.sol", mlp->p.num_peers, mlp->p.num_addresses, time.abs_value);
1025                 glp_print_mip (mlp->p.prob, filename );
1026                 GNUNET_free (filename);
1027         }
1028
1029         /* Reset change and update marker */
1030         mlp->control_param_lp.presolve = GLP_NO;
1031         mlp->mlp_prob_updated = GNUNET_NO;
1032         mlp->mlp_prob_changed = GNUNET_NO;
1033
1034         if ((GNUNET_OK == res_lp) && (GNUNET_OK == res_mip))
1035                 return GNUNET_OK;
1036         else
1037                 return GNUNET_SYSERR;
1038 }
1039
1040 /**
1041  * Add a single address to the solve
1042  *
1043  * @param solver the solver Handle
1044  * @param addresses the address hashmap containing all addresses
1045  * @param address the address to add
1046  * @param network network type of this address
1047  */
1048 void
1049 GAS_mlp_address_add (void *solver,
1050                                                                                 struct GNUNET_CONTAINER_MultiHashMap *addresses,
1051                                                                                 struct ATS_Address *address,
1052                                                                                 uint32_t network)
1053 {
1054   struct GAS_MLP_Handle *mlp = solver;
1055   struct ATS_Peer *p;
1056   struct MLP_information *mlpi;
1057   int c1;
1058   int c2;
1059
1060   GNUNET_assert (NULL != solver);
1061   GNUNET_assert (NULL != addresses);
1062   GNUNET_assert (NULL != address);
1063
1064
1065   if (NULL == address->solver_information)
1066   {
1067                 address->solver_information = GNUNET_malloc (sizeof (struct MLP_information));
1068                 mlpi = address->solver_information;
1069           for (c1 = 0; c1 < mlp->pv.m_q; c1++)
1070           {
1071                 mlpi->q_averaged[c1] = DEFAULT_QUALITY;
1072                 for (c2 = 0; c2 < MLP_AVERAGING_QUEUE_LENGTH; c2++)
1073                         mlpi->q[c1][c2] = MLP_NaN;
1074           }
1075   }
1076   else
1077       LOG (GNUNET_ERROR_TYPE_ERROR, _("Adding address for peer `%s' multiple times\n"), GNUNET_i2s(&address->peer));
1078
1079   /* Is this peer included in the problem? */
1080   if (NULL == (p = GNUNET_CONTAINER_multihashmap_get (mlp->peers, &address->peer.hashPubKey)))
1081   {
1082     LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding address for peer `%s' without address request \n", GNUNET_i2s(&address->peer));
1083         return;
1084   }
1085
1086         LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding address for peer `%s' with address request \n", GNUNET_i2s(&address->peer));
1087         /* Problem size changed: new address for peer with pending request */
1088         mlp->mlp_prob_changed = GNUNET_YES;
1089         if (GNUNET_YES == mlp->mlp_auto_solve)
1090                 GAS_mlp_solve_problem (solver, addresses);
1091 }
1092
1093
1094 static void
1095 mlp_update_quality (struct GAS_MLP_Handle *mlp,
1096                 struct GNUNET_CONTAINER_MultiHashMap *addresses,
1097                 struct ATS_Address * address,
1098                 const struct GNUNET_ATS_Information *ats_prev, uint32_t ats_prev_count)
1099 {
1100   struct MLP_information *mlpi = address->solver_information;
1101   unsigned int c_ats_entry;
1102   unsigned int c_queue_entries;
1103   unsigned int c_cmp;
1104   unsigned int c_queue_it;
1105   unsigned int c_row;
1106   unsigned int c_qual;
1107   unsigned int c_net;
1108   int qual_changed;
1109   int type_index;
1110   int avg_index;
1111   uint32_t type;
1112   uint32_t prev_value;
1113   uint32_t new_value;
1114   double avg;
1115   double *queue;
1116   int rows;
1117   double *val;
1118   int *ind;
1119
1120
1121         LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating %u quality metrics for peer `%s'\n",
1122       ats_prev_count, GNUNET_i2s (&address->peer));
1123
1124         GNUNET_assert (NULL != mlp);
1125   GNUNET_assert (NULL != address);
1126   GNUNET_assert (NULL != address->solver_information);
1127   GNUNET_assert (NULL != ats_prev);
1128
1129   if (NULL == mlp->p.prob)
1130         return;
1131
1132   qual_changed = GNUNET_NO;
1133   for (c_ats_entry = 0; c_ats_entry < ats_prev_count; c_ats_entry++)
1134   {
1135                 type = ntohl (ats_prev[c_ats_entry].type);
1136                 prev_value = ntohl (ats_prev[c_ats_entry].value);
1137                 type_index = -1;
1138                 avg_index = -1;
1139
1140                 /* Check for network update */
1141                 if (type == GNUNET_ATS_NETWORK_TYPE)
1142                 {
1143                                 new_value = get_performance_info (address, GNUNET_ATS_NETWORK_TYPE);
1144                         if (GNUNET_ATS_VALUE_UNDEFINED == new_value)
1145                                 new_value = GNUNET_ATS_NET_UNSPECIFIED;
1146                                 if (new_value != prev_value)
1147                                 {
1148                                 LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating network for peer `%s' from `%s' to `%s'\n",
1149                               GNUNET_i2s (&address->peer),
1150                               GNUNET_ATS_print_network_type(prev_value),
1151                               GNUNET_ATS_print_network_type(new_value));
1152                                 }
1153
1154                                 if (mlpi->c_b == MLP_UNDEFINED)
1155                                         continue; /* This address is not yet in the matrix*/
1156
1157                           rows = glp_get_num_rows(mlp->p.prob);
1158                           ind = GNUNET_malloc (rows * sizeof (int) + 1);
1159                           val = GNUNET_malloc (rows * sizeof (double) + 1);
1160                           int length = glp_get_mat_col (mlp->p.prob, mlpi->c_b, ind, val);
1161
1162                           for (c_net = 0; c_net <= length + 1; c_net ++)
1163                           {
1164                                 if (ind[c_net] == mlp->p.r_quota[prev_value])
1165                                         break; /* Found index for old network */
1166                           }
1167                           val[c_net] = 0.0;
1168                                 glp_set_mat_col (mlp->p.prob, mlpi->c_b, length, ind, val);
1169                                 /* Set updated column */
1170                                 ind[c_net] = mlp->p.r_quota[new_value];
1171                                 val[c_net] = 1.0;
1172                                 glp_set_mat_col (mlp->p.prob, mlpi->c_b, length, ind, val);
1173                           GNUNET_free (ind);
1174                           GNUNET_free (val);
1175
1176                           rows = glp_get_num_rows(mlp->p.prob);
1177                           ind = GNUNET_malloc (rows * sizeof (int) + 1);
1178                           val = GNUNET_malloc (rows * sizeof (double) + 1);
1179                           length = glp_get_mat_col (mlp->p.prob, mlpi->c_b, ind, val);
1180
1181                           for (c_net = 0; c_net <= length + 1; c_net ++)
1182                           {
1183                                 if (ind[c_net] == mlp->p.r_quota[prev_value])
1184                                         LOG (GNUNET_ERROR_TYPE_DEBUG, "Removing old network index [%u] == [%f]\n",ind[c_net],val[c_net]);
1185                                 if (ind[c_net] == mlp->p.r_quota[new_value])
1186                                 {
1187                                         LOG (GNUNET_ERROR_TYPE_DEBUG, "Setting new network index [%u] == [%f]\n",ind[c_net],val[c_net]);
1188                                         break;
1189                                 }
1190                           }
1191                           GNUNET_free (ind);
1192                           GNUNET_free (val);
1193                           mlp->mlp_prob_changed = GNUNET_YES;
1194                                 continue;
1195                 }
1196
1197
1198                 /* Find index for this ATS type */
1199           for (c_cmp = 0; c_cmp < mlp->pv.m_q; c_cmp++)
1200           {
1201             if (type == mlp->pv.q[c_cmp])
1202             {
1203                 type_index = c_cmp;
1204               break;
1205             }
1206           }
1207           if (-1 == type_index)
1208                 continue; /* quality index not found */
1209
1210           /* Get average queue index */
1211           avg_index = mlpi->q_avg_i[type_index];
1212
1213           /* Update averaging queue */
1214           new_value = get_performance_info (address, type);
1215       LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating peer `%s': `%s' from %u to %u\n",
1216         GNUNET_i2s (&address->peer),
1217         mlp_ats_to_string(mlp->pv.q[type_index]), prev_value, new_value);
1218           GNUNET_assert (GNUNET_ATS_VALUE_UNDEFINED != new_value);
1219           mlpi->q[type_index][avg_index] = new_value;
1220
1221           /* Update averaging index */
1222       if (mlpi->q_avg_i[type_index] + 1 < (MLP_AVERAGING_QUEUE_LENGTH))
1223         mlpi->q_avg_i[type_index] ++;
1224       else
1225         mlpi->q_avg_i[type_index] = 0;
1226
1227           /* Update average depending on ATS type */
1228       switch (type)
1229       {
1230         case GNUNET_ATS_QUALITY_NET_DISTANCE:
1231         case GNUNET_ATS_QUALITY_NET_DELAY:
1232                 c_queue_entries = 0;
1233                 avg = 0;
1234           for (c_queue_it = 0; c_queue_it < MLP_AVERAGING_QUEUE_LENGTH; c_queue_it++)
1235           {
1236             if (mlpi->q[type_index][c_queue_it] != MLP_NaN)
1237             {
1238               queue = mlpi->q[type_index] ;
1239               avg += queue[c_queue_it];
1240               c_queue_entries ++;
1241             }
1242           }
1243           if ((c_queue_entries > 0) && (avg > 0))
1244             /* avg = 1 / ((q[0] + ... + q[l]) /c3) => c3 / avg*/
1245             mlpi->q_averaged[type_index] = (double) c_queue_entries / avg;
1246           else
1247             mlpi->q_averaged[type_index] = 0.0;
1248
1249           LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating peer `%s': `%s' average sum of %u elements == %f, average == %f, weight == %f\n",
1250             GNUNET_i2s (&address->peer),
1251             mlp_ats_to_string(mlp->pv.q[type_index]),
1252             c_queue_entries,
1253             avg,
1254             avg / (double) c_queue_entries,
1255             mlpi->q_averaged[type_index]);
1256           qual_changed = GNUNET_YES;
1257                 break;
1258         default:
1259                 GNUNET_break (0);
1260                 LOG (GNUNET_ERROR_TYPE_DEBUG, _("Update for ATS type `%s' not implemented!\n"),
1261                                 mlp_ats_to_string(type));
1262       }
1263   }
1264
1265   /* Changed, but quality will be automatically set during rebuild */
1266   if ((GNUNET_YES == mlp->mlp_prob_changed) &&
1267           (GNUNET_YES == mlp->mlp_auto_solve))
1268   {
1269                 GAS_mlp_solve_problem (mlp, addresses);
1270                 return;
1271   }
1272
1273   /* Update problem matrix if required */
1274   if (GNUNET_NO == qual_changed)
1275         return;
1276
1277   /* Address not yet included in matrix */
1278   if (MLP_UNDEFINED == mlpi->c_b)
1279         return;
1280
1281   /* Update c7) [r_q[index]][c_b] = f_q * q_averaged[type_index]
1282    * Get column mlpi->c_b */
1283   rows = glp_get_num_rows(mlp->p.prob);
1284   ind = GNUNET_malloc (rows * sizeof (int) + 1);
1285   val = GNUNET_malloc (rows * sizeof (double) + 1);
1286   int length = glp_get_mat_col (mlp->p.prob, mlpi->c_b, ind, val);
1287
1288         for (c_qual = 0; c_qual < mlp->pv.m_q; c_qual++)
1289         {
1290                 for (c_row = 0; c_row <= length; c_row ++)
1291                 {
1292                                 if (ind[c_row] == mlp->p.r_q[c_qual])
1293                                         val[c_row] = mlpi->q_averaged[c_qual];
1294                 }
1295         }
1296         /* Set updated column */
1297         glp_set_mat_col (mlp->p.prob, mlpi->c_b, length, ind, val);
1298   GNUNET_free (ind);
1299   GNUNET_free (val);
1300   mlp->mlp_prob_updated = GNUNET_YES;
1301 }
1302
1303 /**
1304  * Updates a single address in the MLP problem
1305  *
1306  * If the address did not exist before in the problem:
1307  * The MLP problem has to be recreated and the problem has to be resolved
1308  *
1309  * ATS performance information in address are already updated, delta + previous
1310  * values are included in atsi_prev (value GNUNET_ATS_VALUE_UNDEFINED if not existing before)
1311  *
1312  * Otherwise the addresses' values can be updated and the existing base can
1313  * be reused
1314  *
1315  * @param solver the solver Handle
1316  * @param addresses the address hashmap containing all addresses
1317  * @param address the update address
1318  * @param prev_session the new session (if changed otherwise current)
1319  * @param prev_in_use the new address in use state (if changed otherwise current)
1320  * @param prev_atsi ATS information updated + previous values, GNUNET_ATS_VALUE_UNDEFINED if not existing before
1321  * @param prev_atsi_count number of atsi values updated
1322  */
1323 void
1324 GAS_mlp_address_update (void *solver,
1325                         struct GNUNET_CONTAINER_MultiHashMap *addresses,
1326                         struct ATS_Address *address,
1327                         uint32_t prev_session,
1328                         int prev_in_use,
1329                         const struct GNUNET_ATS_Information *prev_atsi,
1330                         uint32_t prev_atsi_count)
1331 {
1332         struct ATS_Peer *p;
1333         struct GAS_MLP_Handle *mlp = solver;
1334         struct MLP_information *mlpi = address->solver_information;
1335
1336         GNUNET_assert (NULL != solver);
1337         GNUNET_assert (NULL != addresses);
1338         GNUNET_assert (NULL != address);
1339         GNUNET_assert ((NULL != prev_atsi) || (0 == prev_atsi_count));
1340
1341   if (NULL == mlpi)
1342   {
1343       LOG (GNUNET_ERROR_TYPE_ERROR, _("Updating address for peer `%s' not added before\n"), GNUNET_i2s(&address->peer));
1344       return;
1345   }
1346         mlp_update_quality (mlp, addresses, address, prev_atsi, prev_atsi_count);
1347
1348   /* Is this peer included in the problem? */
1349   if (NULL == (p = GNUNET_CONTAINER_multihashmap_get (mlp->peers, &address->peer.hashPubKey)))
1350   {
1351     LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating address for peer `%s' without address request \n", GNUNET_i2s(&address->peer));
1352         return;
1353   }
1354         LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating address for peer `%s' with address request \n", GNUNET_i2s(&address->peer));
1355
1356         /* Problem size changed: new address for peer with pending request */
1357         mlp->mlp_prob_updated = GNUNET_YES;
1358         if (GNUNET_YES == mlp->mlp_auto_solve)
1359                 GAS_mlp_solve_problem (solver, addresses);
1360   return;
1361 }
1362
1363 /**
1364  * Deletes a single address in the MLP problem
1365  *
1366  * The MLP problem has to be recreated and the problem has to be resolved
1367  *
1368  * @param solver the MLP Handle
1369  * @param addresses the address hashmap
1370  *        the address has to be already removed from the hashmap
1371  * @param address the address to delete
1372  * @param session_only delete only session not whole address
1373  */
1374 void
1375 GAS_mlp_address_delete (void *solver,
1376     struct GNUNET_CONTAINER_MultiHashMap * addresses,
1377     struct ATS_Address *address,
1378     int session_only)
1379 {
1380         struct ATS_Peer *p;
1381         struct GAS_MLP_Handle *mlp = solver;
1382         struct MLP_information *mlpi;
1383
1384         GNUNET_assert (NULL != solver);
1385         GNUNET_assert (NULL != addresses);
1386         GNUNET_assert (NULL != address);
1387
1388         mlpi = address->solver_information;
1389
1390         if (NULL != mlpi)
1391         {
1392                         GNUNET_free (mlpi);
1393                         address->solver_information = NULL;
1394         }
1395
1396   /* Is this peer included in the problem? */
1397   if (NULL == (p = GNUNET_CONTAINER_multihashmap_get (mlp->peers, &address->peer.hashPubKey)))
1398   {
1399     LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting address for peer `%s' without address request \n", GNUNET_i2s(&address->peer));
1400         return;
1401   }
1402         LOG (GNUNET_ERROR_TYPE_DEBUG, "Deleting address for peer `%s' with address request \n", GNUNET_i2s(&address->peer));
1403
1404         /* Problem size changed: new address for peer with pending request */
1405         mlp->mlp_prob_changed = GNUNET_YES;
1406         if (GNUNET_YES == mlp->mlp_auto_solve)
1407                 GAS_mlp_solve_problem (solver, addresses);
1408   return;
1409 }
1410
1411
1412 /**
1413  * Find the active address in the set of addresses of a peer
1414  * @param cls destination
1415  * @param key peer id
1416  * @param value address
1417  * @return GNUNET_OK
1418  */
1419 static int
1420 mlp_get_preferred_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1421 {
1422
1423   struct ATS_Address *aa = (struct ATS_Address *) cls;
1424   struct ATS_Address *addr = value;
1425   struct MLP_information *mlpi = addr->solver_information;
1426   if (mlpi == NULL)
1427     return GNUNET_YES;
1428   if (mlpi->n == GNUNET_YES)
1429   {
1430     aa = addr;
1431       aa->assigned_bw_in = mlpi->b_in;
1432       aa->assigned_bw_out = mlpi->b_out;
1433     return GNUNET_NO;
1434   }
1435   return GNUNET_YES;
1436 }
1437
1438
1439 static double get_peer_pref_value (struct GAS_MLP_Handle *mlp, const struct GNUNET_PeerIdentity *peer)
1440 {
1441         double res;
1442   const double *preferences = NULL;
1443   int c;
1444   preferences = mlp->get_preferences (mlp->get_preferences_cls, peer);
1445
1446   res = 0.0;
1447         for (c = 0; c < GNUNET_ATS_PreferenceCount; c++)
1448         {
1449                 if (c != GNUNET_ATS_PREFERENCE_END)
1450                 {
1451                         //fprintf (stderr, "VALUE[%u] %s %.3f \n", c, GNUNET_i2s (&cur->addr->peer), t[c]);
1452                         res += preferences[c];
1453                 }
1454         }
1455         res /= (GNUNET_ATS_PreferenceCount -1);
1456         return res;
1457 }
1458
1459
1460 /**
1461  * Get the preferred address for a specific peer
1462  *
1463  * @param solver the MLP Handle
1464  * @param addresses address hashmap
1465  * @param peer the peer
1466  * @return suggested address
1467  */
1468 const struct ATS_Address *
1469 GAS_mlp_get_preferred_address (void *solver,
1470                                struct GNUNET_CONTAINER_MultiHashMap * addresses,
1471                                const struct GNUNET_PeerIdentity *peer)
1472 {
1473   struct GAS_MLP_Handle *mlp = solver;
1474   struct ATS_Peer *p;
1475   struct ATS_Address *res = NULL;
1476
1477   GNUNET_assert (NULL != solver);
1478   GNUNET_assert (NULL != addresses);
1479   GNUNET_assert (NULL != peer);
1480
1481   LOG (GNUNET_ERROR_TYPE_DEBUG, "Getting preferred address for `%s'\n",
1482                 GNUNET_i2s (peer));
1483
1484   /* Is this peer included in the problem? */
1485   if (NULL == (p = GNUNET_CONTAINER_multihashmap_get (mlp->peers, &peer->hashPubKey)))
1486   {
1487           LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding peer `%s' to list of peers with requests\n",
1488                         GNUNET_i2s (peer));
1489
1490           p = GNUNET_malloc (sizeof (struct ATS_Peer));
1491           p->id = (*peer);
1492           p->f = get_peer_pref_value (mlp, peer);
1493           GNUNET_CONTAINER_multihashmap_put (mlp->peers, &peer->hashPubKey, p, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1494
1495           /* Added new peer, we have to rebuild problem before solving */
1496           mlp->mlp_prob_changed = GNUNET_YES;
1497   }
1498   if (GNUNET_YES == mlp->mlp_auto_solve)
1499         GAS_mlp_solve_problem (mlp, addresses);
1500
1501   /* Get prefered address */
1502   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
1503                                                                                                                                                                                 mlp_get_preferred_address_it, res);
1504
1505   return res;
1506 }
1507
1508
1509 /**
1510  * Stop notifying about address and bandwidth changes for this peer
1511  *
1512  * @param solver the MLP handle
1513  * @param addresses address hashmap
1514  * @param peer the peer
1515  */
1516 void
1517 GAS_mlp_stop_get_preferred_address (void *solver,
1518                                      struct GNUNET_CONTAINER_MultiHashMap *addresses,
1519                                      const struct GNUNET_PeerIdentity *peer)
1520 {
1521   struct GAS_MLP_Handle *mlp = solver;
1522   struct ATS_Peer *p = NULL;
1523
1524   GNUNET_assert (NULL != solver);
1525   GNUNET_assert (NULL != addresses);
1526   GNUNET_assert (NULL != peer);
1527
1528   if (NULL != (p = GNUNET_CONTAINER_multihashmap_get (mlp->peers, &peer->hashPubKey)))
1529   {
1530         GNUNET_CONTAINER_multihashmap_remove (mlp->peers, &peer->hashPubKey, p);
1531         GNUNET_free (p);
1532   }
1533 }
1534
1535
1536 /**
1537  * Changes the preferences for a peer in the MLP problem
1538  *
1539  * @param solver the MLP Handle
1540  * @param addresses the address hashmap
1541  * @param peer the peer
1542  * @param kind the kind to change the preference
1543  * @param pref_rel the relative score
1544  */
1545 void
1546 GAS_mlp_address_change_preference (void *solver,
1547                                                                    struct GNUNET_CONTAINER_MultiHashMap *addresses,
1548                                                                    const struct GNUNET_PeerIdentity *peer,
1549                                                                    enum GNUNET_ATS_PreferenceKind kind,
1550                                                                    double pref_rel)
1551 {
1552   struct GAS_MLP_Handle *mlp = solver;
1553   struct ATS_Peer *p = NULL;
1554
1555   LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing preference for address for peer `%s'\n",
1556                 GNUNET_i2s(peer));
1557
1558   GNUNET_STATISTICS_update (mlp->stats,"# LP address preference changes", 1, GNUNET_NO);
1559
1560   /* Update the constraints with changed preferences */
1561
1562
1563   /* Update quality constraint c7 */
1564
1565   /* Update relativity constraint c9 */
1566   if (NULL == (p = GNUNET_CONTAINER_multihashmap_get (mlp->peers, &peer->hashPubKey)))
1567   {
1568     LOG (GNUNET_ERROR_TYPE_ERROR, "Updating preference for unknown peer `%s' \n", GNUNET_i2s(peer));
1569         return;
1570   }
1571   p->f = get_peer_pref_value (mlp, peer);
1572   mlp_create_problem_set_value (&mlp->p, p->r_c9, mlp->p.c_r, -p->f, __LINE__);
1573
1574
1575         /* Problem size changed: new address for peer with pending request */
1576         mlp->mlp_prob_updated = GNUNET_YES;
1577         if (GNUNET_YES == mlp->mlp_auto_solve)
1578                 GAS_mlp_solve_problem (solver, addresses);
1579   return;
1580 }
1581
1582
1583 static int
1584 mlp_free_peers (void *cls, const struct GNUNET_HashCode *key, void *value)
1585 {
1586         struct GNUNET_CONTAINER_MultiHashMap *map = cls;
1587         struct ATS_Peer *p = value;
1588
1589         GNUNET_CONTAINER_multihashmap_remove (map, key, value);
1590         GNUNET_free (p);
1591
1592         return GNUNET_OK;
1593 }
1594
1595
1596 /**
1597  * Shutdown the MLP problem solving component
1598  *
1599  * @param solver the solver handle
1600  */
1601 void
1602 GAS_mlp_done (void *solver)
1603 {
1604   struct GAS_MLP_Handle *mlp = solver;
1605   GNUNET_assert (mlp != NULL);
1606
1607   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down mlp solver\n");
1608   mlp_delete_problem (mlp);
1609
1610   GNUNET_CONTAINER_multihashmap_iterate (mlp->peers, &mlp_free_peers, mlp->peers);
1611   GNUNET_CONTAINER_multihashmap_destroy (mlp->peers);
1612   mlp->peers = NULL;
1613
1614   /* Clean up GLPK environment */
1615   glp_free_env();
1616   GNUNET_free (mlp);
1617
1618   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutdown down of mlp solver complete\n");
1619 }
1620
1621
1622 /**
1623  * Init the MLP problem solving component
1624  *
1625  * @param cfg the GNUNET_CONFIGURATION_Handle handle
1626  * @param stats the GNUNET_STATISTICS handle
1627  * @param network array of GNUNET_ATS_NetworkType with length dest_length
1628  * @param out_dest array of outbound quotas
1629  * @param in_dest array of outbound quota
1630  * @param dest_length array length for quota arrays
1631  * @param bw_changed_cb callback for changed bandwidth amounts
1632  * @param bw_changed_cb_cls cls for callback
1633  * @param get_preference callback to get relative preferences for a peer
1634  * @param get_preference_cls cls for callback to get relative preferences
1635  * @return struct GAS_MLP_Handle on success, NULL on fail
1636  */
1637 void *
1638 GAS_mlp_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1639               const struct GNUNET_STATISTICS_Handle *stats,
1640               int *network,
1641               unsigned long long *out_dest,
1642               unsigned long long *in_dest,
1643               int dest_length,
1644               GAS_bandwidth_changed_cb bw_changed_cb,
1645               void *bw_changed_cb_cls,
1646               GAS_get_preferences get_preference,
1647               void *get_preference_cls)
1648 {
1649   struct GAS_MLP_Handle * mlp = GNUNET_malloc (sizeof (struct GAS_MLP_Handle));
1650
1651   double D;
1652   double R;
1653   double U;
1654   unsigned long long tmp;
1655   unsigned int b_min;
1656   unsigned int n_min;
1657   int c;
1658   int c2;
1659   int found;
1660
1661   struct GNUNET_TIME_Relative max_duration;
1662   long long unsigned int max_iterations;
1663
1664   /* Init GLPK environment */
1665   int res = glp_init_env();
1666   switch (res) {
1667     case 0:
1668         LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
1669           "initialization successful");
1670       break;
1671     case 1:
1672         LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
1673           "environment is already initialized");
1674       break;
1675     case 2:
1676         LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
1677           "initialization failed (insufficient memory)");
1678       GNUNET_free(mlp);
1679       return NULL;
1680       break;
1681     case 3:
1682         LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
1683           "initialization failed (unsupported programming model)");
1684       GNUNET_free(mlp);
1685       return NULL;
1686       break;
1687     default:
1688       break;
1689   }
1690
1691
1692   mlp->pv.BIG_M = (double) BIG_M_VALUE;
1693
1694   /* Get timeout for iterations */
1695   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(cfg, "ats", "MLP_MAX_DURATION", &max_duration))
1696   {
1697     max_duration = MLP_MAX_EXEC_DURATION;
1698   }
1699
1700   /* Get maximum number of iterations */
1701   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_size(cfg, "ats", "MLP_MAX_ITERATIONS", &max_iterations))
1702   {
1703     max_iterations = MLP_MAX_ITERATIONS;
1704   }
1705
1706   /* Get diversity coefficient from configuration */
1707   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1708                                                       "MLP_COEFFICIENT_D",
1709                                                       &tmp))
1710     D = (double) tmp / 100;
1711   else
1712     D = DEFAULT_D;
1713
1714   /* Get proportionality coefficient from configuration */
1715   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1716                                                       "MLP_COEFFICIENT_R",
1717                                                       &tmp))
1718     R = (double) tmp / 100;
1719   else
1720     R = DEFAULT_R;
1721
1722   /* Get utilization coefficient from configuration */
1723   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1724                                                       "MLP_COEFFICIENT_U",
1725                                                       &tmp))
1726     U = (double) tmp / 100;
1727   else
1728     U = DEFAULT_U;
1729
1730   /* Get quality metric coefficients from configuration */
1731   int i_delay = MLP_NaN;
1732   int i_distance = MLP_NaN;
1733   int q[GNUNET_ATS_QualityPropertiesCount] = GNUNET_ATS_QualityProperties;
1734   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
1735   {
1736     /* initialize quality coefficients with default value 1.0 */
1737                 mlp->pv.co_Q[c] = DEFAULT_QUALITY;
1738
1739     mlp->pv.q[c] = q[c];
1740     if (q[c] == GNUNET_ATS_QUALITY_NET_DELAY)
1741       i_delay = c;
1742     if (q[c] == GNUNET_ATS_QUALITY_NET_DISTANCE)
1743       i_distance = c;
1744   }
1745
1746   if ((i_delay != MLP_NaN) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1747                                                       "MLP_COEFFICIENT_QUALITY_DELAY",
1748                                                       &tmp)))
1749
1750         mlp->pv.co_Q[i_delay] = (double) tmp / 100;
1751   else
1752         mlp->pv.co_Q[i_delay] = DEFAULT_QUALITY;
1753
1754   if ((i_distance != MLP_NaN) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1755                                                       "MLP_COEFFICIENT_QUALITY_DISTANCE",
1756                                                       &tmp)))
1757         mlp->pv.co_Q[i_distance] = (double) tmp / 100;
1758   else
1759         mlp->pv.co_Q[i_distance] = DEFAULT_QUALITY;
1760
1761   /* Get minimum bandwidth per used address from configuration */
1762   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1763                                                       "MLP_MIN_BANDWIDTH",
1764                                                       &tmp))
1765     b_min = tmp;
1766   else
1767   {
1768     b_min = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1769   }
1770
1771   /* Get minimum number of connections from configuration */
1772   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1773                                                       "MLP_MIN_CONNECTIONS",
1774                                                       &tmp))
1775     n_min = tmp;
1776   else
1777     n_min = DEFAULT_MIN_CONNECTIONS;
1778
1779   /* Init network quotas */
1780   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
1781   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
1782   {
1783                 found = GNUNET_NO;
1784           for (c2 = 0; c2 < dest_length; c2++)
1785           {
1786                         if (quotas[c] == network[c2])
1787                   {
1788                                         mlp->pv.quota_index[c] = network[c2];
1789                                         mlp->pv.quota_out[c] = out_dest[c2];
1790                       mlp->pv.quota_in[c] = in_dest[c2];
1791                       found = GNUNET_YES;
1792                       LOG (GNUNET_ERROR_TYPE_DEBUG, "Quota for network `%s' (in/out) %llu/%llu\n",
1793                                                                 GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
1794                                                                 mlp->pv.quota_out[c],
1795                                                                 mlp->pv.quota_in[c]);
1796                       break;
1797                   }
1798           }
1799
1800       /* Check if defined quota could make problem unsolvable */
1801       if ((n_min * b_min) > mlp->pv.quota_out[c])
1802       {
1803         LOG (GNUNET_ERROR_TYPE_INFO, _("Adjusting inconsistent outbound quota configuration for network `%s', is %llu must be at least %llu\n"),
1804                         GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
1805                         mlp->pv.quota_out[c],
1806                         (n_min * b_min));
1807         mlp->pv.quota_out[c] = (n_min * b_min);
1808       }
1809       if ((n_min * b_min) > mlp->pv.quota_in[c])
1810       {
1811         LOG (GNUNET_ERROR_TYPE_INFO, _("Adjusting inconsistent inbound quota configuration for network `%s', is %llu must be at least %llu\n"),
1812                         GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
1813                         mlp->pv.quota_in[c],
1814                         (n_min * b_min));
1815         mlp->pv.quota_in[c] = (n_min * b_min);
1816       }
1817
1818       /* Check if bandwidth is too big to make problem solvable */
1819       if (mlp->pv.BIG_M < mlp->pv.quota_out[c])
1820       {
1821         LOG (GNUNET_ERROR_TYPE_INFO, _("Adjusting outbound quota configuration for network `%s'from %llu to %.0f\n"),
1822                         GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
1823                         mlp->pv.quota_out[c],
1824                         mlp->pv.BIG_M);
1825         mlp->pv.quota_out[c] = mlp->pv.BIG_M ;
1826       }
1827       if (mlp->pv.BIG_M < mlp->pv.quota_in[c])
1828       {
1829         LOG (GNUNET_ERROR_TYPE_INFO, _("Adjusting inbound quota configuration for network `%s' from %llu to %.0f\n"),
1830                         GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
1831                         mlp->pv.quota_in[c],
1832                         mlp->pv.BIG_M);
1833         mlp->pv.quota_in[c] = mlp->pv.BIG_M ;
1834       }
1835
1836           if (GNUNET_NO == found)
1837                         {
1838                 mlp->pv.quota_in[c] = ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1839                 mlp->pv.quota_out[c] = ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1840                                 LOG (GNUNET_ERROR_TYPE_INFO, _("Using default quota configuration for network `%s' (in/out) %llu/%llu\n"),
1841                                                 GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
1842                                                 mlp->pv.quota_in[c],
1843                                                 mlp->pv.quota_out[c]);
1844                         }
1845   }
1846
1847   /* Assign options to handle */
1848   mlp->stats = (struct GNUNET_STATISTICS_Handle *) stats;
1849   mlp->bw_changed_cb = bw_changed_cb;
1850   mlp->bw_changed_cb_cls = bw_changed_cb_cls;
1851   mlp->get_preferences = get_preference;
1852   mlp->get_preferences_cls = get_preference_cls;
1853   /* Setting MLP Input variables */
1854   mlp->pv.co_D = D;
1855   mlp->pv.co_R = R;
1856   mlp->pv.co_U = U;
1857   mlp->pv.b_min = b_min;
1858   mlp->pv.n_min = n_min;
1859   mlp->pv.m_q = GNUNET_ATS_QualityPropertiesCount;
1860   mlp->write_mip_mps = GNUNET_NO;
1861   mlp->write_mip_sol = GNUNET_NO;
1862   mlp->mlp_prob_changed = GNUNET_NO;
1863   mlp->mlp_prob_updated = GNUNET_NO;
1864   mlp->mlp_auto_solve = GNUNET_YES;
1865   mlp->peers = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
1866
1867   /* Setup GLPK */
1868   /* Redirect GLPK output to GNUnet logging */
1869   glp_term_hook (&mlp_term_hook, (void *) mlp);
1870
1871   /* Init LP solving parameters */
1872   glp_init_smcp(&mlp->control_param_lp);
1873   mlp->control_param_lp.msg_lev = GLP_MSG_OFF;
1874 #if VERBOSE_GLPK
1875   mlp->control_param_lp.msg_lev = GLP_MSG_ALL;
1876 #endif
1877   mlp->control_param_lp.it_lim = max_iterations;
1878   mlp->control_param_lp.tm_lim = max_duration.rel_value;
1879
1880   /* Init MLP solving parameters */
1881   glp_init_iocp(&mlp->control_param_mlp);
1882   mlp->control_param_mlp.msg_lev = GLP_MSG_OFF;
1883 #if VERBOSE_GLPK
1884   mlp->control_param_mlp.msg_lev = GLP_MSG_ALL;
1885 #endif
1886   mlp->control_param_mlp.tm_lim = max_duration.rel_value;
1887
1888   LOG (GNUNET_ERROR_TYPE_DEBUG, "solver ready\n");
1889
1890   return mlp;
1891 }
1892
1893 /* end of gnunet-service-ats_addresses_mlp.c */