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