de048a4144a6d087816c0366a22c2496163bc634
[vpp.git] / vnet / vnet / lisp-cp / control.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 <vlibmemory/api.h>
17 #include <vnet/lisp-cp/control.h>
18 #include <vnet/lisp-cp/packets.h>
19 #include <vnet/lisp-cp/lisp_msg_serdes.h>
20 #include <vnet/lisp-gpe/lisp_gpe.h>
21 #include <vnet/lisp-gpe/lisp_gpe_fwd_entry.h>
22 #include <vnet/lisp-gpe/lisp_gpe_tenant.h>
23 #include <vnet/fib/fib_entry.h>
24 #include <vnet/fib/fib_table.h>
25
26 #include <openssl/evp.h>
27 #include <openssl/hmac.h>
28
29 typedef struct
30 {
31   u8 is_resend;
32   gid_address_t seid;
33   gid_address_t deid;
34   u8 smr_invoked;
35 } map_request_args_t;
36
37 typedef struct
38 {
39   u64 nonce;
40   u8 is_rloc_probe;
41   mapping_t *mappings;
42 } map_records_arg_t;
43
44 static int
45 lisp_add_del_adjacency (lisp_cp_main_t * lcm, gid_address_t * local_eid,
46                         gid_address_t * remote_eid, u8 is_add);
47
48 u8
49 vnet_lisp_get_map_request_mode (void)
50 {
51   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
52   return lcm->map_request_mode;
53 }
54
55 static u16
56 auth_data_len_by_key_id (lisp_key_type_t key_id)
57 {
58   switch (key_id)
59     {
60     case HMAC_SHA_1_96:
61       return SHA1_AUTH_DATA_LEN;
62     case HMAC_SHA_256_128:
63       return SHA256_AUTH_DATA_LEN;
64     default:
65       clib_warning ("unsupported key type: %d!", key_id);
66       return (u16) ~ 0;
67     }
68   return (u16) ~ 0;
69 }
70
71 static const EVP_MD *
72 get_encrypt_fcn (lisp_key_type_t key_id)
73 {
74   switch (key_id)
75     {
76     case HMAC_SHA_1_96:
77       return EVP_sha1 ();
78     case HMAC_SHA_256_128:
79       return EVP_sha256 ();
80     default:
81       clib_warning ("unsupported encryption key type: %d!", key_id);
82       break;
83     }
84   return 0;
85 }
86
87 static int
88 queue_map_request (gid_address_t * seid, gid_address_t * deid,
89                    u8 smr_invoked, u8 is_resend);
90
91 ip_interface_address_t *
92 ip_interface_get_first_interface_address (ip_lookup_main_t * lm,
93                                           u32 sw_if_index, u8 loop)
94 {
95   vnet_main_t *vnm = vnet_get_main ();
96   vnet_sw_interface_t *swif = vnet_get_sw_interface (vnm, sw_if_index);
97   if (loop && swif->flags & VNET_SW_INTERFACE_FLAG_UNNUMBERED)
98     sw_if_index = swif->unnumbered_sw_if_index;
99   u32 ia =
100     (vec_len ((lm)->if_address_pool_index_by_sw_if_index) > (sw_if_index)) ?
101     vec_elt ((lm)->if_address_pool_index_by_sw_if_index, (sw_if_index)) :
102     (u32) ~ 0;
103   return pool_elt_at_index ((lm)->if_address_pool, ia);
104 }
105
106 void *
107 ip_interface_get_first_address (ip_lookup_main_t * lm, u32 sw_if_index,
108                                 u8 version)
109 {
110   ip_interface_address_t *ia;
111
112   ia = ip_interface_get_first_interface_address (lm, sw_if_index, 1);
113   if (!ia)
114     return 0;
115   return ip_interface_address_get_address (lm, ia);
116 }
117
118 int
119 ip_interface_get_first_ip_address (lisp_cp_main_t * lcm, u32 sw_if_index,
120                                    u8 version, ip_address_t * result)
121 {
122   ip_lookup_main_t *lm;
123   void *addr;
124
125   lm = (version == IP4) ? &lcm->im4->lookup_main : &lcm->im6->lookup_main;
126   addr = ip_interface_get_first_address (lm, sw_if_index, version);
127   if (!addr)
128     return 0;
129
130   ip_address_set (result, addr, version);
131   return 1;
132 }
133
134 /**
135  * convert from a LISP address to a FIB prefix
136  */
137 void
138 ip_address_to_fib_prefix (const ip_address_t * addr, fib_prefix_t * prefix)
139 {
140   if (addr->version == IP4)
141     {
142       prefix->fp_len = 32;
143       prefix->fp_proto = FIB_PROTOCOL_IP4;
144       memset (&prefix->fp_addr.pad, 0, sizeof (prefix->fp_addr.pad));
145       memcpy (&prefix->fp_addr.ip4, &addr->ip, sizeof (prefix->fp_addr.ip4));
146     }
147   else
148     {
149       prefix->fp_len = 128;
150       prefix->fp_proto = FIB_PROTOCOL_IP6;
151       memcpy (&prefix->fp_addr.ip6, &addr->ip, sizeof (prefix->fp_addr.ip6));
152     }
153 }
154
155 /**
156  * convert from a LISP to a FIB prefix
157  */
158 void
159 ip_prefix_to_fib_prefix (const ip_prefix_t * ip_prefix,
160                          fib_prefix_t * fib_prefix)
161 {
162   ip_address_to_fib_prefix (&ip_prefix->addr, fib_prefix);
163   fib_prefix->fp_len = ip_prefix->len;
164 }
165
166 /**
167  * Find the sw_if_index of the interface that would be used to egress towards
168  * dst.
169  */
170 u32
171 ip_fib_get_egress_iface_for_dst (lisp_cp_main_t * lcm, ip_address_t * dst)
172 {
173   fib_node_index_t fei;
174   fib_prefix_t prefix;
175
176   ip_address_to_fib_prefix (dst, &prefix);
177
178   fei = fib_table_lookup (0, &prefix);
179
180   return (fib_entry_get_resolving_interface (fei));
181 }
182
183 /**
184  * Find first IP of the interface that would be used to egress towards dst.
185  * Returns 1 if the address is found 0 otherwise.
186  */
187 int
188 ip_fib_get_first_egress_ip_for_dst (lisp_cp_main_t * lcm, ip_address_t * dst,
189                                     ip_address_t * result)
190 {
191   u32 si;
192   ip_lookup_main_t *lm;
193   void *addr = 0;
194   u8 ipver;
195
196   ASSERT (result != 0);
197
198   ipver = ip_addr_version (dst);
199
200   lm = (ipver == IP4) ? &lcm->im4->lookup_main : &lcm->im6->lookup_main;
201   si = ip_fib_get_egress_iface_for_dst (lcm, dst);
202
203   if ((u32) ~ 0 == si)
204     return 0;
205
206   /* find the first ip address */
207   addr = ip_interface_get_first_address (lm, si, ipver);
208   if (0 == addr)
209     return 0;
210
211   ip_address_set (result, addr, ipver);
212   return 1;
213 }
214
215 static int
216 dp_add_del_iface (lisp_cp_main_t * lcm, u32 vni, u8 is_l2, u8 is_add)
217 {
218   uword *dp_table;
219
220   if (!is_l2)
221     {
222       dp_table = hash_get (lcm->table_id_by_vni, vni);
223
224       if (!dp_table)
225         {
226           clib_warning ("vni %d not associated to a vrf!", vni);
227           return VNET_API_ERROR_INVALID_VALUE;
228         }
229     }
230   else
231     {
232       dp_table = hash_get (lcm->bd_id_by_vni, vni);
233       if (!dp_table)
234         {
235           clib_warning ("vni %d not associated to a bridge domain!", vni);
236           return VNET_API_ERROR_INVALID_VALUE;
237         }
238     }
239
240   /* enable/disable data-plane interface */
241   if (is_add)
242     {
243       if (is_l2)
244         lisp_gpe_tenant_l2_iface_add_or_lock (vni, dp_table[0]);
245       else
246         lisp_gpe_tenant_l3_iface_add_or_lock (vni, dp_table[0]);
247     }
248   else
249     {
250       if (is_l2)
251         lisp_gpe_tenant_l2_iface_unlock (vni);
252       else
253         lisp_gpe_tenant_l3_iface_unlock (vni);
254     }
255
256   return 0;
257 }
258
259 static void
260 dp_del_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index, u32 dst_map_index)
261 {
262   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, *a = &_a;
263   fwd_entry_t *fe = 0;
264   uword *feip = 0;
265   memset (a, 0, sizeof (*a));
266
267   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
268   if (!feip)
269     return;
270
271   fe = pool_elt_at_index (lcm->fwd_entry_pool, feip[0]);
272
273   /* delete dp fwd entry */
274   u32 sw_if_index;
275   a->is_add = 0;
276   a->locator_pairs = fe->locator_pairs;
277   a->vni = gid_address_vni (&fe->reid);
278   gid_address_copy (&a->rmt_eid, &fe->reid);
279   if (fe->is_src_dst)
280     gid_address_copy (&a->lcl_eid, &fe->leid);
281
282   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
283
284   /* delete entry in fwd table */
285   hash_unset (lcm->fwd_entry_by_mapping_index, dst_map_index);
286   vec_free (fe->locator_pairs);
287   pool_put (lcm->fwd_entry_pool, fe);
288 }
289
290 /**
291  * Finds first remote locator with best (lowest) priority that has a local
292  * peer locator with an underlying route to it.
293  *
294  */
295 static u32
296 get_locator_pairs (lisp_cp_main_t * lcm, mapping_t * lcl_map,
297                    mapping_t * rmt_map, locator_pair_t ** locator_pairs)
298 {
299   u32 i, limitp = 0, li, found = 0, esi;
300   locator_set_t *rmt_ls, *lcl_ls;
301   ip_address_t _lcl_addr, *lcl_addr = &_lcl_addr;
302   locator_t *lp, *rmt = 0;
303   uword *checked = 0;
304   locator_pair_t pair;
305
306   rmt_ls =
307     pool_elt_at_index (lcm->locator_set_pool, rmt_map->locator_set_index);
308   lcl_ls =
309     pool_elt_at_index (lcm->locator_set_pool, lcl_map->locator_set_index);
310
311   if (!rmt_ls || vec_len (rmt_ls->locator_indices) == 0)
312     return 0;
313
314   while (1)
315     {
316       rmt = 0;
317
318       /* find unvisited remote locator with best priority */
319       for (i = 0; i < vec_len (rmt_ls->locator_indices); i++)
320         {
321           if (0 != hash_get (checked, i))
322             continue;
323
324           li = vec_elt (rmt_ls->locator_indices, i);
325           lp = pool_elt_at_index (lcm->locator_pool, li);
326
327           /* we don't support non-IP locators for now */
328           if (gid_address_type (&lp->address) != GID_ADDR_IP_PREFIX)
329             continue;
330
331           if ((found && lp->priority == limitp)
332               || (!found && lp->priority >= limitp))
333             {
334               rmt = lp;
335
336               /* don't search for locators with lower priority and don't
337                * check this locator again*/
338               limitp = lp->priority;
339               hash_set (checked, i, 1);
340               break;
341             }
342         }
343       /* check if a local locator with a route to remote locator exists */
344       if (rmt != 0)
345         {
346           /* find egress sw_if_index for rmt locator */
347           esi =
348             ip_fib_get_egress_iface_for_dst (lcm,
349                                              &gid_address_ip (&rmt->address));
350           if ((u32) ~ 0 == esi)
351             continue;
352
353           for (i = 0; i < vec_len (lcl_ls->locator_indices); i++)
354             {
355               li = vec_elt (lcl_ls->locator_indices, i);
356               locator_t *sl = pool_elt_at_index (lcm->locator_pool, li);
357
358               /* found local locator with the needed sw_if_index */
359               if (sl->sw_if_index == esi)
360                 {
361                   /* and it has an address */
362                   if (0 == ip_interface_get_first_ip_address (lcm,
363                                                               sl->sw_if_index,
364                                                               gid_address_ip_version
365                                                               (&rmt->address),
366                                                               lcl_addr))
367                     continue;
368
369                   memset (&pair, 0, sizeof (pair));
370                   ip_address_copy (&pair.rmt_loc,
371                                    &gid_address_ip (&rmt->address));
372                   ip_address_copy (&pair.lcl_loc, lcl_addr);
373                   pair.weight = rmt->weight;
374                   pair.priority = rmt->priority;
375                   vec_add1 (locator_pairs[0], pair);
376                   found = 1;
377                 }
378             }
379         }
380       else
381         break;
382     }
383
384   hash_free (checked);
385   return found;
386 }
387
388 static void
389 gid_address_sd_to_flat (gid_address_t * dst, gid_address_t * src,
390                         fid_address_t * fid)
391 {
392   ASSERT (GID_ADDR_SRC_DST == gid_address_type (src));
393
394   dst[0] = src[0];
395
396   switch (fid_addr_type (fid))
397     {
398     case FID_ADDR_IP_PREF:
399       gid_address_type (dst) = GID_ADDR_IP_PREFIX;
400       gid_address_ippref (dst) = fid_addr_ippref (fid);
401       break;
402     case FID_ADDR_MAC:
403       gid_address_type (dst) = GID_ADDR_MAC;
404       mac_copy (gid_address_mac (dst), fid_addr_mac (fid));
405       break;
406     default:
407       clib_warning ("Unsupported fid type %d!", fid_addr_type (fid));
408       break;
409     }
410 }
411
412 u8
413 vnet_lisp_map_register_state_get (void)
414 {
415   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
416   return lcm->map_registering;
417 }
418
419 u8
420 vnet_lisp_rloc_probe_state_get (void)
421 {
422   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
423   return lcm->rloc_probing;
424 }
425
426 static void
427 dp_add_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index, u32 dst_map_index)
428 {
429   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, *a = &_a;
430   mapping_t *src_map, *dst_map;
431   u32 sw_if_index;
432   uword *feip = 0, *dpid;
433   fwd_entry_t *fe;
434   u8 type, is_src_dst = 0;
435
436   memset (a, 0, sizeof (*a));
437
438   /* remove entry if it already exists */
439   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
440   if (feip)
441     dp_del_fwd_entry (lcm, src_map_index, dst_map_index);
442
443   if (lcm->lisp_pitr)
444     src_map = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
445   else
446     src_map = pool_elt_at_index (lcm->mapping_pool, src_map_index);
447   dst_map = pool_elt_at_index (lcm->mapping_pool, dst_map_index);
448
449   /* insert data plane forwarding entry */
450   a->is_add = 1;
451
452   if (MR_MODE_SRC_DST == lcm->map_request_mode)
453     {
454       if (GID_ADDR_SRC_DST == gid_address_type (&dst_map->eid))
455         {
456           gid_address_sd_to_flat (&a->rmt_eid, &dst_map->eid,
457                                   &gid_address_sd_dst (&dst_map->eid));
458           gid_address_sd_to_flat (&a->lcl_eid, &dst_map->eid,
459                                   &gid_address_sd_src (&dst_map->eid));
460         }
461       else
462         {
463           gid_address_copy (&a->rmt_eid, &dst_map->eid);
464           gid_address_copy (&a->lcl_eid, &src_map->eid);
465         }
466       is_src_dst = 1;
467     }
468   else
469     gid_address_copy (&a->rmt_eid, &dst_map->eid);
470
471   a->vni = gid_address_vni (&a->rmt_eid);
472
473   /* get vrf or bd_index associated to vni */
474   type = gid_address_type (&a->rmt_eid);
475   if (GID_ADDR_IP_PREFIX == type)
476     {
477       dpid = hash_get (lcm->table_id_by_vni, a->vni);
478       if (!dpid)
479         {
480           clib_warning ("vni %d not associated to a vrf!", a->vni);
481           return;
482         }
483       a->table_id = dpid[0];
484     }
485   else if (GID_ADDR_MAC == type)
486     {
487       dpid = hash_get (lcm->bd_id_by_vni, a->vni);
488       if (!dpid)
489         {
490           clib_warning ("vni %d not associated to a bridge domain !", a->vni);
491           return;
492         }
493       a->bd_id = dpid[0];
494     }
495
496   /* find best locator pair that 1) verifies LISP policy 2) are connected */
497   if (0 == get_locator_pairs (lcm, src_map, dst_map, &a->locator_pairs))
498     {
499       /* negative entry */
500       a->is_negative = 1;
501       a->action = dst_map->action;
502     }
503
504   /* TODO remove */
505   u8 ipver = ip_prefix_version (&gid_address_ippref (&a->rmt_eid));
506   a->decap_next_index = (ipver == IP4) ?
507     LISP_GPE_INPUT_NEXT_IP4_INPUT : LISP_GPE_INPUT_NEXT_IP6_INPUT;
508
509   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
510
511   /* add tunnel to fwd entry table XXX check return value from DP insertion */
512   pool_get (lcm->fwd_entry_pool, fe);
513   fe->locator_pairs = a->locator_pairs;
514   gid_address_copy (&fe->reid, &a->rmt_eid);
515   gid_address_copy (&fe->leid, &src_map->eid);
516   fe->is_src_dst = is_src_dst;
517   hash_set (lcm->fwd_entry_by_mapping_index, dst_map_index,
518             fe - lcm->fwd_entry_pool);
519 }
520
521 /**
522  * Returns vector of adjacencies.
523  *
524  * The caller must free the vector returned by this function.
525  *
526  * @param vni virtual network identifier
527  * @return vector of adjacencies
528  */
529 lisp_adjacency_t *
530 vnet_lisp_adjacencies_get_by_vni (u32 vni)
531 {
532   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
533   fwd_entry_t *fwd;
534   lisp_adjacency_t *adjs = 0, adj;
535
536   /* *INDENT-OFF* */
537   pool_foreach(fwd, lcm->fwd_entry_pool,
538   ({
539     if (gid_address_vni (&fwd->reid) != vni)
540       continue;
541
542     gid_address_copy (&adj.reid, &fwd->reid);
543     gid_address_copy (&adj.leid, &fwd->leid);
544     vec_add1 (adjs, adj);
545   }));
546   /* *INDENT-ON* */
547
548   return adjs;
549 }
550
551 static clib_error_t *
552 lisp_show_adjacencies_command_fn (vlib_main_t * vm,
553                                   unformat_input_t * input,
554                                   vlib_cli_command_t * cmd)
555 {
556   lisp_adjacency_t *adjs, *adj;
557   vlib_cli_output (vm, "%s %40s\n", "leid", "reid");
558   unformat_input_t _line_input, *line_input = &_line_input;
559   u32 vni = ~0;
560
561   /* Get a line of input. */
562   if (!unformat_user (input, unformat_line_input, line_input))
563     return 0;
564
565   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
566     {
567       if (unformat (line_input, "vni %d", &vni))
568         ;
569       else
570         {
571           vlib_cli_output (vm, "parse error: '%U'",
572                            format_unformat_error, line_input);
573           return 0;
574         }
575     }
576
577   if (~0 == vni)
578     {
579       vlib_cli_output (vm, "error: no vni specified!");
580       return 0;
581     }
582
583   adjs = vnet_lisp_adjacencies_get_by_vni (vni);
584
585   vec_foreach (adj, adjs)
586   {
587     vlib_cli_output (vm, "%U %40U\n", format_gid_address, &adj->leid,
588                      format_gid_address, &adj->reid);
589   }
590   vec_free (adjs);
591
592   return 0;
593 }
594
595 /* *INDENT-OFF* */
596 VLIB_CLI_COMMAND (lisp_show_adjacencies_command) = {
597     .path = "show lisp adjacencies",
598     .short_help = "show lisp adjacencies",
599     .function = lisp_show_adjacencies_command_fn,
600 };
601 /* *INDENT-ON* */
602
603 static lisp_msmr_t *
604 get_map_server (ip_address_t * a)
605 {
606   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
607   lisp_msmr_t *m;
608
609   vec_foreach (m, lcm->map_servers)
610   {
611     if (!ip_address_cmp (&m->address, a))
612       {
613         return m;
614       }
615   }
616   return 0;
617 }
618
619 static lisp_msmr_t *
620 get_map_resolver (ip_address_t * a)
621 {
622   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
623   lisp_msmr_t *m;
624
625   vec_foreach (m, lcm->map_resolvers)
626   {
627     if (!ip_address_cmp (&m->address, a))
628       {
629         return m;
630       }
631   }
632   return 0;
633 }
634
635 int
636 vnet_lisp_add_del_map_server (ip_address_t * addr, u8 is_add)
637 {
638   u32 i;
639   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
640   lisp_msmr_t _ms, *ms = &_ms;
641
642   if (vnet_lisp_enable_disable_status () == 0)
643     {
644       clib_warning ("LISP is disabled!");
645       return VNET_API_ERROR_LISP_DISABLED;
646     }
647
648   if (is_add)
649     {
650       if (get_map_server (addr))
651         {
652           clib_warning ("map-server %U already exists!", format_ip_address,
653                         addr);
654           return -1;
655         }
656
657       memset (ms, 0, sizeof (*ms));
658       ip_address_copy (&ms->address, addr);
659       vec_add1 (lcm->map_servers, ms[0]);
660     }
661   else
662     {
663       for (i = 0; i < vec_len (lcm->map_servers); i++)
664         {
665           ms = vec_elt_at_index (lcm->map_servers, i);
666           if (!ip_address_cmp (&ms->address, addr))
667             {
668               vec_del1 (lcm->map_servers, i);
669               break;
670             }
671         }
672     }
673
674   return 0;
675 }
676
677 static clib_error_t *
678 lisp_add_del_map_server_command_fn (vlib_main_t * vm,
679                                     unformat_input_t * input,
680                                     vlib_cli_command_t * cmd)
681 {
682   int rv = 0;
683   u8 is_add = 1, ip_set = 0;
684   ip_address_t ip;
685   unformat_input_t _line_input, *line_input = &_line_input;
686
687   /* Get a line of input. */
688   if (!unformat_user (input, unformat_line_input, line_input))
689     return 0;
690
691   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
692     {
693       if (unformat (line_input, "add"))
694         is_add = 1;
695       else if (unformat (line_input, "del"))
696         is_add = 0;
697       else if (unformat (line_input, "%U", unformat_ip_address, &ip))
698         ip_set = 1;
699       else
700         {
701           vlib_cli_output (vm, "parse error: '%U'",
702                            format_unformat_error, line_input);
703           return 0;
704         }
705     }
706
707   if (!ip_set)
708     {
709       vlib_cli_output (vm, "map-server ip address not set!");
710       return 0;
711     }
712
713   rv = vnet_lisp_add_del_map_server (&ip, is_add);
714   if (!rv)
715     vlib_cli_output (vm, "failed to %s map-server!",
716                      is_add ? "add" : "delete");
717
718   return 0;
719 }
720
721 /* *INDENT-OFF* */
722 VLIB_CLI_COMMAND (lisp_add_del_map_server_command) = {
723     .path = "lisp map-server",
724     .short_help = "lisp map-server add|del <ip>",
725     .function = lisp_add_del_map_server_command_fn,
726 };
727 /* *INDENT-ON* */
728
729 /**
730  * Add/remove mapping to/from map-cache. Overwriting not allowed.
731  */
732 int
733 vnet_lisp_map_cache_add_del (vnet_lisp_add_del_mapping_args_t * a,
734                              u32 * map_index_result)
735 {
736   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
737   u32 mi, *map_indexp, map_index, i;
738   mapping_t *m, *old_map;
739   u32 **eid_indexes;
740
741   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &a->eid);
742   old_map = mi != ~0 ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
743   if (a->is_add)
744     {
745       /* TODO check if overwriting and take appropriate actions */
746       if (mi != GID_LOOKUP_MISS && !gid_address_cmp (&old_map->eid, &a->eid))
747         {
748           clib_warning ("eid %U found in the eid-table", format_gid_address,
749                         &a->eid);
750           return VNET_API_ERROR_VALUE_EXIST;
751         }
752
753       pool_get (lcm->mapping_pool, m);
754       gid_address_copy (&m->eid, &a->eid);
755       m->locator_set_index = a->locator_set_index;
756       m->ttl = a->ttl;
757       m->action = a->action;
758       m->local = a->local;
759       m->is_static = a->is_static;
760       m->key = vec_dup (a->key);
761       m->key_id = a->key_id;
762
763       map_index = m - lcm->mapping_pool;
764       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->eid, map_index,
765                               1);
766
767       if (pool_is_free_index (lcm->locator_set_pool, a->locator_set_index))
768         {
769           clib_warning ("Locator set with index %d doesn't exist",
770                         a->locator_set_index);
771           return VNET_API_ERROR_INVALID_VALUE;
772         }
773
774       /* add eid to list of eids supported by locator-set */
775       vec_validate (lcm->locator_set_to_eids, a->locator_set_index);
776       eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids,
777                                       a->locator_set_index);
778       vec_add1 (eid_indexes[0], map_index);
779
780       if (a->local)
781         {
782           /* mark as local */
783           vec_add1 (lcm->local_mappings_indexes, map_index);
784         }
785       map_index_result[0] = map_index;
786     }
787   else
788     {
789       if (mi == GID_LOOKUP_MISS)
790         {
791           clib_warning ("eid %U not found in the eid-table",
792                         format_gid_address, &a->eid);
793           return VNET_API_ERROR_INVALID_VALUE;
794         }
795
796       /* clear locator-set to eids binding */
797       eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids,
798                                       a->locator_set_index);
799       for (i = 0; i < vec_len (eid_indexes[0]); i++)
800         {
801           map_indexp = vec_elt_at_index (eid_indexes[0], i);
802           if (map_indexp[0] == mi)
803             break;
804         }
805       vec_del1 (eid_indexes[0], i);
806
807       /* remove local mark if needed */
808       m = pool_elt_at_index (lcm->mapping_pool, mi);
809       if (m->local)
810         {
811           u32 k, *lm_indexp;
812           for (k = 0; k < vec_len (lcm->local_mappings_indexes); k++)
813             {
814               lm_indexp = vec_elt_at_index (lcm->local_mappings_indexes, k);
815               if (lm_indexp[0] == mi)
816                 break;
817             }
818           vec_del1 (lcm->local_mappings_indexes, k);
819         }
820
821       /* remove mapping from dictionary */
822       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->eid, 0, 0);
823       gid_address_free (&m->eid);
824       pool_put_index (lcm->mapping_pool, mi);
825     }
826
827   return 0;
828 }
829
830 /**
831  *  Add/update/delete mapping to/in/from map-cache.
832  */
833 int
834 vnet_lisp_add_del_local_mapping (vnet_lisp_add_del_mapping_args_t * a,
835                                  u32 * map_index_result)
836 {
837   uword *dp_table = 0;
838   u32 vni;
839   u8 type;
840
841   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
842
843   if (vnet_lisp_enable_disable_status () == 0)
844     {
845       clib_warning ("LISP is disabled!");
846       return VNET_API_ERROR_LISP_DISABLED;
847     }
848
849   vni = gid_address_vni (&a->eid);
850   type = gid_address_type (&a->eid);
851   if (GID_ADDR_IP_PREFIX == type)
852     dp_table = hash_get (lcm->table_id_by_vni, vni);
853   else if (GID_ADDR_MAC == type)
854     dp_table = hash_get (lcm->bd_id_by_vni, vni);
855
856   if (!dp_table)
857     {
858       clib_warning ("vni %d not associated to a %s!", vni,
859                     GID_ADDR_IP_PREFIX == type ? "vrf" : "bd");
860       return VNET_API_ERROR_INVALID_VALUE;
861     }
862
863   /* store/remove mapping from map-cache */
864   return vnet_lisp_map_cache_add_del (a, map_index_result);
865 }
866
867 static clib_error_t *
868 lisp_add_del_local_eid_command_fn (vlib_main_t * vm, unformat_input_t * input,
869                                    vlib_cli_command_t * cmd)
870 {
871   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
872   unformat_input_t _line_input, *line_input = &_line_input;
873   u8 is_add = 1;
874   gid_address_t eid;
875   gid_address_t *eids = 0;
876   clib_error_t *error = 0;
877   u8 *locator_set_name = 0;
878   u32 locator_set_index = 0, map_index = 0;
879   uword *p;
880   vnet_lisp_add_del_mapping_args_t _a, *a = &_a;
881   int rv = 0;
882   u32 vni = 0;
883   u8 *key = 0;
884   u32 key_id = 0;
885
886   memset (&eid, 0, sizeof (eid));
887   memset (a, 0, sizeof (*a));
888
889   /* Get a line of input. */
890   if (!unformat_user (input, unformat_line_input, line_input))
891     return 0;
892
893   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
894     {
895       if (unformat (line_input, "add"))
896         is_add = 1;
897       else if (unformat (line_input, "del"))
898         is_add = 0;
899       else if (unformat (line_input, "eid %U", unformat_gid_address, &eid))
900         ;
901       else if (unformat (line_input, "vni %d", &vni))
902         gid_address_vni (&eid) = vni;
903       else if (unformat (line_input, "secret-key %_%v%_", &key))
904         ;
905       else if (unformat (line_input, "key-id %U", unformat_hmac_key_id,
906                          &key_id))
907         ;
908       else if (unformat (line_input, "locator-set %_%v%_", &locator_set_name))
909         {
910           p = hash_get_mem (lcm->locator_set_index_by_name, locator_set_name);
911           if (!p)
912             {
913               error = clib_error_return (0, "locator-set %s doesn't exist",
914                                          locator_set_name);
915               goto done;
916             }
917           locator_set_index = p[0];
918         }
919       else
920         {
921           error = unformat_parse_error (line_input);
922           goto done;
923         }
924     }
925   /* XXX treat batch configuration */
926
927   if (GID_ADDR_SRC_DST == gid_address_type (&eid))
928     {
929       error =
930         clib_error_return (0, "src/dst is not supported for local EIDs!");
931       goto done;
932     }
933
934   if (key && (0 == key_id))
935     {
936       vlib_cli_output (vm, "invalid key_id!");
937       return 0;
938     }
939
940   gid_address_copy (&a->eid, &eid);
941   a->is_add = is_add;
942   a->locator_set_index = locator_set_index;
943   a->local = 1;
944   a->key = key;
945   a->key_id = key_id;
946
947   rv = vnet_lisp_add_del_local_mapping (a, &map_index);
948   if (0 != rv)
949     {
950       error = clib_error_return (0, "failed to %s local mapping!",
951                                  is_add ? "add" : "delete");
952     }
953 done:
954   vec_free (eids);
955   if (locator_set_name)
956     vec_free (locator_set_name);
957   gid_address_free (&a->eid);
958   vec_free (a->key);
959   return error;
960 }
961
962 /* *INDENT-OFF* */
963 VLIB_CLI_COMMAND (lisp_add_del_local_eid_command) = {
964     .path = "lisp eid-table",
965     .short_help = "lisp eid-table add/del [vni <vni>] eid <eid> "
966       "locator-set <locator-set> [key <secret-key> key-id sha1|sha256 ]",
967     .function = lisp_add_del_local_eid_command_fn,
968 };
969 /* *INDENT-ON* */
970
971 int
972 vnet_lisp_eid_table_map (u32 vni, u32 dp_id, u8 is_l2, u8 is_add)
973 {
974   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
975   uword *dp_idp, *vnip, **dp_table_by_vni, **vni_by_dp_table;
976
977   if (vnet_lisp_enable_disable_status () == 0)
978     {
979       clib_warning ("LISP is disabled!");
980       return -1;
981     }
982
983   dp_table_by_vni = is_l2 ? &lcm->bd_id_by_vni : &lcm->table_id_by_vni;
984   vni_by_dp_table = is_l2 ? &lcm->vni_by_bd_id : &lcm->vni_by_table_id;
985
986   if (!is_l2 && (vni == 0 || dp_id == 0))
987     {
988       clib_warning ("can't add/del default vni-vrf mapping!");
989       return -1;
990     }
991
992   dp_idp = hash_get (dp_table_by_vni[0], vni);
993   vnip = hash_get (vni_by_dp_table[0], dp_id);
994
995   if (is_add)
996     {
997       if (dp_idp || vnip)
998         {
999           clib_warning ("vni %d or vrf %d already used in vrf/vni "
1000                         "mapping!", vni, dp_id);
1001           return -1;
1002         }
1003       hash_set (dp_table_by_vni[0], vni, dp_id);
1004       hash_set (vni_by_dp_table[0], dp_id, vni);
1005
1006       /* create dp iface */
1007       dp_add_del_iface (lcm, vni, is_l2, 1);
1008     }
1009   else
1010     {
1011       if (!dp_idp || !vnip)
1012         {
1013           clib_warning ("vni %d or vrf %d not used in any vrf/vni! "
1014                         "mapping!", vni, dp_id);
1015           return -1;
1016         }
1017       hash_unset (dp_table_by_vni[0], vni);
1018       hash_unset (vni_by_dp_table[0], dp_id);
1019
1020       /* remove dp iface */
1021       dp_add_del_iface (lcm, vni, is_l2, 0);
1022     }
1023   return 0;
1024
1025 }
1026
1027 static clib_error_t *
1028 lisp_eid_table_map_command_fn (vlib_main_t * vm,
1029                                unformat_input_t * input,
1030                                vlib_cli_command_t * cmd)
1031 {
1032   u8 is_add = 1, is_l2 = 0;
1033   u32 vni = 0, dp_id = 0;
1034   unformat_input_t _line_input, *line_input = &_line_input;
1035
1036   /* Get a line of input. */
1037   if (!unformat_user (input, unformat_line_input, line_input))
1038     return 0;
1039
1040   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1041     {
1042       if (unformat (line_input, "del"))
1043         is_add = 0;
1044       else if (unformat (line_input, "vni %d", &vni))
1045         ;
1046       else if (unformat (line_input, "vrf %d", &dp_id))
1047         ;
1048       else if (unformat (line_input, "bd %d", &dp_id))
1049         is_l2 = 1;
1050       else
1051         {
1052           return unformat_parse_error (line_input);
1053         }
1054     }
1055   vnet_lisp_eid_table_map (vni, dp_id, is_l2, is_add);
1056   return 0;
1057 }
1058
1059 /* *INDENT-OFF* */
1060 VLIB_CLI_COMMAND (lisp_eid_table_map_command) = {
1061     .path = "lisp eid-table map",
1062     .short_help = "lisp eid-table map [del] vni <vni> vrf <vrf> | bd <bdi>",
1063     .function = lisp_eid_table_map_command_fn,
1064 };
1065 /* *INDENT-ON* */
1066
1067 /* return 0 if the two locator sets are identical 1 otherwise */
1068 static u8
1069 compare_locators (lisp_cp_main_t * lcm, u32 * old_ls_indexes,
1070                   locator_t * new_locators)
1071 {
1072   u32 i, old_li;
1073   locator_t *old_loc, *new_loc;
1074
1075   if (vec_len (old_ls_indexes) != vec_len (new_locators))
1076     return 1;
1077
1078   for (i = 0; i < vec_len (new_locators); i++)
1079     {
1080       old_li = vec_elt (old_ls_indexes, i);
1081       old_loc = pool_elt_at_index (lcm->locator_pool, old_li);
1082
1083       new_loc = vec_elt_at_index (new_locators, i);
1084
1085       if (locator_cmp (old_loc, new_loc))
1086         return 1;
1087     }
1088   return 0;
1089 }
1090
1091 typedef struct
1092 {
1093   u8 is_negative;
1094   void *lcm;
1095   gid_address_t *eids_to_be_deleted;
1096 } remove_mapping_args_t;
1097
1098 /**
1099  * Callback invoked when a sub-prefix is found
1100  */
1101 static void
1102 remove_mapping_if_needed (u32 mi, void *arg)
1103 {
1104   u8 delete = 0;
1105   remove_mapping_args_t *a = arg;
1106   lisp_cp_main_t *lcm = a->lcm;
1107   mapping_t *m;
1108   locator_set_t *ls;
1109
1110   m = pool_elt_at_index (lcm->mapping_pool, mi);
1111   if (!m)
1112     return;
1113
1114   ls = pool_elt_at_index (lcm->locator_set_pool, m->locator_set_index);
1115
1116   if (a->is_negative)
1117     {
1118       if (0 != vec_len (ls->locator_indices))
1119         delete = 1;
1120     }
1121   else
1122     {
1123       if (0 == vec_len (ls->locator_indices))
1124         delete = 1;
1125     }
1126
1127   if (delete)
1128     vec_add1 (a->eids_to_be_deleted, m->eid);
1129 }
1130
1131 /**
1132  * This function searches map cache and looks for IP prefixes that are subset
1133  * of the provided one. If such prefix is found depending on 'is_negative'
1134  * it does follows:
1135  *
1136  * 1) if is_negative is true and found prefix points to positive mapping,
1137  *    then the mapping is removed
1138  * 2) if is_negative is false and found prefix points to negative mapping,
1139  *    then the mapping is removed
1140  */
1141 static void
1142 remove_overlapping_sub_prefixes (lisp_cp_main_t * lcm, gid_address_t * eid,
1143                                  u8 is_negative)
1144 {
1145   gid_address_t *e;
1146   remove_mapping_args_t a;
1147   memset (&a, 0, sizeof (a));
1148
1149   /* do this only in src/dst mode ... */
1150   if (MR_MODE_SRC_DST != lcm->map_request_mode)
1151     return;
1152
1153   /* ... and  only for IP prefix */
1154   if (GID_ADDR_SRC_DST != gid_address_type (eid)
1155       || (FID_ADDR_IP_PREF != gid_address_sd_dst_type (eid)))
1156     return;
1157
1158   a.is_negative = is_negative;
1159   a.lcm = lcm;
1160
1161   gid_dict_foreach_subprefix (&lcm->mapping_index_by_gid, eid,
1162                               remove_mapping_if_needed, &a);
1163
1164   vec_foreach (e, a.eids_to_be_deleted)
1165   {
1166     lisp_add_del_adjacency (lcm, 0, e, 0 /* is_add */ );
1167     vnet_lisp_add_del_mapping (e, 0, 0, 0, 0, 0 /* is add */ , 0, 0);
1168   }
1169
1170   vec_free (a.eids_to_be_deleted);
1171 }
1172
1173 static void
1174 mapping_delete_timer (lisp_cp_main_t * lcm, u32 mi)
1175 {
1176   timing_wheel_delete (&lcm->wheel, mi);
1177 }
1178
1179 /**
1180  * Adds/removes/updates mapping. Does not program forwarding.
1181  *
1182  * @param eid end-host identifier
1183  * @param rlocs vector of remote locators
1184  * @param action action for negative map-reply
1185  * @param is_add add mapping if non-zero, delete otherwise
1186  * @param res_map_index the map-index that was created/updated/removed. It is
1187  *                      set to ~0 if no action is taken.
1188  * @param is_static used for distinguishing between statically learned
1189                     remote mappings and mappings obtained from MR
1190  * @return return code
1191  */
1192 int
1193 vnet_lisp_add_del_mapping (gid_address_t * eid, locator_t * rlocs, u8 action,
1194                            u8 authoritative, u32 ttl, u8 is_add, u8 is_static,
1195                            u32 * res_map_index)
1196 {
1197   vnet_lisp_add_del_mapping_args_t _m_args, *m_args = &_m_args;
1198   vnet_lisp_add_del_locator_set_args_t _ls_args, *ls_args = &_ls_args;
1199   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1200   u32 mi, ls_index = 0, dst_map_index;
1201   mapping_t *old_map;
1202
1203   if (vnet_lisp_enable_disable_status () == 0)
1204     {
1205       clib_warning ("LISP is disabled!");
1206       return VNET_API_ERROR_LISP_DISABLED;
1207     }
1208
1209   if (res_map_index)
1210     res_map_index[0] = ~0;
1211
1212   memset (m_args, 0, sizeof (m_args[0]));
1213   memset (ls_args, 0, sizeof (ls_args[0]));
1214
1215   ls_args->locators = rlocs;
1216
1217   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, eid);
1218   old_map = ((u32) ~ 0 != mi) ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
1219
1220   if (is_add)
1221     {
1222       /* overwrite: if mapping already exists, decide if locators should be
1223        * updated and be done */
1224       if (old_map && gid_address_cmp (&old_map->eid, eid) == 0)
1225         {
1226           if (!is_static && (old_map->is_static || old_map->local))
1227             {
1228               /* do not overwrite local or static remote mappings */
1229               clib_warning ("mapping %U rejected due to collision with local "
1230                             "or static remote mapping!", format_gid_address,
1231                             eid);
1232               return 0;
1233             }
1234
1235           locator_set_t *old_ls;
1236
1237           /* update mapping attributes */
1238           old_map->action = action;
1239           old_map->authoritative = authoritative;
1240           old_map->ttl = ttl;
1241
1242           old_ls = pool_elt_at_index (lcm->locator_set_pool,
1243                                       old_map->locator_set_index);
1244           if (compare_locators (lcm, old_ls->locator_indices,
1245                                 ls_args->locators))
1246             {
1247               /* set locator-set index to overwrite */
1248               ls_args->is_add = 1;
1249               ls_args->index = old_map->locator_set_index;
1250               vnet_lisp_add_del_locator_set (ls_args, 0);
1251               if (res_map_index)
1252                 res_map_index[0] = mi;
1253             }
1254         }
1255       /* new mapping */
1256       else
1257         {
1258           remove_overlapping_sub_prefixes (lcm, eid, 0 == ls_args->locators);
1259
1260           ls_args->is_add = 1;
1261           ls_args->index = ~0;
1262
1263           vnet_lisp_add_del_locator_set (ls_args, &ls_index);
1264
1265           /* add mapping */
1266           gid_address_copy (&m_args->eid, eid);
1267           m_args->is_add = 1;
1268           m_args->action = action;
1269           m_args->locator_set_index = ls_index;
1270           m_args->is_static = is_static;
1271           m_args->ttl = ttl;
1272           vnet_lisp_map_cache_add_del (m_args, &dst_map_index);
1273
1274           if (res_map_index)
1275             res_map_index[0] = dst_map_index;
1276         }
1277     }
1278   else
1279     {
1280       if (old_map == 0 || gid_address_cmp (&old_map->eid, eid) != 0)
1281         {
1282           clib_warning ("cannot delete mapping for eid %U",
1283                         format_gid_address, eid);
1284           return -1;
1285         }
1286
1287       m_args->is_add = 0;
1288       gid_address_copy (&m_args->eid, eid);
1289       m_args->locator_set_index = old_map->locator_set_index;
1290
1291       /* delete mapping associated from map-cache */
1292       vnet_lisp_map_cache_add_del (m_args, 0);
1293
1294       ls_args->is_add = 0;
1295       ls_args->index = old_map->locator_set_index;
1296       /* delete locator set */
1297       vnet_lisp_add_del_locator_set (ls_args, 0);
1298
1299       /* delete timer associated to the mapping if any */
1300       if (old_map->timer_set)
1301         mapping_delete_timer (lcm, mi);
1302
1303       /* return old mapping index */
1304       if (res_map_index)
1305         res_map_index[0] = mi;
1306     }
1307
1308   /* success */
1309   return 0;
1310 }
1311
1312 int
1313 vnet_lisp_clear_all_remote_adjacencies (void)
1314 {
1315   int rv = 0;
1316   u32 mi, *map_indices = 0, *map_indexp;
1317   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1318   vnet_lisp_add_del_mapping_args_t _dm_args, *dm_args = &_dm_args;
1319   vnet_lisp_add_del_locator_set_args_t _ls, *ls = &_ls;
1320
1321   /* *INDENT-OFF* */
1322   pool_foreach_index (mi, lcm->mapping_pool,
1323   ({
1324     vec_add1 (map_indices, mi);
1325   }));
1326   /* *INDENT-ON* */
1327
1328   vec_foreach (map_indexp, map_indices)
1329   {
1330     mapping_t *map = pool_elt_at_index (lcm->mapping_pool, map_indexp[0]);
1331     if (!map->local)
1332       {
1333         dp_del_fwd_entry (lcm, 0, map_indexp[0]);
1334
1335         dm_args->is_add = 0;
1336         gid_address_copy (&dm_args->eid, &map->eid);
1337         dm_args->locator_set_index = map->locator_set_index;
1338
1339         /* delete mapping associated to fwd entry */
1340         vnet_lisp_map_cache_add_del (dm_args, 0);
1341
1342         ls->is_add = 0;
1343         ls->local = 0;
1344         ls->index = map->locator_set_index;
1345         /* delete locator set */
1346         rv = vnet_lisp_add_del_locator_set (ls, 0);
1347         if (rv != 0)
1348           goto cleanup;
1349       }
1350   }
1351
1352 cleanup:
1353   if (map_indices)
1354     vec_free (map_indices);
1355   return rv;
1356 }
1357
1358 /**
1359  * Adds adjacency or removes forwarding entry associated to remote mapping.
1360  * Note that adjacencies are not stored, they only result in forwarding entries
1361  * being created.
1362  */
1363 static int
1364 lisp_add_del_adjacency (lisp_cp_main_t * lcm, gid_address_t * local_eid,
1365                         gid_address_t * remote_eid, u8 is_add)
1366 {
1367   u32 local_mi, remote_mi = ~0;
1368
1369   if (vnet_lisp_enable_disable_status () == 0)
1370     {
1371       clib_warning ("LISP is disabled!");
1372       return VNET_API_ERROR_LISP_DISABLED;
1373     }
1374
1375   remote_mi = gid_dictionary_sd_lookup (&lcm->mapping_index_by_gid,
1376                                         remote_eid, local_eid);
1377   if (GID_LOOKUP_MISS == remote_mi)
1378     {
1379       clib_warning ("Remote eid %U not found. Cannot add adjacency!",
1380                     format_gid_address, remote_eid);
1381
1382       return -1;
1383     }
1384
1385   if (is_add)
1386     {
1387       /* TODO 1) check if src/dst 2) once we have src/dst working, use it in
1388        * delete*/
1389
1390       /* check if source eid has an associated mapping. If pitr mode is on,
1391        * just use the pitr's mapping */
1392       local_mi = lcm->lisp_pitr ? lcm->pitr_map_index :
1393         gid_dictionary_lookup (&lcm->mapping_index_by_gid, local_eid);
1394
1395
1396       if (GID_LOOKUP_MISS == local_mi)
1397         {
1398           clib_warning ("Local eid %U not found. Cannot add adjacency!",
1399                         format_gid_address, local_eid);
1400
1401           return -1;
1402         }
1403
1404       /* update forwarding */
1405       dp_add_fwd_entry (lcm, local_mi, remote_mi);
1406     }
1407   else
1408     dp_del_fwd_entry (lcm, 0, remote_mi);
1409
1410   return 0;
1411 }
1412
1413 int
1414 vnet_lisp_add_del_adjacency (vnet_lisp_add_del_adjacency_args_t * a)
1415 {
1416   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1417   return lisp_add_del_adjacency (lcm, &a->leid, &a->reid, a->is_add);
1418 }
1419
1420 /**
1421  * Handler for add/del remote mapping CLI.
1422  *
1423  * @param vm vlib context
1424  * @param input input from user
1425  * @param cmd cmd
1426  * @return pointer to clib error structure
1427  */
1428 static clib_error_t *
1429 lisp_add_del_remote_mapping_command_fn (vlib_main_t * vm,
1430                                         unformat_input_t * input,
1431                                         vlib_cli_command_t * cmd)
1432 {
1433   clib_error_t *error = 0;
1434   unformat_input_t _line_input, *line_input = &_line_input;
1435   u8 is_add = 1, del_all = 0;
1436   locator_t rloc, *rlocs = 0, *curr_rloc = 0;
1437   gid_address_t eid;
1438   u8 eid_set = 0;
1439   u32 vni, action = ~0, p, w;
1440   int rv;
1441
1442   /* Get a line of input. */
1443   if (!unformat_user (input, unformat_line_input, line_input))
1444     return 0;
1445
1446   memset (&eid, 0, sizeof (eid));
1447   memset (&rloc, 0, sizeof (rloc));
1448
1449   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1450     {
1451       if (unformat (line_input, "del-all"))
1452         del_all = 1;
1453       else if (unformat (line_input, "del"))
1454         is_add = 0;
1455       else if (unformat (line_input, "add"))
1456         ;
1457       else if (unformat (line_input, "eid %U", unformat_gid_address, &eid))
1458         eid_set = 1;
1459       else if (unformat (line_input, "vni %u", &vni))
1460         {
1461           gid_address_vni (&eid) = vni;
1462         }
1463       else if (unformat (line_input, "p %d w %d", &p, &w))
1464         {
1465           if (!curr_rloc)
1466             {
1467               clib_warning
1468                 ("No RLOC configured for setting priority/weight!");
1469               goto done;
1470             }
1471           curr_rloc->priority = p;
1472           curr_rloc->weight = w;
1473         }
1474       else if (unformat (line_input, "rloc %U", unformat_ip_address,
1475                          &gid_address_ip (&rloc.address)))
1476         {
1477           /* since rloc is stored in ip prefix we need to set prefix length */
1478           ip_prefix_t *pref = &gid_address_ippref (&rloc.address);
1479
1480           u8 version = gid_address_ip_version (&rloc.address);
1481           ip_prefix_len (pref) = ip_address_max_len (version);
1482
1483           vec_add1 (rlocs, rloc);
1484           curr_rloc = &rlocs[vec_len (rlocs) - 1];
1485         }
1486       else if (unformat (line_input, "action %U",
1487                          unformat_negative_mapping_action, &action))
1488         ;
1489       else
1490         {
1491           clib_warning ("parse error");
1492           goto done;
1493         }
1494     }
1495
1496   if (!eid_set)
1497     {
1498       clib_warning ("missing eid!");
1499       goto done;
1500     }
1501
1502   if (!del_all)
1503     {
1504       if (is_add && (~0 == action) && 0 == vec_len (rlocs))
1505         {
1506           clib_warning ("no action set for negative map-reply!");
1507           goto done;
1508         }
1509     }
1510   else
1511     {
1512       vnet_lisp_clear_all_remote_adjacencies ();
1513       goto done;
1514     }
1515
1516   /* TODO build src/dst with seid */
1517
1518   /* if it's a delete, clean forwarding */
1519   if (!is_add)
1520     {
1521       lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1522       rv = lisp_add_del_adjacency (lcm, 0, &eid, /* is_add */ 0);
1523       if (rv)
1524         {
1525           goto done;
1526         }
1527     }
1528
1529   /* add as static remote mapping, i.e., not authoritative and infinite
1530    * ttl */
1531   rv = vnet_lisp_add_del_mapping (&eid, rlocs, action, 0, ~0, is_add,
1532                                   1 /* is_static */ , 0);
1533
1534   if (rv)
1535     clib_warning ("failed to %s remote mapping!", is_add ? "add" : "delete");
1536
1537 done:
1538   vec_free (rlocs);
1539   unformat_free (line_input);
1540   return error;
1541 }
1542
1543 VLIB_CLI_COMMAND (lisp_add_del_remote_mapping_command) =
1544 {
1545 .path = "lisp remote-mapping",.short_help =
1546     "lisp remote-mapping add|del [del-all] vni <vni> "
1547     "eid <est-eid> [action <no-action|natively-forward|"
1548     "send-map-request|drop>] rloc <dst-locator> p <prio> w <weight> "
1549     "[rloc <dst-locator> ... ]",.function =
1550     lisp_add_del_remote_mapping_command_fn,};
1551
1552 /**
1553  * Handler for add/del adjacency CLI.
1554  */
1555 static clib_error_t *
1556 lisp_add_del_adjacency_command_fn (vlib_main_t * vm, unformat_input_t * input,
1557                                    vlib_cli_command_t * cmd)
1558 {
1559   clib_error_t *error = 0;
1560   unformat_input_t _line_input, *line_input = &_line_input;
1561   vnet_lisp_add_del_adjacency_args_t _a, *a = &_a;
1562   u8 is_add = 1;
1563   ip_prefix_t *reid_ippref, *leid_ippref;
1564   gid_address_t leid, reid;
1565   u8 *dmac = gid_address_mac (&reid);
1566   u8 *smac = gid_address_mac (&leid);
1567   u8 reid_set = 0, leid_set = 0;
1568   u32 vni;
1569   int rv;
1570
1571   /* Get a line of input. */
1572   if (!unformat_user (input, unformat_line_input, line_input))
1573     return 0;
1574
1575   memset (&reid, 0, sizeof (reid));
1576   memset (&leid, 0, sizeof (leid));
1577
1578   leid_ippref = &gid_address_ippref (&leid);
1579   reid_ippref = &gid_address_ippref (&reid);
1580
1581   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1582     {
1583       if (unformat (line_input, "del"))
1584         is_add = 0;
1585       else if (unformat (line_input, "add"))
1586         ;
1587       else if (unformat (line_input, "reid %U",
1588                          unformat_ip_prefix, reid_ippref))
1589         {
1590           gid_address_type (&reid) = GID_ADDR_IP_PREFIX;
1591           reid_set = 1;
1592         }
1593       else if (unformat (line_input, "reid %U", unformat_mac_address, dmac))
1594         {
1595           gid_address_type (&reid) = GID_ADDR_MAC;
1596           reid_set = 1;
1597         }
1598       else if (unformat (line_input, "vni %u", &vni))
1599         {
1600           gid_address_vni (&leid) = vni;
1601           gid_address_vni (&reid) = vni;
1602         }
1603       else if (unformat (line_input, "leid %U",
1604                          unformat_ip_prefix, leid_ippref))
1605         {
1606           gid_address_type (&leid) = GID_ADDR_IP_PREFIX;
1607           leid_set = 1;
1608         }
1609       else if (unformat (line_input, "leid %U", unformat_mac_address, smac))
1610         {
1611           gid_address_type (&leid) = GID_ADDR_MAC;
1612           leid_set = 1;
1613         }
1614       else
1615         {
1616           clib_warning ("parse error");
1617           goto done;
1618         }
1619     }
1620
1621   if (!reid_set || !leid_set)
1622     {
1623       clib_warning ("missing remote or local eid!");
1624       goto done;
1625     }
1626
1627   if ((gid_address_type (&leid) != gid_address_type (&reid))
1628       || (gid_address_type (&reid) == GID_ADDR_IP_PREFIX
1629           && ip_prefix_version (reid_ippref)
1630           != ip_prefix_version (leid_ippref)))
1631     {
1632       clib_warning ("remote and local EIDs are of different types!");
1633       return error;
1634     }
1635
1636   memset (a, 0, sizeof (a[0]));
1637   gid_address_copy (&a->leid, &leid);
1638   gid_address_copy (&a->reid, &reid);
1639
1640   a->is_add = is_add;
1641   rv = vnet_lisp_add_del_adjacency (a);
1642
1643   if (rv)
1644     clib_warning ("failed to %s adjacency!", is_add ? "add" : "delete");
1645
1646 done:
1647   unformat_free (line_input);
1648   return error;
1649 }
1650
1651 /* *INDENT-OFF* */
1652 VLIB_CLI_COMMAND (lisp_add_del_adjacency_command) = {
1653     .path = "lisp adjacency",
1654     .short_help = "lisp adjacency add|del vni <vni> reid <remote-eid> "
1655       "leid <local-eid>",
1656     .function = lisp_add_del_adjacency_command_fn,
1657 };
1658 /* *INDENT-ON* */
1659
1660 int
1661 vnet_lisp_set_map_request_mode (u8 mode)
1662 {
1663   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1664
1665   if (vnet_lisp_enable_disable_status () == 0)
1666     {
1667       clib_warning ("LISP is disabled!");
1668       return VNET_API_ERROR_LISP_DISABLED;
1669     }
1670
1671   if (mode >= _MR_MODE_MAX)
1672     {
1673       clib_warning ("Invalid LISP map request mode %d!", mode);
1674       return VNET_API_ERROR_INVALID_ARGUMENT;
1675     }
1676
1677   lcm->map_request_mode = mode;
1678   return 0;
1679 }
1680
1681 static clib_error_t *
1682 lisp_map_request_mode_command_fn (vlib_main_t * vm,
1683                                   unformat_input_t * input,
1684                                   vlib_cli_command_t * cmd)
1685 {
1686   unformat_input_t _i, *i = &_i;
1687   map_request_mode_t mr_mode = _MR_MODE_MAX;
1688
1689   /* Get a line of input. */
1690   if (!unformat_user (input, unformat_line_input, i))
1691     return 0;
1692
1693   while (unformat_check_input (i) != UNFORMAT_END_OF_INPUT)
1694     {
1695       if (unformat (i, "dst-only"))
1696         mr_mode = MR_MODE_DST_ONLY;
1697       else if (unformat (i, "src-dst"))
1698         mr_mode = MR_MODE_SRC_DST;
1699       else
1700         {
1701           clib_warning ("parse error '%U'", format_unformat_error, i);
1702           goto done;
1703         }
1704     }
1705
1706   if (_MR_MODE_MAX == mr_mode)
1707     {
1708       clib_warning ("No LISP map request mode entered!");
1709       return 0;
1710     }
1711
1712   vnet_lisp_set_map_request_mode (mr_mode);
1713 done:
1714   return 0;
1715 }
1716
1717 /* *INDENT-OFF* */
1718 VLIB_CLI_COMMAND (lisp_map_request_mode_command) = {
1719     .path = "lisp map-request mode",
1720     .short_help = "lisp map-request mode dst-only|src-dst",
1721     .function = lisp_map_request_mode_command_fn,
1722 };
1723 /* *INDENT-ON* */
1724
1725 static u8 *
1726 format_lisp_map_request_mode (u8 * s, va_list * args)
1727 {
1728   u32 mode = va_arg (*args, u32);
1729
1730   switch (mode)
1731     {
1732     case 0:
1733       return format (0, "dst-only");
1734     case 1:
1735       return format (0, "src-dst");
1736     }
1737   return 0;
1738 }
1739
1740 static clib_error_t *
1741 lisp_show_map_request_mode_command_fn (vlib_main_t * vm,
1742                                        unformat_input_t * input,
1743                                        vlib_cli_command_t * cmd)
1744 {
1745   vlib_cli_output (vm, "map-request mode: %U", format_lisp_map_request_mode,
1746                    vnet_lisp_get_map_request_mode ());
1747   return 0;
1748 }
1749
1750 /* *INDENT-OFF* */
1751 VLIB_CLI_COMMAND (lisp_show_map_request_mode_command) = {
1752     .path = "show lisp map-request mode",
1753     .short_help = "show lisp map-request mode",
1754     .function = lisp_show_map_request_mode_command_fn,
1755 };
1756 /* *INDENT-ON* */
1757
1758 static clib_error_t *
1759 lisp_show_map_resolvers_command_fn (vlib_main_t * vm,
1760                                     unformat_input_t * input,
1761                                     vlib_cli_command_t * cmd)
1762 {
1763   lisp_msmr_t *mr;
1764   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1765
1766   vec_foreach (mr, lcm->map_resolvers)
1767   {
1768     vlib_cli_output (vm, "%U", format_ip_address, &mr->address);
1769   }
1770   return 0;
1771 }
1772
1773 /* *INDENT-OFF* */
1774 VLIB_CLI_COMMAND (lisp_show_map_resolvers_command) = {
1775     .path = "show lisp map-resolvers",
1776     .short_help = "show lisp map-resolvers",
1777     .function = lisp_show_map_resolvers_command_fn,
1778 };
1779 /* *INDENT-ON* */
1780
1781 int
1782 vnet_lisp_pitr_set_locator_set (u8 * locator_set_name, u8 is_add)
1783 {
1784   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1785   u32 locator_set_index = ~0;
1786   mapping_t *m;
1787   uword *p;
1788
1789   if (vnet_lisp_enable_disable_status () == 0)
1790     {
1791       clib_warning ("LISP is disabled!");
1792       return VNET_API_ERROR_LISP_DISABLED;
1793     }
1794
1795   p = hash_get_mem (lcm->locator_set_index_by_name, locator_set_name);
1796   if (!p)
1797     {
1798       clib_warning ("locator-set %v doesn't exist", locator_set_name);
1799       return -1;
1800     }
1801   locator_set_index = p[0];
1802
1803   if (is_add)
1804     {
1805       pool_get (lcm->mapping_pool, m);
1806       m->locator_set_index = locator_set_index;
1807       m->local = 1;
1808       lcm->pitr_map_index = m - lcm->mapping_pool;
1809
1810       /* enable pitr mode */
1811       lcm->lisp_pitr = 1;
1812     }
1813   else
1814     {
1815       /* remove pitr mapping */
1816       pool_put_index (lcm->mapping_pool, lcm->pitr_map_index);
1817
1818       /* disable pitr mode */
1819       lcm->lisp_pitr = 0;
1820     }
1821   return 0;
1822 }
1823
1824 static clib_error_t *
1825 lisp_pitr_set_locator_set_command_fn (vlib_main_t * vm,
1826                                       unformat_input_t * input,
1827                                       vlib_cli_command_t * cmd)
1828 {
1829   u8 locator_name_set = 0;
1830   u8 *locator_set_name = 0;
1831   u8 is_add = 1;
1832   unformat_input_t _line_input, *line_input = &_line_input;
1833   clib_error_t *error = 0;
1834   int rv = 0;
1835
1836   /* Get a line of input. */
1837   if (!unformat_user (input, unformat_line_input, line_input))
1838     return 0;
1839
1840   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1841     {
1842       if (unformat (line_input, "ls %_%v%_", &locator_set_name))
1843         locator_name_set = 1;
1844       else if (unformat (line_input, "disable"))
1845         is_add = 0;
1846       else
1847         return clib_error_return (0, "parse error");
1848     }
1849
1850   if (!locator_name_set)
1851     {
1852       clib_warning ("No locator set specified!");
1853       goto done;
1854     }
1855   rv = vnet_lisp_pitr_set_locator_set (locator_set_name, is_add);
1856   if (0 != rv)
1857     {
1858       error = clib_error_return (0, "failed to %s pitr!",
1859                                  is_add ? "add" : "delete");
1860     }
1861
1862 done:
1863   if (locator_set_name)
1864     vec_free (locator_set_name);
1865   return error;
1866 }
1867
1868 /* *INDENT-OFF* */
1869 VLIB_CLI_COMMAND (lisp_pitr_set_locator_set_command) = {
1870     .path = "lisp pitr",
1871     .short_help = "lisp pitr [disable] ls <locator-set-name>",
1872     .function = lisp_pitr_set_locator_set_command_fn,
1873 };
1874 /* *INDENT-ON* */
1875
1876 static clib_error_t *
1877 lisp_show_pitr_command_fn (vlib_main_t * vm,
1878                            unformat_input_t * input, vlib_cli_command_t * cmd)
1879 {
1880   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1881   mapping_t *m;
1882   locator_set_t *ls;
1883   u8 *tmp_str = 0;
1884
1885   vlib_cli_output (vm, "%=20s%=16s",
1886                    "pitr", lcm->lisp_pitr ? "locator-set" : "");
1887
1888   if (!lcm->lisp_pitr)
1889     {
1890       vlib_cli_output (vm, "%=20s", "disable");
1891       return 0;
1892     }
1893
1894   if (~0 == lcm->pitr_map_index)
1895     {
1896       tmp_str = format (0, "N/A");
1897     }
1898   else
1899     {
1900       m = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
1901       if (~0 != m->locator_set_index)
1902         {
1903           ls =
1904             pool_elt_at_index (lcm->locator_set_pool, m->locator_set_index);
1905           tmp_str = format (0, "%s", ls->name);
1906         }
1907       else
1908         {
1909           tmp_str = format (0, "N/A");
1910         }
1911     }
1912   vec_add1 (tmp_str, 0);
1913
1914   vlib_cli_output (vm, "%=20s%=16s", "enable", tmp_str);
1915
1916   vec_free (tmp_str);
1917
1918   return 0;
1919 }
1920
1921 /* *INDENT-OFF* */
1922 VLIB_CLI_COMMAND (lisp_show_pitr_command) = {
1923     .path = "show lisp pitr",
1924     .short_help = "Show pitr",
1925     .function = lisp_show_pitr_command_fn,
1926 };
1927 /* *INDENT-ON* */
1928
1929 static u8 *
1930 format_eid_entry (u8 * s, va_list * args)
1931 {
1932   vnet_main_t *vnm = va_arg (*args, vnet_main_t *);
1933   lisp_cp_main_t *lcm = va_arg (*args, lisp_cp_main_t *);
1934   mapping_t *mapit = va_arg (*args, mapping_t *);
1935   locator_set_t *ls = va_arg (*args, locator_set_t *);
1936   gid_address_t *gid = &mapit->eid;
1937   u32 ttl = mapit->ttl;
1938   u8 aut = mapit->authoritative;
1939   u32 *loc_index;
1940   u8 first_line = 1;
1941   u8 *loc;
1942
1943   u8 *type = ls->local ? format (0, "local(%s)", ls->name)
1944     : format (0, "remote");
1945
1946   if (vec_len (ls->locator_indices) == 0)
1947     {
1948       s = format (s, "%-35U%-30s%-20u%-u", format_gid_address, gid,
1949                   type, ttl, aut);
1950     }
1951   else
1952     {
1953       vec_foreach (loc_index, ls->locator_indices)
1954       {
1955         locator_t *l = pool_elt_at_index (lcm->locator_pool, loc_index[0]);
1956         if (l->local)
1957           loc = format (0, "%U", format_vnet_sw_if_index_name, vnm,
1958                         l->sw_if_index);
1959         else
1960           loc = format (0, "%U", format_ip_address,
1961                         &gid_address_ip (&l->address));
1962
1963         if (first_line)
1964           {
1965             s = format (s, "%-35U%-20s%-30v%-20u%-u\n", format_gid_address,
1966                         gid, type, loc, ttl, aut);
1967             first_line = 0;
1968           }
1969         else
1970           s = format (s, "%55s%v\n", "", loc);
1971       }
1972     }
1973   return s;
1974 }
1975
1976 static clib_error_t *
1977 lisp_show_eid_table_command_fn (vlib_main_t * vm,
1978                                 unformat_input_t * input,
1979                                 vlib_cli_command_t * cmd)
1980 {
1981   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1982   mapping_t *mapit;
1983   unformat_input_t _line_input, *line_input = &_line_input;
1984   u32 mi;
1985   gid_address_t eid;
1986   u8 print_all = 1;
1987   u8 filter = 0;
1988
1989   memset (&eid, 0, sizeof (eid));
1990
1991   /* Get a line of input. */
1992   if (!unformat_user (input, unformat_line_input, line_input))
1993     return 0;
1994
1995   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1996     {
1997       if (unformat (line_input, "eid %U", unformat_gid_address, &eid))
1998         print_all = 0;
1999       else if (unformat (line_input, "local"))
2000         filter = 1;
2001       else if (unformat (line_input, "remote"))
2002         filter = 2;
2003       else
2004         return clib_error_return (0, "parse error: '%U'",
2005                                   format_unformat_error, line_input);
2006     }
2007
2008   vlib_cli_output (vm, "%-35s%-20s%-30s%-20s%-s",
2009                    "EID", "type", "locators", "ttl", "autoritative");
2010
2011   if (print_all)
2012     {
2013       /* *INDENT-OFF* */
2014       pool_foreach (mapit, lcm->mapping_pool,
2015       ({
2016         locator_set_t * ls = pool_elt_at_index (lcm->locator_set_pool,
2017                                                 mapit->locator_set_index);
2018         if (filter && !((1 == filter && ls->local) ||
2019           (2 == filter && !ls->local)))
2020           {
2021             continue;
2022           }
2023         vlib_cli_output (vm, "%U", format_eid_entry, lcm->vnet_main,
2024                          lcm, mapit, ls);
2025       }));
2026       /* *INDENT-ON* */
2027     }
2028   else
2029     {
2030       mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &eid);
2031       if ((u32) ~ 0 == mi)
2032         return 0;
2033
2034       mapit = pool_elt_at_index (lcm->mapping_pool, mi);
2035       locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool,
2036                                              mapit->locator_set_index);
2037
2038       if (filter && !((1 == filter && ls->local) ||
2039                       (2 == filter && !ls->local)))
2040         {
2041           return 0;
2042         }
2043
2044       vlib_cli_output (vm, "%U,", format_eid_entry, lcm->vnet_main,
2045                        lcm, mapit, ls);
2046     }
2047
2048   return 0;
2049 }
2050
2051 /* *INDENT-OFF* */
2052 VLIB_CLI_COMMAND (lisp_cp_show_eid_table_command) = {
2053     .path = "show lisp eid-table",
2054     .short_help = "Shows EID table",
2055     .function = lisp_show_eid_table_command_fn,
2056 };
2057 /* *INDENT-ON* */
2058
2059 /* cleans locator to locator-set data and removes locators not part of
2060  * any locator-set */
2061 static void
2062 clean_locator_to_locator_set (lisp_cp_main_t * lcm, u32 lsi)
2063 {
2064   u32 i, j, *loc_indexp, *ls_indexp, **ls_indexes, *to_be_deleted = 0;
2065   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool, lsi);
2066   for (i = 0; i < vec_len (ls->locator_indices); i++)
2067     {
2068       loc_indexp = vec_elt_at_index (ls->locator_indices, i);
2069       ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
2070                                      loc_indexp[0]);
2071       for (j = 0; j < vec_len (ls_indexes[0]); j++)
2072         {
2073           ls_indexp = vec_elt_at_index (ls_indexes[0], j);
2074           if (ls_indexp[0] == lsi)
2075             break;
2076         }
2077
2078       /* delete index for removed locator-set */
2079       vec_del1 (ls_indexes[0], j);
2080
2081       /* delete locator if it's part of no locator-set */
2082       if (vec_len (ls_indexes[0]) == 0)
2083         {
2084           pool_put_index (lcm->locator_pool, loc_indexp[0]);
2085           vec_add1 (to_be_deleted, i);
2086         }
2087     }
2088
2089   if (to_be_deleted)
2090     {
2091       for (i = 0; i < vec_len (to_be_deleted); i++)
2092         {
2093           loc_indexp = vec_elt_at_index (to_be_deleted, i);
2094           vec_del1 (ls->locator_indices, loc_indexp[0]);
2095         }
2096       vec_free (to_be_deleted);
2097     }
2098 }
2099
2100 static inline uword *
2101 get_locator_set_index (vnet_lisp_add_del_locator_set_args_t * a, uword * p)
2102 {
2103   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2104
2105   ASSERT (a != NULL);
2106   ASSERT (p != NULL);
2107
2108   /* find locator-set */
2109   if (a->local)
2110     {
2111       p = hash_get_mem (lcm->locator_set_index_by_name, a->name);
2112     }
2113   else
2114     {
2115       *p = a->index;
2116     }
2117
2118   return p;
2119 }
2120
2121 static inline int
2122 is_locator_in_locator_set (lisp_cp_main_t * lcm, locator_set_t * ls,
2123                            locator_t * loc)
2124 {
2125   locator_t *itloc;
2126   u32 *locit;
2127
2128   ASSERT (ls != NULL);
2129   ASSERT (loc != NULL);
2130
2131   vec_foreach (locit, ls->locator_indices)
2132   {
2133     itloc = pool_elt_at_index (lcm->locator_pool, locit[0]);
2134     if ((ls->local && itloc->sw_if_index == loc->sw_if_index) ||
2135         (!ls->local && !gid_address_cmp (&itloc->address, &loc->address)))
2136       {
2137         clib_warning ("Duplicate locator");
2138         return VNET_API_ERROR_VALUE_EXIST;
2139       }
2140   }
2141
2142   return 0;
2143 }
2144
2145 static inline void
2146 remove_locator_from_locator_set (locator_set_t * ls, u32 * locit,
2147                                  u32 ls_index, u32 loc_id)
2148 {
2149   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2150   u32 **ls_indexes = NULL;
2151
2152   ASSERT (ls != NULL);
2153   ASSERT (locit != NULL);
2154
2155   ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets, locit[0]);
2156   pool_put_index (lcm->locator_pool, locit[0]);
2157   vec_del1 (ls->locator_indices, loc_id);
2158   vec_del1 (ls_indexes[0], ls_index);
2159 }
2160
2161 int
2162 vnet_lisp_add_del_locator (vnet_lisp_add_del_locator_set_args_t * a,
2163                            locator_set_t * ls, u32 * ls_result)
2164 {
2165   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2166   locator_t *loc = NULL, *itloc = NULL;
2167   uword _p = (u32) ~ 0, *p = &_p;
2168   u32 loc_index = ~0, ls_index = ~0, *locit = NULL, **ls_indexes = NULL;
2169   u32 loc_id = ~0;
2170   int ret = 0;
2171
2172   ASSERT (a != NULL);
2173
2174   if (vnet_lisp_enable_disable_status () == 0)
2175     {
2176       clib_warning ("LISP is disabled!");
2177       return VNET_API_ERROR_LISP_DISABLED;
2178     }
2179
2180   p = get_locator_set_index (a, p);
2181   if (!p)
2182     {
2183       clib_warning ("locator-set %v doesn't exist", a->name);
2184       return VNET_API_ERROR_INVALID_ARGUMENT;
2185     }
2186
2187   if (ls == 0)
2188     {
2189       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
2190       if (!ls)
2191         {
2192           clib_warning ("locator-set %d to be overwritten doesn't exist!",
2193                         p[0]);
2194           return VNET_API_ERROR_INVALID_ARGUMENT;
2195         }
2196     }
2197
2198   if (a->is_add)
2199     {
2200       if (ls_result)
2201         ls_result[0] = p[0];
2202
2203       /* allocate locators */
2204       vec_foreach (itloc, a->locators)
2205       {
2206         ret = is_locator_in_locator_set (lcm, ls, itloc);
2207         if (0 != ret)
2208           {
2209             return ret;
2210           }
2211
2212         pool_get (lcm->locator_pool, loc);
2213         loc[0] = itloc[0];
2214         loc_index = loc - lcm->locator_pool;
2215
2216         vec_add1 (ls->locator_indices, loc_index);
2217
2218         vec_validate (lcm->locator_to_locator_sets, loc_index);
2219         ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
2220                                        loc_index);
2221         vec_add1 (ls_indexes[0], p[0]);
2222       }
2223     }
2224   else
2225     {
2226       ls_index = p[0];
2227
2228       itloc = a->locators;
2229       loc_id = 0;
2230       vec_foreach (locit, ls->locator_indices)
2231       {
2232         loc = pool_elt_at_index (lcm->locator_pool, locit[0]);
2233
2234         if (loc->local && loc->sw_if_index == itloc->sw_if_index)
2235           {
2236             remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
2237           }
2238         if (0 == loc->local &&
2239             !gid_address_cmp (&loc->address, &itloc->address))
2240           {
2241             remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
2242           }
2243
2244         loc_id++;
2245       }
2246     }
2247
2248   return 0;
2249 }
2250
2251 int
2252 vnet_lisp_add_del_locator_set (vnet_lisp_add_del_locator_set_args_t * a,
2253                                u32 * ls_result)
2254 {
2255   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2256   locator_set_t *ls;
2257   uword _p = (u32) ~ 0, *p = &_p;
2258   u32 ls_index;
2259   u32 **eid_indexes;
2260   int ret = 0;
2261
2262   if (vnet_lisp_enable_disable_status () == 0)
2263     {
2264       clib_warning ("LISP is disabled!");
2265       return VNET_API_ERROR_LISP_DISABLED;
2266     }
2267
2268   if (a->is_add)
2269     {
2270       p = get_locator_set_index (a, p);
2271
2272       /* overwrite */
2273       if (p && p[0] != (u32) ~ 0)
2274         {
2275           ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
2276           if (!ls)
2277             {
2278               clib_warning ("locator-set %d to be overwritten doesn't exist!",
2279                             p[0]);
2280               return -1;
2281             }
2282
2283           /* clean locator to locator-set vectors and remove locators if
2284            * they're not part of another locator-set */
2285           clean_locator_to_locator_set (lcm, p[0]);
2286
2287           /* remove locator indices from locator set */
2288           vec_free (ls->locator_indices);
2289
2290           ls_index = p[0];
2291
2292           if (ls_result)
2293             ls_result[0] = p[0];
2294         }
2295       /* new locator-set */
2296       else
2297         {
2298           pool_get (lcm->locator_set_pool, ls);
2299           memset (ls, 0, sizeof (*ls));
2300           ls_index = ls - lcm->locator_set_pool;
2301
2302           if (a->local)
2303             {
2304               ls->name = vec_dup (a->name);
2305
2306               if (!lcm->locator_set_index_by_name)
2307                 lcm->locator_set_index_by_name = hash_create_vec (
2308                                                                    /* size */
2309                                                                    0,
2310                                                                    sizeof
2311                                                                    (ls->name
2312                                                                     [0]),
2313                                                                    sizeof
2314                                                                    (uword));
2315               hash_set_mem (lcm->locator_set_index_by_name, ls->name,
2316                             ls_index);
2317
2318               /* mark as local locator-set */
2319               vec_add1 (lcm->local_locator_set_indexes, ls_index);
2320             }
2321           ls->local = a->local;
2322           if (ls_result)
2323             ls_result[0] = ls_index;
2324         }
2325
2326       ret = vnet_lisp_add_del_locator (a, ls, NULL);
2327       if (0 != ret)
2328         {
2329           return ret;
2330         }
2331     }
2332   else
2333     {
2334       p = get_locator_set_index (a, p);
2335       if (!p)
2336         {
2337           clib_warning ("locator-set %v doesn't exists", a->name);
2338           return -1;
2339         }
2340
2341       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
2342       if (!ls)
2343         {
2344           clib_warning ("locator-set with index %d doesn't exists", p[0]);
2345           return -1;
2346         }
2347
2348       if (lcm->mreq_itr_rlocs == p[0])
2349         {
2350           clib_warning ("Can't delete the locator-set used to constrain "
2351                         "the itr-rlocs in map-requests!");
2352           return -1;
2353         }
2354
2355       if (vec_len (lcm->locator_set_to_eids) != 0)
2356         {
2357           eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids, p[0]);
2358           if (vec_len (eid_indexes[0]) != 0)
2359             {
2360               clib_warning
2361                 ("Can't delete a locator that supports a mapping!");
2362               return -1;
2363             }
2364         }
2365
2366       /* clean locator to locator-sets data */
2367       clean_locator_to_locator_set (lcm, p[0]);
2368
2369       if (ls->local)
2370         {
2371           u32 it, lsi;
2372
2373           vec_foreach_index (it, lcm->local_locator_set_indexes)
2374           {
2375             lsi = vec_elt (lcm->local_locator_set_indexes, it);
2376             if (lsi == p[0])
2377               {
2378                 vec_del1 (lcm->local_locator_set_indexes, it);
2379                 break;
2380               }
2381           }
2382           hash_unset_mem (lcm->locator_set_index_by_name, ls->name);
2383         }
2384       vec_free (ls->name);
2385       vec_free (ls->locator_indices);
2386       pool_put (lcm->locator_set_pool, ls);
2387     }
2388   return 0;
2389 }
2390
2391 int
2392 vnet_lisp_rloc_probe_enable_disable (u8 is_enable)
2393 {
2394   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2395
2396   lcm->rloc_probing = is_enable;
2397   return 0;
2398 }
2399
2400 int
2401 vnet_lisp_map_register_enable_disable (u8 is_enable)
2402 {
2403   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2404
2405   lcm->map_registering = is_enable;
2406   return 0;
2407 }
2408
2409 clib_error_t *
2410 vnet_lisp_enable_disable (u8 is_enable)
2411 {
2412   u32 vni, dp_table;
2413   clib_error_t *error = 0;
2414   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2415   vnet_lisp_gpe_enable_disable_args_t _a, *a = &_a;
2416
2417   a->is_en = is_enable;
2418   error = vnet_lisp_gpe_enable_disable (a);
2419   if (error)
2420     {
2421       return clib_error_return (0, "failed to %s data-plane!",
2422                                 a->is_en ? "enable" : "disable");
2423     }
2424
2425   if (is_enable)
2426     {
2427       /* enable all l2 and l3 ifaces */
2428
2429       /* *INDENT-OFF* */
2430       hash_foreach(vni, dp_table, lcm->table_id_by_vni, ({
2431         dp_add_del_iface(lcm, vni, 0, 1);
2432       }));
2433       hash_foreach(vni, dp_table, lcm->bd_id_by_vni, ({
2434         dp_add_del_iface(lcm, vni, /* is_l2 */ 1, 1);
2435       }));
2436       /* *INDENT-ON* */
2437     }
2438   else
2439     {
2440       /* clear interface table */
2441       hash_free (lcm->fwd_entry_by_mapping_index);
2442       pool_free (lcm->fwd_entry_pool);
2443     }
2444
2445   /* update global flag */
2446   lcm->is_enabled = is_enable;
2447
2448   return 0;
2449 }
2450
2451 static clib_error_t *
2452 lisp_enable_disable_command_fn (vlib_main_t * vm, unformat_input_t * input,
2453                                 vlib_cli_command_t * cmd)
2454 {
2455   unformat_input_t _line_input, *line_input = &_line_input;
2456   u8 is_enabled = 0;
2457   u8 is_set = 0;
2458
2459   /* Get a line of input. */
2460   if (!unformat_user (input, unformat_line_input, line_input))
2461     return 0;
2462
2463   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2464     {
2465       if (unformat (line_input, "enable"))
2466         {
2467           is_set = 1;
2468           is_enabled = 1;
2469         }
2470       else if (unformat (line_input, "disable"))
2471         is_set = 1;
2472       else
2473         {
2474           return clib_error_return (0, "parse error: '%U'",
2475                                     format_unformat_error, line_input);
2476         }
2477     }
2478
2479   if (!is_set)
2480     return clib_error_return (0, "state not set");
2481
2482   vnet_lisp_enable_disable (is_enabled);
2483   return 0;
2484 }
2485
2486 /* *INDENT-OFF* */
2487 VLIB_CLI_COMMAND (lisp_cp_enable_disable_command) = {
2488     .path = "lisp",
2489     .short_help = "lisp [enable|disable]",
2490     .function = lisp_enable_disable_command_fn,
2491 };
2492 /* *INDENT-ON* */
2493
2494 static clib_error_t *
2495 lisp_map_register_enable_disable_command_fn (vlib_main_t * vm,
2496                                              unformat_input_t * input,
2497                                              vlib_cli_command_t * cmd)
2498 {
2499   unformat_input_t _line_input, *line_input = &_line_input;
2500   u8 is_enabled = 0;
2501   u8 is_set = 0;
2502
2503   /* Get a line of input. */
2504   if (!unformat_user (input, unformat_line_input, line_input))
2505     return 0;
2506
2507   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2508     {
2509       if (unformat (line_input, "enable"))
2510         {
2511           is_set = 1;
2512           is_enabled = 1;
2513         }
2514       else if (unformat (line_input, "disable"))
2515         is_set = 1;
2516       else
2517         {
2518           vlib_cli_output (vm, "parse error: '%U'", format_unformat_error,
2519                            line_input);
2520           return 0;
2521         }
2522     }
2523
2524   if (!is_set)
2525     {
2526       vlib_cli_output (vm, "state not set!");
2527       return 0;
2528     }
2529
2530   vnet_lisp_map_register_enable_disable (is_enabled);
2531   return 0;
2532 }
2533
2534 /* *INDENT-OFF* */
2535 VLIB_CLI_COMMAND (lisp_map_register_enable_disable_command) = {
2536     .path = "lisp map-register",
2537     .short_help = "lisp map-register [enable|disable]",
2538     .function = lisp_map_register_enable_disable_command_fn,
2539 };
2540 /* *INDENT-ON* */
2541
2542 static clib_error_t *
2543 lisp_rloc_probe_enable_disable_command_fn (vlib_main_t * vm,
2544                                            unformat_input_t * input,
2545                                            vlib_cli_command_t * cmd)
2546 {
2547   unformat_input_t _line_input, *line_input = &_line_input;
2548   u8 is_enabled = 0;
2549   u8 is_set = 0;
2550
2551   /* Get a line of input. */
2552   if (!unformat_user (input, unformat_line_input, line_input))
2553     return 0;
2554
2555   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2556     {
2557       if (unformat (line_input, "enable"))
2558         {
2559           is_set = 1;
2560           is_enabled = 1;
2561         }
2562       else if (unformat (line_input, "disable"))
2563         is_set = 1;
2564       else
2565         {
2566           vlib_cli_output (vm, "parse error: '%U'", format_unformat_error,
2567                            line_input);
2568           return 0;
2569         }
2570     }
2571
2572   if (!is_set)
2573     {
2574       vlib_cli_output (vm, "state not set!");
2575       return 0;
2576     }
2577
2578   vnet_lisp_rloc_probe_enable_disable (is_enabled);
2579   return 0;
2580 }
2581
2582 /* *INDENT-OFF* */
2583 VLIB_CLI_COMMAND (lisp_rloc_probe_enable_disable_command) = {
2584     .path = "lisp rloc-probe",
2585     .short_help = "lisp rloc-probe [enable|disable]",
2586     .function = lisp_rloc_probe_enable_disable_command_fn,
2587 };
2588 /* *INDENT-ON* */
2589
2590 u8
2591 vnet_lisp_enable_disable_status (void)
2592 {
2593   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2594   return lcm->is_enabled;
2595 }
2596
2597 static u8 *
2598 format_lisp_status (u8 * s, va_list * args)
2599 {
2600   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2601   return format (s, "%s", lcm->is_enabled ? "enabled" : "disabled");
2602 }
2603
2604 static clib_error_t *
2605 lisp_show_status_command_fn (vlib_main_t * vm, unformat_input_t * input,
2606                              vlib_cli_command_t * cmd)
2607 {
2608   u8 *msg = 0;
2609   msg = format (msg, "feature: %U\ngpe: %U\n",
2610                 format_lisp_status, format_vnet_lisp_gpe_status);
2611   vlib_cli_output (vm, "%v", msg);
2612   vec_free (msg);
2613   return 0;
2614 }
2615
2616 /* *INDENT-OFF* */
2617 VLIB_CLI_COMMAND (lisp_show_status_command) = {
2618     .path = "show lisp status",
2619     .short_help = "show lisp status",
2620     .function = lisp_show_status_command_fn,
2621 };
2622 /* *INDENT-ON* */
2623
2624 static clib_error_t *
2625 lisp_show_eid_table_map_command_fn (vlib_main_t * vm,
2626                                     unformat_input_t * input,
2627                                     vlib_cli_command_t * cmd)
2628 {
2629   hash_pair_t *p;
2630   unformat_input_t _line_input, *line_input = &_line_input;
2631   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2632   uword *vni_table = 0;
2633   u8 is_l2 = 0;
2634
2635   /* Get a line of input. */
2636   if (!unformat_user (input, unformat_line_input, line_input))
2637     return 0;
2638
2639   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2640     {
2641       if (unformat (line_input, "l2"))
2642         {
2643           vni_table = lcm->bd_id_by_vni;
2644           is_l2 = 1;
2645         }
2646       else if (unformat (line_input, "l3"))
2647         {
2648           vni_table = lcm->table_id_by_vni;
2649           is_l2 = 0;
2650         }
2651       else
2652         return clib_error_return (0, "parse error: '%U'",
2653                                   format_unformat_error, line_input);
2654     }
2655
2656   if (!vni_table)
2657     {
2658       vlib_cli_output (vm, "Error: expected l2|l3 param!\n");
2659       return 0;
2660     }
2661
2662   vlib_cli_output (vm, "%=10s%=10s", "VNI", is_l2 ? "BD" : "VRF");
2663
2664   /* *INDENT-OFF* */
2665   hash_foreach_pair (p, vni_table,
2666   ({
2667     vlib_cli_output (vm, "%=10d%=10d", p->key, p->value[0]);
2668   }));
2669   /* *INDENT-ON* */
2670
2671   return 0;
2672 }
2673
2674 /* *INDENT-OFF* */
2675 VLIB_CLI_COMMAND (lisp_show_eid_table_map_command) = {
2676     .path = "show lisp eid-table map",
2677     .short_help = "show lisp eid-table l2|l3",
2678     .function = lisp_show_eid_table_map_command_fn,
2679 };
2680 /* *INDENT-ON* */
2681
2682 static clib_error_t *
2683 lisp_add_del_locator_set_command_fn (vlib_main_t * vm,
2684                                      unformat_input_t * input,
2685                                      vlib_cli_command_t * cmd)
2686 {
2687   lisp_gpe_main_t *lgm = &lisp_gpe_main;
2688   vnet_main_t *vnm = lgm->vnet_main;
2689   unformat_input_t _line_input, *line_input = &_line_input;
2690   u8 is_add = 1;
2691   clib_error_t *error = 0;
2692   u8 *locator_set_name = 0;
2693   locator_t locator, *locators = 0;
2694   vnet_lisp_add_del_locator_set_args_t _a, *a = &_a;
2695   u32 ls_index = 0;
2696   int rv = 0;
2697
2698   memset (&locator, 0, sizeof (locator));
2699   memset (a, 0, sizeof (a[0]));
2700
2701   /* Get a line of input. */
2702   if (!unformat_user (input, unformat_line_input, line_input))
2703     return 0;
2704
2705   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2706     {
2707       if (unformat (line_input, "add %_%v%_", &locator_set_name))
2708         is_add = 1;
2709       else if (unformat (line_input, "del %_%v%_", &locator_set_name))
2710         is_add = 0;
2711       else if (unformat (line_input, "iface %U p %d w %d",
2712                          unformat_vnet_sw_interface, vnm,
2713                          &locator.sw_if_index, &locator.priority,
2714                          &locator.weight))
2715         {
2716           locator.local = 1;
2717           vec_add1 (locators, locator);
2718         }
2719       else
2720         {
2721           error = unformat_parse_error (line_input);
2722           goto done;
2723         }
2724     }
2725
2726   a->name = locator_set_name;
2727   a->locators = locators;
2728   a->is_add = is_add;
2729   a->local = 1;
2730
2731   rv = vnet_lisp_add_del_locator_set (a, &ls_index);
2732   if (0 != rv)
2733     {
2734       error = clib_error_return (0, "failed to %s locator-set!",
2735                                  is_add ? "add" : "delete");
2736     }
2737
2738 done:
2739   vec_free (locators);
2740   if (locator_set_name)
2741     vec_free (locator_set_name);
2742   return error;
2743 }
2744
2745 /* *INDENT-OFF* */
2746 VLIB_CLI_COMMAND (lisp_cp_add_del_locator_set_command) = {
2747     .path = "lisp locator-set",
2748     .short_help = "lisp locator-set add/del <name> [iface <iface-name> "
2749         "p <priority> w <weight>]",
2750     .function = lisp_add_del_locator_set_command_fn,
2751 };
2752 /* *INDENT-ON* */
2753
2754 static clib_error_t *
2755 lisp_add_del_locator_in_set_command_fn (vlib_main_t * vm,
2756                                         unformat_input_t * input,
2757                                         vlib_cli_command_t * cmd)
2758 {
2759   lisp_gpe_main_t *lgm = &lisp_gpe_main;
2760   vnet_main_t *vnm = lgm->vnet_main;
2761   unformat_input_t _line_input, *line_input = &_line_input;
2762   u8 is_add = 1;
2763   clib_error_t *error = 0;
2764   u8 *locator_set_name = 0;
2765   u8 locator_set_name_set = 0;
2766   locator_t locator, *locators = 0;
2767   vnet_lisp_add_del_locator_set_args_t _a, *a = &_a;
2768   u32 ls_index = 0;
2769
2770   memset (&locator, 0, sizeof (locator));
2771   memset (a, 0, sizeof (a[0]));
2772
2773   /* Get a line of input. */
2774   if (!unformat_user (input, unformat_line_input, line_input))
2775     return 0;
2776
2777   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2778     {
2779       if (unformat (line_input, "add"))
2780         is_add = 1;
2781       else if (unformat (line_input, "del"))
2782         is_add = 0;
2783       else if (unformat (line_input, "locator-set %_%v%_", &locator_set_name))
2784         locator_set_name_set = 1;
2785       else if (unformat (line_input, "iface %U p %d w %d",
2786                          unformat_vnet_sw_interface, vnm,
2787                          &locator.sw_if_index, &locator.priority,
2788                          &locator.weight))
2789         {
2790           locator.local = 1;
2791           vec_add1 (locators, locator);
2792         }
2793       else
2794         {
2795           error = unformat_parse_error (line_input);
2796           goto done;
2797         }
2798     }
2799
2800   if (!locator_set_name_set)
2801     {
2802       error = clib_error_return (0, "locator_set name not set!");
2803       goto done;
2804     }
2805
2806   a->name = locator_set_name;
2807   a->locators = locators;
2808   a->is_add = is_add;
2809   a->local = 1;
2810
2811   vnet_lisp_add_del_locator (a, 0, &ls_index);
2812
2813 done:
2814   vec_free (locators);
2815   vec_free (locator_set_name);
2816   return error;
2817 }
2818
2819 /* *INDENT-OFF* */
2820 VLIB_CLI_COMMAND (lisp_cp_add_del_locator_in_set_command) = {
2821     .path = "lisp locator",
2822     .short_help = "lisp locator add/del locator-set <name> iface <iface-name> "
2823                   "p <priority> w <weight>",
2824     .function = lisp_add_del_locator_in_set_command_fn,
2825 };
2826 /* *INDENT-ON* */
2827
2828 static clib_error_t *
2829 lisp_cp_show_locator_sets_command_fn (vlib_main_t * vm,
2830                                       unformat_input_t * input,
2831                                       vlib_cli_command_t * cmd)
2832 {
2833   locator_set_t *lsit;
2834   locator_t *loc;
2835   u32 *locit;
2836   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2837
2838   vlib_cli_output (vm, "%s%=16s%=16s%=16s", "Locator-set", "Locator",
2839                    "Priority", "Weight");
2840
2841   /* *INDENT-OFF* */
2842   pool_foreach (lsit, lcm->locator_set_pool,
2843   ({
2844     u8 * msg = 0;
2845     int next_line = 0;
2846     if (lsit->local)
2847       {
2848         msg = format (msg, "%v", lsit->name);
2849       }
2850     else
2851       {
2852         msg = format (msg, "<%s-%d>", "remote", lsit - lcm->locator_set_pool);
2853       }
2854     vec_foreach (locit, lsit->locator_indices)
2855       {
2856         if (next_line)
2857           {
2858             msg = format (msg, "%16s", " ");
2859           }
2860         loc = pool_elt_at_index (lcm->locator_pool, locit[0]);
2861         if (loc->local)
2862           msg = format (msg, "%16d%16d%16d\n", loc->sw_if_index, loc->priority,
2863                         loc->weight);
2864         else
2865           msg = format (msg, "%16U%16d%16d\n", format_ip_address,
2866                         &gid_address_ip(&loc->address), loc->priority,
2867                         loc->weight);
2868         next_line = 1;
2869       }
2870     vlib_cli_output (vm, "%v", msg);
2871     vec_free (msg);
2872   }));
2873   /* *INDENT-ON* */
2874   return 0;
2875 }
2876
2877 /* *INDENT-OFF* */
2878 VLIB_CLI_COMMAND (lisp_cp_show_locator_sets_command) = {
2879     .path = "show lisp locator-set",
2880     .short_help = "Shows locator-sets",
2881     .function = lisp_cp_show_locator_sets_command_fn,
2882 };
2883 /* *INDENT-ON* */
2884
2885 int
2886 vnet_lisp_add_del_map_resolver (vnet_lisp_add_del_map_resolver_args_t * a)
2887 {
2888   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2889   u32 i;
2890   lisp_msmr_t _mr, *mr = &_mr;
2891
2892   if (vnet_lisp_enable_disable_status () == 0)
2893     {
2894       clib_warning ("LISP is disabled!");
2895       return VNET_API_ERROR_LISP_DISABLED;
2896     }
2897
2898   if (a->is_add)
2899     {
2900
2901       if (get_map_resolver (&a->address))
2902         {
2903           clib_warning ("map-resolver %U already exists!", format_ip_address,
2904                         &a->address);
2905           return -1;
2906         }
2907
2908       memset (mr, 0, sizeof (*mr));
2909       ip_address_copy (&mr->address, &a->address);
2910       vec_add1 (lcm->map_resolvers, *mr);
2911
2912       if (vec_len (lcm->map_resolvers) == 1)
2913         lcm->do_map_resolver_election = 1;
2914     }
2915   else
2916     {
2917       for (i = 0; i < vec_len (lcm->map_resolvers); i++)
2918         {
2919           mr = vec_elt_at_index (lcm->map_resolvers, i);
2920           if (!ip_address_cmp (&mr->address, &a->address))
2921             {
2922               if (!ip_address_cmp (&mr->address, &lcm->active_map_resolver))
2923                 lcm->do_map_resolver_election = 1;
2924
2925               vec_del1 (lcm->map_resolvers, i);
2926               break;
2927             }
2928         }
2929     }
2930   return 0;
2931 }
2932
2933 static clib_error_t *
2934 lisp_add_del_map_resolver_command_fn (vlib_main_t * vm,
2935                                       unformat_input_t * input,
2936                                       vlib_cli_command_t * cmd)
2937 {
2938   unformat_input_t _line_input, *line_input = &_line_input;
2939   u8 is_add = 1, addr_set = 0;
2940   ip_address_t ip_addr;
2941   clib_error_t *error = 0;
2942   int rv = 0;
2943   vnet_lisp_add_del_map_resolver_args_t _a, *a = &_a;
2944
2945   /* Get a line of input. */
2946   if (!unformat_user (input, unformat_line_input, line_input))
2947     return 0;
2948
2949   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2950     {
2951       if (unformat (line_input, "add"))
2952         is_add = 1;
2953       else if (unformat (line_input, "del"))
2954         is_add = 0;
2955       else if (unformat (line_input, "%U", unformat_ip_address, &ip_addr))
2956         addr_set = 1;
2957       else
2958         {
2959           error = unformat_parse_error (line_input);
2960           goto done;
2961         }
2962     }
2963
2964   if (!addr_set)
2965     {
2966       error = clib_error_return (0, "Map-resolver address must be set!");
2967       goto done;
2968     }
2969
2970   a->is_add = is_add;
2971   a->address = ip_addr;
2972   rv = vnet_lisp_add_del_map_resolver (a);
2973   if (0 != rv)
2974     {
2975       error = clib_error_return (0, "failed to %s map-resolver!",
2976                                  is_add ? "add" : "delete");
2977     }
2978
2979 done:
2980   return error;
2981 }
2982
2983 /* *INDENT-OFF* */
2984 VLIB_CLI_COMMAND (lisp_add_del_map_resolver_command) = {
2985     .path = "lisp map-resolver",
2986     .short_help = "lisp map-resolver add/del <ip_address>",
2987     .function = lisp_add_del_map_resolver_command_fn,
2988 };
2989 /* *INDENT-ON* */
2990
2991 int
2992 vnet_lisp_add_del_mreq_itr_rlocs (vnet_lisp_add_del_mreq_itr_rloc_args_t * a)
2993 {
2994   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2995   uword *p = 0;
2996
2997   if (vnet_lisp_enable_disable_status () == 0)
2998     {
2999       clib_warning ("LISP is disabled!");
3000       return VNET_API_ERROR_LISP_DISABLED;
3001     }
3002
3003   if (a->is_add)
3004     {
3005       p = hash_get_mem (lcm->locator_set_index_by_name, a->locator_set_name);
3006       if (!p)
3007         {
3008           clib_warning ("locator-set %v doesn't exist", a->locator_set_name);
3009           return VNET_API_ERROR_INVALID_ARGUMENT;
3010         }
3011
3012       lcm->mreq_itr_rlocs = p[0];
3013     }
3014   else
3015     {
3016       lcm->mreq_itr_rlocs = ~0;
3017     }
3018
3019   return 0;
3020 }
3021
3022 static clib_error_t *
3023 lisp_add_del_mreq_itr_rlocs_command_fn (vlib_main_t * vm,
3024                                         unformat_input_t * input,
3025                                         vlib_cli_command_t * cmd)
3026 {
3027   unformat_input_t _line_input, *line_input = &_line_input;
3028   u8 is_add = 1;
3029   u8 *locator_set_name = 0;
3030   clib_error_t *error = 0;
3031   int rv = 0;
3032   vnet_lisp_add_del_mreq_itr_rloc_args_t _a, *a = &_a;
3033
3034   /* Get a line of input. */
3035   if (!unformat_user (input, unformat_line_input, line_input))
3036     return 0;
3037
3038   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3039     {
3040       if (unformat (line_input, "del"))
3041         is_add = 0;
3042       else if (unformat (line_input, "add %_%v%_", &locator_set_name))
3043         is_add = 1;
3044       else
3045         {
3046           error = unformat_parse_error (line_input);
3047           goto done;
3048         }
3049     }
3050
3051   a->is_add = is_add;
3052   a->locator_set_name = locator_set_name;
3053   rv = vnet_lisp_add_del_mreq_itr_rlocs (a);
3054   if (0 != rv)
3055     {
3056       error = clib_error_return (0, "failed to %s map-request itr-rlocs!",
3057                                  is_add ? "add" : "delete");
3058     }
3059
3060   vec_free (locator_set_name);
3061
3062 done:
3063   return error;
3064
3065 }
3066
3067 /* *INDENT-OFF* */
3068 VLIB_CLI_COMMAND (lisp_add_del_map_request_command) = {
3069     .path = "lisp map-request itr-rlocs",
3070     .short_help = "lisp map-request itr-rlocs add/del <locator_set_name>",
3071     .function = lisp_add_del_mreq_itr_rlocs_command_fn,
3072 };
3073 /* *INDENT-ON* */
3074
3075 static clib_error_t *
3076 lisp_show_mreq_itr_rlocs_command_fn (vlib_main_t * vm,
3077                                      unformat_input_t * input,
3078                                      vlib_cli_command_t * cmd)
3079 {
3080   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3081   locator_set_t *loc_set;
3082
3083   vlib_cli_output (vm, "%=20s", "itr-rlocs");
3084
3085   if (~0 == lcm->mreq_itr_rlocs)
3086     {
3087       return 0;
3088     }
3089
3090   loc_set = pool_elt_at_index (lcm->locator_set_pool, lcm->mreq_itr_rlocs);
3091
3092   vlib_cli_output (vm, "%=20s", loc_set->name);
3093
3094   return 0;
3095 }
3096
3097 /* *INDENT-OFF* */
3098 VLIB_CLI_COMMAND (lisp_show_map_request_command) = {
3099     .path = "show lisp map-request itr-rlocs",
3100     .short_help = "Shows map-request itr-rlocs",
3101     .function = lisp_show_mreq_itr_rlocs_command_fn,
3102 };
3103 /* *INDENT-ON* */
3104
3105 /* Statistics (not really errors) */
3106 #define foreach_lisp_cp_lookup_error           \
3107 _(DROP, "drop")                                \
3108 _(MAP_REQUESTS_SENT, "map-request sent")
3109
3110 static char *lisp_cp_lookup_error_strings[] = {
3111 #define _(sym,string) string,
3112   foreach_lisp_cp_lookup_error
3113 #undef _
3114 };
3115
3116 typedef enum
3117 {
3118 #define _(sym,str) LISP_CP_LOOKUP_ERROR_##sym,
3119   foreach_lisp_cp_lookup_error
3120 #undef _
3121     LISP_CP_LOOKUP_N_ERROR,
3122 } lisp_cp_lookup_error_t;
3123
3124 typedef enum
3125 {
3126   LISP_CP_LOOKUP_NEXT_DROP,
3127   LISP_CP_LOOKUP_N_NEXT,
3128 } lisp_cp_lookup_next_t;
3129
3130 typedef struct
3131 {
3132   gid_address_t dst_eid;
3133   ip_address_t map_resolver_ip;
3134 } lisp_cp_lookup_trace_t;
3135
3136 u8 *
3137 format_lisp_cp_lookup_trace (u8 * s, va_list * args)
3138 {
3139   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
3140   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
3141   lisp_cp_lookup_trace_t *t = va_arg (*args, lisp_cp_lookup_trace_t *);
3142
3143   s = format (s, "LISP-CP-LOOKUP: map-resolver: %U destination eid %U",
3144               format_ip_address, &t->map_resolver_ip, format_gid_address,
3145               &t->dst_eid);
3146   return s;
3147 }
3148
3149 int
3150 get_mr_and_local_iface_ip (lisp_cp_main_t * lcm, ip_address_t * mr_ip,
3151                            ip_address_t * sloc)
3152 {
3153   lisp_msmr_t *mrit;
3154   ip_address_t *a;
3155
3156   if (vec_len (lcm->map_resolvers) == 0)
3157     {
3158       clib_warning ("No map-resolver configured");
3159       return 0;
3160     }
3161
3162   /* find the first mr ip we have a route to and the ip of the
3163    * iface that has a route to it */
3164   vec_foreach (mrit, lcm->map_resolvers)
3165   {
3166     a = &mrit->address;
3167     if (0 != ip_fib_get_first_egress_ip_for_dst (lcm, a, sloc))
3168       {
3169         ip_address_copy (mr_ip, a);
3170
3171         /* also update globals */
3172         return 1;
3173       }
3174   }
3175
3176   clib_warning ("Can't find map-resolver and local interface ip!");
3177   return 0;
3178 }
3179
3180 static gid_address_t *
3181 build_itr_rloc_list (lisp_cp_main_t * lcm, locator_set_t * loc_set)
3182 {
3183   void *addr;
3184   u32 i;
3185   locator_t *loc;
3186   u32 *loc_indexp;
3187   ip_interface_address_t *ia = 0;
3188   gid_address_t gid_data, *gid = &gid_data;
3189   gid_address_t *rlocs = 0;
3190   ip_prefix_t *ippref = &gid_address_ippref (gid);
3191   ip_address_t *rloc = &ip_prefix_addr (ippref);
3192
3193   memset (gid, 0, sizeof (gid[0]));
3194   gid_address_type (gid) = GID_ADDR_IP_PREFIX;
3195   for (i = 0; i < vec_len (loc_set->locator_indices); i++)
3196     {
3197       loc_indexp = vec_elt_at_index (loc_set->locator_indices, i);
3198       loc = pool_elt_at_index (lcm->locator_pool, loc_indexp[0]);
3199
3200       /* Add ipv4 locators first TODO sort them */
3201
3202       /* *INDENT-OFF* */
3203       foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
3204                                     loc->sw_if_index, 1 /* unnumbered */,
3205       ({
3206         addr = ip_interface_address_get_address (&lcm->im4->lookup_main, ia);
3207         ip_address_set (rloc, addr, IP4);
3208         ip_prefix_len (ippref) = 32;
3209         ip_prefix_normalize (ippref);
3210         vec_add1 (rlocs, gid[0]);
3211       }));
3212
3213       /* Add ipv6 locators */
3214       foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
3215                                     loc->sw_if_index, 1 /* unnumbered */,
3216       ({
3217         addr = ip_interface_address_get_address (&lcm->im6->lookup_main, ia);
3218         ip_address_set (rloc, addr, IP6);
3219         ip_prefix_len (ippref) = 128;
3220         ip_prefix_normalize (ippref);
3221         vec_add1 (rlocs, gid[0]);
3222       }));
3223       /* *INDENT-ON* */
3224
3225     }
3226   return rlocs;
3227 }
3228
3229 static vlib_buffer_t *
3230 build_map_request (lisp_cp_main_t * lcm, gid_address_t * deid,
3231                    ip_address_t * sloc, ip_address_t * rloc,
3232                    gid_address_t * itr_rlocs, u64 * nonce_res, u32 * bi_res)
3233 {
3234   vlib_buffer_t *b;
3235   u32 bi;
3236   vlib_main_t *vm = lcm->vlib_main;
3237
3238   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
3239     {
3240       clib_warning ("Can't allocate buffer for Map-Request!");
3241       return 0;
3242     }
3243
3244   b = vlib_get_buffer (vm, bi);
3245
3246   /* leave some space for the encap headers */
3247   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
3248
3249   /* put lisp msg */
3250   lisp_msg_put_mreq (lcm, b, NULL, deid, itr_rlocs, 0 /* smr invoked */ ,
3251                      1 /* rloc probe */ , nonce_res);
3252
3253   /* push outer ip header */
3254   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
3255                        rloc);
3256
3257   bi_res[0] = bi;
3258
3259   return b;
3260 }
3261
3262 static vlib_buffer_t *
3263 build_encapsulated_map_request (lisp_cp_main_t * lcm,
3264                                 gid_address_t * seid, gid_address_t * deid,
3265                                 locator_set_t * loc_set, ip_address_t * mr_ip,
3266                                 ip_address_t * sloc, u8 is_smr_invoked,
3267                                 u64 * nonce_res, u32 * bi_res)
3268 {
3269   vlib_buffer_t *b;
3270   u32 bi;
3271   gid_address_t *rlocs = 0;
3272   vlib_main_t *vm = lcm->vlib_main;
3273
3274   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
3275     {
3276       clib_warning ("Can't allocate buffer for Map-Request!");
3277       return 0;
3278     }
3279
3280   b = vlib_get_buffer (vm, bi);
3281
3282   /* leave some space for the encap headers */
3283   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
3284
3285   /* get rlocs */
3286   rlocs = build_itr_rloc_list (lcm, loc_set);
3287
3288   if (MR_MODE_SRC_DST == lcm->map_request_mode
3289       && GID_ADDR_SRC_DST != gid_address_type (deid))
3290     {
3291       gid_address_t sd;
3292       memset (&sd, 0, sizeof (sd));
3293       build_src_dst (&sd, seid, deid);
3294       lisp_msg_put_mreq (lcm, b, seid, &sd, rlocs, is_smr_invoked,
3295                          0 /* rloc probe */ , nonce_res);
3296     }
3297   else
3298     {
3299       /* put lisp msg */
3300       lisp_msg_put_mreq (lcm, b, seid, deid, rlocs, is_smr_invoked,
3301                          0 /* rloc probe */ , nonce_res);
3302     }
3303
3304   /* push ecm: udp-ip-lisp */
3305   lisp_msg_push_ecm (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, seid, deid);
3306
3307   /* push outer ip header */
3308   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
3309                        mr_ip);
3310
3311   bi_res[0] = bi;
3312
3313   vec_free (rlocs);
3314   return b;
3315 }
3316
3317 static void
3318 reset_pending_mr_counters (pending_map_request_t * r)
3319 {
3320   r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
3321   r->retries_num = 0;
3322 }
3323
3324 static int
3325 elect_map_resolver (lisp_cp_main_t * lcm)
3326 {
3327   lisp_msmr_t *mr;
3328
3329   vec_foreach (mr, lcm->map_resolvers)
3330   {
3331     if (!mr->is_down)
3332       {
3333         ip_address_copy (&lcm->active_map_resolver, &mr->address);
3334         lcm->do_map_resolver_election = 0;
3335         return 1;
3336       }
3337   }
3338   return 0;
3339 }
3340
3341 static void
3342 free_map_register_records (mapping_t * maps)
3343 {
3344   mapping_t *map;
3345   vec_foreach (map, maps) vec_free (map->locators);
3346
3347   vec_free (maps);
3348 }
3349
3350 static void
3351 add_locators (lisp_cp_main_t * lcm, mapping_t * m, u32 locator_set_index,
3352               ip_address_t * probed_loc)
3353 {
3354   u32 *li;
3355   locator_t *loc, new;
3356   ip_interface_address_t *ia = 0;
3357   void *addr;
3358   ip_address_t *new_ip = &gid_address_ip (&new.address);
3359
3360   m->locators = 0;
3361   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool,
3362                                          locator_set_index);
3363   vec_foreach (li, ls->locator_indices)
3364   {
3365     loc = pool_elt_at_index (lcm->locator_pool, li[0]);
3366     new = loc[0];
3367     if (loc->local)
3368       {
3369           /* *INDENT-OFF* */
3370           foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
3371                                         loc->sw_if_index, 1 /* unnumbered */,
3372           ({
3373             addr = ip_interface_address_get_address (&lcm->im4->lookup_main,
3374                                                      ia);
3375             ip_address_set (new_ip, addr, IP4);
3376           }));
3377
3378           /* Add ipv6 locators */
3379           foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
3380                                         loc->sw_if_index, 1 /* unnumbered */,
3381           ({
3382             addr = ip_interface_address_get_address (&lcm->im6->lookup_main,
3383                                                      ia);
3384             ip_address_set (new_ip, addr, IP6);
3385           }));
3386           /* *INDENT-ON* */
3387
3388         if (probed_loc && ip_address_cmp (probed_loc, new_ip) == 0)
3389           new.probed = 1;
3390       }
3391     vec_add1 (m->locators, new);
3392   }
3393 }
3394
3395 static mapping_t *
3396 build_map_register_record_list (lisp_cp_main_t * lcm)
3397 {
3398   mapping_t *recs = 0, rec, *m;
3399
3400   /* *INDENT-OFF* */
3401   pool_foreach(m, lcm->mapping_pool,
3402   {
3403     /* for now build only local mappings */
3404     if (!m->local)
3405       continue;
3406
3407     rec = m[0];
3408     add_locators (lcm, &rec, m->locator_set_index, NULL);
3409     vec_add1 (recs, rec);
3410   });
3411   /* *INDENT-ON* */
3412
3413   return recs;
3414 }
3415
3416 static int
3417 update_map_register_auth_data (map_register_hdr_t * map_reg_hdr,
3418                                lisp_key_type_t key_id, u8 * key,
3419                                u16 auth_data_len, u32 msg_len)
3420 {
3421   MREG_KEY_ID (map_reg_hdr) = clib_host_to_net_u16 (key_id);
3422   MREG_AUTH_DATA_LEN (map_reg_hdr) = clib_host_to_net_u16 (auth_data_len);
3423
3424   unsigned char *result = HMAC (get_encrypt_fcn (key_id), key, vec_len (key),
3425                                 (unsigned char *) map_reg_hdr, msg_len, NULL,
3426                                 NULL);
3427   clib_memcpy (MREG_DATA (map_reg_hdr), result, auth_data_len);
3428
3429   return 0;
3430 }
3431
3432 static vlib_buffer_t *
3433 build_map_register (lisp_cp_main_t * lcm, ip_address_t * sloc,
3434                     ip_address_t * ms_ip, u64 * nonce_res, u8 want_map_notif,
3435                     mapping_t * records, lisp_key_type_t key_id, u8 * key,
3436                     u32 * bi_res)
3437 {
3438   void *map_reg_hdr;
3439   vlib_buffer_t *b;
3440   u32 bi, auth_data_len = 0, msg_len = 0;
3441   vlib_main_t *vm = lcm->vlib_main;
3442
3443   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
3444     {
3445       clib_warning ("Can't allocate buffer for Map-Register!");
3446       return 0;
3447     }
3448
3449   b = vlib_get_buffer (vm, bi);
3450
3451   /* leave some space for the encap headers */
3452   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
3453
3454   auth_data_len = auth_data_len_by_key_id (key_id);
3455   map_reg_hdr = lisp_msg_put_map_register (b, records, want_map_notif,
3456                                            auth_data_len, nonce_res,
3457                                            &msg_len);
3458
3459   update_map_register_auth_data (map_reg_hdr, key_id, key, auth_data_len,
3460                                  msg_len);
3461
3462   /* push outer ip header */
3463   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
3464                        ms_ip);
3465
3466   bi_res[0] = bi;
3467   return b;
3468 }
3469
3470 static int
3471 get_egress_map_resolver_ip (lisp_cp_main_t * lcm, ip_address_t * ip)
3472 {
3473   lisp_msmr_t *mr;
3474   while (lcm->do_map_resolver_election
3475          | (0 == ip_fib_get_first_egress_ip_for_dst (lcm,
3476                                                      &lcm->active_map_resolver,
3477                                                      ip)))
3478     {
3479       if (0 == elect_map_resolver (lcm))
3480         /* all map resolvers are down */
3481         {
3482           /* restart MR checking by marking all of them up */
3483           vec_foreach (mr, lcm->map_resolvers) mr->is_down = 0;
3484           return -1;
3485         }
3486     }
3487   return 0;
3488 }
3489
3490 static int
3491 send_rloc_probe (lisp_cp_main_t * lcm, gid_address_t * deid,
3492                  u32 local_locator_set_index, ip_address_t * sloc,
3493                  ip_address_t * rloc)
3494 {
3495   locator_set_t *ls;
3496   u32 bi;
3497   vlib_buffer_t *b;
3498   vlib_frame_t *f;
3499   u64 nonce = 0;
3500   u32 next_index, *to_next;
3501   gid_address_t *itr_rlocs;
3502
3503   ls = pool_elt_at_index (lcm->locator_set_pool, local_locator_set_index);
3504   itr_rlocs = build_itr_rloc_list (lcm, ls);
3505
3506   b = build_map_request (lcm, deid, sloc, rloc, itr_rlocs, &nonce, &bi);
3507   vec_free (itr_rlocs);
3508   if (!b)
3509     return -1;
3510
3511   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
3512
3513   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
3514     ip4_lookup_node.index : ip6_lookup_node.index;
3515
3516   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
3517
3518   /* Enqueue the packet */
3519   to_next = vlib_frame_vector_args (f);
3520   to_next[0] = bi;
3521   f->n_vectors = 1;
3522   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
3523
3524   hash_set (lcm->map_register_messages_by_nonce, nonce, 0);
3525   return 0;
3526 }
3527
3528 static int
3529 send_rloc_probes (lisp_cp_main_t * lcm)
3530 {
3531   u8 lprio = 0;
3532   mapping_t *lm;
3533   fwd_entry_t *e;
3534   locator_pair_t *lp;
3535   u32 si;
3536
3537   /* *INDENT-OFF* */
3538   pool_foreach (e, lcm->fwd_entry_pool,
3539   {
3540     if (vec_len (e->locator_pairs) == 0)
3541       continue;
3542
3543     si = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &e->leid);
3544     if (~0 == si)
3545       {
3546         clib_warning ("internal error: cannot find local eid %U in "
3547                       "map-cache!", format_gid_address, &e->leid);
3548         continue;
3549       }
3550     lm = pool_elt_at_index (lcm->mapping_pool, si);
3551
3552     /* get the best (lowest) priority */
3553     lprio = e->locator_pairs[0].priority;
3554
3555     /* send rloc-probe for pair(s) with the best remote locator priority */
3556     vec_foreach (lp, e->locator_pairs)
3557       {
3558         if (lp->priority != lprio)
3559           break;
3560
3561         /* get first remote locator */
3562         send_rloc_probe (lcm, &e->reid, lm->locator_set_index, &lp->lcl_loc,
3563                          &lp->rmt_loc);
3564       }
3565   });
3566   /* *INDENT-ON* */
3567
3568   return 0;
3569 }
3570
3571 static int
3572 send_map_register (lisp_cp_main_t * lcm, u8 want_map_notif)
3573 {
3574   u32 bi;
3575   vlib_buffer_t *b;
3576   ip_address_t sloc;
3577   vlib_frame_t *f;
3578   u64 nonce = 0;
3579   u32 next_index, *to_next;
3580   ip_address_t *ms = 0;
3581   mapping_t *records, *r, *g;
3582
3583   // TODO: support multiple map servers and do election
3584   if (0 == vec_len (lcm->map_servers))
3585     return -1;
3586
3587   ms = &lcm->map_servers[0].address;
3588
3589   if (0 == ip_fib_get_first_egress_ip_for_dst (lcm, ms, &sloc))
3590     {
3591       clib_warning ("no eligible interface address found for %U!",
3592                     format_ip_address, &lcm->map_servers[0]);
3593       return -1;
3594     }
3595
3596   records = build_map_register_record_list (lcm);
3597   if (!records)
3598     return -1;
3599
3600   vec_foreach (r, records)
3601   {
3602     u8 *key = r->key;
3603     u8 key_id = r->key_id;
3604
3605     if (!key)
3606       continue;                 /* no secret key -> map-register cannot be sent */
3607
3608     g = 0;
3609     // TODO: group mappings that share common key
3610     vec_add1 (g, r[0]);
3611     b = build_map_register (lcm, &sloc, ms, &nonce, want_map_notif, g,
3612                             key_id, key, &bi);
3613     vec_free (g);
3614     if (!b)
3615       continue;
3616
3617     vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
3618
3619     next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
3620       ip4_lookup_node.index : ip6_lookup_node.index;
3621
3622     f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
3623
3624     /* Enqueue the packet */
3625     to_next = vlib_frame_vector_args (f);
3626     to_next[0] = bi;
3627     f->n_vectors = 1;
3628     vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
3629
3630     hash_set (lcm->map_register_messages_by_nonce, nonce, 0);
3631   }
3632   free_map_register_records (records);
3633
3634   return 0;
3635 }
3636
3637 #define send_encapsulated_map_request(lcm, seid, deid, smr) \
3638   _send_encapsulated_map_request(lcm, seid, deid, smr, 0)
3639
3640 #define resend_encapsulated_map_request(lcm, seid, deid, smr) \
3641   _send_encapsulated_map_request(lcm, seid, deid, smr, 1)
3642
3643 static int
3644 _send_encapsulated_map_request (lisp_cp_main_t * lcm,
3645                                 gid_address_t * seid, gid_address_t * deid,
3646                                 u8 is_smr_invoked, u8 is_resend)
3647 {
3648   u32 next_index, bi = 0, *to_next, map_index;
3649   vlib_buffer_t *b;
3650   vlib_frame_t *f;
3651   u64 nonce = 0;
3652   locator_set_t *loc_set;
3653   mapping_t *map;
3654   pending_map_request_t *pmr, *duplicate_pmr = 0;
3655   ip_address_t sloc;
3656   u32 ls_index;
3657
3658   /* if there is already a pending request remember it */
3659
3660   /* *INDENT-OFF* */
3661   pool_foreach(pmr, lcm->pending_map_requests_pool,
3662   ({
3663     if (!gid_address_cmp (&pmr->src, seid)
3664         && !gid_address_cmp (&pmr->dst, deid))
3665       {
3666         duplicate_pmr = pmr;
3667         break;
3668       }
3669   }));
3670   /* *INDENT-ON* */
3671
3672   if (!is_resend && duplicate_pmr)
3673     {
3674       /* don't send the request if there is a pending map request already */
3675       return 0;
3676     }
3677
3678   /* get locator-set for seid */
3679   if (!lcm->lisp_pitr)
3680     {
3681       map_index = gid_dictionary_lookup (&lcm->mapping_index_by_gid, seid);
3682       if (map_index == ~0)
3683         {
3684           clib_warning ("No local mapping found in eid-table for %U!",
3685                         format_gid_address, seid);
3686           return -1;
3687         }
3688
3689       map = pool_elt_at_index (lcm->mapping_pool, map_index);
3690
3691       if (!map->local)
3692         {
3693           clib_warning
3694             ("Mapping found for src eid %U is not marked as local!",
3695              format_gid_address, seid);
3696           return -1;
3697         }
3698       ls_index = map->locator_set_index;
3699     }
3700   else
3701     {
3702       map_index = lcm->pitr_map_index;
3703       map = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
3704       ls_index = map->locator_set_index;
3705     }
3706
3707   /* overwrite locator set if map-request itr-rlocs configured */
3708   if (~0 != lcm->mreq_itr_rlocs)
3709     {
3710       ls_index = lcm->mreq_itr_rlocs;
3711     }
3712
3713   loc_set = pool_elt_at_index (lcm->locator_set_pool, ls_index);
3714
3715   if (get_egress_map_resolver_ip (lcm, &sloc) < 0)
3716     {
3717       if (duplicate_pmr)
3718         duplicate_pmr->to_be_removed = 1;
3719       return -1;
3720     }
3721
3722   /* build the encapsulated map request */
3723   b = build_encapsulated_map_request (lcm, seid, deid, loc_set,
3724                                       &lcm->active_map_resolver,
3725                                       &sloc, is_smr_invoked, &nonce, &bi);
3726
3727   if (!b)
3728     return -1;
3729
3730   /* set fib index to default and lookup node */
3731   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
3732   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
3733     ip4_lookup_node.index : ip6_lookup_node.index;
3734
3735   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
3736
3737   /* Enqueue the packet */
3738   to_next = vlib_frame_vector_args (f);
3739   to_next[0] = bi;
3740   f->n_vectors = 1;
3741   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
3742
3743   if (duplicate_pmr)
3744     /* if there is a pending request already update it */
3745     {
3746       if (clib_fifo_elts (duplicate_pmr->nonces) >= PENDING_MREQ_QUEUE_LEN)
3747         {
3748           /* remove the oldest nonce */
3749           u64 CLIB_UNUSED (tmp), *nonce_del;
3750           nonce_del = clib_fifo_head (duplicate_pmr->nonces);
3751           hash_unset (lcm->pending_map_requests_by_nonce, nonce_del[0]);
3752           clib_fifo_sub1 (duplicate_pmr->nonces, tmp);
3753         }
3754
3755       clib_fifo_add1 (duplicate_pmr->nonces, nonce);
3756       hash_set (lcm->pending_map_requests_by_nonce, nonce,
3757                 duplicate_pmr - lcm->pending_map_requests_pool);
3758     }
3759   else
3760     {
3761       /* add map-request to pending requests table */
3762       pool_get (lcm->pending_map_requests_pool, pmr);
3763       memset (pmr, 0, sizeof (*pmr));
3764       gid_address_copy (&pmr->src, seid);
3765       gid_address_copy (&pmr->dst, deid);
3766       clib_fifo_add1 (pmr->nonces, nonce);
3767       pmr->is_smr_invoked = is_smr_invoked;
3768       reset_pending_mr_counters (pmr);
3769       hash_set (lcm->pending_map_requests_by_nonce, nonce,
3770                 pmr - lcm->pending_map_requests_pool);
3771     }
3772
3773   return 0;
3774 }
3775
3776 static void
3777 get_src_and_dst_ip (void *hdr, ip_address_t * src, ip_address_t * dst)
3778 {
3779   ip4_header_t *ip4 = hdr;
3780   ip6_header_t *ip6;
3781
3782   if ((ip4->ip_version_and_header_length & 0xF0) == 0x40)
3783     {
3784       ip_address_set (src, &ip4->src_address, IP4);
3785       ip_address_set (dst, &ip4->dst_address, IP4);
3786     }
3787   else
3788     {
3789       ip6 = hdr;
3790       ip_address_set (src, &ip6->src_address, IP6);
3791       ip_address_set (dst, &ip6->dst_address, IP6);
3792     }
3793 }
3794
3795 static u32
3796 lisp_get_vni_from_buffer_ip (lisp_cp_main_t * lcm, vlib_buffer_t * b,
3797                              u8 version)
3798 {
3799   uword *vnip;
3800   u32 vni = ~0, table_id = ~0;
3801
3802   table_id = fib_table_get_table_id_for_sw_if_index ((version ==
3803                                                       IP4 ? FIB_PROTOCOL_IP4 :
3804                                                       FIB_PROTOCOL_IP6),
3805                                                      vnet_buffer
3806                                                      (b)->sw_if_index
3807                                                      [VLIB_RX]);
3808
3809   vnip = hash_get (lcm->vni_by_table_id, table_id);
3810   if (vnip)
3811     vni = vnip[0];
3812   else
3813     clib_warning ("vrf %d is not mapped to any vni!", table_id);
3814
3815   return vni;
3816 }
3817
3818 always_inline u32
3819 lisp_get_vni_from_buffer_eth (lisp_cp_main_t * lcm, vlib_buffer_t * b)
3820 {
3821   uword *vnip;
3822   u32 vni = ~0;
3823   u32 sw_if_index0;
3824
3825   l2input_main_t *l2im = &l2input_main;
3826   l2_input_config_t *config;
3827   l2_bridge_domain_t *bd_config;
3828
3829   sw_if_index0 = vnet_buffer (b)->sw_if_index[VLIB_RX];
3830   config = vec_elt_at_index (l2im->configs, sw_if_index0);
3831   bd_config = vec_elt_at_index (l2im->bd_configs, config->bd_index);
3832
3833   vnip = hash_get (lcm->vni_by_bd_id, bd_config->bd_id);
3834   if (vnip)
3835     vni = vnip[0];
3836   else
3837     clib_warning ("bridge domain %d is not mapped to any vni!",
3838                   config->bd_index);
3839
3840   return vni;
3841 }
3842
3843 always_inline void
3844 get_src_and_dst_eids_from_buffer (lisp_cp_main_t * lcm, vlib_buffer_t * b,
3845                                   gid_address_t * src, gid_address_t * dst)
3846 {
3847   u32 vni = 0;
3848   u16 type;
3849
3850   memset (src, 0, sizeof (*src));
3851   memset (dst, 0, sizeof (*dst));
3852   type = vnet_buffer (b)->lisp.overlay_afi;
3853
3854   if (LISP_AFI_IP == type || LISP_AFI_IP6 == type)
3855     {
3856       ip4_header_t *ip;
3857       u8 version, preflen;
3858
3859       gid_address_type (src) = GID_ADDR_IP_PREFIX;
3860       gid_address_type (dst) = GID_ADDR_IP_PREFIX;
3861
3862       ip = vlib_buffer_get_current (b);
3863       get_src_and_dst_ip (ip, &gid_address_ip (src), &gid_address_ip (dst));
3864
3865       version = gid_address_ip_version (src);
3866       preflen = ip_address_max_len (version);
3867       gid_address_ippref_len (src) = preflen;
3868       gid_address_ippref_len (dst) = preflen;
3869
3870       vni = lisp_get_vni_from_buffer_ip (lcm, b, version);
3871       gid_address_vni (dst) = vni;
3872       gid_address_vni (src) = vni;
3873     }
3874   else if (LISP_AFI_MAC == type)
3875     {
3876       ethernet_header_t *eh;
3877
3878       eh = vlib_buffer_get_current (b);
3879
3880       gid_address_type (src) = GID_ADDR_MAC;
3881       gid_address_type (dst) = GID_ADDR_MAC;
3882       mac_copy (&gid_address_mac (src), eh->src_address);
3883       mac_copy (&gid_address_mac (dst), eh->dst_address);
3884
3885       /* get vni */
3886       vni = lisp_get_vni_from_buffer_eth (lcm, b);
3887
3888       gid_address_vni (dst) = vni;
3889       gid_address_vni (src) = vni;
3890     }
3891 }
3892
3893 static uword
3894 lisp_cp_lookup_inline (vlib_main_t * vm,
3895                        vlib_node_runtime_t * node,
3896                        vlib_frame_t * from_frame, int overlay)
3897 {
3898   u32 *from, *to_next_drop, di, si;
3899   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3900   u32 pkts_mapped = 0;
3901   uword n_left_from, n_left_to_next_drop;
3902
3903   from = vlib_frame_vector_args (from_frame);
3904   n_left_from = from_frame->n_vectors;
3905
3906   while (n_left_from > 0)
3907     {
3908       vlib_get_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
3909                            to_next_drop, n_left_to_next_drop);
3910
3911       while (n_left_from > 0 && n_left_to_next_drop > 0)
3912         {
3913           u32 pi0;
3914           vlib_buffer_t *b0;
3915           gid_address_t src, dst;
3916
3917           pi0 = from[0];
3918           from += 1;
3919           n_left_from -= 1;
3920           to_next_drop[0] = pi0;
3921           to_next_drop += 1;
3922           n_left_to_next_drop -= 1;
3923
3924           b0 = vlib_get_buffer (vm, pi0);
3925           b0->error = node->errors[LISP_CP_LOOKUP_ERROR_DROP];
3926           vnet_buffer (b0)->lisp.overlay_afi = overlay;
3927
3928           /* src/dst eid pair */
3929           get_src_and_dst_eids_from_buffer (lcm, b0, &src, &dst);
3930
3931           /* if we have remote mapping for destination already in map-chache
3932              add forwarding tunnel directly. If not send a map-request */
3933           di = gid_dictionary_sd_lookup (&lcm->mapping_index_by_gid, &dst,
3934                                          &src);
3935           if (~0 != di)
3936             {
3937               mapping_t *m = vec_elt_at_index (lcm->mapping_pool, di);
3938               /* send a map-request also in case of negative mapping entry
3939                  with corresponding action */
3940               if (m->action == LISP_SEND_MAP_REQUEST)
3941                 {
3942                   /* send map-request */
3943                   queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
3944                                      0 /* is_resend */ );
3945                   pkts_mapped++;
3946                 }
3947               else
3948                 {
3949                   si = gid_dictionary_lookup (&lcm->mapping_index_by_gid,
3950                                               &src);
3951                   if (~0 != si)
3952                     {
3953                       dp_add_fwd_entry (lcm, si, di);
3954                     }
3955                 }
3956             }
3957           else
3958             {
3959               /* send map-request */
3960               queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
3961                                  0 /* is_resend */ );
3962               pkts_mapped++;
3963             }
3964
3965           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
3966             {
3967               lisp_cp_lookup_trace_t *tr = vlib_add_trace (vm, node, b0,
3968                                                            sizeof (*tr));
3969
3970               memset (tr, 0, sizeof (*tr));
3971               gid_address_copy (&tr->dst_eid, &dst);
3972               ip_address_copy (&tr->map_resolver_ip,
3973                                &lcm->active_map_resolver);
3974             }
3975           gid_address_free (&dst);
3976           gid_address_free (&src);
3977         }
3978
3979       vlib_put_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
3980                            n_left_to_next_drop);
3981     }
3982   vlib_node_increment_counter (vm, node->node_index,
3983                                LISP_CP_LOOKUP_ERROR_MAP_REQUESTS_SENT,
3984                                pkts_mapped);
3985   return from_frame->n_vectors;
3986 }
3987
3988 static uword
3989 lisp_cp_lookup_ip4 (vlib_main_t * vm,
3990                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
3991 {
3992   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP));
3993 }
3994
3995 static uword
3996 lisp_cp_lookup_ip6 (vlib_main_t * vm,
3997                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
3998 {
3999   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP6));
4000 }
4001
4002 static uword
4003 lisp_cp_lookup_l2 (vlib_main_t * vm,
4004                    vlib_node_runtime_t * node, vlib_frame_t * from_frame)
4005 {
4006   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_MAC));
4007 }
4008
4009 /* *INDENT-OFF* */
4010 VLIB_REGISTER_NODE (lisp_cp_lookup_ip4_node) = {
4011   .function = lisp_cp_lookup_ip4,
4012   .name = "lisp-cp-lookup-ip4",
4013   .vector_size = sizeof (u32),
4014   .format_trace = format_lisp_cp_lookup_trace,
4015   .type = VLIB_NODE_TYPE_INTERNAL,
4016
4017   .n_errors = LISP_CP_LOOKUP_N_ERROR,
4018   .error_strings = lisp_cp_lookup_error_strings,
4019
4020   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
4021
4022   .next_nodes = {
4023       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
4024   },
4025 };
4026 /* *INDENT-ON* */
4027
4028 /* *INDENT-OFF* */
4029 VLIB_REGISTER_NODE (lisp_cp_lookup_ip6_node) = {
4030   .function = lisp_cp_lookup_ip6,
4031   .name = "lisp-cp-lookup-ip6",
4032   .vector_size = sizeof (u32),
4033   .format_trace = format_lisp_cp_lookup_trace,
4034   .type = VLIB_NODE_TYPE_INTERNAL,
4035
4036   .n_errors = LISP_CP_LOOKUP_N_ERROR,
4037   .error_strings = lisp_cp_lookup_error_strings,
4038
4039   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
4040
4041   .next_nodes = {
4042       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
4043   },
4044 };
4045 /* *INDENT-ON* */
4046
4047 /* *INDENT-OFF* */
4048 VLIB_REGISTER_NODE (lisp_cp_lookup_l2_node) = {
4049   .function = lisp_cp_lookup_l2,
4050   .name = "lisp-cp-lookup-l2",
4051   .vector_size = sizeof (u32),
4052   .format_trace = format_lisp_cp_lookup_trace,
4053   .type = VLIB_NODE_TYPE_INTERNAL,
4054
4055   .n_errors = LISP_CP_LOOKUP_N_ERROR,
4056   .error_strings = lisp_cp_lookup_error_strings,
4057
4058   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
4059
4060   .next_nodes = {
4061       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
4062   },
4063 };
4064 /* *INDENT-ON* */
4065
4066 /* lisp_cp_input statistics */
4067 #define foreach_lisp_cp_input_error                     \
4068 _(DROP, "drop")                                         \
4069 _(MAP_REPLIES_RECEIVED, "map-replies received")
4070
4071 static char *lisp_cp_input_error_strings[] = {
4072 #define _(sym,string) string,
4073   foreach_lisp_cp_input_error
4074 #undef _
4075 };
4076
4077 typedef enum
4078 {
4079 #define _(sym,str) LISP_CP_INPUT_ERROR_##sym,
4080   foreach_lisp_cp_input_error
4081 #undef _
4082     LISP_CP_INPUT_N_ERROR,
4083 } lisp_cp_input_error_t;
4084
4085 typedef enum
4086 {
4087   LISP_CP_INPUT_NEXT_DROP,
4088   LISP_CP_INPUT_N_NEXT,
4089 } lisp_cp_input_next_t;
4090
4091 typedef struct
4092 {
4093   gid_address_t dst_eid;
4094   ip4_address_t map_resolver_ip;
4095 } lisp_cp_input_trace_t;
4096
4097 u8 *
4098 format_lisp_cp_input_trace (u8 * s, va_list * args)
4099 {
4100   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
4101   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
4102   CLIB_UNUSED (lisp_cp_input_trace_t * t) =
4103     va_arg (*args, lisp_cp_input_trace_t *);
4104
4105   s = format (s, "LISP-CP-INPUT: TODO");
4106   return s;
4107 }
4108
4109 static void
4110 remove_expired_mapping (lisp_cp_main_t * lcm, u32 mi)
4111 {
4112   mapping_t *m;
4113
4114   m = pool_elt_at_index (lcm->mapping_pool, mi);
4115   lisp_add_del_adjacency (lcm, 0, &m->eid, 0 /* is_add */ );
4116   vnet_lisp_add_del_mapping (&m->eid, 0, 0, 0, ~0, 0 /* is_add */ ,
4117                              0 /* is_static */ , 0);
4118   mapping_delete_timer (lcm, mi);
4119 }
4120
4121 static void
4122 mapping_start_expiration_timer (lisp_cp_main_t * lcm, u32 mi,
4123                                 f64 expiration_time)
4124 {
4125   mapping_t *m;
4126   u64 now = clib_cpu_time_now ();
4127   u64 cpu_cps = lcm->vlib_main->clib_time.clocks_per_second;
4128   u64 exp_clock_time = now + expiration_time * cpu_cps;
4129
4130   m = pool_elt_at_index (lcm->mapping_pool, mi);
4131
4132   m->timer_set = 1;
4133   timing_wheel_insert (&lcm->wheel, exp_clock_time, mi);
4134 }
4135
4136 static void
4137 map_records_arg_free (map_records_arg_t * a)
4138 {
4139   mapping_t *m;
4140   vec_foreach (m, a->mappings)
4141   {
4142     vec_free (m->locators);
4143     gid_address_free (&m->eid);
4144   }
4145
4146   clib_mem_free (a);
4147 }
4148
4149 void *
4150 process_map_reply (map_records_arg_t * a)
4151 {
4152   mapping_t *m;
4153   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4154   u32 dst_map_index = 0;
4155   pending_map_request_t *pmr;
4156   u64 *noncep;
4157   uword *pmr_index;
4158
4159   if (a->is_rloc_probe)
4160     goto done;
4161
4162   /* Check pending requests table and nonce */
4163   pmr_index = hash_get (lcm->pending_map_requests_by_nonce, a->nonce);
4164   if (!pmr_index)
4165     {
4166       clib_warning ("No pending map-request entry with nonce %lu!", a->nonce);
4167       goto done;
4168     }
4169   pmr = pool_elt_at_index (lcm->pending_map_requests_pool, pmr_index[0]);
4170
4171   vec_foreach (m, a->mappings)
4172   {
4173     /* insert/update mappings cache */
4174     vnet_lisp_add_del_mapping (&m->eid, m->locators, m->action,
4175                                m->authoritative, m->ttl,
4176                                1, 0 /* is_static */ , &dst_map_index);
4177
4178     /* try to program forwarding only if mapping saved or updated */
4179     if ((u32) ~ 0 != dst_map_index)
4180       {
4181         lisp_add_del_adjacency (lcm, &pmr->src, &m->eid, 1);
4182         if ((u32) ~ 0 != m->ttl)
4183           mapping_start_expiration_timer (lcm, dst_map_index, m->ttl * 60);
4184       }
4185   }
4186
4187   /* remove pending map request entry */
4188
4189   /* *INDENT-OFF* */
4190   clib_fifo_foreach (noncep, pmr->nonces, ({
4191     hash_unset(lcm->pending_map_requests_by_nonce, noncep[0]);
4192   }));
4193   /* *INDENT-ON* */
4194
4195   clib_fifo_free (pmr->nonces);
4196   pool_put (lcm->pending_map_requests_pool, pmr);
4197
4198 done:
4199   map_records_arg_free (a);
4200   return 0;
4201 }
4202
4203 static int
4204 is_auth_data_valid (map_notify_hdr_t * h, u32 msg_len,
4205                     lisp_key_type_t key_id, u8 * key)
4206 {
4207   u8 *auth_data = 0;
4208   u16 auth_data_len;
4209   int result;
4210
4211   auth_data_len = auth_data_len_by_key_id (key_id);
4212   if ((u16) ~ 0 == auth_data_len)
4213     {
4214       clib_warning ("invalid length for key_id %d!", key_id);
4215       return 0;
4216     }
4217
4218   /* save auth data */
4219   vec_validate (auth_data, auth_data_len - 1);
4220   clib_memcpy (auth_data, MNOTIFY_DATA (h), auth_data_len);
4221
4222   /* clear auth data */
4223   memset (MNOTIFY_DATA (h), 0, auth_data_len);
4224
4225   /* get hash of the message */
4226   unsigned char *code = HMAC (get_encrypt_fcn (key_id), key, vec_len (key),
4227                               (unsigned char *) h, msg_len, NULL, NULL);
4228
4229   result = memcmp (code, auth_data, auth_data_len);
4230
4231   vec_free (auth_data);
4232
4233   return !result;
4234 }
4235
4236 static void
4237 process_map_notify (map_records_arg_t * a)
4238 {
4239   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4240   uword *pmr_index;
4241
4242   pmr_index = hash_get (lcm->map_register_messages_by_nonce, a->nonce);
4243   if (!pmr_index)
4244     {
4245       clib_warning ("No pending map-register entry with nonce %lu!",
4246                     a->nonce);
4247       return;
4248     }
4249
4250   map_records_arg_free (a);
4251   hash_unset (lcm->map_register_messages_by_nonce, a->nonce);
4252 }
4253
4254 static mapping_t *
4255 get_mapping (lisp_cp_main_t * lcm, gid_address_t * e)
4256 {
4257   u32 mi;
4258
4259   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, e);
4260   if (~0 == mi)
4261     {
4262       clib_warning ("eid %U not found in map-cache!", unformat_gid_address,
4263                     e);
4264       return 0;
4265     }
4266   return pool_elt_at_index (lcm->mapping_pool, mi);
4267 }
4268
4269 /**
4270  * When map-notify is received it is necessary that all EIDs in the record
4271  * list share common key. The key is then used to verify authentication
4272  * data in map-notify message.
4273  */
4274 static int
4275 map_record_integrity_check (lisp_cp_main_t * lcm, mapping_t * maps,
4276                             u32 key_id, u8 ** key_out)
4277 {
4278   u32 i, len = vec_len (maps);
4279   mapping_t *m;
4280
4281   /* get key of the first mapping */
4282   m = get_mapping (lcm, &maps[0].eid);
4283   if (!m || !m->key)
4284     return -1;
4285
4286   key_out[0] = m->key;
4287
4288   for (i = 1; i < len; i++)
4289     {
4290       m = get_mapping (lcm, &maps[i].eid);
4291       if (!m || !m->key)
4292         return -1;
4293
4294       if (key_id != m->key_id || vec_cmp (m->key, key_out[0]))
4295         {
4296           clib_warning ("keys does not match! %v, %v", key_out[0], m->key);
4297           return -1;
4298         }
4299     }
4300   return 0;
4301 }
4302
4303 static int
4304 parse_map_records (vlib_buffer_t * b, map_records_arg_t * a, u8 count)
4305 {
4306   locator_t *locators = 0;
4307   u32 i, len;
4308   gid_address_t deid;
4309   mapping_t m;
4310   locator_t *loc;
4311
4312   /* parse record eid */
4313   for (i = 0; i < count; i++)
4314     {
4315       len = lisp_msg_parse_mapping_record (b, &deid, &locators, NULL);
4316       if (len == ~0)
4317         {
4318           clib_warning ("Failed to parse mapping record!");
4319           vec_foreach (loc, locators) locator_free (loc);
4320           vec_free (locators);
4321           return -1;
4322         }
4323
4324       m.locators = locators;
4325       gid_address_copy (&m.eid, &deid);
4326       vec_add1 (a->mappings, m);
4327     }
4328
4329   return 0;
4330 }
4331
4332 static map_records_arg_t *
4333 parse_map_notify (vlib_buffer_t * b)
4334 {
4335   int rc = 0;
4336   map_notify_hdr_t *mnotif_hdr;
4337   lisp_key_type_t key_id;
4338   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4339   u8 *key = 0;
4340   gid_address_t deid;
4341   u16 auth_data_len = 0;
4342   u8 record_count;
4343   map_records_arg_t *a = clib_mem_alloc (sizeof (*a));
4344
4345   memset (a, 0, sizeof (*a));
4346   mnotif_hdr = vlib_buffer_get_current (b);
4347   vlib_buffer_pull (b, sizeof (*mnotif_hdr));
4348   memset (&deid, 0, sizeof (deid));
4349
4350   a->nonce = MNOTIFY_NONCE (mnotif_hdr);
4351   key_id = clib_net_to_host_u16 (MNOTIFY_KEY_ID (mnotif_hdr));
4352   auth_data_len = auth_data_len_by_key_id (key_id);
4353
4354   /* advance buffer by authentication data */
4355   vlib_buffer_pull (b, auth_data_len);
4356
4357   record_count = MNOTIFY_REC_COUNT (mnotif_hdr);
4358   rc = parse_map_records (b, a, record_count);
4359   if (rc != 0)
4360     {
4361       map_records_arg_free (a);
4362       return 0;
4363     }
4364
4365   rc = map_record_integrity_check (lcm, a->mappings, key_id, &key);
4366   if (rc != 0)
4367     {
4368       map_records_arg_free (a);
4369       return 0;
4370     }
4371
4372   /* verify authentication data */
4373   if (!is_auth_data_valid (mnotif_hdr, vlib_buffer_get_tail (b)
4374                            - (u8 *) mnotif_hdr, key_id, key))
4375     {
4376       clib_warning ("Map-notify auth data verification failed for nonce %lu!",
4377                     a->nonce);
4378       map_records_arg_free (a);
4379       return 0;
4380     }
4381   return a;
4382 }
4383
4384 static vlib_buffer_t *
4385 build_map_reply (lisp_cp_main_t * lcm, ip_address_t * sloc,
4386                  ip_address_t * dst, u64 nonce, u8 probe_bit,
4387                  mapping_t * records, u16 dst_port, u32 * bi_res)
4388 {
4389   vlib_buffer_t *b;
4390   u32 bi;
4391   vlib_main_t *vm = lcm->vlib_main;
4392
4393   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
4394     {
4395       clib_warning ("Can't allocate buffer for Map-Register!");
4396       return 0;
4397     }
4398
4399   b = vlib_get_buffer (vm, bi);
4400
4401   /* leave some space for the encap headers */
4402   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
4403
4404   lisp_msg_put_map_reply (b, records, nonce, probe_bit);
4405
4406   /* push outer ip header */
4407   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, dst_port, sloc, dst);
4408
4409   bi_res[0] = bi;
4410   return b;
4411 }
4412
4413 static int
4414 send_map_reply (lisp_cp_main_t * lcm, u32 mi, ip_address_t * dst,
4415                 u8 probe_bit, u64 nonce, u16 dst_port,
4416                 ip_address_t * probed_loc)
4417 {
4418   ip_address_t src;
4419   u32 bi;
4420   vlib_buffer_t *b;
4421   vlib_frame_t *f;
4422   u32 next_index, *to_next;
4423   mapping_t *records = 0, *m;
4424
4425   m = pool_elt_at_index (lcm->mapping_pool, mi);
4426   if (!m)
4427     return -1;
4428
4429   vec_add1 (records, m[0]);
4430   add_locators (lcm, &records[0], m->locator_set_index, probed_loc);
4431   memset (&src, 0, sizeof (src));
4432
4433   if (!ip_fib_get_first_egress_ip_for_dst (lcm, dst, &src))
4434     {
4435       clib_warning ("can't find inteface address for %U", format_ip_address,
4436                     dst);
4437       return -1;
4438     }
4439
4440   b = build_map_reply (lcm, &src, dst, nonce, probe_bit, records, dst_port,
4441                        &bi);
4442   if (!b)
4443     return -1;
4444   free_map_register_records (records);
4445
4446   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
4447   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
4448     ip4_lookup_node.index : ip6_lookup_node.index;
4449
4450   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
4451
4452   /* Enqueue the packet */
4453   to_next = vlib_frame_vector_args (f);
4454   to_next[0] = bi;
4455   f->n_vectors = 1;
4456   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
4457   return 0;
4458 }
4459
4460 void
4461 process_map_request (vlib_main_t * vm, lisp_cp_main_t * lcm,
4462                      vlib_buffer_t * b)
4463 {
4464   u8 *ip_hdr = 0, *udp_hdr;
4465   ip4_header_t *ip4;
4466   ip6_header_t *ip6;
4467   ip_address_t *dst_loc = 0, probed_loc, src_loc;
4468   mapping_t m;
4469   map_request_hdr_t *mreq_hdr;
4470   gid_address_t src, dst;
4471   u64 nonce;
4472   u32 i, len = 0;
4473   gid_address_t *itr_rlocs = 0;
4474
4475   mreq_hdr = vlib_buffer_get_current (b);
4476
4477   // TODO ugly workaround to find out whether LISP is carried by ip4 or 6
4478   // and needs to be fixed
4479   udp_hdr = (u8 *) vlib_buffer_get_current (b) - sizeof (udp_header_t);
4480   ip4 = (ip4_header_t *) (udp_hdr - sizeof (ip4_header_t));
4481   ip6 = (ip6_header_t *) (udp_hdr - sizeof (ip6_header_t));
4482
4483   if ((ip4->ip_version_and_header_length & 0xF0) == 0x40)
4484     ip_hdr = (u8 *) ip4;
4485   else
4486     {
4487       u32 flags = clib_net_to_host_u32
4488         (ip6->ip_version_traffic_class_and_flow_label);
4489       if ((flags & 0xF0000000) == 0x60000000)
4490         ip_hdr = (u8 *) ip6;
4491       else
4492         {
4493           clib_warning ("internal error: cannot determine whether packet "
4494                         "is ip4 or 6!");
4495           return;
4496         }
4497     }
4498
4499   vlib_buffer_pull (b, sizeof (*mreq_hdr));
4500
4501   nonce = MREQ_NONCE (mreq_hdr);
4502
4503   if (!MREQ_SMR (mreq_hdr) && !MREQ_RLOC_PROBE (mreq_hdr))
4504     {
4505       clib_warning
4506         ("Only SMR Map-Requests and RLOC probe supported for now!");
4507       return;
4508     }
4509
4510   /* parse src eid */
4511   len = lisp_msg_parse_addr (b, &src);
4512   if (len == ~0)
4513     return;
4514
4515   len = lisp_msg_parse_itr_rlocs (b, &itr_rlocs,
4516                                   MREQ_ITR_RLOC_COUNT (mreq_hdr) + 1);
4517   if (len == ~0)
4518     return;
4519
4520   /* parse eid records and send SMR-invoked map-requests */
4521   for (i = 0; i < MREQ_REC_COUNT (mreq_hdr); i++)
4522     {
4523       memset (&dst, 0, sizeof (dst));
4524       len = lisp_msg_parse_eid_rec (b, &dst);
4525       if (len == ~0)
4526         {
4527           clib_warning ("Can't parse map-request EID-record");
4528           goto done;
4529         }
4530
4531       if (MREQ_SMR (mreq_hdr))
4532         {
4533           /* send SMR-invoked map-requests */
4534           queue_map_request (&dst, &src, 1 /* invoked */ , 0 /* resend */ );
4535         }
4536       else if (MREQ_RLOC_PROBE (mreq_hdr))
4537         {
4538           memset (&m, 0, sizeof (m));
4539           u32 mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &dst);
4540
4541           // TODO: select best locator; for now use the first one
4542           dst_loc = &gid_address_ip (&itr_rlocs[0]);
4543
4544           /* get src/dst IP addresses */
4545           get_src_and_dst_ip (ip_hdr, &src_loc, &probed_loc);
4546
4547           // TODO get source port from buffer
4548           u16 src_port = LISP_CONTROL_PORT;
4549
4550           send_map_reply (lcm, mi, dst_loc, 1 /* probe-bit */ , nonce,
4551                           src_port, &probed_loc);
4552         }
4553     }
4554
4555 done:
4556   vec_free (itr_rlocs);
4557 }
4558
4559 static map_records_arg_t *
4560 parse_map_reply (vlib_buffer_t * b)
4561 {
4562   locator_t probed;
4563   gid_address_t deid;
4564   void *h;
4565   u32 i, len = 0;
4566   mapping_t m;
4567   map_reply_hdr_t *mrep_hdr;
4568   map_records_arg_t *a = clib_mem_alloc (sizeof (*a));
4569   memset (a, 0, sizeof (*a));
4570   locator_t *locators;
4571
4572   mrep_hdr = vlib_buffer_get_current (b);
4573   a->nonce = MREP_NONCE (mrep_hdr);
4574   a->is_rloc_probe = MREP_RLOC_PROBE (mrep_hdr);
4575   vlib_buffer_pull (b, sizeof (*mrep_hdr));
4576
4577   for (i = 0; i < MREP_REC_COUNT (mrep_hdr); i++)
4578     {
4579       memset (&m, 0, sizeof (m));
4580       locators = 0;
4581       h = vlib_buffer_get_current (b);
4582
4583       m.ttl = clib_net_to_host_u32 (MAP_REC_TTL (h));
4584       m.action = MAP_REC_ACTION (h);
4585       m.authoritative = MAP_REC_AUTH (h);
4586
4587       len = lisp_msg_parse_mapping_record (b, &deid, &locators, &probed);
4588       if (len == ~0)
4589         {
4590           clib_warning ("Failed to parse mapping record!");
4591           map_records_arg_free (a);
4592           return 0;
4593         }
4594
4595       m.locators = locators;
4596       gid_address_copy (&m.eid, &deid);
4597       vec_add1 (a->mappings, m);
4598     }
4599   return a;
4600 }
4601
4602 static void
4603 queue_map_reply_for_processing (map_records_arg_t * a)
4604 {
4605   vl_api_rpc_call_main_thread (process_map_reply, (u8 *) a, sizeof (a));
4606 }
4607
4608 static void
4609 queue_map_notify_for_processing (map_records_arg_t * a)
4610 {
4611   vl_api_rpc_call_main_thread (process_map_notify, (u8 *) a, sizeof (a[0]));
4612 }
4613
4614 static uword
4615 lisp_cp_input (vlib_main_t * vm, vlib_node_runtime_t * node,
4616                vlib_frame_t * from_frame)
4617 {
4618   u32 n_left_from, *from, *to_next_drop;
4619   lisp_msg_type_e type;
4620   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4621   map_records_arg_t *a;
4622
4623   from = vlib_frame_vector_args (from_frame);
4624   n_left_from = from_frame->n_vectors;
4625
4626
4627   while (n_left_from > 0)
4628     {
4629       u32 n_left_to_next_drop;
4630
4631       vlib_get_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
4632                            to_next_drop, n_left_to_next_drop);
4633       while (n_left_from > 0 && n_left_to_next_drop > 0)
4634         {
4635           u32 bi0;
4636           vlib_buffer_t *b0;
4637
4638           bi0 = from[0];
4639           from += 1;
4640           n_left_from -= 1;
4641           to_next_drop[0] = bi0;
4642           to_next_drop += 1;
4643           n_left_to_next_drop -= 1;
4644
4645           b0 = vlib_get_buffer (vm, bi0);
4646
4647           type = lisp_msg_type (vlib_buffer_get_current (b0));
4648           switch (type)
4649             {
4650             case LISP_MAP_REPLY:
4651               a = parse_map_reply (b0);
4652               if (a)
4653                 queue_map_reply_for_processing (a);
4654               break;
4655             case LISP_MAP_REQUEST:
4656               process_map_request (vm, lcm, b0);
4657               break;
4658             case LISP_MAP_NOTIFY:
4659               a = parse_map_notify (b0);
4660               if (a)
4661                 queue_map_notify_for_processing (a);
4662               break;
4663             default:
4664               clib_warning ("Unsupported LISP message type %d", type);
4665               break;
4666             }
4667
4668           b0->error = node->errors[LISP_CP_INPUT_ERROR_DROP];
4669
4670           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
4671             {
4672
4673             }
4674         }
4675
4676       vlib_put_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
4677                            n_left_to_next_drop);
4678     }
4679   return from_frame->n_vectors;
4680 }
4681
4682 /* *INDENT-OFF* */
4683 VLIB_REGISTER_NODE (lisp_cp_input_node) = {
4684   .function = lisp_cp_input,
4685   .name = "lisp-cp-input",
4686   .vector_size = sizeof (u32),
4687   .format_trace = format_lisp_cp_input_trace,
4688   .type = VLIB_NODE_TYPE_INTERNAL,
4689
4690   .n_errors = LISP_CP_INPUT_N_ERROR,
4691   .error_strings = lisp_cp_input_error_strings,
4692
4693   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
4694
4695   .next_nodes = {
4696       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
4697   },
4698 };
4699 /* *INDENT-ON* */
4700
4701 clib_error_t *
4702 lisp_cp_init (vlib_main_t * vm)
4703 {
4704   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4705   clib_error_t *error = 0;
4706
4707   if ((error = vlib_call_init_function (vm, lisp_gpe_init)))
4708     return error;
4709
4710   lcm->im4 = &ip4_main;
4711   lcm->im6 = &ip6_main;
4712   lcm->vlib_main = vm;
4713   lcm->vnet_main = vnet_get_main ();
4714   lcm->mreq_itr_rlocs = ~0;
4715   lcm->lisp_pitr = 0;
4716   memset (&lcm->active_map_resolver, 0, sizeof (lcm->active_map_resolver));
4717
4718   gid_dictionary_init (&lcm->mapping_index_by_gid);
4719   lcm->do_map_resolver_election = 1;
4720   lcm->map_request_mode = MR_MODE_DST_ONLY;
4721
4722   /* default vrf mapped to vni 0 */
4723   hash_set (lcm->table_id_by_vni, 0, 0);
4724   hash_set (lcm->vni_by_table_id, 0, 0);
4725
4726   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp,
4727                          lisp_cp_input_node.index, 1 /* is_ip4 */ );
4728   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp6,
4729                          lisp_cp_input_node.index, 0 /* is_ip4 */ );
4730
4731   u64 now = clib_cpu_time_now ();
4732   timing_wheel_init (&lcm->wheel, now, vm->clib_time.clocks_per_second);
4733   return 0;
4734 }
4735
4736 static void *
4737 send_map_request_thread_fn (void *arg)
4738 {
4739   map_request_args_t *a = arg;
4740   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4741
4742   if (a->is_resend)
4743     resend_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
4744   else
4745     send_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
4746
4747   return 0;
4748 }
4749
4750 static int
4751 queue_map_request (gid_address_t * seid, gid_address_t * deid,
4752                    u8 smr_invoked, u8 is_resend)
4753 {
4754   map_request_args_t a;
4755
4756   a.is_resend = is_resend;
4757   gid_address_copy (&a.seid, seid);
4758   gid_address_copy (&a.deid, deid);
4759   a.smr_invoked = smr_invoked;
4760
4761   vl_api_rpc_call_main_thread (send_map_request_thread_fn,
4762                                (u8 *) & a, sizeof (a));
4763   return 0;
4764 }
4765
4766 /**
4767  * Take an action with a pending map request depending on expiration time
4768  * and re-try counters.
4769  */
4770 static void
4771 update_pending_request (pending_map_request_t * r, f64 dt)
4772 {
4773   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4774   lisp_msmr_t *mr;
4775
4776   if (r->time_to_expire - dt < 0)
4777     /* it's time to decide what to do with this pending request */
4778     {
4779       if (r->retries_num >= NUMBER_OF_RETRIES)
4780         /* too many retries -> assume current map resolver is not available */
4781         {
4782           mr = get_map_resolver (&lcm->active_map_resolver);
4783           if (!mr)
4784             {
4785               clib_warning ("Map resolver %U not found - probably deleted "
4786                             "by the user recently.", format_ip_address,
4787                             &lcm->active_map_resolver);
4788             }
4789           else
4790             {
4791               clib_warning ("map resolver %U is unreachable, ignoring",
4792                             format_ip_address, &lcm->active_map_resolver);
4793
4794               /* mark current map resolver unavailable so it won't be
4795                * selected next time */
4796               mr->is_down = 1;
4797               mr->last_update = vlib_time_now (lcm->vlib_main);
4798             }
4799
4800           reset_pending_mr_counters (r);
4801           elect_map_resolver (lcm);
4802
4803           /* try to find a next eligible map resolver and re-send */
4804           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
4805                              1 /* resend */ );
4806         }
4807       else
4808         {
4809           /* try again */
4810           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
4811                              1 /* resend */ );
4812           r->retries_num++;
4813           r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
4814         }
4815     }
4816   else
4817     r->time_to_expire -= dt;
4818 }
4819
4820 static void
4821 remove_dead_pending_map_requests (lisp_cp_main_t * lcm)
4822 {
4823   u64 *nonce;
4824   pending_map_request_t *pmr;
4825   u32 *to_be_removed = 0, *pmr_index;
4826
4827   /* *INDENT-OFF* */
4828   pool_foreach (pmr, lcm->pending_map_requests_pool,
4829   ({
4830     if (pmr->to_be_removed)
4831       {
4832         clib_fifo_foreach (nonce, pmr->nonces, ({
4833           hash_unset (lcm->pending_map_requests_by_nonce, nonce[0]);
4834         }));
4835
4836         vec_add1 (to_be_removed, pmr - lcm->pending_map_requests_pool);
4837       }
4838   }));
4839   /* *INDENT-ON* */
4840
4841   vec_foreach (pmr_index, to_be_removed)
4842     pool_put_index (lcm->pending_map_requests_by_nonce, pmr_index[0]);
4843
4844   vec_free (to_be_removed);
4845 }
4846
4847 static void
4848 update_rloc_probing (lisp_cp_main_t * lcm, f64 dt)
4849 {
4850   static f64 time_left = RLOC_PROBING_INTERVAL;
4851
4852   if (!lcm->is_enabled || !lcm->rloc_probing)
4853     return;
4854
4855   time_left -= dt;
4856   if (time_left <= 0)
4857     {
4858       time_left = RLOC_PROBING_INTERVAL;
4859       send_rloc_probes (lcm);
4860     }
4861 }
4862
4863 static void
4864 update_map_register (lisp_cp_main_t * lcm, f64 dt)
4865 {
4866   static f64 time_left = QUICK_MAP_REGISTER_INTERVAL;
4867   static u64 mreg_sent_counter = 0;
4868
4869   if (!lcm->is_enabled || !lcm->map_registering)
4870     return;
4871
4872   time_left -= dt;
4873   if (time_left <= 0)
4874     {
4875       if (mreg_sent_counter >= QUICK_MAP_REGISTER_MSG_COUNT)
4876         time_left = MAP_REGISTER_INTERVAL;
4877       else
4878         {
4879           mreg_sent_counter++;
4880           time_left = QUICK_MAP_REGISTER_INTERVAL;
4881         }
4882       send_map_register (lcm, 1 /* want map notify */ );
4883     }
4884 }
4885
4886 static uword
4887 send_map_resolver_service (vlib_main_t * vm,
4888                            vlib_node_runtime_t * rt, vlib_frame_t * f)
4889 {
4890   u32 *expired = 0;
4891   f64 period = 2.0;
4892   pending_map_request_t *pmr;
4893   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4894
4895   while (1)
4896     {
4897       vlib_process_wait_for_event_or_clock (vm, period);
4898
4899       /* currently no signals are expected - just wait for clock */
4900       (void) vlib_process_get_events (vm, 0);
4901
4902       /* *INDENT-OFF* */
4903       pool_foreach (pmr, lcm->pending_map_requests_pool,
4904       ({
4905         if (!pmr->to_be_removed)
4906           update_pending_request (pmr, period);
4907       }));
4908       /* *INDENT-ON* */
4909
4910       remove_dead_pending_map_requests (lcm);
4911
4912       update_map_register (lcm, period);
4913       update_rloc_probing (lcm, period);
4914
4915       u64 now = clib_cpu_time_now ();
4916
4917       expired = timing_wheel_advance (&lcm->wheel, now, expired, 0);
4918       if (vec_len (expired) > 0)
4919         {
4920           u32 *mi = 0;
4921           vec_foreach (mi, expired)
4922           {
4923             remove_expired_mapping (lcm, mi[0]);
4924           }
4925           _vec_len (expired) = 0;
4926         }
4927     }
4928
4929   /* unreachable */
4930   return 0;
4931 }
4932
4933 /* *INDENT-OFF* */
4934 VLIB_REGISTER_NODE (lisp_retry_service_node,static) = {
4935     .function = send_map_resolver_service,
4936     .type = VLIB_NODE_TYPE_PROCESS,
4937     .name = "lisp-retry-service",
4938     .process_log2_n_stack_bytes = 16,
4939 };
4940 /* *INDENT-ON* */
4941
4942 VLIB_INIT_FUNCTION (lisp_cp_init);
4943
4944 /*
4945  * fd.io coding-style-patch-verification: ON
4946  *
4947  * Local Variables:
4948  * eval: (c-set-style "gnu")
4949  * End:
4950  */