lb: fix coverity warning
[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 #include <vnet/udp/udp.h>
21 #include <vppinfra/lock.h>
22
23 //GC runs at most once every so many seconds
24 #define LB_GARBAGE_RUN 60
25
26 //After so many seconds. It is assumed that inter-core race condition will not occur.
27 #define LB_CONCURRENCY_TIMEOUT 10
28
29 // FIB source for adding routes
30 static fib_source_t lb_fib_src;
31
32 lb_main_t lb_main;
33
34 #define lb_get_writer_lock() clib_spinlock_lock (&lb_main.writer_lock)
35 #define lb_put_writer_lock() clib_spinlock_unlock (&lb_main.writer_lock)
36
37 static void lb_as_stack (lb_as_t *as);
38
39
40 const static char * const lb_dpo_gre4_ip4[] = { "lb4-gre4" , NULL };
41 const static char * const lb_dpo_gre4_ip6[] = { "lb6-gre4" , NULL };
42 const static char* const * const lb_dpo_gre4_nodes[DPO_PROTO_NUM] =
43     {
44         [DPO_PROTO_IP4]  = lb_dpo_gre4_ip4,
45         [DPO_PROTO_IP6]  = lb_dpo_gre4_ip6,
46     };
47
48 const static char * const lb_dpo_gre6_ip4[] = { "lb4-gre6" , NULL };
49 const static char * const lb_dpo_gre6_ip6[] = { "lb6-gre6" , NULL };
50 const static char* const * const lb_dpo_gre6_nodes[DPO_PROTO_NUM] =
51     {
52         [DPO_PROTO_IP4]  = lb_dpo_gre6_ip4,
53         [DPO_PROTO_IP6]  = lb_dpo_gre6_ip6,
54     };
55
56 const static char * const lb_dpo_gre4_ip4_port[] = { "lb4-gre4-port" , NULL };
57 const static char * const lb_dpo_gre4_ip6_port[] = { "lb6-gre4-port" , NULL };
58 const static char* const * const lb_dpo_gre4_port_nodes[DPO_PROTO_NUM] =
59     {
60         [DPO_PROTO_IP4]  = lb_dpo_gre4_ip4_port,
61         [DPO_PROTO_IP6]  = lb_dpo_gre4_ip6_port,
62     };
63
64 const static char * const lb_dpo_gre6_ip4_port[] = { "lb4-gre6-port" , NULL };
65 const static char * const lb_dpo_gre6_ip6_port[] = { "lb6-gre6-port" , NULL };
66 const static char* const * const lb_dpo_gre6_port_nodes[DPO_PROTO_NUM] =
67     {
68         [DPO_PROTO_IP4]  = lb_dpo_gre6_ip4_port,
69         [DPO_PROTO_IP6]  = lb_dpo_gre6_ip6_port,
70     };
71
72 const static char * const lb_dpo_l3dsr_ip4[] = {"lb4-l3dsr" , NULL};
73 const static char* const * const lb_dpo_l3dsr_nodes[DPO_PROTO_NUM] =
74     {
75         [DPO_PROTO_IP4]  = lb_dpo_l3dsr_ip4,
76     };
77
78 const static char * const lb_dpo_l3dsr_ip4_port[] = {"lb4-l3dsr-port" , NULL};
79 const static char* const * const lb_dpo_l3dsr_port_nodes[DPO_PROTO_NUM] =
80     {
81         [DPO_PROTO_IP4]  = lb_dpo_l3dsr_ip4_port,
82     };
83
84 const static char * const lb_dpo_nat4_ip4_port[] = { "lb4-nat4-port" , NULL };
85 const static char* const * const lb_dpo_nat4_port_nodes[DPO_PROTO_NUM] =
86     {
87         [DPO_PROTO_IP4]  = lb_dpo_nat4_ip4_port,
88     };
89
90 const static char * const lb_dpo_nat6_ip6_port[] = { "lb6-nat6-port" , NULL };
91 const static char* const * const lb_dpo_nat6_port_nodes[DPO_PROTO_NUM] =
92     {
93         [DPO_PROTO_IP6]  = lb_dpo_nat6_ip6_port,
94     };
95
96 u32 lb_hash_time_now(vlib_main_t * vm)
97 {
98   return (u32) (vlib_time_now(vm) + 10000);
99 }
100
101 u8 *format_lb_main (u8 * s, va_list * args)
102 {
103   vlib_thread_main_t *tm = vlib_get_thread_main();
104   lb_main_t *lbm = &lb_main;
105   s = format(s, "lb_main");
106   s = format(s, " ip4-src-address: %U \n", format_ip4_address, &lbm->ip4_src_address);
107   s = format(s, " ip6-src-address: %U \n", format_ip6_address, &lbm->ip6_src_address);
108   s = format(s, " #vips: %u\n", pool_elts(lbm->vips));
109   s = format(s, " #ass: %u\n", pool_elts(lbm->ass) - 1);
110
111   u32 thread_index;
112   for(thread_index = 0; thread_index < tm->n_vlib_mains; thread_index++ ) {
113     lb_hash_t *h = lbm->per_cpu[thread_index].sticky_ht;
114     if (h) {
115       s = format(s, "core %d\n", thread_index);
116       s = format(s, "  timeout: %ds\n", h->timeout);
117       s = format(s, "  usage: %d / %d\n", lb_hash_elts(h, lb_hash_time_now(vlib_get_main())),  lb_hash_size(h));
118     }
119   }
120
121   return s;
122 }
123
124 static char *lb_vip_type_strings[] = {
125     [LB_VIP_TYPE_IP6_GRE6] = "ip6-gre6",
126     [LB_VIP_TYPE_IP6_GRE4] = "ip6-gre4",
127     [LB_VIP_TYPE_IP4_GRE6] = "ip4-gre6",
128     [LB_VIP_TYPE_IP4_GRE4] = "ip4-gre4",
129     [LB_VIP_TYPE_IP4_L3DSR] = "ip4-l3dsr",
130     [LB_VIP_TYPE_IP4_NAT4] = "ip4-nat4",
131     [LB_VIP_TYPE_IP6_NAT6] = "ip6-nat6",
132 };
133
134 u8 *format_lb_vip_type (u8 * s, va_list * args)
135 {
136   lb_vip_type_t vipt = va_arg (*args, lb_vip_type_t);
137   u32 i;
138   for (i=0; i<LB_VIP_N_TYPES; i++)
139     if (vipt == i)
140       return format(s, lb_vip_type_strings[i]);
141   return format(s, "_WRONG_TYPE_");
142 }
143
144 uword unformat_lb_vip_type (unformat_input_t * input, va_list * args)
145 {
146   lb_vip_type_t *vipt = va_arg (*args, lb_vip_type_t *);
147   u32 i;
148   for (i=0; i<LB_VIP_N_TYPES; i++)
149     if (unformat(input, lb_vip_type_strings[i])) {
150       *vipt = i;
151       return 1;
152     }
153   return 0;
154 }
155
156 u8 *format_lb_vip (u8 * s, va_list * args)
157 {
158   lb_vip_t *vip = va_arg (*args, lb_vip_t *);
159   s = format(s, "%U %U new_size:%u #as:%u%s",
160              format_lb_vip_type, vip->type,
161              format_ip46_prefix, &vip->prefix, vip->plen, IP46_TYPE_ANY,
162              vip->new_flow_table_mask + 1,
163              pool_elts(vip->as_indexes),
164              (vip->flags & LB_VIP_FLAGS_USED)?"":" removed");
165
166   if (vip->port != 0)
167     {
168       s = format(s, "  protocol:%u port:%u ", vip->protocol, vip->port);
169     }
170
171   if (vip->type == LB_VIP_TYPE_IP4_L3DSR)
172     {
173       s = format(s, "  dscp:%u", vip->encap_args.dscp);
174     }
175   else if ((vip->type == LB_VIP_TYPE_IP4_NAT4)
176           || (vip->type == LB_VIP_TYPE_IP6_NAT6))
177     {
178       s = format (s, " type:%s port:%u target_port:%u",
179          (vip->encap_args.srv_type == LB_SRV_TYPE_CLUSTERIP)?"clusterip":
180              "nodeport",
181          ntohs(vip->port), ntohs(vip->encap_args.target_port));
182     }
183
184   return s;
185 }
186
187 u8 *format_lb_as (u8 * s, va_list * args)
188 {
189   lb_as_t *as = va_arg (*args, lb_as_t *);
190   return format(s, "%U %s", format_ip46_address,
191                 &as->address, IP46_TYPE_ANY,
192                 (as->flags & LB_AS_FLAGS_USED)?"used":"removed");
193 }
194
195 u8 *format_lb_vip_detailed (u8 * s, va_list * args)
196 {
197   lb_main_t *lbm = &lb_main;
198   lb_vip_t *vip = va_arg (*args, lb_vip_t *);
199   u32 indent = format_get_indent (s);
200
201   s = format(s, "%U %U [%lu] %U%s\n"
202                    "%U  new_size:%u\n",
203                   format_white_space, indent,
204                   format_lb_vip_type, vip->type,
205                   vip - lbm->vips,
206                   format_ip46_prefix, &vip->prefix, (u32) vip->plen, IP46_TYPE_ANY,
207                   (vip->flags & LB_VIP_FLAGS_USED)?"":" removed",
208                   format_white_space, indent,
209                   vip->new_flow_table_mask + 1);
210
211   if (vip->port != 0)
212     {
213       s = format(s, "%U  protocol:%u port:%u\n",
214                  format_white_space, indent,
215                  vip->protocol, vip->port);
216     }
217
218   if (vip->type == LB_VIP_TYPE_IP4_L3DSR)
219     {
220       s = format(s, "%U  dscp:%u\n",
221                     format_white_space, indent,
222                     vip->encap_args.dscp);
223     }
224   else if ((vip->type == LB_VIP_TYPE_IP4_NAT4)
225           || (vip->type == LB_VIP_TYPE_IP6_NAT6))
226     {
227       s = format (s, "%U  type:%s port:%u target_port:%u",
228          format_white_space, indent,
229          (vip->encap_args.srv_type == LB_SRV_TYPE_CLUSTERIP)?"clusterip":
230              "nodeport",
231          ntohs(vip->port), ntohs(vip->encap_args.target_port));
232     }
233
234   //Print counters
235   s = format(s, "%U  counters:\n",
236              format_white_space, indent);
237   u32 i;
238   for (i=0; i<LB_N_VIP_COUNTERS; i++)
239     s = format(s, "%U    %s: %Lu\n",
240                format_white_space, indent,
241                lbm->vip_counters[i].name,
242                vlib_get_simple_counter(&lbm->vip_counters[i], vip - lbm->vips));
243
244
245   s = format(s, "%U  #as:%u\n",
246              format_white_space, indent,
247              pool_elts(vip->as_indexes));
248
249   //Let's count the buckets for each AS
250   u32 *count = 0;
251   vec_validate(count, pool_len(lbm->ass)); //Possibly big alloc for not much...
252   lb_new_flow_entry_t *nfe;
253   vec_foreach(nfe, vip->new_flow_table)
254     count[nfe->as_index]++;
255
256   lb_as_t *as;
257   u32 *as_index;
258   pool_foreach(as_index, vip->as_indexes, {
259       as = &lbm->ass[*as_index];
260       s = format(s, "%U    %U %u buckets   %Lu flows  dpo:%u %s\n",
261                    format_white_space, indent,
262                    format_ip46_address, &as->address, IP46_TYPE_ANY,
263                    count[as - lbm->ass],
264                    vlib_refcount_get(&lbm->as_refcount, as - lbm->ass),
265                    as->dpo.dpoi_index,
266                    (as->flags & LB_AS_FLAGS_USED)?"used":" removed");
267   });
268
269   vec_free(count);
270   return s;
271 }
272
273 typedef struct {
274   u32 as_index;
275   u32 last;
276   u32 skip;
277 } lb_pseudorand_t;
278
279 static int lb_pseudorand_compare(void *a, void *b)
280 {
281   lb_as_t *asa, *asb;
282   lb_main_t *lbm = &lb_main;
283   asa = &lbm->ass[((lb_pseudorand_t *)a)->as_index];
284   asb = &lbm->ass[((lb_pseudorand_t *)b)->as_index];
285   return memcmp(&asa->address, &asb->address, sizeof(asb->address));
286 }
287
288 static void lb_vip_garbage_collection(lb_vip_t *vip)
289 {
290   lb_main_t *lbm = &lb_main;
291   lb_snat4_key_t m_key4;
292   clib_bihash_kv_8_8_t kv4, value4;
293   lb_snat6_key_t m_key6;
294   clib_bihash_kv_24_8_t kv6, value6;
295   lb_snat_mapping_t *m = 0;
296   CLIB_SPINLOCK_ASSERT_LOCKED (&lbm->writer_lock);
297
298   u32 now = (u32) vlib_time_now(vlib_get_main());
299   if (!clib_u32_loop_gt(now, vip->last_garbage_collection + LB_GARBAGE_RUN))
300     return;
301
302   vip->last_garbage_collection = now;
303   lb_as_t *as;
304   u32 *as_index;
305   pool_foreach(as_index, vip->as_indexes, {
306       as = &lbm->ass[*as_index];
307       if (!(as->flags & LB_AS_FLAGS_USED) && //Not used
308           clib_u32_loop_gt(now, as->last_used + LB_CONCURRENCY_TIMEOUT) &&
309           (vlib_refcount_get(&lbm->as_refcount, as - lbm->ass) == 0))
310         { //Not referenced
311
312           if (lb_vip_is_nat4_port(vip)) {
313               m_key4.addr = as->address.ip4;
314               m_key4.port = vip->encap_args.target_port;
315               m_key4.protocol = 0;
316               m_key4.fib_index = 0;
317
318               kv4.key = m_key4.as_u64;
319               if(!clib_bihash_search_8_8(&lbm->mapping_by_as4, &kv4, &value4))
320                 m = pool_elt_at_index (lbm->snat_mappings, value4.value);
321               ASSERT (m);
322
323               kv4.value = m - lbm->snat_mappings;
324               clib_bihash_add_del_8_8(&lbm->mapping_by_as4, &kv4, 0);
325               pool_put (lbm->snat_mappings, m);
326           } else if (lb_vip_is_nat6_port(vip)) {
327               m_key6.addr.as_u64[0] = as->address.ip6.as_u64[0];
328               m_key6.addr.as_u64[1] = as->address.ip6.as_u64[1];
329               m_key6.port = vip->encap_args.target_port;
330               m_key6.protocol = 0;
331               m_key6.fib_index = 0;
332
333               kv6.key[0] = m_key6.as_u64[0];
334               kv6.key[1] = m_key6.as_u64[1];
335               kv6.key[2] = m_key6.as_u64[2];
336
337               if (!clib_bihash_search_24_8 (&lbm->mapping_by_as6, &kv6, &value6))
338                 m = pool_elt_at_index (lbm->snat_mappings, value6.value);
339               ASSERT (m);
340
341               kv6.value = m - lbm->snat_mappings;
342               clib_bihash_add_del_24_8(&lbm->mapping_by_as6, &kv6, 0);
343               pool_put (lbm->snat_mappings, m);
344           }
345           fib_entry_child_remove(as->next_hop_fib_entry_index,
346                                 as->next_hop_child_index);
347           fib_table_entry_delete_index(as->next_hop_fib_entry_index,
348                                        FIB_SOURCE_RR);
349           as->next_hop_fib_entry_index = FIB_NODE_INDEX_INVALID;
350
351           pool_put(vip->as_indexes, as_index);
352           pool_put(lbm->ass, as);
353         }
354   });
355 }
356
357 void lb_garbage_collection()
358 {
359   lb_main_t *lbm = &lb_main;
360   lb_get_writer_lock();
361   lb_vip_t *vip;
362   u32 *to_be_removed_vips = 0, *i;
363   pool_foreach(vip, lbm->vips, {
364       lb_vip_garbage_collection(vip);
365
366       if (!(vip->flags & LB_VIP_FLAGS_USED) &&
367           (pool_elts(vip->as_indexes) == 0)) {
368         vec_add1(to_be_removed_vips, vip - lbm->vips);
369       }
370   });
371
372   vec_foreach(i, to_be_removed_vips) {
373     vip = &lbm->vips[*i];
374     pool_put(lbm->vips, vip);
375     pool_free(vip->as_indexes);
376   }
377
378   vec_free(to_be_removed_vips);
379   lb_put_writer_lock();
380 }
381
382 static void lb_vip_update_new_flow_table(lb_vip_t *vip)
383 {
384   lb_main_t *lbm = &lb_main;
385   lb_new_flow_entry_t *old_table;
386   u32 i, *as_index;
387   lb_new_flow_entry_t *new_flow_table = 0;
388   lb_as_t *as;
389   lb_pseudorand_t *pr, *sort_arr = 0;
390
391   CLIB_SPINLOCK_ASSERT_LOCKED (&lbm->writer_lock); // We must have the lock
392
393   //Check if some AS is configured or not
394   i = 0;
395   pool_foreach(as_index, vip->as_indexes, {
396       as = &lbm->ass[*as_index];
397       if (as->flags & LB_AS_FLAGS_USED) { //Not used anymore
398         i = 1;
399         goto out; //Not sure 'break' works in this macro-loop
400       }
401   });
402
403 out:
404   if (i == 0) {
405     //Only the default. i.e. no AS
406     vec_validate(new_flow_table, vip->new_flow_table_mask);
407     for (i=0; i<vec_len(new_flow_table); i++)
408       new_flow_table[i].as_index = 0;
409
410     goto finished;
411   }
412
413   //First, let's sort the ASs
414   vec_alloc(sort_arr, pool_elts(vip->as_indexes));
415
416   i = 0;
417   pool_foreach(as_index, vip->as_indexes, {
418       as = &lbm->ass[*as_index];
419       if (!(as->flags & LB_AS_FLAGS_USED)) //Not used anymore
420         continue;
421
422       sort_arr[i].as_index = as - lbm->ass;
423       i++;
424   });
425   _vec_len(sort_arr) = i;
426
427   vec_sort_with_function(sort_arr, lb_pseudorand_compare);
428
429   //Now let's pseudo-randomly generate permutations
430   vec_foreach(pr, sort_arr) {
431     lb_as_t *as = &lbm->ass[pr->as_index];
432
433     u64 seed = clib_xxhash(as->address.as_u64[0] ^
434                            as->address.as_u64[1]);
435     /* We have 2^n buckets.
436      * skip must be prime with 2^n.
437      * So skip must be odd.
438      * MagLev actually state that M should be prime,
439      * but this has a big computation cost (% operation).
440      * Using 2^n is more better (& operation).
441      */
442     pr->skip = ((seed & 0xffffffff) | 1) & vip->new_flow_table_mask;
443     pr->last = (seed >> 32) & vip->new_flow_table_mask;
444   }
445
446   //Let's create a new flow table
447   vec_validate(new_flow_table, vip->new_flow_table_mask);
448   for (i=0; i<vec_len(new_flow_table); i++)
449     new_flow_table[i].as_index = 0;
450
451   u32 done = 0;
452   while (1) {
453     vec_foreach(pr, sort_arr) {
454       while (1) {
455         u32 last = pr->last;
456         pr->last = (pr->last + pr->skip) & vip->new_flow_table_mask;
457         if (new_flow_table[last].as_index == 0) {
458           new_flow_table[last].as_index = pr->as_index;
459           break;
460         }
461       }
462       done++;
463       if (done == vec_len(new_flow_table))
464         goto finished;
465     }
466   }
467
468 finished:
469   vec_free(sort_arr);
470
471   old_table = vip->new_flow_table;
472   vip->new_flow_table = new_flow_table;
473   vec_free(old_table);
474 }
475
476 int lb_conf(ip4_address_t *ip4_address, ip6_address_t *ip6_address,
477            u32 per_cpu_sticky_buckets, u32 flow_timeout)
478 {
479   lb_main_t *lbm = &lb_main;
480
481   if (!is_pow2(per_cpu_sticky_buckets))
482     return VNET_API_ERROR_INVALID_MEMORY_SIZE;
483
484   lb_get_writer_lock(); //Not exactly necessary but just a reminder that it exists for my future self
485   lbm->ip4_src_address = *ip4_address;
486   lbm->ip6_src_address = *ip6_address;
487   lbm->per_cpu_sticky_buckets = per_cpu_sticky_buckets;
488   lbm->flow_timeout = flow_timeout;
489   lb_put_writer_lock();
490   return 0;
491 }
492
493
494
495 static
496 int lb_vip_port_find_index(ip46_address_t *prefix, u8 plen,
497                            u8 protocol, u16 port,
498                            lb_lkp_type_t lkp_type,
499                            u32 *vip_index)
500 {
501   lb_main_t *lbm = &lb_main;
502   lb_vip_t *vip;
503   /* This must be called with the lock owned */
504   CLIB_SPINLOCK_ASSERT_LOCKED (&lbm->writer_lock);
505   ip46_prefix_normalize(prefix, plen);
506   pool_foreach(vip, lbm->vips, {
507       if ((vip->flags & LB_AS_FLAGS_USED) &&
508           vip->plen == plen &&
509           vip->prefix.as_u64[0] == prefix->as_u64[0] &&
510           vip->prefix.as_u64[1] == prefix->as_u64[1])
511         {
512           if((lkp_type == LB_LKP_SAME_IP_PORT &&
513                vip->protocol == protocol &&
514                vip->port == port) ||
515              (lkp_type == LB_LKP_ALL_PORT_IP &&
516                vip->port == 0) ||
517              (lkp_type == LB_LKP_DIFF_IP_PORT &&
518                 (vip->protocol != protocol ||
519                 vip->port != port) ) )
520             {
521               *vip_index = vip - lbm->vips;
522               return 0;
523             }
524         }
525   });
526   return VNET_API_ERROR_NO_SUCH_ENTRY;
527 }
528
529 static
530 int lb_vip_port_find_index_with_lock(ip46_address_t *prefix, u8 plen,
531                                      u8 protocol, u16 port, u32 *vip_index)
532 {
533   return lb_vip_port_find_index(prefix, plen, protocol, port,
534                                 LB_LKP_SAME_IP_PORT, vip_index);
535 }
536
537 static
538 int lb_vip_port_find_all_port_vip(ip46_address_t *prefix, u8 plen,
539                                   u32 *vip_index)
540 {
541   return lb_vip_port_find_index(prefix, plen, ~0, 0,
542                                 LB_LKP_ALL_PORT_IP, vip_index);
543 }
544
545 /* Find out per-port-vip entry with different protocol and port */
546 static
547 int lb_vip_port_find_diff_port(ip46_address_t *prefix, u8 plen,
548                                u8 protocol, u16 port, u32 *vip_index)
549 {
550   return lb_vip_port_find_index(prefix, plen, protocol, port,
551                                 LB_LKP_DIFF_IP_PORT, vip_index);
552 }
553
554 int lb_vip_find_index(ip46_address_t *prefix, u8 plen, u8 protocol,
555                       u16 port, u32 *vip_index)
556 {
557   int ret;
558   lb_get_writer_lock();
559   ret = lb_vip_port_find_index_with_lock(prefix, plen,
560                                          protocol, port, vip_index);
561   lb_put_writer_lock();
562   return ret;
563 }
564
565 static int lb_as_find_index_vip(lb_vip_t *vip, ip46_address_t *address, u32 *as_index)
566 {
567   lb_main_t *lbm = &lb_main;
568   /* This must be called with the lock owned */
569   CLIB_SPINLOCK_ASSERT_LOCKED (&lbm->writer_lock);
570   lb_as_t *as;
571   u32 *asi;
572   pool_foreach(asi, vip->as_indexes, {
573       as = &lbm->ass[*asi];
574       if (as->vip_index == (vip - lbm->vips) &&
575           as->address.as_u64[0] == address->as_u64[0] &&
576           as->address.as_u64[1] == address->as_u64[1])
577       {
578         *as_index = as - lbm->ass;
579         return 0;
580       }
581   });
582   return -1;
583 }
584
585 int lb_vip_add_ass(u32 vip_index, ip46_address_t *addresses, u32 n)
586 {
587   lb_main_t *lbm = &lb_main;
588   lb_get_writer_lock();
589   lb_vip_t *vip;
590   if (!(vip = lb_vip_get_by_index(vip_index))) {
591     lb_put_writer_lock();
592     return VNET_API_ERROR_NO_SUCH_ENTRY;
593   }
594
595   ip46_type_t type = lb_encap_is_ip4(vip)?IP46_TYPE_IP4:IP46_TYPE_IP6;
596   u32 *to_be_added = 0;
597   u32 *to_be_updated = 0;
598   u32 i;
599   u32 *ip;
600   lb_snat_mapping_t *m;
601
602   //Sanity check
603   while (n--) {
604
605     if (!lb_as_find_index_vip(vip, &addresses[n], &i)) {
606       if (lbm->ass[i].flags & LB_AS_FLAGS_USED) {
607         vec_free(to_be_added);
608         vec_free(to_be_updated);
609         lb_put_writer_lock();
610         return VNET_API_ERROR_VALUE_EXIST;
611       }
612       vec_add1(to_be_updated, i);
613       goto next;
614     }
615
616     if (ip46_address_type(&addresses[n]) != type) {
617       vec_free(to_be_added);
618       vec_free(to_be_updated);
619       lb_put_writer_lock();
620       return VNET_API_ERROR_INVALID_ADDRESS_FAMILY;
621     }
622
623     if (n) {
624       u32 n2 = n;
625       while(n2--) //Check for duplicates
626         if (addresses[n2].as_u64[0] == addresses[n].as_u64[0] &&
627             addresses[n2].as_u64[1] == addresses[n].as_u64[1])
628           goto next;
629     }
630
631     vec_add1(to_be_added, n);
632
633 next:
634     continue;
635   }
636
637   //Update reused ASs
638   vec_foreach(ip, to_be_updated) {
639     lbm->ass[*ip].flags = LB_AS_FLAGS_USED;
640   }
641   vec_free(to_be_updated);
642
643   //Create those who have to be created
644   vec_foreach(ip, to_be_added) {
645     lb_as_t *as;
646     u32 *as_index;
647     pool_get(lbm->ass, as);
648     as->address = addresses[*ip];
649     as->flags = LB_AS_FLAGS_USED;
650     as->vip_index = vip_index;
651     pool_get(vip->as_indexes, as_index);
652     *as_index = as - lbm->ass;
653
654     /*
655      * become a child of the FIB entry
656      * so we are informed when its forwarding changes
657      */
658     fib_prefix_t nh = {};
659     if (lb_encap_is_ip4(vip)) {
660         nh.fp_addr.ip4 = as->address.ip4;
661         nh.fp_len = 32;
662         nh.fp_proto = FIB_PROTOCOL_IP4;
663     } else {
664         nh.fp_addr.ip6 = as->address.ip6;
665         nh.fp_len = 128;
666         nh.fp_proto = FIB_PROTOCOL_IP6;
667     }
668
669     as->next_hop_fib_entry_index =
670         fib_table_entry_special_add(0,
671                                     &nh,
672                                     FIB_SOURCE_RR,
673                                     FIB_ENTRY_FLAG_NONE);
674     as->next_hop_child_index =
675         fib_entry_child_add(as->next_hop_fib_entry_index,
676                             lbm->fib_node_type,
677                             as - lbm->ass);
678
679     lb_as_stack(as);
680
681     if ( lb_vip_is_nat4_port(vip) || lb_vip_is_nat6_port(vip) )
682       {
683         /* Add SNAT static mapping */
684         pool_get (lbm->snat_mappings, m);
685         clib_memset (m, 0, sizeof (*m));
686         if (lb_vip_is_nat4_port(vip)) {
687             lb_snat4_key_t m_key4;
688             clib_bihash_kv_8_8_t kv4;
689             m_key4.addr = as->address.ip4;
690             m_key4.port = vip->encap_args.target_port;
691             m_key4.protocol = 0;
692             m_key4.fib_index = 0;
693
694             if (vip->encap_args.srv_type == LB_SRV_TYPE_CLUSTERIP)
695               {
696                 m->src_ip.ip4 = vip->prefix.ip4;
697               }
698             else if (vip->encap_args.srv_type == LB_SRV_TYPE_NODEPORT)
699               {
700                 m->src_ip.ip4 = lbm->ip4_src_address;
701               }
702             m->src_ip_is_ipv6 = 0;
703             m->as_ip.ip4 = as->address.ip4;
704             m->as_ip_is_ipv6 = 0;
705             m->src_port = vip->port;
706             m->target_port = vip->encap_args.target_port;
707             m->vrf_id = 0;
708             m->fib_index = 0;
709
710             kv4.key = m_key4.as_u64;
711             kv4.value = m - lbm->snat_mappings;
712             clib_bihash_add_del_8_8(&lbm->mapping_by_as4, &kv4, 1);
713         } else {
714             lb_snat6_key_t m_key6;
715             clib_bihash_kv_24_8_t kv6;
716             m_key6.addr.as_u64[0] = as->address.ip6.as_u64[0];
717             m_key6.addr.as_u64[1] = as->address.ip6.as_u64[1];
718             m_key6.port = vip->encap_args.target_port;
719             m_key6.protocol = 0;
720             m_key6.fib_index = 0;
721
722             if (vip->encap_args.srv_type == LB_SRV_TYPE_CLUSTERIP)
723               {
724                 m->src_ip.ip6.as_u64[0] = vip->prefix.ip6.as_u64[0];
725                 m->src_ip.ip6.as_u64[1] = vip->prefix.ip6.as_u64[1];
726               }
727             else if (vip->encap_args.srv_type == LB_SRV_TYPE_NODEPORT)
728               {
729                 m->src_ip.ip6.as_u64[0] = lbm->ip6_src_address.as_u64[0];
730                 m->src_ip.ip6.as_u64[1] = lbm->ip6_src_address.as_u64[1];
731               }
732             m->src_ip_is_ipv6 = 1;
733             m->as_ip.ip6.as_u64[0] = as->address.ip6.as_u64[0];
734             m->as_ip.ip6.as_u64[1] = as->address.ip6.as_u64[1];
735             m->as_ip_is_ipv6 = 1;
736             m->src_port = vip->port;
737             m->target_port = vip->encap_args.target_port;
738             m->vrf_id = 0;
739             m->fib_index = 0;
740
741             kv6.key[0] = m_key6.as_u64[0];
742             kv6.key[1] = m_key6.as_u64[1];
743             kv6.key[2] = m_key6.as_u64[2];
744             kv6.value = m - lbm->snat_mappings;
745             clib_bihash_add_del_24_8(&lbm->mapping_by_as6, &kv6, 1);
746         }
747       }
748   }
749   vec_free(to_be_added);
750
751   //Recompute flows
752   lb_vip_update_new_flow_table(vip);
753
754   //Garbage collection maybe
755   lb_vip_garbage_collection(vip);
756
757   lb_put_writer_lock();
758   return 0;
759 }
760
761 int
762 lb_flush_vip_as (u32 vip_index, u32 as_index)
763 {
764   u32 thread_index;
765   vlib_thread_main_t *tm = vlib_get_thread_main();
766   lb_main_t *lbm = &lb_main;
767
768   for(thread_index = 0; thread_index < tm->n_vlib_mains; thread_index++ ) {
769     lb_hash_t *h = lbm->per_cpu[thread_index].sticky_ht;
770     if (h != NULL) {
771         u32 i;
772         lb_hash_bucket_t *b;
773
774         lb_hash_foreach_entry(h, b, i) {
775           if ((vip_index == ~0)
776               || ((b->vip[i] == vip_index) && (as_index == ~0))
777               || ((b->vip[i] == vip_index) && (b->value[i] == as_index)))
778             {
779               vlib_refcount_add(&lbm->as_refcount, thread_index, b->value[i], -1);
780               vlib_refcount_add(&lbm->as_refcount, thread_index, 0, 1);
781               b->vip[i] = ~0;
782               b->value[i] = 0;
783             }
784         }
785         if (vip_index == ~0)
786           {
787             lb_hash_free(h);
788             lbm->per_cpu[thread_index].sticky_ht = 0;
789           }
790       }
791     }
792
793   return 0;
794 }
795
796 int lb_vip_del_ass_withlock(u32 vip_index, ip46_address_t *addresses, u32 n,
797                             u8 flush)
798 {
799   lb_main_t *lbm = &lb_main;
800   u32 now = (u32) vlib_time_now(vlib_get_main());
801   u32 *ip = 0;
802   u32 as_index = 0;
803
804   lb_vip_t *vip;
805   if (!(vip = lb_vip_get_by_index(vip_index))) {
806     return VNET_API_ERROR_NO_SUCH_ENTRY;
807   }
808
809   u32 *indexes = NULL;
810   while (n--) {
811     if (lb_as_find_index_vip(vip, &addresses[n], &as_index)) {
812       vec_free(indexes);
813       return VNET_API_ERROR_NO_SUCH_ENTRY;
814     }
815
816     if (n) { //Check for duplicates
817       u32 n2 = n - 1;
818       while(n2--) {
819         if (addresses[n2].as_u64[0] == addresses[n].as_u64[0] &&
820             addresses[n2].as_u64[1] == addresses[n].as_u64[1])
821           goto next;
822       }
823     }
824
825     vec_add1(indexes, as_index);
826 next:
827   continue;
828   }
829
830   //Garbage collection maybe
831   lb_vip_garbage_collection(vip);
832
833   if (indexes != NULL) {
834     vec_foreach(ip, indexes) {
835       lbm->ass[*ip].flags &= ~LB_AS_FLAGS_USED;
836       lbm->ass[*ip].last_used = now;
837
838       if(flush)
839         {
840           /* flush flow table for deleted ASs*/
841           lb_flush_vip_as(vip_index, *ip);
842         }
843     }
844
845     //Recompute flows
846     lb_vip_update_new_flow_table(vip);
847   }
848
849   vec_free(indexes);
850   return 0;
851 }
852
853 int lb_vip_del_ass(u32 vip_index, ip46_address_t *addresses, u32 n, u8 flush)
854 {
855   lb_get_writer_lock();
856   int ret = lb_vip_del_ass_withlock(vip_index, addresses, n, flush);
857   lb_put_writer_lock();
858
859   return ret;
860 }
861
862 static int
863 lb_vip_prefix_index_alloc (lb_main_t *lbm)
864 {
865   /*
866    * Check for dynamically allocated instance number.
867    */
868   u32 bit;
869
870   bit = clib_bitmap_first_clear (lbm->vip_prefix_indexes);
871
872   lbm->vip_prefix_indexes = clib_bitmap_set(lbm->vip_prefix_indexes, bit, 1);
873
874   return bit;
875 }
876
877 static int
878 lb_vip_prefix_index_free (lb_main_t *lbm, u32 instance)
879 {
880
881   if (clib_bitmap_get (lbm->vip_prefix_indexes, instance) == 0)
882     {
883       return -1;
884     }
885
886   lbm->vip_prefix_indexes = clib_bitmap_set (lbm->vip_prefix_indexes,
887                                              instance, 0);
888
889   return 0;
890 }
891
892 /**
893  * Add the VIP adjacency to the ip4 or ip6 fib
894  */
895 static void lb_vip_add_adjacency(lb_main_t *lbm, lb_vip_t *vip,
896                                  u32 *vip_prefix_index)
897 {
898   dpo_proto_t proto = 0;
899   dpo_type_t dpo_type = 0;
900   u32 vip_idx = 0;
901
902   if (vip->port != 0)
903     {
904       /* for per-port vip, if VIP adjacency has been added,
905        * no need to add adjacency. */
906       if (!lb_vip_port_find_diff_port(&(vip->prefix), vip->plen,
907                                       vip->protocol, vip->port, &vip_idx))
908         {
909           lb_vip_t *exists_vip = lb_vip_get_by_index(vip_idx);
910           *vip_prefix_index = exists_vip ? exists_vip->vip_prefix_index : ~0;
911           return;
912         }
913
914       /* Allocate an index for per-port vip */
915       *vip_prefix_index = lb_vip_prefix_index_alloc(lbm);
916     }
917   else
918     {
919       *vip_prefix_index = vip - lbm->vips;
920     }
921
922   dpo_id_t dpo = DPO_INVALID;
923   fib_prefix_t pfx = {};
924   if (lb_vip_is_ip4(vip->type)) {
925       pfx.fp_addr.ip4 = vip->prefix.ip4;
926       pfx.fp_len = vip->plen - 96;
927       pfx.fp_proto = FIB_PROTOCOL_IP4;
928       proto = DPO_PROTO_IP4;
929   } else {
930       pfx.fp_addr.ip6 = vip->prefix.ip6;
931       pfx.fp_len = vip->plen;
932       pfx.fp_proto = FIB_PROTOCOL_IP6;
933       proto = DPO_PROTO_IP6;
934   }
935
936   if (lb_vip_is_gre4(vip))
937     dpo_type = lbm->dpo_gre4_type;
938   else if (lb_vip_is_gre6(vip))
939     dpo_type = lbm->dpo_gre6_type;
940   else if (lb_vip_is_gre4_port(vip))
941     dpo_type = lbm->dpo_gre4_port_type;
942   else if (lb_vip_is_gre6_port(vip))
943     dpo_type = lbm->dpo_gre6_port_type;
944   else if (lb_vip_is_l3dsr(vip))
945     dpo_type = lbm->dpo_l3dsr_type;
946   else if (lb_vip_is_l3dsr_port(vip))
947     dpo_type = lbm->dpo_l3dsr_port_type;
948   else if(lb_vip_is_nat4_port(vip))
949     dpo_type = lbm->dpo_nat4_port_type;
950   else if (lb_vip_is_nat6_port(vip))
951     dpo_type = lbm->dpo_nat6_port_type;
952
953   dpo_set(&dpo, dpo_type, proto, *vip_prefix_index);
954   fib_table_entry_special_dpo_add(0,
955                                   &pfx,
956                                   lb_fib_src,
957                                   FIB_ENTRY_FLAG_EXCLUSIVE,
958                                   &dpo);
959   dpo_reset(&dpo);
960 }
961
962 /**
963  * Add the VIP filter entry
964  */
965 static int lb_vip_add_port_filter(lb_main_t *lbm, lb_vip_t *vip,
966                                   u32 vip_prefix_index, u32 vip_idx)
967 {
968   vip_port_key_t key;
969   clib_bihash_kv_8_8_t kv;
970
971   key.vip_prefix_index = vip_prefix_index;
972   key.protocol = vip->protocol;
973   key.port = clib_host_to_net_u16(vip->port);
974   key.rsv = 0;
975
976   kv.key = key.as_u64;
977   kv.value = vip_idx;
978   clib_bihash_add_del_8_8(&lbm->vip_index_per_port, &kv, 1);
979
980   return 0;
981 }
982
983 /**
984  * Del the VIP filter entry
985  */
986 static int lb_vip_del_port_filter(lb_main_t *lbm, lb_vip_t *vip)
987 {
988   vip_port_key_t key;
989   clib_bihash_kv_8_8_t kv, value;
990   lb_vip_t *m = 0;
991
992   key.vip_prefix_index = vip->vip_prefix_index;
993   key.protocol = vip->protocol;
994   key.port = clib_host_to_net_u16(vip->port);
995   key.rsv = 0;
996
997   kv.key = key.as_u64;
998   if(clib_bihash_search_8_8(&lbm->vip_index_per_port, &kv, &value) != 0)
999     {
1000       clib_warning("looking up vip_index_per_port failed.");
1001       return VNET_API_ERROR_NO_SUCH_ENTRY;
1002     }
1003   m = pool_elt_at_index (lbm->vips, value.value);
1004   ASSERT (m);
1005
1006   kv.value = m - lbm->vips;
1007   clib_bihash_add_del_8_8(&lbm->vip_index_per_port, &kv, 0);
1008
1009   return 0;
1010 }
1011
1012 /**
1013  * Deletes the adjacency associated with the VIP
1014  */
1015 static void lb_vip_del_adjacency(lb_main_t *lbm, lb_vip_t *vip)
1016 {
1017   fib_prefix_t pfx = {};
1018   u32 vip_idx = 0;
1019
1020   if (vip->port != 0)
1021     {
1022       /* If this vip adjacency is used by other per-port vip,
1023        * no need to del this adjacency. */
1024       if (!lb_vip_port_find_diff_port(&(vip->prefix), vip->plen,
1025                                       vip->protocol, vip->port, &vip_idx))
1026         {
1027           lb_put_writer_lock();
1028           return;
1029         }
1030
1031       /* Return vip_prefix_index for per-port vip */
1032       lb_vip_prefix_index_free(lbm, vip->vip_prefix_index);
1033
1034     }
1035
1036   if (lb_vip_is_ip4(vip->type)) {
1037       pfx.fp_addr.ip4 = vip->prefix.ip4;
1038       pfx.fp_len = vip->plen - 96;
1039       pfx.fp_proto = FIB_PROTOCOL_IP4;
1040   } else {
1041       pfx.fp_addr.ip6 = vip->prefix.ip6;
1042       pfx.fp_len = vip->plen;
1043       pfx.fp_proto = FIB_PROTOCOL_IP6;
1044   }
1045   fib_table_entry_special_remove(0, &pfx, lb_fib_src);
1046 }
1047
1048 int lb_vip_add(lb_vip_add_args_t args, u32 *vip_index)
1049 {
1050   lb_main_t *lbm = &lb_main;
1051   vlib_main_t *vm = vlib_get_main();
1052   lb_vip_t *vip;
1053   lb_vip_type_t type = args.type;
1054   u32 vip_prefix_index = 0;
1055
1056   lb_get_writer_lock();
1057   ip46_prefix_normalize(&(args.prefix), args.plen);
1058
1059   if (!lb_vip_port_find_index_with_lock(&(args.prefix), args.plen,
1060                                          args.protocol, args.port,
1061                                          vip_index))
1062     {
1063       lb_put_writer_lock();
1064       return VNET_API_ERROR_VALUE_EXIST;
1065     }
1066
1067   /* Make sure we can't add a per-port VIP entry
1068    * when there already is an all-port VIP for the same prefix. */
1069   if ((args.port != 0) &&
1070       !lb_vip_port_find_all_port_vip(&(args.prefix), args.plen, vip_index))
1071     {
1072       lb_put_writer_lock();
1073       return VNET_API_ERROR_VALUE_EXIST;
1074     }
1075
1076   /* Make sure we can't add a all-port VIP entry
1077    * when there already is an per-port VIP for the same prefix. */
1078   if ((args.port == 0) &&
1079       !lb_vip_port_find_diff_port(&(args.prefix), args.plen,
1080                                   args.protocol, args.port, vip_index))
1081     {
1082       lb_put_writer_lock();
1083       return VNET_API_ERROR_VALUE_EXIST;
1084     }
1085
1086   /* Make sure all VIP for a given prefix (using different ports) have the same type. */
1087   if ((args.port != 0) &&
1088       !lb_vip_port_find_diff_port(&(args.prefix), args.plen,
1089                                   args.protocol, args.port, vip_index)
1090       && (args.type != lbm->vips[*vip_index].type))
1091     {
1092       lb_put_writer_lock();
1093       return VNET_API_ERROR_INVALID_ARGUMENT;
1094     }
1095
1096   if (!is_pow2(args.new_length)) {
1097     lb_put_writer_lock();
1098     return VNET_API_ERROR_INVALID_MEMORY_SIZE;
1099   }
1100
1101   if (ip46_prefix_is_ip4(&(args.prefix), args.plen) &&
1102       !lb_vip_is_ip4(type)) {
1103     lb_put_writer_lock();
1104     return VNET_API_ERROR_INVALID_ADDRESS_FAMILY;
1105   }
1106
1107   if ((!ip46_prefix_is_ip4(&(args.prefix), args.plen)) &&
1108       !lb_vip_is_ip6(type)) {
1109     lb_put_writer_lock();
1110     return VNET_API_ERROR_INVALID_ADDRESS_FAMILY;
1111   }
1112
1113   if ((type == LB_VIP_TYPE_IP4_L3DSR) &&
1114       (args.encap_args.dscp >= 64) )
1115     {
1116       lb_put_writer_lock();
1117       return VNET_API_ERROR_VALUE_EXIST;
1118     }
1119
1120   //Allocate
1121   pool_get(lbm->vips, vip);
1122
1123   //Init
1124   memcpy (&(vip->prefix), &(args.prefix), sizeof(args.prefix));
1125   vip->plen = args.plen;
1126   if (args.port != 0)
1127     {
1128       vip->protocol = args.protocol;
1129       vip->port = args.port;
1130     }
1131   else
1132     {
1133       vip->protocol = (u8)~0;
1134       vip->port = 0;
1135     }
1136   vip->last_garbage_collection = (u32) vlib_time_now(vlib_get_main());
1137   vip->type = args.type;
1138
1139   if (args.type == LB_VIP_TYPE_IP4_L3DSR) {
1140       vip->encap_args.dscp = args.encap_args.dscp;
1141     }
1142   else if ((args.type == LB_VIP_TYPE_IP4_NAT4)
1143            ||(args.type == LB_VIP_TYPE_IP6_NAT6)) {
1144       vip->encap_args.srv_type = args.encap_args.srv_type;
1145       vip->encap_args.target_port =
1146           clib_host_to_net_u16(args.encap_args.target_port);
1147     }
1148
1149   vip->flags = LB_VIP_FLAGS_USED;
1150   vip->as_indexes = 0;
1151
1152   //Validate counters
1153   u32 i;
1154   for (i = 0; i < LB_N_VIP_COUNTERS; i++) {
1155     vlib_validate_simple_counter(&lbm->vip_counters[i], vip - lbm->vips);
1156     vlib_zero_simple_counter(&lbm->vip_counters[i], vip - lbm->vips);
1157   }
1158
1159   //Configure new flow table
1160   vip->new_flow_table_mask = args.new_length - 1;
1161   vip->new_flow_table = 0;
1162
1163   //Update flow hash table
1164   lb_vip_update_new_flow_table(vip);
1165
1166   //Create adjacency to direct traffic
1167   lb_vip_add_adjacency(lbm, vip, &vip_prefix_index);
1168
1169   if ( (lb_vip_is_nat4_port(vip) || lb_vip_is_nat6_port(vip))
1170       && (args.encap_args.srv_type == LB_SRV_TYPE_NODEPORT) )
1171     {
1172       u32 key;
1173       uword * entry;
1174
1175       //Create maping from nodeport to vip_index
1176       key = clib_host_to_net_u16(args.port);
1177       entry = hash_get_mem (lbm->vip_index_by_nodeport, &key);
1178       if (entry) {
1179         lb_put_writer_lock();
1180         return VNET_API_ERROR_VALUE_EXIST;
1181       }
1182
1183       hash_set_mem (lbm->vip_index_by_nodeport, &key, vip - lbm->vips);
1184
1185       /* receive packets destined to NodeIP:NodePort */
1186       udp_register_dst_port (vm, args.port, lb4_nodeport_node.index, 1);
1187       udp_register_dst_port (vm, args.port, lb6_nodeport_node.index, 0);
1188     }
1189
1190   *vip_index = vip - lbm->vips;
1191   //Create per-port vip filtering table
1192   if (args.port != 0)
1193     {
1194       lb_vip_add_port_filter(lbm, vip, vip_prefix_index, *vip_index);
1195       vip->vip_prefix_index = vip_prefix_index;
1196     }
1197
1198   lb_put_writer_lock();
1199   return 0;
1200 }
1201
1202 int lb_vip_del(u32 vip_index)
1203 {
1204   lb_main_t *lbm = &lb_main;
1205   lb_vip_t *vip;
1206   int rv = 0;
1207
1208   /* Does not remove default vip, i.e. vip_index = 0 */
1209   if (vip_index == 0)
1210     return VNET_API_ERROR_INVALID_VALUE;
1211
1212   lb_get_writer_lock();
1213   if (!(vip = lb_vip_get_by_index(vip_index))) {
1214     lb_put_writer_lock();
1215     return VNET_API_ERROR_NO_SUCH_ENTRY;
1216   }
1217
1218   //FIXME: This operation is actually not working
1219   //We will need to remove state before performing this.
1220
1221   {
1222     //Remove all ASs
1223     ip46_address_t *ass = 0;
1224     lb_as_t *as;
1225     u32 *as_index;
1226
1227     pool_foreach(as_index, vip->as_indexes, {
1228         as = &lbm->ass[*as_index];
1229         vec_add1(ass, as->address);
1230     });
1231     if (vec_len(ass))
1232       lb_vip_del_ass_withlock(vip_index, ass, vec_len(ass), 0);
1233     vec_free(ass);
1234   }
1235
1236   //Delete adjacency
1237   lb_vip_del_adjacency(lbm, vip);
1238
1239   //Delete per-port vip filtering entry
1240   if (vip->port != 0)
1241     {
1242       rv = lb_vip_del_port_filter(lbm, vip);
1243     }
1244
1245   //Set the VIP as unused
1246   vip->flags &= ~LB_VIP_FLAGS_USED;
1247
1248   lb_put_writer_lock();
1249   return rv;
1250 }
1251
1252 /* *INDENT-OFF* */
1253 VLIB_PLUGIN_REGISTER () = {
1254     .version = VPP_BUILD_VER,
1255     .description = "Load Balancer (LB)",
1256 };
1257 /* *INDENT-ON* */
1258
1259 u8 *format_lb_dpo (u8 * s, va_list * va)
1260 {
1261   index_t index = va_arg (*va, index_t);
1262   CLIB_UNUSED(u32 indent) = va_arg (*va, u32);
1263   lb_main_t *lbm = &lb_main;
1264   lb_vip_t *vip = pool_elt_at_index (lbm->vips, index);
1265   return format (s, "%U", format_lb_vip, vip);
1266 }
1267
1268 static void lb_dpo_lock (dpo_id_t *dpo) {}
1269 static void lb_dpo_unlock (dpo_id_t *dpo) {}
1270
1271 static fib_node_t *
1272 lb_fib_node_get_node (fib_node_index_t index)
1273 {
1274   lb_main_t *lbm = &lb_main;
1275   lb_as_t *as = pool_elt_at_index (lbm->ass, index);
1276   return (&as->fib_node);
1277 }
1278
1279 static void
1280 lb_fib_node_last_lock_gone (fib_node_t *node)
1281 {
1282 }
1283
1284 static lb_as_t *
1285 lb_as_from_fib_node (fib_node_t *node)
1286 {
1287   return ((lb_as_t*)(((char*)node) -
1288       STRUCT_OFFSET_OF(lb_as_t, fib_node)));
1289 }
1290
1291 static void
1292 lb_as_stack (lb_as_t *as)
1293 {
1294   lb_main_t *lbm = &lb_main;
1295   lb_vip_t *vip = &lbm->vips[as->vip_index];
1296   dpo_type_t dpo_type = 0;
1297
1298   if (lb_vip_is_gre4(vip))
1299     dpo_type = lbm->dpo_gre4_type;
1300   else if (lb_vip_is_gre6(vip))
1301     dpo_type = lbm->dpo_gre6_type;
1302   else if (lb_vip_is_gre4_port(vip))
1303     dpo_type = lbm->dpo_gre4_port_type;
1304   else if (lb_vip_is_gre6_port(vip))
1305     dpo_type = lbm->dpo_gre6_port_type;
1306   else if (lb_vip_is_l3dsr(vip))
1307     dpo_type = lbm->dpo_l3dsr_type;
1308   else if (lb_vip_is_l3dsr_port(vip))
1309     dpo_type = lbm->dpo_l3dsr_port_type;
1310   else if(lb_vip_is_nat4_port(vip))
1311     dpo_type = lbm->dpo_nat4_port_type;
1312   else if (lb_vip_is_nat6_port(vip))
1313     dpo_type = lbm->dpo_nat6_port_type;
1314
1315   dpo_stack(dpo_type,
1316             lb_vip_is_ip4(vip->type)?DPO_PROTO_IP4:DPO_PROTO_IP6,
1317             &as->dpo,
1318             fib_entry_contribute_ip_forwarding(
1319                 as->next_hop_fib_entry_index));
1320 }
1321
1322 static fib_node_back_walk_rc_t
1323 lb_fib_node_back_walk_notify (fib_node_t *node,
1324                  fib_node_back_walk_ctx_t *ctx)
1325 {
1326     lb_as_stack(lb_as_from_fib_node(node));
1327     return (FIB_NODE_BACK_WALK_CONTINUE);
1328 }
1329
1330 int lb_nat4_interface_add_del (u32 sw_if_index, int is_del)
1331 {
1332   if (is_del)
1333     {
1334       vnet_feature_enable_disable ("ip4-unicast", "lb-nat4-in2out",
1335                                    sw_if_index, 0, 0, 0);
1336     }
1337   else
1338     {
1339       vnet_feature_enable_disable ("ip4-unicast", "lb-nat4-in2out",
1340                                    sw_if_index, 1, 0, 0);
1341     }
1342
1343   return 0;
1344 }
1345
1346 int lb_nat6_interface_add_del (u32 sw_if_index, int is_del)
1347 {
1348   if (is_del)
1349     {
1350       vnet_feature_enable_disable ("ip6-unicast", "lb-nat6-in2out",
1351                                    sw_if_index, 0, 0, 0);
1352     }
1353   else
1354     {
1355       vnet_feature_enable_disable ("ip6-unicast", "lb-nat6-in2out",
1356                                    sw_if_index, 1, 0, 0);
1357     }
1358
1359   return 0;
1360 }
1361
1362 clib_error_t *
1363 lb_init (vlib_main_t * vm)
1364 {
1365   vlib_thread_main_t *tm = vlib_get_thread_main ();
1366   lb_main_t *lbm = &lb_main;
1367   lbm->vnet_main = vnet_get_main ();
1368   lbm->vlib_main = vm;
1369
1370   lb_vip_t *default_vip;
1371   lb_as_t *default_as;
1372   fib_node_vft_t lb_fib_node_vft = {
1373       .fnv_get = lb_fib_node_get_node,
1374       .fnv_last_lock = lb_fib_node_last_lock_gone,
1375       .fnv_back_walk = lb_fib_node_back_walk_notify,
1376   };
1377   dpo_vft_t lb_vft = {
1378       .dv_lock = lb_dpo_lock,
1379       .dv_unlock = lb_dpo_unlock,
1380       .dv_format = format_lb_dpo,
1381   };
1382
1383   //Allocate and init default VIP.
1384   lbm->vips = 0;
1385   pool_get(lbm->vips, default_vip);
1386   default_vip->new_flow_table_mask = 0;
1387   default_vip->prefix.ip6.as_u64[0] = 0xffffffffffffffffL;
1388   default_vip->prefix.ip6.as_u64[1] = 0xffffffffffffffffL;
1389   default_vip->protocol = ~0;
1390   default_vip->port = 0;
1391   default_vip->flags = LB_VIP_FLAGS_USED;
1392
1393   lbm->per_cpu = 0;
1394   vec_validate(lbm->per_cpu, tm->n_vlib_mains - 1);
1395   clib_spinlock_init (&lbm->writer_lock);
1396   lbm->per_cpu_sticky_buckets = LB_DEFAULT_PER_CPU_STICKY_BUCKETS;
1397   lbm->flow_timeout = LB_DEFAULT_FLOW_TIMEOUT;
1398   lbm->ip4_src_address.as_u32 = 0xffffffff;
1399   lbm->ip6_src_address.as_u64[0] = 0xffffffffffffffffL;
1400   lbm->ip6_src_address.as_u64[1] = 0xffffffffffffffffL;
1401   lbm->dpo_gre4_type = dpo_register_new_type(&lb_vft, lb_dpo_gre4_nodes);
1402   lbm->dpo_gre6_type = dpo_register_new_type(&lb_vft, lb_dpo_gre6_nodes);
1403   lbm->dpo_gre4_port_type = dpo_register_new_type(&lb_vft,
1404                                                   lb_dpo_gre4_port_nodes);
1405   lbm->dpo_gre6_port_type = dpo_register_new_type(&lb_vft,
1406                                                   lb_dpo_gre6_port_nodes);
1407   lbm->dpo_l3dsr_type = dpo_register_new_type(&lb_vft,
1408                                               lb_dpo_l3dsr_nodes);
1409   lbm->dpo_l3dsr_port_type = dpo_register_new_type(&lb_vft,
1410                                                    lb_dpo_l3dsr_port_nodes);
1411   lbm->dpo_nat4_port_type = dpo_register_new_type(&lb_vft,
1412                                                   lb_dpo_nat4_port_nodes);
1413   lbm->dpo_nat6_port_type = dpo_register_new_type(&lb_vft,
1414                                                   lb_dpo_nat6_port_nodes);
1415   lbm->fib_node_type = fib_node_register_new_type(&lb_fib_node_vft);
1416
1417   //Init AS reference counters
1418   vlib_refcount_init(&lbm->as_refcount);
1419
1420   //Allocate and init default AS.
1421   lbm->ass = 0;
1422   pool_get(lbm->ass, default_as);
1423   default_as->flags = 0;
1424   default_as->dpo.dpoi_next_node = LB_NEXT_DROP;
1425   default_as->vip_index = ~0;
1426   default_as->address.ip6.as_u64[0] = 0xffffffffffffffffL;
1427   default_as->address.ip6.as_u64[1] = 0xffffffffffffffffL;
1428
1429   /* Generate a valid flow table for default VIP */
1430   default_vip->as_indexes = NULL;
1431   lb_get_writer_lock();
1432   lb_vip_update_new_flow_table(default_vip);
1433   lb_put_writer_lock();
1434
1435   lbm->vip_index_by_nodeport
1436     = hash_create_mem (0, sizeof(u16), sizeof (uword));
1437
1438   clib_bihash_init_8_8 (&lbm->vip_index_per_port,
1439                         "vip_index_per_port", LB_VIP_PER_PORT_BUCKETS,
1440                         LB_VIP_PER_PORT_MEMORY_SIZE);
1441
1442   clib_bihash_init_8_8 (&lbm->mapping_by_as4,
1443                         "mapping_by_as4", LB_MAPPING_BUCKETS,
1444                         LB_MAPPING_MEMORY_SIZE);
1445
1446   clib_bihash_init_24_8 (&lbm->mapping_by_as6,
1447                         "mapping_by_as6", LB_MAPPING_BUCKETS,
1448                         LB_MAPPING_MEMORY_SIZE);
1449
1450 #define _(a,b,c) lbm->vip_counters[c].name = b;
1451   lb_foreach_vip_counter
1452 #undef _
1453
1454   lb_fib_src = fib_source_allocate("lb",
1455                                    FIB_SOURCE_PRIORITY_HI,
1456                                    FIB_SOURCE_BH_SIMPLE);
1457
1458   return NULL;
1459 }
1460
1461 VLIB_INIT_FUNCTION (lb_init);