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