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