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