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