3eabf36861e85c6f7b7d4ccb3da6758fb9cfcb23
[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 /* Stores mapping in map-cache. It does NOT program data plane forwarding for
22  * remote/learned mappings. */
23 int
24 vnet_lisp_add_del_mapping (vnet_lisp_add_del_mapping_args_t * a,
25                            u32 * map_index_result)
26 {
27   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
28   u32 mi, * map_indexp, map_index, i;
29   mapping_t * m;
30   u32 ** eid_indexes;
31
32   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &a->deid);
33   if (a->is_add)
34     {
35       /* TODO check if overwriting and take appropriate actions */
36       if (mi != GID_LOOKUP_MISS)
37         {
38           clib_warning("eid %U found in the eid-table", format_ip_address,
39                        &a->deid);
40           return VNET_API_ERROR_VALUE_EXIST;
41         }
42
43       pool_get(lcm->mapping_pool, m);
44       m->eid = a->deid;
45       m->locator_set_index = a->locator_set_index;
46       m->ttl = a->ttl;
47       m->local = a->local;
48
49       map_index = m - lcm->mapping_pool;
50       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->deid, map_index,
51                               1);
52
53       if (pool_is_free_index(lcm->locator_set_pool, a->locator_set_index))
54         {
55           clib_warning("Locator set with index %d doesn't exist",
56                        a->locator_set_index);
57           return VNET_API_ERROR_INVALID_VALUE;
58         }
59
60       /* add eid to list of eids supported by locator-set */
61       vec_validate (lcm->locator_set_to_eids, a->locator_set_index);
62       eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids,
63                                      a->locator_set_index);
64       vec_add1(eid_indexes[0], map_index);
65
66       if (a->local)
67         {
68           /* mark as local */
69           vec_add1(lcm->local_mappings_indexes, map_index);
70         }
71       map_index_result[0] = map_index;
72     }
73   else
74     {
75       if (mi == GID_LOOKUP_MISS)
76         {
77           clib_warning("eid %U not found in the eid-table", format_ip_address,
78                        &a->deid);
79           return VNET_API_ERROR_INVALID_VALUE;
80         }
81
82       /* clear locator-set to eids binding */
83       eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids,
84                                      a->locator_set_index);
85       for (i = 0; i < vec_len(eid_indexes[0]); i++)
86         {
87           map_indexp = vec_elt_at_index(eid_indexes[0], i);
88           if (map_indexp[0] == mi)
89               break;
90         }
91       vec_del1(eid_indexes[0], i);
92
93       /* remove local mark if needed */
94       m = pool_elt_at_index(lcm->mapping_pool, mi);
95       if (m->local)
96         {
97           u32 k, * lm_indexp;
98           for (k = 0; k < vec_len(lcm->local_mappings_indexes); k++)
99             {
100               lm_indexp = vec_elt_at_index(lcm->local_mappings_indexes, k);
101               if (lm_indexp[0] == mi)
102                 break;
103             }
104           vec_del1(lcm->local_mappings_indexes, k);
105         }
106       else
107         {
108           /* remove tunnel ??? */
109         }
110
111       /* remove mapping from dictionary */
112       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->deid, 0, 0);
113       pool_put_index (lcm->mapping_pool, mi);
114     }
115
116   return 0;
117 }
118
119 /* Stores mapping in map-cache and programs data plane for local mappings. */
120 int
121 vnet_lisp_add_del_local_mapping (vnet_lisp_add_del_mapping_args_t * a,
122                                  u32 * map_index_result)
123 {
124   uword * table_id, * refc;
125   u32 rv;
126   vnet_lisp_gpe_add_del_iface_args_t _ai, *ai = &_ai;
127   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main ();
128
129   /* store/remove mapping from map-cache */
130   rv = vnet_lisp_add_del_mapping (a, map_index_result);
131   if (rv)
132     return rv;
133
134   table_id = hash_get(lcm->table_id_by_vni, /* default for now */ 0);
135
136   if (!table_id)
137     {
138       clib_warning ("vni %d not associated to a vrf!", 0);
139       return VNET_API_ERROR_INVALID_VALUE;
140     }
141
142   refc = hash_get(lcm->dp_if_refcount_by_vni, 0);
143
144   /* enable/disable data-plane interface */
145   if (a->is_add)
146     {
147       /* create interface or update refcount */
148       if (!refc)
149         {
150           ai->is_add = 1;
151           ai->vni = 0; /* default for now, pass vni as parameter */
152           ai->table_id = table_id[0];
153           vnet_lisp_gpe_add_del_iface (ai, 0);
154
155           hash_set(lcm->dp_if_refcount_by_vni, 0 /* table_id */, 1);
156         }
157       else
158         {
159           refc[0]++;
160         }
161     }
162   else
163     {
164       /* since this is a remove for an existing eid, the iface should exist */
165       ASSERT(refc != 0);
166       refc[0]--;
167
168       /* remove iface if needed */
169       if (refc[0] == 0)
170         {
171           ai->is_add = 0;
172           ai->vni = 0; /* default for now, pass vni as parameter */
173           ai->table_id = table_id[0];
174           vnet_lisp_gpe_add_del_iface (ai, 0);
175         }
176     }
177
178   return rv;
179 }
180
181 static clib_error_t *
182 lisp_add_del_local_eid_command_fn (vlib_main_t * vm, unformat_input_t * input,
183                                    vlib_cli_command_t * cmd)
184 {
185   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
186   unformat_input_t _line_input, * line_input = &_line_input;
187   u8 is_add = 1;
188   gid_address_t eid;
189   ip_prefix_t * prefp = &gid_address_ippref(&eid);
190   gid_address_t * eids = 0;
191   clib_error_t * error = 0;
192   u8 * locator_set_name;
193   u32 locator_set_index = 0, map_index = 0;
194   uword * p;
195   vnet_lisp_add_del_mapping_args_t _a, * a = &_a;
196
197   gid_address_type (&eid) = IP_PREFIX;
198
199   /* Get a line of input. */
200   if (! unformat_user (input, unformat_line_input, line_input))
201     return 0;
202
203   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
204     {
205       if (unformat (line_input, "add"))
206         is_add = 1;
207       else if (unformat (line_input, "del"))
208         is_add = 0;
209       else if (unformat (line_input, "eid %U", unformat_ip_prefix, prefp))
210         {
211           vec_add1(eids, eid);
212         }
213       else if (unformat (line_input, "locator-set %_%v%_", &locator_set_name))
214         {
215           p = hash_get_mem(lcm->locator_set_index_by_name, locator_set_name);
216           if (!p)
217             {
218               error = clib_error_return(0, "locator-set %s doesn't exist",
219                                         locator_set_name);
220               goto done;
221             }
222           locator_set_index = p[0];
223         }
224       else
225         {
226           error = unformat_parse_error(line_input);
227           goto done;
228         }
229     }
230
231   /* XXX treat batch configuration */
232   a->deid = eid;
233   a->is_add = is_add;
234   a->locator_set_index = locator_set_index;
235   a->local = 1;
236
237   vnet_lisp_add_del_local_mapping (a, &map_index);
238  done:
239   vec_free(eids);
240   return error;
241 }
242
243 VLIB_CLI_COMMAND (lisp_add_del_local_eid_command) = {
244     .path = "lisp eid-table",
245     .short_help = "lisp eid-table add/del eid <eid> locator-set <locator-set>",
246     .function = lisp_add_del_local_eid_command_fn,
247 };
248
249 static clib_error_t *
250 lisp_show_local_eid_table_command_fn (vlib_main_t * vm,
251                                       unformat_input_t * input,
252                                       vlib_cli_command_t * cmd)
253 {
254   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
255   mapping_t * mapit;
256
257   vlib_cli_output (vm, "%=20s%=16s", "EID", "Locator");
258   pool_foreach (mapit, lcm->mapping_pool,
259   ({
260     u8 * msg = 0;
261     locator_set_t * ls = pool_elt_at_index (lcm->locator_set_pool,
262                                             mapit->locator_set_index);
263     vlib_cli_output (vm, "%-16U%16v", format_gid_address, &mapit->eid,
264                      ls->name);
265     vec_free (msg);
266   }));
267
268   return 0;
269 }
270
271 VLIB_CLI_COMMAND (lisp_cp_show_local_eid_table_command) = {
272     .path = "show lisp eid-table",
273     .short_help = "Shows local EID table",
274     .function = lisp_show_local_eid_table_command_fn,
275 };
276
277 /* cleans locator to locator-set data and removes locators not part of
278  * any locator-set */
279 static void
280 clean_locator_to_locator_set (lisp_cp_main_t * lcm, u32 lsi)
281 {
282   u32 i, j, *loc_indexp, *ls_indexp, **ls_indexes;
283   locator_set_t * ls = pool_elt_at_index(lcm->locator_set_pool, lsi);
284   for (i = 0; i < vec_len(ls->locator_indices); i++)
285     {
286       loc_indexp = vec_elt_at_index(ls->locator_indices, i);
287       ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
288                                     loc_indexp[0]);
289       for (j = 0; j < vec_len(ls_indexes[0]); j++)
290         {
291           ls_indexp = vec_elt_at_index(ls_indexes[0], j);
292           if (ls_indexp[0] == lsi)
293             break;
294         }
295
296       /* delete index for removed locator-set*/
297       vec_del1(ls_indexes[0], j);
298
299       /* delete locator if it's part of no locator-set */
300       if (vec_len (ls_indexes[0]) == 0)
301         pool_put_index(lcm->locator_pool, loc_indexp[0]);
302     }
303 }
304 int
305 vnet_lisp_add_del_locator_set (vnet_lisp_add_del_locator_set_args_t * a,
306                                u32 * ls_result)
307 {
308   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
309   locator_set_t * ls;
310   locator_t * loc, * itloc;
311   uword _p = (u32)~0, * p = &_p;
312   u32 loc_index, ls_index, ** ls_indexes;
313   u32 **eid_indexes;
314
315   if (a->is_add)
316     {
317       /* check if overwrite */
318       if (a->local)
319         p = hash_get_mem(lcm->locator_set_index_by_name, a->name);
320       else
321         *p = a->index;
322
323       /* overwrite */
324       if (p && p[0] != (u32)~0)
325         {
326           ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
327           if (!ls)
328             {
329               clib_warning("locator-set %d to be overwritten doesn't exist!",
330                            p[0]);
331               return -1;
332             }
333
334           /* clean locator to locator-set vectors and remove locators if
335            * they're not part of another locator-set */
336           clean_locator_to_locator_set (lcm, p[0]);
337
338           /* remove locator indices from locator set */
339           vec_free(ls->locator_indices);
340
341           ls_index = p[0];
342
343           if (ls_result)
344             ls_result[0] = p[0];
345         }
346       /* new locator-set */
347       else
348         {
349           pool_get(lcm->locator_set_pool, ls);
350           ls_index = ls - lcm->locator_set_pool;
351
352           if (a->local)
353             {
354               ls->name = vec_dup(a->name);
355
356               if (!lcm->locator_set_index_by_name)
357                 lcm->locator_set_index_by_name = hash_create_vec(
358                     /* size */0, sizeof(ls->name[0]), sizeof(uword));
359               hash_set_mem(lcm->locator_set_index_by_name, ls->name, ls_index);
360
361               /* mark as local locator-set */
362               vec_add1(lcm->local_locator_set_indexes, ls_index);
363             }
364           ls->local = a->local;
365           if (ls_result)
366             ls_result[0] = ls_index;
367         }
368
369       /* allocate locators */
370       vec_foreach (itloc, a->locators)
371         {
372           pool_get(lcm->locator_pool, loc);
373           loc[0] = itloc[0];
374           loc_index = loc - lcm->locator_pool;
375
376           vec_add1(ls->locator_indices, loc_index);
377
378           vec_validate (lcm->locator_to_locator_sets, loc_index);
379           ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
380                                         loc_index);
381           vec_add1(ls_indexes[0], ls_index);
382         }
383     }
384   else
385     {
386       /* find locator-set */
387       if (a->local)
388         {
389           p = hash_get_mem(lcm->locator_set_index_by_name, a->name);
390           if (!p)
391             {
392               clib_warning("locator-set %v doesn't exists", a->name);
393               return -1;
394             }
395         }
396       else
397         *p = a->index;
398
399       ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
400       if (!ls)
401         {
402           clib_warning("locator-set with index %d doesn't exists", p[0]);
403           return -1;
404         }
405 //      /* XXX what happens when a mapping is configured to use the loc-set ? */
406 //      if (vec_len (vec_elt_at_index(lcm->locator_set_to_eids, p[0])) != 0)
407 //        {
408 //          clib_warning ("Can't delete a locator that supports a mapping!");
409 //          return -1;
410 //        }
411
412       if (vec_len(lcm->locator_set_to_eids) != 0)
413       {
414           eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids, p[0]);
415           if (vec_len(eid_indexes[0]) != 0)
416           {
417               clib_warning ("Can't delete a locator that supports a mapping!");
418               return -1;
419           }
420       }
421
422       /* clean locator to locator-sets data */
423       clean_locator_to_locator_set (lcm, p[0]);
424
425       if (ls->local)
426         {
427           u32 it, lsi;
428
429           vec_foreach_index(it, lcm->local_locator_set_indexes)
430           {
431             lsi = vec_elt(lcm->local_locator_set_indexes, it);
432             if (lsi == p[0])
433               {
434                 vec_del1(lcm->local_locator_set_indexes, it);
435                 break;
436               }
437           }
438           hash_unset_mem(lcm->locator_set_index_by_name, ls->name);
439           vec_free(ls->name);
440         }
441       pool_put(lcm->locator_set_pool, ls);
442     }
443   return 0;
444 }
445
446 static inline
447 uword *vnet_lisp_get_locator(vnet_lisp_add_del_locator_set_args_t * a,
448                              uword *p)
449 {
450   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
451
452   ASSERT(a != NULL);
453   ASSERT(p != NULL);
454
455   /* find locator-set */
456   if (a->local)
457   {
458       p = hash_get_mem(lcm->locator_set_index_by_name, a->name);
459   }
460   else
461   {
462       *p = a->index;
463   }
464
465   return p;
466 }
467
468 int
469 vnet_lisp_add_del_locator_set_name (vnet_lisp_add_del_locator_set_args_t * a,
470                                     u32 * ls_result)
471 {
472   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
473   locator_set_t * ls;
474   uword _p = (u32)~0, * p = &_p;
475   u32 ls_index = ~0;
476   u32 **eid_indexes = NULL;
477
478   ASSERT(a != NULL);
479   ASSERT(ls_result != NULL);
480
481   p = vnet_lisp_get_locator(a, p);
482
483   if (a->is_add)
484     {
485       /* overwrite */
486       if (p && p[0] != (u32)~0)
487         {
488           ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
489           if (!ls)
490             {
491               clib_warning("locator-set %d to be overwritten doesn't exist!",
492                            p[0]);
493               return VNET_API_ERROR_UNSPECIFIED;
494             }
495
496           /* clean locator to locator-set vectors and remove locators if
497            * they're not part of another locator-set */
498           clean_locator_to_locator_set (lcm, p[0]);
499
500           /* remove locator indices from locator set */
501           vec_free(ls->locator_indices);
502
503           ls_index = p[0];
504
505           if (ls_result)
506             ls_result[0] = p[0];
507         }
508       /* new locator-set */
509       else
510         {
511           pool_get(lcm->locator_set_pool, ls);
512           ls_index = ls - lcm->locator_set_pool;
513
514           if (a->local)
515             {
516               ls->name = vec_dup(a->name);
517
518               if (!lcm->locator_set_index_by_name)
519                 lcm->locator_set_index_by_name = hash_create_vec(
520                     /* size */0, sizeof(ls->name[0]), sizeof(uword));
521               hash_set_mem(lcm->locator_set_index_by_name, ls->name, ls_index);
522
523               /* mark as local locator-set */
524               vec_add1(lcm->local_locator_set_indexes, ls_index);
525             }
526           ls->local = a->local;
527           ls->locator_indices = NULL;
528           if (ls_result)
529             ls_result[0] = ls_index;
530         }
531     }
532   else
533     {
534        if (!p)
535        {
536            clib_warning("locator-set %v doesn't exists", a->name);
537            return VNET_API_ERROR_INVALID_ARGUMENT;
538        }
539
540        ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
541        if (!ls)
542        {
543            clib_warning("locator-set with index %d doesn't exists", p[0]);
544            return VNET_API_ERROR_INVALID_ARGUMENT;
545        }
546
547       if (vec_len(lcm->locator_set_to_eids) != 0)
548       {
549           eid_indexes = vec_elt_at_index(lcm->locator_set_to_eids, p[0]);
550           if (vec_len(eid_indexes[0]) != 0)
551           {
552               clib_warning ("Can't delete a locator that supports a mapping!");
553               return -1;
554           }
555       }
556
557       /* clean locator to locator-sets data */
558       clean_locator_to_locator_set (lcm, p[0]);
559
560       if (ls->local)
561         {
562           u32 it, lsi;
563
564           vec_foreach_index(it, lcm->local_locator_set_indexes)
565             {
566               lsi = vec_elt(lcm->local_locator_set_indexes, it);
567               if (lsi == p[0])
568                 {
569                   vec_del1(lcm->local_locator_set_indexes, it);
570                   break;
571                 }
572             }
573           hash_unset_mem(lcm->locator_set_index_by_name, ls->name);
574           vec_free(ls->name);
575         }
576       pool_put(lcm->locator_set_pool, ls);
577     }
578   return 0;
579 }
580
581 int
582 vnet_lisp_add_del_locator (vnet_lisp_add_del_locator_set_args_t *a,
583                            u32 *ls_result)
584 {
585   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
586   locator_set_t *ls = NULL;
587   locator_t *loc = NULL, *itloc = NULL;
588   uword _p = (u32)~0, * p = &_p;
589   u32 loc_index = ~0, ls_index = ~0, *locit = NULL, **ls_indexes = NULL;
590   u32 i = ~0;
591
592   ASSERT(a != NULL);
593   ASSERT(ls_result != NULL);
594
595   p = vnet_lisp_get_locator(a, p);
596   if (!p) {
597       clib_warning("locator-set %v doesn't exists", a->name);
598       return VNET_API_ERROR_INVALID_ARGUMENT;
599   }
600
601   ls_index = p[0];
602
603   if (a->is_add)
604     {
605         ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
606         if (!ls)
607         {
608             clib_warning("locator-set %d to be overwritten doesn't exist!",
609                          p[0]);
610             return VNET_API_ERROR_INVALID_ARGUMENT;
611         }
612
613         if (ls_result)
614             ls_result[0] = p[0];
615
616       /* allocate locators */
617       itloc = a->locators;
618       pool_get(lcm->locator_pool, loc);
619       loc[0] = itloc[0];
620       loc_index = loc - lcm->locator_pool;
621
622       vec_add1(ls->locator_indices, loc_index);
623
624       vec_validate (lcm->locator_to_locator_sets, loc_index);
625       ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
626                                     loc_index);
627       vec_add1(ls_indexes[0], ls_index);
628     }
629   else
630     {
631       ls = pool_elt_at_index(lcm->locator_set_pool, p[0]);
632       if (!ls)
633         {
634           clib_warning("locator-set with index %d doesn't exists", p[0]);
635           return VNET_API_ERROR_INVALID_ARGUMENT;
636         }
637
638       if (ls->local)
639       {
640           itloc = a->locators;
641           i = 0;
642           vec_foreach (locit, ls->locator_indices)
643           {
644               loc = pool_elt_at_index(lcm->locator_pool, locit[0]);
645               if (loc->local && loc->sw_if_index == itloc->sw_if_index)
646               {
647                   ls_indexes = vec_elt_at_index(lcm->locator_to_locator_sets,
648                                                 locit[0]);
649                   pool_put_index(lcm->locator_pool, locit[0]);
650                   vec_del1(ls->locator_indices, i);
651                   vec_del1(ls_indexes[0], ls_index);
652               }
653               i++;
654           }
655       }
656     }
657   return 0;
658 }
659
660 static clib_error_t *
661 lisp_add_del_locator_set_command_fn (vlib_main_t * vm, unformat_input_t * input,
662                                      vlib_cli_command_t * cmd)
663 {
664   lisp_gpe_main_t * lgm = &lisp_gpe_main;
665   vnet_main_t * vnm = lgm->vnet_main;
666   unformat_input_t _line_input, * line_input = &_line_input;
667   u8 is_add = 1;
668   clib_error_t * error = 0;
669   u8 * locator_set_name = 0;
670   locator_t locator, * locators = 0;
671   vnet_lisp_add_del_locator_set_args_t _a, * a = &_a;
672   u32 ls_index = 0;
673
674   memset(&locator, 0, sizeof(locator));
675   memset(a, 0, sizeof(a[0]));
676
677   /* Get a line of input. */
678   if (! unformat_user (input, unformat_line_input, line_input))
679     return 0;
680
681   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
682     {
683       if (unformat (line_input, "add %_%v%_", &locator_set_name))
684         is_add = 1;
685       else if (unformat (line_input, "del %_%v%_", &locator_set_name))
686         is_add = 0;
687       else if (unformat (line_input, "iface %U p %d w %d",
688                          unformat_vnet_sw_interface, vnm, &locator.sw_if_index,
689                          &locator.priority, &locator.weight))
690         {
691           locator.local = 1;
692           vec_add1(locators, locator);
693         }
694       else
695         {
696           error = unformat_parse_error(line_input);
697           goto done;
698         }
699     }
700
701   a->name = locator_set_name;
702   a->locators = locators;
703   a->is_add = is_add;
704   a->local = 1;
705
706   vnet_lisp_add_del_locator_set(a, &ls_index);
707
708  done:
709   vec_free(locators);
710   vec_free(locator_set_name);
711   return error;
712 }
713
714 VLIB_CLI_COMMAND (lisp_cp_add_del_locator_set_command) = {
715     .path = "lisp locator-set",
716     .short_help = "lisp locator-set add/del <name> iface <iface-name> "
717         "<priority> <weight>",
718     .function = lisp_add_del_locator_set_command_fn,
719 };
720
721 static clib_error_t *
722 lisp_cp_show_locator_sets_command_fn (vlib_main_t * vm,
723                                       unformat_input_t * input,
724                                       vlib_cli_command_t * cmd)
725 {
726   locator_set_t * lsit;
727   locator_t * loc;
728   u32 * locit;
729   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
730
731   vlib_cli_output (vm, "%=20s%=16s%=16s%=16s", "Locator-set", "Locator",
732                    "Priority", "Weight");
733   pool_foreach (lsit, lcm->locator_set_pool,
734   ({
735     u8 * msg = 0;
736     msg = format (msg, "%-16v", lsit->name);
737     vec_foreach (locit, lsit->locator_indices)
738       {
739         loc = pool_elt_at_index (lcm->locator_pool, locit[0]);
740         if (loc->local)
741           msg = format (msg, "%16d%16d%16d", loc->sw_if_index, loc->priority,
742                         loc->weight);
743         else
744           msg = format (msg, "%16U%16d%16d", format_gid_address, &loc->address,
745                         loc->priority, loc->weight);
746       }
747     vlib_cli_output (vm, "%v", msg);
748     vec_free (msg);
749   }));
750   return 0;
751 }
752
753 VLIB_CLI_COMMAND (lisp_cp_show_locator_sets_command) = {
754     .path = "show lisp locator-set",
755     .short_help = "Shows locator-sets",
756     .function = lisp_cp_show_locator_sets_command_fn,
757 };
758
759 int
760 vnet_lisp_add_del_map_resolver (vnet_lisp_add_del_map_resolver_args_t * a)
761 {
762   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
763   ip_address_t * addr;
764   u32 i;
765
766   if (a->is_add)
767     {
768       vec_foreach(addr, lcm->map_resolvers)
769         {
770           if (!ip_address_cmp (addr, &a->address))
771             {
772               clib_warning("map-resolver %U already exists!", format_ip_address,
773                            &a->address);
774               return -1;
775             }
776         }
777       vec_add1(lcm->map_resolvers, a->address);
778     }
779   else
780     {
781       for (i = 0; i < vec_len(lcm->map_resolvers); i++)
782         {
783           addr = vec_elt_at_index(lcm->map_resolvers, i);
784           if (!ip_address_cmp (addr, &a->address))
785             {
786               vec_delete(lcm->map_resolvers, 1, i);
787               break;
788             }
789         }
790     }
791   return 0;
792 }
793
794 static clib_error_t *
795 lisp_add_del_map_resolver_command_fn (vlib_main_t * vm,
796                                          unformat_input_t * input,
797                                          vlib_cli_command_t * cmd)
798 {
799   unformat_input_t _line_input, * line_input = &_line_input;
800   u8 is_add = 1;
801   ip_address_t ip_addr;
802   clib_error_t * error = 0;
803   vnet_lisp_add_del_map_resolver_args_t _a, * a = &_a;
804
805   /* Get a line of input. */
806   if (! unformat_user (input, unformat_line_input, line_input))
807     return 0;
808
809   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
810     {
811       if (unformat (line_input, "add"))
812         is_add = 1;
813       else if (unformat (line_input, "del"))
814         is_add = 0;
815       else if (unformat (line_input, "%U", unformat_ip_address, &ip_addr))
816         ;
817       else
818         {
819           error = unformat_parse_error(line_input);
820           goto done;
821         }
822     }
823   a->is_add = is_add;
824   a->address = ip_addr;
825   vnet_lisp_add_del_map_resolver (a);
826
827  done:
828   return error;
829 }
830
831 VLIB_CLI_COMMAND (lisp_add_del_map_resolver_command) = {
832     .path = "lisp map-resolver",
833     .short_help = "lisp map-resolver add/del <ip_address>",
834     .function = lisp_add_del_map_resolver_command_fn,
835 };
836
837 /* Statistics (not really errors) */
838 #define foreach_lisp_cp_lookup_error           \
839 _(DROP, "drop")                                \
840 _(MAP_REQUESTS_SENT, "map-request sent")
841
842 static char * lisp_cp_lookup_error_strings[] = {
843 #define _(sym,string) string,
844   foreach_lisp_cp_lookup_error
845 #undef _
846 };
847
848 typedef enum
849 {
850 #define _(sym,str) LISP_CP_LOOKUP_ERROR_##sym,
851     foreach_lisp_cp_lookup_error
852 #undef _
853     LISP_CP_LOOKUP_N_ERROR,
854 } lisp_cp_lookup_error_t;
855
856 typedef enum
857 {
858   LISP_CP_LOOKUP_NEXT_DROP,
859   LISP_CP_LOOKUP_NEXT_IP4_LOOKUP,
860   LISP_CP_LOOKUP_NEXT_IP6_LOOKUP,
861   LISP_CP_LOOKUP_N_NEXT,
862 } lisp_cp_lookup_next_t;
863
864 typedef struct
865 {
866   gid_address_t dst_eid;
867   ip4_address_t map_resolver_ip;
868 } lisp_cp_lookup_trace_t;
869
870 u8 *
871 format_lisp_cp_lookup_trace (u8 * s, va_list * args)
872 {
873   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
874   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
875   lisp_cp_lookup_trace_t * t = va_arg (*args, lisp_cp_lookup_trace_t *);
876
877   s = format (s, "LISP-CP-LOOKUP: map-resolver: %U destination eid %U",
878               format_ip_address, &t->map_resolver_ip, format_gid_address,
879               &t->dst_eid);
880   return s;
881 }
882
883 static u32
884 ip_fib_lookup_with_table (lisp_cp_main_t * lcm, u32 fib_index,
885                           ip_address_t * dst)
886 {
887   if (ip_addr_version (dst) == IP4)
888       return ip4_fib_lookup_with_table (lcm->im4, fib_index, &ip_addr_v4(dst),
889                                         0);
890   else
891       return ip6_fib_lookup_with_table (lcm->im6, fib_index, &ip_addr_v6(dst));
892 }
893
894 void
895 get_local_iface_ip_for_dst (lisp_cp_main_t *lcm, ip_address_t * dst,
896                             ip_address_t * sloc)
897 {
898   u32 adj_index;
899   ip_adjacency_t * adj;
900   ip_interface_address_t * ia = 0;
901   ip_lookup_main_t * lm;
902   ip4_address_t * l4 = 0;
903   ip6_address_t * l6 = 0;
904
905   lm = ip_addr_version (dst) == IP4 ?
906       &lcm->im4->lookup_main : &lcm->im6->lookup_main;
907
908   adj_index = ip_fib_lookup_with_table (lcm, 0, dst);
909   adj = ip_get_adjacency (lm, adj_index);
910
911   if (adj->lookup_next_index == IP_LOOKUP_NEXT_ARP)
912     {
913       ia = pool_elt_at_index(lm->if_address_pool, adj->if_address_index);
914       if (ip_addr_version(dst) == IP4)
915         {
916           l4 = ip_interface_address_get_address (lm, ia);
917         }
918       else
919         {
920           l6 = ip_interface_address_get_address (lm, ia);
921         }
922     }
923   else if (adj->lookup_next_index == IP_LOOKUP_NEXT_REWRITE)
924     {
925       /* find sw_if_index in rewrite header */
926       u32 sw_if_index = adj->rewrite_header.sw_if_index;
927
928       /* find suitable address */
929       if (ip_addr_version(dst) == IP4)
930         {
931           /* find the first ip address */
932           foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
933                                         sw_if_index, 1 /* unnumbered */,
934           ({
935             l4 = ip_interface_address_get_address (&lcm->im4->lookup_main, ia);
936             break;
937           }));
938         }
939       else
940         {
941           /* find the first ip address */
942           foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
943                                         sw_if_index, 1 /* unnumbered */,
944           ({
945             l6 = ip_interface_address_get_address (&lcm->im6->lookup_main, ia);
946             break;
947           }));
948         }
949     }
950   else
951     {
952       clib_warning("Can't find local local interface ip for dst %U",
953                    format_ip_address, dst);
954       return;
955     }
956
957   if (l4)
958     {
959       ip_addr_v4(sloc).as_u32 = l4->as_u32;
960       ip_addr_version(sloc) = IP4;
961     }
962   else if (l6)
963     {
964       clib_memcpy (&ip_addr_v6(sloc), l6, sizeof(*l6));
965       ip_addr_version(sloc) = IP6;
966     }
967   else
968     {
969       clib_warning("Can't find local interface addr for dst %U",
970                    format_ip_address, dst);
971     }
972 }
973
974
975 static ip_address_t *
976 build_itr_rloc_list (lisp_cp_main_t * lcm, locator_set_t * loc_set)
977 {
978   ip4_address_t * l4;
979   ip6_address_t * l6;
980   u32 i;
981   locator_t * loc;
982   u32 * loc_indexp;
983   ip_interface_address_t * ia = 0;
984   ip_address_t * rlocs = 0;
985   ip_address_t _rloc, * rloc = &_rloc;
986
987   for (i = 0; i < vec_len(loc_set->locator_indices); i++)
988     {
989       loc_indexp = vec_elt_at_index(loc_set->locator_indices, i);
990       loc = pool_elt_at_index (lcm->locator_pool, loc_indexp[0]);
991
992       ip_addr_version(rloc) = IP4;
993       /* Add ipv4 locators first TODO sort them */
994       foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
995                                     loc->sw_if_index, 1 /* unnumbered */,
996       ({
997         l4 = ip_interface_address_get_address (&lcm->im4->lookup_main, ia);
998   ip_addr_v4(rloc) = l4[0];
999   vec_add1(rlocs, rloc[0]);
1000       }));
1001
1002       ip_addr_version(rloc) = IP6;
1003       /* Add ipv6 locators */
1004       foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
1005                                     loc->sw_if_index, 1 /* unnumbered */,
1006       ({
1007   l6 = ip_interface_address_get_address (&lcm->im6->lookup_main, ia);
1008   ip_addr_v6(rloc) = l6[0];
1009   vec_add1(rlocs, rloc[0]);
1010       }));
1011     }
1012   return rlocs;
1013 }
1014
1015 static vlib_buffer_t *
1016 build_encapsulated_map_request (vlib_main_t * vm, lisp_cp_main_t *lcm,
1017                                 gid_address_t * seid, gid_address_t * deid,
1018                                 locator_set_t * loc_set, u8 is_smr_invoked,
1019                                 u64 *nonce_res, u32 * bi_res)
1020 {
1021   vlib_buffer_t * b;
1022   u32 bi;
1023   ip_address_t * mr_ip, sloc;
1024   ip_address_t * rlocs = 0;
1025
1026   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
1027     {
1028       clib_warning ("Can't allocate buffer for Map-Request!");
1029       return 0;
1030     }
1031
1032   b = vlib_get_buffer (vm, bi);
1033
1034   /* leave some space for the encap headers */
1035   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
1036
1037   /* get rlocs */
1038   rlocs = build_itr_rloc_list (lcm, loc_set);
1039
1040   /* put lisp msg */
1041   lisp_msg_put_mreq (lcm, b, seid, deid, rlocs, is_smr_invoked, nonce_res);
1042
1043   /* push ecm: udp-ip-lisp */
1044   lisp_msg_push_ecm (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, seid, deid);
1045
1046   /* get map-resolver ip XXX use first*/
1047   mr_ip = vec_elt_at_index(lcm->map_resolvers, 0);
1048
1049   /* get local iface ip to use in map-request XXX fib 0 for now*/
1050   get_local_iface_ip_for_dst (lcm, mr_ip, &sloc);
1051
1052   /* push outer ip header */
1053   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, &sloc,
1054                        mr_ip);
1055
1056   bi_res[0] = bi;
1057
1058   if (rlocs)
1059     vec_free(rlocs);
1060   return b;
1061 }
1062
1063 static void
1064 send_encapsulated_map_request (vlib_main_t * vm, lisp_cp_main_t *lcm,
1065                                gid_address_t * seid, gid_address_t * deid,
1066                                u8 is_smr_invoked)
1067 {
1068   u32 next_index, bi = 0, * to_next, map_index;
1069   vlib_buffer_t * b;
1070   vlib_frame_t * f;
1071   u64 nonce = 0;
1072   locator_set_t * loc_set;
1073   mapping_t * map;
1074   pending_map_request_t * pmr;
1075
1076   /* get locator-set for seid */
1077   map_index = gid_dictionary_lookup (&lcm->mapping_index_by_gid, seid);
1078   if (map_index == ~0)
1079     {
1080       clib_warning("No local mapping found in eid-table for %U!",
1081                    format_gid_address, seid);
1082       return;
1083     }
1084
1085   map = pool_elt_at_index (lcm->mapping_pool, map_index);
1086
1087   if (!map->local)
1088     {
1089       clib_warning("Mapping found for src eid %U is not marked as local!",
1090                    format_gid_address, seid);
1091       return;
1092     }
1093   loc_set = pool_elt_at_index (lcm->locator_set_pool, map->locator_set_index);
1094
1095   /* build the encapsulated map request */
1096   b = build_encapsulated_map_request (vm, lcm, seid, deid, loc_set,
1097                                       is_smr_invoked, &nonce, &bi);
1098
1099   if (!b)
1100     return;
1101
1102   vnet_buffer(b)->sw_if_index[VLIB_TX] = ~0;
1103   next_index = (ip_prefix_version(&gid_address_ippref(seid)) == IP4) ?
1104       ip4_lookup_node.index : ip6_lookup_node.index;
1105
1106   f = vlib_get_frame_to_node (vm, next_index);
1107
1108   /* Enqueue the packet */
1109   to_next = vlib_frame_vector_args (f);
1110   to_next[0] = bi;
1111   f->n_vectors = 1;
1112   vlib_put_frame_to_node (vm, next_index, f);
1113
1114   /* add map-request to pending requests table */
1115   pool_get(lcm->pending_map_requests_pool, pmr);
1116   gid_address_copy (&pmr->src, seid);
1117   gid_address_copy (&pmr->dst, deid);
1118   pmr->src_mapping_index = map_index;
1119   hash_set(lcm->pending_map_requests_by_nonce, nonce,
1120            pmr - lcm->pending_map_requests_pool);
1121 }
1122
1123 static void
1124 get_src_and_dst (void *hdr, ip_address_t * src, ip_address_t *dst)
1125 {
1126   ip4_header_t * ip4 = hdr;
1127   ip6_header_t * ip6;
1128
1129   if ((ip4->ip_version_and_header_length & 0xF0) == 0x40)
1130     {
1131       ip_addr_v4(src).as_u32 = ip4->src_address.as_u32;
1132       ip_addr_version(src) = IP4;
1133       ip_addr_v4(dst).as_u32 = ip4->dst_address.as_u32;
1134       ip_addr_version(dst) = IP4;
1135     }
1136   else
1137     {
1138       ip6 = hdr;
1139       clib_memcpy (&ip_addr_v6(src), &ip6->src_address, sizeof(ip6->src_address));
1140       ip_addr_version(src) = IP6;
1141       clib_memcpy (&ip_addr_v6(dst), &ip6->dst_address, sizeof(ip6->dst_address));
1142       ip_addr_version(dst) = IP6;
1143     }
1144 }
1145
1146 static uword
1147 lisp_cp_lookup (vlib_main_t * vm, vlib_node_runtime_t * node,
1148               vlib_frame_t * from_frame)
1149 {
1150   u32 * from, * to_next_drop;
1151   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main();
1152   u32 pkts_mapped = 0;
1153   uword n_left_from, n_left_to_next_drop;
1154
1155   from = vlib_frame_vector_args (from_frame);
1156   n_left_from = from_frame->n_vectors;
1157
1158   while (n_left_from > 0)
1159     {
1160       vlib_get_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
1161                            to_next_drop, n_left_to_next_drop);
1162
1163       while (n_left_from > 0 && n_left_to_next_drop > 0)
1164         {
1165           u32 pi0;
1166           vlib_buffer_t * p0;
1167           ip4_header_t * ip0;
1168           gid_address_t src, dst;
1169           ip_prefix_t * spref, * dpref;
1170
1171           gid_address_type (&src) = IP_PREFIX;
1172           spref = &gid_address_ippref(&src);
1173           gid_address_type (&dst) = IP_PREFIX;
1174           dpref = &gid_address_ippref(&dst);
1175
1176           pi0 = from[0];
1177           from += 1;
1178           n_left_from -= 1;
1179           to_next_drop[0] = pi0;
1180           to_next_drop += 1;
1181           n_left_to_next_drop -= 1;
1182
1183           p0 = vlib_get_buffer (vm, pi0);
1184           p0->error = node->errors[LISP_CP_LOOKUP_ERROR_DROP];
1185
1186           /* src/dst eid pair */
1187           ip0 = vlib_buffer_get_current (p0);
1188           get_src_and_dst (ip0, &ip_prefix_addr(spref), &ip_prefix_addr(dpref));
1189           ip_prefix_len(spref) = ip_address_max_len (ip_prefix_version(spref));
1190           ip_prefix_len(dpref) = ip_address_max_len (ip_prefix_version(dpref));
1191
1192           /* send map-request */
1193           send_encapsulated_map_request (vm, lcm, &src, &dst, 0);
1194
1195           pkts_mapped++;
1196
1197           if (PREDICT_FALSE(p0->flags & VLIB_BUFFER_IS_TRACED))
1198             {
1199               lisp_cp_lookup_trace_t *tr = vlib_add_trace (vm, node, p0,
1200                                                           sizeof(*tr));
1201               gid_address_copy (&tr->dst_eid, &dst);
1202               clib_memcpy (&tr->map_resolver_ip,
1203                       vec_elt_at_index(lcm->map_resolvers, 0),
1204                       sizeof(ip_address_t));
1205             }
1206         }
1207
1208       vlib_put_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP, n_left_to_next_drop);
1209     }
1210   vlib_node_increment_counter (vm, node->node_index,
1211                                LISP_CP_LOOKUP_ERROR_MAP_REQUESTS_SENT,
1212                                pkts_mapped);
1213   return from_frame->n_vectors;
1214 }
1215
1216 VLIB_REGISTER_NODE (lisp_cp_lookup_node) = {
1217   .function = lisp_cp_lookup,
1218   .name = "lisp-cp-lookup",
1219   .vector_size = sizeof (u32),
1220   .format_trace = format_lisp_cp_lookup_trace,
1221   .type = VLIB_NODE_TYPE_INTERNAL,
1222
1223   .n_errors = LISP_CP_LOOKUP_N_ERROR,
1224   .error_strings = lisp_cp_lookup_error_strings,
1225
1226   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
1227
1228   .next_nodes = {
1229       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
1230       [LISP_CP_LOOKUP_NEXT_IP4_LOOKUP] = "ip4-lookup",
1231       [LISP_CP_LOOKUP_NEXT_IP6_LOOKUP] = "ip6-lookup",
1232   },
1233 };
1234
1235 /* lisp_cp_input statistics */
1236 #define foreach_lisp_cp_input_error                   \
1237 _(DROP, "drop")                                        \
1238 _(MAP_REPLIES_RECEIVED, "map-replies received")
1239
1240 static char * lisp_cp_input_error_strings[] = {
1241 #define _(sym,string) string,
1242   foreach_lisp_cp_input_error
1243 #undef _
1244 };
1245
1246 typedef enum
1247 {
1248 #define _(sym,str) LISP_CP_INPUT_ERROR_##sym,
1249     foreach_lisp_cp_input_error
1250 #undef _
1251     LISP_CP_INPUT_N_ERROR,
1252 } lisp_cp_input_error_t;
1253
1254 typedef enum
1255 {
1256   LISP_CP_INPUT_NEXT_DROP,
1257   LISP_CP_INPUT_N_NEXT,
1258 } lisp_cp_input_next_t;
1259
1260 typedef struct
1261 {
1262   gid_address_t dst_eid;
1263   ip4_address_t map_resolver_ip;
1264 } lisp_cp_input_trace_t;
1265
1266 u8 *
1267 format_lisp_cp_input_trace (u8 * s, va_list * args)
1268 {
1269   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1270   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1271   CLIB_UNUSED(lisp_cp_input_trace_t * t) = va_arg (*args, lisp_cp_input_trace_t *);
1272
1273   s = format (s, "LISP-CP-INPUT: TODO");
1274   return s;
1275 }
1276
1277 ip_interface_address_t *
1278 ip_interface_get_first_interface_address (ip_lookup_main_t *lm, u32 sw_if_index,
1279                                           u8 loop)
1280 {
1281   vnet_main_t *vnm = vnet_get_main ();
1282   vnet_sw_interface_t * swif = vnet_get_sw_interface (vnm, sw_if_index);
1283   if (loop && swif->flags & VNET_SW_INTERFACE_FLAG_UNNUMBERED)
1284     sw_if_index = swif->unnumbered_sw_if_index;
1285   u32 ia =
1286       (vec_len((lm)->if_address_pool_index_by_sw_if_index) > (sw_if_index)) ?
1287           vec_elt((lm)->if_address_pool_index_by_sw_if_index, (sw_if_index)) :
1288           (u32) ~0;
1289   return pool_elt_at_index((lm)->if_address_pool, ia);
1290 }
1291
1292 void *
1293 ip_interface_get_first_ip_addres (ip_lookup_main_t *lm, u32 sw_if_index,
1294                                    u8 loop)
1295 {
1296   ip_interface_address_t * ia = ip_interface_get_first_interface_address (
1297       lm, sw_if_index, loop);
1298   return ip_interface_address_get_address (lm, ia);
1299 }
1300
1301 void
1302 del_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index,
1303                u32 dst_map_index)
1304 {
1305   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, * a = &_a;
1306   fwd_entry_t * fe = 0;
1307   uword * feip = 0;
1308   memset(a, 0, sizeof(*a));
1309
1310   feip = hash_get(lcm->fwd_entry_by_mapping_index, dst_map_index);
1311   if (!feip)
1312     return;
1313
1314   fe = pool_elt_at_index(lcm->fwd_entry_pool, feip[0]);
1315
1316   /* delete dp fwd entry */
1317   u32 sw_if_index;
1318   a->is_add = 0;
1319   a->dlocator = fe->dst_loc;
1320   a->slocator = fe->src_loc;
1321   a->vni = 0; // XXX should be part of mapping/eid
1322   gid_address_copy(&a->deid, &fe->deid);
1323
1324   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
1325
1326   /* delete entry in fwd table */
1327   hash_unset(lcm->fwd_entry_by_mapping_index, dst_map_index);
1328   pool_put(lcm->fwd_entry_pool, fe);
1329 }
1330
1331 void
1332 add_fwd_entry (lisp_cp_main_t* lcm, u32 src_map_index, u32 dst_map_index)
1333 {
1334   mapping_t * src_map, * dst_map;
1335   locator_set_t * dst_ls, * src_ls;
1336   u32 i, minp = ~0;
1337   locator_t * dl = 0;
1338   uword * feip = 0, * tidp;
1339   fwd_entry_t* fe;
1340   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, * a = &_a;
1341
1342   memset (a, 0, sizeof(*a));
1343
1344   /* remove entry if it already exists */
1345   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
1346   if (feip)
1347     del_fwd_entry (lcm, src_map_index, dst_map_index);
1348
1349   src_map = pool_elt_at_index (lcm->mapping_pool, src_map_index);
1350   dst_map = pool_elt_at_index (lcm->mapping_pool, dst_map_index);
1351
1352   /* XXX simple forwarding policy: first lowest (value) priority locator */
1353   dst_ls = pool_elt_at_index (lcm->locator_set_pool,
1354                               dst_map->locator_set_index);
1355   for (i = 0; i < vec_len (dst_ls->locator_indices); i++)
1356     {
1357       u32 li = vec_elt (dst_ls->locator_indices, i);
1358       locator_t * l = pool_elt_at_index (lcm->locator_pool, li);
1359       if (l->priority < minp && gid_address_type(&l->address) == IP_PREFIX)
1360         {
1361           minp = l->priority;
1362           dl = l;
1363         }
1364     }
1365   if (dl)
1366     {
1367       src_ls = pool_elt_at_index (lcm->locator_set_pool,
1368                                   src_map->locator_set_index);
1369       for (i = 0; i < vec_len (src_ls->locator_indices); i++)
1370         {
1371           u32 li = vec_elt (src_ls->locator_indices, i);
1372           locator_t * sl = pool_elt_at_index (lcm->locator_pool, li);
1373
1374           if (ip_addr_version(&gid_address_ip(&dl->address)) == IP4)
1375             {
1376               ip4_address_t * l4;
1377               l4 = ip_interface_get_first_ip_addres (&lcm->im4->lookup_main,
1378                                                      sl->sw_if_index,
1379                                                      1 /* unnumbered */);
1380               ip_addr_v4(&a->slocator) = *l4;
1381               ip_addr_version(&a->slocator) = IP4;
1382             }
1383           else
1384             {
1385               ip6_address_t * l6;
1386               l6 = ip_interface_get_first_ip_addres (&lcm->im6->lookup_main,
1387                                                      sl->sw_if_index,
1388                                                      1 /* unnumbered */);
1389               ip_addr_v6(&a->slocator) = *l6;
1390               ip_addr_version(&a->slocator) = IP6;
1391             }
1392         }
1393     }
1394   /* insert data plane forwarding entry */
1395   u32 sw_if_index;
1396   a->is_add = 1;
1397   if (dl)
1398     a->dlocator = gid_address_ip(&dl->address);
1399   else
1400     {
1401       a->is_negative = 1;
1402       a->action = dst_map->action;
1403     }
1404
1405   gid_address_copy (&a->deid, &dst_map->eid);
1406   a->vni = 0; // XXX should be part of mapping/eid
1407
1408   tidp = hash_get(lcm->table_id_by_vni, a->vni);
1409   if (!tidp)
1410     {
1411       clib_warning("vni %d not associated to a vrf!", a->vni);
1412       return;
1413     }
1414   a->table_id = tidp[0];
1415
1416   /* TODO remove */
1417   u8 ipver = ip_prefix_version(&gid_address_ippref(&a->deid));
1418   a->decap_next_index = (ipver == IP4) ?
1419           LISP_GPE_INPUT_NEXT_IP4_INPUT : LISP_GPE_INPUT_NEXT_IP6_INPUT;
1420
1421   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
1422
1423   /* add tunnel to fwd entry table XXX check return value from DP insertion */
1424   pool_get (lcm->fwd_entry_pool, fe);
1425   fe->dst_loc = a->dlocator;
1426   fe->src_loc = a->slocator;
1427   gid_address_copy (&fe->deid, &a->deid);
1428   hash_set (lcm->fwd_entry_by_mapping_index, dst_map_index,
1429             fe - lcm->fwd_entry_pool);
1430 }
1431
1432 /* return 0 if the two locator sets are identical 1 otherwise */
1433 static u8
1434 compare_locators (lisp_cp_main_t *lcm, u32 * old_ls_indexes,
1435                   locator_t * new_locators)
1436 {
1437   u32 i, old_li;
1438   locator_t * old_loc, * new_loc;
1439
1440   if (vec_len (old_ls_indexes) != vec_len(new_locators))
1441     return 1;
1442
1443   for (i = 0; i < vec_len(new_locators); i++)
1444     {
1445       old_li = vec_elt(old_ls_indexes, i);
1446       old_loc = pool_elt_at_index(lcm->locator_pool, old_li);
1447
1448       new_loc = vec_elt_at_index(new_locators, i);
1449
1450       if (locator_cmp (old_loc, new_loc))
1451         return 1;
1452     }
1453   return 0;
1454 }
1455
1456 void
1457 process_map_reply (lisp_cp_main_t * lcm, vlib_buffer_t * b)
1458 {
1459   u32 len = 0, i, ls_index = 0;
1460   void * h;
1461   vnet_lisp_add_del_locator_set_args_t _ls_arg, * ls_arg = &_ls_arg;
1462   vnet_lisp_add_del_mapping_args_t _m_args, * m_args = &_m_args;
1463   pending_map_request_t * pmr;
1464   locator_t probed;
1465   map_reply_hdr_t * mrep_hdr;
1466   u64 nonce;
1467   u32 dst_map_index, mi;
1468   uword * pmr_index;
1469
1470   mrep_hdr = vlib_buffer_get_current (b);
1471
1472   /* Check pending requests table and nonce */
1473   nonce = MREP_NONCE(mrep_hdr);
1474   pmr_index = hash_get(lcm->pending_map_requests_by_nonce, nonce);
1475   if (!pmr_index)
1476     {
1477       clib_warning("No pending map-request entry with nonce %lu!", nonce);
1478       return;
1479     }
1480   pmr = pool_elt_at_index(lcm->pending_map_requests_pool, pmr_index[0]);
1481
1482   vlib_buffer_pull (b, sizeof(*mrep_hdr));
1483
1484   for (i = 0; i < MREP_REC_COUNT(mrep_hdr); i++)
1485     {
1486       memset (ls_arg, 0, sizeof(*ls_arg));
1487       memset (m_args, 0, sizeof(*m_args));
1488
1489       h = vlib_buffer_get_current (b);
1490       m_args->ttl = clib_net_to_host_u32 (MAP_REC_TTL(h));
1491       m_args->action = MAP_REC_ACTION(h);
1492       m_args->authoritative = MAP_REC_AUTH(h);
1493
1494       len = lisp_msg_parse_mapping_record (b, &m_args->deid, &ls_arg->locators,
1495                                            &probed);
1496       if (len == ~0)
1497         {
1498           clib_warning ("Failed to parse mapping record!");
1499           vec_free(ls_arg->locators);
1500           return;
1501         }
1502
1503       mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &m_args->deid);
1504
1505       /* if mapping already exists, decide if locators (and forwarding) should
1506        * be updated and be done */
1507       if (mi != ~0)
1508         {
1509           mapping_t * old_map;
1510           locator_set_t * old_ls;
1511           old_map = pool_elt_at_index(lcm->mapping_pool, mi);
1512
1513           /* update mapping attributes */
1514           old_map->action = m_args->action;
1515           old_map->authoritative = m_args->authoritative;
1516           old_map->ttl = m_args->ttl;
1517
1518           old_ls = pool_elt_at_index(lcm->locator_set_pool,
1519                                      old_map->locator_set_index);
1520           /* if the two locators are not equal, update them and forwarding
1521            * otherwise there's nothing to be done */
1522           if (compare_locators (lcm, old_ls->locator_indices, ls_arg->locators))
1523             {
1524               /* set locator-set index to overwrite */
1525               ls_arg->is_add = 1;
1526               ls_arg->index = old_map->locator_set_index;
1527               vnet_lisp_add_del_locator_set (ls_arg, 0);
1528               add_fwd_entry (lcm, pmr->src_mapping_index, mi);
1529             }
1530         }
1531       /* new mapping */
1532       else
1533         {
1534           /* add locator-set */
1535           ls_arg->is_add = 1;
1536           ls_arg->index = ~0;
1537           vnet_lisp_add_del_locator_set (ls_arg, &ls_index);
1538
1539           /* add mapping */
1540           m_args->is_add = 1;
1541           m_args->locator_set_index = ls_index;
1542           vnet_lisp_add_del_mapping (m_args, &dst_map_index);
1543
1544           /* add forwarding tunnel */
1545           add_fwd_entry (lcm, pmr->src_mapping_index, dst_map_index);
1546         }
1547       vec_free(ls_arg->locators);
1548     }
1549
1550   /* remove pending map request entry */
1551   hash_unset(lcm->pending_map_requests_by_nonce, nonce);
1552   pool_put(lcm->pending_map_requests_pool, pmr);
1553 }
1554
1555 void
1556 process_map_request (vlib_main_t * vm, lisp_cp_main_t * lcm, vlib_buffer_t * b)
1557 {
1558   map_request_hdr_t * mreq_hdr;
1559   gid_address_t src, dst;
1560 //  u64 nonce;
1561   u32 i, len = 0;
1562   gid_address_t * itr_rlocs = 0;
1563
1564   mreq_hdr = vlib_buffer_get_current (b);
1565   vlib_buffer_pull (b, sizeof(*mreq_hdr));
1566
1567 //  nonce = MREQ_NONCE(mreq_hdr);
1568
1569   if (!MREQ_SMR(mreq_hdr)) {
1570       clib_warning("Only SMR Map-Requests supported for now!");
1571       return;
1572   }
1573
1574   /* parse src eid */
1575   len = lisp_msg_parse_addr (b, &src);
1576   if (len == ~0)
1577     return;
1578
1579   /* for now we don't do anything with the itr's rlocs */
1580   len = lisp_msg_parse_itr_rlocs (b, &itr_rlocs, MREQ_ITR_RLOC_COUNT(mreq_hdr) + 1);
1581   if (len == ~0)
1582     return;
1583
1584   /* parse eid records and send SMR-invoked map-requests */
1585   for (i = 0; i < MREQ_REC_COUNT(mreq_hdr); i++)
1586     {
1587       memset(&dst, 0, sizeof(dst));
1588       len = lisp_msg_parse_eid_rec (b, &dst);
1589       if (len == ~0)
1590         {
1591           clib_warning("Can't parse map-request EID-record");
1592           return;
1593         }
1594       /* send SMR-invoked map-requests */
1595       send_encapsulated_map_request (vm, lcm, &dst, &src, /* invoked */ 1);
1596     }
1597 }
1598
1599 static uword
1600 lisp_cp_input (vlib_main_t * vm, vlib_node_runtime_t * node,
1601                vlib_frame_t * from_frame)
1602 {
1603   u32 n_left_from, * from, * to_next_drop;
1604   lisp_msg_type_e type;
1605   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
1606
1607   from = vlib_frame_vector_args (from_frame);
1608   n_left_from = from_frame->n_vectors;
1609
1610
1611   while (n_left_from > 0)
1612     {
1613       u32 n_left_to_next_drop;
1614
1615       vlib_get_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
1616                            to_next_drop, n_left_to_next_drop);
1617       while (n_left_from > 0 && n_left_to_next_drop > 0)
1618         {
1619           u32 bi0;
1620           vlib_buffer_t * b0;
1621
1622           bi0 = from[0];
1623           from += 1;
1624           n_left_from -= 1;
1625           to_next_drop[0] = bi0;
1626           to_next_drop += 1;
1627           n_left_to_next_drop -= 1;
1628
1629           b0 = vlib_get_buffer (vm, bi0);
1630
1631           type = lisp_msg_type(vlib_buffer_get_current (b0));
1632           switch (type)
1633             {
1634             case LISP_MAP_REPLY:
1635               process_map_reply (lcm, b0);
1636               break;
1637             case LISP_MAP_REQUEST:
1638               process_map_request(vm, lcm, b0);
1639               break;
1640             default:
1641               clib_warning("Unsupported LISP message type %d", type);
1642               break;
1643             }
1644
1645           b0->error = node->errors[LISP_CP_INPUT_ERROR_DROP];
1646
1647           if (PREDICT_FALSE(b0->flags & VLIB_BUFFER_IS_TRACED))
1648             {
1649
1650             }
1651         }
1652
1653       vlib_put_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP, n_left_to_next_drop);
1654     }
1655   return from_frame->n_vectors;
1656 }
1657
1658 VLIB_REGISTER_NODE (lisp_cp_input_node) = {
1659   .function = lisp_cp_input,
1660   .name = "lisp-cp-input",
1661   .vector_size = sizeof (u32),
1662   .format_trace = format_lisp_cp_input_trace,
1663   .type = VLIB_NODE_TYPE_INTERNAL,
1664
1665   .n_errors = LISP_CP_INPUT_N_ERROR,
1666   .error_strings = lisp_cp_input_error_strings,
1667
1668   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
1669
1670   .next_nodes = {
1671       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
1672   },
1673 };
1674
1675 clib_error_t *
1676 lisp_cp_init (vlib_main_t *vm)
1677 {
1678   lisp_cp_main_t * lcm = vnet_lisp_cp_get_main();
1679   clib_error_t * error = 0;
1680
1681   if ((error = vlib_call_init_function (vm, lisp_gpe_init)))
1682     return error;
1683
1684   lcm->im4 = &ip4_main;
1685   lcm->im6 = &ip6_main;
1686   lcm->vlib_main = vm;
1687   lcm->vnet_main = vnet_get_main();
1688
1689   gid_dictionary_init (&lcm->mapping_index_by_gid);
1690
1691   /* default vrf mapped to vni 0 */
1692   hash_set(lcm->table_id_by_vni, 0, 0);
1693
1694   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp,
1695                          lisp_cp_input_node.index, 1 /* is_ip4 */);
1696   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp6,
1697                          lisp_cp_input_node.index, 0 /* is_ip4 */);
1698
1699   return 0;
1700 }
1701
1702 VLIB_INIT_FUNCTION(lisp_cp_init);