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