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