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