-test cleanup
[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 MLP_DEFAULT_D 1.0
46 #define MLP_DEFAULT_R 1.0
47 #define MLP_DEFAULT_U 1.0
48 #define MLP_DEFAULT_QUALITY 1.0
49 #define MLP_DEFAULT_MIN_CONNECTIONS 4
50 #define MLP_DEFAULT_PEER_PREFERENCE 1.0
51
52 #define MLP_NaN -1
53 #define MLP_UNDEFINED 0
54 #define GLP_YES 1.0
55 #define GLP_NO  0.0
56
57 enum MLP_Output_Format
58 {
59   MLP_MPS,
60   MLP_CPLEX,
61   MLP_GLPK
62 };
63
64
65 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   GNUNET_assert (NULL != peer);
1079   if (peer->processed == GNUNET_NO)
1080   {
1081       /* Add peer dependent constraints */
1082       /* Add c2) One address active per peer */
1083       GNUNET_asprintf(&name, "c2_%s", GNUNET_i2s(&address->peer));
1084       peer->r_c2 = mlp_create_problem_create_constraint (p, name, GLP_FX, 1.0, 1.0);
1085       GNUNET_free (name);
1086       if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1087       {
1088         if (GNUNET_YES == mlp->opt_dbg_optimize_relativity)
1089         {
1090           /* Add c9) Relativity */
1091           GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&address->peer));
1092           peer->r_c9 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
1093           GNUNET_free (name);
1094           /* c9) set coefficient */
1095           mlp_create_problem_set_value (p, peer->r_c9, p->c_r, -peer->f , __LINE__);
1096         }
1097       }
1098       peer->processed = GNUNET_YES;
1099   }
1100
1101   /* Reset addresses' solver information */
1102   mlpi->c_b = 0;
1103   mlpi->c_n = 0;
1104   mlpi->n = 0;
1105   mlpi->r_c1 = 0;
1106   mlpi->r_c3 = 0;
1107
1108   /* Add bandwidth column */
1109   GNUNET_asprintf (&name, "b_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
1110   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1111   {
1112     mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0);
1113   }
1114   else
1115   {
1116     /* Maximize for bandwidth assignment in feasibility testing */
1117     mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 1.0);
1118   }
1119   GNUNET_free (name);
1120
1121   /* Add address active column */
1122   GNUNET_asprintf (&name, "n_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address);
1123   mlpi->c_n = mlp_create_problem_create_column (p, name, GLP_IV, GLP_DB, 0.0, 1.0, 0.0);
1124   GNUNET_free (name);
1125
1126   /* Add address dependent constraints */
1127   /* Add c1) bandwidth capping: b_t  + (-M) * n_t <= 0 */
1128   GNUNET_asprintf(&name, "c1_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
1129   mlpi->r_c1 = mlp_create_problem_create_constraint (p, name, GLP_UP, 0.0, 0.0);
1130   GNUNET_free (name);
1131   /*  c1) set b = 1 coefficient */
1132   mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_b, 1, __LINE__);
1133   /*  c1) set n = - min (M, quota) coefficient */
1134   cur_bigm = (double) mlp->pv.quota_out[addr_net_index];
1135   if (cur_bigm > mlp->pv.BIG_M)
1136     cur_bigm = (double) mlp->pv.BIG_M;
1137   mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_n, -cur_bigm, __LINE__);
1138
1139   /* Add constraint c 3) minimum bandwidth
1140    * b_t + (-n_t * b_min) >= 0
1141    * */
1142   GNUNET_asprintf(&name, "c3_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address);
1143   mlpi->r_c3 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0);
1144   GNUNET_free (name);
1145
1146   /*  c3) set b = 1 coefficient */
1147   mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_b, 1, __LINE__);
1148   /*  c3) set n = -b_min coefficient */
1149   mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_n, - ((double )mlp->pv.b_min), __LINE__);
1150
1151
1152   /* Set coefficient entries in invariant rows */
1153
1154   /* Feasbility */
1155
1156   /* c 4) minimum connections */
1157   mlp_create_problem_set_value (p, p->r_c4, mlpi->c_n, 1, __LINE__);
1158   /* c 2) 1 address peer peer */
1159   mlp_create_problem_set_value (p, peer->r_c2, mlpi->c_n, 1, __LINE__);
1160   /* c 10) obey network specific quotas
1161    * (1)*b_1 + ... + (1)*b_m <= quota_n
1162    */
1163   mlp_create_problem_set_value (p, p->r_quota[addr_net_index], mlpi->c_b, 1, __LINE__);
1164
1165   /* Optimality */
1166   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1167   {
1168     /* c 6) maximize diversity */
1169     mlp_create_problem_set_value (p, p->r_c6, mlpi->c_n, 1, __LINE__);
1170     /* c 9) relativity */
1171     if (GNUNET_YES == mlp->opt_dbg_optimize_relativity)
1172       mlp_create_problem_set_value (p, peer->r_c9, mlpi->c_b, 1, __LINE__);
1173     /* c 8) utility */
1174     if (GNUNET_YES == mlp->opt_dbg_optimize_utility)
1175       mlp_create_problem_set_value (p, p->r_c8, mlpi->c_b, 1, __LINE__);
1176     /* c 7) Optimize quality */
1177     /* For all quality metrics, set quality of this address */
1178     if (GNUNET_YES == mlp->opt_dbg_optimize_quality)
1179     {
1180       props = mlp->get_properties (mlp->get_properties_cls, address);
1181       for (c = 0; c < mlp->pv.m_q; c++)
1182       {
1183         if ((props[c] < 1.0) && (props[c] > 2.0))
1184         {
1185           fprintf (stderr, "PROP == %.3f \t ", props[c]);
1186           GNUNET_break (0);
1187         }
1188         mlp_create_problem_set_value (p, p->r_q[c], mlpi->c_b, props[c], __LINE__);
1189       }
1190     }
1191   }
1192
1193   return GNUNET_OK;
1194 }
1195
1196
1197 /**
1198  * Create the invariant columns c4, c6, c10, c8, c7
1199  */
1200 static void
1201 mlp_create_problem_add_invariant_rows (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
1202 {
1203   int c;
1204
1205   /* Feasibility */
1206
1207   /* Row for c4) minimum connection */
1208   /* Number of minimum connections is min(|Peers|, n_min) */
1209   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);
1210
1211   /* Rows for c 10) Enforce network quotas */
1212   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
1213   {
1214     char * text;
1215     GNUNET_asprintf(&text, "c10_quota_ats_%s",
1216         GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]));
1217     p->r_quota[c] = mlp_create_problem_create_constraint (p, text, GLP_DB, 0.0, mlp->pv.quota_out[c]);
1218     GNUNET_free (text);
1219   }
1220
1221   /* Optimality */
1222   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1223   {
1224     char *name;
1225     /* Add row for c6) Maximize for diversity */
1226     if (GNUNET_YES == mlp->opt_dbg_optimize_diversity)
1227     {
1228       p->r_c6 = mlp_create_problem_create_constraint (p, "c6", GLP_FX, 0.0, 0.0);
1229       /* Set c6 ) Setting -D */
1230       mlp_create_problem_set_value (p, p->r_c6, p->c_d, -1, __LINE__);
1231     }
1232
1233     /* Adding rows for c 8) Maximize utility */
1234     if (GNUNET_YES == mlp->opt_dbg_optimize_utility)
1235     {
1236       p->r_c8 = mlp_create_problem_create_constraint (p, "c8", GLP_FX, 0.0, 0.0);
1237       /* -u */
1238       mlp_create_problem_set_value (p, p->r_c8, p->c_u, -1, __LINE__);
1239     }
1240
1241     /* For all quality metrics:
1242      * c 7) Maximize quality, austerity */
1243     if (GNUNET_YES == mlp->opt_dbg_optimize_quality)
1244     {
1245       for (c = 0; c < mlp->pv.m_q; c++)
1246       {
1247         GNUNET_asprintf(&name, "c7_q%i_%s", c, mlp_ats_to_string(mlp->pv.q[c]));
1248         p->r_q[c] = mlp_create_problem_create_constraint (p, name, GLP_FX, 0.0, 0.0);
1249         GNUNET_free (name);
1250         mlp_create_problem_set_value (p, p->r_q[c], p->c_q[c], -1, __LINE__);
1251       }
1252     }
1253   }
1254 }
1255
1256
1257 /**
1258  * Create the invariant columns d, u, r, q0 ... qm
1259  */
1260 static void
1261 mlp_create_problem_add_invariant_columns (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p)
1262 {
1263   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
1264   {
1265     char *name;
1266     int c;
1267
1268     /* Diversity d column  */
1269     if (GNUNET_YES == mlp->opt_dbg_optimize_diversity)
1270       p->c_d = mlp_create_problem_create_column (p, "d", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_D);
1271
1272     /* Utilization u column  */
1273     if (GNUNET_YES == mlp->opt_dbg_optimize_utility)
1274       p->c_u = mlp_create_problem_create_column (p, "u", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_U);
1275
1276     /* Relativity r column  */
1277     if (GNUNET_YES == mlp->opt_dbg_optimize_relativity)
1278       p->c_r = mlp_create_problem_create_column (p, "r", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_R);
1279
1280     /* Quality metric columns */
1281     if (GNUNET_YES == mlp->opt_dbg_optimize_quality)
1282     {
1283       for (c = 0; c < mlp->pv.m_q; c++)
1284       {
1285         GNUNET_asprintf (&name, "q_%u", mlp->pv.q[c]);
1286         p->c_q[c] = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_Q[c]);
1287         GNUNET_free (name);
1288       }
1289     }
1290   }
1291 }
1292
1293
1294 /**
1295  * Create the MLP problem
1296  *
1297  * @param mlp the MLP handle
1298  * @return #GNUNET_OK or #GNUNET_SYSERR
1299  */
1300 static int
1301 mlp_create_problem (struct GAS_MLP_Handle *mlp)
1302 {
1303   struct MLP_Problem *p = &mlp->p;
1304   int res = GNUNET_OK;
1305
1306   GNUNET_assert (p->prob == NULL);
1307   GNUNET_assert (p->ia == NULL);
1308   GNUNET_assert (p->ja == NULL);
1309   GNUNET_assert (p->ar == NULL);
1310   /* Reset MLP problem struct */
1311
1312   /* create the glpk problem */
1313   p->prob = glp_create_prob ();
1314   GNUNET_assert (NULL != p->prob);
1315   p->num_peers = mlp_create_problem_count_peers (mlp->requested_peers, mlp->addresses);
1316   p->num_addresses = mlp_create_problem_count_addresses (mlp->requested_peers, mlp->addresses);
1317
1318   /* Create problem matrix: 10 * #addresses + #q * #addresses + #q, + #peer + 2 + 1 */
1319   p->num_elements = (10 * p->num_addresses + mlp->pv.m_q * p->num_addresses +
1320       mlp->pv.m_q + p->num_peers + 2 + 1);
1321   LOG (GNUNET_ERROR_TYPE_DEBUG,
1322        "Rebuilding problem for %u peer(s) and %u addresse(s) and %u quality metrics == %u elements\n",
1323        p->num_peers,
1324        p->num_addresses,
1325        mlp->pv.m_q,
1326        p->num_elements);
1327
1328   /* Set a problem name */
1329   glp_set_prob_name (p->prob, "GNUnet ATS bandwidth distribution");
1330   /* Set optimization direction to maximize */
1331   glp_set_obj_dir (p->prob, GLP_MAX);
1332
1333   /* Create problem matrix */
1334   /* last +1 caused by glpk index starting with one: [1..elements]*/
1335   p->ci = 1;
1336   /* row index */
1337   p->ia = GNUNET_malloc (p->num_elements * sizeof (int));
1338   /* column index */
1339   p->ja = GNUNET_malloc (p->num_elements * sizeof (int));
1340   /* coefficient */
1341   p->ar = GNUNET_malloc (p->num_elements * sizeof (double));
1342
1343   if ((NULL == p->ia) || (NULL == p->ja) || (NULL == p->ar))
1344   {
1345       LOG (GNUNET_ERROR_TYPE_ERROR, _("Problem size too large, cannot allocate memory!\n"));
1346       return GNUNET_SYSERR;
1347   }
1348
1349   /* Adding invariant columns */
1350   mlp_create_problem_add_invariant_columns (mlp, p);
1351
1352   /* Adding address independent constraint rows */
1353   mlp_create_problem_add_invariant_rows (mlp, p);
1354
1355   /* Adding address dependent columns constraint rows */
1356   GNUNET_CONTAINER_multipeermap_iterate (mlp->addresses,
1357                                          &mlp_create_problem_add_address_information,
1358                                          mlp);
1359
1360   /* Load the matrix */
1361   LOG (GNUNET_ERROR_TYPE_DEBUG, "Loading matrix\n");
1362   glp_load_matrix(p->prob, (p->ci)-1, p->ia, p->ja, p->ar);
1363   if (GNUNET_YES == mlp->opt_dbg_autoscale_problem)
1364   {
1365     glp_scale_prob (p->prob, GLP_SF_AUTO);
1366   }
1367
1368   return res;
1369 }
1370
1371
1372 /**
1373  * Solves the LP problem
1374  *
1375  * @param mlp the MLP Handle
1376  * @return #GNUNET_OK if could be solved, #GNUNET_SYSERR on failure
1377  */
1378 static int
1379 mlp_solve_lp_problem (struct GAS_MLP_Handle *mlp)
1380 {
1381   int res = 0;
1382   int res_status = 0;
1383   res = glp_simplex(mlp->p.prob, &mlp->control_param_lp);
1384   if (0 == res)
1385     LOG(GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem: %s\n",
1386         mlp_solve_to_string (res));
1387   else
1388     LOG(GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem failed: %s\n",
1389         mlp_solve_to_string (res));
1390
1391   /* Analyze problem status  */
1392   res_status = glp_get_status (mlp->p.prob);
1393   switch (res_status) {
1394     case GLP_OPT: /* solution is optimal */
1395       LOG (GNUNET_ERROR_TYPE_INFO,
1396           "Solving LP problem: %s, %s\n",
1397           mlp_solve_to_string(res),
1398           mlp_status_to_string(res_status));
1399       return GNUNET_OK;
1400     default:
1401       LOG (GNUNET_ERROR_TYPE_ERROR,
1402           "Solving LP problem failed: %s %s\n",
1403           mlp_solve_to_string(res),
1404           mlp_status_to_string(res_status));
1405       return GNUNET_SYSERR;
1406   }
1407 }
1408
1409
1410 /**
1411  * Propagates the results when MLP problem was solved
1412  *
1413  * @param cls the MLP handle
1414  * @param key the peer identity
1415  * @param value the address
1416  * @return #GNUNET_OK to continue
1417  */
1418 static int
1419 mlp_propagate_results (void *cls,
1420                        const struct GNUNET_PeerIdentity *key,
1421                        void *value)
1422 {
1423   struct GAS_MLP_Handle *mlp = cls;
1424   struct ATS_Address *address;
1425   struct MLP_information *mlpi;
1426   double mlp_bw_in = MLP_NaN;
1427   double mlp_bw_out = MLP_NaN;
1428   double mlp_use = MLP_NaN;
1429
1430   /* Check if we have to add this peer due to a pending request */
1431   if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mlp->requested_peers,
1432                                                            key))
1433   {
1434     return GNUNET_OK;
1435   }
1436   address = value;
1437   GNUNET_assert (address->solver_information != NULL);
1438   mlpi = address->solver_information;
1439
1440   mlp_bw_in = glp_mip_col_val(mlp->p.prob, mlpi->c_b);/* FIXME */
1441   if (mlp_bw_in > (double) UINT32_MAX)
1442   {
1443       LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
1444       mlp_bw_in = (double) UINT32_MAX;
1445   }
1446   mlp_bw_out = glp_mip_col_val(mlp->p.prob, mlpi->c_b);
1447   if (mlp_bw_out > (double) UINT32_MAX)
1448   {
1449       LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" );
1450       mlp_bw_out = (double) UINT32_MAX;
1451   }
1452   mlp_use = glp_mip_col_val(mlp->p.prob, mlpi->c_n);
1453
1454   /*
1455    * Debug: solution
1456    * LOG (GNUNET_ERROR_TYPE_INFO, "MLP result address: `%s' `%s' length %u session %u, mlp use %.3f\n",
1457    *    GNUNET_i2s(&address->peer), address->plugin,
1458    *    address->addr_len, address->session_id);
1459    */
1460
1461   if (GLP_YES == mlp_use)
1462   {
1463     /* This address was selected by the solver to be used */
1464     mlpi->n = GNUNET_YES;
1465     if (GNUNET_NO == address->active)
1466     {
1467             /* Address was not used before, enabling address */
1468       LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : enabling address\n",
1469           (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1470       address->active = GNUNET_YES;
1471       address->assigned_bw_in = mlp_bw_in;
1472       mlpi->b_in = mlp_bw_in;
1473       address->assigned_bw_out = mlp_bw_out;
1474       mlpi->b_out = mlp_bw_out;
1475       if ((NULL == mlp->exclude_peer) || (0 != memcmp (&address->peer, mlp->exclude_peer, sizeof (address->peer))))
1476         mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
1477       return GNUNET_OK;
1478     }
1479     else if (GNUNET_YES == address->active)
1480     {
1481       /* Address was used before, check for bandwidth change */
1482       if ((mlp_bw_out != address->assigned_bw_out) ||
1483               (mlp_bw_in != address->assigned_bw_in))
1484       {
1485           LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : bandwidth changed\n",
1486               (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1487           address->assigned_bw_in = mlp_bw_in;
1488           mlpi->b_in = mlp_bw_in;
1489           address->assigned_bw_out = mlp_bw_out;
1490           mlpi->b_out = mlp_bw_out;
1491           if ((NULL == mlp->exclude_peer) || (0 != memcmp (&address->peer, mlp->exclude_peer, sizeof (address->peer))))
1492             mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
1493           return GNUNET_OK;
1494       }
1495     }
1496     else
1497       GNUNET_break (0);
1498   }
1499   else if (GLP_NO == mlp_use)
1500   {
1501     /* This address was selected by the solver to be not used */
1502     mlpi->n = GNUNET_NO;
1503     if (GNUNET_NO == address->active)
1504     {
1505       /* Address was not used before, nothing to do */
1506       LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : no change\n",
1507           (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1508       return GNUNET_OK;
1509     }
1510     else if (GNUNET_YES == address->active)
1511     {
1512     /* Address was used before, disabling address */
1513     LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : disabling address\n",
1514         (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out);
1515       address->active = GNUNET_NO;
1516       /* Set bandwidth to 0 */
1517       address->assigned_bw_in = 0;
1518       mlpi->b_in = 0;
1519       address->assigned_bw_out = 0;
1520       mlpi->b_out = 0;
1521       return GNUNET_OK;
1522     }
1523     else
1524       GNUNET_break (0);
1525   }
1526   else
1527     GNUNET_break (0);
1528
1529   return GNUNET_OK;
1530 }
1531
1532
1533 static void
1534 notify (struct GAS_MLP_Handle *mlp,
1535         enum GAS_Solver_Operation op,
1536         enum GAS_Solver_Status stat,
1537         enum GAS_Solver_Additional_Information add)
1538 {
1539   if (NULL != mlp->env->info_cb)
1540     mlp->env->info_cb (mlp->env->info_cb_cls, op, stat, add);
1541 }
1542
1543
1544 static void
1545 mlp_branch_and_cut_cb (glp_tree *tree, void *info)
1546 {
1547   struct GAS_MLP_Handle *mlp = info;
1548   double mlp_obj = 0;
1549
1550   switch (glp_ios_reason (tree))
1551   {
1552     case GLP_ISELECT:
1553         /* Do nothing here */
1554       break;
1555     case GLP_IPREPRO:
1556         /* Do nothing here */
1557       break;
1558     case GLP_IROWGEN:
1559         /* Do nothing here */
1560       break;
1561     case GLP_IHEUR:
1562         /* Do nothing here */
1563       break;
1564     case GLP_ICUTGEN:
1565         /* Do nothing here */
1566       break;
1567     case GLP_IBRANCH:
1568         /* Do nothing here */
1569       break;
1570     case GLP_IBINGO:
1571         /* A better solution was found  */
1572       mlp->ps.mlp_gap = glp_ios_mip_gap (tree);
1573       mlp_obj = glp_mip_obj_val (mlp->p.prob);
1574       mlp->ps.lp_mlp_gap = (abs(mlp_obj - mlp->ps.lp_objective_value)) / (abs(mlp_obj) + DBL_EPSILON);
1575
1576       LOG (GNUNET_ERROR_TYPE_INFO,
1577           "Found better integer solution, current gaps: %.3f <= %.3f, %.3f <= %.3f\n",
1578           mlp->ps.mlp_gap, mlp->pv.mip_gap,
1579           mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap);
1580
1581       if (mlp->ps.mlp_gap <= mlp->pv.mip_gap)
1582       {
1583         LOG (GNUNET_ERROR_TYPE_INFO,
1584           "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n",
1585           mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap);
1586         glp_ios_terminate (tree);
1587       }
1588
1589       if (mlp->ps.lp_mlp_gap <= mlp->pv.lp_mip_gap)
1590       {
1591         LOG (GNUNET_ERROR_TYPE_INFO,
1592           "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n",
1593           mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap);
1594         glp_ios_terminate (tree);
1595       }
1596
1597       break;
1598     default:
1599       break;
1600   }
1601   //GNUNET_break (0);
1602 }
1603
1604
1605 /**
1606  * Solves the MLP problem
1607  *
1608  * @param solver the MLP Handle
1609  * @return #GNUNET_OK if could be solved, #GNUNET_SYSERR on failure
1610  */
1611 static int
1612 GAS_mlp_solve_problem (void *solver)
1613 {
1614   struct GAS_MLP_Handle *mlp = solver;
1615   char *filename;
1616   int res_lp = 0;
1617   int mip_res = 0;
1618   int mip_status = 0;
1619
1620   struct GNUNET_TIME_Absolute start_total;
1621   struct GNUNET_TIME_Absolute start_cur_op;
1622   struct GNUNET_TIME_Relative dur_total;
1623   struct GNUNET_TIME_Relative dur_setup;
1624   struct GNUNET_TIME_Relative dur_lp;
1625   struct GNUNET_TIME_Relative dur_mlp;
1626
1627   GNUNET_assert(NULL != solver);
1628
1629   if (GNUNET_YES == mlp->stat_bulk_lock)
1630     {
1631       mlp->stat_bulk_requests++;
1632       return GNUNET_NO;
1633     }
1634   notify(mlp, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS,
1635       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1636   start_total = GNUNET_TIME_absolute_get();
1637
1638   if (0 == GNUNET_CONTAINER_multipeermap_size(mlp->requested_peers))
1639     {
1640       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1641       return GNUNET_OK; /* No pending requests */
1642     }
1643   if (0 == GNUNET_CONTAINER_multipeermap_size(mlp->addresses))
1644     {
1645       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1646       return GNUNET_OK; /* No addresses available */
1647     }
1648
1649   if ((GNUNET_NO == mlp->stat_mlp_prob_changed)
1650       && (GNUNET_NO == mlp->stat_mlp_prob_updated))
1651     {
1652       LOG(GNUNET_ERROR_TYPE_DEBUG, "No changes to problem\n");
1653       notify(mlp, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS, GAS_INFO_NONE);
1654       return GNUNET_OK;
1655     }
1656   if (GNUNET_YES == mlp->stat_mlp_prob_changed)
1657   {
1658     LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem size changed, rebuilding\n");
1659     notify(mlp, GAS_OP_SOLVE_SETUP_START, GAS_STAT_SUCCESS, GAS_INFO_FULL);
1660     mlp_delete_problem(mlp);
1661     if (GNUNET_SYSERR == mlp_create_problem(mlp))
1662       {
1663         notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_FAIL, GAS_INFO_FULL);
1664         return GNUNET_SYSERR;
1665       }
1666     notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_SUCCESS, GAS_INFO_FULL);
1667     if (GNUNET_NO == mlp->opt_dbg_intopt_presolver)
1668     {
1669     mlp->control_param_lp.presolve = GLP_YES; /* LP presolver, we need lp solution */
1670     mlp->control_param_mlp.presolve = GNUNET_NO; /* No presolver, we have LP solution */
1671     }
1672     else
1673     {
1674       mlp->control_param_lp.presolve = GNUNET_NO; /* LP presolver, we need lp solution */
1675       mlp->control_param_mlp.presolve = GLP_YES; /* No presolver, we have LP solution */
1676       dur_lp = GNUNET_TIME_UNIT_ZERO;
1677     }
1678   }
1679   else
1680   {
1681     LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem was updated, resolving\n");
1682   }
1683
1684   /* Reset solution info */
1685   mlp->ps.lp_objective_value = 0.0;
1686   mlp->ps.mlp_gap = 1.0;
1687   mlp->ps.mlp_objective_value = 0.0;
1688   mlp->ps.lp_mlp_gap = 0.0;
1689
1690   dur_setup = GNUNET_TIME_absolute_get_duration (start_total);
1691
1692   /* Run LP solver */
1693   if (GNUNET_NO == mlp->opt_dbg_intopt_presolver)
1694   {
1695     notify(mlp, GAS_OP_SOLVE_MLP_LP_START, GAS_STAT_SUCCESS,
1696         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1697     LOG(GNUNET_ERROR_TYPE_DEBUG,
1698         "Running LP solver %s\n",
1699         (GLP_YES == mlp->control_param_lp.presolve)? "with presolver": "without presolver");
1700     start_cur_op = GNUNET_TIME_absolute_get();
1701
1702     /* Solve LP */
1703     /* Only for debugging:
1704      * Always use LP presolver:
1705      * mlp->control_param_lp.presolve = GLP_YES; */
1706     res_lp = mlp_solve_lp_problem(mlp);
1707     if (GNUNET_OK == res_lp)
1708     {
1709         mlp->ps.lp_objective_value = glp_get_obj_val (mlp->p.prob);
1710         LOG (GNUNET_ERROR_TYPE_DEBUG,
1711              "LP solution was: %.3f\n",
1712              mlp->ps.lp_objective_value);
1713     }
1714
1715     dur_lp = GNUNET_TIME_absolute_get_duration (start_cur_op);
1716     notify(mlp, GAS_OP_SOLVE_MLP_LP_STOP,
1717         (GNUNET_OK == res_lp) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1718         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1719   }
1720
1721   if (GNUNET_YES == mlp->opt_dbg_intopt_presolver)
1722     res_lp = GNUNET_OK;
1723
1724   /* Run MLP solver */
1725   if ((GNUNET_OK == res_lp) || (GNUNET_YES == mlp->opt_dbg_intopt_presolver))
1726   {
1727     LOG(GNUNET_ERROR_TYPE_DEBUG, "Running MLP solver \n");
1728     notify(mlp, GAS_OP_SOLVE_MLP_MLP_START, GAS_STAT_SUCCESS,
1729         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1730     start_cur_op = GNUNET_TIME_absolute_get();
1731
1732     /* Solve MIP */
1733
1734     /* Only for debugging, always use LP presolver */
1735     if (GNUNET_YES == mlp->opt_dbg_intopt_presolver)
1736       mlp->control_param_mlp.presolve = GNUNET_YES;
1737
1738     mip_res = glp_intopt (mlp->p.prob, &mlp->control_param_mlp);
1739     switch (mip_res)
1740     {
1741         case 0:
1742           /* Successful */
1743           LOG (GNUNET_ERROR_TYPE_INFO,
1744                "Solving MLP problem: %s\n",
1745                mlp_solve_to_string (mip_res));
1746           break;
1747         case GLP_ETMLIM: /* Time limit reached */
1748         case GLP_EMIPGAP: /* MIP gap tolerance limit reached */
1749         case GLP_ESTOP: /* Solver was instructed to stop*/
1750           /* Semi-successful */
1751           LOG (GNUNET_ERROR_TYPE_INFO,
1752                "Solving MLP problem solution was interupted: %s\n",
1753                mlp_solve_to_string (mip_res));
1754           break;
1755         case GLP_EBOUND:
1756         case GLP_EROOT:
1757         case GLP_ENOPFS:
1758         case GLP_ENODFS:
1759         case GLP_EFAIL:
1760         default:
1761          /* Fail */
1762           LOG (GNUNET_ERROR_TYPE_INFO,
1763               "Solving MLP problem failed: %s\n",
1764               mlp_solve_to_string (mip_res));
1765         break;
1766     }
1767
1768     /* Analyze problem status  */
1769     mip_status = glp_mip_status(mlp->p.prob);
1770     switch (mip_status)
1771     {
1772       case GLP_OPT: /* solution is optimal */
1773         LOG (GNUNET_ERROR_TYPE_WARNING,
1774             "Solution of MLP problem is optimal: %s, %s\n",
1775             mlp_solve_to_string (mip_res),
1776             mlp_status_to_string (mip_status));
1777         mip_res = GNUNET_OK;
1778         break;
1779       case GLP_FEAS: /* solution is feasible but not proven optimal */
1780
1781         if ( (mlp->ps.mlp_gap <= mlp->pv.mip_gap) ||
1782              (mlp->ps.lp_mlp_gap <= mlp->pv.lp_mip_gap) )
1783         {
1784           LOG (GNUNET_ERROR_TYPE_INFO,
1785                  "Solution of MLP problem is feasible and solution within gap constraints: %s, %s\n",
1786                  mlp_solve_to_string (mip_res),
1787                  mlp_status_to_string (mip_status));
1788           mip_res = GNUNET_OK;
1789         }
1790         else
1791         {
1792           LOG (GNUNET_ERROR_TYPE_WARNING,
1793                "Solution of MLP problem is feasible but solution not within gap constraints: %s, %s\n",
1794                mlp_solve_to_string (mip_res),
1795                mlp_status_to_string (mip_status));
1796           mip_res = GNUNET_SYSERR;
1797         }
1798         break;
1799       case GLP_UNDEF: /* Solution undefined */
1800       case GLP_NOFEAS: /* No feasible solution */
1801       default:
1802         LOG (GNUNET_ERROR_TYPE_ERROR,
1803             "Solving MLP problem failed: %s %s\n",
1804             mlp_solve_to_string (mip_res),
1805             mlp_status_to_string (mip_status));
1806         mip_res = GNUNET_SYSERR;
1807         break;
1808     }
1809
1810     dur_mlp = GNUNET_TIME_absolute_get_duration (start_cur_op);
1811     dur_total = GNUNET_TIME_absolute_get_duration (start_total);
1812
1813     notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP,
1814         (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1815         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1816   }
1817   else
1818   {
1819     /* Do not execute mip solver since lp solution is invalid */
1820     dur_mlp = GNUNET_TIME_UNIT_ZERO;
1821     dur_total = GNUNET_TIME_absolute_get_duration (start_total);
1822
1823     notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP, GAS_STAT_FAIL,
1824         (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1825     mip_res = GNUNET_SYSERR;
1826   }
1827
1828   /* Notify about end */
1829   notify(mlp, GAS_OP_SOLVE_STOP,
1830       ((GNUNET_OK == mip_res) && (GNUNET_OK == mip_res)) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1831       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED);
1832
1833   LOG (GNUNET_ERROR_TYPE_DEBUG,
1834       "Execution time for %s solve: (total/setup/lp/mlp) : %llu %llu %llu %llu\n",
1835       (GNUNET_YES == mlp->stat_mlp_prob_changed) ? "full" : "updated",
1836       (unsigned long long) dur_total.rel_value_us,
1837       (unsigned long long) dur_setup.rel_value_us,
1838       (unsigned long long) dur_lp.rel_value_us,
1839       (unsigned long long) dur_mlp.rel_value_us);
1840
1841   /* Save stats */
1842   mlp->ps.lp_res = res_lp;
1843   mlp->ps.mip_res = mip_res;
1844   mlp->ps.lp_presolv = mlp->control_param_lp.presolve;
1845   mlp->ps.mip_presolv = mlp->control_param_mlp.presolve;
1846   mlp->ps.p_cols = glp_get_num_cols(mlp->p.prob);
1847   mlp->ps.p_rows = glp_get_num_rows(mlp->p.prob);
1848   mlp->ps.p_elements = mlp->p.num_elements;
1849
1850   /* Propagate result*/
1851   notify (mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START,
1852       (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1853       GAS_INFO_NONE);
1854   if ((GNUNET_OK == res_lp) && (GNUNET_OK == mip_res))
1855     {
1856       GNUNET_CONTAINER_multipeermap_iterate(mlp->addresses,
1857           &mlp_propagate_results, mlp);
1858     }
1859   notify (mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP,
1860       (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL,
1861       GAS_INFO_NONE);
1862
1863   struct GNUNET_TIME_Absolute time = GNUNET_TIME_absolute_get();
1864   if ( (GNUNET_YES == mlp->opt_dump_problem_all) ||
1865       (mlp->opt_dump_problem_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res))) )
1866     {
1867       /* Write problem to disk */
1868       switch (mlp->opt_log_format) {
1869         case MLP_CPLEX:
1870           GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.cplex", mlp->p.num_peers,
1871               mlp->p.num_addresses, time.abs_value_us);
1872           glp_write_lp (mlp->p.prob, NULL, filename);
1873           break;
1874         case MLP_GLPK:
1875           GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.glpk", mlp->p.num_peers,
1876               mlp->p.num_addresses, time.abs_value_us);
1877           glp_write_prob (mlp->p.prob, 0, filename);
1878           break;
1879         case MLP_MPS:
1880           GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.mps", mlp->p.num_peers,
1881               mlp->p.num_addresses, time.abs_value_us);
1882           glp_write_mps (mlp->p.prob, GLP_MPS_FILE, NULL, filename);
1883           break;
1884         default:
1885           break;
1886       }
1887       LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped problem to file: `%s' \n", filename);
1888       GNUNET_free(filename);
1889     }
1890   if ( (mlp->opt_dump_solution_all) ||
1891       (mlp->opt_dump_solution_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res))) )
1892   {
1893     /* Write solution to disk */
1894     GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.sol", mlp->p.num_peers,
1895         mlp->p.num_addresses, time.abs_value_us);
1896     glp_print_mip(mlp->p.prob, filename);
1897     LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped solution to file: `%s' \n", filename);
1898     GNUNET_free(filename);
1899   }
1900
1901   /* Reset change and update marker */
1902   mlp->control_param_lp.presolve = GLP_NO;
1903   mlp->stat_mlp_prob_updated = GNUNET_NO;
1904   mlp->stat_mlp_prob_changed = GNUNET_NO;
1905
1906   if ((GNUNET_OK == res_lp) && (GNUNET_OK == mip_res))
1907     return GNUNET_OK;
1908   else
1909     return GNUNET_SYSERR;
1910 }
1911
1912 /**
1913  * Add a single address to the solve
1914  *
1915  * @param solver the solver Handle
1916  * @param address the address to add
1917  * @param network network type of this address
1918  */
1919 static void
1920 GAS_mlp_address_add (void *solver,
1921                     struct ATS_Address *address,
1922                     uint32_t network)
1923 {
1924   struct GAS_MLP_Handle *mlp = solver;
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 ==
1946       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
1947                                          &address->peer))
1948   {
1949     /* FIXME: should this be an error? */
1950     LOG (GNUNET_ERROR_TYPE_DEBUG,
1951          "Adding address for peer `%s' without address request\n",
1952          GNUNET_i2s(&address->peer));
1953     return;
1954   }
1955
1956   LOG (GNUNET_ERROR_TYPE_DEBUG,
1957        "Adding address for peer `%s' with address request \n",
1958        GNUNET_i2s(&address->peer));
1959   /* Problem size changed: new address for peer with pending request */
1960   mlp->stat_mlp_prob_changed = GNUNET_YES;
1961   if (GNUNET_YES == mlp->opt_mlp_auto_solve)
1962     GAS_mlp_solve_problem (solver);
1963 }
1964
1965
1966 /**
1967  * Transport properties for this address have changed
1968  *
1969  * @param solver solver handle
1970  * @param address the address
1971  * @param type the ATSI type in HBO
1972  * @param abs_value the absolute value of the property
1973  * @param rel_value the normalized value
1974  */
1975 static void
1976 GAS_mlp_address_property_changed (void *solver,
1977                                   struct ATS_Address *address,
1978                                   uint32_t type,
1979                                   uint32_t abs_value,
1980                                   double rel_value)
1981 {
1982   struct MLP_information *mlpi = address->solver_information;
1983   struct GAS_MLP_Handle *mlp = solver;
1984   int c1;
1985   int type_index;
1986
1987   GNUNET_assert (NULL != solver);
1988   GNUNET_assert (NULL != address);
1989
1990   if (NULL == mlpi)
1991   {
1992       LOG (GNUNET_ERROR_TYPE_INFO,
1993           _("Updating address property `%s' for peer `%s' %p not added before\n"),
1994           GNUNET_ATS_print_property_type (type),
1995           GNUNET_i2s(&address->peer),
1996           address);
1997       GNUNET_break (0);
1998       return;
1999   }
2000
2001   if (NULL ==
2002       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
2003                                          &address->peer))
2004   {
2005     /* Peer is not requested, so no need to update problem */
2006     return;
2007   }
2008   LOG (GNUNET_ERROR_TYPE_INFO, "Updating property `%s' address for peer `%s' to abs %llu rel %.3f\n",
2009       GNUNET_ATS_print_property_type (type),
2010       GNUNET_i2s(&address->peer),
2011       abs_value,
2012       rel_value);
2013
2014   if (GNUNET_YES == mlp->opt_dbg_feasibility_only)
2015     return;
2016
2017   /* Find row index */
2018   type_index = -1;
2019   for (c1 = 0; c1 < mlp->pv.m_q; c1++)
2020   {
2021     if (type == mlp->pv.q[c1])
2022     {
2023       type_index = c1;
2024       break;
2025     }
2026   }
2027   if (-1 == type_index)
2028   {
2029     GNUNET_break (0);
2030     return; /* quality index not found */
2031   }
2032
2033   /* Update c7) [r_q[index]][c_b] = f_q * q_averaged[type_index] */
2034   if (GNUNET_YES == mlp_create_problem_update_value (&mlp->p,
2035       mlp->p.r_q[type_index], mlpi->c_b, rel_value, __LINE__))
2036   {
2037     mlp->stat_mlp_prob_updated = GNUNET_YES;
2038     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
2039       GAS_mlp_solve_problem (solver);
2040   }
2041
2042 }
2043
2044
2045 /**
2046  * Transport session for this address has changed
2047  *
2048  * NOTE: values in addresses are already updated
2049  *
2050  * @param solver solver handle
2051  * @param address the address
2052  * @param cur_session the current session
2053  * @param new_session the new session
2054  */
2055 static void
2056 GAS_mlp_address_session_changed (void *solver,
2057                                   struct ATS_Address *address,
2058                                   uint32_t cur_session,
2059                                   uint32_t new_session)
2060 {
2061   /* Nothing to do here */
2062   return;
2063 }
2064
2065
2066 /**
2067  * Transport session for this address has changed
2068  *
2069  * NOTE: values in addresses are already updated
2070  *
2071  * @param solver solver handle
2072  * @param address the address
2073  * @param in_use usage state
2074  */
2075 static void
2076 GAS_mlp_address_inuse_changed (void *solver,
2077                                struct ATS_Address *address,
2078                                int in_use)
2079 {
2080   /* Nothing to do here */
2081   return;
2082 }
2083
2084
2085 /**
2086  * Network scope for this address has changed
2087  *
2088  * NOTE: values in addresses are already updated
2089  *
2090  * @param solver solver handle
2091  * @param address the address
2092  * @param current_network the current network
2093  * @param new_network the new network
2094  */
2095 static void
2096 GAS_mlp_address_change_network (void *solver,
2097                                struct ATS_Address *address,
2098                                uint32_t current_network,
2099                                uint32_t new_network)
2100 {
2101   struct MLP_information *mlpi = address->solver_information;
2102   struct GAS_MLP_Handle *mlp = solver;
2103   int nets_avail[] = GNUNET_ATS_NetworkType;
2104   int c1;
2105
2106   GNUNET_assert (NULL != solver);
2107   GNUNET_assert (NULL != address);
2108
2109   if (GNUNET_ATS_NetworkTypeCount <= new_network)
2110   {
2111    GNUNET_break (0);
2112    return;
2113   }
2114
2115   if (NULL == mlpi)
2116   {
2117     GNUNET_break (0);
2118     return;
2119   }
2120
2121   if (mlpi->c_b == MLP_UNDEFINED)
2122     return; /* This address is not yet in the matrix*/
2123
2124   if (NULL ==
2125       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
2126                                          &address->peer))
2127   {
2128     /* Peer is not requested, so no need to update problem */
2129     GNUNET_break (0);
2130     return;
2131   }
2132
2133   if (current_network == new_network)
2134   {
2135     GNUNET_break (0);
2136     return;
2137   }
2138
2139   for (c1 = 0; c1 < GNUNET_ATS_NetworkTypeCount ; c1 ++)
2140   {
2141     if (nets_avail[c1] == new_network)
2142       break;
2143   }
2144
2145   if (GNUNET_ATS_NetworkTypeCount == c1)
2146   {
2147     /* Invalid network */
2148     GNUNET_break (0);
2149     return;
2150   }
2151
2152   LOG (GNUNET_ERROR_TYPE_DEBUG, "Updating network for peer `%s' from `%s' to `%s'\n",
2153       GNUNET_i2s (&address->peer),
2154       GNUNET_ATS_print_network_type(current_network),
2155       GNUNET_ATS_print_network_type(new_network));
2156
2157   for (c1 = 0; c1 < GNUNET_ATS_NetworkTypeCount; c1++)
2158   {
2159     if (mlp->pv.quota_index[c1] == current_network)
2160     {
2161       /* Remove from old network */
2162       mlp_create_problem_update_value (&mlp->p,
2163           mlp->p.r_quota[c1],
2164           mlpi->c_b, 0.0, __LINE__);
2165       break;
2166     }
2167   }
2168
2169   for (c1 = 0; c1 < GNUNET_ATS_NetworkTypeCount; c1++)
2170   {
2171     if (mlp->pv.quota_index[c1] == new_network)
2172     {
2173       /* Remove from old network */
2174       if (GNUNET_SYSERR == mlp_create_problem_update_value (&mlp->p,
2175           mlp->p.r_quota[c1],
2176           mlpi->c_b, 1.0, __LINE__))
2177       {
2178         /* This quota did not exist in the problem, recreate */
2179         GNUNET_break (0);
2180       }
2181       break;
2182     }
2183   }
2184
2185   mlp->stat_mlp_prob_changed = GNUNET_YES;
2186 }
2187
2188
2189 /**
2190  * Find the active address in the set of addresses of a peer
2191  * @param cls destination
2192  * @param key peer id
2193  * @param value address
2194  * @return #GNUNET_OK
2195  */
2196 static int
2197 mlp_get_preferred_address_it (void *cls,
2198                               const struct GNUNET_PeerIdentity *key,
2199                               void *value)
2200 {
2201   static int counter = 0;
2202   struct ATS_Address **aa = cls;
2203   struct ATS_Address *addr = value;
2204   struct MLP_information *mlpi = addr->solver_information;
2205
2206   if (mlpi == NULL)
2207     return GNUNET_YES;
2208
2209   /*
2210    * Debug output
2211    * GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2212    *           "MLP [%u] Peer `%s' %s length %u session %u active %s mlp active %s\n",
2213    *           counter, GNUNET_i2s (&addr->peer), addr->plugin, addr->addr_len, addr->session_id,
2214    *           (GNUNET_YES == addr->active) ? "active" : "inactive",
2215    *           (GNUNET_YES == mlpi->n) ? "active" : "inactive");
2216    */
2217
2218   if (GNUNET_YES == mlpi->n)
2219   {
2220
2221     (*aa) = addr;
2222     (*aa)->assigned_bw_in = mlpi->b_in;
2223     (*aa)->assigned_bw_out = mlpi->b_out;
2224     return GNUNET_NO;
2225   }
2226   counter++;
2227   return GNUNET_YES;
2228 }
2229
2230
2231 static double
2232 get_peer_pref_value (struct GAS_MLP_Handle *mlp,
2233                      const struct GNUNET_PeerIdentity *peer)
2234 {
2235   double res;
2236   const double *preferences = NULL;
2237   int c;
2238   preferences = mlp->get_preferences (mlp->get_preferences_cls, peer);
2239
2240   res = 0.0;
2241   for (c = 0; c < GNUNET_ATS_PreferenceCount; c++)
2242   {
2243     if (c != GNUNET_ATS_PREFERENCE_END)
2244     {
2245       /* fprintf (stderr, "VALUE[%u] %s %.3f \n",
2246        *        c, GNUNET_i2s (&cur->addr->peer), t[c]); */
2247       res += preferences[c];
2248     }
2249   }
2250
2251   res /= (GNUNET_ATS_PreferenceCount -1);
2252   res += 1.0;
2253
2254   LOG (GNUNET_ERROR_TYPE_DEBUG,
2255        "Peer preference for peer  `%s' == %.2f\n",
2256        GNUNET_i2s(peer), res);
2257
2258   return res;
2259 }
2260
2261
2262 /**
2263  * Get the preferred address for a specific peer
2264  *
2265  * @param solver the MLP Handle
2266  * @param peer the peer
2267  * @return suggested address
2268  */
2269 static const struct ATS_Address *
2270 GAS_mlp_get_preferred_address (void *solver,
2271                                const struct GNUNET_PeerIdentity *peer)
2272 {
2273   struct GAS_MLP_Handle *mlp = solver;
2274   struct ATS_Peer *p;
2275   struct ATS_Address *res;
2276
2277   GNUNET_assert (NULL != solver);
2278   GNUNET_assert (NULL != peer);
2279
2280   LOG (GNUNET_ERROR_TYPE_DEBUG, "Getting preferred address for `%s'\n",
2281       GNUNET_i2s (peer));
2282
2283   /* Is this peer included in the problem? */
2284   if (NULL ==
2285       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
2286                                          peer))
2287     {
2288       LOG (GNUNET_ERROR_TYPE_INFO, "Adding peer `%s' to list of requested_peers with requests\n",
2289           GNUNET_i2s (peer));
2290
2291       p = GNUNET_new (struct ATS_Peer);
2292       p->id = (*peer);
2293       p->f = get_peer_pref_value (mlp, peer);
2294       GNUNET_CONTAINER_multipeermap_put (mlp->requested_peers,
2295                                          peer, p,
2296                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2297
2298       /* Added new peer, we have to rebuild problem before solving */
2299       mlp->stat_mlp_prob_changed = GNUNET_YES;
2300
2301       if ((GNUNET_YES == mlp->opt_mlp_auto_solve)&&
2302           (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(mlp->addresses,
2303                                                                 peer)))
2304       {
2305         mlp->exclude_peer = peer;
2306         GAS_mlp_solve_problem (mlp);
2307         mlp->exclude_peer = NULL;
2308       }
2309   }
2310   /* Get prefered address */
2311   res = NULL;
2312   GNUNET_CONTAINER_multipeermap_get_multiple (mlp->addresses, peer,
2313                                               &mlp_get_preferred_address_it, &res);
2314   return res;
2315 }
2316
2317
2318 /**
2319  * Deletes a single address in the MLP problem
2320  *
2321  * The MLP problem has to be recreated and the problem has to be resolved
2322  *
2323  * @param solver the MLP Handle
2324  * @param address the address to delete
2325  * @param session_only delete only session not whole address
2326  */
2327 static void
2328 GAS_mlp_address_delete (void *solver,
2329                         struct ATS_Address *address,
2330                         int session_only)
2331 {
2332   struct GAS_MLP_Handle *mlp = solver;
2333   struct MLP_information *mlpi;
2334   int was_active;
2335
2336   GNUNET_assert (NULL != solver);
2337   GNUNET_assert (NULL != address);
2338
2339   mlpi = address->solver_information;
2340   if ((GNUNET_NO == session_only) && (NULL != mlpi))
2341   {
2342     /* Remove full address */
2343     GNUNET_free (mlpi);
2344     address->solver_information = NULL;
2345   }
2346   was_active = address->active;
2347   address->active = GNUNET_NO;
2348   address->assigned_bw_in = 0;
2349   address->assigned_bw_out = 0;
2350
2351   /* Is this peer included in the problem? */
2352   if (NULL ==
2353       GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers,
2354                                          &address->peer))
2355   {
2356     LOG (GNUNET_ERROR_TYPE_INFO,
2357          "Deleting %s for peer `%s' without address request \n",
2358          (session_only == GNUNET_YES) ? "session" : "address",
2359          GNUNET_i2s(&address->peer));
2360     return;
2361   }
2362   LOG (GNUNET_ERROR_TYPE_INFO, "Deleting %s for peer `%s' with address request \n",
2363       (session_only == GNUNET_YES) ? "session" : "address",
2364       GNUNET_i2s(&address->peer));
2365
2366   /* Problem size changed: new address for peer with pending request */
2367   mlp->stat_mlp_prob_changed = GNUNET_YES;
2368   if (GNUNET_YES == mlp->opt_mlp_auto_solve)
2369   {
2370     GAS_mlp_solve_problem (solver);
2371   }
2372   if (GNUNET_YES == was_active)
2373   {
2374     if (NULL == GAS_mlp_get_preferred_address (solver, &address->peer))
2375     {
2376       /* No alternative address, disconnecting peer */
2377       mlp->bw_changed_cb (mlp->bw_changed_cb_cls, address);
2378     }
2379   }
2380
2381   return;
2382 }
2383
2384
2385 /**
2386  * Start a bulk operation
2387  *
2388  * @param solver the solver
2389  */
2390 static void
2391 GAS_mlp_bulk_start (void *solver)
2392 {
2393   struct GAS_MLP_Handle *s = solver;
2394
2395   LOG (GNUNET_ERROR_TYPE_DEBUG,
2396        "Locking solver for bulk operation ...\n");
2397   GNUNET_assert (NULL != solver);
2398   s->stat_bulk_lock ++;
2399 }
2400
2401
2402 static void
2403 GAS_mlp_bulk_stop (void *solver)
2404 {
2405   struct GAS_MLP_Handle *s = solver;
2406
2407   LOG (GNUNET_ERROR_TYPE_DEBUG,
2408        "Unlocking solver from bulk operation ...\n");
2409   GNUNET_assert (NULL != solver);
2410
2411   if (s->stat_bulk_lock < 1)
2412   {
2413     GNUNET_break (0);
2414     return;
2415   }
2416   s->stat_bulk_lock --;
2417
2418   if (0 < s->stat_bulk_requests)
2419   {
2420     GAS_mlp_solve_problem (solver);
2421     s->stat_bulk_requests= 0;
2422   }
2423 }
2424
2425
2426
2427 /**
2428  * Stop notifying about address and bandwidth changes for this peer
2429  *
2430  * @param solver the MLP handle
2431  * @param peer the peer
2432  */
2433 static void
2434 GAS_mlp_stop_get_preferred_address (void *solver,
2435                                      const struct GNUNET_PeerIdentity *peer)
2436 {
2437   struct GAS_MLP_Handle *mlp = solver;
2438   struct ATS_Peer *p = NULL;
2439
2440   GNUNET_assert (NULL != solver);
2441   GNUNET_assert (NULL != peer);
2442   if (NULL != (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer)))
2443   {
2444     GNUNET_assert (GNUNET_YES ==
2445                    GNUNET_CONTAINER_multipeermap_remove (mlp->requested_peers, peer, p));
2446     GNUNET_free (p);
2447
2448     mlp->stat_mlp_prob_changed = GNUNET_YES;
2449     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
2450     {
2451       GAS_mlp_solve_problem (solver);
2452     }
2453   }
2454 }
2455
2456
2457 /**
2458  * Changes the preferences for a peer in the MLP problem
2459  *
2460  * @param solver the MLP Handle
2461  * @param peer the peer
2462  * @param kind the kind to change the preference
2463  * @param pref_rel the relative score
2464  */
2465 static void
2466 GAS_mlp_address_change_preference (void *solver,
2467                    const struct GNUNET_PeerIdentity *peer,
2468                    enum GNUNET_ATS_PreferenceKind kind,
2469                    double pref_rel)
2470 {
2471   struct GAS_MLP_Handle *mlp = solver;
2472   struct ATS_Peer *p;
2473
2474   LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing preference for address for peer `%s' to %.2f\n",
2475       GNUNET_i2s(peer), pref_rel);
2476
2477   GNUNET_STATISTICS_update (mlp->stats,"# LP address preference changes", 1, GNUNET_NO);
2478   /* Update the constraints with changed preferences */
2479
2480
2481
2482   /* Update relativity constraint c9 */
2483   if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer)))
2484   {
2485     LOG (GNUNET_ERROR_TYPE_INFO, "Updating preference for unknown peer `%s'\n", GNUNET_i2s(peer));
2486     return;
2487   }
2488
2489   if (GNUNET_NO == mlp->opt_dbg_feasibility_only)
2490   {
2491     p->f = get_peer_pref_value (mlp, peer);
2492     mlp_create_problem_update_value (&mlp->p, p->r_c9, mlp->p.c_r, -p->f, __LINE__);
2493
2494     /* Problem size changed: new address for peer with pending request */
2495     mlp->stat_mlp_prob_updated = GNUNET_YES;
2496     if (GNUNET_YES == mlp->opt_mlp_auto_solve)
2497       GAS_mlp_solve_problem (solver);
2498   }
2499 }
2500
2501
2502 /**
2503  * Get application feedback for a peer
2504  *
2505  * @param solver the solver handle
2506  * @param application the application
2507  * @param peer the peer to change the preference for
2508  * @param scope the time interval for this feedback: [now - scope .. now]
2509  * @param kind the kind to change the preference
2510  * @param score the score
2511  */
2512 static void
2513 GAS_mlp_address_preference_feedback (void *solver,
2514                                     void *application,
2515                                     const struct GNUNET_PeerIdentity *peer,
2516                                     const struct GNUNET_TIME_Relative scope,
2517                                     enum GNUNET_ATS_PreferenceKind kind,
2518                                     double score)
2519 {
2520   struct GAS_PROPORTIONAL_Handle *s = solver;
2521   GNUNET_assert (NULL != solver);
2522   GNUNET_assert (NULL != peer);
2523
2524   GNUNET_assert (NULL != s);
2525 }
2526
2527
2528 static int
2529 mlp_free_peers (void *cls,
2530                 const struct GNUNET_PeerIdentity *key, void *value)
2531 {
2532   struct GNUNET_CONTAINER_MultiPeerMap *map = cls;
2533   struct ATS_Peer *p = value;
2534
2535   GNUNET_assert (GNUNET_YES ==
2536                  GNUNET_CONTAINER_multipeermap_remove (map, key, value));
2537   GNUNET_free (p);
2538
2539   return GNUNET_OK;
2540 }
2541
2542
2543 /**
2544  * Shutdown the MLP problem solving component
2545  *
2546  * @param cls the solver handle
2547  * @return NULL
2548  */
2549 void *
2550 libgnunet_plugin_ats_mlp_done (void *cls)
2551 {
2552   struct GAS_MLP_Handle *mlp = cls;
2553   GNUNET_assert (mlp != NULL);
2554
2555   LOG (GNUNET_ERROR_TYPE_DEBUG,
2556        "Shutting down mlp solver\n");
2557   mlp_delete_problem (mlp);
2558
2559   GNUNET_CONTAINER_multipeermap_iterate (mlp->requested_peers,
2560                                          &mlp_free_peers,
2561                                          mlp->requested_peers);
2562   GNUNET_CONTAINER_multipeermap_destroy (mlp->requested_peers);
2563   mlp->requested_peers = NULL;
2564
2565   /* Clean up GLPK environment */
2566   glp_free_env();
2567   GNUNET_free (mlp);
2568
2569   LOG (GNUNET_ERROR_TYPE_DEBUG,
2570        "Shutdown down of mlp solver complete\n");
2571   return NULL;
2572 }
2573
2574
2575 void *
2576 libgnunet_plugin_ats_mlp_init (void *cls)
2577 {
2578   struct GNUNET_ATS_PluginEnvironment *env = cls;
2579   struct GAS_MLP_Handle * mlp = GNUNET_new (struct GAS_MLP_Handle);
2580
2581   float f_tmp;
2582   unsigned long long tmp;
2583   unsigned int b_min;
2584   unsigned int n_min;
2585   int c;
2586   int c2;
2587   int found;
2588   char *outputformat;
2589
2590   struct GNUNET_TIME_Relative max_duration;
2591   long long unsigned int max_iterations;
2592
2593   GNUNET_assert (NULL != env->cfg);
2594   GNUNET_assert (NULL != env->addresses);
2595   GNUNET_assert (NULL != env->bandwidth_changed_cb);
2596   GNUNET_assert (NULL != env->get_preferences);
2597   GNUNET_assert (NULL != env->get_property);
2598
2599   /* Init GLPK environment */
2600   int res = glp_init_env();
2601   switch (res) {
2602     case 0:
2603       LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
2604           "initialization successful");
2605       break;
2606     case 1:
2607       LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n",
2608           "environment is already initialized");
2609       break;
2610     case 2:
2611       LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
2612           "initialization failed (insufficient memory)");
2613       GNUNET_free(mlp);
2614       return NULL;
2615       break;
2616     case 3:
2617       LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n",
2618           "initialization failed (unsupported programming model)");
2619       GNUNET_free(mlp);
2620       return NULL;
2621       break;
2622     default:
2623       break;
2624   }
2625
2626   mlp->opt_dump_problem_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2627      "ats", "MLP_DUMP_PROBLEM_ALL");
2628   if (GNUNET_SYSERR == mlp->opt_dump_problem_all)
2629    mlp->opt_dump_problem_all = GNUNET_NO;
2630
2631   mlp->opt_dump_solution_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2632      "ats", "MLP_DUMP_SOLUTION_ALL");
2633   if (GNUNET_SYSERR == mlp->opt_dump_solution_all)
2634    mlp->opt_dump_solution_all = GNUNET_NO;
2635
2636   mlp->opt_dump_problem_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2637      "ats", "MLP_DUMP_PROBLEM_ON_FAIL");
2638   if (GNUNET_SYSERR == mlp->opt_dump_problem_on_fail)
2639    mlp->opt_dump_problem_on_fail = GNUNET_NO;
2640
2641   mlp->opt_dump_solution_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2642      "ats", "MLP_DUMP_SOLUTION_ON_FAIL");
2643   if (GNUNET_SYSERR == mlp->opt_dump_solution_on_fail)
2644    mlp->opt_dump_solution_on_fail = GNUNET_NO;
2645
2646   mlp->opt_dbg_glpk_verbose = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2647      "ats", "MLP_DBG_GLPK_VERBOSE");
2648   if (GNUNET_SYSERR == mlp->opt_dbg_glpk_verbose)
2649    mlp->opt_dbg_glpk_verbose = GNUNET_NO;
2650
2651   mlp->opt_dbg_feasibility_only = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2652      "ats", "MLP_DBG_FEASIBILITY_ONLY");
2653   if (GNUNET_SYSERR == mlp->opt_dbg_feasibility_only)
2654    mlp->opt_dbg_feasibility_only = GNUNET_NO;
2655   if (GNUNET_YES == mlp->opt_dbg_feasibility_only)
2656     LOG (GNUNET_ERROR_TYPE_WARNING,
2657         "MLP solver is configured to check feasibility only!\n");
2658
2659   mlp->opt_dbg_autoscale_problem = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2660      "ats", "MLP_DBG_AUTOSCALE_PROBLEM");
2661   if (GNUNET_SYSERR == mlp->opt_dbg_autoscale_problem)
2662    mlp->opt_dbg_autoscale_problem = GNUNET_NO;
2663   if (GNUNET_YES == mlp->opt_dbg_autoscale_problem)
2664     LOG (GNUNET_ERROR_TYPE_WARNING,
2665         "MLP solver is configured automatically scale the problem!\n");
2666
2667   mlp->opt_dbg_intopt_presolver = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2668      "ats", "MLP_DBG_INTOPT_PRESOLVE");
2669   if (GNUNET_SYSERR == mlp->opt_dbg_intopt_presolver)
2670    mlp->opt_dbg_intopt_presolver = GNUNET_NO;
2671   if (GNUNET_YES == mlp->opt_dbg_intopt_presolver)
2672     LOG (GNUNET_ERROR_TYPE_WARNING,
2673         "MLP solver is configured use the mlp presolver\n");
2674
2675   mlp->opt_dbg_optimize_diversity = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2676      "ats", "MLP_DBG_OPTIMIZE_DIVERSITY");
2677   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_diversity)
2678    mlp->opt_dbg_optimize_diversity = GNUNET_YES;
2679   if (GNUNET_NO == mlp->opt_dbg_optimize_diversity)
2680     LOG (GNUNET_ERROR_TYPE_WARNING,
2681         "MLP solver is not optimizing for diversity\n");
2682
2683   mlp->opt_dbg_optimize_relativity= GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2684      "ats", "MLP_DBG_OPTIMIZE_RELATIVITY");
2685   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_relativity)
2686    mlp->opt_dbg_optimize_relativity = GNUNET_YES;
2687   if (GNUNET_NO == mlp->opt_dbg_optimize_relativity)
2688     LOG (GNUNET_ERROR_TYPE_WARNING,
2689         "MLP solver is not optimizing for relativity\n");
2690
2691   mlp->opt_dbg_optimize_quality = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2692      "ats", "MLP_DBG_OPTIMIZE_QUALITY");
2693   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_quality)
2694    mlp->opt_dbg_optimize_quality = GNUNET_YES;
2695   if (GNUNET_NO == mlp->opt_dbg_optimize_quality)
2696     LOG (GNUNET_ERROR_TYPE_WARNING,
2697         "MLP solver is not optimizing for quality\n");
2698
2699   mlp->opt_dbg_optimize_utility = GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
2700      "ats", "MLP_DBG_OPTIMIZE_UTILITY");
2701   if (GNUNET_SYSERR == mlp->opt_dbg_optimize_utility)
2702    mlp->opt_dbg_optimize_utility = GNUNET_YES;
2703   if (GNUNET_NO == mlp->opt_dbg_optimize_utility)
2704     LOG (GNUNET_ERROR_TYPE_WARNING,
2705         "MLP solver is not optimizing for utility\n");
2706
2707   if ( (GNUNET_NO == mlp->opt_dbg_optimize_utility) &&
2708        (GNUNET_NO == mlp->opt_dbg_optimize_quality) &&
2709        (GNUNET_NO == mlp->opt_dbg_optimize_relativity) &&
2710        (GNUNET_NO == mlp->opt_dbg_optimize_utility) &&
2711        (GNUNET_NO == mlp->opt_dbg_feasibility_only))
2712   {
2713     LOG (GNUNET_ERROR_TYPE_ERROR,
2714         _("MLP solver is not optimizing for anything, changing to feasibility check\n"));
2715     mlp->opt_dbg_feasibility_only = GNUNET_YES;
2716   }
2717
2718   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (env->cfg,
2719      "ats", "MLP_LOG_FORMAT", &outputformat))
2720    mlp->opt_log_format = MLP_CPLEX;
2721   else
2722   {
2723     GNUNET_STRINGS_utf8_toupper(outputformat, outputformat);
2724     if (0 == strcmp (outputformat, "MPS"))
2725     {
2726       mlp->opt_log_format = MLP_MPS;
2727     }
2728     else if (0 == strcmp (outputformat, "CPLEX"))
2729     {
2730       mlp->opt_log_format = MLP_CPLEX;
2731     }
2732     else if (0 == strcmp (outputformat, "GLPK"))
2733     {
2734       mlp->opt_log_format = MLP_GLPK;
2735     }
2736     else
2737     {
2738       LOG (GNUNET_ERROR_TYPE_WARNING,
2739           "Invalid log format `%s' in configuration, using CPLEX!\n",
2740           outputformat);
2741       mlp->opt_log_format = MLP_CPLEX;
2742     }
2743     GNUNET_free (outputformat);
2744   }
2745
2746   mlp->pv.BIG_M = (double) BIG_M_VALUE;
2747
2748   mlp->pv.mip_gap = (double) 0.0;
2749   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2750       "MLP_MAX_MIP_GAP", &f_tmp))
2751   {
2752     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2753     {
2754       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2755           "MIP gap", f_tmp);
2756     }
2757     else
2758     {
2759       mlp->pv.mip_gap = f_tmp;
2760       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2761           "MIP gap", f_tmp);
2762     }
2763   }
2764
2765   mlp->pv.lp_mip_gap = (double) 0.0;
2766   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2767       "MLP_MAX_LP_MIP_GAP", &f_tmp))
2768   {
2769     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2770     {
2771       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2772           "LP/MIP", f_tmp);
2773     }
2774     else
2775     {
2776       mlp->pv.lp_mip_gap = f_tmp;
2777       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2778           "LP/MIP", f_tmp);
2779     }
2780   }
2781
2782   /* Get timeout for iterations */
2783   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(env->cfg, "ats",
2784       "MLP_MAX_DURATION", &max_duration))
2785   {
2786     max_duration = MLP_MAX_EXEC_DURATION;
2787   }
2788
2789   /* Get maximum number of iterations */
2790   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats",
2791       "MLP_MAX_ITERATIONS", &max_iterations))
2792   {
2793     max_iterations = MLP_MAX_ITERATIONS;
2794   }
2795
2796   /* Get diversity coefficient from configuration */
2797   mlp->pv.co_D = MLP_DEFAULT_D;
2798   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2799       "MLP_COEFFICIENT_D", &f_tmp))
2800   {
2801     if ((f_tmp < 0.0))
2802     {
2803       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2804           "MLP_COEFFICIENT_D", f_tmp);
2805     }
2806     else
2807     {
2808       mlp->pv.co_D = f_tmp;
2809       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2810           "MLP_COEFFICIENT_D", f_tmp);
2811     }
2812   }
2813
2814   /* Get relativity coefficient from configuration */
2815   mlp->pv.co_R = MLP_DEFAULT_R;
2816   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2817       "MLP_COEFFICIENT_R", &f_tmp))
2818   {
2819     if ((f_tmp < 0.0))
2820     {
2821       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2822           "MLP_COEFFICIENT_R", f_tmp);
2823     }
2824     else
2825     {
2826       mlp->pv.co_R = f_tmp;
2827       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2828           "MLP_COEFFICIENT_R", f_tmp);
2829     }
2830   }
2831
2832
2833   /* Get utilization coefficient from configuration */
2834   mlp->pv.co_U = MLP_DEFAULT_U;
2835   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2836       "MLP_COEFFICIENT_U", &f_tmp))
2837   {
2838     if ((f_tmp < 0.0))
2839     {
2840       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2841           "MLP_COEFFICIENT_U", f_tmp);
2842     }
2843     else
2844     {
2845       mlp->pv.co_U = f_tmp;
2846       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n",
2847           "MLP_COEFFICIENT_U", f_tmp);
2848     }
2849   }
2850
2851   /* Get quality metric coefficients from configuration */
2852   int i_delay = MLP_NaN;
2853   int i_distance = MLP_NaN;
2854   int q[GNUNET_ATS_QualityPropertiesCount] = GNUNET_ATS_QualityProperties;
2855   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
2856   {
2857     /* initialize quality coefficients with default value 1.0 */
2858       mlp->pv.co_Q[c] = MLP_DEFAULT_QUALITY;
2859
2860     mlp->pv.q[c] = q[c];
2861     if (q[c] == GNUNET_ATS_QUALITY_NET_DELAY)
2862       i_delay = c;
2863     if (q[c] == GNUNET_ATS_QUALITY_NET_DISTANCE)
2864       i_distance = c;
2865   }
2866
2867   if ( (i_delay != MLP_NaN) &&
2868        (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2869           "MLP_COEFFICIENT_QUALITY_DELAY", &tmp)) )
2870     mlp->pv.co_Q[i_delay] = (double) tmp / 100;
2871   else
2872     mlp->pv.co_Q[i_delay] = MLP_DEFAULT_QUALITY;
2873
2874   if ( (i_distance != MLP_NaN) &&
2875         (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2876           "MLP_COEFFICIENT_QUALITY_DISTANCE", &tmp)) )
2877     mlp->pv.co_Q[i_distance] = (double) tmp / 100;
2878   else
2879     mlp->pv.co_Q[i_distance] = MLP_DEFAULT_QUALITY;
2880
2881   /* Get minimum bandwidth per used address from configuration */
2882   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2883                                                       "MLP_MIN_BANDWIDTH",
2884                                                       &tmp))
2885     b_min = tmp;
2886   else
2887   {
2888     b_min = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
2889   }
2890
2891   /* Get minimum number of connections from configuration */
2892   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats",
2893                                                       "MLP_MIN_CONNECTIONS",
2894                                                       &tmp))
2895     n_min = tmp;
2896   else
2897     n_min = MLP_DEFAULT_MIN_CONNECTIONS;
2898
2899   /* Init network quotas */
2900   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
2901   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
2902   {
2903       found = GNUNET_NO;
2904       for (c2 = 0; c2 < env->network_count; c2++)
2905       {
2906           if (quotas[c] == env->networks[c2])
2907           {
2908               mlp->pv.quota_index[c] = env->networks[c2];
2909               mlp->pv.quota_out[c] = env->out_quota[c2];
2910               mlp->pv.quota_in[c] = env->in_quota[c2];
2911
2912               found = GNUNET_YES;
2913               LOG (GNUNET_ERROR_TYPE_INFO,
2914                   "Quota for network `%s' (in/out) %llu/%llu\n",
2915                   GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2916                   mlp->pv.quota_out[c],
2917                   mlp->pv.quota_in[c]);
2918               break;
2919
2920           }
2921       }
2922
2923       /* Check if defined quota could make problem unsolvable */
2924       if ((n_min * b_min) > mlp->pv.quota_out[c])
2925       {
2926         LOG (GNUNET_ERROR_TYPE_INFO,
2927             _("Adjusting inconsistent outbound quota configuration for network `%s', is %llu must be at least %llu\n"),
2928             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2929             mlp->pv.quota_out[c],
2930             (n_min * b_min));
2931         mlp->pv.quota_out[c] = (n_min * b_min);
2932       }
2933       if ((n_min * b_min) > mlp->pv.quota_in[c])
2934       {
2935         LOG (GNUNET_ERROR_TYPE_INFO,
2936             _("Adjusting inconsistent inbound quota configuration for network `%s', is %llu must be at least %llu\n"),
2937             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2938             mlp->pv.quota_in[c],
2939             (n_min * b_min));
2940         mlp->pv.quota_in[c] = (n_min * b_min);
2941       }
2942
2943       /* Check if bandwidth is too big to make problem solvable */
2944       if (mlp->pv.BIG_M < mlp->pv.quota_out[c])
2945       {
2946         LOG (GNUNET_ERROR_TYPE_INFO,
2947             _("Adjusting outbound quota configuration for network `%s'from %llu to %.0f\n"),
2948             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2949             mlp->pv.quota_out[c],
2950             mlp->pv.BIG_M);
2951         mlp->pv.quota_out[c] = mlp->pv.BIG_M ;
2952       }
2953       if (mlp->pv.BIG_M < mlp->pv.quota_in[c])
2954       {
2955         LOG (GNUNET_ERROR_TYPE_INFO, _("Adjusting inbound quota configuration for network `%s' from %llu to %.0f\n"),
2956             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2957             mlp->pv.quota_in[c],
2958             mlp->pv.BIG_M);
2959         mlp->pv.quota_in[c] = mlp->pv.BIG_M ;
2960       }
2961
2962       if (GNUNET_NO == found)
2963       {
2964         mlp->pv.quota_in[c] = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
2965         mlp->pv.quota_out[c] = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
2966         LOG (GNUNET_ERROR_TYPE_INFO, _("Using default quota configuration for network `%s' (in/out) %llu/%llu\n"),
2967             GNUNET_ATS_print_network_type(mlp->pv.quota_index[c]),
2968             mlp->pv.quota_in[c],
2969             mlp->pv.quota_out[c]);
2970       }
2971   }
2972   mlp->env = env;
2973   env->sf.s_add = &GAS_mlp_address_add;
2974   env->sf.s_address_update_property = &GAS_mlp_address_property_changed;
2975   env->sf.s_address_update_session = &GAS_mlp_address_session_changed;
2976   env->sf.s_address_update_inuse = &GAS_mlp_address_inuse_changed;
2977   env->sf.s_address_update_network = &GAS_mlp_address_change_network;
2978   env->sf.s_get = &GAS_mlp_get_preferred_address;
2979   env->sf.s_get_stop = &GAS_mlp_stop_get_preferred_address;
2980   env->sf.s_pref = &GAS_mlp_address_change_preference;
2981   env->sf.s_feedback = &GAS_mlp_address_preference_feedback;
2982   env->sf.s_del = &GAS_mlp_address_delete;
2983   env->sf.s_bulk_start = &GAS_mlp_bulk_start;
2984   env->sf.s_bulk_stop = &GAS_mlp_bulk_stop;
2985
2986
2987   /* Assign options to handle */
2988   mlp->stats = (struct GNUNET_STATISTICS_Handle *) env->stats;
2989   mlp->addresses = env->addresses;
2990   mlp->bw_changed_cb = env->bandwidth_changed_cb;
2991   mlp->bw_changed_cb_cls = env->bw_changed_cb_cls;
2992   mlp->get_preferences =  env->get_preferences;
2993   mlp->get_preferences_cls = env->get_preference_cls;
2994   mlp->get_properties = env->get_property;
2995   mlp->get_properties_cls = env->get_property_cls;
2996   /* Setting MLP Input variables */
2997
2998   mlp->pv.b_min = b_min;
2999   mlp->pv.n_min = n_min;
3000   mlp->pv.m_q = GNUNET_ATS_QualityPropertiesCount;
3001   mlp->stat_mlp_prob_changed = GNUNET_NO;
3002   mlp->stat_mlp_prob_updated = GNUNET_NO;
3003   mlp->opt_mlp_auto_solve = GNUNET_YES;
3004   mlp->requested_peers = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO);
3005   mlp->stat_bulk_requests = 0;
3006   mlp->stat_bulk_lock = 0;
3007
3008   /* Setup GLPK */
3009   /* Redirect GLPK output to GNUnet logging */
3010   glp_term_hook (&mlp_term_hook, (void *) mlp);
3011
3012   /* Init LP solving parameters */
3013   glp_init_smcp(&mlp->control_param_lp);
3014   mlp->control_param_lp.msg_lev = GLP_MSG_OFF;
3015   if (GNUNET_YES == mlp->opt_dbg_glpk_verbose)
3016     mlp->control_param_lp.msg_lev = GLP_MSG_ALL;
3017
3018   mlp->control_param_lp.it_lim = max_iterations;
3019   mlp->control_param_lp.tm_lim = max_duration.rel_value_us / 1000LL;
3020
3021   /* Init MLP solving parameters */
3022   glp_init_iocp(&mlp->control_param_mlp);
3023   /* Setting callback function */
3024   mlp->control_param_mlp.cb_func = &mlp_branch_and_cut_cb;
3025   mlp->control_param_mlp.cb_info = mlp;
3026   mlp->control_param_mlp.msg_lev = GLP_MSG_OFF;
3027   mlp->control_param_mlp.mip_gap = mlp->pv.mip_gap;
3028   if (GNUNET_YES == mlp->opt_dbg_glpk_verbose)
3029     mlp->control_param_mlp.msg_lev = GLP_MSG_ALL;
3030   mlp->control_param_mlp.tm_lim = max_duration.rel_value_us / 1000LL;
3031
3032   LOG (GNUNET_ERROR_TYPE_DEBUG, "solver ready\n");
3033
3034   return mlp;
3035 }
3036
3037 /* end of plugin_ats_mlp.c */