6af4697e37cdf2a08aa267f736e7751e8cb9e6de
[vpp.git] / plugins / lb-plugin / lb / lb.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <lb/lb.h>
17 #include <vnet/plugin/plugin.h>
18 #include <vnet/api_errno.h>
19
20 //GC runs at most once every so many seconds
21 #define LB_GARBAGE_RUN 60
22
23 //After so many seconds. It is assumed that inter-core race condition will not occur.
24 #define LB_CONCURRENCY_TIMEOUT 10
25
26 lb_main_t lb_main;
27
28 #define lb_get_writer_lock() do {} while(__sync_lock_test_and_set (lb_main.writer_lock, 1))
29 #define lb_put_writer_lock() lb_main.writer_lock[0] = 0
30
31 static void lb_as_stack (lb_as_t *as);
32
33
34 const static char * const lb_dpo_gre4_ip4[] = { "lb4-gre4" , NULL };
35 const static char * const lb_dpo_gre4_ip6[] = { "lb6-gre4" , NULL };
36 const static char* const * const lb_dpo_gre4_nodes[DPO_PROTO_NUM] =
37     {
38         [DPO_PROTO_IP4]  = lb_dpo_gre4_ip4,
39         [DPO_PROTO_IP6]  = lb_dpo_gre4_ip6,
40     };
41
42 const static char * const lb_dpo_gre6_ip4[] = { "lb4-gre6" , NULL };
43 const static char * const lb_dpo_gre6_ip6[] = { "lb6-gre6" , NULL };
44 const static char* const * const lb_dpo_gre6_nodes[DPO_PROTO_NUM] =
45     {
46         [DPO_PROTO_IP4]  = lb_dpo_gre6_ip4,
47         [DPO_PROTO_IP6]  = lb_dpo_gre6_ip6,
48     };
49
50 u32 lb_hash_time_now(vlib_main_t * vm)
51 {
52   return (u32) (vlib_time_now(vm) + 10000);
53 }
54
55 u8 *format_lb_main (u8 * s, va_list * args)
56 {
57   vlib_thread_main_t *tm = vlib_get_thread_main();
58   lb_main_t *lbm = &lb_main;
59   s = format(s, "lb_main");
60   s = format(s, " ip4-src-address: %U \n", format_ip4_address, &lbm->ip4_src_address);
61   s = format(s, " ip6-src-address: %U \n", format_ip6_address, &lbm->ip6_src_address);
62   s = format(s, " #vips: %u\n", pool_elts(lbm->vips));
63   s = format(s, " #ass: %u\n", pool_elts(lbm->ass) - 1);
64
65   u32 cpu_index;
66   for(cpu_index = 0; cpu_index < tm->n_vlib_mains; cpu_index++ ) {
67     lb_hash_t *h = lbm->per_cpu[cpu_index].sticky_ht;
68     if (h) {
69       s = format(s, "core %d\n", cpu_index);
70       s = format(s, "  timeout: %ds\n", h->timeout);
71       s = format(s, "  usage: %d / %d\n", lb_hash_elts(h, lb_hash_time_now(vlib_get_main())),  lb_hash_size(h));
72     }
73   }
74
75   return s;
76 }
77
78 static char *lb_vip_type_strings[] = {
79     [LB_VIP_TYPE_IP6_GRE6] = "ip6-gre6",
80     [LB_VIP_TYPE_IP6_GRE4] = "ip6-gre4",
81     [LB_VIP_TYPE_IP4_GRE6] = "ip4-gre6",
82     [LB_VIP_TYPE_IP4_GRE4] = "ip4-gre4",
83 };
84
85 u8 *format_lb_vip_type (u8 * s, va_list * args)
86 {
87   lb_vip_type_t vipt = va_arg (*args, lb_vip_type_t);
88   u32 i;
89   for (i=0; i<LB_VIP_N_TYPES; i++)
90     if (vipt == i)
91       return format(s, lb_vip_type_strings[i]);
92   return format(s, "_WRONG_TYPE_");
93 }
94
95 uword unformat_lb_vip_type (unformat_input_t * input, va_list * args)
96 {
97   lb_vip_type_t *vipt = va_arg (*args, lb_vip_type_t *);
98   u32 i;
99   for (i=0; i<LB_VIP_N_TYPES; i++)
100     if (unformat(input, lb_vip_type_strings[i])) {
101       *vipt = i;
102       return 1;
103     }
104   return 0;
105 }
106
107 u8 *format_lb_vip (u8 * s, va_list * args)
108 {
109   lb_vip_t *vip = va_arg (*args, lb_vip_t *);
110   return format(s, "%U %U new_size:%u #as:%u%s",
111              format_lb_vip_type, vip->type,
112              format_ip46_prefix, &vip->prefix, vip->plen, IP46_TYPE_ANY,
113              vip->new_flow_table_mask + 1,
114              pool_elts(vip->as_indexes),
115              (vip->flags & LB_VIP_FLAGS_USED)?"":" removed");
116 }
117
118 u8 *format_lb_as (u8 * s, va_list * args)
119 {
120   lb_as_t *as = va_arg (*args, lb_as_t *);
121   return format(s, "%U %s", format_ip46_address, &as->address, (as->flags & LB_AS_FLAGS_USED)?"used":"removed");
122 }
123
124 u8 *format_lb_vip_detailed (u8 * s, va_list * args)
125 {
126   lb_main_t *lbm = &lb_main;
127   lb_vip_t *vip = va_arg (*args, lb_vip_t *);
128   uword indent = format_get_indent (s);
129
130   s = format(s, "%U %U [%u] %U%s\n"
131                    "%U  new_size:%u\n",
132                   format_white_space, indent,
133                   format_lb_vip_type, vip->type,
134                   vip - lbm->vips, format_ip46_prefix, &vip->prefix, vip->plen, IP46_TYPE_ANY,
135                   (vip->flags & LB_VIP_FLAGS_USED)?"":" removed",
136                   format_white_space, indent,
137                   vip->new_flow_table_mask + 1);
138
139   //Print counters
140   s = format(s, "%U  counters:\n",
141              format_white_space, indent);
142   u32 i;
143   for (i=0; i<LB_N_VIP_COUNTERS; i++)
144     s = format(s, "%U    %s: %d\n",
145                format_white_space, indent,
146                lbm->vip_counters[i].name,
147                vlib_get_simple_counter(&lbm->vip_counters[i], vip - lbm->vips));
148
149
150   s = format(s, "%U  #as:%u\n",
151              format_white_space, indent,
152              pool_elts(vip->as_indexes));
153
154   //Let's count the buckets for each AS
155   u32 *count = 0;
156   vec_validate(count, pool_len(lbm->ass)); //Possibly big alloc for not much...
157   lb_new_flow_entry_t *nfe;
158   vec_foreach(nfe, vip->new_flow_table)
159     count[nfe->as_index]++;
160
161   lb_as_t *as;
162   u32 *as_index;
163   pool_foreach(as_index, vip->as_indexes, {
164       as = &lbm->ass[*as_index];
165       s = format(s, "%U    %U %d buckets   %d flows  dpo:%u %s\n",
166                    format_white_space, indent,
167                    format_ip46_address, &as->address, IP46_TYPE_ANY,
168                    count[as - lbm->ass],
169                    vlib_refcount_get(&lbm->as_refcount, as - lbm->ass),
170                    as->dpo.dpoi_index,
171                    (as->flags & LB_AS_FLAGS_USED)?"used":" removed");
172   });
173
174   vec_free(count);
175
176   /*
177   s = format(s, "%U  new flows table:\n", format_white_space, indent);
178   lb_new_flow_entry_t *nfe;
179   vec_foreach(nfe, vip->new_flow_table) {
180     s = format(s, "%U    %d: %d\n", format_white_space, indent, nfe - vip->new_flow_table, nfe->as_index);
181   }
182   */
183   return s;
184 }
185
186 typedef struct {
187   u32 as_index;
188   u32 last;
189   u32 skip;
190 } lb_pseudorand_t;
191
192 static int lb_pseudorand_compare(void *a, void *b)
193 {
194   lb_as_t *asa, *asb;
195   lb_main_t *lbm = &lb_main;
196   asa = &lbm->ass[((lb_pseudorand_t *)a)->as_index];
197   asb = &lbm->ass[((lb_pseudorand_t *)b)->as_index];
198   return memcmp(&asa->address, &asb->address, sizeof(asb->address));
199 }
200
201 static void lb_vip_garbage_collection(lb_vip_t *vip)
202 {
203   lb_main_t *lbm = &lb_main;
204   ASSERT (lbm->writer_lock[0]);
205
206   u32 now = (u32) vlib_time_now(vlib_get_main());
207   if (!clib_u32_loop_gt(now, vip->last_garbage_collection + LB_GARBAGE_RUN))
208     return;
209
210   vip->last_garbage_collection = now;
211   lb_as_t *as;
212   u32 *as_index;
213   pool_foreach(as_index, vip->as_indexes, {
214       as = &lbm->ass[*as_index];
215       if (!(as->flags & LB_AS_FLAGS_USED) && //Not used
216           clib_u32_loop_gt(now, as->last_used + LB_CONCURRENCY_TIMEOUT) && //Not recently used
217           (vlib_refcount_get(&lbm->as_refcount, as - lbm->ass) == 0))
218         { //Not referenced
219           fib_entry_child_remove(as->next_hop_fib_entry_index,
220                                  as->next_hop_child_index);
221           fib_table_entry_delete_index(as->next_hop_fib_entry_index,
222                                        FIB_SOURCE_RR);
223           as->next_hop_fib_entry_index = FIB_NODE_INDEX_INVALID;
224
225           pool_put(vip->as_indexes, as_index);
226           pool_put(lbm->ass, as);
227         }
228   });
229 }
230
231 void lb_garbage_collection()
232 {
233   lb_main_t *lbm = &lb_main;
234   lb_get_writer_lock();
235   lb_vip_t *vip;
236   u32 *to_be_removed_vips = 0, *i;
237   pool_foreach(vip, lbm->vips, {
238       lb_vip_garbage_collection(vip);
239
240       if (!(vip->flags & LB_VIP_FLAGS_USED) &&
241           (pool_elts(vip->as_indexes) == 0)) {
242         vec_add1(to_be_removed_vips, vip - lbm->vips);
243       }
244   });
245
246   vec_foreach(i, to_be_removed_vips) {
247     vip = &lbm->vips[*i];
248     pool_put(lbm->vips, vip);
249     pool_free(vip->as_indexes);
250   }
251
252   vec_free(to_be_removed_vips);
253   lb_put_writer_lock();
254 }
255
256 static void lb_vip_update_new_flow_table(lb_vip_t *vip)
257 {
258   lb_main_t *lbm = &lb_main;
259   lb_new_flow_entry_t *old_table;
260   u32 i, *as_index;
261   lb_new_flow_entry_t *new_flow_table = 0;
262   lb_as_t *as;
263   lb_pseudorand_t *pr, *sort_arr = 0;
264   u32 count;
265
266   ASSERT (lbm->writer_lock[0]); //We must have the lock
267
268   //Check if some AS is configured or not
269   i = 0;
270   pool_foreach(as_index, vip->as_indexes, {
271       as = &lbm->ass[*as_index];
272       if (as->flags & LB_AS_FLAGS_USED) { //Not used anymore
273         i = 1;
274         goto out; //Not sure 'break' works in this macro-loop
275       }
276   });
277
278 out:
279   if (i == 0) {
280     //Only the default. i.e. no AS
281     vec_validate(new_flow_table, vip->new_flow_table_mask);
282     for (i=0; i<vec_len(new_flow_table); i++)
283       new_flow_table[i].as_index = 0;
284
285     goto finished;
286   }
287
288   //First, let's sort the ASs
289   sort_arr = 0;
290   vec_alloc(sort_arr, pool_elts(vip->as_indexes));
291
292   i = 0;
293   pool_foreach(as_index, vip->as_indexes, {
294       as = &lbm->ass[*as_index];
295       if (!(as->flags & LB_AS_FLAGS_USED)) //Not used anymore
296         continue;
297
298       sort_arr[i].as_index = as - lbm->ass;
299       i++;
300   });
301   _vec_len(sort_arr) = i;
302
303   vec_sort_with_function(sort_arr, lb_pseudorand_compare);
304
305   //Now let's pseudo-randomly generate permutations
306   vec_foreach(pr, sort_arr) {
307     lb_as_t *as = &lbm->ass[pr->as_index];
308
309     u64 seed = clib_xxhash(as->address.as_u64[0] ^
310                            as->address.as_u64[1]);
311     /* We have 2^n buckets.
312      * skip must be prime with 2^n.
313      * So skip must be odd.
314      * MagLev actually state that M should be prime,
315      * but this has a big computation cost (% operation).
316      * Using 2^n is more better (& operation).
317      */
318     pr->skip = ((seed & 0xffffffff) | 1) & vip->new_flow_table_mask;
319     pr->last = (seed >> 32) & vip->new_flow_table_mask;
320   }
321
322   //Let's create a new flow table
323   vec_validate(new_flow_table, vip->new_flow_table_mask);
324   for (i=0; i<vec_len(new_flow_table); i++)
325     new_flow_table[i].as_index = ~0;
326
327   u32 done = 0;
328   while (1) {
329     vec_foreach(pr, sort_arr) {
330       while (1) {
331         u32 last = pr->last;
332         pr->last = (pr->last + pr->skip) & vip->new_flow_table_mask;
333         if (new_flow_table[last].as_index == ~0) {
334           new_flow_table[last].as_index = pr->as_index;
335           break;
336         }
337       }
338       done++;
339       if (done == vec_len(new_flow_table))
340         goto finished;
341     }
342   }
343
344   vec_free(sort_arr);
345
346 finished:
347
348 //Count number of changed entries
349   count = 0;
350   for (i=0; i<vec_len(new_flow_table); i++)
351     if (vip->new_flow_table == 0 ||
352         new_flow_table[i].as_index != vip->new_flow_table[i].as_index)
353       count++;
354
355   old_table = vip->new_flow_table;
356   vip->new_flow_table = new_flow_table;
357   vec_free(old_table);
358 }
359
360 int lb_conf(ip4_address_t *ip4_address, ip6_address_t *ip6_address,
361            u32 per_cpu_sticky_buckets, u32 flow_timeout)
362 {
363   lb_main_t *lbm = &lb_main;
364
365   if (!is_pow2(per_cpu_sticky_buckets))
366     return VNET_API_ERROR_INVALID_MEMORY_SIZE;
367
368   lb_get_writer_lock(); //Not exactly necessary but just a reminder that it exists for my future self
369   lbm->ip4_src_address = *ip4_address;
370   lbm->ip6_src_address = *ip6_address;
371   lbm->per_cpu_sticky_buckets = per_cpu_sticky_buckets;
372   lbm->flow_timeout = flow_timeout;
373   lb_put_writer_lock();
374   return 0;
375 }
376
377 static
378 int lb_vip_find_index_with_lock(ip46_address_t *prefix, u8 plen, u32 *vip_index)
379 {
380   lb_main_t *lbm = &lb_main;
381   lb_vip_t *vip;
382   ASSERT (lbm->writer_lock[0]); //This must be called with the lock owned
383   ip46_prefix_normalize(prefix, plen);
384   pool_foreach(vip, lbm->vips, {
385       if ((vip->flags & LB_AS_FLAGS_USED) &&
386           vip->plen == plen &&
387           vip->prefix.as_u64[0] == prefix->as_u64[0] &&
388           vip->prefix.as_u64[1] == prefix->as_u64[1]) {
389         *vip_index = vip - lbm->vips;
390         return 0;
391       }
392   });
393   return VNET_API_ERROR_NO_SUCH_ENTRY;
394 }
395
396 int lb_vip_find_index(ip46_address_t *prefix, u8 plen, u32 *vip_index)
397 {
398   int ret;
399   lb_get_writer_lock();
400   ret = lb_vip_find_index_with_lock(prefix, plen, vip_index);
401   lb_put_writer_lock();
402   return ret;
403 }
404
405 static int lb_as_find_index_vip(lb_vip_t *vip, ip46_address_t *address, u32 *as_index)
406 {
407   lb_main_t *lbm = &lb_main;
408   ASSERT (lbm->writer_lock[0]); //This must be called with the lock owned
409   lb_as_t *as;
410   u32 *asi;
411   pool_foreach(asi, vip->as_indexes, {
412       as = &lbm->ass[*asi];
413       if (as->vip_index == (vip - lbm->vips) &&
414           as->address.as_u64[0] == address->as_u64[0] &&
415           as->address.as_u64[1] == address->as_u64[1]) {
416         *as_index = as - lbm->ass;
417         return 0;
418       }
419   });
420   return -1;
421 }
422
423 int lb_vip_add_ass(u32 vip_index, ip46_address_t *addresses, u32 n)
424 {
425   lb_main_t *lbm = &lb_main;
426   lb_get_writer_lock();
427   lb_vip_t *vip;
428   if (!(vip = lb_vip_get_by_index(vip_index))) {
429     lb_put_writer_lock();
430     return VNET_API_ERROR_NO_SUCH_ENTRY;
431   }
432
433   ip46_type_t type = lb_vip_is_gre4(vip)?IP46_TYPE_IP4:IP46_TYPE_IP6;
434   u32 *to_be_added = 0;
435   u32 *to_be_updated = 0;
436   u32 i;
437   u32 *ip;
438
439   //Sanity check
440   while (n--) {
441
442     if (!lb_as_find_index_vip(vip, &addresses[n], &i)) {
443       if (lbm->ass[i].flags & LB_AS_FLAGS_USED) {
444         vec_free(to_be_added);
445         vec_free(to_be_updated);
446         lb_put_writer_lock();
447         return VNET_API_ERROR_VALUE_EXIST;
448       }
449       vec_add1(to_be_updated, i);
450       goto next;
451     }
452
453     if (ip46_address_type(&addresses[n]) != type) {
454       vec_free(to_be_added);
455       vec_free(to_be_updated);
456       lb_put_writer_lock();
457       return VNET_API_ERROR_INVALID_ADDRESS_FAMILY;
458     }
459
460     if (n) {
461       u32 n2 = n;
462       while(n2--) //Check for duplicates
463         if (addresses[n2].as_u64[0] == addresses[n].as_u64[0] &&
464             addresses[n2].as_u64[1] == addresses[n].as_u64[1])
465           goto next;
466     }
467
468     vec_add1(to_be_added, n);
469
470 next:
471     continue;
472   }
473
474   //Update reused ASs
475   vec_foreach(ip, to_be_updated) {
476     lbm->ass[*ip].flags = LB_AS_FLAGS_USED;
477   }
478   vec_free(to_be_updated);
479
480   //Create those who have to be created
481   vec_foreach(ip, to_be_added) {
482     lb_as_t *as;
483     u32 *as_index;
484     pool_get(lbm->ass, as);
485     as->address = addresses[*ip];
486     as->flags = LB_AS_FLAGS_USED;
487     as->vip_index = vip_index;
488     pool_get(vip->as_indexes, as_index);
489     *as_index = as - lbm->ass;
490
491     /*
492      * become a child of the FIB entry
493      * so we are informed when its forwarding changes
494      */
495     fib_prefix_t nh = {};
496     if (lb_vip_is_gre4(vip)) {
497         nh.fp_addr.ip4 = as->address.ip4;
498         nh.fp_len = 32;
499         nh.fp_proto = FIB_PROTOCOL_IP4;
500     } else {
501         nh.fp_addr.ip6 = as->address.ip6;
502         nh.fp_len = 128;
503         nh.fp_proto = FIB_PROTOCOL_IP6;
504     }
505
506     as->next_hop_fib_entry_index =
507         fib_table_entry_special_add(0,
508                                     &nh,
509                                     FIB_SOURCE_RR,
510                                     FIB_ENTRY_FLAG_NONE,
511                                     ADJ_INDEX_INVALID);
512     as->next_hop_child_index =
513         fib_entry_child_add(as->next_hop_fib_entry_index,
514                             lbm->fib_node_type,
515                             as - lbm->ass);
516
517     lb_as_stack(as);
518   }
519   vec_free(to_be_added);
520
521   //Recompute flows
522   lb_vip_update_new_flow_table(vip);
523
524   //Garbage collection maybe
525   lb_vip_garbage_collection(vip);
526
527   lb_put_writer_lock();
528   return 0;
529 }
530
531 int lb_vip_del_ass_withlock(u32 vip_index, ip46_address_t *addresses, u32 n)
532 {
533   lb_main_t *lbm = &lb_main;
534   u32 now = (u32) vlib_time_now(vlib_get_main());
535   u32 *ip = 0;
536
537   lb_vip_t *vip;
538   if (!(vip = lb_vip_get_by_index(vip_index))) {
539     return VNET_API_ERROR_NO_SUCH_ENTRY;
540   }
541
542   u32 *indexes = NULL;
543   while (n--) {
544     u32 i;
545     if (lb_as_find_index_vip(vip, &addresses[n], &i)) {
546       vec_free(indexes);
547       return VNET_API_ERROR_NO_SUCH_ENTRY;
548     }
549
550     if (n) { //Check for duplicates
551       u32 n2 = n - 1;
552       while(n2--) {
553         if (addresses[n2].as_u64[0] == addresses[n].as_u64[0] &&
554             addresses[n2].as_u64[1] == addresses[n].as_u64[1])
555           goto next;
556       }
557     }
558
559     vec_add1(indexes, i);
560 next:
561   continue;
562   }
563
564   //Garbage collection maybe
565   lb_vip_garbage_collection(vip);
566
567   if (indexes != NULL) {
568     vec_foreach(ip, indexes) {
569       lbm->ass[*ip].flags &= ~LB_AS_FLAGS_USED;
570       lbm->ass[*ip].last_used = now;
571     }
572
573     //Recompute flows
574     lb_vip_update_new_flow_table(vip);
575   }
576
577   vec_free(indexes);
578   return 0;
579 }
580
581 int lb_vip_del_ass(u32 vip_index, ip46_address_t *addresses, u32 n)
582 {
583   lb_get_writer_lock();
584   int ret = lb_vip_del_ass_withlock(vip_index, addresses, n);
585   lb_put_writer_lock();
586   return ret;
587 }
588
589 /**
590  * Add the VIP adjacency to the ip4 or ip6 fib
591  */
592 static void lb_vip_add_adjacency(lb_main_t *lbm, lb_vip_t *vip)
593 {
594   dpo_proto_t proto = 0;
595   dpo_id_t dpo = DPO_NULL;
596   fib_prefix_t pfx = {};
597   if (lb_vip_is_ip4(vip)) {
598       pfx.fp_addr.ip4 = vip->prefix.ip4;
599       pfx.fp_len = vip->plen - 96;
600       pfx.fp_proto = FIB_PROTOCOL_IP4;
601       proto = DPO_PROTO_IP4;
602   } else {
603       pfx.fp_addr.ip6 = vip->prefix.ip6;
604       pfx.fp_len = vip->plen;
605       pfx.fp_proto = FIB_PROTOCOL_IP6;
606       proto = DPO_PROTO_IP6;
607   }
608   dpo_set(&dpo, lb_vip_is_gre4(vip)?lbm->dpo_gre4_type:lbm->dpo_gre6_type,
609       proto, vip - lbm->vips);
610   fib_table_entry_special_dpo_add(0,
611                                   &pfx,
612                                   FIB_SOURCE_PLUGIN_HI,
613                                   FIB_ENTRY_FLAG_EXCLUSIVE,
614                                   &dpo);
615   dpo_reset(&dpo);
616 }
617
618 /**
619  * Deletes the adjacency associated with the VIP
620  */
621 static void lb_vip_del_adjacency(lb_main_t *lbm, lb_vip_t *vip)
622 {
623   fib_prefix_t pfx = {};
624   if (lb_vip_is_ip4(vip)) {
625       pfx.fp_addr.ip4 = vip->prefix.ip4;
626       pfx.fp_len = vip->plen - 96;
627       pfx.fp_proto = FIB_PROTOCOL_IP4;
628   } else {
629       pfx.fp_addr.ip6 = vip->prefix.ip6;
630       pfx.fp_len = vip->plen;
631       pfx.fp_proto = FIB_PROTOCOL_IP6;
632   }
633   fib_table_entry_special_remove(0, &pfx, FIB_SOURCE_PLUGIN_HI);
634 }
635
636 int lb_vip_add(ip46_address_t *prefix, u8 plen, lb_vip_type_t type, u32 new_length, u32 *vip_index)
637 {
638   lb_main_t *lbm = &lb_main;
639   lb_vip_t *vip;
640   lb_get_writer_lock();
641   ip46_prefix_normalize(prefix, plen);
642
643   if (!lb_vip_find_index_with_lock(prefix, plen, vip_index)) {
644     lb_put_writer_lock();
645     return VNET_API_ERROR_VALUE_EXIST;
646   }
647
648   if (!is_pow2(new_length)) {
649     lb_put_writer_lock();
650     return VNET_API_ERROR_INVALID_MEMORY_SIZE;
651   }
652
653   if (ip46_prefix_is_ip4(prefix, plen) &&
654       (type != LB_VIP_TYPE_IP4_GRE4) &&
655       (type != LB_VIP_TYPE_IP4_GRE6))
656     return VNET_API_ERROR_INVALID_ADDRESS_FAMILY;
657
658
659   //Allocate
660   pool_get(lbm->vips, vip);
661
662   //Init
663   vip->prefix = *prefix;
664   vip->plen = plen;
665   vip->last_garbage_collection = (u32) vlib_time_now(vlib_get_main());
666   vip->type = type;
667   vip->flags = LB_VIP_FLAGS_USED;
668   vip->as_indexes = 0;
669
670   //Validate counters
671   u32 i;
672   for (i = 0; i < LB_N_VIP_COUNTERS; i++) {
673     vlib_validate_simple_counter(&lbm->vip_counters[i], vip - lbm->vips);
674     vlib_zero_simple_counter(&lbm->vip_counters[i], vip - lbm->vips);
675   }
676
677   //Configure new flow table
678   vip->new_flow_table_mask = new_length - 1;
679   vip->new_flow_table = 0;
680
681   //Create a new flow hash table full of the default entry
682   lb_vip_update_new_flow_table(vip);
683
684   //Create adjacency to direct traffic
685   lb_vip_add_adjacency(lbm, vip);
686
687   //Return result
688   *vip_index = vip - lbm->vips;
689
690   lb_put_writer_lock();
691   return 0;
692 }
693
694 int lb_vip_del(u32 vip_index)
695 {
696   lb_main_t *lbm = &lb_main;
697   lb_vip_t *vip;
698   lb_get_writer_lock();
699   if (!(vip = lb_vip_get_by_index(vip_index))) {
700     lb_put_writer_lock();
701     return VNET_API_ERROR_NO_SUCH_ENTRY;
702   }
703
704   //FIXME: This operation is actually not working
705   //We will need to remove state before performing this.
706
707   {
708     //Remove all ASs
709     ip46_address_t *ass = 0;
710     lb_as_t *as;
711     u32 *as_index;
712     pool_foreach(as_index, vip->as_indexes, {
713         as = &lbm->ass[*as_index];
714         vec_add1(ass, as->address);
715     });
716     if (vec_len(ass))
717       lb_vip_del_ass_withlock(vip_index, ass, vec_len(ass));
718     vec_free(ass);
719   }
720
721   //Delete adjacency
722   lb_vip_del_adjacency(lbm, vip);
723
724   //Set the VIP as unused
725   vip->flags &= ~LB_VIP_FLAGS_USED;
726
727   lb_put_writer_lock();
728   return 0;
729 }
730
731 clib_error_t *
732 vlib_plugin_register (vlib_main_t * vm,
733                       vnet_plugin_handoff_t * h,
734                       int from_early_init)
735 {
736   clib_error_t *error = 0;
737   return error;
738 }
739
740
741 u8 *format_lb_dpo (u8 * s, va_list * va)
742 {
743   index_t index = va_arg (*va, index_t);
744   CLIB_UNUSED(u32 indent) = va_arg (*va, u32);
745   lb_main_t *lbm = &lb_main;
746   lb_vip_t *vip = pool_elt_at_index (lbm->vips, index);
747   return format (s, "%U", format_lb_vip, vip);
748 }
749
750 static void lb_dpo_lock (dpo_id_t *dpo) {}
751 static void lb_dpo_unlock (dpo_id_t *dpo) {}
752
753 static fib_node_t *
754 lb_fib_node_get_node (fib_node_index_t index)
755 {
756   lb_main_t *lbm = &lb_main;
757   lb_as_t *as = pool_elt_at_index (lbm->ass, index);
758   return (&as->fib_node);
759 }
760
761 static void
762 lb_fib_node_last_lock_gone (fib_node_t *node)
763 {
764 }
765
766 static lb_as_t *
767 lb_as_from_fib_node (fib_node_t *node)
768 {
769   return ((lb_as_t*)(((char*)node) -
770       STRUCT_OFFSET_OF(lb_as_t, fib_node)));
771 }
772
773 static void
774 lb_as_stack (lb_as_t *as)
775 {
776   lb_main_t *lbm = &lb_main;
777   lb_vip_t *vip = &lbm->vips[as->vip_index];
778   dpo_stack(lb_vip_is_gre4(vip)?lbm->dpo_gre4_type:lbm->dpo_gre6_type,
779             lb_vip_is_ip4(vip)?DPO_PROTO_IP4:DPO_PROTO_IP6,
780             &as->dpo,
781             fib_entry_contribute_ip_forwarding(
782                 as->next_hop_fib_entry_index));
783 }
784
785 static fib_node_back_walk_rc_t
786 lb_fib_node_back_walk_notify (fib_node_t *node,
787                                fib_node_back_walk_ctx_t *ctx)
788 {
789     lb_as_stack(lb_as_from_fib_node(node));
790     return (FIB_NODE_BACK_WALK_CONTINUE);
791 }
792
793 clib_error_t *
794 lb_init (vlib_main_t * vm)
795 {
796   vlib_thread_main_t *tm = vlib_get_thread_main ();
797   lb_main_t *lbm = &lb_main;
798   lb_as_t *default_as;
799   fib_node_vft_t lb_fib_node_vft = {
800       .fnv_get = lb_fib_node_get_node,
801       .fnv_last_lock = lb_fib_node_last_lock_gone,
802       .fnv_back_walk = lb_fib_node_back_walk_notify,
803   };
804   dpo_vft_t lb_vft = {
805       .dv_lock = lb_dpo_lock,
806       .dv_unlock = lb_dpo_unlock,
807       .dv_format = format_lb_dpo,
808   };
809
810   lbm->vips = 0;
811   lbm->per_cpu = 0;
812   vec_validate(lbm->per_cpu, tm->n_vlib_mains - 1);
813   lbm->writer_lock = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,  CLIB_CACHE_LINE_BYTES);
814   lbm->writer_lock[0] = 0;
815   lbm->per_cpu_sticky_buckets = LB_DEFAULT_PER_CPU_STICKY_BUCKETS;
816   lbm->flow_timeout = LB_DEFAULT_FLOW_TIMEOUT;
817   lbm->ip4_src_address.as_u32 = 0xffffffff;
818   lbm->ip6_src_address.as_u64[0] = 0xffffffffffffffffL;
819   lbm->ip6_src_address.as_u64[1] = 0xffffffffffffffffL;
820   lbm->dpo_gre4_type = dpo_register_new_type(&lb_vft, lb_dpo_gre4_nodes);
821   lbm->dpo_gre6_type = dpo_register_new_type(&lb_vft, lb_dpo_gre6_nodes);
822   lbm->fib_node_type = fib_node_register_new_type(&lb_fib_node_vft);
823
824   //Init AS reference counters
825   vlib_refcount_init(&lbm->as_refcount);
826
827   //Allocate and init default AS.
828   lbm->ass = 0;
829   pool_get(lbm->ass, default_as);
830   default_as->flags = 0;
831   default_as->dpo.dpoi_next_node = LB_NEXT_DROP;
832   default_as->vip_index = ~0;
833   default_as->address.ip6.as_u64[0] = 0xffffffffffffffffL;
834   default_as->address.ip6.as_u64[1] = 0xffffffffffffffffL;
835
836 #define _(a,b,c) lbm->vip_counters[c].name = b;
837   lb_foreach_vip_counter
838 #undef _
839   return NULL;
840 }
841
842 VLIB_INIT_FUNCTION (lb_init);