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