ONE-14: Fix crash when re-enable Lisp
[vpp.git] / vnet / 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 <vnet/lisp-cp/control.h>
17 #include <vnet/lisp-cp/packets.h>
18 #include <vnet/lisp-cp/lisp_msg_serdes.h>
19 #include <vnet/lisp-gpe/lisp_gpe.h>
20
21 static void
22 add_fwd_entry (lisp_cp_main_t* lcm, u32 src_map_index, u32 dst_map_index);
23
24 static void
25 del_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index, u32 dst_map_index);
26
27 static u8
28 compare_locators (lisp_cp_main_t *lcm, u32 * old_ls_indexes,
29                   locator_t * new_locators);
30
31 /* Stores mapping in map-cache. It does NOT program data plane forwarding for
32  * remote/learned mappings. */
33 int
34 vnet_lisp_add_del_mapping (vnet_lisp_add_del_mapping_args_t * a,
35                            u32 * map_index_result)
36 {
37   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
38   u32 mi, * map_indexp, map_index, i;
39   mapping_t * m, * old_map;
40   u32 ** eid_indexes;
41
42   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &a->deid);
43   old_map = mi != ~0 ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
44   if (a->is_add)
45     {
46       /* TODO check if overwriting and take appropriate actions */
47       if (mi != GID_LOOKUP_MISS && !gid_address_cmp (&old_map->eid,
48                                                      &a->deid))
49         {
50           clib_warning("eid %U found in the eid-table", format_ip_address,
51                        &a->deid);
52           return VNET_API_ERROR_VALUE_EXIST;
53         }
54
55       pool_get(lcm->mapping_pool, m);
56       m->eid = a->deid;
57       m->locator_set_index = a->locator_set_index;
58       m->ttl = a->ttl;
59       m->action = a->action;
60       m->local = a->local;
61
62       map_index = m - lcm->mapping_pool;
63       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->deid, map_index,
64                               1);
65
66       if (pool_is_free_index(lcm->locator_set_pool, a->locator_set_index))
67         {
68           clib_warning("Locator set with index %d doesn't exist",
69                        a->locator_set_index);
70           return VNET_API_ERROR_INVALID_VALUE;
71         }
72
73       /* add eid to list of eids supported by locator-set */
74       vec_validate (lcm->locator_set_to_eids, a->locator_set_index);
75       eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids,
76                                      a->locator_set_index);
77       vec_add1(eid_indexes[0], map_index);
78
79       if (a->local)
80         {
81           /* mark as local */
82           vec_add1(lcm->local_mappings_indexes, map_index);
83         }
84       map_index_result[0] = map_index;
85     }
86   else
87     {
88       if (mi == GID_LOOKUP_MISS)
89         {
90           clib_warning("eid %U not found in the eid-table", format_ip_address,
91                        &a->deid);
92           return VNET_API_ERROR_INVALID_VALUE;
93         }
94
95       /* clear locator-set to eids binding */
96       eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids,
97                                      a->locator_set_index);
98       for (i = 0; i < vec_len(eid_indexes[0]); i++)
99         {
100           map_indexp = vec_elt_at_index(eid_indexes[0], i);
101           if (map_indexp[0] == mi)
102               break;
103         }
104       vec_del1(eid_indexes[0], i);
105
106       /* remove local mark if needed */
107       m = pool_elt_at_index(lcm->mapping_pool, mi);
108       if (m->local)
109         {
110           u32 k, * lm_indexp;
111           for (k = 0; k < vec_len(lcm->local_mappings_indexes); k++)
112             {
113               lm_indexp = vec_elt_at_index(lcm->local_mappings_indexes, k);
114               if (lm_indexp[0] == mi)
115                 break;
116             }
117           vec_del1(lcm->local_mappings_indexes, k);
118         }
119       else
120         {
121           /* remove tunnel ??? */
122         }
123
124       /* remove mapping from dictionary */
125       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->deid, 0, 0);
126       pool_put_index (lcm->mapping_pool, mi);
127     }
128
129   return 0;
130 }
131
132 /* Stores mapping in map-cache and programs data plane for local mappings. */
133 int
134 vnet_lisp_add_del_local_mapping (vnet_lisp_add_del_mapping_args_t * a,
135                                  u32 * map_index_result)
136 {
137   uword * table_id, * refc;
138   u32 rv, vni;
139   vnet_lisp_gpe_add_del_iface_args_t _ai, *ai = &_ai;
140   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
141
142   vni = gid_address_vni(&a->deid);
143
144   /* store/remove mapping from map-cache */
145   rv = vnet_lisp_add_del_mapping (a, map_index_result);
146   if (rv)
147     return rv;
148
149   table_id = hash_get(lcm->table_id_by_vni, vni);
150
151   if (!table_id)
152     {
153       clib_warning ("vni %d not associated to a vrf!", vni);
154       return VNET_API_ERROR_INVALID_VALUE;
155     }
156
157   refc = hash_get(lcm->dp_if_refcount_by_vni, vni);
158
159   /* enable/disable data-plane interface */
160   if (a->is_add)
161     {
162       /* create interface or update refcount */
163       if (!refc)
164         {
165           ai->is_add = 1;
166           ai->vni = vni;
167           ai->table_id = table_id[0];
168           vnet_lisp_gpe_add_del_iface (ai, 0);
169
170           /* counts the number of eids in a vni that use the interface */
171           hash_set(lcm->dp_if_refcount_by_vni, vni, 1);
172         }
173       else
174         {
175           refc[0]++;
176         }
177     }
178   else
179     {
180       /* since this is a remove for an existing eid, the iface should exist */
181       ASSERT(refc != 0);
182       refc[0]--;
183
184       /* remove iface if needed */
185       if (refc[0] == 0)
186         {
187           ai->is_add = 0;
188           ai->vni = vni;
189           ai->table_id = table_id[0];
190           vnet_lisp_gpe_add_del_iface (ai, 0);
191           hash_unset (lcm->dp_if_refcount_by_vni, vni);
192         }
193     }
194
195   return rv;
196 }
197
198 static clib_error_t *
199 lisp_add_del_local_eid_command_fn (vlib_main_t * vm, unformat_input_t * input,
200                                    vlib_cli_command_t * cmd)
201 {
202   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
203   unformat_input_t _line_input, * line_input = &_line_input;
204   u8 is_add = 1;
205   gid_address_t eid;
206   ip_prefix_t * prefp = &gid_address_ippref(&eid);
207   gid_address_t * eids = 0;
208   clib_error_t * error = 0;
209   u8 * locator_set_name = 0;
210   u32 locator_set_index = 0, map_index = 0;
211   uword * p;
212   vnet_lisp_add_del_mapping_args_t _a, * a = &_a;
213
214   gid_address_type (&eid) = GID_ADDR_IP_PREFIX;
215
216   /* Get a line of input. */
217   if (! unformat_user (input, unformat_line_input, line_input))
218     return 0;
219
220   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
221     {
222       if (unformat (line_input, "add"))
223         is_add = 1;
224       else if (unformat (line_input, "del"))
225         is_add = 0;
226       else if (unformat (line_input, "eid %U", unformat_ip_prefix, prefp))
227         {
228           vec_add1(eids, eid);
229         }
230       else if (unformat (line_input, "locator-set %_%v%_", &locator_set_name))
231         {
232           p = hash_get_mem(lcm->locator_set_index_by_name, locator_set_name);
233           if (!p)
234             {
235               error = clib_error_return(0, "locator-set %s doesn't exist",
236                                         locator_set_name);
237               goto done;
238             }
239           locator_set_index = p[0];
240         }
241       else
242         {
243           error = unformat_parse_error(line_input);
244           goto done;
245         }
246     }
247
248   /* XXX treat batch configuration */
249   a->deid = eid;
250   a->is_add = is_add;
251   a->locator_set_index = locator_set_index;
252   a->local = 1;
253
254   vnet_lisp_add_del_local_mapping (a, &map_index);
255  done:
256   vec_free(eids);
257   if (locator_set_name)
258     vec_free (locator_set_name);
259   return error;
260 }
261
262 VLIB_CLI_COMMAND (lisp_add_del_local_eid_command) = {
263     .path = "lisp eid-table",
264     .short_help = "lisp eid-table add/del eid <eid> locator-set <locator-set>",
265     .function = lisp_add_del_local_eid_command_fn,
266 };
267
268 static int
269 lisp_add_del_negative_static_mapping (gid_address_t * deid,
270     vnet_lisp_add_del_locator_set_args_t * ls, u8 action, u8 is_add)
271 {
272   uword * p;
273   mapping_t * map;
274   u32 mi = ~0;
275   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
276   uword * refc;
277   vnet_lisp_add_del_mapping_args_t _dm_args, * dm_args = &_dm_args;
278   int rv = 0;
279   u32 ls_index = 0, dst_map_index;
280   vnet_lisp_gpe_add_del_iface_args_t _ai, *ai = &_ai;
281
282   memset (dm_args, 0, sizeof (dm_args[0]));
283   u32 vni = gid_address_vni (deid);
284   refc = hash_get (lcm->dp_if_refcount_by_vni, vni);
285
286   p = hash_get (lcm->table_id_by_vni, vni);
287   if (!p)
288     {
289       clib_warning ("vni %d not associated to a vrf!", vni);
290       return VNET_API_ERROR_INVALID_VALUE;
291     }
292
293   if (is_add)
294     {
295       vnet_lisp_add_del_locator_set (ls, &ls_index);
296       /* add mapping */
297       gid_address_copy (&dm_args->deid, deid);
298       dm_args->is_add = 1;
299       dm_args->action = action;
300       dm_args->locator_set_index = ls_index;
301
302       /* create interface or update refcount */
303       if (!refc)
304         {
305           vnet_lisp_gpe_add_del_iface_args_t _ai, *ai = &_ai;
306           ai->is_add = 1;
307           ai->vni = vni;
308           ai->table_id = p[0];
309           vnet_lisp_gpe_add_del_iface (ai, 0);
310
311           /* counts the number of eids in a vni that use the interface */
312           hash_set (lcm->dp_if_refcount_by_vni, vni, 1);
313         }
314       else
315         refc[0]++;
316
317       rv = vnet_lisp_add_del_local_mapping (dm_args, &dst_map_index);
318       if (!rv)
319         add_fwd_entry (lcm, lcm->pitr_map_index, dst_map_index);
320     }
321   else
322     {
323       mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, deid);
324       if ((u32)~0 == mi)
325         {
326           clib_warning ("eid %U marked for removal, but not found in "
327                         "map-cache!", unformat_gid_address, deid);
328           return VNET_API_ERROR_INVALID_VALUE;
329         }
330
331       /* delete forwarding entry */
332       del_fwd_entry (lcm, 0, mi);
333
334       dm_args->is_add = 0;
335       gid_address_copy (&dm_args->deid, deid);
336       map = pool_elt_at_index (lcm->mapping_pool, mi);
337       dm_args->locator_set_index = map->locator_set_index;
338
339       /* delete mapping associated to fwd entry */
340       vnet_lisp_add_del_mapping (dm_args, 0);
341
342       refc = hash_get (lcm->dp_if_refcount_by_vni, vni);
343       ASSERT(refc != 0);
344       refc[0]--;
345
346       /* remove iface if needed */
347       if (refc[0] == 0)
348         {
349           ai->is_add = 0;
350           ai->vni = vni;
351           ai->table_id = p[0];
352           vnet_lisp_gpe_add_del_iface (ai, 0);
353           hash_unset (lcm->dp_if_refcount_by_vni, vni);
354         }
355     }
356   return rv;
357 }
358
359 /**
360  * Adds/removes/updates static remote mapping.
361  *
362  * This function also modifies forwarding entries if needed.
363  *
364  * @param deid destination EID
365  * @param seid source EID
366  * @param rlocs vector of remote locators
367  * @param action action for negative map-reply
368  * @param is_add add mapping if non-zero, delete otherwise
369  * @return return code
370  */
371 int
372 vnet_lisp_add_del_remote_mapping (gid_address_t * deid, gid_address_t * seid,
373                                   ip_address_t * rlocs, u8 action, u8 is_add)
374 {
375   vnet_lisp_add_del_mapping_args_t _dm_args, * dm_args = &_dm_args;
376   vnet_lisp_add_del_mapping_args_t _sm_args, * sm_args = &_sm_args;
377   vnet_lisp_add_del_locator_set_args_t _ls, * ls = &_ls;
378   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
379   u32 mi, ls_index = 0, dst_map_index, src_map_index;
380   locator_t loc;
381   ip_address_t * dl;
382   int rc = -1;
383
384   memset (sm_args, 0, sizeof (sm_args[0]));
385   memset (dm_args, 0, sizeof (dm_args[0]));
386   memset (ls, 0, sizeof (ls[0]));
387
388   /* prepare remote locator set */
389   vec_foreach (dl, rlocs)
390     {
391       memset (&loc, 0, sizeof (loc));
392       gid_address_ip (&loc.address) = dl[0];
393       vec_add1 (ls->locators, loc);
394     }
395   src_map_index = gid_dictionary_lookup (&lcm->mapping_index_by_gid, seid);
396
397   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, deid);
398   /* new mapping */
399   if ((u32)~0 == mi)
400     {
401       ls->is_add = 1;
402       ls->index = ~0;
403
404       /* process a negative mapping */
405       if (0 == vec_len (rlocs))
406         return lisp_add_del_negative_static_mapping (deid, ls,
407                                                      action, is_add);
408
409       if ((u32)~0 == src_map_index)
410         {
411           clib_warning ("seid %U not found!", format_gid_address, seid);
412           goto done;
413         }
414
415       if (!is_add)
416         {
417           clib_warning ("deid %U marked for removal but not "
418                         "found!", format_gid_address, deid);
419           goto done;
420         }
421
422       vnet_lisp_add_del_locator_set (ls, &ls_index);
423
424       /* add mapping */
425       gid_address_copy (&dm_args->deid, deid);
426       dm_args->is_add = 1;
427       dm_args->action = action;
428       dm_args->locator_set_index = ls_index;
429       vnet_lisp_add_del_mapping (dm_args, &dst_map_index);
430
431       /* add fwd tunnel */
432       add_fwd_entry (lcm, src_map_index, dst_map_index);
433     }
434   else
435     {
436       /* delete mapping */
437       if (!is_add)
438         {
439           /* delete forwarding entry */
440           del_fwd_entry (lcm, 0, mi);
441           dm_args->is_add = 0;
442           gid_address_copy (&dm_args->deid, deid);
443           mapping_t * map = pool_elt_at_index (lcm->mapping_pool, mi);
444           dm_args->locator_set_index = map->locator_set_index;
445
446           /* delete mapping associated to fwd entry */
447           vnet_lisp_add_del_mapping (dm_args, 0);
448
449           ls->is_add = 0;
450           ls->index = map->locator_set_index;
451           /* delete locator set */
452           vnet_lisp_add_del_locator_set (ls, 0);
453         }
454       /* update existing locator set */
455       else
456         {
457           if ((u32)~0 == src_map_index)
458             {
459               clib_warning ("seid %U not found!", format_gid_address, seid);
460               goto done;
461             }
462
463           mapping_t * old_map;
464           locator_set_t * old_ls;
465           old_map = pool_elt_at_index (lcm->mapping_pool, mi);
466
467           /* update mapping attributes */
468           old_map->action = action;
469
470           old_ls = pool_elt_at_index(lcm->locator_set_pool,
471                                      old_map->locator_set_index);
472           if (compare_locators (lcm, old_ls->locator_indices,
473                                 ls->locators))
474             {
475               /* set locator-set index to overwrite */
476               ls->is_add = 1;
477               ls->index = old_map->locator_set_index;
478               vnet_lisp_add_del_locator_set (ls, 0);
479               add_fwd_entry (lcm, src_map_index, mi);
480             }
481         }
482     }
483   /* success */
484   rc = 0;
485 done:
486   vec_free (ls->locators);
487   return rc;
488 }
489
490 /**
491  * Handler for add/del remote mapping CLI.
492  *
493  * @param vm vlib context
494  * @param input input from user
495  * @param cmd cmd
496  * @return pointer to clib error structure
497  */
498 static clib_error_t *
499 lisp_add_del_remote_mapping_command_fn (vlib_main_t * vm,
500                                         unformat_input_t * input,
501                                         vlib_cli_command_t * cmd)
502 {
503   clib_error_t * error = 0;
504   unformat_input_t _line_input, * line_input = &_line_input;
505   u8 is_add = 1;
506   ip_address_t rloc, * rlocs = 0;
507   ip_prefix_t * deid_ippref, * seid_ippref;
508   gid_address_t seid, deid;
509   u8 deid_set = 0;
510   u8 * s = 0;
511   u32 vni, action = ~0;
512
513   /* Get a line of input. */
514   if (! unformat_user (input, unformat_line_input, line_input))
515     return 0;
516
517   memset (&deid, 0, sizeof (deid));
518   memset (&seid, 0, sizeof (seid));
519
520   seid_ippref = &gid_address_ippref(&seid);
521   deid_ippref = &gid_address_ippref(&deid);
522
523   gid_address_type (&deid) = GID_ADDR_IP_PREFIX;
524   gid_address_type (&seid) = GID_ADDR_IP_PREFIX;
525
526   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
527     {
528       if (unformat (line_input, "del"))
529         is_add = 0;
530       if (unformat (line_input, "add"))
531         ;
532       else if (unformat (line_input, "deid %U",
533                          unformat_ip_prefix, deid_ippref))
534         {
535           deid_set = 1;
536         }
537       else if (unformat (line_input, "vni %u", &vni))
538         {
539           gid_address_set_vni (&seid, vni);
540           gid_address_set_vni (&deid, vni);
541         }
542       else if (unformat (line_input, "seid %U",
543                          unformat_ip_prefix, seid_ippref))
544         ;
545       else if (unformat (line_input, "rloc %U", unformat_ip_address, &rloc))
546         vec_add1 (rlocs, rloc);
547       else if (unformat (line_input, "action %s", &s))
548         {
549           if (!strcmp ((char *)s, "no-action"))
550             action = ACTION_NONE;
551           if (!strcmp ((char *)s, "natively-forward"))
552             action = ACTION_NATIVELY_FORWARDED;
553           if (!strcmp ((char *)s, "send-map-request"))
554             action = ACTION_SEND_MAP_REQUEST;
555           else if (!strcmp ((char *)s, "drop"))
556             action = ACTION_DROP;
557           else
558             {
559               clib_warning ("invalid action: '%s'", s);
560               goto done;
561             }
562         }
563       else
564         {
565           clib_warning ("parse error");
566           goto done;
567         }
568     }
569
570   if (!deid_set)
571     {
572       clib_warning ("missing deid!");
573       goto done;
574     }
575
576   if (is_add
577       && (ip_prefix_version (deid_ippref)
578         != ip_prefix_version (seid_ippref)))
579     {
580       clib_warning ("source and destination EIDs are not"
581                     " in the same IP family!");
582       goto done;
583     }
584
585   if (is_add && (~0 == action)
586       && 0 == vec_len (rlocs))
587     {
588       clib_warning ("no action set for negative map-reply!");
589       goto done;
590     }
591
592   int rv = vnet_lisp_add_del_remote_mapping (&deid, &seid, rlocs,
593                                              action, is_add);
594   if (rv)
595     clib_warning ("failed to %s remote mapping!",
596                   is_add ? "add" : "delete");
597
598 done:
599   unformat_free (line_input);
600   if (s)
601     vec_free (s);
602   return error;
603 }
604
605 VLIB_CLI_COMMAND (lisp_add_del_remote_mapping_command) = {
606     .path = "lisp remote-mapping",
607     .short_help = "lisp remote-mapping add|del vni <vni>"
608      "deid <dest-eid> seid <src-eid> [action <no-action|natively-forward|"
609      "send-map-request|drop>] rloc <dst-locator> [rloc <dst-locator> ... ]",
610     .function = lisp_add_del_remote_mapping_command_fn,
611 };
612
613 int
614 vnet_lisp_pitr_set_locator_set (u8 * locator_set_name, u8 is_add)
615 {
616   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
617   u32 locator_set_index = ~0;
618   mapping_t * m;
619   uword * p;
620
621   p = hash_get_mem (lcm->locator_set_index_by_name, locator_set_name);
622   if (!p)
623     {
624       clib_warning ("locator-set %v doesn't exist", locator_set_name);
625       return -1;
626     }
627   locator_set_index = p[0];
628
629   if (is_add)
630     {
631       pool_get (lcm->mapping_pool, m);
632       m->locator_set_index = locator_set_index;
633       m->local = 1;
634       lcm->pitr_map_index = m - lcm->mapping_pool;
635
636       /* enable pitr mode */
637       lcm->lisp_pitr = 1;
638     }
639   else
640     {
641       /* remove pitr mapping */
642       pool_put_index (lcm->mapping_pool, lcm->pitr_map_index);
643
644       /* disable pitr mode */
645       lcm->lisp_pitr = 0;
646     }
647   return 0;
648 }
649
650 static clib_error_t *
651 lisp_pitr_set_locator_set_command_fn (vlib_main_t * vm,
652                                       unformat_input_t * input,
653                                       vlib_cli_command_t * cmd)
654 {
655   u8 locator_name_set = 0;
656   u8 * locator_set_name = 0;
657   u8 is_add = 1;
658   unformat_input_t _line_input, * line_input = &_line_input;
659
660   /* Get a line of input. */
661   if (! unformat_user (input, unformat_line_input, line_input))
662     return 0;
663
664   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
665     {
666       if (unformat (line_input, "ls %_%v%_", &locator_set_name))
667         locator_name_set = 1;
668       else if (unformat (line_input, "disable"))
669         is_add = 0;
670       else
671         return clib_error_return (0, "parse error");
672     }
673
674   if (!locator_name_set)
675     {
676       clib_warning ("No locator set specified!");
677       goto done;
678     }
679   vnet_lisp_pitr_set_locator_set (locator_set_name, is_add);
680
681 done:
682   if (locator_set_name)
683     vec_free (locator_set_name);
684   return 0;
685 }
686
687 VLIB_CLI_COMMAND (lisp_pitr_set_locator_set_command) = {
688     .path = "lisp pitr",
689     .short_help = "lisp pitr [disable] ls <locator-set-name>",
690     .function = lisp_pitr_set_locator_set_command_fn,
691 };
692
693 static clib_error_t *
694 lisp_show_local_eid_table_command_fn (vlib_main_t * vm,
695                                       unformat_input_t * input,
696                                       vlib_cli_command_t * cmd)
697 {
698   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
699   mapping_t * mapit;
700
701   vlib_cli_output (vm, "%=20s%=16s", "EID", "Locator");
702   pool_foreach (mapit, lcm->mapping_pool,
703   ({
704     u8 * msg = 0;
705     locator_set_t * ls = pool_elt_at_index (lcm->locator_set_pool,
706                                             mapit->locator_set_index);
707     vlib_cli_output (vm, "%-16U%16v", format_gid_address, &mapit->eid,
708                      ls->name);
709     vec_free (msg);
710   }));
711
712   return 0;
713 }
714
715 VLIB_CLI_COMMAND (lisp_cp_show_local_eid_table_command) = {
716     .path = "show lisp eid-table",
717     .short_help = "Shows local EID table",
718     .function = lisp_show_local_eid_table_command_fn,
719 };
720
721 /* cleans locator to locator-set data and removes locators not part of
722  * any locator-set */
723 static void
724 clean_locator_to_locator_set (lisp_cp_main_t * lcm, u32 lsi)
725 {
726   u32 i, j, *loc_indexp, *ls_indexp, **ls_indexes;
727   locator_set_t * ls = pool_elt_at_index(lcm->locator_set_pool, lsi);
728   for (i = 0; i < vec_len(ls->locator_indices); i++)
729     {
730       loc_indexp = vec_elt_at_index(ls->locator_indices, i);
731       ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
732                                     loc_indexp[0]);
733       for (j = 0; j < vec_len(ls_indexes[0]); j++)
734         {
735           ls_indexp = vec_elt_at_index(ls_indexes[0], j);
736           if (ls_indexp[0] == lsi)
737             break;
738         }
739
740       /* delete index for removed locator-set*/
741       vec_del1(ls_indexes[0], j);
742
743       /* delete locator if it's part of no locator-set */
744       if (vec_len (ls_indexes[0]) == 0)
745         pool_put_index(lcm->locator_pool, loc_indexp[0]);
746     }
747 }
748 int
749 vnet_lisp_add_del_locator_set (vnet_lisp_add_del_locator_set_args_t * a,
750                                u32 * ls_result)
751 {
752   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
753   locator_set_t * ls;
754   locator_t * loc, * itloc;
755   uword _p = (u32)~0, * p = &_p;
756   u32 loc_index, ls_index, ** ls_indexes;
757   u32 **eid_indexes;
758
759   if (a->is_add)
760     {
761       /* check if overwrite */
762       if (a->local)
763         p = hash_get_mem(lcm->locator_set_index_by_name, a->name);
764       else
765         *p = a->index;
766
767       /* overwrite */
768       if (p && p[0] != (u32)~0)
769         {
770           ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
771           if (!ls)
772             {
773               clib_warning("locator-set %d to be overwritten doesn't exist!",
774                            p[0]);
775               return -1;
776             }
777
778           /* clean locator to locator-set vectors and remove locators if
779            * they're not part of another locator-set */
780           clean_locator_to_locator_set (lcm, p[0]);
781
782           /* remove locator indices from locator set */
783           vec_free(ls->locator_indices);
784
785           ls_index = p[0];
786
787           if (ls_result)
788             ls_result[0] = p[0];
789         }
790       /* new locator-set */
791       else
792         {
793           pool_get(lcm->locator_set_pool, ls);
794           ls_index = ls - lcm->locator_set_pool;
795
796           if (a->local)
797             {
798               ls->name = vec_dup(a->name);
799
800               if (!lcm->locator_set_index_by_name)
801                 lcm->locator_set_index_by_name = hash_create_vec(
802                     /* size */0, sizeof(ls->name[0]), sizeof(uword));
803               hash_set_mem(lcm->locator_set_index_by_name, ls->name, ls_index);
804
805               /* mark as local locator-set */
806               vec_add1(lcm->local_locator_set_indexes, ls_index);
807             }
808           ls->local = a->local;
809           if (ls_result)
810             ls_result[0] = ls_index;
811         }
812
813       /* allocate locators */
814       vec_foreach (itloc, a->locators)
815         {
816           pool_get(lcm->locator_pool, loc);
817           loc[0] = itloc[0];
818           loc_index = loc - lcm->locator_pool;
819
820           vec_add1(ls->locator_indices, loc_index);
821
822           vec_validate (lcm->locator_to_locator_sets, loc_index);
823           ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
824                                         loc_index);
825           vec_add1(ls_indexes[0], ls_index);
826         }
827     }
828   else
829     {
830       /* find locator-set */
831       if (a->local)
832         {
833           p = hash_get_mem(lcm->locator_set_index_by_name, a->name);
834           if (!p)
835             {
836               clib_warning("locator-set %v doesn't exists", a->name);
837               return -1;
838             }
839         }
840       else
841         *p = a->index;
842
843       ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
844       if (!ls)
845         {
846           clib_warning("locator-set with index %d doesn't exists", p[0]);
847           return -1;
848         }
849 //      /* XXX what happens when a mapping is configured to use the loc-set ? */
850 //      if (vec_len (vec_elt_at_index(lcm->locator_set_to_eids, p[0])) != 0)
851 //        {
852 //          clib_warning ("Can't delete a locator that supports a mapping!");
853 //          return -1;
854 //        }
855
856       if (vec_len(lcm->locator_set_to_eids) != 0)
857       {
858           eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids, p[0]);
859           if (vec_len(eid_indexes[0]) != 0)
860           {
861               clib_warning ("Can't delete a locator that supports a mapping!");
862               return -1;
863           }
864       }
865
866       /* clean locator to locator-sets data */
867       clean_locator_to_locator_set (lcm, p[0]);
868
869       if (ls->local)
870         {
871           u32 it, lsi;
872
873           vec_foreach_index(it, lcm->local_locator_set_indexes)
874           {
875             lsi = vec_elt(lcm->local_locator_set_indexes, it);
876             if (lsi == p[0])
877               {
878                 vec_del1(lcm->local_locator_set_indexes, it);
879                 break;
880               }
881           }
882           hash_unset_mem(lcm->locator_set_index_by_name, ls->name);
883           vec_free(ls->name);
884         }
885       pool_put(lcm->locator_set_pool, ls);
886     }
887   return 0;
888 }
889
890 static inline
891 uword *vnet_lisp_get_locator(vnet_lisp_add_del_locator_set_args_t * a,
892                              uword *p)
893 {
894   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
895
896   ASSERT(a != NULL);
897   ASSERT(p != NULL);
898
899   /* find locator-set */
900   if (a->local)
901   {
902       p = hash_get_mem(lcm->locator_set_index_by_name, a->name);
903   }
904   else
905   {
906       *p = a->index;
907   }
908
909   return p;
910 }
911
912 int
913 vnet_lisp_add_del_locator_set_name (vnet_lisp_add_del_locator_set_args_t * a,
914                                     u32 * ls_result)
915 {
916   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
917   locator_set_t * ls;
918   uword _p = (u32)~0, * p = &_p;
919   u32 ls_index = ~0;
920   u32 **eid_indexes = NULL;
921
922   ASSERT(a != NULL);
923   ASSERT(ls_result != NULL);
924
925   p = vnet_lisp_get_locator(a, p);
926
927   if (a->is_add)
928     {
929       /* overwrite */
930       if (p && p[0] != (u32)~0)
931         {
932           ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
933           if (!ls)
934             {
935               clib_warning("locator-set %d to be overwritten doesn't exist!",
936                            p[0]);
937               return VNET_API_ERROR_UNSPECIFIED;
938             }
939
940           /* clean locator to locator-set vectors and remove locators if
941            * they're not part of another locator-set */
942           clean_locator_to_locator_set (lcm, p[0]);
943
944           /* remove locator indices from locator set */
945           vec_free(ls->locator_indices);
946
947           ls_index = p[0];
948
949           if (ls_result)
950             ls_result[0] = p[0];
951         }
952       /* new locator-set */
953       else
954         {
955           pool_get(lcm->locator_set_pool, ls);
956           ls_index = ls - lcm->locator_set_pool;
957
958           if (a->local)
959             {
960               ls->name = vec_dup(a->name);
961
962               if (!lcm->locator_set_index_by_name)
963                 lcm->locator_set_index_by_name = hash_create_vec(
964                     /* size */0, sizeof(ls->name[0]), sizeof(uword));
965               hash_set_mem(lcm->locator_set_index_by_name, ls->name, ls_index);
966
967               /* mark as local locator-set */
968               vec_add1(lcm->local_locator_set_indexes, ls_index);
969             }
970           ls->local = a->local;
971           ls->locator_indices = NULL;
972           if (ls_result)
973             ls_result[0] = ls_index;
974         }
975     }
976   else
977     {
978        if (!p)
979        {
980            clib_warning("locator-set %v doesn't exists", a->name);
981            return VNET_API_ERROR_INVALID_ARGUMENT;
982        }
983
984        ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
985        if (!ls)
986        {
987            clib_warning("locator-set with index %d doesn't exists", p[0]);
988            return VNET_API_ERROR_INVALID_ARGUMENT;
989        }
990
991       if (vec_len(lcm->locator_set_to_eids) != 0)
992       {
993           eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids, p[0]);
994           if (vec_len(eid_indexes[0]) != 0)
995           {
996               clib_warning ("Can't delete a locator that supports a mapping!");
997               return -1;
998           }
999       }
1000
1001       /* clean locator to locator-sets data */
1002       clean_locator_to_locator_set (lcm, p[0]);
1003
1004       if (ls->local)
1005         {
1006           u32 it, lsi;
1007
1008           vec_foreach_index(it, lcm->local_locator_set_indexes)
1009             {
1010               lsi = vec_elt(lcm->local_locator_set_indexes, it);
1011               if (lsi == p[0])
1012                 {
1013                   vec_del1(lcm->local_locator_set_indexes, it);
1014                   break;
1015                 }
1016             }
1017           hash_unset_mem(lcm->locator_set_index_by_name, ls->name);
1018           vec_free(ls->name);
1019         }
1020       pool_put(lcm->locator_set_pool, ls);
1021     }
1022   return 0;
1023 }
1024
1025 int
1026 vnet_lisp_add_del_locator (vnet_lisp_add_del_locator_set_args_t *a,
1027                            u32 *ls_result)
1028 {
1029   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
1030   locator_set_t *ls = NULL;
1031   locator_t *loc = NULL, *itloc = NULL;
1032   uword _p = (u32)~0, * p = &_p;
1033   u32 loc_index = ~0, ls_index = ~0, *locit = NULL, **ls_indexes = NULL;
1034   u32 i = ~0;
1035
1036   ASSERT(a != NULL);
1037   ASSERT(ls_result != NULL);
1038
1039   p = vnet_lisp_get_locator(a, p);
1040   if (!p) {
1041       clib_warning("locator-set %v doesn't exists", a->name);
1042       return VNET_API_ERROR_INVALID_ARGUMENT;
1043   }
1044
1045   ls_index = p[0];
1046
1047   if (a->is_add)
1048     {
1049         ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
1050         if (!ls)
1051         {
1052             clib_warning("locator-set %d to be overwritten doesn't exist!",
1053                          p[0]);
1054             return VNET_API_ERROR_INVALID_ARGUMENT;
1055         }
1056
1057         if (ls_result)
1058             ls_result[0] = p[0];
1059
1060       /* allocate locators */
1061       itloc = a->locators;
1062       pool_get(lcm->locator_pool, loc);
1063       loc[0] = itloc[0];
1064       loc_index = loc - lcm->locator_pool;
1065
1066       vec_add1(ls->locator_indices, loc_index);
1067
1068       vec_validate (lcm->locator_to_locator_sets, loc_index);
1069       ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
1070                                     loc_index);
1071       vec_add1(ls_indexes[0], ls_index);
1072     }
1073   else
1074     {
1075       ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
1076       if (!ls)
1077         {
1078           clib_warning("locator-set with index %d doesn't exists", p[0]);
1079           return VNET_API_ERROR_INVALID_ARGUMENT;
1080         }
1081
1082       if (ls->local)
1083       {
1084           itloc = a->locators;
1085           i = 0;
1086           vec_foreach (locit, ls->locator_indices)
1087           {
1088               loc = pool_elt_at_index(lcm->locator_pool, locit[0]);
1089               if (loc->local && loc->sw_if_index == itloc->sw_if_index)
1090               {
1091                   ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
1092                                                 locit[0]);
1093                   pool_put_index(lcm->locator_pool, locit[0]);
1094                   vec_del1(ls->locator_indices, i);
1095                   vec_del1(ls_indexes[0], ls_index);
1096               }
1097               i++;
1098           }
1099       }
1100     }
1101   return 0;
1102 }
1103
1104 clib_error_t *
1105 vnet_lisp_enable_disable (u8 is_enabled)
1106 {
1107   vnet_lisp_gpe_add_del_iface_args_t _ai, * ai= &_ai;
1108   uword * table_id, * refc;
1109   u32 i;
1110   clib_error_t * error = 0;
1111   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
1112   vnet_lisp_gpe_enable_disable_args_t _a, * a = &_a;
1113
1114   a->is_en = is_enabled;
1115   error = vnet_lisp_gpe_enable_disable (a);
1116   if (error)
1117     {
1118       return clib_error_return (0, "failed to %s data-plane!",
1119                                 a->is_en ? "enable" : "disable");
1120     }
1121
1122   if (is_enabled)
1123     {
1124       /* enable all ifaces */
1125       for (i = 0; i < vec_len (lcm->local_mappings_indexes); i++)
1126         {
1127           mapping_t * m = vec_elt_at_index (lcm->mapping_pool, i);
1128           ai->is_add = 1;
1129           ai->vni = gid_address_vni (&m->eid);
1130
1131           refc = hash_get (lcm->dp_if_refcount_by_vni, ai->vni);
1132           if (!refc)
1133             {
1134               table_id = hash_get (lcm->table_id_by_vni, ai->vni);
1135               if (table_id)
1136                 {
1137                   ai->table_id = table_id[0];
1138                   /* enables interface and adds defaults */
1139                   vnet_lisp_gpe_add_del_iface (ai, 0);
1140                 }
1141               else
1142                 return clib_error_return (0, "no table_id found for vni %u!",
1143                                           ai->vni);
1144
1145               hash_set (lcm->dp_if_refcount_by_vni, ai->vni, 1);
1146             }
1147           else
1148             {
1149               refc[0]++;
1150             }
1151         }
1152     }
1153   else
1154     {
1155       /* clear refcount table */
1156       hash_free (lcm->dp_if_refcount_by_vni);
1157       hash_free (lcm->fwd_entry_by_mapping_index);
1158       pool_free (lcm->fwd_entry_pool);
1159     }
1160
1161   /* update global flag */
1162   lcm->is_enabled = is_enabled;
1163
1164   return 0;
1165 }
1166
1167 static clib_error_t *
1168 lisp_enable_disable_command_fn (vlib_main_t * vm, unformat_input_t * input,
1169                                    vlib_cli_command_t * cmd)
1170 {
1171   unformat_input_t _line_input, * line_input = &_line_input;
1172   u8 is_enabled = 0;
1173   u8 is_set = 0;
1174
1175   /* Get a line of input. */
1176   if (! unformat_user (input, unformat_line_input, line_input))
1177     return 0;
1178
1179   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1180     {
1181       if (unformat (line_input, "enable"))
1182         {
1183           is_set = 1;
1184           is_enabled = 1;
1185         }
1186       else if (unformat (line_input, "disable"))
1187         is_set = 1;
1188       else
1189         {
1190           return clib_error_return (0, "parse error: '%U'",
1191                                    format_unformat_error, line_input);
1192         }
1193     }
1194
1195   if (!is_set)
1196       return clib_error_return (0, "state not set");
1197
1198   return vnet_lisp_enable_disable (is_enabled);
1199 }
1200
1201 VLIB_CLI_COMMAND (lisp_cp_enable_disable_command) = {
1202     .path = "lisp",
1203     .short_help = "lisp [enable|disable]",
1204     .function = lisp_enable_disable_command_fn,
1205 };
1206
1207 u8
1208 vnet_lisp_enable_disable_status (void)
1209 {
1210   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
1211   return lcm->is_enabled;
1212 }
1213
1214 static u8 *
1215 format_lisp_status (u8 * s, va_list * args)
1216 {
1217   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
1218   return format (s, "%s", lcm->is_enabled ? "enabled" : "disabled");
1219 }
1220
1221 static clib_error_t *
1222 lisp_show_status_command_fn (vlib_main_t * vm, unformat_input_t * input,
1223                              vlib_cli_command_t * cmd)
1224 {
1225   u8 * msg = 0;
1226   msg = format (msg, "feature: %U\ngpe: %U\n",
1227                 format_lisp_status, format_vnet_lisp_gpe_status);
1228   vlib_cli_output (vm, "%v", msg);
1229   vec_free (msg);
1230   return 0;
1231 }
1232
1233 VLIB_CLI_COMMAND (lisp_show_status_command) = {
1234     .path = "show lisp status",
1235     .short_help = "show lisp status",
1236     .function = lisp_show_status_command_fn,
1237 };
1238 static clib_error_t *
1239 lisp_add_del_locator_set_command_fn (vlib_main_t * vm, unformat_input_t * input,
1240                                      vlib_cli_command_t * cmd)
1241 {
1242   lisp_gpe_main_t * lgm = &lisp_gpe_main;
1243   vnet_main_t * vnm = lgm->vnet_main;
1244   unformat_input_t _line_input, * line_input = &_line_input;
1245   u8 is_add = 1;
1246   clib_error_t * error = 0;
1247   u8 * locator_set_name = 0;
1248   locator_t locator, * locators = 0;
1249   vnet_lisp_add_del_locator_set_args_t _a, * a = &_a;
1250   u32 ls_index = 0;
1251
1252   memset(&locator, 0, sizeof(locator));
1253   memset(a, 0, sizeof(a[0]));
1254
1255   /* Get a line of input. */
1256   if (! unformat_user (input, unformat_line_input, line_input))
1257     return 0;
1258
1259   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1260     {
1261       if (unformat (line_input, "add %_%v%_", &locator_set_name))
1262         is_add = 1;
1263       else if (unformat (line_input, "del %_%v%_", &locator_set_name))
1264         is_add = 0;
1265       else if (unformat (line_input, "iface %U p %d w %d",
1266                          unformat_vnet_sw_interface, vnm, &locator.sw_if_index,
1267                          &locator.priority, &locator.weight))
1268         {
1269           locator.local = 1;
1270           vec_add1(locators, locator);
1271         }
1272       else
1273         {
1274           error = unformat_parse_error(line_input);
1275           goto done;
1276         }
1277     }
1278
1279   a->name = locator_set_name;
1280   a->locators = locators;
1281   a->is_add = is_add;
1282   a->local = 1;
1283
1284   vnet_lisp_add_del_locator_set(a, &ls_index);
1285
1286  done:
1287   vec_free(locators);
1288   if (locator_set_name)
1289     vec_free (locator_set_name);
1290   return error;
1291 }
1292
1293 VLIB_CLI_COMMAND (lisp_cp_add_del_locator_set_command) = {
1294     .path = "lisp locator-set",
1295     .short_help = "lisp locator-set add/del <name> iface <iface-name> "
1296         "p <priority> w <weight>",
1297     .function = lisp_add_del_locator_set_command_fn,
1298 };
1299
1300 static clib_error_t *
1301 lisp_cp_show_locator_sets_command_fn (vlib_main_t * vm,
1302                                       unformat_input_t * input,
1303                                       vlib_cli_command_t * cmd)
1304 {
1305   locator_set_t * lsit;
1306   locator_t * loc;
1307   u32 * locit;
1308   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
1309
1310   vlib_cli_output (vm, "%=20s%=16s%=16s%=16s", "Locator-set", "Locator",
1311                    "Priority", "Weight");
1312   pool_foreach (lsit, lcm->locator_set_pool,
1313   ({
1314     u8 * msg = 0;
1315     msg = format (msg, "%-16v", lsit->name);
1316     vec_foreach (locit, lsit->locator_indices)
1317       {
1318         loc = pool_elt_at_index (lcm->locator_pool, locit[0]);
1319         if (loc->local)
1320           msg = format (msg, "%16d%16d%16d", loc->sw_if_index, loc->priority,
1321                         loc->weight);
1322         else
1323           msg = format (msg, "%16U%16d%16d", format_gid_address, &loc->address,
1324                         loc->priority, loc->weight);
1325       }
1326     vlib_cli_output (vm, "%v", msg);
1327     vec_free (msg);
1328   }));
1329   return 0;
1330 }
1331
1332 VLIB_CLI_COMMAND (lisp_cp_show_locator_sets_command) = {
1333     .path = "show lisp locator-set",
1334     .short_help = "Shows locator-sets",
1335     .function = lisp_cp_show_locator_sets_command_fn,
1336 };
1337
1338 int
1339 vnet_lisp_add_del_map_resolver (vnet_lisp_add_del_map_resolver_args_t * a)
1340 {
1341   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
1342   ip_address_t * addr;
1343   u32 i;
1344
1345   if (a->is_add)
1346     {
1347       vec_foreach(addr, lcm->map_resolvers)
1348         {
1349           if (!ip_address_cmp (addr, &a->address))
1350             {
1351               clib_warning("map-resolver %U already exists!", format_ip_address,
1352                            &a->address);
1353               return -1;
1354             }
1355         }
1356       vec_add1(lcm->map_resolvers, a->address);
1357     }
1358   else
1359     {
1360       for (i = 0; i < vec_len(lcm->map_resolvers); i++)
1361         {
1362           addr = vec_elt_at_index(lcm->map_resolvers, i);
1363           if (!ip_address_cmp (addr, &a->address))
1364             {
1365               vec_delete(lcm->map_resolvers, 1, i);
1366               break;
1367             }
1368         }
1369     }
1370   return 0;
1371 }
1372
1373 static clib_error_t *
1374 lisp_add_del_map_resolver_command_fn (vlib_main_t * vm,
1375                                          unformat_input_t * input,
1376                                          vlib_cli_command_t * cmd)
1377 {
1378   unformat_input_t _line_input, * line_input = &_line_input;
1379   u8 is_add = 1;
1380   ip_address_t ip_addr;
1381   clib_error_t * error = 0;
1382   vnet_lisp_add_del_map_resolver_args_t _a, * a = &_a;
1383
1384   /* Get a line of input. */
1385   if (! unformat_user (input, unformat_line_input, line_input))
1386     return 0;
1387
1388   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1389     {
1390       if (unformat (line_input, "add"))
1391         is_add = 1;
1392       else if (unformat (line_input, "del"))
1393         is_add = 0;
1394       else if (unformat (line_input, "%U", unformat_ip_address, &ip_addr))
1395         ;
1396       else
1397         {
1398           error = unformat_parse_error(line_input);
1399           goto done;
1400         }
1401     }
1402   a->is_add = is_add;
1403   a->address = ip_addr;
1404   vnet_lisp_add_del_map_resolver (a);
1405
1406  done:
1407   return error;
1408 }
1409
1410 VLIB_CLI_COMMAND (lisp_add_del_map_resolver_command) = {
1411     .path = "lisp map-resolver",
1412     .short_help = "lisp map-resolver add/del <ip_address>",
1413     .function = lisp_add_del_map_resolver_command_fn,
1414 };
1415
1416 /* Statistics (not really errors) */
1417 #define foreach_lisp_cp_lookup_error           \
1418 _(DROP, "drop")                                \
1419 _(MAP_REQUESTS_SENT, "map-request sent")
1420
1421 static char * lisp_cp_lookup_error_strings[] = {
1422 #define _(sym,string) string,
1423   foreach_lisp_cp_lookup_error
1424 #undef _
1425 };
1426
1427 typedef enum
1428 {
1429 #define _(sym,str) LISP_CP_LOOKUP_ERROR_##sym,
1430     foreach_lisp_cp_lookup_error
1431 #undef _
1432     LISP_CP_LOOKUP_N_ERROR,
1433 } lisp_cp_lookup_error_t;
1434
1435 typedef enum
1436 {
1437   LISP_CP_LOOKUP_NEXT_DROP,
1438   LISP_CP_LOOKUP_NEXT_IP4_LOOKUP,
1439   LISP_CP_LOOKUP_NEXT_IP6_LOOKUP,
1440   LISP_CP_LOOKUP_N_NEXT,
1441 } lisp_cp_lookup_next_t;
1442
1443 typedef struct
1444 {
1445   gid_address_t dst_eid;
1446   ip_address_t map_resolver_ip;
1447 } lisp_cp_lookup_trace_t;
1448
1449 u8 *
1450 format_lisp_cp_lookup_trace (u8 * s, va_list * args)
1451 {
1452   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1453   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1454   lisp_cp_lookup_trace_t * t = va_arg (*args, lisp_cp_lookup_trace_t *);
1455
1456   s = format (s, "LISP-CP-LOOKUP: map-resolver: %U destination eid %U",
1457               format_ip_address, &t->map_resolver_ip, format_gid_address,
1458               &t->dst_eid);
1459   return s;
1460 }
1461
1462 static u32
1463 ip_fib_lookup_with_table (lisp_cp_main_t * lcm, u32 fib_index,
1464                           ip_address_t * dst)
1465 {
1466   if (ip_addr_version (dst) == IP4)
1467       return ip4_fib_lookup_with_table (lcm->im4, fib_index, &ip_addr_v4(dst),
1468                                         0);
1469   else
1470       return ip6_fib_lookup_with_table (lcm->im6, fib_index, &ip_addr_v6(dst));
1471 }
1472
1473 void
1474 get_mr_and_local_iface_ip (lisp_cp_main_t *lcm, ip_address_t * mr_ip,
1475                             ip_address_t * sloc)
1476 {
1477   u32 adj_index;
1478   ip_adjacency_t * adj;
1479   ip_interface_address_t * ia = 0;
1480   ip_lookup_main_t * lm;
1481   ip4_address_t * l4 = 0;
1482   ip6_address_t * l6 = 0;
1483   ip_address_t * mrit;
1484
1485   if (vec_len(lcm->map_resolvers) == 0)
1486     {
1487       clib_warning("No map-resolver configured");
1488       return;
1489     }
1490
1491   /* find the first mr ip we have a route to and the ip of the
1492    * iface that has a route to it */
1493   vec_foreach(mrit, lcm->map_resolvers)
1494     {
1495       lm = ip_addr_version (mrit) == IP4 ?
1496           &lcm->im4->lookup_main : &lcm->im6->lookup_main;
1497
1498       adj_index = ip_fib_lookup_with_table (lcm, 0, mrit);
1499       adj = ip_get_adjacency (lm, adj_index);
1500
1501       if (adj == 0)
1502         continue;
1503
1504       if (adj->lookup_next_index == IP_LOOKUP_NEXT_ARP)
1505         {
1506           ia = pool_elt_at_index(lm->if_address_pool, adj->if_address_index);
1507           if (ip_addr_version(mrit) == IP4)
1508             {
1509               l4 = ip_interface_address_get_address (lm, ia);
1510             }
1511           else
1512             {
1513               l6 = ip_interface_address_get_address (lm, ia);
1514             }
1515         }
1516       else if (adj->lookup_next_index == IP_LOOKUP_NEXT_REWRITE)
1517         {
1518           /* find sw_if_index in rewrite header */
1519           u32 sw_if_index = adj->rewrite_header.sw_if_index;
1520
1521           /* find suitable address */
1522           if (ip_addr_version(mrit) == IP4)
1523             {
1524               /* find the first ip address */
1525               foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
1526                                             sw_if_index, 1 /* unnumbered */,
1527               ({
1528                 l4 = ip_interface_address_get_address (&lcm->im4->lookup_main,
1529                                                        ia);
1530                 break;
1531               }));
1532             }
1533           else
1534             {
1535               /* find the first ip address */
1536               foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
1537                                             sw_if_index, 1 /* unnumbered */,
1538               ({
1539                 l6 = ip_interface_address_get_address (&lcm->im6->lookup_main,
1540                                                        ia);
1541                 break;
1542               }));
1543             }
1544         }
1545
1546       if (l4)
1547         {
1548           ip_addr_v4(sloc).as_u32 = l4->as_u32;
1549           ip_addr_version(sloc) = IP4;
1550           ip_address_copy(mr_ip, mrit);
1551           return;
1552         }
1553       else if (l6)
1554         {
1555           clib_memcpy (&ip_addr_v6(sloc), l6, sizeof(*l6));
1556           ip_addr_version(sloc) = IP6;
1557           ip_address_copy(mr_ip, mrit);
1558           return;
1559         }
1560     }
1561
1562   clib_warning("Can't find map-resolver and local interface ip!");
1563   return;
1564 }
1565
1566 static gid_address_t *
1567 build_itr_rloc_list (lisp_cp_main_t * lcm, locator_set_t * loc_set)
1568 {
1569   ip4_address_t * l4;
1570   ip6_address_t * l6;
1571   u32 i;
1572   locator_t * loc;
1573   u32 * loc_indexp;
1574   ip_interface_address_t * ia = 0;
1575   gid_address_t gid_data, * gid = &gid_data;
1576   gid_address_t * rlocs = 0;
1577   ip_prefix_t * ippref = &gid_address_ippref (gid);
1578   ip_address_t * rloc = &ip_prefix_addr (ippref);
1579
1580   gid_address_type (gid) = GID_ADDR_IP_PREFIX;
1581   for (i = 0; i < vec_len(loc_set->locator_indices); i++)
1582     {
1583       loc_indexp = vec_elt_at_index(loc_set->locator_indices, i);
1584       loc = pool_elt_at_index (lcm->locator_pool, loc_indexp[0]);
1585
1586       ip_addr_version(rloc) = IP4;
1587       /* Add ipv4 locators first TODO sort them */
1588       foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
1589                                     loc->sw_if_index, 1 /* unnumbered */,
1590       ({
1591         l4 = ip_interface_address_get_address (&lcm->im4->lookup_main, ia);
1592         ip_addr_v4 (rloc) = l4[0];
1593         ip_prefix_len (ippref) = 32;
1594         vec_add1 (rlocs, gid[0]);
1595       }));
1596
1597       ip_addr_version(rloc) = IP6;
1598       /* Add ipv6 locators */
1599       foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
1600                                     loc->sw_if_index, 1 /* unnumbered */,
1601       ({
1602         l6 = ip_interface_address_get_address (&lcm->im6->lookup_main, ia);
1603         ip_addr_v6 (rloc) = l6[0];
1604         ip_prefix_len (ippref) = 128;
1605         vec_add1 (rlocs, gid[0]);
1606       }));
1607     }
1608   return rlocs;
1609 }
1610
1611 static vlib_buffer_t *
1612 build_encapsulated_map_request (vlib_main_t * vm, lisp_cp_main_t *lcm,
1613                                 gid_address_t * seid, gid_address_t * deid,
1614                                 locator_set_t * loc_set, ip_address_t * mr_ip,
1615                                 ip_address_t * sloc, u8 is_smr_invoked,
1616                                 u64 *nonce_res, u32 * bi_res)
1617 {
1618   vlib_buffer_t * b;
1619   u32 bi;
1620   gid_address_t * rlocs = 0;
1621
1622   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
1623     {
1624       clib_warning ("Can't allocate buffer for Map-Request!");
1625       return 0;
1626     }
1627
1628   b = vlib_get_buffer (vm, bi);
1629
1630   /* leave some space for the encap headers */
1631   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
1632
1633   /* get rlocs */
1634   rlocs = build_itr_rloc_list (lcm, loc_set);
1635
1636   /* put lisp msg */
1637   lisp_msg_put_mreq (lcm, b, seid, deid, rlocs, is_smr_invoked, nonce_res);
1638
1639   /* push ecm: udp-ip-lisp */
1640   lisp_msg_push_ecm (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, seid, deid);
1641
1642   /* push outer ip header */
1643   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
1644                        mr_ip);
1645
1646   bi_res[0] = bi;
1647
1648   if (rlocs)
1649     vec_free(rlocs);
1650   return b;
1651 }
1652
1653 static void
1654 send_encapsulated_map_request (vlib_main_t * vm, lisp_cp_main_t *lcm,
1655                                gid_address_t * seid, gid_address_t * deid,
1656                                u8 is_smr_invoked)
1657 {
1658   u32 next_index, bi = 0, * to_next, map_index;
1659   vlib_buffer_t * b;
1660   vlib_frame_t * f;
1661   u64 nonce = 0;
1662   locator_set_t * loc_set;
1663   mapping_t * map;
1664   pending_map_request_t * pmr;
1665   ip_address_t mr_ip, sloc;
1666
1667   /* get locator-set for seid */
1668   if (!lcm->lisp_pitr)
1669     {
1670       map_index = gid_dictionary_lookup (&lcm->mapping_index_by_gid, seid);
1671       if (map_index == ~0)
1672         {
1673           clib_warning("No local mapping found in eid-table for %U!",
1674                        format_gid_address, seid);
1675           return;
1676         }
1677
1678       map = pool_elt_at_index (lcm->mapping_pool, map_index);
1679
1680       if (!map->local)
1681         {
1682           clib_warning("Mapping found for src eid %U is not marked as local!",
1683                        format_gid_address, seid);
1684           return;
1685         }
1686     }
1687   else
1688     {
1689       map_index = lcm->pitr_map_index;
1690       map = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
1691     }
1692
1693   loc_set = pool_elt_at_index (lcm->locator_set_pool, map->locator_set_index);
1694
1695   /* get local iface ip to use in map-request XXX fib 0 for now*/
1696   get_mr_and_local_iface_ip (lcm, &mr_ip, &sloc);
1697
1698   /* build the encapsulated map request */
1699   b = build_encapsulated_map_request (vm, lcm, seid, deid, loc_set, &mr_ip,
1700                                       &sloc, is_smr_invoked, &nonce, &bi);
1701
1702   if (!b)
1703     return;
1704
1705   /* set fib index and lookup node */
1706   vnet_buffer(b)->sw_if_index[VLIB_TX] = ~0;
1707   next_index = (ip_addr_version(&mr_ip) == IP4) ?
1708       ip4_lookup_node.index : ip6_lookup_node.index;
1709
1710   f = vlib_get_frame_to_node (vm, next_index);
1711
1712   /* Enqueue the packet */
1713   to_next = vlib_frame_vector_args (f);
1714   to_next[0] = bi;
1715   f->n_vectors = 1;
1716   vlib_put_frame_to_node (vm, next_index, f);
1717
1718   /* add map-request to pending requests table */
1719   pool_get(lcm->pending_map_requests_pool, pmr);
1720   gid_address_copy (&pmr->src, seid);
1721   gid_address_copy (&pmr->dst, deid);
1722   pmr->src_mapping_index = map_index;
1723   hash_set(lcm->pending_map_requests_by_nonce, nonce,
1724            pmr - lcm->pending_map_requests_pool);
1725 }
1726
1727 static void
1728 get_src_and_dst (void *hdr, ip_address_t * src, ip_address_t *dst)
1729 {
1730   ip4_header_t * ip4 = hdr;
1731   ip6_header_t * ip6;
1732
1733   if ((ip4->ip_version_and_header_length & 0xF0) == 0x40)
1734     {
1735       ip_addr_v4(src).as_u32 = ip4->src_address.as_u32;
1736       ip_addr_version(src) = IP4;
1737       ip_addr_v4(dst).as_u32 = ip4->dst_address.as_u32;
1738       ip_addr_version(dst) = IP4;
1739     }
1740   else
1741     {
1742       ip6 = hdr;
1743       clib_memcpy (&ip_addr_v6(src), &ip6->src_address, sizeof(ip6->src_address));
1744       ip_addr_version(src) = IP6;
1745       clib_memcpy (&ip_addr_v6(dst), &ip6->dst_address, sizeof(ip6->dst_address));
1746       ip_addr_version(dst) = IP6;
1747     }
1748 }
1749
1750 static uword
1751 lisp_cp_lookup (vlib_main_t * vm, vlib_node_runtime_t * node,
1752               vlib_frame_t * from_frame)
1753 {
1754   u32 * from, * to_next_drop, di, si;
1755   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main();
1756   u32 pkts_mapped = 0;
1757   uword n_left_from, n_left_to_next_drop;
1758
1759   from = vlib_frame_vector_args (from_frame);
1760   n_left_from = from_frame->n_vectors;
1761
1762   while (n_left_from > 0)
1763     {
1764       vlib_get_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
1765                            to_next_drop, n_left_to_next_drop);
1766
1767       while (n_left_from > 0 && n_left_to_next_drop > 0)
1768         {
1769           u32 pi0;
1770           vlib_buffer_t * p0;
1771           ip4_header_t * ip0;
1772           gid_address_t src, dst;
1773           ip_prefix_t * spref, * dpref;
1774
1775           gid_address_type (&src) = GID_ADDR_IP_PREFIX;
1776           spref = &gid_address_ippref(&src);
1777           gid_address_type (&dst) = GID_ADDR_IP_PREFIX;
1778           dpref = &gid_address_ippref(&dst);
1779
1780           pi0 = from[0];
1781           from += 1;
1782           n_left_from -= 1;
1783           to_next_drop[0] = pi0;
1784           to_next_drop += 1;
1785           n_left_to_next_drop -= 1;
1786
1787           p0 = vlib_get_buffer (vm, pi0);
1788           p0->error = node->errors[LISP_CP_LOOKUP_ERROR_DROP];
1789
1790           /* src/dst eid pair */
1791           ip0 = vlib_buffer_get_current (p0);
1792           get_src_and_dst (ip0, &ip_prefix_addr(spref), &ip_prefix_addr(dpref));
1793           ip_prefix_len(spref) = ip_address_max_len (ip_prefix_version(spref));
1794           ip_prefix_len(dpref) = ip_address_max_len (ip_prefix_version(dpref));
1795
1796           /* if we have remote mapping for destination already in map-chache
1797              add forwarding tunnel directly. If not send a map-request */
1798           di = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &dst);
1799           if (~0 != di)
1800             {
1801               mapping_t * m =  vec_elt_at_index (lcm->mapping_pool, di);
1802               /* send a map-request also in case of negative mapping entry
1803                 with corresponding action */
1804               if (m->action == ACTION_SEND_MAP_REQUEST)
1805                 {
1806                   /* send map-request */
1807                   send_encapsulated_map_request (vm, lcm, &src, &dst, 0);
1808                   pkts_mapped++;
1809                 }
1810               else
1811                 {
1812                   si =  gid_dictionary_lookup (&lcm->mapping_index_by_gid,
1813                                                &src);
1814                   if (~0 != si)
1815                     {
1816                       add_fwd_entry (lcm, si, di);
1817                     }
1818                 }
1819             }
1820           else
1821             {
1822               /* send map-request */
1823               send_encapsulated_map_request (vm, lcm, &src, &dst, 0);
1824               pkts_mapped++;
1825             }
1826
1827           if (PREDICT_FALSE(p0->flags & VLIB_BUFFER_IS_TRACED))
1828             {
1829               lisp_cp_lookup_trace_t *tr = vlib_add_trace (vm, node, p0,
1830                                                           sizeof(*tr));
1831
1832               memset(tr, 0, sizeof(*tr));
1833               gid_address_copy (&tr->dst_eid, &dst);
1834               if (vec_len(lcm->map_resolvers) > 0)
1835                 {
1836                   clib_memcpy (&tr->map_resolver_ip,
1837                                vec_elt_at_index(lcm->map_resolvers, 0),
1838                                sizeof(ip_address_t));
1839                 }
1840             }
1841         }
1842
1843       vlib_put_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP, n_left_to_next_drop);
1844     }
1845   vlib_node_increment_counter (vm, node->node_index,
1846                                LISP_CP_LOOKUP_ERROR_MAP_REQUESTS_SENT,
1847                                pkts_mapped);
1848   return from_frame->n_vectors;
1849 }
1850
1851 VLIB_REGISTER_NODE (lisp_cp_lookup_node) = {
1852   .function = lisp_cp_lookup,
1853   .name = "lisp-cp-lookup",
1854   .vector_size = sizeof (u32),
1855   .format_trace = format_lisp_cp_lookup_trace,
1856   .type = VLIB_NODE_TYPE_INTERNAL,
1857
1858   .n_errors = LISP_CP_LOOKUP_N_ERROR,
1859   .error_strings = lisp_cp_lookup_error_strings,
1860
1861   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
1862
1863   .next_nodes = {
1864       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
1865       [LISP_CP_LOOKUP_NEXT_IP4_LOOKUP] = "ip4-lookup",
1866       [LISP_CP_LOOKUP_NEXT_IP6_LOOKUP] = "ip6-lookup",
1867   },
1868 };
1869
1870 /* lisp_cp_input statistics */
1871 #define foreach_lisp_cp_input_error                   \
1872 _(DROP, "drop")                                        \
1873 _(MAP_REPLIES_RECEIVED, "map-replies received")
1874
1875 static char * lisp_cp_input_error_strings[] = {
1876 #define _(sym,string) string,
1877   foreach_lisp_cp_input_error
1878 #undef _
1879 };
1880
1881 typedef enum
1882 {
1883 #define _(sym,str) LISP_CP_INPUT_ERROR_##sym,
1884     foreach_lisp_cp_input_error
1885 #undef _
1886     LISP_CP_INPUT_N_ERROR,
1887 } lisp_cp_input_error_t;
1888
1889 typedef enum
1890 {
1891   LISP_CP_INPUT_NEXT_DROP,
1892   LISP_CP_INPUT_N_NEXT,
1893 } lisp_cp_input_next_t;
1894
1895 typedef struct
1896 {
1897   gid_address_t dst_eid;
1898   ip4_address_t map_resolver_ip;
1899 } lisp_cp_input_trace_t;
1900
1901 u8 *
1902 format_lisp_cp_input_trace (u8 * s, va_list * args)
1903 {
1904   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1905   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1906   CLIB_UNUSED(lisp_cp_input_trace_t * t) = va_arg (*args, lisp_cp_input_trace_t *);
1907
1908   s = format (s, "LISP-CP-INPUT: TODO");
1909   return s;
1910 }
1911
1912 ip_interface_address_t *
1913 ip_interface_get_first_interface_address (ip_lookup_main_t *lm, u32 sw_if_index,
1914                                           u8 loop)
1915 {
1916   vnet_main_t *vnm = vnet_get_main ();
1917   vnet_sw_interface_t * swif = vnet_get_sw_interface (vnm, sw_if_index);
1918   if (loop && swif->flags & VNET_SW_INTERFACE_FLAG_UNNUMBERED)
1919     sw_if_index = swif->unnumbered_sw_if_index;
1920   u32 ia =
1921       (vec_len((lm)->if_address_pool_index_by_sw_if_index) > (sw_if_index)) ?
1922           vec_elt((lm)->if_address_pool_index_by_sw_if_index, (sw_if_index)) :
1923           (u32) ~0;
1924   return pool_elt_at_index((lm)->if_address_pool, ia);
1925 }
1926
1927 void *
1928 ip_interface_get_first_ip_addres (ip_lookup_main_t *lm, u32 sw_if_index,
1929                                    u8 loop)
1930 {
1931   ip_interface_address_t * ia = ip_interface_get_first_interface_address (
1932       lm, sw_if_index, loop);
1933   return ip_interface_address_get_address (lm, ia);
1934 }
1935
1936 static void
1937 del_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index,
1938                u32 dst_map_index)
1939 {
1940   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, * a = &_a;
1941   fwd_entry_t * fe = 0;
1942   uword * feip = 0;
1943   memset(a, 0, sizeof(*a));
1944
1945   feip = hash_get(lcm->fwd_entry_by_mapping_index, dst_map_index);
1946   if (!feip)
1947     return;
1948
1949   fe = pool_elt_at_index(lcm->fwd_entry_pool, feip[0]);
1950
1951   /* delete dp fwd entry */
1952   u32 sw_if_index;
1953   a->is_add = 0;
1954   a->dlocator = fe->dst_loc;
1955   a->slocator = fe->src_loc;
1956   a->vni = gid_address_vni(&a->deid);
1957   gid_address_copy(&a->deid, &fe->deid);
1958
1959   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
1960
1961   /* delete entry in fwd table */
1962   hash_unset(lcm->fwd_entry_by_mapping_index, dst_map_index);
1963   pool_put(lcm->fwd_entry_pool, fe);
1964 }
1965
1966 static void
1967 add_fwd_entry (lisp_cp_main_t* lcm, u32 src_map_index, u32 dst_map_index)
1968 {
1969   mapping_t * src_map, * dst_map;
1970   locator_set_t * dst_ls, * src_ls;
1971   u32 i, minp = ~0, sw_if_index;
1972   locator_t * dl = 0;
1973   uword * feip = 0, * tidp;
1974   fwd_entry_t* fe;
1975   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, * a = &_a;
1976
1977   memset (a, 0, sizeof(*a));
1978
1979   /* remove entry if it already exists */
1980   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
1981   if (feip)
1982     del_fwd_entry (lcm, src_map_index, dst_map_index);
1983
1984   src_map = pool_elt_at_index (lcm->mapping_pool, src_map_index);
1985   dst_map = pool_elt_at_index (lcm->mapping_pool, dst_map_index);
1986
1987   gid_address_copy (&a->deid, &dst_map->eid);
1988   a->vni = gid_address_vni(&a->deid);
1989
1990   tidp = hash_get(lcm->table_id_by_vni, a->vni);
1991   if (!tidp)
1992     {
1993       clib_warning("vni %d not associated to a vrf!", a->vni);
1994       return;
1995     }
1996   a->table_id = tidp[0];
1997
1998   /* XXX simple forwarding policy: first lowest (value) priority locator */
1999   dst_ls = pool_elt_at_index (lcm->locator_set_pool,
2000                               dst_map->locator_set_index);
2001   for (i = 0; i < vec_len (dst_ls->locator_indices); i++)
2002     {
2003       u32 li = vec_elt (dst_ls->locator_indices, i);
2004       locator_t * l = pool_elt_at_index (lcm->locator_pool, li);
2005       if (l->priority < minp && gid_address_type(&l->address)
2006             == GID_ADDR_IP_PREFIX)
2007         {
2008           minp = l->priority;
2009           dl = l;
2010         }
2011     }
2012   if (dl)
2013     {
2014       src_ls = pool_elt_at_index(lcm->locator_set_pool,
2015                                  src_map->locator_set_index);
2016       for (i = 0; i < vec_len(src_ls->locator_indices); i++)
2017         {
2018           u32 li = vec_elt (src_ls->locator_indices, i);
2019           locator_t * sl = pool_elt_at_index (lcm->locator_pool, li);
2020
2021           if (ip_addr_version(&gid_address_ip(&dl->address)) == IP4)
2022             {
2023               ip4_address_t * l4;
2024               l4 = ip_interface_get_first_ip_addres (&lcm->im4->lookup_main,
2025                                                      sl->sw_if_index,
2026                                                      1 /* unnumbered */);
2027               ip_addr_v4(&a->slocator) = *l4;
2028               ip_addr_version(&a->slocator) = IP4;
2029             }
2030           else
2031             {
2032               ip6_address_t * l6;
2033               l6 = ip_interface_get_first_ip_addres (&lcm->im6->lookup_main,
2034                                                      sl->sw_if_index,
2035                                                      1 /* unnumbered */);
2036               ip_addr_v6(&a->slocator) = *l6;
2037               ip_addr_version(&a->slocator) = IP6;
2038             }
2039         }
2040     }
2041
2042   /* insert data plane forwarding entry */
2043   a->is_add = 1;
2044   if (dl)
2045     a->dlocator = gid_address_ip(&dl->address);
2046   else
2047     {
2048       a->is_negative = 1;
2049       a->action = dst_map->action;
2050     }
2051
2052   /* TODO remove */
2053   u8 ipver = ip_prefix_version(&gid_address_ippref(&a->deid));
2054   a->decap_next_index = (ipver == IP4) ?
2055           LISP_GPE_INPUT_NEXT_IP4_INPUT : LISP_GPE_INPUT_NEXT_IP6_INPUT;
2056
2057   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
2058
2059   /* add tunnel to fwd entry table XXX check return value from DP insertion */
2060   pool_get (lcm->fwd_entry_pool, fe);
2061   fe->dst_loc = a->dlocator;
2062   fe->src_loc = a->slocator;
2063   gid_address_copy (&fe->deid, &a->deid);
2064   hash_set (lcm->fwd_entry_by_mapping_index, dst_map_index,
2065             fe - lcm->fwd_entry_pool);
2066 }
2067
2068 /* return 0 if the two locator sets are identical 1 otherwise */
2069 static u8
2070 compare_locators (lisp_cp_main_t *lcm, u32 * old_ls_indexes,
2071                   locator_t * new_locators)
2072 {
2073   u32 i, old_li;
2074   locator_t * old_loc, * new_loc;
2075
2076   if (vec_len (old_ls_indexes) != vec_len(new_locators))
2077     return 1;
2078
2079   for (i = 0; i < vec_len(new_locators); i++)
2080     {
2081       old_li = vec_elt(old_ls_indexes, i);
2082       old_loc = pool_elt_at_index(lcm->locator_pool, old_li);
2083
2084       new_loc = vec_elt_at_index(new_locators, i);
2085
2086       if (locator_cmp (old_loc, new_loc))
2087         return 1;
2088     }
2089   return 0;
2090 }
2091
2092 void
2093 process_map_reply (lisp_cp_main_t * lcm, vlib_buffer_t * b)
2094 {
2095   mapping_t * old_map;
2096   locator_t * loc;
2097   u32 len = 0, i, ls_index = 0;
2098   void * h;
2099   vnet_lisp_add_del_locator_set_args_t _ls_arg, * ls_arg = &_ls_arg;
2100   vnet_lisp_add_del_mapping_args_t _m_args, * m_args = &_m_args;
2101   pending_map_request_t * pmr;
2102   locator_t probed;
2103   map_reply_hdr_t * mrep_hdr;
2104   u64 nonce;
2105   u32 dst_map_index, mi;
2106   uword * pmr_index;
2107
2108   mrep_hdr = vlib_buffer_get_current (b);
2109
2110   /* Check pending requests table and nonce */
2111   nonce = MREP_NONCE(mrep_hdr);
2112   pmr_index = hash_get(lcm->pending_map_requests_by_nonce, nonce);
2113   if (!pmr_index)
2114     {
2115       clib_warning("No pending map-request entry with nonce %lu!", nonce);
2116       return;
2117     }
2118   pmr = pool_elt_at_index(lcm->pending_map_requests_pool, pmr_index[0]);
2119
2120   vlib_buffer_pull (b, sizeof(*mrep_hdr));
2121
2122   for (i = 0; i < MREP_REC_COUNT(mrep_hdr); i++)
2123     {
2124       memset (ls_arg, 0, sizeof(*ls_arg));
2125       memset (m_args, 0, sizeof(*m_args));
2126
2127       h = vlib_buffer_get_current (b);
2128       m_args->ttl = clib_net_to_host_u32 (MAP_REC_TTL(h));
2129       m_args->action = MAP_REC_ACTION(h);
2130       m_args->authoritative = MAP_REC_AUTH(h);
2131
2132       len = lisp_msg_parse_mapping_record (b, &m_args->deid, &ls_arg->locators,
2133                                            &probed);
2134       if (len == ~0)
2135         {
2136           clib_warning ("Failed to parse mapping record!");
2137           vec_foreach (loc, ls_arg->locators)
2138             {
2139               locator_free (loc);
2140             }
2141           vec_free(ls_arg->locators);
2142           return;
2143         }
2144
2145       mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &m_args->deid);
2146       old_map = mi != ~0 ? pool_elt_at_index(lcm->mapping_pool, mi) : 0;
2147
2148       /* if mapping already exists, decide if locators (and forwarding) should
2149        * be updated and be done */
2150       if (old_map != 0 && !gid_address_cmp (&old_map->eid, &m_args->deid))
2151         {
2152           locator_set_t * old_ls;
2153
2154           /* update mapping attributes */
2155           old_map->action = m_args->action;
2156           old_map->authoritative = m_args->authoritative;
2157           old_map->ttl = m_args->ttl;
2158
2159           old_ls = pool_elt_at_index(lcm->locator_set_pool,
2160                                      old_map->locator_set_index);
2161           /* if the two locators are not equal, update them and forwarding
2162            * otherwise there's nothing to be done */
2163           if (compare_locators (lcm, old_ls->locator_indices, ls_arg->locators))
2164             {
2165               /* set locator-set index to overwrite */
2166               ls_arg->is_add = 1;
2167               ls_arg->index = old_map->locator_set_index;
2168               vnet_lisp_add_del_locator_set (ls_arg, 0);
2169               add_fwd_entry (lcm, pmr->src_mapping_index, mi);
2170             }
2171         }
2172       /* new mapping */
2173       else
2174         {
2175           /* add locator-set */
2176           ls_arg->is_add = 1;
2177           ls_arg->index = ~0;
2178           vnet_lisp_add_del_locator_set (ls_arg, &ls_index);
2179
2180           /* add mapping */
2181           m_args->is_add = 1;
2182           m_args->locator_set_index = ls_index;
2183           vnet_lisp_add_del_mapping (m_args, &dst_map_index);
2184
2185           /* add forwarding tunnel */
2186           add_fwd_entry (lcm, pmr->src_mapping_index, dst_map_index);
2187         }
2188       vec_free(ls_arg->locators);
2189     }
2190
2191   /* remove pending map request entry */
2192   hash_unset(lcm->pending_map_requests_by_nonce, nonce);
2193   pool_put(lcm->pending_map_requests_pool, pmr);
2194 }
2195
2196 void
2197 process_map_request (vlib_main_t * vm, lisp_cp_main_t * lcm, vlib_buffer_t * b)
2198 {
2199   map_request_hdr_t * mreq_hdr;
2200   gid_address_t src, dst;
2201 //  u64 nonce;
2202   u32 i, len = 0;
2203   gid_address_t * itr_rlocs = 0, * rloc;
2204
2205   mreq_hdr = vlib_buffer_get_current (b);
2206   vlib_buffer_pull (b, sizeof(*mreq_hdr));
2207
2208 //  nonce = MREQ_NONCE(mreq_hdr);
2209
2210   if (!MREQ_SMR(mreq_hdr)) {
2211       clib_warning("Only SMR Map-Requests supported for now!");
2212       return;
2213   }
2214
2215   /* parse src eid */
2216   len = lisp_msg_parse_addr (b, &src);
2217   if (len == ~0)
2218     return;
2219
2220   /* for now we don't do anything with the itr's rlocs */
2221   len = lisp_msg_parse_itr_rlocs (b, &itr_rlocs, MREQ_ITR_RLOC_COUNT(mreq_hdr) + 1);
2222   if (len == ~0)
2223     return;
2224
2225   /* TODO: RLOCs are currently unused, so free them for now */
2226   vec_foreach (rloc, itr_rlocs)
2227     {
2228       gid_address_free (rloc);
2229     }
2230
2231   /* parse eid records and send SMR-invoked map-requests */
2232   for (i = 0; i < MREQ_REC_COUNT(mreq_hdr); i++)
2233     {
2234       memset(&dst, 0, sizeof(dst));
2235       len = lisp_msg_parse_eid_rec (b, &dst);
2236       if (len == ~0)
2237         {
2238           clib_warning("Can't parse map-request EID-record");
2239           return;
2240         }
2241       /* send SMR-invoked map-requests */
2242       send_encapsulated_map_request (vm, lcm, &dst, &src, /* invoked */ 1);
2243     }
2244 }
2245
2246 static uword
2247 lisp_cp_input (vlib_main_t * vm, vlib_node_runtime_t * node,
2248                vlib_frame_t * from_frame)
2249 {
2250   u32 n_left_from, * from, * to_next_drop;
2251   lisp_msg_type_e type;
2252   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
2253
2254   from = vlib_frame_vector_args (from_frame);
2255   n_left_from = from_frame->n_vectors;
2256
2257
2258   while (n_left_from > 0)
2259     {
2260       u32 n_left_to_next_drop;
2261
2262       vlib_get_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
2263                            to_next_drop, n_left_to_next_drop);
2264       while (n_left_from > 0 && n_left_to_next_drop > 0)
2265         {
2266           u32 bi0;
2267           vlib_buffer_t * b0;
2268
2269           bi0 = from[0];
2270           from += 1;
2271           n_left_from -= 1;
2272           to_next_drop[0] = bi0;
2273           to_next_drop += 1;
2274           n_left_to_next_drop -= 1;
2275
2276           b0 = vlib_get_buffer (vm, bi0);
2277
2278           type = lisp_msg_type(vlib_buffer_get_current (b0));
2279           switch (type)
2280             {
2281             case LISP_MAP_REPLY:
2282               process_map_reply (lcm, b0);
2283               break;
2284             case LISP_MAP_REQUEST:
2285               process_map_request(vm, lcm, b0);
2286               break;
2287             default:
2288               clib_warning("Unsupported LISP message type %d", type);
2289               break;
2290             }
2291
2292           b0->error = node->errors[LISP_CP_INPUT_ERROR_DROP];
2293
2294           if (PREDICT_FALSE(b0->flags & VLIB_BUFFER_IS_TRACED))
2295             {
2296
2297             }
2298         }
2299
2300       vlib_put_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP, n_left_to_next_drop);
2301     }
2302   return from_frame->n_vectors;
2303 }
2304
2305 VLIB_REGISTER_NODE (lisp_cp_input_node) = {
2306   .function = lisp_cp_input,
2307   .name = "lisp-cp-input",
2308   .vector_size = sizeof (u32),
2309   .format_trace = format_lisp_cp_input_trace,
2310   .type = VLIB_NODE_TYPE_INTERNAL,
2311
2312   .n_errors = LISP_CP_INPUT_N_ERROR,
2313   .error_strings = lisp_cp_input_error_strings,
2314
2315   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
2316
2317   .next_nodes = {
2318       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
2319   },
2320 };
2321
2322 clib_error_t *
2323 lisp_cp_init (vlib_main_t *vm)
2324 {
2325   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
2326   clib_error_t * error = 0;
2327
2328   if ((error = vlib_call_init_function (vm, lisp_gpe_init)))
2329     return error;
2330
2331   lcm->im4 = &ip4_main;
2332   lcm->im6 = &ip6_main;
2333   lcm->vlib_main = vm;
2334   lcm->vnet_main = vnet_get_main();
2335
2336   gid_dictionary_init (&lcm->mapping_index_by_gid);
2337
2338   /* default vrf mapped to vni 0 */
2339   hash_set(lcm->table_id_by_vni, 0, 0);
2340
2341   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp,
2342                          lisp_cp_input_node.index, 1 /* is_ip4 */);
2343   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp6,
2344                          lisp_cp_input_node.index, 0 /* is_ip4 */);
2345
2346   return 0;
2347 }
2348
2349 VLIB_INIT_FUNCTION(lisp_cp_init);