- doxygen
[oweals/gnunet.git] / src / ats / gnunet-service-ats_addresses_mlp.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file ats/gnunet-service-ats_addresses_mlp.c
23  * @brief ats mlp problem solver
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet-service-ats_addresses.h"
30 #include "gnunet-service-ats_addresses_mlp.h"
31 #include "gnunet_statistics_service.h"
32 #include "glpk.h"
33
34 #define WRITE_MLP GNUNET_NO
35 #define DEBUG_ATS GNUNET_NO
36 #define VERBOSE_GLPK GNUNET_NO
37
38 #define ENABLE_C8 GNUNET_YES
39 #define ENABLE_C9 GNUNET_YES
40 /**
41  * Translate glpk solver error codes to text
42  * @param retcode return code
43  * @return string with result
44  */
45 const char *
46 mlp_solve_to_string (int retcode)
47 {
48   switch (retcode) {
49     case 0:
50       return "ok";
51       break;
52     case GLP_EBADB:
53       return "invalid basis";
54       break;
55     case GLP_ESING:
56       return "singular matrix";
57       break;
58     case GLP_ECOND:
59       return "ill-conditioned matrix";
60       break;
61     case GLP_EBOUND:
62       return "invalid bounds";
63       break;
64     case GLP_EFAIL:
65       return "solver failed";
66       break;
67     case GLP_EOBJLL:
68       return "objective lower limit reached";
69       break;
70     case GLP_EOBJUL:
71       return "objective upper limit reached";
72       break;
73     case GLP_EITLIM:
74       return "iteration limit exceeded";
75       break;
76     case GLP_ETMLIM:
77       return "time limit exceeded";
78       break;
79     case GLP_ENOPFS:
80       return "no primal feasible solution";
81       break;
82     case GLP_EROOT:
83       return "root LP optimum not provided";
84       break;
85     case GLP_ESTOP:
86       return "search terminated by application";
87       break;
88     case GLP_EMIPGAP:
89       return "relative mip gap tolerance reached";
90       break;
91     case GLP_ENOFEAS:
92       return "no dual feasible solution";
93       break;
94     case GLP_ENOCVG:
95       return "no convergence";
96       break;
97     case GLP_EINSTAB:
98       return "numerical instability";
99       break;
100     case GLP_EDATA:
101       return "invalid data";
102       break;
103     case GLP_ERANGE:
104       return "result out of range";
105       break;
106     default:
107       GNUNET_break (0);
108       return "unknown error";
109       break;
110   }
111   GNUNET_break (0);
112   return "unknown error";
113 }
114
115
116 /**
117  * Translate glpk status error codes to text
118  * @param retcode return code
119  * @return string with result
120  */
121 const char *
122 mlp_status_to_string (int retcode)
123 {
124   switch (retcode) {
125     case GLP_UNDEF:
126       return "solution is undefined";
127       break;
128     case GLP_FEAS:
129       return "solution is feasible";
130       break;
131     case GLP_INFEAS:
132       return "solution is infeasible";
133       break;
134     case GLP_NOFEAS:
135       return "no feasible solution exists";
136       break;
137     case GLP_OPT:
138       return "solution is optimal";
139       break;
140     case GLP_UNBND:
141       return "solution is unbounded";
142       break;
143     default:
144       GNUNET_break (0);
145       return "unknown error";
146       break;
147   }
148   GNUNET_break (0);
149   return "unknown error";
150 }
151
152 /**
153  * Translate ATS properties to text
154  * Just intended for debugging
155  *
156  * @param ats_index the ATS index
157  * @return string with result
158  */
159 const char *
160 mlp_ats_to_string (int ats_index)
161 {
162   switch (ats_index) {
163     case GNUNET_ATS_ARRAY_TERMINATOR:
164       return "GNUNET_ATS_ARRAY_TERMINATOR";
165       break;
166     case GNUNET_ATS_UTILIZATION_UP:
167       return "GNUNET_ATS_UTILIZATION_UP";
168       break;
169     case GNUNET_ATS_UTILIZATION_DOWN:
170       return "GNUNET_ATS_UTILIZATION_DOWN";
171       break;
172     case GNUNET_ATS_COST_LAN:
173       return "GNUNET_ATS_COST_LAN";
174       break;
175     case GNUNET_ATS_COST_WAN:
176       return "GNUNET_ATS_COST_LAN";
177       break;
178     case GNUNET_ATS_COST_WLAN:
179       return "GNUNET_ATS_COST_WLAN";
180       break;
181     case GNUNET_ATS_NETWORK_TYPE:
182       return "GNUNET_ATS_NETWORK_TYPE";
183       break;
184     case GNUNET_ATS_QUALITY_NET_DELAY:
185       return "GNUNET_ATS_QUALITY_NET_DELAY";
186       break;
187     case GNUNET_ATS_QUALITY_NET_DISTANCE:
188       return "GNUNET_ATS_QUALITY_NET_DISTANCE";
189       break;
190     default:
191       return "unknown";
192       break;
193   }
194   GNUNET_break (0);
195   return "unknown error";
196 }
197
198 /**
199  * Find a peer in the DLL
200  *
201  * @param mlp the mlp handle
202  * @param peer the peer to find
203  * @return the peer struct
204  */
205 static struct ATS_Peer *
206 mlp_find_peer (struct GAS_MLP_Handle *mlp, const struct GNUNET_PeerIdentity *peer)
207 {
208   struct ATS_Peer *res = mlp->peer_head;
209   while (res != NULL)
210   {
211     if (0 == memcmp (peer, &res->id, sizeof (struct GNUNET_PeerIdentity)))
212       break;
213     res = res->next;
214   }
215   return res;
216 }
217
218 /**
219  * Intercept GLPK terminal output
220  * @param info the mlp handle
221  * @param s the string to print
222  * @return 0: glpk prints output on terminal, 0 != surpress output
223  */
224 static int
225 mlp_term_hook (void *info, const char *s)
226 {
227   /* Not needed atm struct MLP_information *mlp = info; */
228   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s", s);
229   return 1;
230 }
231
232 /**
233  * Delete the MLP problem and free the constrain matrix
234  *
235  * @param mlp the MLP handle
236  */
237 static void
238 mlp_delete_problem (struct GAS_MLP_Handle *mlp)
239 {
240   if (mlp != NULL)
241   {
242     if (mlp->prob != NULL)
243       glp_delete_prob(mlp->prob);
244
245     /* delete row index */
246     if (mlp->ia != NULL)
247     {
248       GNUNET_free (mlp->ia);
249       mlp->ia = NULL;
250     }
251
252     /* delete column index */
253     if (mlp->ja != NULL)
254     {
255       GNUNET_free (mlp->ja);
256       mlp->ja = NULL;
257     }
258
259     /* delete coefficients */
260     if (mlp->ar != NULL)
261     {
262       GNUNET_free (mlp->ar);
263       mlp->ar = NULL;
264     }
265     mlp->ci = 0;
266     mlp->prob = NULL;
267   }
268 }
269
270 /**
271  * Add constraints that are iterating over "forall addresses"
272  * and collects all existing peers for "forall peers" constraints
273  *
274  * @param cls GAS_MLP_Handle
275  * @param key Hashcode
276  * @param value ATS_Address
277  *
278  * @return GNUNET_OK to continue
279  */
280 static int
281 create_constraint_it (void *cls, const GNUNET_HashCode * key, void *value)
282 {
283   struct GAS_MLP_Handle *mlp = cls;
284   struct ATS_Address *address = value;
285   struct MLP_information *mlpi;
286   unsigned int row_index;
287   char *name;
288
289   GNUNET_assert (address->mlp_information != NULL);
290   mlpi = (struct MLP_information *) address->mlp_information;
291
292   /* c 1) bandwidth capping
293    * b_t  + (-M) * n_t <= 0
294    */
295   row_index = glp_add_rows (mlp->prob, 1);
296   mlpi->r_c1 = row_index;
297   /* set row name */
298   GNUNET_asprintf(&name, "c1_%s_%s", GNUNET_i2s(&address->peer), address->plugin);
299   glp_set_row_name (mlp->prob, row_index, name);
300   GNUNET_free (name);
301   /* set row bounds: <= 0 */
302   glp_set_row_bnds (mlp->prob, row_index, GLP_UP, 0.0, 0.0);
303   mlp->ia[mlp->ci] = row_index;
304   mlp->ja[mlp->ci] = mlpi->c_b;
305   mlp->ar[mlp->ci] = 1;
306   mlp->ci++;
307
308   mlp->ia[mlp->ci] = row_index;
309   mlp->ja[mlp->ci] = mlpi->c_n;
310   mlp->ar[mlp->ci] = -mlp->BIG_M;
311   mlp->ci++;
312
313   /* c 3) minimum bandwidth
314    * b_t + (-n_t * b_min) >= 0
315    */
316
317   row_index = glp_add_rows (mlp->prob, 1);
318   /* set row name */
319   GNUNET_asprintf(&name, "c3_%s_%s", GNUNET_i2s(&address->peer), address->plugin);
320   glp_set_row_name (mlp->prob, row_index, name);
321   GNUNET_free (name);
322   mlpi->r_c3 = row_index;
323   /* set row bounds: >= 0 */
324   glp_set_row_bnds (mlp->prob, row_index, GLP_LO, 0.0, 0.0);
325
326   mlp->ia[mlp->ci] = row_index;
327   mlp->ja[mlp->ci] = mlpi->c_b;
328   mlp->ar[mlp->ci] = 1;
329   mlp->ci++;
330
331   mlp->ia[mlp->ci] = row_index;
332   mlp->ja[mlp->ci] = mlpi->c_n;
333   mlp->ar[mlp->ci] = - (double) mlp->b_min;
334   mlp->ci++;
335
336   /* c 4) minimum connections
337    * (1)*n_1 + ... + (1)*n_m >= n_min
338    */
339   mlp->ia[mlp->ci] = mlp->r_c4;
340   mlp->ja[mlp->ci] = mlpi->c_n;
341   mlp->ar[mlp->ci] = 1;
342   mlp->ci++;
343
344   /* c 6) maximize diversity
345    * (1)*n_1 + ... + (1)*n_m - d == 0
346    */
347   mlp->ia[mlp->ci] = mlp->r_c6;
348   mlp->ja[mlp->ci] = mlpi->c_n;
349   mlp->ar[mlp->ci] = 1;
350   mlp->ci++;
351
352   /* c 10) obey network specific quotas
353    * (1)*b_1 + ... + (1)*b_m <= quota_n
354    */
355
356   int cur_row = 0;
357   int c;
358   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
359     {
360     if (mlp->quota_index[c] == address->atsp_network_type)
361     {
362       cur_row = mlp->r_quota[c];
363       break;
364     }
365   }
366
367   if (cur_row != 0)
368   {
369     mlp->ia[mlp->ci] = cur_row;
370     mlp->ja[mlp->ci] = mlpi->c_b;
371     mlp->ar[mlp->ci] = 1;
372     mlp->ci++;
373   }
374   else
375   {
376     GNUNET_break (0);
377   }
378
379   return GNUNET_OK;
380 }
381
382 /**
383  * Find the required ATS information for an address
384  *
385  * @param addr the address
386  * @param ats_index the desired ATS index
387  *
388  * @return the index on success, otherwise GNUNET_SYSERR
389  */
390
391 static int
392 mlp_lookup_ats (struct ATS_Address *addr, int ats_index)
393 {
394   struct GNUNET_ATS_Information * ats = addr->ats;
395   int c = 0;
396   int found = GNUNET_NO;
397   for (c = 0; c < addr->ats_count; c++)
398   {
399     if (ats[c].type == ats_index)
400     {
401       found = GNUNET_YES;
402       break;
403     }
404   }
405   if (found == GNUNET_YES)
406     return c;
407   else
408     return GNUNET_SYSERR;
409 }
410
411 /**
412  * Adds the problem constraints for all addresses
413  * Required for problem recreation after address deletion
414  *
415  * @param mlp the mlp handle
416  * @param addresses all addresses
417  */
418
419 static void
420 mlp_add_constraints_all_addresses (struct GAS_MLP_Handle *mlp, struct GNUNET_CONTAINER_MultiHashMap * addresses)
421 {
422   unsigned int n_addresses;
423   int c;
424   char *name;
425
426   /* Problem matrix*/
427   n_addresses = GNUNET_CONTAINER_multihashmap_size(addresses);
428
429   /* Required indices in the constrain matrix
430    *
431    * feasibility constraints:
432    *
433    * c 1) bandwidth capping
434    * #rows: |n_addresses|
435    * #indices: 2 * |n_addresses|
436    *
437    * c 2) one active address per peer
438    * #rows: |peers|
439    * #indices: |n_addresses|
440    *
441    * c 3) minium bandwidth assigned
442    * #rows: |n_addresses|
443    * #indices: 2 * |n_addresses|
444    *
445    * c 4) minimum number of active connections
446    * #rows: 1
447    * #indices: |n_addresses|
448    *
449    * c 5) maximum ressource consumption
450    * #rows: |ressources|
451    * #indices: |n_addresses|
452    *
453    * c 10) obey network specific quota
454    * #rows: |network types
455    * #indices: |n_addresses|
456    *
457    * Sum for feasibility constraints:
458    * #rows: 3 * |n_addresses| +  |ressources| + |peers| + 1
459    * #indices: 7 * |n_addresses|
460    *
461    * optimality constraints:
462    *
463    * c 6) diversity
464    * #rows: 1
465    * #indices: |n_addresses| + 1
466    *
467    * c 7) quality
468    * #rows: |quality properties|
469    * #indices: |n_addresses| + |quality properties|
470    *
471    * c 8) utilization
472    * #rows: 1
473    * #indices: |n_addresses| + 1
474    *
475    * c 9) relativity
476    * #rows: |peers|
477    * #indices: |n_addresses| + |peers|
478    * */
479
480   /* last +1 caused by glpk index starting with one: [1..pi]*/
481   int pi = ((7 * n_addresses) + (5 * n_addresses +  mlp->m_q + mlp->c_p + 2) + 1);
482   mlp->cm_size = pi;
483   mlp->ci = 1;
484
485   /* row index */
486   int *ia = GNUNET_malloc (pi * sizeof (int));
487   mlp->ia = ia;
488
489   /* column index */
490   int *ja = GNUNET_malloc (pi * sizeof (int));
491   mlp->ja = ja;
492
493   /* coefficient */
494   double *ar= GNUNET_malloc (pi * sizeof (double));
495   mlp->ar = ar;
496
497   /* Adding constraint rows
498    * This constraints are kind of "for all addresses"
499    * Feasibility constraints:
500    *
501    * c 1) bandwidth capping
502    * c 3) minimum bandwidth
503    * c 4) minimum number of connections
504    * c 6) maximize diversity
505    * c 10) obey network specific quota
506    */
507
508   int min = mlp->n_min;
509   if (mlp->n_min > mlp->c_p)
510     min = mlp->c_p;
511
512   mlp->r_c4 = glp_add_rows (mlp->prob, 1);
513   glp_set_row_name (mlp->prob, mlp->r_c4, "c4");
514   glp_set_row_bnds (mlp->prob, mlp->r_c4, GLP_LO, min, min);
515
516   /* Add row for c6) */
517
518   mlp->r_c6 = glp_add_rows (mlp->prob, 1);
519   /* Set type type to fix */
520   glp_set_row_bnds (mlp->prob, mlp->r_c6, GLP_FX, 0.0, 0.0);
521   /* Setting -D */
522   ia[mlp->ci] = mlp->r_c6 ;
523   ja[mlp->ci] = mlp->c_d;
524   ar[mlp->ci] = -1;
525   mlp->ci++;
526
527   /* Add rows for c 10) */
528   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
529   {
530     mlp->r_quota[c] = glp_add_rows (mlp->prob, 1);
531     char * text;
532     GNUNET_asprintf(&text, "quota_ats_%i", mlp->quota_index[c]);
533     glp_set_row_name (mlp->prob, mlp->r_quota[c], text);
534     GNUNET_free (text);
535     /* Set bounds to 0 <= x <= quota_out */
536     glp_set_row_bnds (mlp->prob, mlp->r_quota[c], GLP_UP, 0.0, mlp->quota_out[c]);
537   }
538
539   GNUNET_CONTAINER_multihashmap_iterate (addresses, create_constraint_it, mlp);
540
541   /* Adding constraint rows
542    * This constraints are kind of "for all peers"
543    * Feasibility constraints:
544    *
545    * c 2) 1 address per peer
546    * sum (n_p1_1 + ... + n_p1_n) = 1
547    *
548    * c 8) utilization
549    * sum (f_p * b_p1_1 + ... + f_p * b_p1_n) - u = 0
550    *
551    * c 9) relativity
552    * V p : sum (bt_1 + ... +bt_n) - f_p * r = 0
553    * */
554
555   /* Adding rows for c 8) */
556   mlp->r_c8 = glp_add_rows (mlp->prob, mlp->c_p);
557   glp_set_row_name (mlp->prob, mlp->r_c8, "c8");
558   /* Set row bound == 0 */
559   glp_set_row_bnds (mlp->prob, mlp->r_c8, GLP_FX, 0.0, 0.0);
560   /* -u */
561
562   ia[mlp->ci] = mlp->r_c8;
563   ja[mlp->ci] = mlp->c_u;
564   ar[mlp->ci] = -1;
565   mlp->ci++;
566
567   struct ATS_Peer * peer = mlp->peer_head;
568   while (peer != NULL)
569   {
570     struct ATS_Address *addr = peer->head;
571     struct MLP_information *mlpi = NULL;
572
573     /* Adding rows for c 2) */
574     peer->r_c2 = glp_add_rows (mlp->prob, 1);
575     GNUNET_asprintf(&name, "c2_%s", GNUNET_i2s(&peer->id));
576     glp_set_row_name (mlp->prob, peer->r_c2, name);
577     GNUNET_free (name);
578     /* Set row bound == 1 */
579     glp_set_row_bnds (mlp->prob, peer->r_c2, GLP_FX, 1.0, 1.0);
580
581     /* Adding rows for c 9) */
582 #if ENABLE_C9
583     peer->r_c9 = glp_add_rows (mlp->prob, 1);
584     GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&peer->id));
585     glp_set_row_name (mlp->prob, peer->r_c9, name);
586     GNUNET_free (name);
587     /* Set row bound == 0 */
588     glp_set_row_bnds (mlp->prob, peer->r_c9, GLP_LO, 0.0, 0.0);
589
590     /* Set -r */
591     ia[mlp->ci] = peer->r_c9;
592     ja[mlp->ci] = mlp->c_r;
593     ar[mlp->ci] = -1;
594     mlp->ci++;
595 #endif
596
597     while (addr != NULL)
598     {
599       mlpi = (struct MLP_information *) addr->mlp_information;
600
601       /* coefficient for c 2) */
602
603       ia[mlp->ci] = peer->r_c2;
604       ja[mlp->ci] = mlpi->c_n;
605       ar[mlp->ci] = 1;
606       mlp->ci++;
607
608       /* coefficient for c 8) */
609       ia[mlp->ci] = mlp->r_c8;
610       ja[mlp->ci] = mlpi->c_b;
611       ar[mlp->ci] = peer->f;
612       mlp->ci++;
613
614 #if ENABLE_C9
615       /* coefficient for c 9) */
616       ia[mlp->ci] = peer->r_c9;
617       ja[mlp->ci] = mlpi->c_b;
618       ar[mlp->ci] = 1;
619       mlp->ci++;
620 #endif
621
622       addr = addr->next;
623     }
624     peer = peer->next;
625   }
626
627   /* c 7) For all quality metrics */
628
629
630   for (c = 0; c < mlp->m_q; c++)
631   {
632     struct ATS_Peer *tp;
633     struct ATS_Address *ta;
634     struct MLP_information * mlpi;
635     double value = 1.0;
636
637     /* Adding rows for c 7) */
638     mlp->r_q[c] = glp_add_rows (mlp->prob, 1);
639     GNUNET_asprintf(&name, "c7_q%i_%s", c, mlp_ats_to_string(mlp->q[c]));
640     glp_set_row_name (mlp->prob, mlp->r_q[c], name);
641     GNUNET_free (name);
642     /* Set row bound == 0 */
643     glp_set_row_bnds (mlp->prob, mlp->r_q[c], GLP_LO, 0.0, 0.0);
644
645     ia[mlp->ci] = mlp->r_q[c];
646     ja[mlp->ci] = mlp->c_q[c];
647     ar[mlp->ci] = -1;
648     mlp->ci++;
649
650     for (tp = mlp->peer_head; tp != NULL; tp = tp->next)
651       for (ta = tp->head; ta != NULL; ta = ta->next)
652         {
653           mlpi = ta->mlp_information;
654           value = mlpi->q_averaged[c];
655
656           mlpi->r_q[c] = mlp->r_q[c];
657
658           ia[mlp->ci] = mlp->r_q[c];
659           ja[mlp->ci] = mlpi->c_b;
660           ar[mlp->ci] = tp->f * value;
661           mlp->ci++;
662         }
663   }
664 }
665
666
667 /**
668  * Add columns for all addresses
669  *
670  * @param cls GAS_MLP_Handle
671  * @param key Hashcode
672  * @param value ATS_Address
673  *
674  * @return GNUNET_OK to continue
675  */
676 static int
677 create_columns_it (void *cls, const GNUNET_HashCode * key, void *value)
678 {
679   struct GAS_MLP_Handle *mlp = cls;
680   struct ATS_Address *address = value;
681   struct MLP_information *mlpi;
682   unsigned int col;
683   char *name;
684
685   GNUNET_assert (address->mlp_information != NULL);
686   mlpi = address->mlp_information;
687
688   /* Add bandwidth column */
689   col = glp_add_cols (mlp->prob, 2);
690   mlpi->c_b = col;
691   mlpi->c_n = col + 1;
692
693
694   GNUNET_asprintf (&name, "b_%s_%s", GNUNET_i2s (&address->peer), address->plugin);
695   glp_set_col_name (mlp->prob, mlpi->c_b , name);
696   GNUNET_free (name);
697   /* Lower bound == 0 */
698   glp_set_col_bnds (mlp->prob, mlpi->c_b , GLP_LO, 0.0, 0.0);
699   /* Continuous value*/
700   glp_set_col_kind (mlp->prob, mlpi->c_b , GLP_CV);
701   /* Objective function coefficient == 0 */
702   glp_set_obj_coef (mlp->prob, mlpi->c_b , 0);
703
704
705   /* Add usage column */
706   GNUNET_asprintf (&name, "n_%s_%s", GNUNET_i2s (&address->peer), address->plugin);
707   glp_set_col_name (mlp->prob, mlpi->c_n, name);
708   GNUNET_free (name);
709   /* Limit value : 0 <= value <= 1 */
710   glp_set_col_bnds (mlp->prob, mlpi->c_n, GLP_DB, 0.0, 1.0);
711   /* Integer value*/
712   glp_set_col_kind (mlp->prob, mlpi->c_n, GLP_IV);
713   /* Objective function coefficient == 0 */
714   glp_set_obj_coef (mlp->prob, mlpi->c_n, 0);
715
716   return GNUNET_OK;
717 }
718
719
720
721 /**
722  * Create the MLP problem
723  *
724  * @param mlp the MLP handle
725  * @param addresses the hashmap containing all adresses
726  * @return GNUNET_OK or GNUNET_SYSERR
727  */
728 static int
729 mlp_create_problem (struct GAS_MLP_Handle *mlp, struct GNUNET_CONTAINER_MultiHashMap * addresses)
730 {
731   int res = GNUNET_OK;
732   int col;
733   int c;
734   char *name;
735
736   GNUNET_assert (mlp->prob == NULL);
737
738   /* create the glpk problem */
739   mlp->prob = glp_create_prob ();
740
741   /* Set a problem name */
742   glp_set_prob_name (mlp->prob, "gnunet ats bandwidth distribution");
743
744   /* Set optimization direction to maximize */
745   glp_set_obj_dir (mlp->prob, GLP_MAX);
746
747   /* Adding invariant columns */
748
749   /* Diversity d column  */
750
751   col = glp_add_cols (mlp->prob, 1);
752   mlp->c_d = col;
753   /* Column name */
754   glp_set_col_name (mlp->prob, col, "d");
755   /* Column objective function coefficient */
756   glp_set_obj_coef (mlp->prob, col, mlp->co_D);
757   /* Column lower bound = 0.0 */
758   glp_set_col_bnds (mlp->prob, col, GLP_LO, 0.0, 0.0);
759
760   /* Utilization u column  */
761
762   col = glp_add_cols (mlp->prob, 1);
763   mlp->c_u = col;
764   /* Column name */
765   glp_set_col_name (mlp->prob, col, "u");
766   /* Column objective function coefficient */
767   glp_set_obj_coef (mlp->prob, col, mlp->co_U);
768   /* Column lower bound = 0.0 */
769   glp_set_col_bnds (mlp->prob, col, GLP_LO, 0.0, 0.0);
770
771 #if ENABLE_C9
772   /* Relativity r column  */
773   col = glp_add_cols (mlp->prob, 1);
774   mlp->c_r = col;
775   /* Column name */
776   glp_set_col_name (mlp->prob, col, "r");
777   /* Column objective function coefficient */
778   glp_set_obj_coef (mlp->prob, col, mlp->co_R);
779   /* Column lower bound = 0.0 */
780   glp_set_col_bnds (mlp->prob, col, GLP_LO, 0.0, 0.0);
781 #endif
782
783   /* Quality metric columns */
784   col = glp_add_cols(mlp->prob, mlp->m_q);
785   for (c = 0; c < mlp->m_q; c++)
786   {
787     mlp->c_q[c] = col + c;
788     GNUNET_asprintf (&name, "q_%u", mlp->q[c]);
789     glp_set_col_name (mlp->prob, col + c, name);
790     /* Column lower bound = 0.0 */
791     glp_set_col_bnds (mlp->prob, col + c, GLP_LO, 0.0, 0.0);
792     GNUNET_free (name);
793     /* Coefficient == Qm */
794     glp_set_obj_coef (mlp->prob, col + c, mlp->co_Q[c]);
795   }
796
797   /* Add columns for addresses */
798   GNUNET_CONTAINER_multihashmap_iterate (addresses, create_columns_it, mlp);
799
800   /* Add constraints */
801   mlp_add_constraints_all_addresses (mlp, addresses);
802
803   /* Load the matrix */
804   glp_load_matrix(mlp->prob, (mlp->ci-1), mlp->ia, mlp->ja, mlp->ar);
805
806   return res;
807 }
808
809
810 struct SolveContext
811 {
812   struct GNUNET_TIME_Relative lp_duration;
813   struct GNUNET_TIME_Relative mlp_duration;
814 };
815
816
817 /**
818  * Solves the LP problem
819  *
820  * @param mlp the MLP Handle
821  * @param s_ctx context to return results
822  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
823  */
824 static int
825 mlp_solve_lp_problem (struct GAS_MLP_Handle *mlp, struct SolveContext *s_ctx)
826 {
827   int res;
828   struct GNUNET_TIME_Relative duration;
829   struct GNUNET_TIME_Absolute end;
830   struct GNUNET_TIME_Absolute start = GNUNET_TIME_absolute_get();
831
832   /* LP presolver?
833    * Presolver is required if the problem was modified and an existing
834    * valid basis is now invalid */
835   if (mlp->presolver_required == GNUNET_YES)
836     mlp->control_param_lp.presolve = GLP_ON;
837   else
838     mlp->control_param_lp.presolve = GLP_OFF;
839
840   /* Solve LP problem to have initial valid solution */
841 lp_solv:
842   res = glp_simplex(mlp->prob, &mlp->control_param_lp);
843   if (res == 0)
844   {
845     /* The LP problem instance has been successfully solved. */
846   }
847   else if (res == GLP_EITLIM)
848   {
849     /* simplex iteration limit has been exceeded. */
850     // TODO Increase iteration limit?
851   }
852   else if (res == GLP_ETMLIM)
853   {
854     /* Time limit has been exceeded.  */
855     // TODO Increase time limit?
856   }
857   else
858   {
859     /* Problem was ill-defined, retry with presolver */
860     if (mlp->presolver_required == GNUNET_NO)
861     {
862       mlp->presolver_required = GNUNET_YES;
863       goto lp_solv;
864     }
865     else
866     {
867       /* Problem was ill-defined, no way to handle that */
868       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
869           "ats-mlp",
870           "Solving LP problem failed: %i %s\n", res, mlp_solve_to_string(res));
871       return GNUNET_SYSERR;
872     }
873   }
874
875   end = GNUNET_TIME_absolute_get ();
876   duration = GNUNET_TIME_absolute_get_difference (start, end);
877   mlp->lp_solved++;
878   mlp->lp_total_duration =+ duration.rel_value;
879   s_ctx->lp_duration = duration;
880
881   GNUNET_STATISTICS_update (mlp->stats,"# LP problem solved", 1, GNUNET_NO);
882   GNUNET_STATISTICS_set (mlp->stats,"# LP execution time (ms)", duration.rel_value, GNUNET_NO);
883   GNUNET_STATISTICS_set (mlp->stats,"# LP execution time average (ms)",
884                          mlp->lp_total_duration / mlp->lp_solved,  GNUNET_NO);
885
886
887   /* Analyze problem status  */
888   res = glp_get_status (mlp->prob);
889   switch (res) {
890     /* solution is optimal */
891     case GLP_OPT:
892     /* solution is feasible */
893     case GLP_FEAS:
894       break;
895
896     /* Problem was ill-defined, no way to handle that */
897     default:
898       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
899           "ats-mlp",
900           "Solving LP problem failed, no solution: %s\n", mlp_status_to_string(res));
901       return GNUNET_SYSERR;
902       break;
903   }
904
905   /* solved sucessfully, no presolver required next time */
906   mlp->presolver_required = GNUNET_NO;
907
908   return GNUNET_OK;
909 }
910
911
912 /**
913  * Solves the MLP problem
914  *
915  * @param mlp the MLP Handle
916  * @param s_ctx context to return results
917  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
918  */
919 int
920 mlp_solve_mlp_problem (struct GAS_MLP_Handle *mlp, struct SolveContext *s_ctx)
921 {
922   int res;
923   struct GNUNET_TIME_Relative duration;
924   struct GNUNET_TIME_Absolute end;
925   struct GNUNET_TIME_Absolute start = GNUNET_TIME_absolute_get();
926
927   /* solve MLP problem */
928   res = glp_intopt(mlp->prob, &mlp->control_param_mlp);
929
930   if (res == 0)
931   {
932     /* The MLP problem instance has been successfully solved. */
933   }
934   else if (res == GLP_EITLIM)
935   {
936     /* simplex iteration limit has been exceeded. */
937     // TODO Increase iteration limit?
938   }
939   else if (res == GLP_ETMLIM)
940   {
941     /* Time limit has been exceeded.  */
942     // TODO Increase time limit?
943   }
944   else
945   {
946     /* Problem was ill-defined, no way to handle that */
947     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
948         "ats-mlp",
949         "Solving MLP problem failed:  %s\n", mlp_solve_to_string(res));
950     return GNUNET_SYSERR;
951   }
952
953   end = GNUNET_TIME_absolute_get ();
954   duration = GNUNET_TIME_absolute_get_difference (start, end);
955   mlp->mlp_solved++;
956   mlp->mlp_total_duration =+ duration.rel_value;
957   s_ctx->mlp_duration = duration;
958
959   GNUNET_STATISTICS_update (mlp->stats,"# MLP problem solved", 1, GNUNET_NO);
960   GNUNET_STATISTICS_set (mlp->stats,"# MLP execution time (ms)", duration.rel_value, GNUNET_NO);
961   GNUNET_STATISTICS_set (mlp->stats,"# MLP execution time average (ms)",
962                          mlp->mlp_total_duration / mlp->mlp_solved,  GNUNET_NO);
963
964   /* Analyze problem status  */
965   res = glp_mip_status(mlp->prob);
966   switch (res) {
967     /* solution is optimal */
968     case GLP_OPT:
969     /* solution is feasible */
970     case GLP_FEAS:
971       break;
972
973     /* Problem was ill-defined, no way to handle that */
974     default:
975       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
976           "ats-mlp",
977           "Solving MLP problem failed, %s\n\n", mlp_status_to_string(res));
978       return GNUNET_SYSERR;
979       break;
980   }
981
982   return GNUNET_OK;
983 }
984
985 int GAS_mlp_solve_problem (struct GAS_MLP_Handle *mlp);
986
987 static void
988 mlp_scheduler (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
989 {
990   struct GAS_MLP_Handle *mlp = cls;
991
992   mlp->mlp_task = GNUNET_SCHEDULER_NO_TASK;
993
994   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
995     return;
996
997
998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Scheduled problem solving\n");
999
1000   if (mlp->addr_in_problem != 0)
1001     GAS_mlp_solve_problem(mlp);
1002 }
1003
1004 /**
1005  * Solves the MLP problem
1006  *
1007  * @param mlp the MLP Handle
1008  * @return GNUNET_OK if could be solved, GNUNET_SYSERR on failure
1009  */
1010 int
1011 GAS_mlp_solve_problem (struct GAS_MLP_Handle *mlp)
1012 {
1013   int res;
1014   struct SolveContext s_ctx;
1015   mlp->last_execution = GNUNET_TIME_absolute_get ();
1016
1017   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Solve LP problem\n");
1018 #if WRITE_MLP
1019   char * name;
1020   static int i;
1021   i++;
1022   GNUNET_asprintf(&name, "problem_%i", i);
1023   glp_write_lp (mlp->prob, 0, name);
1024   GNUNET_free (name);
1025 # endif
1026
1027   res = mlp_solve_lp_problem (mlp, &s_ctx);
1028   if (res != GNUNET_OK)
1029   {
1030     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "LP Problem solving failed\n");
1031     return GNUNET_SYSERR;
1032   }
1033 #if WRITE_MLP
1034   GNUNET_asprintf(&name, "problem_%i_lp_solution", i);
1035   glp_print_sol (mlp->prob,  name);
1036   GNUNET_free (name);
1037 # endif
1038
1039
1040   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Solve MLP problem\n");
1041   res = mlp_solve_mlp_problem (mlp, &s_ctx);
1042   if (res != GNUNET_OK)
1043   {
1044     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MLP Problem solving failed\n");
1045     return GNUNET_SYSERR;
1046   }
1047 #if WRITE_MLP
1048   GNUNET_asprintf(&name, "problem_%i_mlp_solution", i);
1049   glp_print_mip (mlp->prob, name);
1050   GNUNET_free (name);
1051 # endif
1052
1053   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Problem solved %s (LP duration %llu / MLP duration %llu)\n",
1054       (GNUNET_OK == res) ? "successfully" : "failed", s_ctx.lp_duration, s_ctx.mlp_duration);
1055   /* Process result */
1056   struct ATS_Peer *p = NULL;
1057   struct ATS_Address *a = NULL;
1058   struct MLP_information *mlpi = NULL;
1059
1060   for (p = mlp->peer_head; p != NULL; p = p->next)
1061   {
1062     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s'\n", GNUNET_i2s (&p->id));
1063     for (a = p->head; a != NULL; a = a->next)
1064     {
1065       double b = 0.0;
1066       double n = 0.0;
1067
1068       mlpi = a->mlp_information;
1069
1070       b = glp_mip_col_val(mlp->prob, mlpi->c_b);
1071       mlpi->b = b;
1072
1073       n = glp_mip_col_val(mlp->prob, mlpi->c_n);
1074       if (n == 1.0)
1075         mlpi->n = GNUNET_YES;
1076       else
1077         mlpi->n = GNUNET_NO;
1078
1079       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tAddress %s %f\n",
1080           (n == 1.0) ? "[x]" : "[ ]", b);
1081     }
1082   }
1083
1084   if (mlp->mlp_task != GNUNET_SCHEDULER_NO_TASK)
1085   {
1086     GNUNET_SCHEDULER_cancel(mlp->mlp_task);
1087     mlp->mlp_task = GNUNET_SCHEDULER_NO_TASK;
1088   }
1089   mlp->mlp_task = GNUNET_SCHEDULER_add_delayed (mlp->exec_interval, &mlp_scheduler, mlp);
1090   return res;
1091 }
1092
1093 /**
1094  * Init the MLP problem solving component
1095  *
1096  * @param cfg the GNUNET_CONFIGURATION_Handle handle
1097  * @param stats the GNUNET_STATISTICS handle
1098  * @param max_duration maximum numbers of iterations for the LP/MLP Solver
1099  * @param max_iterations maximum time limit for the LP/MLP Solver
1100  * @return struct GAS_MLP_Handle * on success, NULL on fail
1101  */
1102 struct GAS_MLP_Handle *
1103 GAS_mlp_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1104               const struct GNUNET_STATISTICS_Handle *stats,
1105               struct GNUNET_TIME_Relative max_duration,
1106               unsigned int max_iterations)
1107 {
1108   struct GAS_MLP_Handle * mlp = GNUNET_malloc (sizeof (struct GAS_MLP_Handle));
1109
1110   double D;
1111   double R;
1112   double U;
1113   long long unsigned int tmp;
1114   unsigned int b_min;
1115   unsigned int n_min;
1116   struct GNUNET_TIME_Relative i_exec;
1117   int c;
1118   char * quota_out_str;
1119   char * quota_in_str;
1120
1121   /* Init GLPK environment */
1122   GNUNET_assert (glp_init_env() == 0);
1123
1124   /* Create initial MLP problem */
1125   mlp->prob = glp_create_prob();
1126   GNUNET_assert (mlp->prob != NULL);
1127
1128   mlp->BIG_M = (double) BIG_M_VALUE;
1129
1130   /* Get diversity coefficient from configuration */
1131   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1132                                                       "COEFFICIENT_D",
1133                                                       &tmp))
1134     D = (double) tmp / 100;
1135   else
1136     D = 1.0;
1137
1138   /* Get proportionality coefficient from configuration */
1139   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1140                                                       "COEFFICIENT_R",
1141                                                       &tmp))
1142     R = (double) tmp / 100;
1143   else
1144     R = 1.0;
1145
1146   /* Get utilization coefficient from configuration */
1147   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1148                                                       "COEFFICIENT_U",
1149                                                       &tmp))
1150     U = (double) tmp / 100;
1151   else
1152     U = 1.0;
1153
1154   /* Get quality metric coefficients from configuration */
1155   int i_delay = -1;
1156   int i_distance = -1;
1157   int q[GNUNET_ATS_QualityPropertiesCount] = GNUNET_ATS_QualityProperties;
1158   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
1159   {
1160     /* initialize quality coefficients with default value 1.0 */
1161     mlp->co_Q[c] = 1.0;
1162
1163     mlp->q[c] = q[c];
1164     if (q[c] == GNUNET_ATS_QUALITY_NET_DELAY)
1165       i_delay = c;
1166     if (q[c] == GNUNET_ATS_QUALITY_NET_DISTANCE)
1167       i_distance = c;
1168   }
1169
1170   if ((i_delay != -1) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1171                                                       "COEFFICIENT_QUALITY_DELAY",
1172                                                       &tmp)))
1173
1174     mlp->co_Q[i_delay] = (double) tmp / 100;
1175   else
1176     mlp->co_Q[i_delay] = 1.0;
1177
1178   if ((i_distance != -1) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1179                                                       "COEFFICIENT_QUALITY_DISTANCE",
1180                                                       &tmp)))
1181     mlp->co_Q[i_distance] = (double) tmp / 100;
1182   else
1183     mlp->co_Q[i_distance] = 1.0;
1184
1185   /* Get minimum bandwidth per used address from configuration */
1186   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1187                                                       "MIN_BANDWIDTH",
1188                                                       &tmp))
1189     b_min = tmp;
1190   else
1191   {
1192     b_min = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1193   }
1194
1195   /* Get minimum number of connections from configuration */
1196   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats",
1197                                                       "MIN_CONNECTIONS",
1198                                                       &tmp))
1199     n_min = tmp;
1200   else
1201     n_min = 4;
1202
1203   /* Init network quotas */
1204   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
1205   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
1206   {
1207     mlp->quota_index[c] = quotas[c];
1208     static char * entry_in = NULL;
1209     static char * entry_out = NULL;
1210     unsigned long long quota_in = 0;
1211     unsigned long long quota_out = 0;
1212
1213     switch (quotas[c]) {
1214       case GNUNET_ATS_NET_UNSPECIFIED:
1215         entry_out = "UNSPECIFIED_QUOTA_OUT";
1216         entry_in = "UNSPECIFIED_QUOTA_IN";
1217         break;
1218       case GNUNET_ATS_NET_LOOPBACK:
1219         entry_out = "LOOPBACK_QUOTA_OUT";
1220         entry_in = "LOOPBACK_QUOTA_IN";
1221         break;
1222       case GNUNET_ATS_NET_LAN:
1223         entry_out = "LAN_QUOTA_OUT";
1224         entry_in = "LAN_QUOTA_IN";
1225         break;
1226       case GNUNET_ATS_NET_WAN:
1227         entry_out = "WAN_QUOTA_OUT";
1228         entry_in = "WAN_QUOTA_IN";
1229         break;
1230       case GNUNET_ATS_NET_WLAN:
1231         entry_out = "WLAN_QUOTA_OUT";
1232         entry_in = "WLAN_QUOTA_IN";
1233         break;
1234       default:
1235         break;
1236     }
1237
1238     if ((entry_in == NULL) || (entry_out == NULL))
1239       continue;
1240
1241     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
1242     {
1243       if (0 == strcmp(quota_out_str, BIG_M_STRING) ||
1244           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &quota_out)))
1245         quota_out = mlp->BIG_M;
1246
1247       GNUNET_free (quota_out_str);
1248       quota_out_str = NULL;
1249     }
1250     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
1251     {
1252       quota_out = mlp->BIG_M;
1253     }
1254     else
1255     {
1256       quota_out = mlp->BIG_M;
1257     }
1258
1259     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
1260     {
1261       if (0 == strcmp(quota_in_str, BIG_M_STRING) ||
1262           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &quota_in)))
1263         quota_in = mlp->BIG_M;
1264
1265       GNUNET_free (quota_in_str);
1266       quota_in_str = NULL;
1267     }
1268     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
1269     {
1270       quota_in = mlp->BIG_M;
1271     }
1272     else
1273     {
1274       quota_in = mlp->BIG_M;
1275     }
1276
1277     /* Check if defined quota could make problem unsolvable */
1278     if (((n_min * b_min) > quota_out) && (GNUNET_ATS_NET_UNSPECIFIED != quotas[c]))
1279     {
1280       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Inconsistent quota configuration value `%s': " \
1281           "outbound quota (%u Bps) too small for combination of minimum connections and minimum bandwidth per peer (%u * %u Bps = %u)\n", entry_out, quota_out, n_min, b_min, n_min * b_min);
1282
1283       GAS_mlp_done(mlp);
1284       mlp = NULL;
1285       return NULL;
1286     }
1287
1288     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found `%s' quota %llu and `%s' quota %llu\n",
1289                 entry_out, quota_out, entry_in, quota_in);
1290     GNUNET_STATISTICS_update ((struct GNUNET_STATISTICS_Handle *) stats, entry_out, quota_out, GNUNET_NO);
1291     GNUNET_STATISTICS_update ((struct GNUNET_STATISTICS_Handle *) stats, entry_in, quota_in, GNUNET_NO);
1292     mlp->quota_out[c] = quota_out;
1293     mlp->quota_in[c] = quota_in;
1294   }
1295
1296   /* Get minimum number of connections from configuration */
1297   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_time (cfg, "ats",
1298                                                         "ATS_EXEC_INTERVAL",
1299                                                         &i_exec))
1300     mlp->exec_interval = i_exec;
1301   else
1302     mlp->exec_interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30);
1303
1304   mlp->stats = (struct GNUNET_STATISTICS_Handle *) stats;
1305   mlp->max_iterations = max_iterations;
1306   mlp->max_exec_duration = max_duration;
1307   mlp->auto_solve = GNUNET_YES;
1308
1309   /* Redirect GLPK output to GNUnet logging */
1310   glp_error_hook((void *) mlp, &mlp_term_hook);
1311
1312   /* Init LP solving parameters */
1313   glp_init_smcp(&mlp->control_param_lp);
1314
1315   mlp->control_param_lp.msg_lev = GLP_MSG_OFF;
1316 #if VERBOSE_GLPK
1317   mlp->control_param_lp.msg_lev = GLP_MSG_ALL;
1318 #endif
1319
1320   mlp->control_param_lp.it_lim = max_iterations;
1321   mlp->control_param_lp.tm_lim = max_duration.rel_value;
1322
1323   /* Init MLP solving parameters */
1324   glp_init_iocp(&mlp->control_param_mlp);
1325
1326   mlp->control_param_mlp.msg_lev = GLP_MSG_OFF;
1327 #if VERBOSE_GLPK
1328   mlp->control_param_mlp.msg_lev = GLP_MSG_ALL;
1329 #endif
1330   mlp->control_param_mlp.tm_lim = max_duration.rel_value;
1331
1332   mlp->last_execution = GNUNET_TIME_absolute_get_forever();
1333
1334   mlp->co_D = D;
1335   mlp->co_R = R;
1336   mlp->co_U = U;
1337   mlp->b_min = b_min;
1338   mlp->n_min = n_min;
1339   mlp->m_q = GNUNET_ATS_QualityPropertiesCount;
1340
1341   return mlp;
1342 }
1343
1344 static void
1345 update_quality (struct GAS_MLP_Handle *mlp, struct ATS_Address * address)
1346 {
1347   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating quality metrics for peer `%s'\n",
1348       GNUNET_i2s (&address->peer));
1349
1350   GNUNET_assert (NULL != address);
1351   GNUNET_assert (NULL != address->mlp_information);
1352   GNUNET_assert (NULL != address->ats);
1353
1354   struct MLP_information *mlpi = address->mlp_information;
1355   struct GNUNET_ATS_Information *ats = address->ats;
1356   GNUNET_assert (mlpi != NULL);
1357
1358   int c;
1359   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
1360   {
1361     int index = mlp_lookup_ats(address, mlp->q[c]);
1362
1363     if (index == GNUNET_SYSERR)
1364       continue;
1365
1366     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating address for peer `%s' value `%s': %f\n",
1367         GNUNET_i2s (&address->peer),
1368         mlp_ats_to_string(mlp->q[c]),
1369         (double) ats[index].value);
1370
1371     int i = mlpi->q_avg_i[c];
1372     double * qp = mlpi->q[c];
1373     qp[i] = (double) ats[index].value;
1374
1375     int t;
1376     for (t = 0; t < MLP_AVERAGING_QUEUE_LENGTH; t++)
1377     {
1378       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s': `%s' queue[%u]: %f\n",
1379         GNUNET_i2s (&address->peer),
1380         mlp_ats_to_string(mlp->q[c]),
1381         t,
1382         qp[t]);
1383     }
1384
1385     if (mlpi->q_avg_i[c] + 1 < (MLP_AVERAGING_QUEUE_LENGTH))
1386       mlpi->q_avg_i[c] ++;
1387     else
1388       mlpi->q_avg_i[c] = 0;
1389
1390
1391     int c2;
1392     int c3;
1393     double avg = 0.0;
1394     switch (mlp->q[c])
1395     {
1396       case GNUNET_ATS_QUALITY_NET_DELAY:
1397         c3 = 0;
1398         for (c2 = 0; c2 < MLP_AVERAGING_QUEUE_LENGTH; c2++)
1399         {
1400           if (mlpi->q[c][c2] != -1)
1401           {
1402             double * t2 = mlpi->q[c] ;
1403             avg += t2[c2];
1404             c3 ++;
1405           }
1406         }
1407         if (c3 > 0)
1408           /* avg = 1 / ((q[0] + ... + q[l]) /c3) => c3 / avg*/
1409           mlpi->q_averaged[c] = (double) c3 / avg;
1410         else
1411           mlpi->q_averaged[c] = 0.0;
1412
1413         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s': `%s' average sum: %f, average: %f, weight: %f\n",
1414           GNUNET_i2s (&address->peer),
1415           mlp_ats_to_string(mlp->q[c]),
1416           avg,
1417           avg / (double) c3,
1418           mlpi->q_averaged[c]);
1419
1420         break;
1421       case GNUNET_ATS_QUALITY_NET_DISTANCE:
1422         c3 = 0;
1423         for (c2 = 0; c2 < MLP_AVERAGING_QUEUE_LENGTH; c2++)
1424         {
1425           if (mlpi->q[c][c2] != -1)
1426           {
1427             double * t2 = mlpi->q[c] ;
1428             avg += t2[c2];
1429             c3 ++;
1430           }
1431         }
1432         if (c3 > 0)
1433           /* avg = 1 / ((q[0] + ... + q[l]) /c3) => c3 / avg*/
1434           mlpi->q_averaged[c] = (double) c3 / avg;
1435         else
1436           mlpi->q_averaged[c] = 0.0;
1437
1438         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s': `%s' average sum: %f, average: %f, weight: %f\n",
1439           GNUNET_i2s (&address->peer),
1440           mlp_ats_to_string(mlp->q[c]),
1441           avg,
1442           avg / (double) c3,
1443           mlpi->q_averaged[c]);
1444
1445         break;
1446       default:
1447         break;
1448     }
1449
1450     if ((mlpi->c_b != 0) && (mlpi->r_q[c] != 0))
1451     {
1452
1453       /* Get current number of columns */
1454       int found = GNUNET_NO;
1455       int cols = glp_get_num_cols(mlp->prob);
1456       int *ind = GNUNET_malloc (cols * sizeof (int) + 1);
1457       double *val = GNUNET_malloc (cols * sizeof (double) + 1);
1458
1459       /* Get the matrix row of quality */
1460       int length = glp_get_mat_row(mlp->prob, mlp->r_q[c], ind, val);
1461       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "cols %i, length %i c_b %i\n", cols, length, mlpi->c_b);
1462       int c4;
1463       /* Get the index if matrix row of quality */
1464       for (c4 = 1; c4 <= length; c4++ )
1465       {
1466         if (mlpi->c_b == ind[c4])
1467         {
1468           /* Update the value */
1469           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating quality `%s' column `%s' row `%s' : %f -> %f\n",
1470               mlp_ats_to_string(mlp->q[c]),
1471               glp_get_col_name (mlp->prob, ind[c4]),
1472               glp_get_row_name (mlp->prob, mlp->r_q[c]),
1473               val[c4],
1474               mlpi->q_averaged[c]);
1475           val[c4] = mlpi->q_averaged[c];
1476           found = GNUNET_YES;
1477           break;
1478         }
1479       }
1480
1481       if (found == GNUNET_NO)
1482         {
1483
1484           ind[length+1] = mlpi->c_b;
1485           val[length+1] = mlpi->q_averaged[c];
1486           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%i ind[%i] val[%i]:  %i %f\n", length+1,  length+1, length+1, mlpi->c_b, mlpi->q_averaged[c]);
1487           glp_set_mat_row (mlp->prob, mlpi->r_q[c], length+1, ind, val);
1488         }
1489       else
1490         {
1491         /* Get the index if matrix row of quality */
1492         glp_set_mat_row (mlp->prob, mlpi->r_q[c], length, ind, val);
1493         }
1494
1495       GNUNET_free (ind);
1496       GNUNET_free (val);
1497     }
1498   }
1499 }
1500
1501 /**
1502  * Updates a single address in the MLP problem
1503  *
1504  * If the address did not exist before in the problem:
1505  * The MLP problem has to be recreated and the problem has to be resolved
1506  *
1507  * Otherwise the addresses' values can be updated and the existing base can
1508  * be reused
1509  *
1510  * @param mlp the MLP Handle
1511  * @param addresses the address hashmap
1512  *        the address has to be already removed from the hashmap
1513  * @param address the address to update
1514  */
1515 void
1516 GAS_mlp_address_update (struct GAS_MLP_Handle *mlp, struct GNUNET_CONTAINER_MultiHashMap * addresses, struct ATS_Address *address)
1517 {
1518   int new;
1519   struct MLP_information *mlpi;
1520
1521   GNUNET_STATISTICS_update (mlp->stats, "# MLP address updates", 1, GNUNET_NO);
1522
1523   /* We add a new address */
1524   if (address->mlp_information == NULL)
1525     new = GNUNET_YES;
1526   else
1527     new = GNUNET_NO;
1528
1529   /* Do the update */
1530   if (new == GNUNET_YES)
1531   {
1532     mlpi = GNUNET_malloc (sizeof (struct MLP_information));
1533
1534     int c;
1535     for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
1536     {
1537       int c2;
1538       mlpi->r_q[c] = 0;
1539       for (c2 = 0; c2 < MLP_AVERAGING_QUEUE_LENGTH; c2++)
1540         mlpi->q[c][c2] = -1.0; /* -1.0: invalid value */
1541       mlpi->q_avg_i[c] = 0;
1542       mlpi->q_averaged[c] = 0.0;
1543     }
1544
1545     address->mlp_information = mlpi;
1546     mlp->addr_in_problem ++;
1547     GNUNET_STATISTICS_update (mlp->stats, "# addresses in MLP", 1, GNUNET_NO);
1548
1549     /* Check for and add peer */
1550     struct ATS_Peer *peer = mlp_find_peer (mlp, &address->peer);
1551     if (peer == NULL)
1552     {
1553
1554       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding new peer `%s'\n",
1555           GNUNET_i2s (&address->peer));
1556
1557       peer = GNUNET_malloc (sizeof (struct ATS_Peer));
1558       peer->head = NULL;
1559       peer->tail = NULL;
1560
1561       int c;
1562       for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
1563       {
1564         peer->f_q[c] = 1.0;
1565       }
1566       peer->f = 1.0;
1567
1568       memcpy (&peer->id, &address->peer, sizeof (struct GNUNET_PeerIdentity));
1569       GNUNET_assert(address->prev == NULL);
1570       GNUNET_assert(address->next == NULL);
1571       GNUNET_CONTAINER_DLL_insert (peer->head, peer->tail, address);
1572       GNUNET_CONTAINER_DLL_insert (mlp->peer_head, mlp->peer_tail, peer);
1573       mlp->c_p ++;
1574       GNUNET_STATISTICS_update (mlp->stats, "# peers in MLP", 1, GNUNET_NO);
1575     }
1576     else
1577     {
1578
1579       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding address to peer `%s'\n",
1580           GNUNET_i2s (&address->peer));
1581
1582       GNUNET_CONTAINER_DLL_insert (peer->head, peer->tail, address);
1583     }
1584     update_quality (mlp, address);
1585   }
1586   else
1587   {
1588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating existing address to peer `%s'\n",
1589         GNUNET_i2s (&address->peer));
1590
1591     update_quality (mlp, address);
1592   }
1593
1594   /* Recalculate */
1595   if (new == GNUNET_YES)
1596   {
1597     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Recreating problem: new address\n");
1598
1599     mlp_delete_problem (mlp);
1600     mlp_create_problem (mlp, addresses);
1601     mlp->presolver_required = GNUNET_YES;
1602   }
1603   if (mlp->auto_solve == GNUNET_YES)
1604     GAS_mlp_solve_problem (mlp);
1605 }
1606
1607 /**
1608  * Deletes a single address in the MLP problem
1609  *
1610  * The MLP problem has to be recreated and the problem has to be resolved
1611  *
1612  * @param mlp the MLP Handle
1613  * @param addresses the address hashmap
1614  *        the address has to be already removed from the hashmap
1615  * @param address the address to delete
1616  */
1617 void
1618 GAS_mlp_address_delete (struct GAS_MLP_Handle *mlp, struct GNUNET_CONTAINER_MultiHashMap * addresses, struct ATS_Address *address)
1619 {
1620   GNUNET_STATISTICS_update (mlp->stats,"# LP address deletions", 1, GNUNET_NO);
1621
1622   /* Free resources */
1623   if (address->mlp_information != NULL)
1624   {
1625     GNUNET_free (address->mlp_information);
1626     address->mlp_information = NULL;
1627
1628     mlp->addr_in_problem --;
1629     GNUNET_STATISTICS_update (mlp->stats, "# addresses in MLP", -1, GNUNET_NO);
1630   }
1631
1632   /* Remove from peer list */
1633   struct ATS_Peer *head = mlp_find_peer (mlp, &address->peer);
1634   GNUNET_assert (head != NULL);
1635
1636   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleting address for `%s'\n", GNUNET_i2s (&address->peer));
1637
1638   GNUNET_CONTAINER_DLL_remove (head->head, head->tail, address);
1639   if ((head->head == NULL) && (head->tail == NULL))
1640   {
1641     /* No address for peer left, remove peer */
1642
1643     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleting peer `%s'\n", GNUNET_i2s (&address->peer));
1644
1645     GNUNET_CONTAINER_DLL_remove (mlp->peer_head, mlp->peer_tail, head);
1646     GNUNET_free (head);
1647     mlp->c_p --;
1648     GNUNET_STATISTICS_update (mlp->stats, "# peers in MLP", -1, GNUNET_NO);
1649   }
1650
1651   /* Update problem */
1652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Recreating problem: new address\n");
1653
1654   mlp_delete_problem (mlp);
1655   if ((GNUNET_CONTAINER_multihashmap_size (addresses) > 0) && (mlp->c_p > 0))
1656   {
1657     mlp_create_problem (mlp, addresses);
1658
1659     /* Recalculate */
1660     mlp->presolver_required = GNUNET_YES;
1661     if (mlp->auto_solve == GNUNET_YES)
1662       GAS_mlp_solve_problem (mlp);
1663   }
1664 }
1665
1666 static int
1667 mlp_get_preferred_address_it (void *cls, const GNUNET_HashCode * key, void *value)
1668 {
1669
1670   struct ATS_PreferedAddress *aa = (struct ATS_PreferedAddress *) cls;
1671   struct ATS_Address *addr = value;
1672   struct MLP_information *mlpi = addr->mlp_information;
1673   if (mlpi == NULL)
1674     return GNUNET_YES;
1675   if (mlpi->n == GNUNET_YES)
1676   {
1677     aa->address = addr;
1678     if (mlpi->b > (double) UINT32_MAX)
1679       aa->bandwidth_out = UINT32_MAX;
1680     else
1681       aa->bandwidth_out = (uint32_t) mlpi->b;
1682     aa->bandwidth_in = 0;
1683     return GNUNET_NO;
1684   }
1685   return GNUNET_YES;
1686 }
1687
1688
1689 /**
1690  * Get the preferred address for a specific peer
1691  *
1692  * @param mlp the MLP Handle
1693  * @param addresses address hashmap
1694  * @param peer the peer
1695  * @return suggested address
1696  */
1697 struct ATS_PreferedAddress *
1698 GAS_mlp_get_preferred_address (struct GAS_MLP_Handle *mlp,
1699                                struct GNUNET_CONTAINER_MultiHashMap * addresses,
1700                                const struct GNUNET_PeerIdentity *peer)
1701 {
1702   struct ATS_PreferedAddress * aa = GNUNET_malloc (sizeof (struct ATS_PreferedAddress));
1703   aa->address = NULL;
1704   aa->bandwidth_in = 0;
1705   aa->bandwidth_out = 0;
1706   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Getting preferred address for `%s'\n", GNUNET_i2s (peer));
1707   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey, mlp_get_preferred_address_it, aa);
1708   return aa;
1709 }
1710
1711
1712 /**
1713  * Changes the preferences for a peer in the MLP problem
1714  *
1715  * @param mlp the MLP Handle
1716  * @param peer the peer
1717  * @param kind the kind to change the preference
1718  * @param score the score
1719  */
1720 void
1721 GAS_mlp_address_change_preference (struct GAS_MLP_Handle *mlp,
1722                                    const struct GNUNET_PeerIdentity *peer,
1723                                    enum GNUNET_ATS_PreferenceKind kind,
1724                                    float score)
1725 {
1726   GNUNET_STATISTICS_update (mlp->stats,"# LP address preference changes", 1, GNUNET_NO);
1727
1728   struct ATS_Peer *p = mlp_find_peer (mlp, peer);
1729   p = p;
1730   /* Here we have to do the matching */
1731 }
1732
1733 /**
1734  * Shutdown the MLP problem solving component
1735  * @param mlp the MLP handle
1736  */
1737 void
1738 GAS_mlp_done (struct GAS_MLP_Handle *mlp)
1739 {
1740   struct ATS_Peer * peer;
1741   struct ATS_Address *addr;
1742
1743   GNUNET_assert (mlp != NULL);
1744
1745   if (mlp->mlp_task != GNUNET_SCHEDULER_NO_TASK)
1746   {
1747     GNUNET_SCHEDULER_cancel(mlp->mlp_task);
1748     mlp->mlp_task = GNUNET_SCHEDULER_NO_TASK;
1749   }
1750
1751   /* clean up peer list */
1752   peer = mlp->peer_head;
1753   while (peer != NULL)
1754   {
1755     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up peer `%s'\n", GNUNET_i2s (&peer->id));
1756     GNUNET_CONTAINER_DLL_remove(mlp->peer_head, mlp->peer_tail, peer);
1757     for (addr = peer->head; NULL != addr; addr = peer->head)
1758     {
1759       GNUNET_CONTAINER_DLL_remove(peer->head, peer->tail, addr);
1760       GNUNET_free (addr->mlp_information);
1761       addr->mlp_information = NULL;
1762     }
1763     GNUNET_free (peer);
1764     peer = mlp->peer_head;
1765   }
1766   mlp_delete_problem (mlp);
1767
1768   /* Clean up GLPK environment */
1769   glp_free_env();
1770
1771   GNUNET_free (mlp);
1772 }
1773
1774
1775 /* end of gnunet-service-ats_addresses_mlp.c */