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