Add option to use LISP Proxy-ETR
[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
1325       ls_args->is_add = 1;
1326       ls_args->index = ~0;
1327       vec_add1 (ls_args->locators, loc);
1328       vnet_lisp_add_del_locator_set (ls_args, &ls_index);
1329
1330       /* Add petr mapping */
1331       pool_get (lcm->mapping_pool, m);
1332       m->locator_set_index = ls_index;
1333       lcm->petr_map_index = m - lcm->mapping_pool;
1334
1335       /* Enable use-petr */
1336       lcm->flags |= LISP_FLAG_USE_PETR;
1337     }
1338   else
1339     {
1340       m = pool_elt_at_index (lcm->mapping_pool, lcm->petr_map_index);
1341
1342       /* Remove petr locator */
1343       ls_args->is_add = 0;
1344       ls_args->index = m->locator_set_index;
1345       vnet_lisp_add_del_locator_set (ls_args, 0);
1346
1347       /* Remove petr mapping */
1348       pool_put_index (lcm->mapping_pool, lcm->petr_map_index);
1349
1350       /* Disable use-petr */
1351       lcm->flags &= ~LISP_FLAG_USE_PETR;
1352     }
1353   return 0;
1354 }
1355
1356 /* cleans locator to locator-set data and removes locators not part of
1357  * any locator-set */
1358 static void
1359 clean_locator_to_locator_set (lisp_cp_main_t * lcm, u32 lsi)
1360 {
1361   u32 i, j, *loc_indexp, *ls_indexp, **ls_indexes, *to_be_deleted = 0;
1362   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool, lsi);
1363   for (i = 0; i < vec_len (ls->locator_indices); i++)
1364     {
1365       loc_indexp = vec_elt_at_index (ls->locator_indices, i);
1366       ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
1367                                      loc_indexp[0]);
1368       for (j = 0; j < vec_len (ls_indexes[0]); j++)
1369         {
1370           ls_indexp = vec_elt_at_index (ls_indexes[0], j);
1371           if (ls_indexp[0] == lsi)
1372             break;
1373         }
1374
1375       /* delete index for removed locator-set */
1376       vec_del1 (ls_indexes[0], j);
1377
1378       /* delete locator if it's part of no locator-set */
1379       if (vec_len (ls_indexes[0]) == 0)
1380         {
1381           pool_put_index (lcm->locator_pool, loc_indexp[0]);
1382           vec_add1 (to_be_deleted, i);
1383         }
1384     }
1385
1386   if (to_be_deleted)
1387     {
1388       for (i = 0; i < vec_len (to_be_deleted); i++)
1389         {
1390           loc_indexp = vec_elt_at_index (to_be_deleted, i);
1391           vec_del1 (ls->locator_indices, loc_indexp[0]);
1392         }
1393       vec_free (to_be_deleted);
1394     }
1395 }
1396
1397 static inline uword *
1398 get_locator_set_index (vnet_lisp_add_del_locator_set_args_t * a, uword * p)
1399 {
1400   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1401
1402   ASSERT (a != NULL);
1403   ASSERT (p != NULL);
1404
1405   /* find locator-set */
1406   if (a->local)
1407     {
1408       p = hash_get_mem (lcm->locator_set_index_by_name, a->name);
1409     }
1410   else
1411     {
1412       *p = a->index;
1413     }
1414
1415   return p;
1416 }
1417
1418 static inline int
1419 is_locator_in_locator_set (lisp_cp_main_t * lcm, locator_set_t * ls,
1420                            locator_t * loc)
1421 {
1422   locator_t *itloc;
1423   u32 *locit;
1424
1425   ASSERT (ls != NULL);
1426   ASSERT (loc != NULL);
1427
1428   vec_foreach (locit, ls->locator_indices)
1429   {
1430     itloc = pool_elt_at_index (lcm->locator_pool, locit[0]);
1431     if ((ls->local && itloc->sw_if_index == loc->sw_if_index) ||
1432         (!ls->local && !gid_address_cmp (&itloc->address, &loc->address)))
1433       {
1434         clib_warning ("Duplicate locator");
1435         return VNET_API_ERROR_VALUE_EXIST;
1436       }
1437   }
1438
1439   return 0;
1440 }
1441
1442 static inline void
1443 remove_locator_from_locator_set (locator_set_t * ls, u32 * locit,
1444                                  u32 ls_index, u32 loc_id)
1445 {
1446   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1447   u32 **ls_indexes = NULL;
1448
1449   ASSERT (ls != NULL);
1450   ASSERT (locit != NULL);
1451
1452   ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets, locit[0]);
1453   pool_put_index (lcm->locator_pool, locit[0]);
1454   vec_del1 (ls->locator_indices, loc_id);
1455   vec_del1 (ls_indexes[0], ls_index);
1456 }
1457
1458 int
1459 vnet_lisp_add_del_locator (vnet_lisp_add_del_locator_set_args_t * a,
1460                            locator_set_t * ls, u32 * ls_result)
1461 {
1462   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1463   locator_t *loc = NULL, *itloc = NULL;
1464   uword _p = (u32) ~ 0, *p = &_p;
1465   u32 loc_index = ~0, ls_index = ~0, *locit = NULL, **ls_indexes = NULL;
1466   u32 loc_id = ~0;
1467   int ret = 0;
1468
1469   ASSERT (a != NULL);
1470
1471   if (vnet_lisp_enable_disable_status () == 0)
1472     {
1473       clib_warning ("LISP is disabled!");
1474       return VNET_API_ERROR_LISP_DISABLED;
1475     }
1476
1477   p = get_locator_set_index (a, p);
1478   if (!p)
1479     {
1480       clib_warning ("locator-set %v doesn't exist", a->name);
1481       return VNET_API_ERROR_INVALID_ARGUMENT;
1482     }
1483
1484   if (ls == 0)
1485     {
1486       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
1487       if (!ls)
1488         {
1489           clib_warning ("locator-set %d to be overwritten doesn't exist!",
1490                         p[0]);
1491           return VNET_API_ERROR_INVALID_ARGUMENT;
1492         }
1493     }
1494
1495   if (a->is_add)
1496     {
1497       if (ls_result)
1498         ls_result[0] = p[0];
1499
1500       /* allocate locators */
1501       vec_foreach (itloc, a->locators)
1502       {
1503         ret = is_locator_in_locator_set (lcm, ls, itloc);
1504         if (0 != ret)
1505           {
1506             return ret;
1507           }
1508
1509         pool_get (lcm->locator_pool, loc);
1510         loc[0] = itloc[0];
1511         loc_index = loc - lcm->locator_pool;
1512
1513         vec_add1 (ls->locator_indices, loc_index);
1514
1515         vec_validate (lcm->locator_to_locator_sets, loc_index);
1516         ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
1517                                        loc_index);
1518         vec_add1 (ls_indexes[0], p[0]);
1519       }
1520     }
1521   else
1522     {
1523       ls_index = p[0];
1524
1525       itloc = a->locators;
1526       loc_id = 0;
1527       vec_foreach (locit, ls->locator_indices)
1528       {
1529         loc = pool_elt_at_index (lcm->locator_pool, locit[0]);
1530
1531         if (loc->local && loc->sw_if_index == itloc->sw_if_index)
1532           {
1533             remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
1534           }
1535         if (0 == loc->local &&
1536             !gid_address_cmp (&loc->address, &itloc->address))
1537           {
1538             remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
1539           }
1540
1541         loc_id++;
1542       }
1543     }
1544
1545   return 0;
1546 }
1547
1548 int
1549 vnet_lisp_add_del_locator_set (vnet_lisp_add_del_locator_set_args_t * a,
1550                                u32 * ls_result)
1551 {
1552   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1553   locator_set_t *ls;
1554   uword _p = (u32) ~ 0, *p = &_p;
1555   u32 ls_index;
1556   u32 **eid_indexes;
1557   int ret = 0;
1558
1559   if (vnet_lisp_enable_disable_status () == 0)
1560     {
1561       clib_warning ("LISP is disabled!");
1562       return VNET_API_ERROR_LISP_DISABLED;
1563     }
1564
1565   if (a->is_add)
1566     {
1567       p = get_locator_set_index (a, p);
1568
1569       /* overwrite */
1570       if (p && p[0] != (u32) ~ 0)
1571         {
1572           ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
1573           if (!ls)
1574             {
1575               clib_warning ("locator-set %d to be overwritten doesn't exist!",
1576                             p[0]);
1577               return -1;
1578             }
1579
1580           /* clean locator to locator-set vectors and remove locators if
1581            * they're not part of another locator-set */
1582           clean_locator_to_locator_set (lcm, p[0]);
1583
1584           /* remove locator indices from locator set */
1585           vec_free (ls->locator_indices);
1586
1587           ls_index = p[0];
1588
1589           if (ls_result)
1590             ls_result[0] = p[0];
1591         }
1592       /* new locator-set */
1593       else
1594         {
1595           pool_get (lcm->locator_set_pool, ls);
1596           memset (ls, 0, sizeof (*ls));
1597           ls_index = ls - lcm->locator_set_pool;
1598
1599           if (a->local)
1600             {
1601               ls->name = vec_dup (a->name);
1602
1603               if (!lcm->locator_set_index_by_name)
1604                 lcm->locator_set_index_by_name = hash_create_vec (
1605                                                                    /* size */
1606                                                                    0,
1607                                                                    sizeof
1608                                                                    (ls->name
1609                                                                     [0]),
1610                                                                    sizeof
1611                                                                    (uword));
1612               hash_set_mem (lcm->locator_set_index_by_name, ls->name,
1613                             ls_index);
1614
1615               /* mark as local locator-set */
1616               vec_add1 (lcm->local_locator_set_indexes, ls_index);
1617             }
1618           ls->local = a->local;
1619           if (ls_result)
1620             ls_result[0] = ls_index;
1621         }
1622
1623       ret = vnet_lisp_add_del_locator (a, ls, NULL);
1624       if (0 != ret)
1625         {
1626           return ret;
1627         }
1628     }
1629   else
1630     {
1631       p = get_locator_set_index (a, p);
1632       if (!p)
1633         {
1634           clib_warning ("locator-set %v doesn't exists", a->name);
1635           return -1;
1636         }
1637
1638       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
1639       if (!ls)
1640         {
1641           clib_warning ("locator-set with index %d doesn't exists", p[0]);
1642           return -1;
1643         }
1644
1645       if (lcm->mreq_itr_rlocs == p[0])
1646         {
1647           clib_warning ("Can't delete the locator-set used to constrain "
1648                         "the itr-rlocs in map-requests!");
1649           return -1;
1650         }
1651
1652       if (vec_len (lcm->locator_set_to_eids) != 0)
1653         {
1654           eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids, p[0]);
1655           if (vec_len (eid_indexes[0]) != 0)
1656             {
1657               clib_warning
1658                 ("Can't delete a locator that supports a mapping!");
1659               return -1;
1660             }
1661         }
1662
1663       /* clean locator to locator-sets data */
1664       clean_locator_to_locator_set (lcm, p[0]);
1665
1666       if (ls->local)
1667         {
1668           u32 it, lsi;
1669
1670           vec_foreach_index (it, lcm->local_locator_set_indexes)
1671           {
1672             lsi = vec_elt (lcm->local_locator_set_indexes, it);
1673             if (lsi == p[0])
1674               {
1675                 vec_del1 (lcm->local_locator_set_indexes, it);
1676                 break;
1677               }
1678           }
1679           hash_unset_mem (lcm->locator_set_index_by_name, ls->name);
1680         }
1681       vec_free (ls->name);
1682       vec_free (ls->locator_indices);
1683       pool_put (lcm->locator_set_pool, ls);
1684     }
1685   return 0;
1686 }
1687
1688 int
1689 vnet_lisp_rloc_probe_enable_disable (u8 is_enable)
1690 {
1691   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1692
1693   lcm->rloc_probing = is_enable;
1694   return 0;
1695 }
1696
1697 int
1698 vnet_lisp_map_register_enable_disable (u8 is_enable)
1699 {
1700   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1701
1702   lcm->map_registering = is_enable;
1703   return 0;
1704 }
1705
1706 clib_error_t *
1707 vnet_lisp_enable_disable (u8 is_enable)
1708 {
1709   u32 vni, dp_table;
1710   clib_error_t *error = 0;
1711   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1712   vnet_lisp_gpe_enable_disable_args_t _a, *a = &_a;
1713
1714   a->is_en = is_enable;
1715   error = vnet_lisp_gpe_enable_disable (a);
1716   if (error)
1717     {
1718       return clib_error_return (0, "failed to %s data-plane!",
1719                                 a->is_en ? "enable" : "disable");
1720     }
1721
1722   if (is_enable)
1723     {
1724       /* enable all l2 and l3 ifaces */
1725
1726       /* *INDENT-OFF* */
1727       hash_foreach(vni, dp_table, lcm->table_id_by_vni, ({
1728         dp_add_del_iface(lcm, vni, 0, 1);
1729       }));
1730       hash_foreach(vni, dp_table, lcm->bd_id_by_vni, ({
1731         dp_add_del_iface(lcm, vni, /* is_l2 */ 1, 1);
1732       }));
1733       /* *INDENT-ON* */
1734     }
1735   else
1736     {
1737       /* clear interface table */
1738       hash_free (lcm->fwd_entry_by_mapping_index);
1739       pool_free (lcm->fwd_entry_pool);
1740     }
1741
1742   /* update global flag */
1743   lcm->is_enabled = is_enable;
1744
1745   return 0;
1746 }
1747
1748 u8
1749 vnet_lisp_enable_disable_status (void)
1750 {
1751   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1752   return lcm->is_enabled;
1753 }
1754
1755 int
1756 vnet_lisp_add_del_map_resolver (vnet_lisp_add_del_map_resolver_args_t * a)
1757 {
1758   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1759   u32 i;
1760   lisp_msmr_t _mr, *mr = &_mr;
1761
1762   if (vnet_lisp_enable_disable_status () == 0)
1763     {
1764       clib_warning ("LISP is disabled!");
1765       return VNET_API_ERROR_LISP_DISABLED;
1766     }
1767
1768   if (a->is_add)
1769     {
1770
1771       if (get_map_resolver (&a->address))
1772         {
1773           clib_warning ("map-resolver %U already exists!", format_ip_address,
1774                         &a->address);
1775           return -1;
1776         }
1777
1778       memset (mr, 0, sizeof (*mr));
1779       ip_address_copy (&mr->address, &a->address);
1780       vec_add1 (lcm->map_resolvers, *mr);
1781
1782       if (vec_len (lcm->map_resolvers) == 1)
1783         lcm->do_map_resolver_election = 1;
1784     }
1785   else
1786     {
1787       for (i = 0; i < vec_len (lcm->map_resolvers); i++)
1788         {
1789           mr = vec_elt_at_index (lcm->map_resolvers, i);
1790           if (!ip_address_cmp (&mr->address, &a->address))
1791             {
1792               if (!ip_address_cmp (&mr->address, &lcm->active_map_resolver))
1793                 lcm->do_map_resolver_election = 1;
1794
1795               vec_del1 (lcm->map_resolvers, i);
1796               break;
1797             }
1798         }
1799     }
1800   return 0;
1801 }
1802
1803 int
1804 vnet_lisp_add_del_mreq_itr_rlocs (vnet_lisp_add_del_mreq_itr_rloc_args_t * a)
1805 {
1806   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1807   uword *p = 0;
1808
1809   if (vnet_lisp_enable_disable_status () == 0)
1810     {
1811       clib_warning ("LISP is disabled!");
1812       return VNET_API_ERROR_LISP_DISABLED;
1813     }
1814
1815   if (a->is_add)
1816     {
1817       p = hash_get_mem (lcm->locator_set_index_by_name, a->locator_set_name);
1818       if (!p)
1819         {
1820           clib_warning ("locator-set %v doesn't exist", a->locator_set_name);
1821           return VNET_API_ERROR_INVALID_ARGUMENT;
1822         }
1823
1824       lcm->mreq_itr_rlocs = p[0];
1825     }
1826   else
1827     {
1828       lcm->mreq_itr_rlocs = ~0;
1829     }
1830
1831   return 0;
1832 }
1833
1834 /* Statistics (not really errors) */
1835 #define foreach_lisp_cp_lookup_error           \
1836 _(DROP, "drop")                                \
1837 _(MAP_REQUESTS_SENT, "map-request sent")
1838
1839 static char *lisp_cp_lookup_error_strings[] = {
1840 #define _(sym,string) string,
1841   foreach_lisp_cp_lookup_error
1842 #undef _
1843 };
1844
1845 typedef enum
1846 {
1847 #define _(sym,str) LISP_CP_LOOKUP_ERROR_##sym,
1848   foreach_lisp_cp_lookup_error
1849 #undef _
1850     LISP_CP_LOOKUP_N_ERROR,
1851 } lisp_cp_lookup_error_t;
1852
1853 typedef enum
1854 {
1855   LISP_CP_LOOKUP_NEXT_DROP,
1856   LISP_CP_LOOKUP_N_NEXT,
1857 } lisp_cp_lookup_next_t;
1858
1859 typedef struct
1860 {
1861   gid_address_t dst_eid;
1862   ip_address_t map_resolver_ip;
1863 } lisp_cp_lookup_trace_t;
1864
1865 u8 *
1866 format_lisp_cp_lookup_trace (u8 * s, va_list * args)
1867 {
1868   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1869   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1870   lisp_cp_lookup_trace_t *t = va_arg (*args, lisp_cp_lookup_trace_t *);
1871
1872   s = format (s, "LISP-CP-LOOKUP: map-resolver: %U destination eid %U",
1873               format_ip_address, &t->map_resolver_ip, format_gid_address,
1874               &t->dst_eid);
1875   return s;
1876 }
1877
1878 int
1879 get_mr_and_local_iface_ip (lisp_cp_main_t * lcm, ip_address_t * mr_ip,
1880                            ip_address_t * sloc)
1881 {
1882   lisp_msmr_t *mrit;
1883   ip_address_t *a;
1884
1885   if (vec_len (lcm->map_resolvers) == 0)
1886     {
1887       clib_warning ("No map-resolver configured");
1888       return 0;
1889     }
1890
1891   /* find the first mr ip we have a route to and the ip of the
1892    * iface that has a route to it */
1893   vec_foreach (mrit, lcm->map_resolvers)
1894   {
1895     a = &mrit->address;
1896     if (0 != ip_fib_get_first_egress_ip_for_dst (lcm, a, sloc))
1897       {
1898         ip_address_copy (mr_ip, a);
1899
1900         /* also update globals */
1901         return 1;
1902       }
1903   }
1904
1905   clib_warning ("Can't find map-resolver and local interface ip!");
1906   return 0;
1907 }
1908
1909 static gid_address_t *
1910 build_itr_rloc_list (lisp_cp_main_t * lcm, locator_set_t * loc_set)
1911 {
1912   void *addr;
1913   u32 i;
1914   locator_t *loc;
1915   u32 *loc_indexp;
1916   ip_interface_address_t *ia = 0;
1917   gid_address_t gid_data, *gid = &gid_data;
1918   gid_address_t *rlocs = 0;
1919   ip_prefix_t *ippref = &gid_address_ippref (gid);
1920   ip_address_t *rloc = &ip_prefix_addr (ippref);
1921
1922   memset (gid, 0, sizeof (gid[0]));
1923   gid_address_type (gid) = GID_ADDR_IP_PREFIX;
1924   for (i = 0; i < vec_len (loc_set->locator_indices); i++)
1925     {
1926       loc_indexp = vec_elt_at_index (loc_set->locator_indices, i);
1927       loc = pool_elt_at_index (lcm->locator_pool, loc_indexp[0]);
1928
1929       /* Add ipv4 locators first TODO sort them */
1930
1931       /* *INDENT-OFF* */
1932       foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
1933                                     loc->sw_if_index, 1 /* unnumbered */,
1934       ({
1935         addr = ip_interface_address_get_address (&lcm->im4->lookup_main, ia);
1936         ip_address_set (rloc, addr, IP4);
1937         ip_prefix_len (ippref) = 32;
1938         ip_prefix_normalize (ippref);
1939         vec_add1 (rlocs, gid[0]);
1940       }));
1941
1942       /* Add ipv6 locators */
1943       foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
1944                                     loc->sw_if_index, 1 /* unnumbered */,
1945       ({
1946         addr = ip_interface_address_get_address (&lcm->im6->lookup_main, ia);
1947         ip_address_set (rloc, addr, IP6);
1948         ip_prefix_len (ippref) = 128;
1949         ip_prefix_normalize (ippref);
1950         vec_add1 (rlocs, gid[0]);
1951       }));
1952       /* *INDENT-ON* */
1953
1954     }
1955   return rlocs;
1956 }
1957
1958 static vlib_buffer_t *
1959 build_map_request (lisp_cp_main_t * lcm, gid_address_t * deid,
1960                    ip_address_t * sloc, ip_address_t * rloc,
1961                    gid_address_t * itr_rlocs, u64 * nonce_res, u32 * bi_res)
1962 {
1963   vlib_buffer_t *b;
1964   u32 bi;
1965   vlib_main_t *vm = lcm->vlib_main;
1966
1967   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
1968     {
1969       clib_warning ("Can't allocate buffer for Map-Request!");
1970       return 0;
1971     }
1972
1973   b = vlib_get_buffer (vm, bi);
1974
1975   /* leave some space for the encap headers */
1976   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
1977
1978   /* put lisp msg */
1979   lisp_msg_put_mreq (lcm, b, NULL, deid, itr_rlocs, 0 /* smr invoked */ ,
1980                      1 /* rloc probe */ , nonce_res);
1981
1982   /* push outer ip header */
1983   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
1984                        rloc);
1985
1986   bi_res[0] = bi;
1987
1988   return b;
1989 }
1990
1991 static vlib_buffer_t *
1992 build_encapsulated_map_request (lisp_cp_main_t * lcm,
1993                                 gid_address_t * seid, gid_address_t * deid,
1994                                 locator_set_t * loc_set, ip_address_t * mr_ip,
1995                                 ip_address_t * sloc, u8 is_smr_invoked,
1996                                 u64 * nonce_res, u32 * bi_res)
1997 {
1998   vlib_buffer_t *b;
1999   u32 bi;
2000   gid_address_t *rlocs = 0;
2001   vlib_main_t *vm = lcm->vlib_main;
2002
2003   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
2004     {
2005       clib_warning ("Can't allocate buffer for Map-Request!");
2006       return 0;
2007     }
2008
2009   b = vlib_get_buffer (vm, bi);
2010
2011   /* leave some space for the encap headers */
2012   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2013
2014   /* get rlocs */
2015   rlocs = build_itr_rloc_list (lcm, loc_set);
2016
2017   if (MR_MODE_SRC_DST == lcm->map_request_mode
2018       && GID_ADDR_SRC_DST != gid_address_type (deid))
2019     {
2020       gid_address_t sd;
2021       memset (&sd, 0, sizeof (sd));
2022       build_src_dst (&sd, seid, deid);
2023       lisp_msg_put_mreq (lcm, b, seid, &sd, rlocs, is_smr_invoked,
2024                          0 /* rloc probe */ , nonce_res);
2025     }
2026   else
2027     {
2028       /* put lisp msg */
2029       lisp_msg_put_mreq (lcm, b, seid, deid, rlocs, is_smr_invoked,
2030                          0 /* rloc probe */ , nonce_res);
2031     }
2032
2033   /* push ecm: udp-ip-lisp */
2034   lisp_msg_push_ecm (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, seid, deid);
2035
2036   /* push outer ip header */
2037   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2038                        mr_ip);
2039
2040   bi_res[0] = bi;
2041
2042   vec_free (rlocs);
2043   return b;
2044 }
2045
2046 static void
2047 reset_pending_mr_counters (pending_map_request_t * r)
2048 {
2049   r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
2050   r->retries_num = 0;
2051 }
2052
2053 static int
2054 elect_map_resolver (lisp_cp_main_t * lcm)
2055 {
2056   lisp_msmr_t *mr;
2057
2058   vec_foreach (mr, lcm->map_resolvers)
2059   {
2060     if (!mr->is_down)
2061       {
2062         ip_address_copy (&lcm->active_map_resolver, &mr->address);
2063         lcm->do_map_resolver_election = 0;
2064         return 1;
2065       }
2066   }
2067   return 0;
2068 }
2069
2070 static void
2071 free_map_register_records (mapping_t * maps)
2072 {
2073   mapping_t *map;
2074   vec_foreach (map, maps) vec_free (map->locators);
2075
2076   vec_free (maps);
2077 }
2078
2079 static void
2080 add_locators (lisp_cp_main_t * lcm, mapping_t * m, u32 locator_set_index,
2081               ip_address_t * probed_loc)
2082 {
2083   u32 *li;
2084   locator_t *loc, new;
2085   ip_interface_address_t *ia = 0;
2086   void *addr;
2087   ip_address_t *new_ip = &gid_address_ip (&new.address);
2088
2089   m->locators = 0;
2090   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool,
2091                                          locator_set_index);
2092   vec_foreach (li, ls->locator_indices)
2093   {
2094     loc = pool_elt_at_index (lcm->locator_pool, li[0]);
2095     new = loc[0];
2096     if (loc->local)
2097       {
2098           /* *INDENT-OFF* */
2099           foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
2100                                         loc->sw_if_index, 1 /* unnumbered */,
2101           ({
2102             addr = ip_interface_address_get_address (&lcm->im4->lookup_main,
2103                                                      ia);
2104             ip_address_set (new_ip, addr, IP4);
2105           }));
2106
2107           /* Add ipv6 locators */
2108           foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
2109                                         loc->sw_if_index, 1 /* unnumbered */,
2110           ({
2111             addr = ip_interface_address_get_address (&lcm->im6->lookup_main,
2112                                                      ia);
2113             ip_address_set (new_ip, addr, IP6);
2114           }));
2115           /* *INDENT-ON* */
2116
2117         if (probed_loc && ip_address_cmp (probed_loc, new_ip) == 0)
2118           new.probed = 1;
2119       }
2120     vec_add1 (m->locators, new);
2121   }
2122 }
2123
2124 static mapping_t *
2125 build_map_register_record_list (lisp_cp_main_t * lcm)
2126 {
2127   mapping_t *recs = 0, rec, *m;
2128
2129   /* *INDENT-OFF* */
2130   pool_foreach(m, lcm->mapping_pool,
2131   {
2132     /* for now build only local mappings */
2133     if (!m->local)
2134       continue;
2135
2136     rec = m[0];
2137     add_locators (lcm, &rec, m->locator_set_index, NULL);
2138     vec_add1 (recs, rec);
2139   });
2140   /* *INDENT-ON* */
2141
2142   return recs;
2143 }
2144
2145 static int
2146 update_map_register_auth_data (map_register_hdr_t * map_reg_hdr,
2147                                lisp_key_type_t key_id, u8 * key,
2148                                u16 auth_data_len, u32 msg_len)
2149 {
2150   MREG_KEY_ID (map_reg_hdr) = clib_host_to_net_u16 (key_id);
2151   MREG_AUTH_DATA_LEN (map_reg_hdr) = clib_host_to_net_u16 (auth_data_len);
2152
2153   unsigned char *result = HMAC (get_encrypt_fcn (key_id), key, vec_len (key),
2154                                 (unsigned char *) map_reg_hdr, msg_len, NULL,
2155                                 NULL);
2156   clib_memcpy (MREG_DATA (map_reg_hdr), result, auth_data_len);
2157
2158   return 0;
2159 }
2160
2161 static vlib_buffer_t *
2162 build_map_register (lisp_cp_main_t * lcm, ip_address_t * sloc,
2163                     ip_address_t * ms_ip, u64 * nonce_res, u8 want_map_notif,
2164                     mapping_t * records, lisp_key_type_t key_id, u8 * key,
2165                     u32 * bi_res)
2166 {
2167   void *map_reg_hdr;
2168   vlib_buffer_t *b;
2169   u32 bi, auth_data_len = 0, msg_len = 0;
2170   vlib_main_t *vm = lcm->vlib_main;
2171
2172   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
2173     {
2174       clib_warning ("Can't allocate buffer for Map-Register!");
2175       return 0;
2176     }
2177
2178   b = vlib_get_buffer (vm, bi);
2179
2180   /* leave some space for the encap headers */
2181   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2182
2183   auth_data_len = auth_data_len_by_key_id (key_id);
2184   map_reg_hdr = lisp_msg_put_map_register (b, records, want_map_notif,
2185                                            auth_data_len, nonce_res,
2186                                            &msg_len);
2187
2188   update_map_register_auth_data (map_reg_hdr, key_id, key, auth_data_len,
2189                                  msg_len);
2190
2191   /* push outer ip header */
2192   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2193                        ms_ip);
2194
2195   bi_res[0] = bi;
2196   return b;
2197 }
2198
2199 static int
2200 get_egress_map_resolver_ip (lisp_cp_main_t * lcm, ip_address_t * ip)
2201 {
2202   lisp_msmr_t *mr;
2203   while (lcm->do_map_resolver_election
2204          | (0 == ip_fib_get_first_egress_ip_for_dst (lcm,
2205                                                      &lcm->active_map_resolver,
2206                                                      ip)))
2207     {
2208       if (0 == elect_map_resolver (lcm))
2209         /* all map resolvers are down */
2210         {
2211           /* restart MR checking by marking all of them up */
2212           vec_foreach (mr, lcm->map_resolvers) mr->is_down = 0;
2213           return -1;
2214         }
2215     }
2216   return 0;
2217 }
2218
2219 /* CP output statistics */
2220 #define foreach_lisp_cp_output_error                  \
2221 _(MAP_REGISTERS_SENT, "map-registers sent")           \
2222 _(RLOC_PROBES_SENT, "rloc-probes sent")
2223
2224 static char *lisp_cp_output_error_strings[] = {
2225 #define _(sym,string) string,
2226   foreach_lisp_cp_output_error
2227 #undef _
2228 };
2229
2230 typedef enum
2231 {
2232 #define _(sym,str) LISP_CP_OUTPUT_ERROR_##sym,
2233   foreach_lisp_cp_output_error
2234 #undef _
2235     LISP_CP_OUTPUT_N_ERROR,
2236 } lisp_cp_output_error_t;
2237
2238 static uword
2239 lisp_cp_output (vlib_main_t * vm, vlib_node_runtime_t * node,
2240                 vlib_frame_t * from_frame)
2241 {
2242   return 0;
2243 }
2244
2245 /* dummy node used only for statistics */
2246 /* *INDENT-OFF* */
2247 VLIB_REGISTER_NODE (lisp_cp_output_node) = {
2248   .function = lisp_cp_output,
2249   .name = "lisp-cp-output",
2250   .vector_size = sizeof (u32),
2251   .format_trace = format_lisp_cp_input_trace,
2252   .type = VLIB_NODE_TYPE_INTERNAL,
2253
2254   .n_errors = LISP_CP_OUTPUT_N_ERROR,
2255   .error_strings = lisp_cp_output_error_strings,
2256
2257   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
2258
2259   .next_nodes = {
2260       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
2261   },
2262 };
2263 /* *INDENT-ON* */
2264
2265 static int
2266 send_rloc_probe (lisp_cp_main_t * lcm, gid_address_t * deid,
2267                  u32 local_locator_set_index, ip_address_t * sloc,
2268                  ip_address_t * rloc)
2269 {
2270   locator_set_t *ls;
2271   u32 bi;
2272   vlib_buffer_t *b;
2273   vlib_frame_t *f;
2274   u64 nonce = 0;
2275   u32 next_index, *to_next;
2276   gid_address_t *itr_rlocs;
2277
2278   ls = pool_elt_at_index (lcm->locator_set_pool, local_locator_set_index);
2279   itr_rlocs = build_itr_rloc_list (lcm, ls);
2280
2281   b = build_map_request (lcm, deid, sloc, rloc, itr_rlocs, &nonce, &bi);
2282   vec_free (itr_rlocs);
2283   if (!b)
2284     return -1;
2285
2286   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
2287
2288   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
2289     ip4_lookup_node.index : ip6_lookup_node.index;
2290
2291   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
2292
2293   /* Enqueue the packet */
2294   to_next = vlib_frame_vector_args (f);
2295   to_next[0] = bi;
2296   f->n_vectors = 1;
2297   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
2298
2299   hash_set (lcm->map_register_messages_by_nonce, nonce, 0);
2300   return 0;
2301 }
2302
2303 static int
2304 send_rloc_probes (lisp_cp_main_t * lcm)
2305 {
2306   u8 lprio = 0;
2307   mapping_t *lm;
2308   fwd_entry_t *e;
2309   locator_pair_t *lp;
2310   u32 si, rloc_probes_sent = 0;
2311
2312   /* *INDENT-OFF* */
2313   pool_foreach (e, lcm->fwd_entry_pool,
2314   {
2315     if (vec_len (e->locator_pairs) == 0)
2316       continue;
2317
2318     si = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &e->leid);
2319     if (~0 == si)
2320       {
2321         clib_warning ("internal error: cannot find local eid %U in "
2322                       "map-cache!", format_gid_address, &e->leid);
2323         continue;
2324       }
2325     lm = pool_elt_at_index (lcm->mapping_pool, si);
2326
2327     /* get the best (lowest) priority */
2328     lprio = e->locator_pairs[0].priority;
2329
2330     /* send rloc-probe for pair(s) with the best remote locator priority */
2331     vec_foreach (lp, e->locator_pairs)
2332       {
2333         if (lp->priority != lprio)
2334           break;
2335
2336         /* get first remote locator */
2337         send_rloc_probe (lcm, &e->reid, lm->locator_set_index, &lp->lcl_loc,
2338                          &lp->rmt_loc);
2339         rloc_probes_sent++;
2340       }
2341   });
2342   /* *INDENT-ON* */
2343
2344   vlib_node_increment_counter (vlib_get_main (), lisp_cp_output_node.index,
2345                                LISP_CP_OUTPUT_ERROR_RLOC_PROBES_SENT,
2346                                rloc_probes_sent);
2347   return 0;
2348 }
2349
2350 static int
2351 send_map_register (lisp_cp_main_t * lcm, u8 want_map_notif)
2352 {
2353   u32 bi, map_registers_sent = 0;
2354   vlib_buffer_t *b;
2355   ip_address_t sloc;
2356   vlib_frame_t *f;
2357   u64 nonce = 0;
2358   u32 next_index, *to_next;
2359   ip_address_t *ms = 0;
2360   mapping_t *records, *r, *g;
2361
2362   // TODO: support multiple map servers and do election
2363   if (0 == vec_len (lcm->map_servers))
2364     return -1;
2365
2366   ms = &lcm->map_servers[0].address;
2367
2368   if (0 == ip_fib_get_first_egress_ip_for_dst (lcm, ms, &sloc))
2369     {
2370       clib_warning ("no eligible interface address found for %U!",
2371                     format_ip_address, &lcm->map_servers[0]);
2372       return -1;
2373     }
2374
2375   records = build_map_register_record_list (lcm);
2376   if (!records)
2377     return -1;
2378
2379   vec_foreach (r, records)
2380   {
2381     u8 *key = r->key;
2382     u8 key_id = r->key_id;
2383
2384     if (!key)
2385       continue;                 /* no secret key -> map-register cannot be sent */
2386
2387     g = 0;
2388     // TODO: group mappings that share common key
2389     vec_add1 (g, r[0]);
2390     b = build_map_register (lcm, &sloc, ms, &nonce, want_map_notif, g,
2391                             key_id, key, &bi);
2392     vec_free (g);
2393     if (!b)
2394       continue;
2395
2396     vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
2397
2398     next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
2399       ip4_lookup_node.index : ip6_lookup_node.index;
2400
2401     f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
2402
2403     /* Enqueue the packet */
2404     to_next = vlib_frame_vector_args (f);
2405     to_next[0] = bi;
2406     f->n_vectors = 1;
2407     vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
2408     map_registers_sent++;
2409
2410     hash_set (lcm->map_register_messages_by_nonce, nonce, 0);
2411   }
2412   free_map_register_records (records);
2413
2414   vlib_node_increment_counter (vlib_get_main (), lisp_cp_output_node.index,
2415                                LISP_CP_OUTPUT_ERROR_MAP_REGISTERS_SENT,
2416                                map_registers_sent);
2417
2418   return 0;
2419 }
2420
2421 #define send_encapsulated_map_request(lcm, seid, deid, smr) \
2422   _send_encapsulated_map_request(lcm, seid, deid, smr, 0)
2423
2424 #define resend_encapsulated_map_request(lcm, seid, deid, smr) \
2425   _send_encapsulated_map_request(lcm, seid, deid, smr, 1)
2426
2427 static int
2428 _send_encapsulated_map_request (lisp_cp_main_t * lcm,
2429                                 gid_address_t * seid, gid_address_t * deid,
2430                                 u8 is_smr_invoked, u8 is_resend)
2431 {
2432   u32 next_index, bi = 0, *to_next, map_index;
2433   vlib_buffer_t *b;
2434   vlib_frame_t *f;
2435   u64 nonce = 0;
2436   locator_set_t *loc_set;
2437   mapping_t *map;
2438   pending_map_request_t *pmr, *duplicate_pmr = 0;
2439   ip_address_t sloc;
2440   u32 ls_index;
2441
2442   /* if there is already a pending request remember it */
2443
2444   /* *INDENT-OFF* */
2445   pool_foreach(pmr, lcm->pending_map_requests_pool,
2446   ({
2447     if (!gid_address_cmp (&pmr->src, seid)
2448         && !gid_address_cmp (&pmr->dst, deid))
2449       {
2450         duplicate_pmr = pmr;
2451         break;
2452       }
2453   }));
2454   /* *INDENT-ON* */
2455
2456   if (!is_resend && duplicate_pmr)
2457     {
2458       /* don't send the request if there is a pending map request already */
2459       return 0;
2460     }
2461
2462   /* get locator-set for seid */
2463   if (!lcm->lisp_pitr)
2464     {
2465       map_index = gid_dictionary_lookup (&lcm->mapping_index_by_gid, seid);
2466       if (map_index == ~0)
2467         {
2468           clib_warning ("No local mapping found in eid-table for %U!",
2469                         format_gid_address, seid);
2470           return -1;
2471         }
2472
2473       map = pool_elt_at_index (lcm->mapping_pool, map_index);
2474
2475       if (!map->local)
2476         {
2477           clib_warning
2478             ("Mapping found for src eid %U is not marked as local!",
2479              format_gid_address, seid);
2480           return -1;
2481         }
2482       ls_index = map->locator_set_index;
2483     }
2484   else
2485     {
2486       map_index = lcm->pitr_map_index;
2487       map = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
2488       ls_index = map->locator_set_index;
2489     }
2490
2491   /* overwrite locator set if map-request itr-rlocs configured */
2492   if (~0 != lcm->mreq_itr_rlocs)
2493     {
2494       ls_index = lcm->mreq_itr_rlocs;
2495     }
2496
2497   loc_set = pool_elt_at_index (lcm->locator_set_pool, ls_index);
2498
2499   if (get_egress_map_resolver_ip (lcm, &sloc) < 0)
2500     {
2501       if (duplicate_pmr)
2502         duplicate_pmr->to_be_removed = 1;
2503       return -1;
2504     }
2505
2506   /* build the encapsulated map request */
2507   b = build_encapsulated_map_request (lcm, seid, deid, loc_set,
2508                                       &lcm->active_map_resolver,
2509                                       &sloc, is_smr_invoked, &nonce, &bi);
2510
2511   if (!b)
2512     return -1;
2513
2514   /* set fib index to default and lookup node */
2515   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
2516   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
2517     ip4_lookup_node.index : ip6_lookup_node.index;
2518
2519   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
2520
2521   /* Enqueue the packet */
2522   to_next = vlib_frame_vector_args (f);
2523   to_next[0] = bi;
2524   f->n_vectors = 1;
2525   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
2526
2527   if (duplicate_pmr)
2528     /* if there is a pending request already update it */
2529     {
2530       if (clib_fifo_elts (duplicate_pmr->nonces) >= PENDING_MREQ_QUEUE_LEN)
2531         {
2532           /* remove the oldest nonce */
2533           u64 CLIB_UNUSED (tmp), *nonce_del;
2534           nonce_del = clib_fifo_head (duplicate_pmr->nonces);
2535           hash_unset (lcm->pending_map_requests_by_nonce, nonce_del[0]);
2536           clib_fifo_sub1 (duplicate_pmr->nonces, tmp);
2537         }
2538
2539       clib_fifo_add1 (duplicate_pmr->nonces, nonce);
2540       hash_set (lcm->pending_map_requests_by_nonce, nonce,
2541                 duplicate_pmr - lcm->pending_map_requests_pool);
2542     }
2543   else
2544     {
2545       /* add map-request to pending requests table */
2546       pool_get (lcm->pending_map_requests_pool, pmr);
2547       memset (pmr, 0, sizeof (*pmr));
2548       gid_address_copy (&pmr->src, seid);
2549       gid_address_copy (&pmr->dst, deid);
2550       clib_fifo_add1 (pmr->nonces, nonce);
2551       pmr->is_smr_invoked = is_smr_invoked;
2552       reset_pending_mr_counters (pmr);
2553       hash_set (lcm->pending_map_requests_by_nonce, nonce,
2554                 pmr - lcm->pending_map_requests_pool);
2555     }
2556
2557   return 0;
2558 }
2559
2560 static void
2561 get_src_and_dst_ip (void *hdr, ip_address_t * src, ip_address_t * dst)
2562 {
2563   ip4_header_t *ip4 = hdr;
2564   ip6_header_t *ip6;
2565
2566   if ((ip4->ip_version_and_header_length & 0xF0) == 0x40)
2567     {
2568       ip_address_set (src, &ip4->src_address, IP4);
2569       ip_address_set (dst, &ip4->dst_address, IP4);
2570     }
2571   else
2572     {
2573       ip6 = hdr;
2574       ip_address_set (src, &ip6->src_address, IP6);
2575       ip_address_set (dst, &ip6->dst_address, IP6);
2576     }
2577 }
2578
2579 static u32
2580 lisp_get_vni_from_buffer_ip (lisp_cp_main_t * lcm, vlib_buffer_t * b,
2581                              u8 version)
2582 {
2583   uword *vnip;
2584   u32 vni = ~0, table_id = ~0;
2585
2586   table_id = fib_table_get_table_id_for_sw_if_index ((version ==
2587                                                       IP4 ? FIB_PROTOCOL_IP4 :
2588                                                       FIB_PROTOCOL_IP6),
2589                                                      vnet_buffer
2590                                                      (b)->sw_if_index
2591                                                      [VLIB_RX]);
2592
2593   vnip = hash_get (lcm->vni_by_table_id, table_id);
2594   if (vnip)
2595     vni = vnip[0];
2596   else
2597     clib_warning ("vrf %d is not mapped to any vni!", table_id);
2598
2599   return vni;
2600 }
2601
2602 always_inline u32
2603 lisp_get_vni_from_buffer_eth (lisp_cp_main_t * lcm, vlib_buffer_t * b)
2604 {
2605   uword *vnip;
2606   u32 vni = ~0;
2607   u32 sw_if_index0;
2608
2609   l2input_main_t *l2im = &l2input_main;
2610   l2_input_config_t *config;
2611   l2_bridge_domain_t *bd_config;
2612
2613   sw_if_index0 = vnet_buffer (b)->sw_if_index[VLIB_RX];
2614   config = vec_elt_at_index (l2im->configs, sw_if_index0);
2615   bd_config = vec_elt_at_index (l2im->bd_configs, config->bd_index);
2616
2617   vnip = hash_get (lcm->vni_by_bd_id, bd_config->bd_id);
2618   if (vnip)
2619     vni = vnip[0];
2620   else
2621     clib_warning ("bridge domain %d is not mapped to any vni!",
2622                   config->bd_index);
2623
2624   return vni;
2625 }
2626
2627 always_inline void
2628 get_src_and_dst_eids_from_buffer (lisp_cp_main_t * lcm, vlib_buffer_t * b,
2629                                   gid_address_t * src, gid_address_t * dst)
2630 {
2631   u32 vni = 0;
2632   u16 type;
2633
2634   memset (src, 0, sizeof (*src));
2635   memset (dst, 0, sizeof (*dst));
2636   type = vnet_buffer (b)->lisp.overlay_afi;
2637
2638   if (LISP_AFI_IP == type || LISP_AFI_IP6 == type)
2639     {
2640       ip4_header_t *ip;
2641       u8 version, preflen;
2642
2643       gid_address_type (src) = GID_ADDR_IP_PREFIX;
2644       gid_address_type (dst) = GID_ADDR_IP_PREFIX;
2645
2646       ip = vlib_buffer_get_current (b);
2647       get_src_and_dst_ip (ip, &gid_address_ip (src), &gid_address_ip (dst));
2648
2649       version = gid_address_ip_version (src);
2650       preflen = ip_address_max_len (version);
2651       gid_address_ippref_len (src) = preflen;
2652       gid_address_ippref_len (dst) = preflen;
2653
2654       vni = lisp_get_vni_from_buffer_ip (lcm, b, version);
2655       gid_address_vni (dst) = vni;
2656       gid_address_vni (src) = vni;
2657     }
2658   else if (LISP_AFI_MAC == type)
2659     {
2660       ethernet_header_t *eh;
2661
2662       eh = vlib_buffer_get_current (b);
2663
2664       gid_address_type (src) = GID_ADDR_MAC;
2665       gid_address_type (dst) = GID_ADDR_MAC;
2666       mac_copy (&gid_address_mac (src), eh->src_address);
2667       mac_copy (&gid_address_mac (dst), eh->dst_address);
2668
2669       /* get vni */
2670       vni = lisp_get_vni_from_buffer_eth (lcm, b);
2671
2672       gid_address_vni (dst) = vni;
2673       gid_address_vni (src) = vni;
2674     }
2675 }
2676
2677 static uword
2678 lisp_cp_lookup_inline (vlib_main_t * vm,
2679                        vlib_node_runtime_t * node,
2680                        vlib_frame_t * from_frame, int overlay)
2681 {
2682   u32 *from, *to_next_drop, di, si;
2683   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2684   u32 pkts_mapped = 0;
2685   uword n_left_from, n_left_to_next_drop;
2686
2687   from = vlib_frame_vector_args (from_frame);
2688   n_left_from = from_frame->n_vectors;
2689
2690   while (n_left_from > 0)
2691     {
2692       vlib_get_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
2693                            to_next_drop, n_left_to_next_drop);
2694
2695       while (n_left_from > 0 && n_left_to_next_drop > 0)
2696         {
2697           u32 pi0;
2698           vlib_buffer_t *b0;
2699           gid_address_t src, dst;
2700
2701           pi0 = from[0];
2702           from += 1;
2703           n_left_from -= 1;
2704           to_next_drop[0] = pi0;
2705           to_next_drop += 1;
2706           n_left_to_next_drop -= 1;
2707
2708           b0 = vlib_get_buffer (vm, pi0);
2709           b0->error = node->errors[LISP_CP_LOOKUP_ERROR_DROP];
2710           vnet_buffer (b0)->lisp.overlay_afi = overlay;
2711
2712           /* src/dst eid pair */
2713           get_src_and_dst_eids_from_buffer (lcm, b0, &src, &dst);
2714
2715           /* if we have remote mapping for destination already in map-chache
2716              add forwarding tunnel directly. If not send a map-request */
2717           di = gid_dictionary_sd_lookup (&lcm->mapping_index_by_gid, &dst,
2718                                          &src);
2719           if (~0 != di)
2720             {
2721               mapping_t *m = vec_elt_at_index (lcm->mapping_pool, di);
2722               /* send a map-request also in case of negative mapping entry
2723                  with corresponding action */
2724               if (m->action == LISP_SEND_MAP_REQUEST)
2725                 {
2726                   /* send map-request */
2727                   queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
2728                                      0 /* is_resend */ );
2729                   pkts_mapped++;
2730                 }
2731               else
2732                 {
2733                   si = gid_dictionary_lookup (&lcm->mapping_index_by_gid,
2734                                               &src);
2735                   if (~0 != si)
2736                     {
2737                       dp_add_fwd_entry_from_mt (si, di);
2738                     }
2739                 }
2740             }
2741           else
2742             {
2743               /* send map-request */
2744               queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
2745                                  0 /* is_resend */ );
2746               pkts_mapped++;
2747             }
2748
2749           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
2750             {
2751               lisp_cp_lookup_trace_t *tr = vlib_add_trace (vm, node, b0,
2752                                                            sizeof (*tr));
2753
2754               memset (tr, 0, sizeof (*tr));
2755               gid_address_copy (&tr->dst_eid, &dst);
2756               ip_address_copy (&tr->map_resolver_ip,
2757                                &lcm->active_map_resolver);
2758             }
2759           gid_address_free (&dst);
2760           gid_address_free (&src);
2761         }
2762
2763       vlib_put_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
2764                            n_left_to_next_drop);
2765     }
2766   vlib_node_increment_counter (vm, node->node_index,
2767                                LISP_CP_LOOKUP_ERROR_MAP_REQUESTS_SENT,
2768                                pkts_mapped);
2769   return from_frame->n_vectors;
2770 }
2771
2772 static uword
2773 lisp_cp_lookup_ip4 (vlib_main_t * vm,
2774                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
2775 {
2776   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP));
2777 }
2778
2779 static uword
2780 lisp_cp_lookup_ip6 (vlib_main_t * vm,
2781                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
2782 {
2783   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP6));
2784 }
2785
2786 static uword
2787 lisp_cp_lookup_l2 (vlib_main_t * vm,
2788                    vlib_node_runtime_t * node, vlib_frame_t * from_frame)
2789 {
2790   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_MAC));
2791 }
2792
2793 /* *INDENT-OFF* */
2794 VLIB_REGISTER_NODE (lisp_cp_lookup_ip4_node) = {
2795   .function = lisp_cp_lookup_ip4,
2796   .name = "lisp-cp-lookup-ip4",
2797   .vector_size = sizeof (u32),
2798   .format_trace = format_lisp_cp_lookup_trace,
2799   .type = VLIB_NODE_TYPE_INTERNAL,
2800
2801   .n_errors = LISP_CP_LOOKUP_N_ERROR,
2802   .error_strings = lisp_cp_lookup_error_strings,
2803
2804   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
2805
2806   .next_nodes = {
2807       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
2808   },
2809 };
2810 /* *INDENT-ON* */
2811
2812 /* *INDENT-OFF* */
2813 VLIB_REGISTER_NODE (lisp_cp_lookup_ip6_node) = {
2814   .function = lisp_cp_lookup_ip6,
2815   .name = "lisp-cp-lookup-ip6",
2816   .vector_size = sizeof (u32),
2817   .format_trace = format_lisp_cp_lookup_trace,
2818   .type = VLIB_NODE_TYPE_INTERNAL,
2819
2820   .n_errors = LISP_CP_LOOKUP_N_ERROR,
2821   .error_strings = lisp_cp_lookup_error_strings,
2822
2823   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
2824
2825   .next_nodes = {
2826       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
2827   },
2828 };
2829 /* *INDENT-ON* */
2830
2831 /* *INDENT-OFF* */
2832 VLIB_REGISTER_NODE (lisp_cp_lookup_l2_node) = {
2833   .function = lisp_cp_lookup_l2,
2834   .name = "lisp-cp-lookup-l2",
2835   .vector_size = sizeof (u32),
2836   .format_trace = format_lisp_cp_lookup_trace,
2837   .type = VLIB_NODE_TYPE_INTERNAL,
2838
2839   .n_errors = LISP_CP_LOOKUP_N_ERROR,
2840   .error_strings = lisp_cp_lookup_error_strings,
2841
2842   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
2843
2844   .next_nodes = {
2845       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
2846   },
2847 };
2848 /* *INDENT-ON* */
2849
2850 /* lisp_cp_input statistics */
2851 #define foreach_lisp_cp_input_error                               \
2852 _(DROP, "drop")                                                   \
2853 _(RLOC_PROBE_REQ_RECEIVED, "rloc-probe requests received")        \
2854 _(RLOC_PROBE_REP_RECEIVED, "rloc-probe replies received")         \
2855 _(MAP_NOTIFIES_RECEIVED, "map-notifies received")                 \
2856 _(MAP_REPLIES_RECEIVED, "map-replies received")
2857
2858 static char *lisp_cp_input_error_strings[] = {
2859 #define _(sym,string) string,
2860   foreach_lisp_cp_input_error
2861 #undef _
2862 };
2863
2864 typedef enum
2865 {
2866 #define _(sym,str) LISP_CP_INPUT_ERROR_##sym,
2867   foreach_lisp_cp_input_error
2868 #undef _
2869     LISP_CP_INPUT_N_ERROR,
2870 } lisp_cp_input_error_t;
2871
2872 typedef struct
2873 {
2874   gid_address_t dst_eid;
2875   ip4_address_t map_resolver_ip;
2876 } lisp_cp_input_trace_t;
2877
2878 u8 *
2879 format_lisp_cp_input_trace (u8 * s, va_list * args)
2880 {
2881   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
2882   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
2883   CLIB_UNUSED (lisp_cp_input_trace_t * t) =
2884     va_arg (*args, lisp_cp_input_trace_t *);
2885
2886   s = format (s, "LISP-CP-INPUT: TODO");
2887   return s;
2888 }
2889
2890 static void
2891 remove_expired_mapping (lisp_cp_main_t * lcm, u32 mi)
2892 {
2893   mapping_t *m;
2894   vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
2895   memset (adj_args, 0, sizeof (adj_args[0]));
2896
2897   m = pool_elt_at_index (lcm->mapping_pool, mi);
2898
2899   gid_address_copy (&adj_args->reid, &m->eid);
2900   adj_args->is_add = 0;
2901   if (vnet_lisp_add_del_adjacency (adj_args))
2902     clib_warning ("failed to del adjacency!");
2903
2904   vnet_lisp_add_del_mapping (&m->eid, 0, 0, 0, ~0, 0 /* is_add */ ,
2905                              0 /* is_static */ , 0);
2906   mapping_delete_timer (lcm, mi);
2907 }
2908
2909 static void
2910 mapping_start_expiration_timer (lisp_cp_main_t * lcm, u32 mi,
2911                                 f64 expiration_time)
2912 {
2913   mapping_t *m;
2914   u64 now = clib_cpu_time_now ();
2915   u64 cpu_cps = lcm->vlib_main->clib_time.clocks_per_second;
2916   u64 exp_clock_time = now + expiration_time * cpu_cps;
2917
2918   m = pool_elt_at_index (lcm->mapping_pool, mi);
2919
2920   m->timer_set = 1;
2921   timing_wheel_insert (&lcm->wheel, exp_clock_time, mi);
2922 }
2923
2924 static void
2925 map_records_arg_free (map_records_arg_t * a)
2926 {
2927   mapping_t *m;
2928   vec_foreach (m, a->mappings)
2929   {
2930     vec_free (m->locators);
2931     gid_address_free (&m->eid);
2932   }
2933
2934   clib_mem_free (a);
2935 }
2936
2937 void *
2938 process_map_reply (map_records_arg_t * a)
2939 {
2940   mapping_t *m;
2941   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2942   u32 dst_map_index = 0;
2943   pending_map_request_t *pmr;
2944   u64 *noncep;
2945   uword *pmr_index;
2946
2947   if (a->is_rloc_probe)
2948     goto done;
2949
2950   /* Check pending requests table and nonce */
2951   pmr_index = hash_get (lcm->pending_map_requests_by_nonce, a->nonce);
2952   if (!pmr_index)
2953     {
2954       clib_warning ("No pending map-request entry with nonce %lu!", a->nonce);
2955       goto done;
2956     }
2957   pmr = pool_elt_at_index (lcm->pending_map_requests_pool, pmr_index[0]);
2958
2959   vec_foreach (m, a->mappings)
2960   {
2961     /* insert/update mappings cache */
2962     vnet_lisp_add_del_mapping (&m->eid, m->locators, m->action,
2963                                m->authoritative, m->ttl,
2964                                1, 0 /* is_static */ , &dst_map_index);
2965
2966     if (dst_map_index == (u32) ~ 0)
2967       continue;
2968
2969     /* try to program forwarding only if mapping saved or updated */
2970     vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
2971     memset (adj_args, 0, sizeof (adj_args[0]));
2972
2973     gid_address_copy (&adj_args->leid, &pmr->src);
2974     gid_address_copy (&adj_args->reid, &m->eid);
2975     adj_args->is_add = 1;
2976     if (vnet_lisp_add_del_adjacency (adj_args))
2977       clib_warning ("failed to add adjacency!");
2978
2979     if ((u32) ~ 0 != m->ttl)
2980       mapping_start_expiration_timer (lcm, dst_map_index, m->ttl * 60);
2981   }
2982
2983   /* remove pending map request entry */
2984
2985   /* *INDENT-OFF* */
2986   clib_fifo_foreach (noncep, pmr->nonces, ({
2987     hash_unset(lcm->pending_map_requests_by_nonce, noncep[0]);
2988   }));
2989   /* *INDENT-ON* */
2990
2991   clib_fifo_free (pmr->nonces);
2992   pool_put (lcm->pending_map_requests_pool, pmr);
2993
2994 done:
2995   map_records_arg_free (a);
2996   return 0;
2997 }
2998
2999 static int
3000 is_auth_data_valid (map_notify_hdr_t * h, u32 msg_len,
3001                     lisp_key_type_t key_id, u8 * key)
3002 {
3003   u8 *auth_data = 0;
3004   u16 auth_data_len;
3005   int result;
3006
3007   auth_data_len = auth_data_len_by_key_id (key_id);
3008   if ((u16) ~ 0 == auth_data_len)
3009     {
3010       clib_warning ("invalid length for key_id %d!", key_id);
3011       return 0;
3012     }
3013
3014   /* save auth data */
3015   vec_validate (auth_data, auth_data_len - 1);
3016   clib_memcpy (auth_data, MNOTIFY_DATA (h), auth_data_len);
3017
3018   /* clear auth data */
3019   memset (MNOTIFY_DATA (h), 0, auth_data_len);
3020
3021   /* get hash of the message */
3022   unsigned char *code = HMAC (get_encrypt_fcn (key_id), key, vec_len (key),
3023                               (unsigned char *) h, msg_len, NULL, NULL);
3024
3025   result = memcmp (code, auth_data, auth_data_len);
3026
3027   vec_free (auth_data);
3028
3029   return !result;
3030 }
3031
3032 static void
3033 process_map_notify (map_records_arg_t * a)
3034 {
3035   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3036   uword *pmr_index;
3037
3038   pmr_index = hash_get (lcm->map_register_messages_by_nonce, a->nonce);
3039   if (!pmr_index)
3040     {
3041       clib_warning ("No pending map-register entry with nonce %lu!",
3042                     a->nonce);
3043       return;
3044     }
3045
3046   map_records_arg_free (a);
3047   hash_unset (lcm->map_register_messages_by_nonce, a->nonce);
3048 }
3049
3050 static mapping_t *
3051 get_mapping (lisp_cp_main_t * lcm, gid_address_t * e)
3052 {
3053   u32 mi;
3054
3055   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, e);
3056   if (~0 == mi)
3057     {
3058       clib_warning ("eid %U not found in map-cache!", unformat_gid_address,
3059                     e);
3060       return 0;
3061     }
3062   return pool_elt_at_index (lcm->mapping_pool, mi);
3063 }
3064
3065 /**
3066  * When map-notify is received it is necessary that all EIDs in the record
3067  * list share common key. The key is then used to verify authentication
3068  * data in map-notify message.
3069  */
3070 static int
3071 map_record_integrity_check (lisp_cp_main_t * lcm, mapping_t * maps,
3072                             u32 key_id, u8 ** key_out)
3073 {
3074   u32 i, len = vec_len (maps);
3075   mapping_t *m;
3076
3077   /* get key of the first mapping */
3078   m = get_mapping (lcm, &maps[0].eid);
3079   if (!m || !m->key)
3080     return -1;
3081
3082   key_out[0] = m->key;
3083
3084   for (i = 1; i < len; i++)
3085     {
3086       m = get_mapping (lcm, &maps[i].eid);
3087       if (!m || !m->key)
3088         return -1;
3089
3090       if (key_id != m->key_id || vec_cmp (m->key, key_out[0]))
3091         {
3092           clib_warning ("keys does not match! %v, %v", key_out[0], m->key);
3093           return -1;
3094         }
3095     }
3096   return 0;
3097 }
3098
3099 static int
3100 parse_map_records (vlib_buffer_t * b, map_records_arg_t * a, u8 count)
3101 {
3102   locator_t *locators = 0;
3103   u32 i, len;
3104   gid_address_t deid;
3105   mapping_t m;
3106   locator_t *loc;
3107
3108   /* parse record eid */
3109   for (i = 0; i < count; i++)
3110     {
3111       len = lisp_msg_parse_mapping_record (b, &deid, &locators, NULL);
3112       if (len == ~0)
3113         {
3114           clib_warning ("Failed to parse mapping record!");
3115           vec_foreach (loc, locators) locator_free (loc);
3116           vec_free (locators);
3117           return -1;
3118         }
3119
3120       m.locators = locators;
3121       gid_address_copy (&m.eid, &deid);
3122       vec_add1 (a->mappings, m);
3123     }
3124
3125   return 0;
3126 }
3127
3128 static map_records_arg_t *
3129 parse_map_notify (vlib_buffer_t * b)
3130 {
3131   int rc = 0;
3132   map_notify_hdr_t *mnotif_hdr;
3133   lisp_key_type_t key_id;
3134   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3135   u8 *key = 0;
3136   gid_address_t deid;
3137   u16 auth_data_len = 0;
3138   u8 record_count;
3139   map_records_arg_t *a = clib_mem_alloc (sizeof (*a));
3140
3141   memset (a, 0, sizeof (*a));
3142   mnotif_hdr = vlib_buffer_get_current (b);
3143   vlib_buffer_pull (b, sizeof (*mnotif_hdr));
3144   memset (&deid, 0, sizeof (deid));
3145
3146   a->nonce = MNOTIFY_NONCE (mnotif_hdr);
3147   key_id = clib_net_to_host_u16 (MNOTIFY_KEY_ID (mnotif_hdr));
3148   auth_data_len = auth_data_len_by_key_id (key_id);
3149
3150   /* advance buffer by authentication data */
3151   vlib_buffer_pull (b, auth_data_len);
3152
3153   record_count = MNOTIFY_REC_COUNT (mnotif_hdr);
3154   rc = parse_map_records (b, a, record_count);
3155   if (rc != 0)
3156     {
3157       map_records_arg_free (a);
3158       return 0;
3159     }
3160
3161   rc = map_record_integrity_check (lcm, a->mappings, key_id, &key);
3162   if (rc != 0)
3163     {
3164       map_records_arg_free (a);
3165       return 0;
3166     }
3167
3168   /* verify authentication data */
3169   if (!is_auth_data_valid (mnotif_hdr, vlib_buffer_get_tail (b)
3170                            - (u8 *) mnotif_hdr, key_id, key))
3171     {
3172       clib_warning ("Map-notify auth data verification failed for nonce %lu!",
3173                     a->nonce);
3174       map_records_arg_free (a);
3175       return 0;
3176     }
3177   return a;
3178 }
3179
3180 static vlib_buffer_t *
3181 build_map_reply (lisp_cp_main_t * lcm, ip_address_t * sloc,
3182                  ip_address_t * dst, u64 nonce, u8 probe_bit,
3183                  mapping_t * records, u16 dst_port, u32 * bi_res)
3184 {
3185   vlib_buffer_t *b;
3186   u32 bi;
3187   vlib_main_t *vm = lcm->vlib_main;
3188
3189   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
3190     {
3191       clib_warning ("Can't allocate buffer for Map-Register!");
3192       return 0;
3193     }
3194
3195   b = vlib_get_buffer (vm, bi);
3196
3197   /* leave some space for the encap headers */
3198   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
3199
3200   lisp_msg_put_map_reply (b, records, nonce, probe_bit);
3201
3202   /* push outer ip header */
3203   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, dst_port, sloc, dst);
3204
3205   bi_res[0] = bi;
3206   return b;
3207 }
3208
3209 static int
3210 send_map_reply (lisp_cp_main_t * lcm, u32 mi, ip_address_t * dst,
3211                 u8 probe_bit, u64 nonce, u16 dst_port,
3212                 ip_address_t * probed_loc)
3213 {
3214   ip_address_t src;
3215   u32 bi;
3216   vlib_buffer_t *b;
3217   vlib_frame_t *f;
3218   u32 next_index, *to_next;
3219   mapping_t *records = 0, *m;
3220
3221   m = pool_elt_at_index (lcm->mapping_pool, mi);
3222   if (!m)
3223     return -1;
3224
3225   vec_add1 (records, m[0]);
3226   add_locators (lcm, &records[0], m->locator_set_index, probed_loc);
3227   memset (&src, 0, sizeof (src));
3228
3229   if (!ip_fib_get_first_egress_ip_for_dst (lcm, dst, &src))
3230     {
3231       clib_warning ("can't find inteface address for %U", format_ip_address,
3232                     dst);
3233       return -1;
3234     }
3235
3236   b = build_map_reply (lcm, &src, dst, nonce, probe_bit, records, dst_port,
3237                        &bi);
3238   if (!b)
3239     return -1;
3240   free_map_register_records (records);
3241
3242   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
3243   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
3244     ip4_lookup_node.index : ip6_lookup_node.index;
3245
3246   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
3247
3248   /* Enqueue the packet */
3249   to_next = vlib_frame_vector_args (f);
3250   to_next[0] = bi;
3251   f->n_vectors = 1;
3252   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
3253   return 0;
3254 }
3255
3256 static void
3257 find_ip_header (vlib_buffer_t * b, u8 ** ip_hdr)
3258 {
3259   const i32 start = vnet_buffer (b)->ip.start_of_ip_header;
3260   if (start < 0 && start < -sizeof (b->pre_data))
3261     {
3262       *ip_hdr = 0;
3263       return;
3264     }
3265
3266   *ip_hdr = b->data + start;
3267   if ((u8 *) * ip_hdr > (u8 *) vlib_buffer_get_current (b))
3268     *ip_hdr = 0;
3269 }
3270
3271 void
3272 process_map_request (vlib_main_t * vm, vlib_node_runtime_t * node,
3273                      lisp_cp_main_t * lcm, vlib_buffer_t * b)
3274 {
3275   u8 *ip_hdr = 0;
3276   ip_address_t *dst_loc = 0, probed_loc, src_loc;
3277   mapping_t m;
3278   map_request_hdr_t *mreq_hdr;
3279   gid_address_t src, dst;
3280   u64 nonce;
3281   u32 i, len = 0, rloc_probe_recv = 0;
3282   gid_address_t *itr_rlocs = 0;
3283
3284   mreq_hdr = vlib_buffer_get_current (b);
3285   if (!MREQ_SMR (mreq_hdr) && !MREQ_RLOC_PROBE (mreq_hdr))
3286     {
3287       clib_warning
3288         ("Only SMR Map-Requests and RLOC probe supported for now!");
3289       return;
3290     }
3291
3292   vlib_buffer_pull (b, sizeof (*mreq_hdr));
3293   nonce = MREQ_NONCE (mreq_hdr);
3294
3295   /* parse src eid */
3296   len = lisp_msg_parse_addr (b, &src);
3297   if (len == ~0)
3298     return;
3299
3300   len = lisp_msg_parse_itr_rlocs (b, &itr_rlocs,
3301                                   MREQ_ITR_RLOC_COUNT (mreq_hdr) + 1);
3302   if (len == ~0)
3303     goto done;
3304
3305   /* parse eid records and send SMR-invoked map-requests */
3306   for (i = 0; i < MREQ_REC_COUNT (mreq_hdr); i++)
3307     {
3308       memset (&dst, 0, sizeof (dst));
3309       len = lisp_msg_parse_eid_rec (b, &dst);
3310       if (len == ~0)
3311         {
3312           clib_warning ("Can't parse map-request EID-record");
3313           goto done;
3314         }
3315
3316       if (MREQ_SMR (mreq_hdr))
3317         {
3318           /* send SMR-invoked map-requests */
3319           queue_map_request (&dst, &src, 1 /* invoked */ , 0 /* resend */ );
3320         }
3321       else if (MREQ_RLOC_PROBE (mreq_hdr))
3322         {
3323           find_ip_header (b, &ip_hdr);
3324           if (!ip_hdr)
3325             {
3326               clib_warning ("Cannot find the IP header!");
3327               goto done;
3328             }
3329           rloc_probe_recv++;
3330           memset (&m, 0, sizeof (m));
3331           u32 mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &dst);
3332
3333           // TODO: select best locator; for now use the first one
3334           dst_loc = &gid_address_ip (&itr_rlocs[0]);
3335
3336           /* get src/dst IP addresses */
3337           get_src_and_dst_ip (ip_hdr, &src_loc, &probed_loc);
3338
3339           // TODO get source port from buffer
3340           u16 src_port = LISP_CONTROL_PORT;
3341
3342           send_map_reply (lcm, mi, dst_loc, 1 /* probe-bit */ , nonce,
3343                           src_port, &probed_loc);
3344         }
3345     }
3346
3347 done:
3348   vlib_node_increment_counter (vm, node->node_index,
3349                                LISP_CP_INPUT_ERROR_RLOC_PROBE_REQ_RECEIVED,
3350                                rloc_probe_recv);
3351   vec_free (itr_rlocs);
3352 }
3353
3354 static map_records_arg_t *
3355 parse_map_reply (vlib_buffer_t * b)
3356 {
3357   locator_t probed;
3358   gid_address_t deid;
3359   void *h;
3360   u32 i, len = 0;
3361   mapping_t m;
3362   map_reply_hdr_t *mrep_hdr;
3363   map_records_arg_t *a = clib_mem_alloc (sizeof (*a));
3364   memset (a, 0, sizeof (*a));
3365   locator_t *locators;
3366
3367   mrep_hdr = vlib_buffer_get_current (b);
3368   a->nonce = MREP_NONCE (mrep_hdr);
3369   a->is_rloc_probe = MREP_RLOC_PROBE (mrep_hdr);
3370   vlib_buffer_pull (b, sizeof (*mrep_hdr));
3371
3372   for (i = 0; i < MREP_REC_COUNT (mrep_hdr); i++)
3373     {
3374       memset (&m, 0, sizeof (m));
3375       locators = 0;
3376       h = vlib_buffer_get_current (b);
3377
3378       m.ttl = clib_net_to_host_u32 (MAP_REC_TTL (h));
3379       m.action = MAP_REC_ACTION (h);
3380       m.authoritative = MAP_REC_AUTH (h);
3381
3382       len = lisp_msg_parse_mapping_record (b, &deid, &locators, &probed);
3383       if (len == ~0)
3384         {
3385           clib_warning ("Failed to parse mapping record!");
3386           map_records_arg_free (a);
3387           return 0;
3388         }
3389
3390       m.locators = locators;
3391       gid_address_copy (&m.eid, &deid);
3392       vec_add1 (a->mappings, m);
3393     }
3394   return a;
3395 }
3396
3397 static void
3398 queue_map_reply_for_processing (map_records_arg_t * a)
3399 {
3400   vl_api_rpc_call_main_thread (process_map_reply, (u8 *) a, sizeof (*a));
3401 }
3402
3403 static void
3404 queue_map_notify_for_processing (map_records_arg_t * a)
3405 {
3406   vl_api_rpc_call_main_thread (process_map_notify, (u8 *) a, sizeof (a[0]));
3407 }
3408
3409 static uword
3410 lisp_cp_input (vlib_main_t * vm, vlib_node_runtime_t * node,
3411                vlib_frame_t * from_frame)
3412 {
3413   u32 n_left_from, *from, *to_next_drop, rloc_probe_rep_recv = 0,
3414     map_notifies_recv = 0;
3415   lisp_msg_type_e type;
3416   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3417   map_records_arg_t *a;
3418
3419   from = vlib_frame_vector_args (from_frame);
3420   n_left_from = from_frame->n_vectors;
3421
3422
3423   while (n_left_from > 0)
3424     {
3425       u32 n_left_to_next_drop;
3426
3427       vlib_get_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
3428                            to_next_drop, n_left_to_next_drop);
3429       while (n_left_from > 0 && n_left_to_next_drop > 0)
3430         {
3431           u32 bi0;
3432           vlib_buffer_t *b0;
3433
3434           bi0 = from[0];
3435           from += 1;
3436           n_left_from -= 1;
3437           to_next_drop[0] = bi0;
3438           to_next_drop += 1;
3439           n_left_to_next_drop -= 1;
3440
3441           b0 = vlib_get_buffer (vm, bi0);
3442
3443           type = lisp_msg_type (vlib_buffer_get_current (b0));
3444           switch (type)
3445             {
3446             case LISP_MAP_REPLY:
3447               a = parse_map_reply (b0);
3448               if (a)
3449                 {
3450                   if (a->is_rloc_probe)
3451                     rloc_probe_rep_recv++;
3452                   queue_map_reply_for_processing (a);
3453                 }
3454               break;
3455             case LISP_MAP_REQUEST:
3456               process_map_request (vm, node, lcm, b0);
3457               break;
3458             case LISP_MAP_NOTIFY:
3459               a = parse_map_notify (b0);
3460               if (a)
3461                 {
3462                   map_notifies_recv++;
3463                   queue_map_notify_for_processing (a);
3464                 }
3465               break;
3466             default:
3467               clib_warning ("Unsupported LISP message type %d", type);
3468               break;
3469             }
3470
3471           b0->error = node->errors[LISP_CP_INPUT_ERROR_DROP];
3472
3473           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
3474             {
3475
3476             }
3477         }
3478
3479       vlib_put_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
3480                            n_left_to_next_drop);
3481     }
3482   vlib_node_increment_counter (vm, node->node_index,
3483                                LISP_CP_INPUT_ERROR_RLOC_PROBE_REP_RECEIVED,
3484                                rloc_probe_rep_recv);
3485   vlib_node_increment_counter (vm, node->node_index,
3486                                LISP_CP_INPUT_ERROR_MAP_NOTIFIES_RECEIVED,
3487                                map_notifies_recv);
3488   return from_frame->n_vectors;
3489 }
3490
3491 /* *INDENT-OFF* */
3492 VLIB_REGISTER_NODE (lisp_cp_input_node) = {
3493   .function = lisp_cp_input,
3494   .name = "lisp-cp-input",
3495   .vector_size = sizeof (u32),
3496   .format_trace = format_lisp_cp_input_trace,
3497   .type = VLIB_NODE_TYPE_INTERNAL,
3498
3499   .n_errors = LISP_CP_INPUT_N_ERROR,
3500   .error_strings = lisp_cp_input_error_strings,
3501
3502   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
3503
3504   .next_nodes = {
3505       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
3506   },
3507 };
3508 /* *INDENT-ON* */
3509
3510 clib_error_t *
3511 lisp_cp_init (vlib_main_t * vm)
3512 {
3513   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3514   clib_error_t *error = 0;
3515
3516   if ((error = vlib_call_init_function (vm, lisp_gpe_init)))
3517     return error;
3518
3519   lcm->im4 = &ip4_main;
3520   lcm->im6 = &ip6_main;
3521   lcm->vlib_main = vm;
3522   lcm->vnet_main = vnet_get_main ();
3523   lcm->mreq_itr_rlocs = ~0;
3524   lcm->lisp_pitr = 0;
3525   lcm->flags = 0;
3526   memset (&lcm->active_map_resolver, 0, sizeof (lcm->active_map_resolver));
3527
3528   gid_dictionary_init (&lcm->mapping_index_by_gid);
3529   lcm->do_map_resolver_election = 1;
3530   lcm->map_request_mode = MR_MODE_DST_ONLY;
3531
3532   /* default vrf mapped to vni 0 */
3533   hash_set (lcm->table_id_by_vni, 0, 0);
3534   hash_set (lcm->vni_by_table_id, 0, 0);
3535
3536   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp,
3537                          lisp_cp_input_node.index, 1 /* is_ip4 */ );
3538   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp6,
3539                          lisp_cp_input_node.index, 0 /* is_ip4 */ );
3540
3541   u64 now = clib_cpu_time_now ();
3542   timing_wheel_init (&lcm->wheel, now, vm->clib_time.clocks_per_second);
3543   return 0;
3544 }
3545
3546 static void *
3547 send_map_request_thread_fn (void *arg)
3548 {
3549   map_request_args_t *a = arg;
3550   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3551
3552   if (a->is_resend)
3553     resend_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
3554   else
3555     send_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
3556
3557   return 0;
3558 }
3559
3560 static int
3561 queue_map_request (gid_address_t * seid, gid_address_t * deid,
3562                    u8 smr_invoked, u8 is_resend)
3563 {
3564   map_request_args_t a;
3565
3566   a.is_resend = is_resend;
3567   gid_address_copy (&a.seid, seid);
3568   gid_address_copy (&a.deid, deid);
3569   a.smr_invoked = smr_invoked;
3570
3571   vl_api_rpc_call_main_thread (send_map_request_thread_fn,
3572                                (u8 *) & a, sizeof (a));
3573   return 0;
3574 }
3575
3576 /**
3577  * Take an action with a pending map request depending on expiration time
3578  * and re-try counters.
3579  */
3580 static void
3581 update_pending_request (pending_map_request_t * r, f64 dt)
3582 {
3583   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3584   lisp_msmr_t *mr;
3585
3586   if (r->time_to_expire - dt < 0)
3587     /* it's time to decide what to do with this pending request */
3588     {
3589       if (r->retries_num >= NUMBER_OF_RETRIES)
3590         /* too many retries -> assume current map resolver is not available */
3591         {
3592           mr = get_map_resolver (&lcm->active_map_resolver);
3593           if (!mr)
3594             {
3595               clib_warning ("Map resolver %U not found - probably deleted "
3596                             "by the user recently.", format_ip_address,
3597                             &lcm->active_map_resolver);
3598             }
3599           else
3600             {
3601               clib_warning ("map resolver %U is unreachable, ignoring",
3602                             format_ip_address, &lcm->active_map_resolver);
3603
3604               /* mark current map resolver unavailable so it won't be
3605                * selected next time */
3606               mr->is_down = 1;
3607               mr->last_update = vlib_time_now (lcm->vlib_main);
3608             }
3609
3610           reset_pending_mr_counters (r);
3611           elect_map_resolver (lcm);
3612
3613           /* try to find a next eligible map resolver and re-send */
3614           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
3615                              1 /* resend */ );
3616         }
3617       else
3618         {
3619           /* try again */
3620           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
3621                              1 /* resend */ );
3622           r->retries_num++;
3623           r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
3624         }
3625     }
3626   else
3627     r->time_to_expire -= dt;
3628 }
3629
3630 static void
3631 remove_dead_pending_map_requests (lisp_cp_main_t * lcm)
3632 {
3633   u64 *nonce;
3634   pending_map_request_t *pmr;
3635   u32 *to_be_removed = 0, *pmr_index;
3636
3637   /* *INDENT-OFF* */
3638   pool_foreach (pmr, lcm->pending_map_requests_pool,
3639   ({
3640     if (pmr->to_be_removed)
3641       {
3642         clib_fifo_foreach (nonce, pmr->nonces, ({
3643           hash_unset (lcm->pending_map_requests_by_nonce, nonce[0]);
3644         }));
3645
3646         vec_add1 (to_be_removed, pmr - lcm->pending_map_requests_pool);
3647       }
3648   }));
3649   /* *INDENT-ON* */
3650
3651   vec_foreach (pmr_index, to_be_removed)
3652     pool_put_index (lcm->pending_map_requests_by_nonce, pmr_index[0]);
3653
3654   vec_free (to_be_removed);
3655 }
3656
3657 static void
3658 update_rloc_probing (lisp_cp_main_t * lcm, f64 dt)
3659 {
3660   static f64 time_left = RLOC_PROBING_INTERVAL;
3661
3662   if (!lcm->is_enabled || !lcm->rloc_probing)
3663     return;
3664
3665   time_left -= dt;
3666   if (time_left <= 0)
3667     {
3668       time_left = RLOC_PROBING_INTERVAL;
3669       send_rloc_probes (lcm);
3670     }
3671 }
3672
3673 static void
3674 update_map_register (lisp_cp_main_t * lcm, f64 dt)
3675 {
3676   static f64 time_left = QUICK_MAP_REGISTER_INTERVAL;
3677   static u64 mreg_sent_counter = 0;
3678
3679   if (!lcm->is_enabled || !lcm->map_registering)
3680     return;
3681
3682   time_left -= dt;
3683   if (time_left <= 0)
3684     {
3685       if (mreg_sent_counter >= QUICK_MAP_REGISTER_MSG_COUNT)
3686         time_left = MAP_REGISTER_INTERVAL;
3687       else
3688         {
3689           mreg_sent_counter++;
3690           time_left = QUICK_MAP_REGISTER_INTERVAL;
3691         }
3692       send_map_register (lcm, 1 /* want map notify */ );
3693     }
3694 }
3695
3696 static uword
3697 send_map_resolver_service (vlib_main_t * vm,
3698                            vlib_node_runtime_t * rt, vlib_frame_t * f)
3699 {
3700   u32 *expired = 0;
3701   f64 period = 2.0;
3702   pending_map_request_t *pmr;
3703   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3704
3705   while (1)
3706     {
3707       vlib_process_wait_for_event_or_clock (vm, period);
3708
3709       /* currently no signals are expected - just wait for clock */
3710       (void) vlib_process_get_events (vm, 0);
3711
3712       /* *INDENT-OFF* */
3713       pool_foreach (pmr, lcm->pending_map_requests_pool,
3714       ({
3715         if (!pmr->to_be_removed)
3716           update_pending_request (pmr, period);
3717       }));
3718       /* *INDENT-ON* */
3719
3720       remove_dead_pending_map_requests (lcm);
3721
3722       update_map_register (lcm, period);
3723       update_rloc_probing (lcm, period);
3724
3725       u64 now = clib_cpu_time_now ();
3726
3727       expired = timing_wheel_advance (&lcm->wheel, now, expired, 0);
3728       if (vec_len (expired) > 0)
3729         {
3730           u32 *mi = 0;
3731           vec_foreach (mi, expired)
3732           {
3733             remove_expired_mapping (lcm, mi[0]);
3734           }
3735           _vec_len (expired) = 0;
3736         }
3737     }
3738
3739   /* unreachable */
3740   return 0;
3741 }
3742
3743 /* *INDENT-OFF* */
3744 VLIB_REGISTER_NODE (lisp_retry_service_node,static) = {
3745     .function = send_map_resolver_service,
3746     .type = VLIB_NODE_TYPE_PROCESS,
3747     .name = "lisp-retry-service",
3748     .process_log2_n_stack_bytes = 16,
3749 };
3750 /* *INDENT-ON* */
3751
3752 VLIB_INIT_FUNCTION (lisp_cp_init);
3753
3754 /*
3755  * fd.io coding-style-patch-verification: ON
3756  *
3757  * Local Variables:
3758  * eval: (c-set-style "gnu")
3759  * End:
3760  */