guix-env: some update.
[oweals/gnunet.git] / src / ats / plugin_ats_mlp.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011-2014 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file ats/plugin_ats_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_ats_service.h"
30 #include "gnunet_ats_plugin.h"
31 #include "gnunet-service-ats_addresses.h"
32 #include "gnunet_statistics_service.h"
33 #include <float.h>
34 #include <glpk.h>
35
36
37 #define BIG_M_VALUE (UINT32_MAX) /10
38 #define BIG_M_STRING "unlimited"
39
40 #define MLP_AVERAGING_QUEUE_LENGTH 3
41
42 #define MLP_MAX_EXEC_DURATION   GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10)
43 #define MLP_MAX_ITERATIONS      4096
44
45 #define MLP_DEFAULT_D 1.0
46 #define MLP_DEFAULT_R 1.0
47 #define MLP_DEFAULT_U 1.0
48 #define MLP_DEFAULT_QUALITY 1.0
49 #define MLP_DEFAULT_MIN_CONNECTIONS 4
50 #define MLP_DEFAULT_PEER_PREFERENCE 1.0
51
52 #define MLP_NaN -1
53 #define MLP_UNDEFINED 0
54 #define GLP_YES 1.0
55 #define GLP_NO  0.0
56
57 enum MLP_Output_Format
58 {
59   MLP_MPS,
60   MLP_CPLEX,
61   MLP_GLPK
62 };
63
64
65 enum QualityMetrics
66 {
67   RQ_QUALITY_METRIC_DELAY = 0,
68   RQ_QUALITY_METRIC_DISTANCE = 1,
69   RQ_QUALITY_METRIC_COUNT = 2
70 };
71
72
73 static const char *
74 print_quality_type (enum QualityMetrics qm)
75 {
76   switch (qm){
77   case RQ_QUALITY_METRIC_DELAY:
78     return "delay";
79   case RQ_QUALITY_METRIC_DISTANCE:
80     return "distance";
81   default:
82     GNUNET_break (0);
83     return NULL;
84   }
85 }
86
87
88 struct MLP_Solution
89 {
90   int lp_res;
91   int lp_presolv;
92   int mip_res;
93   int mip_presolv;
94
95   double lp_objective_value;
96   double mlp_objective_value;
97   double mlp_gap;
98   double lp_mlp_gap;
99
100   int p_elements;
101   int p_cols;
102   int p_rows;
103
104   int n_peers;
105   int n_addresses;
106
107 };
108
109 struct ATS_Peer
110 {
111   struct GNUNET_PeerIdentity id;
112
113   /* Was this peer already added to the current problem? */
114   int processed;
115
116   /* constraint 2: 1 address per peer*/
117   unsigned int r_c2;
118
119   /* constraint 9: relativity */
120   unsigned int r_c9;
121
122   /* Legacy preference value */
123   double f;
124 };
125
126 struct MLP_Problem
127 {
128   /**
129    * GLPK (MLP) problem object
130    */
131   glp_prob *prob;
132
133   /* Number of addresses in problem */
134   unsigned int num_addresses;
135   /* Number of peers in problem */
136   unsigned int num_peers;
137   /* Number of elements in problem matrix */
138   unsigned int num_elements;
139
140   /* Row index constraint 2: */
141   unsigned int r_c2;
142   /* Row index constraint 4: minimum connections */
143   unsigned int r_c4;
144   /* Row index constraint 6: maximize diversity */
145   unsigned int r_c6;
146   /* Row index constraint 8: utilization*/
147   unsigned int r_c8;
148   /* Row index constraint 9: relativity*/
149   unsigned int r_c9;
150   /* Row indices quality metrics  */
151   int r_q[RQ_QUALITY_METRIC_COUNT];
152   /* Row indices ATS network quotas */
153   int r_quota[GNUNET_ATS_NetworkTypeCount];
154
155   /* Column index Diversity (D) column */
156   int c_d;
157   /* Column index Utilization (U) column */
158   int c_u;
159   /* Column index Proportionality (R) column */
160   int c_r;
161   /* Column index quality metrics  */
162   int c_q[RQ_QUALITY_METRIC_COUNT];
163
164   /* Problem matrix */
165   /* Current index */
166   unsigned int ci;
167   /* Row index array */
168   int *ia;
169   /* Column index array */
170   int *ja;
171   /* Column index value */
172   double *ar;
173
174 };
175
176 struct MLP_Variables
177 {
178   /* Big M value for bandwidth capping */
179   double BIG_M;
180
181   /* MIP Gap */
182   double mip_gap;
183
184   /* LP MIP Gap */
185   double lp_mip_gap;
186
187   /* Number of quality metrics @deprecated, use RQ_QUALITY_METRIC_COUNT */
188   int m_q;
189
190   /* Number of quality metrics */
191   int m_rc;
192
193   /* Quality metric coefficients*/
194   double co_Q[RQ_QUALITY_METRIC_COUNT];
195
196   /* Ressource costs coefficients*/
197   double co_RC[RQ_QUALITY_METRIC_COUNT];
198
199   /* Diversity coefficient */
200   double co_D;
201
202   /* Utility coefficient */
203   double co_U;
204
205   /* Relativity coefficient */
206   double co_R;
207
208   /* Minimum bandwidth assigned to an address */
209   unsigned int b_min;
210
211   /* Minimum number of addresses with bandwidth assigned */
212   unsigned int n_min;
213
214   /* Quotas */
215   /* Array mapping array index to ATS network */
216   int quota_index[GNUNET_ATS_NetworkTypeCount];
217   /* Outbound quotas */
218   unsigned long long quota_out[GNUNET_ATS_NetworkTypeCount];
219   /* Inbound quotas */
220
221   unsigned long long quota_in[GNUNET_ATS_NetworkTypeCount];
222
223   /* ATS ressource costs
224    * array with GNUNET_ATS_QualityPropertiesCount elements
225    * contains mapping to GNUNET_ATS_Property
226    * */
227   int rc[RQ_QUALITY_METRIC_COUNT];
228
229 };
230
231 /**
232  * MLP Handle
233  */
234 struct GAS_MLP_Handle
235 {
236   struct GNUNET_ATS_PluginEnvironment *env;
237
238   /**
239    * Exclude peer from next result propagation
240    */
241   const struct GNUNET_PeerIdentity *exclude_peer;
242
243   /**
244    * Encapsulation for the MLP problem
245    */
246   struct MLP_Problem p;
247
248   /**
249    * Encapsulation for the MLP problem variables
250    */
251   struct MLP_Variables pv;
252
253   /**
254    * Encapsulation for the MLP solution
255    */
256   struct MLP_Solution ps;
257
258   /**
259    * Bulk lock
260    */
261   int stat_bulk_lock;
262
263   /**
264    * Number of changes while solver was locked
265    */
266   int stat_bulk_requests;
267
268   /**
269    * GLPK LP control parameter
270    */
271   glp_smcp control_param_lp;
272
273   /**
274    * GLPK LP control parameter
275    */
276   glp_iocp control_param_mlp;
277
278   /**
279    * Peers with pending address requests
280    */
281   struct GNUNET_CONTAINER_MultiPeerMap *requested_peers;
282
283   /**
284    * Was the problem updated since last solution
285    */
286   int stat_mlp_prob_updated;
287
288   /**
289    * Has the problem size changed since last solution
290    */
291   int stat_mlp_prob_changed;
292
293   /**
294    * Solve the problem automatically when updates occur?
295    * Default: GNUNET_YES
296    * Can be disabled for test and measurements
297    */
298   int opt_mlp_auto_solve;
299
300   /**
301    * Write all MILP problems to a MPS file
302    */
303   int opt_dump_problem_all;
304
305   /**
306    * Write all MILP problem solutions to a file
307    */
308   int opt_dump_solution_all;
309
310   /**
311    * Write MILP problems to a MPS file when solver fails
312    */
313   int opt_dump_problem_on_fail;
314
315   /**
316    * Write MILP problem solutions to a file when solver fails
317    */
318   int opt_dump_solution_on_fail;
319
320   /**
321    * solve feasibility only
322    */
323   int opt_dbg_feasibility_only;
324
325   /**
326    * solve autoscale the problem
327    */
328   int opt_dbg_autoscale_problem;
329
330   /**
331    * use the intopt presolver instead of simplex
332    */
333   int opt_dbg_intopt_presolver;
334
335   /**
336    * Print GLPK output
337    */
338   int opt_dbg_glpk_verbose;
339
340   /**
341    * solve autoscale the problem
342    */
343   int opt_dbg_optimize_relativity;
344
345   /**
346    * solve autoscale the problem
347    */
348   int opt_dbg_optimize_diversity;
349
350   /**
351    * solve autoscale the problem
352    */
353   int opt_dbg_optimize_quality;
354
355   /**
356    * solve autoscale the problem
357    */
358   int opt_dbg_optimize_utility;
359
360
361   /**
362    * Output format
363    */
364   enum MLP_Output_Format opt_log_format;
365 };
366
367 /**
368  * Address specific MLP information
369  */
370 struct MLP_information
371 {
372
373   /**
374    * Bandwidth assigned outbound
375    */
376   uint32_t b_out;
377
378   /**
379    * Bandwidth assigned inbound
380    */
381   uint32_t b_in;
382
383   /**
384    * Address selected
385    */
386   int n;
387
388   /**
389    * bandwidth column index
390    */
391   signed int c_b;
392
393   /**
394    * address usage column
395    */
396   signed int c_n;
397
398   /* row indexes */
399
400   /**
401    * constraint 1: bandwidth capping
402    */
403   unsigned int r_c1;
404
405   /**
406    * constraint 3: minimum bandwidth
407    */
408   unsigned int r_c3;
409 };
410
411
412
413 /**
414  *
415  * NOTE: Do not modify this documentation. This documentation is based on
416  * gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
417  * use build_txt.sh to generate plaintext output
418  *
419  *    The MLP solver (mlp) tries to finds an optimal bandwidth assignmentby
420  *    optimizing an mixed integer programming problem. The MLP solver uses a
421  *    number of constraints to find the best adddress for a peer and an optimal
422  *    bandwidth assignment. mlp uses the GNU Linear Programming Kit to solve the
423  *    MLP problem.
424  *
425  *    We defined a constraint system to find an optimal bandwidth assignment.
426  *    This constraint system uses as an input data addresses, bandwidth quotas,
427  *    preferences and quality values. This constraint system is stored in an
428  *    matrix based equotation system.
429  *
430  *   5 Using GLPK
431  *
432  *    A (M)LP problem consists of a target function to optimizes, constraints
433  *    and rows and columns. FIXME GLP uses three arrays to index the matrix: two
434  *    integer arrays storing the row and column indices in the matrix and an
435  *    float array to store the coeeficient.
436  *
437  *    To solve the problem we first find an initial solution for the LP problem
438  *    using the LP solver and then find an MLP solution based on this solution
439  *    using the MLP solver.
440  *
441  *    Solving (M)LP problems has the property that finding an initial solution
442  *    for the LP problem is computationally expensive and finding the MLP
443  *    solution is cheaper. This is especially interesting an existing LP
444  *    solution can be reused if only coefficients in the matrix have changed
445  *    (addresses updated). Only when the problem size changes (addresses added
446  *    or deleted) a new LP solution has to be found.
447  *
448  *    Intended usage
449  *    The mlp solver solves the bandwidth assignment problem only on demand when
450  *    an address suggestion is requested. When an address is requested mlp the
451  *    solves the mlp problem and if the active address or the bandwidth assigned
452  *    changes it calls the callback to addresses. The mlp solver gets notified
453  *    about new addresses (adding sessions), removed addresses (address
454  *    deletions) and address updates. To benefit from the mlp properties
455  *    mentioned in section 5 the solver rembers if since the last solution
456  *    addresses were added or deleted (problem size changed, problem has to be
457  *    rebuild and solved from sratch) or if addresses were updated and the
458  *    existing solution can be reused.
459  *
460  *     5.1 Input data
461  *
462  *    The quotas for each network segment are passed by addresses. MLP can be
463  *    adapted using configuration settings and uses the following parameters:
464  *      * MLP_MAX_DURATION:
465  *        Maximum duration for a MLP solution procees (default: 3 sec.)
466  *      * MLP_MAX_ITERATIONS:
467  *        Maximum number of iterations for a MLP solution process (default:
468  *        1024)
469  *      * MLP_MIN_CONNECTIONS:
470  *        Minimum number of desired connections (default: 4)
471  *      * MLP_MIN_BANDWIDTH:
472  *        Minimum amount of bandwidth assigned to an address (default: 1024)
473  *      * MLP_COEFFICIENT_D:
474  *        Diversity coefficient (default: 1.0)
475  *      * MLP_COEFFICIENT_R:
476  *        Relativity coefficient (default: 1.0)
477  *      * MLP_COEFFICIENT_U:
478  *        Utilization coefficient (default: 1.0)
479  *      * MLP_COEFFICIENT_D:
480  *        Diversity coefficient (default: 1.0)
481  *      * MLP_COEFFICIENT_QUALITY_DELAY:
482  *        Quality delay coefficient (default: 1.0)
483  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
484  *        Quality distance coefficient (default: 1.0)
485  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
486  *        Quality distance coefficient (default: 1.0)
487  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
488  *        Quality distance coefficient (default: 1.0)
489  *      * MLP_COEFFICIENT_QUALITY_DISTANCE:
490  *        Quality distance coefficient (default: 1.0)
491  *
492  *     5.2 Data structures used
493  *
494  *    mlp has for each known peer a struct ATS_Peer containing information about
495  *    a specific peer. The address field solver_information contains information
496  *    about the mlp properties of this address.
497  *
498  *     5.3 Initializing
499  *
500  *    During initialization mlp initializes the GLPK libray used to solve the
501  *    MLP problem: it initializes the glpk environment and creates an initial LP
502  *    problem. Next it loads the configuration values from the configuration or
503  *    uses the default values configured in -addresses_mlp.h. The quotas used
504  *    are given by addresses but may have to be adjusted. mlp uses a upper limit
505  *    for the bandwidth assigned called BIG M and a minimum amount of bandwidth
506  *    an address gets assigned as well as a minium desired number of
507  *    connections. If the configured quota is bigger than BIG M, it is reduced
508  *    to BIG M. If the configured quota is smaller than MLP_MIN_CONNECTIONS
509  *    *MLP_MIN_BANDWIDTH it is increased to this value.
510  *
511  *     5.4 Shutdown
512
513  */
514
515 #define LOG(kind,...) GNUNET_log_from (kind, "ats-mlp",__VA_ARGS__)
516
517 /**
518  * Print debug output for mlp problem creation
519  */
520 #define DEBUG_MLP_PROBLEM_CREATION GNUNET_NO
521
522
523 /**
524  * Intercept GLPK terminal output
525  * @param info the mlp handle
526  * @param s the string to print
527  * @return 0: glpk prints output on terminal, 0 != surpress output
528  */
529 static int
530 mlp_term_hook (void *info, const char *s)
531 {
532   struct GAS_MLP_Handle *mlp = info;
533
534   if (mlp->opt_dbg_glpk_verbose)
535     LOG (GNUNET_ERROR_TYPE_ERROR, "%s", s);
536   return 1;
537 }
538
539
540 /**
541  * Reset peers for next problem creation
542  *
543  * @param cls not used
544  * @param key the key
545  * @param value ATS_Peer
546  * @return #GNUNET_OK
547  */
548 static int
549 reset_peers (void *cls,
550              const struct GNUNET_PeerIdentity *key,
551              void *value)
552  {
553    struct ATS_Peer *peer = value;
554    peer->processed = GNUNET_NO;
555    return GNUNET_OK;
556  }
557
558 /**
559  * Delete the MLP problem and free the constrain matrix
560  *
561  * @param mlp the MLP handle
562  */
563 static void
564 mlp_delete_problem (struct GAS_MLP_Handle *mlp)
565 {
566   int c;
567   if (mlp == NULL)
568     return;
569   if (mlp->p.prob != NULL)
570   {
571     glp_delete_prob(mlp->p.prob);
572     mlp->p.prob = NULL;
573   }
574
575   /* delete row index */
576   if (mlp->p.ia != NULL)
577   {
578     GNUNET_free (mlp->p.ia);
579     mlp->p.ia = NULL;
580   }
581
582   /* delete column index */
583   if (mlp->p.ja != NULL)
584   {
585     GNUNET_free (mlp->p.ja);
586     mlp->p.ja = NULL;
587   }
588
589   /* delete coefficients */
590   if (mlp->p.ar != NULL)
591   {
592     GNUNET_free (mlp->p.ar);
593     mlp->p.ar = NULL;
594   }
595   mlp->p.ci = 0;
596   mlp->p.prob = NULL;
597
598   mlp->p.c_d = MLP_UNDEFINED;
599   mlp->p.c_r = MLP_UNDEFINED;
600   mlp->p.r_c2 = MLP_UNDEFINED;
601   mlp->p.r_c4 = MLP_UNDEFINED;
602   mlp->p.r_c6 = MLP_UNDEFINED;
603   mlp->p.r_c9 = MLP_UNDEFINED;
604   for (c = 0; c < RQ_QUALITY_METRIC_COUNT ; c ++)
605     mlp->p.r_q[c] = MLP_UNDEFINED;
606   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c ++)
607     mlp->p.r_quota[c] = MLP_UNDEFINED;
608   mlp->p.ci = MLP_UNDEFINED;
609
610
611   GNUNET_CONTAINER_multipeermap_iterate (mlp->requested_peers,
612                                          &reset_peers, NULL);
613 }
614
615
616 /**
617  * Translate glpk status error codes to text
618  * @param retcode return code
619  * @return string with result
620  */
621 static const char *
622 mlp_status_to_string (int retcode)
623 {
624   switch (retcode) {
625     case GLP_UNDEF:
626       return "solution is undefined";
627     case GLP_FEAS:
628       return "solution is feasible";
629     case GLP_INFEAS:
630       return "solution is infeasible";
631     case GLP_NOFEAS:
632       return "no feasible solution exists";
633     case GLP_OPT:
634       return "solution is optimal";
635     case GLP_UNBND:
636       return "solution is unbounded";
637     default:
638       GNUNET_break (0);
639       return "unknown error";
640   }
641 }
642
643
644 /**
645  * Translate glpk solver error codes to text
646  * @param retcode return code
647  * @return string with result
648  */
649 static const char *
650 mlp_solve_to_string (int retcode)
651 {
652   switch (retcode) {
653     case 0:
654       return "ok";
655     case GLP_EBADB:
656       return "invalid basis";
657     case GLP_ESING:
658       return "singular matrix";
659     case GLP_ECOND:
660       return "ill-conditioned matrix";
661     case GLP_EBOUND:
662       return "invalid bounds";
663     case GLP_EFAIL:
664       return "solver failed";
665     case GLP_EOBJLL:
666       return "objective lower limit reached";
667     case GLP_EOBJUL:
668       return "objective upper limit reached";
669     case GLP_EITLIM:
670       return "iteration limit exceeded";
671     case GLP_ETMLIM:
672       return "time limit exceeded";
673     case GLP_ENOPFS:
674       return "no primal feasible solution";
675     case GLP_ENODFS:
676       return "no dual feasible solution";
677     case GLP_EROOT:
678       return "root LP optimum not provided";
679     case GLP_ESTOP:
680       return "search terminated by application";
681     case GLP_EMIPGAP:
682       return "relative mip gap tolerance reached";
683     case GLP_ENOFEAS:
684       return "no dual feasible solution";
685     case GLP_ENOCVG:
686       return "no convergence";
687     case GLP_EINSTAB:
688       return "numerical instability";
689     case GLP_EDATA:
690       return "invalid data";
691     case GLP_ERANGE:
692       return "result out of range";
693     default:
694       GNUNET_break (0);
695       return "unknown error";
696   }
697 }
698
699
700 struct CountContext
701 {
702   const struct GNUNET_CONTAINER_MultiPeerMap *map;
703   int result;
704 };
705
706 static int
707 mlp_create_problem_count_addresses_it (void *cls,
708                                        const struct GNUNET_PeerIdentity *key,
709                                        void *value)
710 {
711   struct CountContext *cctx = cls;
712
713   /* Check if we have to add this peer due to a pending request */
714   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (cctx->map, key))
715     cctx->result++;
716   return GNUNET_OK;
717 }
718
719
720 static int
721 mlp_create_problem_count_addresses (const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers,
722                                     const struct GNUNET_CONTAINER_MultiPeerMap *addresses)
723 {
724   struct CountContext cctx;
725
726   cctx.map = requested_peers;
727   cctx.result = 0;
728   GNUNET_CONTAINER_multipeermap_iterate (addresses,
729            &mlp_create_problem_count_addresses_it, &cctx);
730   return cctx.result;
731 }
732
733
734 static int
735 mlp_create_problem_count_peers_it (void *cls,
736                                    const struct GNUNET_PeerIdentity *key,
737                                    void *value)
738 {
739   struct CountContext *cctx = cls;
740
741   /* Check if we have to addresses for the requested peer */
742   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (cctx->map, key))
743     cctx->result++;
744   return GNUNET_OK;
745 }
746
747
748 static int
749 mlp_create_problem_count_peers (const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers,
750     const struct GNUNET_CONTAINER_MultiPeerMap *addresses)
751 {
752   struct CountContext cctx;
753
754   cctx.map = addresses;
755   cctx.result = 0;
756   GNUNET_CONTAINER_multipeermap_iterate (requested_peers,
757            &mlp_create_problem_count_peers_it, &cctx);
758   return cctx.result;
759 }
760
761
762 /**
763  * Updates an existing value in the matrix
764  *
765  * Extract the row, updates the value and updates the row in the problem
766  *
767  * @param p the mlp problem
768  * @param row the row to create the value in
769  * @param col the column to create the value in
770  * @param val the value to set
771  * @param line calling line for debbuging
772  * @return GNUNET_YES value changed, GNUNET_NO value did not change, GNUNET_SYSERR
773  * on error
774  */
775 static int
776 mlp_create_problem_update_value (struct MLP_Problem *p,
777                               int row, int col, double val,
778                               int line)
779 {
780   int c_cols;
781   int c_elems;
782   int c1;
783   int res;
784   int found;
785   double *val_array;
786   int *ind_array;
787
788   GNUNET_assert (NULL != p->prob);
789
790   /* Get number of columns and prepare data structure */
791   c_cols = glp_get_num_cols(p->prob);
792   if (0 >= c_cols)
793     return GNUNET_SYSERR;
794
795   val_array = GNUNET_malloc ((c_cols +1)* sizeof (double));
796   GNUNET_assert (NULL != val_array);
797   ind_array = GNUNET_malloc ((c_cols+1) * sizeof (int));
798   GNUNET_assert (NULL != ind_array);
799   /* Extract the row */
800
801   /* Update the value */
802   c_elems = glp_get_mat_row (p->prob, row, ind_array, val_array);
803   found = GNUNET_NO;
804   for (c1 = 1; c1 < (c_elems+1); c1++)
805   {
806     if (ind_array[c1] == col)
807     {
808       found = GNUNET_YES;
809       break;
810     }
811   }
812   if (GNUNET_NO == found)
813   {
814     ind_array[c_elems+1] = col;
815     val_array[c_elems+1] = val;
816     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P] Setting value in [%s : %s] to `%.2f'\n",
817         glp_get_row_name (p->prob, row), glp_get_col_name (p->prob, col),
818         val);
819     glp_set_mat_row (p->prob, row, c_elems+1, ind_array, val_array);
820     GNUNET_free (ind_array);
821     GNUNET_free (val_array);
822     return GNUNET_YES;
823   }
824   else
825   {
826     /* Update value */
827     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P] Updating value in [%s : %s] from `%.2f' to `%.2f'\n",
828         glp_get_row_name (p->prob, row), glp_get_col_name (p->prob, col),
829         val_array[c1], val);
830     if (val != val_array[c1])
831       res = GNUNET_YES;
832     else
833       res = GNUNET_NO;
834     val_array[c1] = val;
835     /* Update the row in the matrix */
836     glp_set_mat_row (p->prob, row, c_elems, ind_array, val_array);
837   }
838
839   GNUNET_free (ind_array);
840   GNUNET_free (val_array);
841   return res;
842 }
843
844 /**
845  * Creates a new value in the matrix
846  *
847  * Sets the row and column index in the problem array and increments the
848  * position field
849  *
850  * @param p the mlp problem
851  * @param row the row to create the value in
852  * @param col the column to create the value in
853  * @param val the value to set
854  * @param line calling line for debbuging
855  */
856 static void
857 mlp_create_problem_set_value (struct MLP_Problem *p,
858                               int row, int col, double val,
859                               int line)
860 {
861   if ((p->ci) >= p->num_elements)
862   {
863     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Request for index %u bigger than array size of %u\n",
864         line, p->ci + 1, p->num_elements);
865     GNUNET_break (0);
866     return;
867   }
868   if ((0 == row) || (0 == col))
869   {
870     GNUNET_break (0);
871     LOG (GNUNET_ERROR_TYPE_ERROR, "[P]: Invalid call from line %u: row = %u, col = %u\n",
872         line, row, col);
873   }
874   p->ia[p->ci] = row ;
875   p->ja[p->ci] = col;
876   p->ar[p->ci] = val;
877 #if  DEBUG_MLP_PROBLEM_CREATION
878   LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Set value [%u,%u] in index %u ==  %.2f\n",
879       line, p->ia[p->ci], p->ja[p->ci], p->ci, p->ar[p->ci]);
880 #endif
881   p->ci++;
882 }
883
884 static int
885 mlp_create_problem_create_column (struct MLP_Problem *p, char *name,
886     unsigned int type, unsigned int bound, double lb, double ub,
887     double coef)
888 {
889   int col = glp_add_cols (p->prob, 1);
890   glp_set_col_name (p->prob, col, name);
891   glp_set_col_bnds (p->prob, col, bound, lb, ub);
892   glp_set_col_kind (p->prob, col, type);
893   glp_set_obj_coef (p->prob, col, coef);
894 #if  DEBUG_MLP_PROBLEM_CREATION
895   LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added column [%u] `%s': %.2f\n",
896       col, name, coef);
897 #endif
898   return col;
899 }
900
901 static int
902 mlp_create_problem_create_constraint (struct MLP_Problem *p, char *name,
903     unsigned int bound, double lb, double ub)
904 {
905   char * op;
906   int row = glp_add_rows (p->prob, 1);
907   /* set row name */
908   glp_set_row_name (p->prob, row, name);
909   /* set row bounds: <= 0 */
910   glp_set_row_bnds (p->prob, row, bound, lb, ub);
911   switch (bound)
912   {
913     case GLP_UP:
914             GNUNET_asprintf(&op, "-inf <= x <= %.2f", ub);
915             break;
916     case GLP_DB:
917             GNUNET_asprintf(&op, "%.2f <= x <= %.2f", lb, ub);
918             break;
919     case GLP_FX:
920             GNUNET_asprintf(&op, "%.2f == x == %.2f", lb, ub);
921             break;
922     case GLP_LO:
923             GNUNET_asprintf(&op, "%.2f <= x <= inf", lb);
924             break;
925     default:
926             GNUNET_asprintf(&op, "ERROR");
927             break;
928   }
929 #if  DEBUG_MLP_PROBLEM_CREATION
930     LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added row [%u] `%s': %s\n",
931         row, name, op);
932 #endif
933   GNUNET_free (op);
934   return row;
935 }
936
937 /**
938  * Create the
939  * - address columns b and n
940  * - address dependent constraint rows c1, c3
941  * - peer dependent rows c2 and c9
942  * - Set address dependent entries in problem matrix as well
943  */
944 static int
945 mlp_create_problem_add_address_information (void *cls,
946                                             const struct GNUNET_PeerIdentity *key,
947                                             void *value)
948 {
949   struct GAS_MLP_Handle *mlp = cls;
950   struct MLP_Problem *p = &mlp->p;
951   struct ATS_Address *address = value;
952   struct ATS_Peer *peer;
953   struct MLP_information *mlpi;
954   char *name;
955   double cur_bigm;
956   uint32_t addr_net;
957   uint32_t addr_net_index;
958   unsigned long long max_quota;
959   int c;
960
961   /* Check if we have to add this peer due to a pending request */
962   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains(mlp->requested_peers, key))
963     return GNUNET_OK;
964
965   mlpi = address->solver_information;
966   if (NULL == mlpi)
967   {
968       fprintf (stderr, "%s %p\n",GNUNET_i2s (&address->peer), address);
969       GNUNET_break (0);
970       return GNUNET_OK;
971   }
972
973   addr_net = address->properties.scope;
974   for (addr_net_index = 0; addr_net_index < GNUNET_ATS_NetworkTypeCount; addr_net_index++)
975   {
976     if (mlp->pv.quota_index[addr_net_index] == addr_net)
977       break;
978   }
979
980   if (addr_net_index >= GNUNET_ATS_NetworkTypeCount)
981   {
982     GNUNET_break (0);
983     return GNUNET_OK;
984   }
985
986   max_quota = 0;
987   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
988   {
989     if (mlp->pv.quota_out[c] > max_quota)
990       max_quota = mlp->pv.quota_out[c];
991     if (mlp->pv.quota_in[c] > max_quota)
992       max_quota = mlp->pv.quota_in[c];
993   }
994   if (max_quota > mlp->pv.BIG_M)
995     cur_bigm = (double) mlp->pv.BIG_M;
996   else
997     cur_bigm = max_quota;
998
999
1000   /* Get peer */
1001   peer = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, key);
1002   GNUNET_assert (NULL != peer);
1003   if (peer->processed == GNUNET_NO)
1004   {
1005       /* Add peer dependent constraints */
1006       /* Add c2) One address active per peer */
1007       GNUNET_asprintf(&name, "c2_%s", GNUNET_i2s(&address->peer));
1008       peer->r_c2 = mlp_create_problem_create_constraint (p, name, GLP_FX, 1.0, 1.0);
1009       GNUNET_free (name);
1010       if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1011       {
1012         if (GNUNET_YES == mlp->opt_dbg_optimize_relativity)
1013         {
1014           /* Add c9) Relativity */
1015           GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&address->peer));
1016           peer->r_c9 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
1017           GNUNET_free (name);
1018           /* c9) set coefficient */
1019           mlp_create_problem_set_value (p, peer->r_c9, p->c_r, -peer->f , __LINE__);
1020         }
1021       }
1022       peer->processed = GNUNET_YES;
1023   }
1024
1025   /* Reset addresses' solver information */
1026   mlpi->c_b = 0;
1027   mlpi->c_n = 0;
1028   mlpi->n = 0;
1029   mlpi->r_c1 = 0;
1030   mlpi->r_c3 = 0;
1031
1032   /* Add bandwidth column */
1033   GNUNET_asprintf (&name, "b_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
1034   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1035   {
1036     mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0);
1037   }
1038   else
1039   {
1040     /* Maximize for bandwidth assignment in feasibility testing */
1041     mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 1.0);
1042   }
1043   GNUNET_free (name);
1044
1045   /* Add address active column */
1046   GNUNET_asprintf (&name, "n_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
1047   mlpi->c_n = mlp_create_problem_create_column (p, name, GLP_IV, GLP_DB, 0.0, 1.0, 0.0);
1048   GNUNET_free (name);
1049
1050   /* Add address dependent constraints */
1051   /* Add c1) bandwidth capping: b_t  + (-M) * n_t <= 0 */
1052   GNUNET_asprintf(&name, "c1_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
1053   mlpi->r_c1 = mlp_create_problem_create_constraint (p, name, GLP_UP, 0.0, 0.0);
1054   GNUNET_free (name);
1055   /*  c1) set b = 1 coefficient */
1056   mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_b, 1, __LINE__);
1057   /*  c1) set n = - min (M, quota) coefficient */
1058   cur_bigm = (double) mlp->pv.quota_out[addr_net_index];
1059   if (cur_bigm > mlp->pv.BIG_M)
1060     cur_bigm = (double) mlp->pv.BIG_M;
1061   mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_n, -cur_bigm, __LINE__);
1062
1063   /* Add constraint c 3) minimum bandwidth
1064    * b_t + (-n_t * b_min) >= 0
1065    * */
1066   GNUNET_asprintf(&name, "c3_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
1067   mlpi->r_c3 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
1068   GNUNET_free (name);
1069
1070   /*  c3) set b = 1 coefficient */
1071   mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_b, 1, __LINE__);
1072   /*  c3) set n = -b_min coefficient */
1073   mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_n, - ((double )mlp->pv.b_min), __LINE__);
1074
1075
1076   /* Set coefficient entries in invariant rows */
1077
1078   /* Feasbility */
1079
1080   /* c 4) minimum connections */
1081   mlp_create_problem_set_value (p, p->r_c4, mlpi->c_n, 1, __LINE__);
1082   /* c 2) 1 address peer peer */
1083   mlp_create_problem_set_value (p, peer->r_c2, mlpi->c_n, 1, __LINE__);
1084   /* c 10) obey network specific quotas
1085    * (1)*b_1 + ... + (1)*b_m <= quota_n
1086    */
1087   mlp_create_problem_set_value (p, p->r_quota[addr_net_index], mlpi->c_b, 1, __LINE__);
1088
1089   /* Optimality */
1090   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1091   {
1092     /* c 6) maximize diversity */
1093     mlp_create_problem_set_value (p, p->r_c6, mlpi->c_n, 1, __LINE__);
1094     /* c 9) relativity */
1095     if (GNUNET_YES == mlp->opt_dbg_optimize_relativity)
1096       mlp_create_problem_set_value (p, peer->r_c9, mlpi->c_b, 1, __LINE__);
1097     /* c 8) utility */
1098     if (GNUNET_YES == mlp->opt_dbg_optimize_utility)
1099       mlp_create_problem_set_value (p, p->r_c8, mlpi->c_b, 1, __LINE__);
1100     /* c 7) Optimize quality */
1101     /* For all quality metrics, set quality of this address */
1102     if (GNUNET_YES == mlp->opt_dbg_optimize_quality)
1103     {
1104       mlp_create_problem_set_value (p,
1105                                     p->r_q[RQ_QUALITY_METRIC_DELAY],
1106                                     mlpi->c_b,
1107                                     address->norm_delay.norm,
1108                                     __LINE__);
1109       mlp_create_problem_set_value (p,
1110                                     p->r_q[RQ_QUALITY_METRIC_DISTANCE],
1111                                     mlpi->c_b,
1112                                     address->norm_distance.norm,
1113                                     __LINE__);
1114     }
1115   }
1116
1117   return GNUNET_OK;
1118 }
1119
1120
1121 /**
1122  * Create the invariant columns c4, c6, c10, c8, c7
1123  */
1124 static void
1125 mlp_create_problem_add_invariant_rows (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
1126 {
1127   int c;
1128
1129   /* Feasibility */
1130
1131   /* Row for c4) minimum connection */
1132   /* Number of minimum connections is min(|Peers|, n_min) */
1133   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);
1134
1135   /* Rows for c 10) Enforce network quotas */
1136   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
1137   {
1138     char * text;
1139     GNUNET_asprintf(&text, "c10_quota_ats_%s",
1140         GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]));
1141     p->r_quota[c] = mlp_create_problem_create_constraint (p, text, GLP_DB, 0.0, mlp->pv.quota_out[c]);
1142     GNUNET_free (text);
1143   }
1144
1145   /* Optimality */
1146   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1147   {
1148     char *name;
1149     /* Add row for c6) Maximize for diversity */
1150     if (GNUNET_YES == mlp->opt_dbg_optimize_diversity)
1151     {
1152       p->r_c6 = mlp_create_problem_create_constraint (p, "c6", GLP_FX, 0.0, 0.0);
1153       /* Set c6 ) Setting -D */
1154       mlp_create_problem_set_value (p, p->r_c6, p->c_d, -1, __LINE__);
1155     }
1156
1157     /* Adding rows for c 8) Maximize utility */
1158     if (GNUNET_YES == mlp->opt_dbg_optimize_utility)
1159     {
1160       p->r_c8 = mlp_create_problem_create_constraint (p, "c8", GLP_FX, 0.0, 0.0);
1161       /* -u */
1162       mlp_create_problem_set_value (p, p->r_c8, p->c_u, -1, __LINE__);
1163     }
1164
1165     /* For all quality metrics:
1166      * c 7) Maximize quality, austerity */
1167     if (GNUNET_YES == mlp->opt_dbg_optimize_quality)
1168     {
1169       for (c = 0; c < mlp->pv.m_q; c++)
1170       {
1171         GNUNET_asprintf (&name,
1172                          "c7_q%i_%s", c,
1173                          print_quality_type (c));
1174         p->r_q[c] = mlp_create_problem_create_constraint (p, name, GLP_FX, 0.0, 0.0);
1175         GNUNET_free (name);
1176         mlp_create_problem_set_value (p,
1177                                       p->r_q[c],
1178                                       p->c_q[c], -1, __LINE__);
1179       }
1180     }
1181   }
1182 }
1183
1184
1185 /**
1186  * Create the invariant columns d, u, r, q0 ... qm
1187  */
1188 static void
1189 mlp_create_problem_add_invariant_columns (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
1190 {
1191   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1192   {
1193     char *name;
1194     int c;
1195
1196     /* Diversity d column  */
1197     if (GNUNET_YES == mlp->opt_dbg_optimize_diversity)
1198       p->c_d = mlp_create_problem_create_column (p, "d", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_D);
1199
1200     /* Utilization u column  */
1201     if (GNUNET_YES == mlp->opt_dbg_optimize_utility)
1202       p->c_u = mlp_create_problem_create_column (p, "u", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_U);
1203
1204     /* Relativity r column  */
1205     if (GNUNET_YES == mlp->opt_dbg_optimize_relativity)
1206       p->c_r = mlp_create_problem_create_column (p, "r", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_R);
1207
1208     /* Quality metric columns */
1209     if (GNUNET_YES == mlp->opt_dbg_optimize_quality)
1210     {
1211       for (c = 0; c < mlp->pv.m_q; c++)
1212       {
1213         GNUNET_asprintf (&name, "q_%u", c);
1214         p->c_q[c] = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_Q[c]);
1215         GNUNET_free (name);
1216       }
1217     }
1218   }
1219 }
1220
1221
1222 /**
1223  * Create the MLP problem
1224  *
1225  * @param mlp the MLP handle
1226  * @return #GNUNET_OK or #GNUNET_SYSERR
1227  */
1228 static int
1229 mlp_create_problem (struct GAS_MLP_Handle *mlp)
1230 {
1231   struct MLP_Problem *p = &mlp->p;
1232   int res = GNUNET_OK;
1233
1234   GNUNET_assert (p->prob == NULL);
1235   GNUNET_assert (p->ia == NULL);
1236   GNUNET_assert (p->ja == NULL);
1237   GNUNET_assert (p->ar == NULL);
1238   /* Reset MLP problem struct */
1239
1240   /* create the glpk problem */
1241   p->prob = glp_create_prob ();
1242   GNUNET_assert (NULL != p->prob);
1243   p->num_peers = mlp_create_problem_count_peers (mlp->requested_peers, mlp->env->addresses);
1244   p->num_addresses = mlp_create_problem_count_addresses (mlp->requested_peers,
1245                                                          mlp->env->addresses);
1246
1247   /* Create problem matrix: 10 * #addresses + #q * #addresses + #q, + #peer + 2 + 1 */
1248   p->num_elements = (10 * p->num_addresses + mlp->pv.m_q * p->num_addresses +
1249       mlp->pv.m_q + p->num_peers + 2 + 1);
1250   LOG (GNUNET_ERROR_TYPE_DEBUG,
1251        "Rebuilding problem for %u peer(s) and %u addresse(s) and %u quality metrics == %u elements\n",
1252        p->num_peers,
1253        p->num_addresses,
1254        mlp->pv.m_q,
1255        p->num_elements);
1256
1257   /* Set a problem name */
1258   glp_set_prob_name (p->prob, "GNUnet ATS bandwidth distribution");
1259   /* Set optimization direction to maximize */
1260   glp_set_obj_dir (p->prob, GLP_MAX);
1261
1262   /* Create problem matrix */
1263   /* last +1 caused by glpk index starting with one: [1..elements]*/
1264   p->ci = 1;
1265   /* row index */
1266   p->ia = GNUNET_malloc (p->num_elements * sizeof (int));
1267   /* column index */
1268   p->ja = GNUNET_malloc (p->num_elements * sizeof (int));
1269   /* coefficient */
1270   p->ar = GNUNET_malloc (p->num_elements * sizeof (double));
1271
1272   if ((NULL == p->ia) || (NULL == p->ja) || (NULL == p->ar))
1273   {
1274       LOG (GNUNET_ERROR_TYPE_ERROR, _("Problem size too large, cannot allocate memory!\n"));
1275       return GNUNET_SYSERR;
1276   }
1277
1278   /* Adding invariant columns */
1279   mlp_create_problem_add_invariant_columns (mlp, p);
1280
1281   /* Adding address independent constraint rows */
1282   mlp_create_problem_add_invariant_rows (mlp, p);
1283
1284   /* Adding address dependent columns constraint rows */
1285   GNUNET_CONTAINER_multipeermap_iterate (mlp->env->addresses,
1286                                          &mlp_create_problem_add_address_information,
1287                                          mlp);
1288
1289   /* Load the matrix */
1290   LOG (GNUNET_ERROR_TYPE_DEBUG, "Loading matrix\n");
1291   glp_load_matrix(p->prob, (p->ci)-1, p->ia, p->ja, p->ar);
1292   if (GNUNET_YES == mlp->opt_dbg_autoscale_problem)
1293   {
1294     glp_scale_prob (p->prob, GLP_SF_AUTO);
1295   }
1296
1297   return res;
1298 }
1299
1300
1301 /**
1302  * Solves the LP problem
1303  *
1304  * @param mlp the MLP Handle
1305  * @return #GNUNET_OK if could be solved, #GNUNET_SYSERR on failure
1306  */
1307 static int
1308 mlp_solve_lp_problem (struct GAS_MLP_Handle *mlp)
1309 {
1310   int res = 0;
1311   int res_status = 0;
1312   res = glp_simplex(mlp->p.prob, &mlp->control_param_lp);
1313   if (0 == res)
1314     LOG(GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem: %s\n",
1315         mlp_solve_to_string (res));
1316   else
1317     LOG(GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem failed: %s\n",
1318         mlp_solve_to_string (res));
1319
1320   /* Analyze problem status  */
1321   res_status = glp_get_status (mlp->p.prob);
1322   switch (res_status) {
1323     case GLP_OPT: /* solution is optimal */
1324       LOG (GNUNET_ERROR_TYPE_INFO,
1325           "Solving LP problem: %s, %s\n",
1326           mlp_solve_to_string(res),
1327           mlp_status_to_string(res_status));
1328       return GNUNET_OK;
1329     default:
1330       LOG (GNUNET_ERROR_TYPE_ERROR,
1331           "Solving LP problem failed: %s %s\n",
1332           mlp_solve_to_string(res),
1333           mlp_status_to_string(res_status));
1334       return GNUNET_SYSERR;
1335   }
1336 }
1337
1338
1339 /**
1340  * Propagates the results when MLP problem was solved
1341  *
1342  * @param cls the MLP handle
1343  * @param key the peer identity
1344  * @param value the address
1345  * @return #GNUNET_OK to continue
1346  */
1347 static int
1348 mlp_propagate_results (void *cls,
1349                        const struct GNUNET_PeerIdentity *key,
1350                        void *value)
1351 {
1352   struct GAS_MLP_Handle *mlp = cls;
1353   struct ATS_Address *address;
1354   struct MLP_information *mlpi;
1355   double mlp_bw_in = MLP_NaN;
1356   double mlp_bw_out = MLP_NaN;
1357   double mlp_use = MLP_NaN;
1358
1359   /* Check if we have to add this peer due to a pending request */
1360   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mlp->requested_peers,
1361                                                            key))
1362   {
1363     return GNUNET_OK;
1364   }
1365   address = value;
1366   GNUNET_assert (address->solver_information != NULL);
1367   mlpi = address->solver_information;
1368
1369   mlp_bw_in = glp_mip_col_val(mlp->p.prob, mlpi->c_b);/* FIXME */
1370   if (mlp_bw_in > (double) UINT32_MAX)
1371   {
1372       LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
1373       mlp_bw_in = (double) UINT32_MAX;
1374   }
1375   mlp_bw_out = glp_mip_col_val(mlp->p.prob, mlpi->c_b);
1376   if (mlp_bw_out > (double) UINT32_MAX)
1377   {
1378       LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
1379       mlp_bw_out = (double) UINT32_MAX;
1380   }
1381   mlp_use = glp_mip_col_val(mlp->p.prob, mlpi->c_n);
1382
1383   /*
1384    * Debug: solution
1385    * LOG (GNUNET_ERROR_TYPE_INFO, "MLP result address: `%s' `%s' length %u session %u, mlp use %.3f\n",
1386    *    GNUNET_i2s(&address->peer), address->plugin,
1387    *    address->addr_len, address->session_id);
1388    */
1389
1390   if (GLP_YES == mlp_use)
1391   {
1392     /* This address was selected by the solver to be used */
1393     mlpi->n = GNUNET_YES;
1394     if (GNUNET_NO == address->active)
1395     {
1396             /* Address was not used before, enabling address */
1397       LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : enabling address\n",
1398           (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1399       address->active = GNUNET_YES;
1400       address->assigned_bw_in = mlp_bw_in;
1401       mlpi->b_in = mlp_bw_in;
1402       address->assigned_bw_out = mlp_bw_out;
1403       mlpi->b_out = mlp_bw_out;
1404       if ((NULL == mlp->exclude_peer) || (0 != memcmp (&address->peer, mlp->exclude_peer, sizeof (address->peer))))
1405         mlp->env->bandwidth_changed_cb (mlp->env->cls, address);
1406       return GNUNET_OK;
1407     }
1408     else if (GNUNET_YES == address->active)
1409     {
1410       /* Address was used before, check for bandwidth change */
1411       if ((mlp_bw_out != address->assigned_bw_out) ||
1412               (mlp_bw_in != address->assigned_bw_in))
1413       {
1414           LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : bandwidth changed\n",
1415               (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1416           address->assigned_bw_in = mlp_bw_in;
1417           mlpi->b_in = mlp_bw_in;
1418           address->assigned_bw_out = mlp_bw_out;
1419           mlpi->b_out = mlp_bw_out;
1420           if ((NULL == mlp->exclude_peer) || (0 != memcmp (&address->peer, mlp->exclude_peer, sizeof (address->peer))))
1421             mlp->env->bandwidth_changed_cb (mlp->env->cls, address);
1422           return GNUNET_OK;
1423       }
1424     }
1425     else
1426       GNUNET_break (0);
1427   }
1428   else if (GLP_NO == mlp_use)
1429   {
1430     /* This address was selected by the solver to be not used */
1431     mlpi->n = GNUNET_NO;
1432     if (GNUNET_NO == address->active)
1433     {
1434       /* Address was not used before, nothing to do */
1435       LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : no change\n",
1436           (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1437       return GNUNET_OK;
1438     }
1439     else if (GNUNET_YES == address->active)
1440     {
1441     /* Address was used before, disabling address */
1442     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : disabling address\n",
1443         (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1444       address->active = GNUNET_NO;
1445       /* Set bandwidth to 0 */
1446       address->assigned_bw_in = 0;
1447       mlpi->b_in = 0;
1448       address->assigned_bw_out = 0;
1449       mlpi->b_out = 0;
1450       return GNUNET_OK;
1451     }
1452     else
1453       GNUNET_break (0);
1454   }
1455   else
1456     GNUNET_break (0);
1457
1458   return GNUNET_OK;
1459 }
1460
1461
1462 static void
1463 notify (struct GAS_MLP_Handle *mlp,
1464         enum GAS_Solver_Operation op,
1465         enum GAS_Solver_Status stat,
1466         enum GAS_Solver_Additional_Information add)
1467 {
1468   mlp->env->info_cb (mlp->env->cls,
1469                      op,
1470                      stat,
1471                      add);
1472 }
1473
1474
1475 static void
1476 mlp_branch_and_cut_cb (glp_tree *tree, void *info)
1477 {
1478   struct GAS_MLP_Handle *mlp = info;
1479   double mlp_obj = 0;
1480
1481   switch (glp_ios_reason (tree))
1482   {
1483     case GLP_ISELECT:
1484         /* Do nothing here */
1485       break;
1486     case GLP_IPREPRO:
1487         /* Do nothing here */
1488       break;
1489     case GLP_IROWGEN:
1490         /* Do nothing here */
1491       break;
1492     case GLP_IHEUR:
1493         /* Do nothing here */
1494       break;
1495     case GLP_ICUTGEN:
1496         /* Do nothing here */
1497       break;
1498     case GLP_IBRANCH:
1499         /* Do nothing here */
1500       break;
1501     case GLP_IBINGO:
1502         /* A better solution was found  */
1503       mlp->ps.mlp_gap = glp_ios_mip_gap (tree);
1504       mlp_obj = glp_mip_obj_val (mlp->p.prob);
1505       mlp->ps.lp_mlp_gap = (abs(mlp_obj - mlp->ps.lp_objective_value)) / (abs(mlp_obj) + DBL_EPSILON);
1506
1507       LOG (GNUNET_ERROR_TYPE_INFO,
1508           "Found better integer solution, current gaps: %.3f <= %.3f, %.3f <= %.3f\n",
1509           mlp->ps.mlp_gap, mlp->pv.mip_gap,
1510           mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap);
1511
1512       if (mlp->ps.mlp_gap <= mlp->pv.mip_gap)
1513       {
1514         LOG (GNUNET_ERROR_TYPE_INFO,
1515           "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n",
1516           mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap);
1517         glp_ios_terminate (tree);
1518       }
1519
1520       if (mlp->ps.lp_mlp_gap <= mlp->pv.lp_mip_gap)
1521       {
1522         LOG (GNUNET_ERROR_TYPE_INFO,
1523           "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n",
1524           mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap);
1525         glp_ios_terminate (tree);
1526       }
1527
1528       break;
1529     default:
1530       break;
1531   }
1532   //GNUNET_break (0);
1533 }
1534
1535
1536 /**
1537  * Solves the MLP problem
1538  *
1539  * @param solver the MLP Handle
1540  * @return #GNUNET_OK if could be solved, #GNUNET_SYSERR on failure
1541  */
1542 static int
1543 GAS_mlp_solve_problem (void *solver)
1544 {
1545   struct GAS_MLP_Handle *mlp = solver;
1546   char *filename;
1547   int res_lp = 0;
1548   int mip_res = 0;
1549   int mip_status = 0;
1550
1551   struct GNUNET_TIME_Absolute start_total;
1552   struct GNUNET_TIME_Absolute start_cur_op;
1553   struct GNUNET_TIME_Relative dur_total;
1554   struct GNUNET_TIME_Relative dur_setup;
1555   struct GNUNET_TIME_Relative dur_lp;
1556   struct GNUNET_TIME_Relative dur_mlp;
1557
1558   GNUNET_assert(NULL != solver);
1559
1560   if (GNUNET_YES == mlp->stat_bulk_lock)
1561     {
1562       mlp->stat_bulk_requests++;
1563       return GNUNET_NO;
1564     }
1565   notify(mlp, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS,
1566       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1567   start_total = GNUNET_TIME_absolute_get();
1568
1569   if (0 == GNUNET_CONTAINER_multipeermap_size(mlp->requested_peers))
1570     {
1571       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1572       return GNUNET_OK; /* No pending requests */
1573     }
1574   if (0 == GNUNET_CONTAINER_multipeermap_size(mlp->env->addresses))
1575     {
1576       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1577       return GNUNET_OK; /* No addresses available */
1578     }
1579
1580   if ((GNUNET_NO == mlp->stat_mlp_prob_changed)
1581       && (GNUNET_NO == mlp->stat_mlp_prob_updated))
1582     {
1583       LOG(GNUNET_ERROR_TYPE_DEBUG, "No changes to problem\n");
1584       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1585       return GNUNET_OK;
1586     }
1587   if (GNUNET_YES == mlp->stat_mlp_prob_changed)
1588   {
1589     LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem size changed, rebuilding\n");
1590     notify(mlp, GAS_OP_SOLVE_SETUP_START, GAS_STAT_SUCCESS, GAS_INFO_FULL);
1591     mlp_delete_problem (mlp);
1592     if (GNUNET_SYSERR == mlp_create_problem (mlp))
1593       {
1594         notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_FAIL, GAS_INFO_FULL);
1595         return GNUNET_SYSERR;
1596       }
1597     notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_SUCCESS, GAS_INFO_FULL);
1598     if (GNUNET_NO == mlp->opt_dbg_intopt_presolver)
1599     {
1600     mlp->control_param_lp.presolve = GLP_YES; /* LP presolver, we need lp solution */
1601     mlp->control_param_mlp.presolve = GNUNET_NO; /* No presolver, we have LP solution */
1602     }
1603     else
1604     {
1605       mlp->control_param_lp.presolve = GNUNET_NO; /* LP presolver, we need lp solution */
1606       mlp->control_param_mlp.presolve = GLP_YES; /* No presolver, we have LP solution */
1607       dur_lp = GNUNET_TIME_UNIT_ZERO;
1608     }
1609   }
1610   else
1611   {
1612     LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem was updated, resolving\n");
1613   }
1614
1615   /* Reset solution info */
1616   mlp->ps.lp_objective_value = 0.0;
1617   mlp->ps.mlp_gap = 1.0;
1618   mlp->ps.mlp_objective_value = 0.0;
1619   mlp->ps.lp_mlp_gap = 0.0;
1620
1621   dur_setup = GNUNET_TIME_absolute_get_duration (start_total);
1622
1623   /* Run LP solver */
1624   if (GNUNET_NO == mlp->opt_dbg_intopt_presolver)
1625   {
1626     notify(mlp, GAS_OP_SOLVE_MLP_LP_START, GAS_STAT_SUCCESS,
1627         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1628     LOG(GNUNET_ERROR_TYPE_DEBUG,
1629         "Running LP solver %s\n",
1630         (GLP_YES == mlp->control_param_lp.presolve)? "with presolver": "without presolver");
1631     start_cur_op = GNUNET_TIME_absolute_get();
1632
1633     /* Solve LP */
1634     /* Only for debugging:
1635      * Always use LP presolver:
1636      * mlp->control_param_lp.presolve = GLP_YES; */
1637     res_lp = mlp_solve_lp_problem(mlp);
1638     if (GNUNET_OK == res_lp)
1639     {
1640         mlp->ps.lp_objective_value = glp_get_obj_val (mlp->p.prob);
1641         LOG (GNUNET_ERROR_TYPE_DEBUG,
1642              "LP solution was: %.3f\n",
1643              mlp->ps.lp_objective_value);
1644     }
1645
1646     dur_lp = GNUNET_TIME_absolute_get_duration (start_cur_op);
1647     notify(mlp, GAS_OP_SOLVE_MLP_LP_STOP,
1648         (GNUNET_OK == res_lp) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1649         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1650   }
1651
1652   if (GNUNET_YES == mlp->opt_dbg_intopt_presolver)
1653     res_lp = GNUNET_OK;
1654
1655   /* Run MLP solver */
1656   if ((GNUNET_OK == res_lp) || (GNUNET_YES == mlp->opt_dbg_intopt_presolver))
1657   {
1658     LOG(GNUNET_ERROR_TYPE_DEBUG, "Running MLP solver \n");
1659     notify(mlp, GAS_OP_SOLVE_MLP_MLP_START, GAS_STAT_SUCCESS,
1660         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1661     start_cur_op = GNUNET_TIME_absolute_get();
1662
1663     /* Solve MIP */
1664
1665     /* Only for debugging, always use LP presolver */
1666     if (GNUNET_YES == mlp->opt_dbg_intopt_presolver)
1667       mlp->control_param_mlp.presolve = GNUNET_YES;
1668
1669     mip_res = glp_intopt (mlp->p.prob, &mlp->control_param_mlp);
1670     switch (mip_res)
1671     {
1672         case 0:
1673           /* Successful */
1674           LOG (GNUNET_ERROR_TYPE_INFO,
1675                "Solving MLP problem: %s\n",
1676                mlp_solve_to_string (mip_res));
1677           break;
1678         case GLP_ETMLIM: /* Time limit reached */
1679         case GLP_EMIPGAP: /* MIP gap tolerance limit reached */
1680         case GLP_ESTOP: /* Solver was instructed to stop*/
1681           /* Semi-successful */
1682           LOG (GNUNET_ERROR_TYPE_INFO,
1683                "Solving MLP problem solution was interupted: %s\n",
1684                mlp_solve_to_string (mip_res));
1685           break;
1686         case GLP_EBOUND:
1687         case GLP_EROOT:
1688         case GLP_ENOPFS:
1689         case GLP_ENODFS:
1690         case GLP_EFAIL:
1691         default:
1692          /* Fail */
1693           LOG (GNUNET_ERROR_TYPE_INFO,
1694               "Solving MLP problem failed: %s\n",
1695               mlp_solve_to_string (mip_res));
1696         break;
1697     }
1698
1699     /* Analyze problem status  */
1700     mip_status = glp_mip_status(mlp->p.prob);
1701     switch (mip_status)
1702     {
1703       case GLP_OPT: /* solution is optimal */
1704         LOG (GNUNET_ERROR_TYPE_WARNING,
1705             "Solution of MLP problem is optimal: %s, %s\n",
1706             mlp_solve_to_string (mip_res),
1707             mlp_status_to_string (mip_status));
1708         mip_res = GNUNET_OK;
1709         break;
1710       case GLP_FEAS: /* solution is feasible but not proven optimal */
1711
1712         if ( (mlp->ps.mlp_gap <= mlp->pv.mip_gap) ||
1713              (mlp->ps.lp_mlp_gap <= mlp->pv.lp_mip_gap) )
1714         {
1715           LOG (GNUNET_ERROR_TYPE_INFO,
1716                  "Solution of MLP problem is feasible and solution within gap constraints: %s, %s\n",
1717                  mlp_solve_to_string (mip_res),
1718                  mlp_status_to_string (mip_status));
1719           mip_res = GNUNET_OK;
1720         }
1721         else
1722         {
1723           LOG (GNUNET_ERROR_TYPE_WARNING,
1724                "Solution of MLP problem is feasible but solution not within gap constraints: %s, %s\n",
1725                mlp_solve_to_string (mip_res),
1726                mlp_status_to_string (mip_status));
1727           mip_res = GNUNET_SYSERR;
1728         }
1729         break;
1730       case GLP_UNDEF: /* Solution undefined */
1731       case GLP_NOFEAS: /* No feasible solution */
1732       default:
1733         LOG (GNUNET_ERROR_TYPE_ERROR,
1734             "Solving MLP problem failed: %s %s\n",
1735             mlp_solve_to_string (mip_res),
1736             mlp_status_to_string (mip_status));
1737         mip_res = GNUNET_SYSERR;
1738         break;
1739     }
1740
1741     dur_mlp = GNUNET_TIME_absolute_get_duration (start_cur_op);
1742     dur_total = GNUNET_TIME_absolute_get_duration (start_total);
1743
1744     notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP,
1745         (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1746         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1747   }
1748   else
1749   {
1750     /* Do not execute mip solver since lp solution is invalid */
1751     dur_mlp = GNUNET_TIME_UNIT_ZERO;
1752     dur_total = GNUNET_TIME_absolute_get_duration (start_total);
1753
1754     notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP, GAS_STAT_FAIL,
1755         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1756     mip_res = GNUNET_SYSERR;
1757   }
1758
1759   /* Notify about end */
1760   notify(mlp, GAS_OP_SOLVE_STOP,
1761       ((GNUNET_OK == mip_res) && (GNUNET_OK == mip_res)) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1762       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1763
1764   LOG (GNUNET_ERROR_TYPE_DEBUG,
1765       "Execution time for %s solve: (total/setup/lp/mlp) : %llu %llu %llu %llu\n",
1766       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? "full" : "updated",
1767       (unsigned long long) dur_total.rel_value_us,
1768       (unsigned long long) dur_setup.rel_value_us,
1769       (unsigned long long) dur_lp.rel_value_us,
1770       (unsigned long long) dur_mlp.rel_value_us);
1771
1772   /* Save stats */
1773   mlp->ps.lp_res = res_lp;
1774   mlp->ps.mip_res = mip_res;
1775   mlp->ps.lp_presolv = mlp->control_param_lp.presolve;
1776   mlp->ps.mip_presolv = mlp->control_param_mlp.presolve;
1777   mlp->ps.p_cols = glp_get_num_cols(mlp->p.prob);
1778   mlp->ps.p_rows = glp_get_num_rows(mlp->p.prob);
1779   mlp->ps.p_elements = mlp->p.num_elements;
1780
1781   /* Propagate result*/
1782   notify (mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1783       (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1784       GAS_INFO_NONE);
1785   if ((GNUNET_OK == res_lp) && (GNUNET_OK == mip_res))
1786     {
1787       GNUNET_CONTAINER_multipeermap_iterate(mlp->env->addresses,
1788           &mlp_propagate_results, mlp);
1789     }
1790   notify (mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1791       (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1792       GAS_INFO_NONE);
1793
1794   struct GNUNET_TIME_Absolute time = GNUNET_TIME_absolute_get();
1795   if ( (GNUNET_YES == mlp->opt_dump_problem_all) ||
1796       (mlp->opt_dump_problem_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res))) )
1797     {
1798       /* Write problem to disk */
1799       switch (mlp->opt_log_format) {
1800         case MLP_CPLEX:
1801           GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.cplex", mlp->p.num_peers,
1802               mlp->p.num_addresses, time.abs_value_us);
1803           glp_write_lp (mlp->p.prob, NULL, filename);
1804           break;
1805         case MLP_GLPK:
1806           GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.glpk", mlp->p.num_peers,
1807               mlp->p.num_addresses, time.abs_value_us);
1808           glp_write_prob (mlp->p.prob, 0, filename);
1809           break;
1810         case MLP_MPS:
1811           GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.mps", mlp->p.num_peers,
1812               mlp->p.num_addresses, time.abs_value_us);
1813           glp_write_mps (mlp->p.prob, GLP_MPS_FILE, NULL, filename);
1814           break;
1815         default:
1816           break;
1817       }
1818       LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped problem to file: `%s' \n", filename);
1819       GNUNET_free(filename);
1820     }
1821   if ( (mlp->opt_dump_solution_all) ||
1822       (mlp->opt_dump_solution_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res))) )
1823   {
1824     /* Write solution to disk */
1825     GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.sol", mlp->p.num_peers,
1826         mlp->p.num_addresses, time.abs_value_us);
1827     glp_print_mip(mlp->p.prob, filename);
1828     LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped solution to file: `%s' \n", filename);
1829     GNUNET_free(filename);
1830   }
1831
1832   /* Reset change and update marker */
1833   mlp->control_param_lp.presolve = GLP_NO;
1834   mlp->stat_mlp_prob_updated = GNUNET_NO;
1835   mlp->stat_mlp_prob_changed = GNUNET_NO;
1836
1837   if ((GNUNET_OK == res_lp) && (GNUNET_OK == mip_res))
1838     return GNUNET_OK;
1839   else
1840     return GNUNET_SYSERR;
1841 }
1842
1843 /**
1844  * Add a single address to the solve
1845  *
1846  * @param solver the solver Handle
1847  * @param address the address to add
1848  * @param network network type of this address
1849  */
1850 static void
1851 GAS_mlp_address_add (void *solver,
1852                     struct ATS_Address *address,
1853                     uint32_t network)
1854 {
1855   struct GAS_MLP_Handle *mlp = solver;
1856
1857   if (GNUNET_ATS_NetworkTypeCount <= network)
1858   {
1859     GNUNET_break (0);
1860     return;
1861   }
1862
1863   if (NULL == address->solver_information)
1864   {
1865       address->solver_information = GNUNET_new (struct MLP_information);
1866   }
1867   else
1868       LOG (GNUNET_ERROR_TYPE_ERROR,
1869            _("Adding address for peer `%s' multiple times\n"),
1870            GNUNET_i2s(&address->peer));
1871
1872   /* Is this peer included in the problem? */
1873   if (NULL ==
1874       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1875                                          &address->peer))
1876   {
1877     /* FIXME: should this be an error? */
1878     LOG (GNUNET_ERROR_TYPE_DEBUG,
1879          "Adding address for peer `%s' without address request\n",
1880          GNUNET_i2s(&address->peer));
1881     return;
1882   }
1883
1884   LOG (GNUNET_ERROR_TYPE_DEBUG,
1885        "Adding address for peer `%s' with address request \n",
1886        GNUNET_i2s(&address->peer));
1887   /* Problem size changed: new address for peer with pending request */
1888   mlp->stat_mlp_prob_changed = GNUNET_YES;
1889   if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1890     GAS_mlp_solve_problem (solver);
1891 }
1892
1893
1894 /**
1895  * Transport properties for this address have changed
1896  *
1897  * @param solver solver handle
1898  * @param address the address
1899  */
1900 static void
1901 GAS_mlp_address_property_changed (void *solver,
1902                                   struct ATS_Address *address)
1903 {
1904   struct MLP_information *mlpi = address->solver_information;
1905   struct GAS_MLP_Handle *mlp = solver;
1906
1907   if (NULL == mlp->p.prob)
1908     return; /* There is no MLP problem to update yet */
1909
1910   if (NULL == mlpi)
1911   {
1912     LOG (GNUNET_ERROR_TYPE_INFO,
1913          _("Updating address property for peer `%s' %p not added before\n"),
1914          GNUNET_i2s (&address->peer),
1915          address);
1916     GNUNET_break (0);
1917     return;
1918   }
1919   if (NULL ==
1920       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1921                                          &address->peer))
1922   {
1923     /* Peer is not requested, so no need to update problem */
1924     return;
1925   }
1926   LOG (GNUNET_ERROR_TYPE_DEBUG,
1927        "Updating properties for peer `%s'\n",
1928        GNUNET_i2s(&address->peer));
1929
1930   if (GNUNET_YES == mlp->opt_dbg_feasibility_only)
1931     return;
1932
1933   /* Update c7) [r_q[index]][c_b] = f_q * q_averaged[type_index] */
1934   if ( (GNUNET_YES ==
1935         mlp_create_problem_update_value (&mlp->p,
1936                                          mlp->p.r_q[RQ_QUALITY_METRIC_DELAY],
1937                                          mlpi->c_b,
1938                                          address->norm_delay.norm,
1939                                          __LINE__)) ||
1940        (GNUNET_YES ==
1941         mlp_create_problem_update_value (&mlp->p,
1942                                          mlp->p.r_q[RQ_QUALITY_METRIC_DISTANCE],
1943                                          mlpi->c_b,
1944                                          address->norm_distance.norm,
1945                                          __LINE__)) )
1946   {
1947     mlp->stat_mlp_prob_updated = GNUNET_YES;
1948     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1949       GAS_mlp_solve_problem (solver);
1950   }
1951
1952 }
1953
1954
1955 /**
1956  * Find the active address in the set of addresses of a peer
1957  * @param cls destination
1958  * @param key peer id
1959  * @param value address
1960  * @return #GNUNET_OK
1961  */
1962 static int
1963 mlp_get_preferred_address_it (void *cls,
1964                               const struct GNUNET_PeerIdentity *key,
1965                               void *value)
1966 {
1967   static int counter = 0;
1968   struct ATS_Address **aa = cls;
1969   struct ATS_Address *addr = value;
1970   struct MLP_information *mlpi = addr->solver_information;
1971
1972   if (mlpi == NULL)
1973     return GNUNET_YES;
1974
1975   /*
1976    * Debug output
1977    * GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1978    *           "MLP [%u] Peer `%s' %s length %u session %u active %s mlp active %s\n",
1979    *           counter, GNUNET_i2s (&addr->peer), addr->plugin, addr->addr_len, addr->session_id,
1980    *           (GNUNET_YES == addr->active) ? "active" : "inactive",
1981    *           (GNUNET_YES == mlpi->n) ? "active" : "inactive");
1982    */
1983
1984   if (GNUNET_YES == mlpi->n)
1985   {
1986
1987     (*aa) = addr;
1988     (*aa)->assigned_bw_in = mlpi->b_in;
1989     (*aa)->assigned_bw_out = mlpi->b_out;
1990     return GNUNET_NO;
1991   }
1992   counter++;
1993   return GNUNET_YES;
1994 }
1995
1996
1997 static double
1998 get_peer_pref_value (struct GAS_MLP_Handle *mlp,
1999                      const struct GNUNET_PeerIdentity *peer)
2000 {
2001   double res;
2002   const double *preferences;
2003   int c;
2004
2005   preferences = mlp->env->get_preferences (mlp->env->cls, peer);
2006   res = 0.0;
2007   for (c = 0; c < GNUNET_ATS_PREFERENCE_END; c++)
2008   {
2009     /* fprintf (stderr, "VALUE[%u] %s %.3f \n",
2010      *        c, GNUNET_i2s (&cur->addr->peer), t[c]); */
2011     res += preferences[c];
2012   }
2013
2014   res /= GNUNET_ATS_PREFERENCE_END;
2015   res += 1.0;
2016
2017   LOG (GNUNET_ERROR_TYPE_DEBUG,
2018        "Peer preference for peer  `%s' == %.2f\n",
2019        GNUNET_i2s(peer), res);
2020
2021   return res;
2022 }
2023
2024
2025 /**
2026  * Get the preferred address for a specific peer
2027  *
2028  * @param solver the MLP Handle
2029  * @param peer the peer
2030  */
2031 static void
2032 GAS_mlp_get_preferred_address (void *solver,
2033                                const struct GNUNET_PeerIdentity *peer)
2034 {
2035   struct GAS_MLP_Handle *mlp = solver;
2036   struct ATS_Peer *p;
2037   struct ATS_Address *res;
2038
2039   LOG (GNUNET_ERROR_TYPE_DEBUG,
2040        "Getting preferred address for `%s'\n",
2041        GNUNET_i2s (peer));
2042
2043   /* Is this peer included in the problem? */
2044   if (NULL ==
2045       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
2046                                          peer))
2047     {
2048       LOG (GNUNET_ERROR_TYPE_INFO, "Adding peer `%s' to list of requested_peers with requests\n",
2049           GNUNET_i2s (peer));
2050
2051       p = GNUNET_new (struct ATS_Peer);
2052       p->id = (*peer);
2053       p->f = get_peer_pref_value (mlp, peer);
2054       GNUNET_CONTAINER_multipeermap_put (mlp->requested_peers,
2055                                          peer, p,
2056                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2057
2058       /* Added new peer, we have to rebuild problem before solving */
2059       mlp->stat_mlp_prob_changed = GNUNET_YES;
2060
2061       if ((GNUNET_YES == mlp->opt_mlp_auto_solve)&&
2062           (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(mlp->env->addresses,
2063                                                                 peer)))
2064       {
2065         mlp->exclude_peer = peer;
2066         GAS_mlp_solve_problem (mlp);
2067         mlp->exclude_peer = NULL;
2068       }
2069   }
2070   /* Get prefered address */
2071   res = NULL;
2072   GNUNET_CONTAINER_multipeermap_get_multiple (mlp->env->addresses, peer,
2073                                               &mlp_get_preferred_address_it, &res);
2074   if (NULL != res)
2075     mlp->env->bandwidth_changed_cb (mlp->env->cls,
2076                                     res);
2077 }
2078
2079
2080 /**
2081  * Deletes a single address in the MLP problem
2082  *
2083  * The MLP problem has to be recreated and the problem has to be resolved
2084  *
2085  * @param solver the MLP Handle
2086  * @param address the address to delete
2087  */
2088 static void
2089 GAS_mlp_address_delete (void *solver,
2090                         struct ATS_Address *address)
2091 {
2092   struct GAS_MLP_Handle *mlp = solver;
2093   struct MLP_information *mlpi;
2094   struct ATS_Address *res;
2095   int was_active;
2096
2097   mlpi = address->solver_information;
2098   if (NULL != mlpi)
2099   {
2100     /* Remove full address */
2101     GNUNET_free (mlpi);
2102     address->solver_information = NULL;
2103   }
2104   was_active = address->active;
2105   address->active = GNUNET_NO;
2106   address->assigned_bw_in = 0;
2107   address->assigned_bw_out = 0;
2108
2109   /* Is this peer included in the problem? */
2110   if (NULL ==
2111       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
2112                                          &address->peer))
2113   {
2114     LOG (GNUNET_ERROR_TYPE_INFO,
2115          "Deleting address for peer `%s' without address request \n",
2116          GNUNET_i2s(&address->peer));
2117     return;
2118   }
2119   LOG (GNUNET_ERROR_TYPE_INFO,
2120        "Deleting address for peer `%s' with address request \n",
2121       GNUNET_i2s (&address->peer));
2122
2123   /* Problem size changed: new address for peer with pending request */
2124   mlp->stat_mlp_prob_changed = GNUNET_YES;
2125   if (GNUNET_YES == mlp->opt_mlp_auto_solve)
2126   {
2127     GAS_mlp_solve_problem (solver);
2128   }
2129   if (GNUNET_YES == was_active)
2130   {
2131     GAS_mlp_get_preferred_address (solver, &address->peer);
2132     res = NULL;
2133     GNUNET_CONTAINER_multipeermap_get_multiple (mlp->env->addresses,
2134                                                 &address->peer,
2135                                                 &mlp_get_preferred_address_it,
2136                                                 &res);
2137     if (NULL == res)
2138     {
2139       /* No alternative address, disconnecting peer */
2140       mlp->env->bandwidth_changed_cb (mlp->env->cls, address);
2141     }
2142   }
2143 }
2144
2145
2146 /**
2147  * Start a bulk operation
2148  *
2149  * @param solver the solver
2150  */
2151 static void
2152 GAS_mlp_bulk_start (void *solver)
2153 {
2154   struct GAS_MLP_Handle *s = solver;
2155
2156   LOG (GNUNET_ERROR_TYPE_DEBUG,
2157        "Locking solver for bulk operation ...\n");
2158   GNUNET_assert (NULL != solver);
2159   s->stat_bulk_lock ++;
2160 }
2161
2162
2163 static void
2164 GAS_mlp_bulk_stop (void *solver)
2165 {
2166   struct GAS_MLP_Handle *s = solver;
2167
2168   LOG (GNUNET_ERROR_TYPE_DEBUG,
2169        "Unlocking solver from bulk operation ...\n");
2170   GNUNET_assert (NULL != solver);
2171
2172   if (s->stat_bulk_lock < 1)
2173   {
2174     GNUNET_break (0);
2175     return;
2176   }
2177   s->stat_bulk_lock --;
2178
2179   if (0 < s->stat_bulk_requests)
2180   {
2181     GAS_mlp_solve_problem (solver);
2182     s->stat_bulk_requests= 0;
2183   }
2184 }
2185
2186
2187
2188 /**
2189  * Stop notifying about address and bandwidth changes for this peer
2190  *
2191  * @param solver the MLP handle
2192  * @param peer the peer
2193  */
2194 static void
2195 GAS_mlp_stop_get_preferred_address (void *solver,
2196                                      const struct GNUNET_PeerIdentity *peer)
2197 {
2198   struct GAS_MLP_Handle *mlp = solver;
2199   struct ATS_Peer *p = NULL;
2200
2201   GNUNET_assert (NULL != solver);
2202   GNUNET_assert (NULL != peer);
2203   if (NULL != (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer)))
2204   {
2205     GNUNET_assert (GNUNET_YES ==
2206                    GNUNET_CONTAINER_multipeermap_remove (mlp->requested_peers, peer, p));
2207     GNUNET_free (p);
2208
2209     mlp->stat_mlp_prob_changed = GNUNET_YES;
2210     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
2211     {
2212       GAS_mlp_solve_problem (solver);
2213     }
2214   }
2215 }
2216
2217
2218 /**
2219  * Changes the preferences for a peer in the MLP problem
2220  *
2221  * @param solver the MLP Handle
2222  * @param peer the peer
2223  * @param kind the kind to change the preference
2224  * @param pref_rel the relative score
2225  */
2226 static void
2227 GAS_mlp_address_change_preference (void *solver,
2228                    const struct GNUNET_PeerIdentity *peer,
2229                    enum GNUNET_ATS_PreferenceKind kind,
2230                    double pref_rel)
2231 {
2232   struct GAS_MLP_Handle *mlp = solver;
2233   struct ATS_Peer *p;
2234
2235   LOG (GNUNET_ERROR_TYPE_DEBUG,
2236        "Changing preference for address for peer `%s' to %.2f\n",
2237        GNUNET_i2s(peer),
2238        pref_rel);
2239
2240   GNUNET_STATISTICS_update (mlp->env->stats,
2241                             "# LP address preference changes", 1, GNUNET_NO);
2242   /* Update the constraints with changed preferences */
2243
2244
2245
2246   /* Update relativity constraint c9 */
2247   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer)))
2248   {
2249     LOG (GNUNET_ERROR_TYPE_INFO,
2250          "Updating preference for unknown peer `%s'\n",
2251          GNUNET_i2s(peer));
2252     return;
2253   }
2254
2255   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
2256   {
2257     p->f = get_peer_pref_value (mlp, peer);
2258     mlp_create_problem_update_value (&mlp->p,
2259                                      p->r_c9,
2260                                      mlp->p.c_r,
2261                                      - p->f,
2262                                      __LINE__);
2263
2264     /* Problem size changed: new address for peer with pending request */
2265     mlp->stat_mlp_prob_updated = GNUNET_YES;
2266     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
2267       GAS_mlp_solve_problem (solver);
2268   }
2269 }
2270
2271
2272 /**
2273  * Get application feedback for a peer
2274  *
2275  * @param solver the solver handle
2276  * @param application the application
2277  * @param peer the peer to change the preference for
2278  * @param scope the time interval for this feedback: [now - scope .. now]
2279  * @param kind the kind to change the preference
2280  * @param score the score
2281  */
2282 static void
2283 GAS_mlp_address_preference_feedback (void *solver,
2284                                      struct GNUNET_SERVICE_Client *application,
2285                                      const struct GNUNET_PeerIdentity *peer,
2286                                      const struct GNUNET_TIME_Relative scope,
2287                                      enum GNUNET_ATS_PreferenceKind kind,
2288                                      double score)
2289 {
2290   struct GAS_PROPORTIONAL_Handle *s = solver;
2291
2292   GNUNET_assert (NULL != solver);
2293   GNUNET_assert (NULL != peer);
2294   GNUNET_assert (NULL != s);
2295 }
2296
2297
2298 static int
2299 mlp_free_peers (void *cls,
2300                 const struct GNUNET_PeerIdentity *key, void *value)
2301 {
2302   struct GNUNET_CONTAINER_MultiPeerMap *map = cls;
2303   struct ATS_Peer *p = value;
2304
2305   GNUNET_assert (GNUNET_YES ==
2306                  GNUNET_CONTAINER_multipeermap_remove (map, key, value));
2307   GNUNET_free (p);
2308
2309   return GNUNET_OK;
2310 }
2311
2312
2313 /**
2314  * Shutdown the MLP problem solving component
2315  *
2316  * @param cls the solver handle
2317  * @return NULL
2318  */
2319 void *
2320 libgnunet_plugin_ats_mlp_done (void *cls)
2321 {
2322   struct GNUNET_ATS_SolverFunctions *sf = cls;
2323   struct GAS_MLP_Handle *mlp = sf->cls;
2324
2325   LOG (GNUNET_ERROR_TYPE_DEBUG,
2326        "Shutting down mlp solver\n");
2327   mlp_delete_problem (mlp);
2328   GNUNET_CONTAINER_multipeermap_iterate (mlp->requested_peers,
2329                                          &mlp_free_peers,
2330                                          mlp->requested_peers);
2331   GNUNET_CONTAINER_multipeermap_destroy (mlp->requested_peers);
2332   mlp->requested_peers = NULL;
2333
2334   /* Clean up GLPK environment */
2335   glp_free_env();
2336   GNUNET_free (mlp);
2337
2338   LOG (GNUNET_ERROR_TYPE_DEBUG,
2339        "Shutdown down of mlp solver complete\n");
2340   return NULL;
2341 }
2342
2343
2344 void *
2345 libgnunet_plugin_ats_mlp_init (void *cls)
2346 {
2347   static struct GNUNET_ATS_SolverFunctions sf;
2348   struct GNUNET_ATS_PluginEnvironment *env = cls;
2349   struct GAS_MLP_Handle * mlp = GNUNET_new (struct GAS_MLP_Handle);
2350   float f_tmp;
2351   unsigned long long tmp;
2352   unsigned int b_min;
2353   unsigned int n_min;
2354   int c;
2355   char *outputformat;
2356
2357   struct GNUNET_TIME_Relative max_duration;
2358   long long unsigned int max_iterations;
2359
2360   /* Init GLPK environment */
2361   int res = glp_init_env();
2362   switch (res) {
2363     case 0:
2364       LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
2365           "initialization successful");
2366       break;
2367     case 1:
2368       LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
2369           "environment is already initialized");
2370       break;
2371     case 2:
2372       LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
2373           "initialization failed (insufficient memory)");
2374       GNUNET_free(mlp);
2375       return NULL;
2376       break;
2377     case 3:
2378       LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
2379           "initialization failed (unsupported programming model)");
2380       GNUNET_free(mlp);
2381       return NULL;
2382       break;
2383     default:
2384       break;
2385   }
2386
2387   mlp->opt_dump_problem_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2388      "ats", "MLP_DUMP_PROBLEM_ALL");
2389   if (GNUNET_SYSERR == mlp->opt_dump_problem_all)
2390    mlp->opt_dump_problem_all = GNUNET_NO;
2391
2392   mlp->opt_dump_solution_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2393      "ats", "MLP_DUMP_SOLUTION_ALL");
2394   if (GNUNET_SYSERR == mlp->opt_dump_solution_all)
2395    mlp->opt_dump_solution_all = GNUNET_NO;
2396
2397   mlp->opt_dump_problem_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2398      "ats", "MLP_DUMP_PROBLEM_ON_FAIL");
2399   if (GNUNET_SYSERR == mlp->opt_dump_problem_on_fail)
2400    mlp->opt_dump_problem_on_fail = GNUNET_NO;
2401
2402   mlp->opt_dump_solution_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2403      "ats", "MLP_DUMP_SOLUTION_ON_FAIL");
2404   if (GNUNET_SYSERR == mlp->opt_dump_solution_on_fail)
2405    mlp->opt_dump_solution_on_fail = GNUNET_NO;
2406
2407   mlp->opt_dbg_glpk_verbose = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2408      "ats", "MLP_DBG_GLPK_VERBOSE");
2409   if (GNUNET_SYSERR == mlp->opt_dbg_glpk_verbose)
2410    mlp->opt_dbg_glpk_verbose = GNUNET_NO;
2411
2412   mlp->opt_dbg_feasibility_only = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2413      "ats", "MLP_DBG_FEASIBILITY_ONLY");
2414   if (GNUNET_SYSERR == mlp->opt_dbg_feasibility_only)
2415    mlp->opt_dbg_feasibility_only = GNUNET_NO;
2416   if (GNUNET_YES == mlp->opt_dbg_feasibility_only)
2417     LOG (GNUNET_ERROR_TYPE_WARNING,
2418         "MLP solver is configured to check feasibility only!\n");
2419
2420   mlp->opt_dbg_autoscale_problem = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2421      "ats", "MLP_DBG_AUTOSCALE_PROBLEM");
2422   if (GNUNET_SYSERR == mlp->opt_dbg_autoscale_problem)
2423    mlp->opt_dbg_autoscale_problem = GNUNET_NO;
2424   if (GNUNET_YES == mlp->opt_dbg_autoscale_problem)
2425     LOG (GNUNET_ERROR_TYPE_WARNING,
2426         "MLP solver is configured automatically scale the problem!\n");
2427
2428   mlp->opt_dbg_intopt_presolver = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2429      "ats", "MLP_DBG_INTOPT_PRESOLVE");
2430   if (GNUNET_SYSERR == mlp->opt_dbg_intopt_presolver)
2431    mlp->opt_dbg_intopt_presolver = GNUNET_NO;
2432   if (GNUNET_YES == mlp->opt_dbg_intopt_presolver)
2433     LOG (GNUNET_ERROR_TYPE_WARNING,
2434         "MLP solver is configured use the mlp presolver\n");
2435
2436   mlp->opt_dbg_optimize_diversity = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2437      "ats", "MLP_DBG_OPTIMIZE_DIVERSITY");
2438   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_diversity)
2439    mlp->opt_dbg_optimize_diversity = GNUNET_YES;
2440   if (GNUNET_NO == mlp->opt_dbg_optimize_diversity)
2441     LOG (GNUNET_ERROR_TYPE_WARNING,
2442         "MLP solver is not optimizing for diversity\n");
2443
2444   mlp->opt_dbg_optimize_relativity= GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2445      "ats", "MLP_DBG_OPTIMIZE_RELATIVITY");
2446   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_relativity)
2447    mlp->opt_dbg_optimize_relativity = GNUNET_YES;
2448   if (GNUNET_NO == mlp->opt_dbg_optimize_relativity)
2449     LOG (GNUNET_ERROR_TYPE_WARNING,
2450         "MLP solver is not optimizing for relativity\n");
2451
2452   mlp->opt_dbg_optimize_quality = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2453      "ats", "MLP_DBG_OPTIMIZE_QUALITY");
2454   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_quality)
2455    mlp->opt_dbg_optimize_quality = GNUNET_YES;
2456   if (GNUNET_NO == mlp->opt_dbg_optimize_quality)
2457     LOG (GNUNET_ERROR_TYPE_WARNING,
2458         "MLP solver is not optimizing for quality\n");
2459
2460   mlp->opt_dbg_optimize_utility = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2461      "ats", "MLP_DBG_OPTIMIZE_UTILITY");
2462   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_utility)
2463    mlp->opt_dbg_optimize_utility = GNUNET_YES;
2464   if (GNUNET_NO == mlp->opt_dbg_optimize_utility)
2465     LOG (GNUNET_ERROR_TYPE_WARNING,
2466         "MLP solver is not optimizing for utility\n");
2467
2468   if ( (GNUNET_NO == mlp->opt_dbg_optimize_utility) &&
2469        (GNUNET_NO == mlp->opt_dbg_optimize_quality) &&
2470        (GNUNET_NO == mlp->opt_dbg_optimize_relativity) &&
2471        (GNUNET_NO == mlp->opt_dbg_optimize_utility) &&
2472        (GNUNET_NO == mlp->opt_dbg_feasibility_only))
2473   {
2474     LOG (GNUNET_ERROR_TYPE_ERROR,
2475         _("MLP solver is not optimizing for anything, changing to feasibility check\n"));
2476     mlp->opt_dbg_feasibility_only = GNUNET_YES;
2477   }
2478
2479   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (env->cfg,
2480      "ats", "MLP_LOG_FORMAT", &outputformat))
2481    mlp->opt_log_format = MLP_CPLEX;
2482   else
2483   {
2484     GNUNET_STRINGS_utf8_toupper(outputformat, outputformat);
2485     if (0 == strcmp (outputformat, "MPS"))
2486     {
2487       mlp->opt_log_format = MLP_MPS;
2488     }
2489     else if (0 == strcmp (outputformat, "CPLEX"))
2490     {
2491       mlp->opt_log_format = MLP_CPLEX;
2492     }
2493     else if (0 == strcmp (outputformat, "GLPK"))
2494     {
2495       mlp->opt_log_format = MLP_GLPK;
2496     }
2497     else
2498     {
2499       LOG (GNUNET_ERROR_TYPE_WARNING,
2500           "Invalid log format `%s' in configuration, using CPLEX!\n",
2501           outputformat);
2502       mlp->opt_log_format = MLP_CPLEX;
2503     }
2504     GNUNET_free (outputformat);
2505   }
2506
2507   mlp->pv.BIG_M = (double) BIG_M_VALUE;
2508
2509   mlp->pv.mip_gap = (double) 0.0;
2510   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2511       "MLP_MAX_MIP_GAP", &f_tmp))
2512   {
2513     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2514     {
2515       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2516           "MIP gap", f_tmp);
2517     }
2518     else
2519     {
2520       mlp->pv.mip_gap = f_tmp;
2521       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2522           "MIP gap", f_tmp);
2523     }
2524   }
2525
2526   mlp->pv.lp_mip_gap = (double) 0.0;
2527   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2528       "MLP_MAX_LP_MIP_GAP", &f_tmp))
2529   {
2530     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2531     {
2532       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2533           "LP/MIP", f_tmp);
2534     }
2535     else
2536     {
2537       mlp->pv.lp_mip_gap = f_tmp;
2538       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2539           "LP/MIP", f_tmp);
2540     }
2541   }
2542
2543   /* Get timeout for iterations */
2544   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(env->cfg, "ats",
2545       "MLP_MAX_DURATION", &max_duration))
2546   {
2547     max_duration = MLP_MAX_EXEC_DURATION;
2548   }
2549
2550   /* Get maximum number of iterations */
2551   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats",
2552       "MLP_MAX_ITERATIONS", &max_iterations))
2553   {
2554     max_iterations = MLP_MAX_ITERATIONS;
2555   }
2556
2557   /* Get diversity coefficient from configuration */
2558   mlp->pv.co_D = MLP_DEFAULT_D;
2559   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2560       "MLP_COEFFICIENT_D", &f_tmp))
2561   {
2562     if ((f_tmp < 0.0))
2563     {
2564       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2565           "MLP_COEFFICIENT_D", f_tmp);
2566     }
2567     else
2568     {
2569       mlp->pv.co_D = f_tmp;
2570       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2571           "MLP_COEFFICIENT_D", f_tmp);
2572     }
2573   }
2574
2575   /* Get relativity coefficient from configuration */
2576   mlp->pv.co_R = MLP_DEFAULT_R;
2577   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2578       "MLP_COEFFICIENT_R", &f_tmp))
2579   {
2580     if ((f_tmp < 0.0))
2581     {
2582       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2583           "MLP_COEFFICIENT_R", f_tmp);
2584     }
2585     else
2586     {
2587       mlp->pv.co_R = f_tmp;
2588       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2589           "MLP_COEFFICIENT_R", f_tmp);
2590     }
2591   }
2592
2593
2594   /* Get utilization coefficient from configuration */
2595   mlp->pv.co_U = MLP_DEFAULT_U;
2596   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2597       "MLP_COEFFICIENT_U", &f_tmp))
2598   {
2599     if ((f_tmp < 0.0))
2600     {
2601       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2602           "MLP_COEFFICIENT_U", f_tmp);
2603     }
2604     else
2605     {
2606       mlp->pv.co_U = f_tmp;
2607       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2608           "MLP_COEFFICIENT_U", f_tmp);
2609     }
2610   }
2611
2612   /* Get quality metric coefficients from configuration */
2613   for (c = 0; c < RQ_QUALITY_METRIC_COUNT; c++)
2614   {
2615     /* initialize quality coefficients with default value 1.0 */
2616     mlp->pv.co_Q[c] = MLP_DEFAULT_QUALITY;
2617   }
2618
2619
2620   if (GNUNET_OK ==
2621       GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2622                                            "MLP_COEFFICIENT_QUALITY_DELAY",
2623                                            &tmp))
2624     mlp->pv.co_Q[RQ_QUALITY_METRIC_DELAY] = (double) tmp / 100;
2625   else
2626     mlp->pv.co_Q[RQ_QUALITY_METRIC_DELAY] = MLP_DEFAULT_QUALITY;
2627
2628   if (GNUNET_OK ==
2629       GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2630                                            "MLP_COEFFICIENT_QUALITY_DISTANCE",
2631                                            &tmp))
2632     mlp->pv.co_Q[RQ_QUALITY_METRIC_DISTANCE] = (double) tmp / 100;
2633   else
2634     mlp->pv.co_Q[RQ_QUALITY_METRIC_DISTANCE] = MLP_DEFAULT_QUALITY;
2635
2636   /* Get minimum bandwidth per used address from configuration */
2637   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2638                                                       "MLP_MIN_BANDWIDTH",
2639                                                       &tmp))
2640     b_min = tmp;
2641   else
2642   {
2643     b_min = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
2644   }
2645
2646   /* Get minimum number of connections from configuration */
2647   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2648                                                       "MLP_MIN_CONNECTIONS",
2649                                                       &tmp))
2650     n_min = tmp;
2651   else
2652     n_min = MLP_DEFAULT_MIN_CONNECTIONS;
2653
2654   /* Init network quotas */
2655   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
2656   {
2657     mlp->pv.quota_index[c] = c;
2658     mlp->pv.quota_out[c] = env->out_quota[c];
2659     mlp->pv.quota_in[c] = env->in_quota[c];
2660
2661     LOG (GNUNET_ERROR_TYPE_INFO,
2662          "Quota for network `%s' (in/out) %llu/%llu\n",
2663          GNUNET_ATS_print_network_type (c),
2664          mlp->pv.quota_out[c],
2665          mlp->pv.quota_in[c]);
2666     /* Check if defined quota could make problem unsolvable */
2667     if ((n_min * b_min) > mlp->pv.quota_out[c])
2668     {
2669       LOG (GNUNET_ERROR_TYPE_INFO,
2670            _("Adjusting inconsistent outbound quota configuration for network `%s', is %llu must be at least %llu\n"),
2671            GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2672            mlp->pv.quota_out[c],
2673            (n_min * b_min));
2674       mlp->pv.quota_out[c] = (n_min * b_min);
2675     }
2676     if ((n_min * b_min) > mlp->pv.quota_in[c])
2677     {
2678       LOG (GNUNET_ERROR_TYPE_INFO,
2679            _("Adjusting inconsistent inbound quota configuration for network `%s', is %llu must be at least %llu\n"),
2680            GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2681            mlp->pv.quota_in[c],
2682            (n_min * b_min));
2683       mlp->pv.quota_in[c] = (n_min * b_min);
2684     }
2685     /* Check if bandwidth is too big to make problem solvable */
2686     if (mlp->pv.BIG_M < mlp->pv.quota_out[c])
2687     {
2688       LOG (GNUNET_ERROR_TYPE_INFO,
2689            _("Adjusting outbound quota configuration for network `%s'from %llu to %.0f\n"),
2690            GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2691            mlp->pv.quota_out[c],
2692            mlp->pv.BIG_M);
2693       mlp->pv.quota_out[c] = mlp->pv.BIG_M ;
2694     }
2695     if (mlp->pv.BIG_M < mlp->pv.quota_in[c])
2696     {
2697       LOG (GNUNET_ERROR_TYPE_INFO,
2698            _("Adjusting inbound quota configuration for network `%s' from %llu to %.0f\n"),
2699            GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2700            mlp->pv.quota_in[c],
2701            mlp->pv.BIG_M);
2702       mlp->pv.quota_in[c] = mlp->pv.BIG_M ;
2703     }
2704   }
2705   mlp->env = env;
2706   sf.cls = mlp;
2707   sf.s_add = &GAS_mlp_address_add;
2708   sf.s_address_update_property = &GAS_mlp_address_property_changed;
2709   sf.s_get = &GAS_mlp_get_preferred_address;
2710   sf.s_get_stop = &GAS_mlp_stop_get_preferred_address;
2711   sf.s_pref = &GAS_mlp_address_change_preference;
2712   sf.s_feedback = &GAS_mlp_address_preference_feedback;
2713   sf.s_del = &GAS_mlp_address_delete;
2714   sf.s_bulk_start = &GAS_mlp_bulk_start;
2715   sf.s_bulk_stop = &GAS_mlp_bulk_stop;
2716
2717   /* Setting MLP Input variables */
2718   mlp->pv.b_min = b_min;
2719   mlp->pv.n_min = n_min;
2720   mlp->pv.m_q = RQ_QUALITY_METRIC_COUNT;
2721   mlp->stat_mlp_prob_changed = GNUNET_NO;
2722   mlp->stat_mlp_prob_updated = GNUNET_NO;
2723   mlp->opt_mlp_auto_solve = GNUNET_YES;
2724   mlp->requested_peers = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
2725   mlp->stat_bulk_requests = 0;
2726   mlp->stat_bulk_lock = 0;
2727
2728   /* Setup GLPK */
2729   /* Redirect GLPK output to GNUnet logging */
2730   glp_term_hook (&mlp_term_hook, (void *) mlp);
2731
2732   /* Init LP solving parameters */
2733   glp_init_smcp(&mlp->control_param_lp);
2734   mlp->control_param_lp.msg_lev = GLP_MSG_OFF;
2735   if (GNUNET_YES == mlp->opt_dbg_glpk_verbose)
2736     mlp->control_param_lp.msg_lev = GLP_MSG_ALL;
2737
2738   mlp->control_param_lp.it_lim = max_iterations;
2739   mlp->control_param_lp.tm_lim = max_duration.rel_value_us / 1000LL;
2740
2741   /* Init MLP solving parameters */
2742   glp_init_iocp(&mlp->control_param_mlp);
2743   /* Setting callback function */
2744   mlp->control_param_mlp.cb_func = &mlp_branch_and_cut_cb;
2745   mlp->control_param_mlp.cb_info = mlp;
2746   mlp->control_param_mlp.msg_lev = GLP_MSG_OFF;
2747   mlp->control_param_mlp.mip_gap = mlp->pv.mip_gap;
2748   if (GNUNET_YES == mlp->opt_dbg_glpk_verbose)
2749     mlp->control_param_mlp.msg_lev = GLP_MSG_ALL;
2750   mlp->control_param_mlp.tm_lim = max_duration.rel_value_us / 1000LL;
2751
2752   LOG (GNUNET_ERROR_TYPE_DEBUG, "solver ready\n");
2753
2754   return &sf;
2755 }
2756
2757 /* end of plugin_ats_mlp.c */