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