map: use SVR for MAP-T
[vpp.git] / src / plugins / map / map.c
1 /*
2  * map.c : MAP support
3  *
4  * Copyright (c) 2015 Cisco and/or its affiliates.
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <vnet/fib/fib_table.h>
19 #include <vnet/fib/fib_entry_track.h>
20 #include <vnet/fib/ip6_fib.h>
21 #include <vnet/adj/adj.h>
22 #include <vppinfra/crc32.h>
23 #include <vnet/plugin/plugin.h>
24 #include <vpp/app/version.h>
25 #include "map.h"
26
27 map_main_t map_main;
28
29 /*
30  * This code supports the following MAP modes:
31  *
32  * Algorithmic Shared IPv4 address (ea_bits_len > 0):
33  *   ea_bits_len + ip4_prefix > 32
34  *   psid_length > 0, ip6_prefix < 64, ip4_prefix <= 32
35  * Algorithmic Full IPv4 address (ea_bits_len > 0):
36  *   ea_bits_len + ip4_prefix = 32
37  *   psid_length = 0, ip6_prefix < 64, ip4_prefix <= 32
38  * Algorithmic IPv4 prefix (ea_bits_len > 0):
39  *   ea_bits_len + ip4_prefix < 32
40  *   psid_length = 0, ip6_prefix < 64, ip4_prefix <= 32
41  *
42  * Independent Shared IPv4 address (ea_bits_len = 0):
43  *   ip4_prefix = 32
44  *   psid_length > 0
45  *   Rule IPv6 address = 128, Rule PSID Set
46  * Independent Full IPv4 address (ea_bits_len = 0):
47  *   ip4_prefix = 32
48  *   psid_length = 0, ip6_prefix = 128
49  * Independent IPv4 prefix (ea_bits_len = 0):
50  *   ip4_prefix < 32
51  *   psid_length = 0, ip6_prefix = 128
52  *
53  */
54
55 /*
56  * This code supports MAP-T:
57  *
58  * With a DMR prefix length of 64 or 96 (RFC6052).
59  *
60  */
61
62
63 /*
64  * Save user-assigned MAP domain names ("tags") in a vector of
65  * extra domain information.
66  */
67 static void
68 map_save_extras (u32 map_domain_index, u8 * tag)
69 {
70   map_main_t *mm = &map_main;
71   map_domain_extra_t *de;
72
73   if (map_domain_index == ~0)
74     return;
75
76   vec_validate (mm->domain_extras, map_domain_index);
77   de = vec_elt_at_index (mm->domain_extras, map_domain_index);
78   clib_memset (de, 0, sizeof (*de));
79
80   if (!tag)
81     return;
82
83   de->tag = vec_dup (tag);
84 }
85
86
87 static void
88 map_free_extras (u32 map_domain_index)
89 {
90   map_main_t *mm = &map_main;
91   map_domain_extra_t *de;
92   u8 *tag;
93
94   if (map_domain_index == ~0)
95     return;
96
97   de = vec_elt_at_index (mm->domain_extras, map_domain_index);
98   tag = de->tag;
99   if (!tag)
100     return;
101
102   vec_free (tag);
103   de->tag = 0;
104 }
105
106
107 int
108 map_create_domain (ip4_address_t * ip4_prefix,
109                    u8 ip4_prefix_len,
110                    ip6_address_t * ip6_prefix,
111                    u8 ip6_prefix_len,
112                    ip6_address_t * ip6_src,
113                    u8 ip6_src_len,
114                    u8 ea_bits_len,
115                    u8 psid_offset,
116                    u8 psid_length,
117                    u32 * map_domain_index, u16 mtu, u8 flags, u8 * tag)
118 {
119   u8 suffix_len, suffix_shift;
120   map_main_t *mm = &map_main;
121   map_domain_t *d;
122
123   /* How many, and which bits to grab from the IPv4 DA */
124   if (ip4_prefix_len + ea_bits_len < 32)
125     {
126       flags |= MAP_DOMAIN_PREFIX;
127       suffix_shift = 32 - ip4_prefix_len - ea_bits_len;
128       suffix_len = ea_bits_len;
129     }
130   else
131     {
132       suffix_shift = 0;
133       suffix_len = 32 - ip4_prefix_len;
134     }
135
136   /* EA bits must be within the first 64 bits */
137   if (ea_bits_len > 0 && ((ip6_prefix_len + ea_bits_len) > 64 ||
138                           ip6_prefix_len + suffix_len + psid_length > 64))
139     {
140       clib_warning
141         ("Embedded Address bits must be within the first 64 bits of "
142          "the IPv6 prefix");
143       return -1;
144     }
145
146   /* Get domain index */
147   pool_get_aligned (mm->domains, d, CLIB_CACHE_LINE_BYTES);
148   clib_memset (d, 0, sizeof (*d));
149   *map_domain_index = d - mm->domains;
150
151   /* Init domain struct */
152   d->ip4_prefix.as_u32 = ip4_prefix->as_u32;
153   d->ip4_prefix_len = ip4_prefix_len;
154   d->ip6_prefix = *ip6_prefix;
155   d->ip6_prefix_len = ip6_prefix_len;
156   d->ip6_src = *ip6_src;
157   d->ip6_src_len = ip6_src_len;
158   d->ea_bits_len = ea_bits_len;
159   d->psid_offset = psid_offset;
160   d->psid_length = psid_length;
161   d->mtu = mtu;
162   d->flags = flags;
163   d->suffix_shift = suffix_shift;
164   d->suffix_mask = (1 << suffix_len) - 1;
165
166   d->psid_shift = 16 - psid_length - psid_offset;
167   d->psid_mask = (1 << d->psid_length) - 1;
168   d->ea_shift = 64 - ip6_prefix_len - suffix_len - d->psid_length;
169
170   /* Save a user-assigned MAP domain name if provided. */
171   if (tag)
172     map_save_extras (*map_domain_index, tag);
173
174   /* MAP longest match lookup table (input feature / FIB) */
175   mm->ip4_prefix_tbl->add (mm->ip4_prefix_tbl, &d->ip4_prefix,
176                            d->ip4_prefix_len, *map_domain_index);
177
178   /* Really needed? Or always use FIB? */
179   mm->ip6_src_prefix_tbl->add (mm->ip6_src_prefix_tbl, &d->ip6_src,
180                                d->ip6_src_len, *map_domain_index);
181
182   /* Validate packet/byte counters */
183   map_domain_counter_lock (mm);
184   int i;
185   for (i = 0; i < vec_len (mm->simple_domain_counters); i++)
186     {
187       vlib_validate_simple_counter (&mm->simple_domain_counters[i],
188                                     *map_domain_index);
189       vlib_zero_simple_counter (&mm->simple_domain_counters[i],
190                                 *map_domain_index);
191     }
192   for (i = 0; i < vec_len (mm->domain_counters); i++)
193     {
194       vlib_validate_combined_counter (&mm->domain_counters[i],
195                                       *map_domain_index);
196       vlib_zero_combined_counter (&mm->domain_counters[i], *map_domain_index);
197     }
198   map_domain_counter_unlock (mm);
199
200   return 0;
201 }
202
203 /*
204  * map_delete_domain
205  */
206 int
207 map_delete_domain (u32 map_domain_index)
208 {
209   map_main_t *mm = &map_main;
210   map_domain_t *d;
211
212   if (pool_is_free_index (mm->domains, map_domain_index))
213     {
214       clib_warning ("MAP domain delete: domain does not exist: %d",
215                     map_domain_index);
216       return -1;
217     }
218
219   d = pool_elt_at_index (mm->domains, map_domain_index);
220   mm->ip4_prefix_tbl->delete (mm->ip4_prefix_tbl, &d->ip4_prefix,
221                               d->ip4_prefix_len);
222   mm->ip6_src_prefix_tbl->delete (mm->ip6_src_prefix_tbl, &d->ip6_src,
223                                   d->ip6_src_len);
224
225   /* Release user-assigned MAP domain name. */
226   map_free_extras (map_domain_index);
227
228   /* Deleting rules */
229   if (d->rules)
230     clib_mem_free (d->rules);
231
232   pool_put (mm->domains, d);
233
234   return 0;
235 }
236
237 int
238 map_add_del_psid (u32 map_domain_index, u16 psid, ip6_address_t * tep,
239                   bool is_add)
240 {
241   map_domain_t *d;
242   map_main_t *mm = &map_main;
243
244   if (pool_is_free_index (mm->domains, map_domain_index))
245     {
246       clib_warning ("MAP rule: domain does not exist: %d", map_domain_index);
247       return -1;
248     }
249   d = pool_elt_at_index (mm->domains, map_domain_index);
250
251   /* Rules are only used in 1:1 independent case */
252   if (d->ea_bits_len > 0)
253     return (-1);
254
255   if (!d->rules)
256     {
257       u32 l = (0x1 << d->psid_length) * sizeof (ip6_address_t);
258       d->rules = clib_mem_alloc_aligned (l, CLIB_CACHE_LINE_BYTES);
259       if (!d->rules)
260         return -1;
261       clib_memset (d->rules, 0, l);
262     }
263
264   if (psid >= (0x1 << d->psid_length))
265     {
266       clib_warning ("MAP rule: PSID outside bounds: %d [%d]", psid,
267                     0x1 << d->psid_length);
268       return -1;
269     }
270
271   if (is_add)
272     {
273       d->rules[psid] = *tep;
274     }
275   else
276     {
277       clib_memset (&d->rules[psid], 0, sizeof (ip6_address_t));
278     }
279   return 0;
280 }
281
282 #ifdef MAP_SKIP_IP6_LOOKUP
283 /**
284  * Pre-resolved per-protocol global next-hops
285  */
286 map_main_pre_resolved_t pre_resolved[FIB_PROTOCOL_MAX];
287
288 static void
289 map_pre_resolve_init (map_main_pre_resolved_t * pr)
290 {
291   pr->fei = FIB_NODE_INDEX_INVALID;
292   fib_node_init (&pr->node, FIB_NODE_TYPE_MAP_E);
293 }
294
295 static u8 *
296 format_map_pre_resolve (u8 * s, va_list * ap)
297 {
298   map_main_pre_resolved_t *pr = va_arg (*ap, map_main_pre_resolved_t *);
299
300   if (FIB_NODE_INDEX_INVALID != pr->fei)
301     {
302       const fib_prefix_t *pfx;
303
304       pfx = fib_entry_get_prefix (pr->fei);
305
306       return (format (s, "%U (%u)",
307                       format_ip46_address, &pfx->fp_addr, IP46_TYPE_ANY,
308                       pr->dpo.dpoi_index));
309     }
310   else
311     {
312       return (format (s, "un-set"));
313     }
314 }
315
316
317 /**
318  * Function definition to inform the FIB node that its last lock has gone.
319  */
320 static void
321 map_last_lock_gone (fib_node_t * node)
322 {
323   /*
324    * The MAP is a root of the graph. As such
325    * it never has children and thus is never locked.
326    */
327   ASSERT (0);
328 }
329
330 static map_main_pre_resolved_t *
331 map_from_fib_node (fib_node_t * node)
332 {
333   ASSERT (FIB_NODE_TYPE_MAP_E == node->fn_type);
334   return ((map_main_pre_resolved_t *)
335           (((char *) node) -
336            STRUCT_OFFSET_OF (map_main_pre_resolved_t, node)));
337 }
338
339 static void
340 map_stack (map_main_pre_resolved_t * pr)
341 {
342   const dpo_id_t *dpo;
343
344   dpo = fib_entry_contribute_ip_forwarding (pr->fei);
345
346   dpo_copy (&pr->dpo, dpo);
347 }
348
349 /**
350  * Function definition to backwalk a FIB node
351  */
352 static fib_node_back_walk_rc_t
353 map_back_walk (fib_node_t * node, fib_node_back_walk_ctx_t * ctx)
354 {
355   map_stack (map_from_fib_node (node));
356
357   return (FIB_NODE_BACK_WALK_CONTINUE);
358 }
359
360 /**
361  * Function definition to get a FIB node from its index
362  */
363 static fib_node_t *
364 map_fib_node_get (fib_node_index_t index)
365 {
366   return (&pre_resolved[index].node);
367 }
368
369 /*
370  * Virtual function table registered by MPLS GRE tunnels
371  * for participation in the FIB object graph.
372  */
373 const static fib_node_vft_t map_vft = {
374   .fnv_get = map_fib_node_get,
375   .fnv_last_lock = map_last_lock_gone,
376   .fnv_back_walk = map_back_walk,
377 };
378
379 static void
380 map_fib_resolve (map_main_pre_resolved_t * pr,
381                  fib_protocol_t proto, u8 len, const ip46_address_t * addr)
382 {
383   fib_prefix_t pfx = {
384     .fp_proto = proto,
385     .fp_len = len,
386     .fp_addr = *addr,
387   };
388
389   pr->fei = fib_entry_track (0, // default fib
390                              &pfx, FIB_NODE_TYPE_MAP_E, proto, &pr->sibling);
391   map_stack (pr);
392 }
393
394 static void
395 map_fib_unresolve (map_main_pre_resolved_t * pr,
396                    fib_protocol_t proto, u8 len, const ip46_address_t * addr)
397 {
398   if (pr->fei != FIB_NODE_INDEX_INVALID)
399     {
400       fib_entry_untrack (pr->fei, pr->sibling);
401
402       dpo_reset (&pr->dpo);
403
404       pr->fei = FIB_NODE_INDEX_INVALID;
405       pr->sibling = FIB_NODE_INDEX_INVALID;
406     }
407 }
408
409 void
410 map_pre_resolve (ip4_address_t * ip4, ip6_address_t * ip6, bool is_del)
411 {
412   if (ip6 && (ip6->as_u64[0] != 0 || ip6->as_u64[1] != 0))
413     {
414       ip46_address_t addr = {
415         .ip6 = *ip6,
416       };
417       if (is_del)
418         map_fib_unresolve (&pre_resolved[FIB_PROTOCOL_IP6],
419                            FIB_PROTOCOL_IP6, 128, &addr);
420       else
421         map_fib_resolve (&pre_resolved[FIB_PROTOCOL_IP6],
422                          FIB_PROTOCOL_IP6, 128, &addr);
423     }
424   if (ip4 && (ip4->as_u32 != 0))
425     {
426       ip46_address_t addr = {
427         .ip4 = *ip4,
428       };
429       if (is_del)
430         map_fib_unresolve (&pre_resolved[FIB_PROTOCOL_IP4],
431                            FIB_PROTOCOL_IP4, 32, &addr);
432       else
433         map_fib_resolve (&pre_resolved[FIB_PROTOCOL_IP4],
434                          FIB_PROTOCOL_IP4, 32, &addr);
435     }
436 }
437 #endif
438
439 static clib_error_t *
440 map_security_check_command_fn (vlib_main_t * vm,
441                                unformat_input_t * input,
442                                vlib_cli_command_t * cmd)
443 {
444   unformat_input_t _line_input, *line_input = &_line_input;
445   clib_error_t *error = NULL;
446   bool enable = false;
447   bool check_frag = false;
448   bool saw_enable = false;
449   bool saw_frag = false;
450
451   /* Get a line of input. */
452   if (!unformat_user (input, unformat_line_input, line_input))
453     return 0;
454
455   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
456     {
457       if (unformat (line_input, "enable"))
458         {
459           enable = false;
460           saw_enable = true;
461         }
462       else if (unformat (line_input, "disable"))
463         {
464           enable = true;
465           saw_enable = true;
466         }
467       else if (unformat (line_input, "fragments on"))
468         {
469           check_frag = true;
470           saw_frag = true;
471         }
472       else if (unformat (line_input, "fragments off"))
473         {
474           check_frag = false;
475           saw_frag = true;
476         }
477       else
478         {
479           error = clib_error_return (0, "unknown input `%U'",
480                                      format_unformat_error, line_input);
481           goto done;
482         }
483     }
484
485   if (!saw_enable)
486     {
487       error = clib_error_return (0,
488                                  "Must specify enable 'enable' or 'disable'");
489       goto done;
490     }
491
492   if (!saw_frag)
493     {
494       error = clib_error_return (0, "Must specify fragments 'on' or 'off'");
495       goto done;
496     }
497
498   map_param_set_security_check (enable, check_frag);
499
500 done:
501   unformat_free (line_input);
502
503   return error;
504 }
505
506
507 static clib_error_t *
508 map_add_domain_command_fn (vlib_main_t * vm,
509                            unformat_input_t * input, vlib_cli_command_t * cmd)
510 {
511   unformat_input_t _line_input, *line_input = &_line_input;
512   ip4_address_t ip4_prefix;
513   ip6_address_t ip6_prefix;
514   ip6_address_t ip6_src;
515   u32 ip6_prefix_len = 0, ip4_prefix_len = 0, map_domain_index, ip6_src_len;
516   u32 num_m_args = 0;
517   /* Optional arguments */
518   u32 ea_bits_len = 0, psid_offset = 0, psid_length = 0;
519   u32 mtu = 0;
520   u8 flags = 0;
521   u8 *tag = 0;
522   ip6_src_len = 128;
523   clib_error_t *error = NULL;
524
525   /* Get a line of input. */
526   if (!unformat_user (input, unformat_line_input, line_input))
527     return 0;
528
529   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
530     {
531       if (unformat
532           (line_input, "ip4-pfx %U/%d", unformat_ip4_address, &ip4_prefix,
533            &ip4_prefix_len))
534         num_m_args++;
535       else
536         if (unformat
537             (line_input, "ip6-pfx %U/%d", unformat_ip6_address, &ip6_prefix,
538              &ip6_prefix_len))
539         num_m_args++;
540       else
541         if (unformat
542             (line_input, "ip6-src %U/%d", unformat_ip6_address, &ip6_src,
543              &ip6_src_len))
544         num_m_args++;
545       else
546         if (unformat
547             (line_input, "ip6-src %U", unformat_ip6_address, &ip6_src))
548         num_m_args++;
549       else if (unformat (line_input, "ea-bits-len %d", &ea_bits_len))
550         num_m_args++;
551       else if (unformat (line_input, "psid-offset %d", &psid_offset))
552         num_m_args++;
553       else if (unformat (line_input, "psid-len %d", &psid_length))
554         num_m_args++;
555       else if (unformat (line_input, "mtu %d", &mtu))
556         num_m_args++;
557       else if (unformat (line_input, "tag %v", &tag))
558         ;
559       else
560         {
561           error = clib_error_return (0, "unknown input `%U'",
562                                      format_unformat_error, line_input);
563           goto done;
564         }
565     }
566
567   if (num_m_args < 3)
568     {
569       error = clib_error_return (0, "mandatory argument(s) missing");
570       goto done;
571     }
572
573   map_create_domain (&ip4_prefix, ip4_prefix_len,
574                      &ip6_prefix, ip6_prefix_len, &ip6_src, ip6_src_len,
575                      ea_bits_len, psid_offset, psid_length, &map_domain_index,
576                      mtu, flags, tag);
577
578 done:
579   unformat_free (line_input);
580
581   return error;
582 }
583
584 static clib_error_t *
585 map_del_domain_command_fn (vlib_main_t * vm,
586                            unformat_input_t * input, vlib_cli_command_t * cmd)
587 {
588   unformat_input_t _line_input, *line_input = &_line_input;
589   u32 num_m_args = 0;
590   u32 map_domain_index;
591   clib_error_t *error = NULL;
592
593   /* Get a line of input. */
594   if (!unformat_user (input, unformat_line_input, line_input))
595     return 0;
596
597   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
598     {
599       if (unformat (line_input, "index %d", &map_domain_index))
600         num_m_args++;
601       else
602         {
603           error = clib_error_return (0, "unknown input `%U'",
604                                      format_unformat_error, line_input);
605           goto done;
606         }
607     }
608
609   if (num_m_args != 1)
610     {
611       error = clib_error_return (0, "mandatory argument(s) missing");
612       goto done;
613     }
614
615   map_delete_domain (map_domain_index);
616
617 done:
618   unformat_free (line_input);
619
620   return error;
621 }
622
623 static clib_error_t *
624 map_add_rule_command_fn (vlib_main_t * vm,
625                          unformat_input_t * input, vlib_cli_command_t * cmd)
626 {
627   unformat_input_t _line_input, *line_input = &_line_input;
628   ip6_address_t tep;
629   u32 num_m_args = 0;
630   u32 psid = 0, map_domain_index;
631   clib_error_t *error = NULL;
632
633   /* Get a line of input. */
634   if (!unformat_user (input, unformat_line_input, line_input))
635     return 0;
636
637   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
638     {
639       if (unformat (line_input, "index %d", &map_domain_index))
640         num_m_args++;
641       else if (unformat (line_input, "psid %d", &psid))
642         num_m_args++;
643       else
644         if (unformat (line_input, "ip6-dst %U", unformat_ip6_address, &tep))
645         num_m_args++;
646       else
647         {
648           error = clib_error_return (0, "unknown input `%U'",
649                                      format_unformat_error, line_input);
650           goto done;
651         }
652     }
653
654   if (num_m_args != 3)
655     {
656       error = clib_error_return (0, "mandatory argument(s) missing");
657       goto done;
658     }
659
660   if (map_add_del_psid (map_domain_index, psid, &tep, 1) != 0)
661     {
662       error = clib_error_return (0, "Failing to add Mapping Rule");
663       goto done;
664     }
665
666 done:
667   unformat_free (line_input);
668
669   return error;
670 }
671
672 #if MAP_SKIP_IP6_LOOKUP
673 static clib_error_t *
674 map_pre_resolve_command_fn (vlib_main_t * vm,
675                             unformat_input_t * input,
676                             vlib_cli_command_t * cmd)
677 {
678   unformat_input_t _line_input, *line_input = &_line_input;
679   ip4_address_t ip4nh, *p_v4 = NULL;
680   ip6_address_t ip6nh, *p_v6 = NULL;
681   clib_error_t *error = NULL;
682   bool is_del = false;
683
684   clib_memset (&ip4nh, 0, sizeof (ip4nh));
685   clib_memset (&ip6nh, 0, sizeof (ip6nh));
686
687   /* Get a line of input. */
688   if (!unformat_user (input, unformat_line_input, line_input))
689     return 0;
690
691   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
692     {
693       if (unformat (line_input, "ip4-nh %U", unformat_ip4_address, &ip4nh))
694         p_v4 = &ip4nh;
695       else
696         if (unformat (line_input, "ip6-nh %U", unformat_ip6_address, &ip6nh))
697         p_v6 = &ip6nh;
698       else if (unformat (line_input, "del"))
699         is_del = true;
700       else
701         {
702           error = clib_error_return (0, "unknown input `%U'",
703                                      format_unformat_error, line_input);
704           goto done;
705         }
706     }
707
708   map_pre_resolve (p_v4, p_v6, is_del);
709
710 done:
711   unformat_free (line_input);
712
713   return error;
714 }
715 #endif
716
717 static clib_error_t *
718 map_icmp_relay_source_address_command_fn (vlib_main_t * vm,
719                                           unformat_input_t * input,
720                                           vlib_cli_command_t * cmd)
721 {
722   unformat_input_t _line_input, *line_input = &_line_input;
723   ip4_address_t icmp_src_address;
724   ip4_address_t *p_icmp_addr = 0;
725   map_main_t *mm = &map_main;
726   clib_error_t *error = NULL;
727
728   mm->icmp4_src_address.as_u32 = 0;
729
730   /* Get a line of input. */
731   if (!unformat_user (input, unformat_line_input, line_input))
732     return 0;
733
734   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
735     {
736       if (unformat
737           (line_input, "%U", unformat_ip4_address, &icmp_src_address))
738         {
739           mm->icmp4_src_address = icmp_src_address;
740           p_icmp_addr = &icmp_src_address;
741         }
742       else
743         {
744           error = clib_error_return (0, "unknown input `%U'",
745                                      format_unformat_error, line_input);
746           goto done;
747         }
748     }
749
750   map_param_set_icmp (p_icmp_addr);
751
752 done:
753   unformat_free (line_input);
754
755   return error;
756 }
757
758 static clib_error_t *
759 map_icmp_unreachables_command_fn (vlib_main_t * vm,
760                                   unformat_input_t * input,
761                                   vlib_cli_command_t * cmd)
762 {
763   unformat_input_t _line_input, *line_input = &_line_input;
764   int num_m_args = 0;
765   clib_error_t *error = NULL;
766   bool enabled = false;
767
768   /* Get a line of input. */
769   if (!unformat_user (input, unformat_line_input, line_input))
770     return 0;
771
772   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
773     {
774       num_m_args++;
775       if (unformat (line_input, "on"))
776         enabled = true;
777       else if (unformat (line_input, "off"))
778         enabled = false;
779       else
780         {
781           error = clib_error_return (0, "unknown input `%U'",
782                                      format_unformat_error, line_input);
783           goto done;
784         }
785     }
786
787
788   if (num_m_args != 1)
789     error = clib_error_return (0, "mandatory argument(s) missing");
790
791
792   map_param_set_icmp6 (enabled);
793
794 done:
795   unformat_free (line_input);
796
797   return error;
798 }
799
800
801 static clib_error_t *
802 map_fragment_command_fn (vlib_main_t * vm,
803                          unformat_input_t * input, vlib_cli_command_t * cmd)
804 {
805   unformat_input_t _line_input, *line_input = &_line_input;
806   clib_error_t *error = NULL;
807   bool frag_inner = false;
808   bool frag_ignore_df = false;
809   bool saw_in_out = false;
810   bool saw_df = false;
811
812   /* Get a line of input. */
813   if (!unformat_user (input, unformat_line_input, line_input))
814     return 0;
815
816   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
817     {
818       if (unformat (line_input, "inner"))
819         {
820           frag_inner = true;
821           saw_in_out = true;
822         }
823       else if (unformat (line_input, "outer"))
824         {
825           frag_inner = false;
826           saw_in_out = true;
827         }
828       else if (unformat (line_input, "ignore-df"))
829         {
830           frag_ignore_df = true;
831           saw_df = true;
832         }
833       else if (unformat (line_input, "honor-df"))
834         {
835           frag_ignore_df = false;
836           saw_df = true;
837         }
838       else
839         {
840           error = clib_error_return (0, "unknown input `%U'",
841                                      format_unformat_error, line_input);
842           goto done;
843         }
844     }
845
846   if (!saw_in_out)
847     {
848       error = clib_error_return (0, "Must specify 'inner' or 'outer'");
849       goto done;
850     }
851
852   if (!saw_df)
853     {
854       error = clib_error_return (0, "Must specify 'ignore-df' or 'honor-df'");
855       goto done;
856     }
857
858   map_param_set_fragmentation (frag_inner, frag_ignore_df);
859
860 done:
861   unformat_free (line_input);
862
863   return error;
864 }
865
866 static clib_error_t *
867 map_traffic_class_command_fn (vlib_main_t * vm,
868                               unformat_input_t * input,
869                               vlib_cli_command_t * cmd)
870 {
871   unformat_input_t _line_input, *line_input = &_line_input;
872   u32 tc = 0;
873   clib_error_t *error = NULL;
874   bool tc_copy = false;
875
876
877   /* Get a line of input. */
878   if (!unformat_user (input, unformat_line_input, line_input))
879     return 0;
880
881   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
882     {
883       if (unformat (line_input, "copy"))
884         tc_copy = true;
885       else if (unformat (line_input, "%x", &tc))
886         tc = tc & 0xff;
887       else
888         {
889           error = clib_error_return (0, "unknown input `%U'",
890                                      format_unformat_error, line_input);
891           goto done;
892         }
893     }
894
895   map_param_set_traffic_class (tc_copy, tc);
896
897 done:
898   unformat_free (line_input);
899
900   return error;
901 }
902
903 static char *
904 map_flags_to_string (u32 flags)
905 {
906   if (flags & MAP_DOMAIN_PREFIX)
907     return "prefix";
908   return "";
909 }
910
911 static u8 *
912 format_map_domain (u8 * s, va_list * args)
913 {
914   map_domain_t *d = va_arg (*args, map_domain_t *);
915   bool counters = va_arg (*args, int);
916   map_main_t *mm = &map_main;
917   ip6_address_t ip6_prefix;
918   u32 map_domain_index = d - mm->domains;
919   map_domain_extra_t *de;
920
921   if (d->rules)
922     clib_memset (&ip6_prefix, 0, sizeof (ip6_prefix));
923   else
924     ip6_prefix = d->ip6_prefix;
925
926   de = vec_elt_at_index (mm->domain_extras, map_domain_index);
927
928   s = format (s,
929               "[%d] tag {%v} ip4-pfx %U/%d ip6-pfx %U/%d ip6-src %U/%d "
930               "ea-bits-len %d psid-offset %d psid-len %d mtu %d %s",
931               map_domain_index, de->tag,
932               format_ip4_address, &d->ip4_prefix, d->ip4_prefix_len,
933               format_ip6_address, &ip6_prefix, d->ip6_prefix_len,
934               format_ip6_address, &d->ip6_src, d->ip6_src_len,
935               d->ea_bits_len, d->psid_offset, d->psid_length, d->mtu,
936               map_flags_to_string (d->flags));
937
938   if (counters)
939     {
940       map_domain_counter_lock (mm);
941       vlib_counter_t v;
942       vlib_get_combined_counter (&mm->domain_counters[MAP_DOMAIN_COUNTER_TX],
943                                  map_domain_index, &v);
944       s = format (s, "  TX: %lld/%lld", v.packets, v.bytes);
945       vlib_get_combined_counter (&mm->domain_counters[MAP_DOMAIN_COUNTER_RX],
946                                  map_domain_index, &v);
947       s = format (s, "  RX: %lld/%lld", v.packets, v.bytes);
948       map_domain_counter_unlock (mm);
949     }
950   s = format (s, "\n");
951
952   if (d->rules)
953     {
954       int i;
955       ip6_address_t dst;
956       for (i = 0; i < (0x1 << d->psid_length); i++)
957         {
958           dst = d->rules[i];
959           if (dst.as_u64[0] == 0 && dst.as_u64[1] == 0)
960             continue;
961           s = format (s,
962                       " rule psid: %d ip6-dst %U\n", i, format_ip6_address,
963                       &dst);
964         }
965     }
966   return s;
967 }
968
969 static u8 *
970 format_map_ip6_reass (u8 * s, va_list * args)
971 {
972   map_main_t *mm = &map_main;
973   map_ip6_reass_t *r = va_arg (*args, map_ip6_reass_t *);
974   map_ip6_reass_key_t *k = &r->key;
975   f64 now = vlib_time_now (mm->vlib_main);
976   f64 lifetime = (((f64) mm->ip6_reass_conf_lifetime_ms) / 1000);
977   f64 dt = (r->ts + lifetime > now) ? (r->ts + lifetime - now) : -1;
978   s = format (s,
979               "ip6-reass src=%U  dst=%U  protocol=%d  identifier=%d  lifetime=%.3lf\n",
980               format_ip6_address, &k->src.as_u8, format_ip6_address,
981               &k->dst.as_u8, k->protocol,
982               clib_net_to_host_u32 (k->fragment_id), dt);
983   return s;
984 }
985
986 static clib_error_t *
987 show_map_domain_command_fn (vlib_main_t * vm, unformat_input_t * input,
988                             vlib_cli_command_t * cmd)
989 {
990   unformat_input_t _line_input, *line_input = &_line_input;
991   map_main_t *mm = &map_main;
992   map_domain_t *d;
993   bool counters = false;
994   u32 map_domain_index = ~0;
995   clib_error_t *error = NULL;
996
997   /* Get a line of input. */
998   if (!unformat_user (input, unformat_line_input, line_input))
999     return 0;
1000
1001   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1002     {
1003       if (unformat (line_input, "counters"))
1004         counters = true;
1005       else if (unformat (line_input, "index %d", &map_domain_index))
1006         ;
1007       else
1008         {
1009           error = clib_error_return (0, "unknown input `%U'",
1010                                      format_unformat_error, line_input);
1011           goto done;
1012         }
1013     }
1014
1015   if (pool_elts (mm->domains) == 0)
1016     vlib_cli_output (vm, "No MAP domains are configured...");
1017
1018   if (map_domain_index == ~0)
1019     {
1020       /* *INDENT-OFF* */
1021       pool_foreach(d, mm->domains,
1022         ({vlib_cli_output(vm, "%U", format_map_domain, d, counters);}));
1023       /* *INDENT-ON* */
1024     }
1025   else
1026     {
1027       if (pool_is_free_index (mm->domains, map_domain_index))
1028         {
1029           error = clib_error_return (0, "MAP domain does not exists %d",
1030                                      map_domain_index);
1031           goto done;
1032         }
1033
1034       d = pool_elt_at_index (mm->domains, map_domain_index);
1035       vlib_cli_output (vm, "%U", format_map_domain, d, counters);
1036     }
1037
1038 done:
1039   unformat_free (line_input);
1040
1041   return error;
1042 }
1043
1044 static clib_error_t *
1045 show_map_fragments_command_fn (vlib_main_t * vm, unformat_input_t * input,
1046                                vlib_cli_command_t * cmd)
1047 {
1048   map_main_t *mm = &map_main;
1049   map_ip6_reass_t *f6;
1050
1051   /* *INDENT-OFF* */
1052   pool_foreach(f6, mm->ip6_reass_pool, ({vlib_cli_output (vm, "%U", format_map_ip6_reass, f6);}));
1053   /* *INDENT-ON* */
1054   return (0);
1055 }
1056
1057 u64
1058 map_error_counter_get (u32 node_index, map_error_t map_error)
1059 {
1060   vlib_main_t *vm = vlib_get_main ();
1061   vlib_node_runtime_t *error_node = vlib_node_get_runtime (vm, node_index);
1062   vlib_error_main_t *em = &vm->error_main;
1063   vlib_error_t e = error_node->errors[map_error];
1064   vlib_node_t *n = vlib_get_node (vm, node_index);
1065   u32 ci;
1066
1067   ci = vlib_error_get_code (&vm->node_main, e);
1068   ASSERT (ci < n->n_errors);
1069   ci += n->error_heap_index;
1070
1071   return (em->counters[ci]);
1072 }
1073
1074 static clib_error_t *
1075 show_map_stats_command_fn (vlib_main_t * vm, unformat_input_t * input,
1076                            vlib_cli_command_t * cmd)
1077 {
1078   map_main_t *mm = &map_main;
1079   map_domain_t *d;
1080   int domains = 0, rules = 0, domaincount = 0, rulecount = 0;
1081   if (pool_elts (mm->domains) == 0)
1082     {
1083       vlib_cli_output (vm, "No MAP domains are configured...");
1084       return 0;
1085     }
1086
1087   /* *INDENT-OFF* */
1088   pool_foreach(d, mm->domains, ({
1089     if (d->rules) {
1090       rulecount+= 0x1 << d->psid_length;
1091       rules += sizeof(ip6_address_t) * 0x1 << d->psid_length;
1092     }
1093     domains += sizeof(*d);
1094     domaincount++;
1095   }));
1096   /* *INDENT-ON* */
1097
1098   vlib_cli_output (vm, "MAP domains structure: %d\n", sizeof (map_domain_t));
1099   vlib_cli_output (vm, "MAP domains: %d (%d bytes)\n", domaincount, domains);
1100   vlib_cli_output (vm, "MAP rules: %d (%d bytes)\n", rulecount, rules);
1101   vlib_cli_output (vm, "Total: %d bytes)\n", rules + domains);
1102
1103 #if MAP_SKIP_IP6_LOOKUP
1104   vlib_cli_output (vm,
1105                    "MAP pre-resolve: IP6 next-hop: %U, IP4 next-hop: %U\n",
1106                    format_map_pre_resolve, &pre_resolved[FIB_PROTOCOL_IP6],
1107                    format_map_pre_resolve, &pre_resolved[FIB_PROTOCOL_IP4]);
1108
1109 #endif
1110
1111   if (mm->tc_copy)
1112     vlib_cli_output (vm, "MAP traffic-class: copy");
1113   else
1114     vlib_cli_output (vm, "MAP traffic-class: %x", mm->tc);
1115
1116   if (mm->tcp_mss)
1117     vlib_cli_output (vm, "MAP TCP MSS clamping: %u", mm->tcp_mss);
1118
1119   vlib_cli_output (vm,
1120                    "MAP IPv6 inbound security check: %s, fragmented packet security check: %s",
1121                    mm->sec_check ? "enabled" : "disabled",
1122                    mm->sec_check_frag ? "enabled" : "disabled");
1123
1124   vlib_cli_output (vm, "ICMP-relay IPv4 source address: %U\n",
1125                    format_ip4_address, &mm->icmp4_src_address);
1126   vlib_cli_output (vm, "ICMP6 unreachables sent for unmatched packets: %s\n",
1127                    mm->icmp6_enabled ? "enabled" : "disabled");
1128   vlib_cli_output (vm, "Inner fragmentation: %s\n",
1129                    mm->frag_inner ? "enabled" : "disabled");
1130   vlib_cli_output (vm, "Fragment packets regardless of DF flag: %s\n",
1131                    mm->frag_ignore_df ? "enabled" : "disabled");
1132
1133   /*
1134    * Counters
1135    */
1136   vlib_combined_counter_main_t *cm = mm->domain_counters;
1137   u64 total_pkts[MAP_N_DOMAIN_COUNTER];
1138   u64 total_bytes[MAP_N_DOMAIN_COUNTER];
1139   int which, i;
1140   vlib_counter_t v;
1141
1142   clib_memset (total_pkts, 0, sizeof (total_pkts));
1143   clib_memset (total_bytes, 0, sizeof (total_bytes));
1144
1145   map_domain_counter_lock (mm);
1146   vec_foreach (cm, mm->domain_counters)
1147   {
1148     which = cm - mm->domain_counters;
1149
1150     for (i = 0; i < vlib_combined_counter_n_counters (cm); i++)
1151       {
1152         vlib_get_combined_counter (cm, i, &v);
1153         total_pkts[which] += v.packets;
1154         total_bytes[which] += v.bytes;
1155       }
1156   }
1157   map_domain_counter_unlock (mm);
1158
1159   vlib_cli_output (vm, "Encapsulated packets: %lld bytes: %lld\n",
1160                    total_pkts[MAP_DOMAIN_COUNTER_TX],
1161                    total_bytes[MAP_DOMAIN_COUNTER_TX]);
1162   vlib_cli_output (vm, "Decapsulated packets: %lld bytes: %lld\n",
1163                    total_pkts[MAP_DOMAIN_COUNTER_RX],
1164                    total_bytes[MAP_DOMAIN_COUNTER_RX]);
1165
1166   vlib_cli_output (vm, "ICMP relayed packets: %d\n",
1167                    vlib_get_simple_counter (&mm->icmp_relayed, 0));
1168
1169   return 0;
1170 }
1171
1172 static clib_error_t *
1173 map_params_reass_command_fn (vlib_main_t * vm, unformat_input_t * input,
1174                              vlib_cli_command_t * cmd)
1175 {
1176   unformat_input_t _line_input, *line_input = &_line_input;
1177   u32 lifetime = ~0;
1178   f64 ht_ratio = (MAP_IP6_REASS_CONF_HT_RATIO_MAX + 1);
1179   u32 pool_size = ~0;
1180   u64 buffers = ~(0ull);
1181   u8 ip4 = 0, ip6 = 0;
1182
1183   if (!unformat_user (input, unformat_line_input, line_input))
1184     return 0;
1185
1186   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1187     {
1188       if (unformat (line_input, "lifetime %u", &lifetime))
1189         ;
1190       else if (unformat (line_input, "ht-ratio %lf", &ht_ratio))
1191         ;
1192       else if (unformat (line_input, "pool-size %u", &pool_size))
1193         ;
1194       else if (unformat (line_input, "buffers %llu", &buffers))
1195         ;
1196       else if (unformat (line_input, "ip4"))
1197         ip4 = 1;
1198       else if (unformat (line_input, "ip6"))
1199         ip6 = 1;
1200       else
1201         {
1202           unformat_free (line_input);
1203           return clib_error_return (0, "invalid input");
1204         }
1205     }
1206   unformat_free (line_input);
1207
1208   if (!ip4 && !ip6)
1209     return clib_error_return (0, "must specify ip4 and/or ip6");
1210
1211   if (ip4)
1212     {
1213       return clib_error_return (0,
1214                                 "ip4 reassembly no longer supported in map");
1215     }
1216
1217   if (ip6)
1218     {
1219       if (pool_size != ~0 && pool_size > MAP_IP6_REASS_CONF_POOL_SIZE_MAX)
1220         return clib_error_return (0, "invalid ip6-reass pool-size ( > %d)",
1221                                   MAP_IP6_REASS_CONF_POOL_SIZE_MAX);
1222       if (ht_ratio > MAP_IP6_REASS_CONF_HT_RATIO_MAX)
1223         return clib_error_return (0, "invalid ip6-reass ht-log2len ( > %d)",
1224                                   MAP_IP6_REASS_CONF_HT_RATIO_MAX);
1225       if (lifetime != ~0 && lifetime > MAP_IP6_REASS_CONF_LIFETIME_MAX)
1226         return clib_error_return (0, "invalid ip6-reass lifetime ( > %d)",
1227                                   MAP_IP6_REASS_CONF_LIFETIME_MAX);
1228       if (buffers != ~(0ull) && buffers > MAP_IP6_REASS_CONF_BUFFERS_MAX)
1229         return clib_error_return (0, "invalid ip6-reass buffers ( > %ld)",
1230                                   MAP_IP6_REASS_CONF_BUFFERS_MAX);
1231     }
1232
1233   int rv;
1234   u32 reass = 0, packets = 0;
1235   rv = map_param_set_reassembly (!ip4, lifetime, pool_size, buffers, ht_ratio,
1236                                  &reass, &packets);
1237
1238   switch (rv)
1239     {
1240     case 0:
1241       vlib_cli_output (vm,
1242                        "Note: destroyed-reassembly=%u , dropped-fragments=%u",
1243                        reass, packets);
1244       break;
1245
1246     case MAP_ERR_BAD_POOL_SIZE:
1247       return clib_error_return (0, "Could not set reass pool-size");
1248
1249     case MAP_ERR_BAD_HT_RATIO:
1250       return clib_error_return (0, "Could not set reass ht-log2len");
1251
1252     case MAP_ERR_BAD_LIFETIME:
1253       return clib_error_return (0, "Could not set ip6-reass lifetime");
1254
1255     case MAP_ERR_BAD_BUFFERS:
1256       return clib_error_return (0, "Could not set ip6-reass buffers");
1257
1258     case MAP_ERR_BAD_BUFFERS_TOO_LARGE:
1259       return clib_error_return (0,
1260                                 "Note: 'ip6-reass buffers' > pool-size * max-fragments-per-reassembly.");
1261     }
1262
1263   return 0;
1264 }
1265
1266
1267 static clib_error_t *
1268 map_if_command_fn (vlib_main_t * vm,
1269                    unformat_input_t * input, vlib_cli_command_t * cmd)
1270 {
1271   unformat_input_t _line_input, *line_input = &_line_input;
1272   clib_error_t *error = NULL;
1273   bool is_enable = true, is_translation = false;
1274   vnet_main_t *vnm = vnet_get_main ();
1275   u32 sw_if_index = ~0;
1276
1277   /* Get a line of input. */
1278   if (!unformat_user (input, unformat_line_input, line_input))
1279     return 0;
1280
1281   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1282     {
1283       if (unformat
1284           (line_input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index))
1285         ;
1286       else if (unformat (line_input, "del"))
1287         is_enable = false;
1288       else if (unformat (line_input, "map-t"))
1289         is_translation = true;
1290       else
1291         {
1292           error = clib_error_return (0, "unknown input `%U'",
1293                                      format_unformat_error, line_input);
1294           goto done;
1295         }
1296     }
1297
1298 done:
1299   unformat_free (line_input);
1300
1301   if (sw_if_index == ~0)
1302     {
1303       error = clib_error_return (0, "unknown interface");
1304       return error;
1305     }
1306
1307   int rv = map_if_enable_disable (is_enable, sw_if_index, is_translation);
1308   if (rv)
1309     {
1310       error = clib_error_return (0, "failure enabling MAP on interface");
1311     }
1312
1313   return error;
1314 }
1315
1316
1317 /*
1318  * packet trace format function
1319  */
1320 u8 *
1321 format_map_trace (u8 * s, va_list * args)
1322 {
1323   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1324   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1325   map_trace_t *t = va_arg (*args, map_trace_t *);
1326   u32 map_domain_index = t->map_domain_index;
1327   u16 port = t->port;
1328
1329   s =
1330     format (s, "MAP domain index: %d L4 port: %u", map_domain_index,
1331             clib_net_to_host_u16 (port));
1332
1333   return s;
1334 }
1335
1336 static_always_inline map_ip6_reass_t *
1337 map_ip6_reass_lookup (map_ip6_reass_key_t * k, u32 bucket, f64 now)
1338 {
1339   map_main_t *mm = &map_main;
1340   u32 ri = mm->ip6_reass_hash_table[bucket];
1341   while (ri != MAP_REASS_INDEX_NONE)
1342     {
1343       map_ip6_reass_t *r = pool_elt_at_index (mm->ip6_reass_pool, ri);
1344       if (now < r->ts + (((f64) mm->ip6_reass_conf_lifetime_ms) / 1000) &&
1345           r->key.as_u64[0] == k->as_u64[0] &&
1346           r->key.as_u64[1] == k->as_u64[1] &&
1347           r->key.as_u64[2] == k->as_u64[2] &&
1348           r->key.as_u64[3] == k->as_u64[3] &&
1349           r->key.as_u64[4] == k->as_u64[4])
1350         return r;
1351       ri = r->bucket_next;
1352     }
1353   return NULL;
1354 }
1355
1356 #define map_ip6_reass_pool_index(r) (r - map_main.ip6_reass_pool)
1357
1358 void
1359 map_ip6_reass_free (map_ip6_reass_t * r, u32 ** pi_to_drop)
1360 {
1361   map_main_t *mm = &map_main;
1362   int i;
1363   for (i = 0; i < MAP_IP6_REASS_MAX_FRAGMENTS_PER_REASSEMBLY; i++)
1364     if (r->fragments[i].pi != ~0)
1365       {
1366         vec_add1 (*pi_to_drop, r->fragments[i].pi);
1367         r->fragments[i].pi = ~0;
1368         map_main.ip6_reass_buffered_counter--;
1369       }
1370
1371   // Unlink in hash bucket
1372   map_ip6_reass_t *r2 = NULL;
1373   u32 r2i = mm->ip6_reass_hash_table[r->bucket];
1374   while (r2i != map_ip6_reass_pool_index (r))
1375     {
1376       ASSERT (r2i != MAP_REASS_INDEX_NONE);
1377       r2 = pool_elt_at_index (mm->ip6_reass_pool, r2i);
1378       r2i = r2->bucket_next;
1379     }
1380   if (r2)
1381     {
1382       r2->bucket_next = r->bucket_next;
1383     }
1384   else
1385     {
1386       mm->ip6_reass_hash_table[r->bucket] = r->bucket_next;
1387     }
1388
1389   // Unlink in list
1390   if (r->fifo_next == map_ip6_reass_pool_index (r))
1391     {
1392       //Single element in the list, list is now empty
1393       mm->ip6_reass_fifo_last = MAP_REASS_INDEX_NONE;
1394     }
1395   else
1396     {
1397       if (mm->ip6_reass_fifo_last == map_ip6_reass_pool_index (r))      //First element
1398         mm->ip6_reass_fifo_last = r->fifo_prev;
1399       pool_elt_at_index (mm->ip6_reass_pool, r->fifo_prev)->fifo_next =
1400         r->fifo_next;
1401       pool_elt_at_index (mm->ip6_reass_pool, r->fifo_next)->fifo_prev =
1402         r->fifo_prev;
1403     }
1404
1405   // Free from pool if necessary
1406   pool_put (mm->ip6_reass_pool, r);
1407   mm->ip6_reass_allocated--;
1408 }
1409
1410 map_ip6_reass_t *
1411 map_ip6_reass_get (ip6_address_t * src, ip6_address_t * dst, u32 fragment_id,
1412                    u8 protocol, u32 ** pi_to_drop)
1413 {
1414   map_ip6_reass_t *r;
1415   map_main_t *mm = &map_main;
1416   map_ip6_reass_key_t k = {
1417     .src = *src,
1418     .dst = *dst,
1419     .fragment_id = fragment_id,
1420     .protocol = protocol
1421   };
1422
1423   u32 h = 0;
1424   int i;
1425
1426 #ifdef clib_crc32c_uses_intrinsics
1427   h = clib_crc32c ((u8 *) k.as_u32, 40);
1428 #else
1429   u64 tmp =
1430     k.as_u64[0] ^ k.as_u64[1] ^ k.as_u64[2] ^ k.as_u64[3] ^ k.as_u64[4];
1431   h = clib_xxhash (tmp);
1432 #endif
1433
1434   h = h >> (32 - mm->ip6_reass_ht_log2len);
1435
1436   f64 now = vlib_time_now (mm->vlib_main);
1437
1438   //Cache garbage collection
1439   while (mm->ip6_reass_fifo_last != MAP_REASS_INDEX_NONE)
1440     {
1441       map_ip6_reass_t *last =
1442         pool_elt_at_index (mm->ip6_reass_pool, mm->ip6_reass_fifo_last);
1443       if (last->ts + (((f64) mm->ip6_reass_conf_lifetime_ms) / 1000) < now)
1444         map_ip6_reass_free (last, pi_to_drop);
1445       else
1446         break;
1447     }
1448
1449   if ((r = map_ip6_reass_lookup (&k, h, now)))
1450     return r;
1451
1452   if (mm->ip6_reass_allocated >= mm->ip6_reass_conf_pool_size)
1453     return NULL;
1454
1455   pool_get (mm->ip6_reass_pool, r);
1456   mm->ip6_reass_allocated++;
1457   for (i = 0; i < MAP_IP6_REASS_MAX_FRAGMENTS_PER_REASSEMBLY; i++)
1458     {
1459       r->fragments[i].pi = ~0;
1460       r->fragments[i].next_data_len = 0;
1461       r->fragments[i].next_data_offset = 0;
1462     }
1463
1464   u32 ri = map_ip6_reass_pool_index (r);
1465
1466   //Link in new bucket
1467   r->bucket = h;
1468   r->bucket_next = mm->ip6_reass_hash_table[h];
1469   mm->ip6_reass_hash_table[h] = ri;
1470
1471   //Link in fifo
1472   if (mm->ip6_reass_fifo_last != MAP_REASS_INDEX_NONE)
1473     {
1474       r->fifo_next =
1475         pool_elt_at_index (mm->ip6_reass_pool,
1476                            mm->ip6_reass_fifo_last)->fifo_next;
1477       r->fifo_prev = mm->ip6_reass_fifo_last;
1478       pool_elt_at_index (mm->ip6_reass_pool, r->fifo_prev)->fifo_next = ri;
1479       pool_elt_at_index (mm->ip6_reass_pool, r->fifo_next)->fifo_prev = ri;
1480     }
1481   else
1482     {
1483       r->fifo_next = r->fifo_prev = ri;
1484       mm->ip6_reass_fifo_last = ri;
1485     }
1486
1487   //Set other fields
1488   r->ts = now;
1489   r->key = k;
1490   r->ip4_header.ip_version_and_header_length = 0;
1491 #ifdef MAP_IP6_REASS_COUNT_BYTES
1492   r->expected_total = 0xffff;
1493   r->forwarded = 0;
1494 #endif
1495   return r;
1496 }
1497
1498 int
1499 map_ip6_reass_add_fragment (map_ip6_reass_t * r, u32 pi,
1500                             u16 data_offset, u16 next_data_offset,
1501                             u8 * data_start, u16 data_len)
1502 {
1503   map_ip6_fragment_t *f = NULL, *prev_f = NULL;
1504   u16 copied_len = (data_len > 20) ? 20 : data_len;
1505
1506   if (map_main.ip6_reass_buffered_counter >= map_main.ip6_reass_conf_buffers)
1507     return -1;
1508
1509   //Lookup for fragments for the current buffer
1510   //and the one before that
1511   int i;
1512   for (i = 0; i < MAP_IP6_REASS_MAX_FRAGMENTS_PER_REASSEMBLY; i++)
1513     {
1514       if (data_offset && r->fragments[i].next_data_offset == data_offset)
1515         {
1516           prev_f = &r->fragments[i];    // This is buffer for previous packet
1517         }
1518       else if (r->fragments[i].next_data_offset == next_data_offset)
1519         {
1520           f = &r->fragments[i]; // This is a buffer for the current packet
1521         }
1522       else if (r->fragments[i].next_data_offset == 0)
1523         {                       //Available
1524           if (f == NULL)
1525             f = &r->fragments[i];
1526           else if (prev_f == NULL)
1527             prev_f = &r->fragments[i];
1528         }
1529     }
1530
1531   if (!f || f->pi != ~0)
1532     return -1;
1533
1534   if (data_offset)
1535     {
1536       if (!prev_f)
1537         return -1;
1538
1539       clib_memcpy_fast (prev_f->next_data, data_start, copied_len);
1540       prev_f->next_data_len = copied_len;
1541       prev_f->next_data_offset = data_offset;
1542     }
1543   else
1544     {
1545       if (((ip4_header_t *) data_start)->ip_version_and_header_length != 0x45)
1546         return -1;
1547
1548       if (r->ip4_header.ip_version_and_header_length == 0)
1549         clib_memcpy_fast (&r->ip4_header, data_start, sizeof (ip4_header_t));
1550     }
1551
1552   if (data_len > 20)
1553     {
1554       f->next_data_offset = next_data_offset;
1555       f->pi = pi;
1556       map_main.ip6_reass_buffered_counter++;
1557     }
1558   return 0;
1559 }
1560
1561 u8
1562 map_get_ht_log2len (f32 ht_ratio, u16 pool_size)
1563 {
1564   u32 desired_size = (u32) (pool_size * ht_ratio);
1565   u8 i;
1566   for (i = 1; i < 31; i++)
1567     if ((1 << i) >= desired_size)
1568       return i;
1569   return 4;
1570 }
1571
1572 void
1573 map_ip6_reass_reinit (u32 * trashed_reass, u32 * dropped_packets)
1574 {
1575   map_main_t *mm = &map_main;
1576   if (dropped_packets)
1577     *dropped_packets = mm->ip6_reass_buffered_counter;
1578   if (trashed_reass)
1579     *trashed_reass = mm->ip6_reass_allocated;
1580   int i;
1581   if (mm->ip6_reass_fifo_last != MAP_REASS_INDEX_NONE)
1582     {
1583       u16 ri = mm->ip6_reass_fifo_last;
1584       do
1585         {
1586           map_ip6_reass_t *r = pool_elt_at_index (mm->ip6_reass_pool, ri);
1587           for (i = 0; i < MAP_IP6_REASS_MAX_FRAGMENTS_PER_REASSEMBLY; i++)
1588             if (r->fragments[i].pi != ~0)
1589               map_ip6_drop_pi (r->fragments[i].pi);
1590
1591           ri = r->fifo_next;
1592           pool_put (mm->ip6_reass_pool, r);
1593         }
1594       while (ri != mm->ip6_reass_fifo_last);
1595       mm->ip6_reass_fifo_last = MAP_REASS_INDEX_NONE;
1596     }
1597
1598   vec_free (mm->ip6_reass_hash_table);
1599   vec_resize (mm->ip6_reass_hash_table, 1 << mm->ip6_reass_ht_log2len);
1600   for (i = 0; i < (1 << mm->ip6_reass_ht_log2len); i++)
1601     mm->ip6_reass_hash_table[i] = MAP_REASS_INDEX_NONE;
1602   pool_free (mm->ip6_reass_pool);
1603   pool_alloc (mm->ip6_reass_pool, mm->ip6_reass_conf_pool_size);
1604
1605   mm->ip6_reass_allocated = 0;
1606   mm->ip6_reass_buffered_counter = 0;
1607 }
1608
1609 int
1610 map_ip6_reass_conf_ht_ratio (f32 ht_ratio, u32 * trashed_reass,
1611                              u32 * dropped_packets)
1612 {
1613   map_main_t *mm = &map_main;
1614   if (ht_ratio > MAP_IP6_REASS_CONF_HT_RATIO_MAX)
1615     return -1;
1616
1617   map_ip6_reass_lock ();
1618   mm->ip6_reass_conf_ht_ratio = ht_ratio;
1619   mm->ip6_reass_ht_log2len =
1620     map_get_ht_log2len (ht_ratio, mm->ip6_reass_conf_pool_size);
1621   map_ip6_reass_reinit (trashed_reass, dropped_packets);
1622   map_ip6_reass_unlock ();
1623   return 0;
1624 }
1625
1626 int
1627 map_ip6_reass_conf_pool_size (u16 pool_size, u32 * trashed_reass,
1628                               u32 * dropped_packets)
1629 {
1630   map_main_t *mm = &map_main;
1631   if (pool_size > MAP_IP6_REASS_CONF_POOL_SIZE_MAX)
1632     return -1;
1633
1634   map_ip6_reass_lock ();
1635   mm->ip6_reass_conf_pool_size = pool_size;
1636   map_ip6_reass_reinit (trashed_reass, dropped_packets);
1637   map_ip6_reass_unlock ();
1638   return 0;
1639 }
1640
1641 int
1642 map_ip6_reass_conf_lifetime (u16 lifetime_ms)
1643 {
1644   map_main.ip6_reass_conf_lifetime_ms = lifetime_ms;
1645   return 0;
1646 }
1647
1648 int
1649 map_ip6_reass_conf_buffers (u32 buffers)
1650 {
1651   map_main.ip6_reass_conf_buffers = buffers;
1652   return 0;
1653 }
1654
1655 static clib_error_t *
1656 map_tcp_mss_command_fn (vlib_main_t * vm,
1657                         unformat_input_t * input, vlib_cli_command_t * cmd)
1658 {
1659   unformat_input_t _line_input, *line_input = &_line_input;
1660   clib_error_t *error = NULL;
1661   u32 tcp_mss = 0;
1662
1663   /* Get a line of input. */
1664   if (!unformat_user (input, unformat_line_input, line_input))
1665     return 0;
1666
1667   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1668     {
1669       if (unformat (line_input, "%u", &tcp_mss))
1670         ;
1671       else
1672         {
1673           error = clib_error_return (0, "unknown input `%U'",
1674                                      format_unformat_error, line_input);
1675           goto done;
1676         }
1677     }
1678
1679   if (tcp_mss >= (0x1 << 16))
1680     {
1681       error = clib_error_return (0, "invalid value `%u'", tcp_mss);
1682       goto done;
1683     }
1684
1685   map_param_set_tcp (tcp_mss);
1686
1687 done:
1688   unformat_free (line_input);
1689
1690   return error;
1691 }
1692
1693
1694 /* *INDENT-OFF* */
1695
1696 /*?
1697  * Configure MAP reassembly behaviour
1698  *
1699  * @cliexpar
1700  * @cliexstart{map params reassembly}
1701  * @cliexend
1702  ?*/
1703 VLIB_CLI_COMMAND(map_ip4_reass_lifetime_command, static) = {
1704   .path = "map params reassembly",
1705   .short_help = "map params reassembly [ip4 | ip6] [lifetime <lifetime-ms>] "
1706                 "[pool-size <pool-size>] [buffers <buffers>] "
1707                 "[ht-ratio <ht-ratio>]",
1708   .function = map_params_reass_command_fn,
1709 };
1710
1711 /*?
1712  * Set or copy the IP TOS/Traffic Class field
1713  *
1714  * @cliexpar
1715  * @cliexstart{map params traffic-class}
1716  *
1717  * This command is used to set the traffic-class field in translated
1718  * or encapsulated packets. If copy is specifed (the default) then the
1719  * traffic-class/TOS field is copied from the original packet to the
1720  * translated / encapsulating header.
1721  * @cliexend
1722  ?*/
1723 VLIB_CLI_COMMAND(map_traffic_class_command, static) = {
1724   .path = "map params traffic-class",
1725   .short_help = "map params traffic-class {0x0-0xff | copy}",
1726   .function = map_traffic_class_command_fn,
1727 };
1728
1729 /*?
1730  * TCP MSS clamping
1731  *
1732  * @cliexpar
1733  * @cliexstart{map params tcp-mss}
1734  *
1735  * This command is used to set the TCP MSS in translated
1736  * or encapsulated packets.
1737  * @cliexend
1738  ?*/
1739 VLIB_CLI_COMMAND(map_tcp_mss_command, static) = {
1740   .path = "map params tcp-mss",
1741   .short_help = "map params tcp-mss <value>",
1742   .function = map_tcp_mss_command_fn,
1743 };
1744
1745 /*?
1746  * Bypass IP4/IP6 lookup
1747  *
1748  * @cliexpar
1749  * @cliexstart{map params pre-resolve}
1750  *
1751  * Bypass a second FIB lookup of the translated or encapsulated
1752  * packet, and forward the packet directly to the specified
1753  * next-hop. This optimization trades forwarding flexibility for
1754  * performance.
1755  * @cliexend
1756  ?*/
1757 VLIB_CLI_COMMAND(map_pre_resolve_command, static) = {
1758   .path = "map params pre-resolve",
1759   .short_help = " map params pre-resolve {ip4-nh <address>} "
1760                 "| {ip6-nh <address>}",
1761   .function = map_pre_resolve_command_fn,
1762 };
1763
1764 /*?
1765  * Enable or disable the MAP-E inbound security check
1766  * Specifiy if the inbound security check should be done on fragments
1767  *
1768  * @cliexpar
1769  * @cliexstart{map params security-check}
1770  *
1771  * By default, a decapsulated packet's IPv4 source address will be
1772  * verified against the outer header's IPv6 source address. Disabling
1773  * this feature will allow IPv4 source address spoofing.
1774  *
1775  * Typically the inbound on-decapsulation security check is only done
1776  * on the first packet. The packet that contains the L4
1777  * information. While a security check on every fragment is possible,
1778  * it has a cost. State must be created on the first fragment.
1779  * @cliexend
1780  ?*/
1781 VLIB_CLI_COMMAND(map_security_check_command, static) = {
1782   .path = "map params security-check",
1783   .short_help = "map params security-check enable|disable fragments on|off",
1784   .function = map_security_check_command_fn,
1785 };
1786
1787
1788 /*?
1789  * Specifiy the IPv4 source address used for relayed ICMP error messages
1790  *
1791  * @cliexpar
1792  * @cliexstart{map params icmp source-address}
1793  *
1794  * This command specifies which IPv4 source address (must be local to
1795  * the system), that is used for relayed received IPv6 ICMP error
1796  * messages.
1797  * @cliexend
1798  ?*/
1799 VLIB_CLI_COMMAND(map_icmp_relay_source_address_command, static) = {
1800   .path = "map params icmp source-address",
1801   .short_help = "map params icmp source-address <ip4-address>",
1802   .function = map_icmp_relay_source_address_command_fn,
1803 };
1804
1805 /*?
1806  * Send IPv6 ICMP unreachables
1807  *
1808  * @cliexpar
1809  * @cliexstart{map params icmp6 unreachables}
1810  *
1811  * Send IPv6 ICMP unreachable messages back if security check fails or
1812  * no MAP domain exists.
1813  * @cliexend
1814  ?*/
1815 VLIB_CLI_COMMAND(map_icmp_unreachables_command, static) = {
1816   .path = "map params icmp6 unreachables",
1817   .short_help = "map params icmp6 unreachables {on|off}",
1818   .function = map_icmp_unreachables_command_fn,
1819 };
1820
1821 /*?
1822  * Configure MAP fragmentation behaviour
1823  *
1824  * @cliexpar
1825  * @cliexstart{map params fragment}
1826  *
1827  * Allows fragmentation of the IPv4 packet even if the DF bit is
1828  * set. The choice between inner or outer fragmentation of tunnel
1829  * packets is complicated. The benefit of inner fragmentation is that
1830  * the ultimate endpoint must reassemble, instead of the tunnel
1831  * endpoint.
1832  * @cliexend
1833  ?*/
1834 VLIB_CLI_COMMAND(map_fragment_command, static) = {
1835   .path = "map params fragment",
1836   .short_help = "map params fragment inner|outer ignore-df|honor-df",
1837   .function = map_fragment_command_fn,
1838 };
1839
1840
1841 /*?
1842  * Add MAP domain
1843  *
1844  * @cliexpar
1845  * @cliexstart{map add domain}
1846  * @cliexend
1847  ?*/
1848 VLIB_CLI_COMMAND(map_add_domain_command, static) = {
1849   .path = "map add domain",
1850   .short_help = "map add domain [tag <tag>] ip4-pfx <ip4-pfx> "
1851       "ip6-pfx <ip6-pfx> "
1852       "ip6-src <ip6-pfx> ea-bits-len <n> psid-offset <n> psid-len <n> "
1853       "[map-t] [mtu <mtu>]",
1854   .function = map_add_domain_command_fn,
1855 };
1856
1857 /*?
1858  * Add MAP rule to a domain
1859  *
1860  * @cliexpar
1861  * @cliexstart{map add rule}
1862  * @cliexend
1863  ?*/
1864 VLIB_CLI_COMMAND(map_add_rule_command, static) = {
1865   .path = "map add rule",
1866   .short_help = "map add rule index <domain> psid <psid> ip6-dst <ip6-addr>",
1867   .function = map_add_rule_command_fn,
1868 };
1869
1870 /*?
1871  * Delete MAP domain
1872  *
1873  * @cliexpar
1874  * @cliexstart{map del domain}
1875  * @cliexend
1876  ?*/
1877 VLIB_CLI_COMMAND(map_del_command, static) = {
1878   .path = "map del domain",
1879   .short_help = "map del domain index <domain>",
1880   .function = map_del_domain_command_fn,
1881 };
1882
1883 /*?
1884  * Show MAP domains
1885  *
1886  * @cliexpar
1887  * @cliexstart{show map domain}
1888  * @cliexend
1889  ?*/
1890 VLIB_CLI_COMMAND(show_map_domain_command, static) = {
1891   .path = "show map domain",
1892   .short_help = "show map domain index <n> [counters]",
1893   .function = show_map_domain_command_fn,
1894 };
1895
1896 /*?
1897  * Show MAP statistics
1898  *
1899  * @cliexpar
1900  * @cliexstart{show map stats}
1901  * @cliexend
1902  ?*/
1903 VLIB_CLI_COMMAND(show_map_stats_command, static) = {
1904   .path = "show map stats",
1905   .short_help = "show map stats",
1906   .function = show_map_stats_command_fn,
1907 };
1908
1909 /*?
1910  * Show MAP fragmentation information
1911  *
1912  * @cliexpar
1913  * @cliexstart{show map fragments}
1914  * @cliexend
1915  ?*/
1916 VLIB_CLI_COMMAND(show_map_fragments_command, static) = {
1917   .path = "show map fragments",
1918   .short_help = "show map fragments",
1919   .function = show_map_fragments_command_fn,
1920 };
1921
1922 /*?
1923  * Enable MAP processing on interface (input feature)
1924  *
1925  ?*/
1926 VLIB_CLI_COMMAND(map_if_command, static) = {
1927   .path = "map interface",
1928   .short_help = "map interface <interface-name> [map-t] [del]",
1929   .function = map_if_command_fn,
1930 };
1931
1932 VLIB_PLUGIN_REGISTER() = {
1933   .version = VPP_BUILD_VER,
1934   .description = "Mapping of Address and Port (MAP)",
1935 };
1936
1937 /* *INDENT-ON* */
1938
1939 /*
1940  * map_init
1941  */
1942 clib_error_t *
1943 map_init (vlib_main_t * vm)
1944 {
1945   map_main_t *mm = &map_main;
1946   clib_error_t *error = 0;
1947
1948   memset (mm, 0, sizeof (*mm));
1949
1950   mm->vnet_main = vnet_get_main ();
1951   mm->vlib_main = vm;
1952
1953 #ifdef MAP_SKIP_IP6_LOOKUP
1954   fib_protocol_t proto;
1955
1956   FOR_EACH_FIB_PROTOCOL (proto)
1957   {
1958     map_pre_resolve_init (&pre_resolved[proto]);
1959   }
1960 #endif
1961
1962   /* traffic class */
1963   mm->tc = 0;
1964   mm->tc_copy = true;
1965
1966   /* Inbound security check */
1967   mm->sec_check = true;
1968   mm->sec_check_frag = false;
1969
1970   /* ICMP6 Type 1, Code 5 for security check failure */
1971   mm->icmp6_enabled = false;
1972
1973   /* Inner or outer fragmentation */
1974   mm->frag_inner = false;
1975   mm->frag_ignore_df = false;
1976
1977   vec_validate (mm->domain_counters, MAP_N_DOMAIN_COUNTER - 1);
1978   mm->domain_counters[MAP_DOMAIN_COUNTER_RX].name = "/map/rx";
1979   mm->domain_counters[MAP_DOMAIN_COUNTER_TX].name = "/map/tx";
1980
1981   vlib_validate_simple_counter (&mm->icmp_relayed, 0);
1982   vlib_zero_simple_counter (&mm->icmp_relayed, 0);
1983   mm->icmp_relayed.stat_segment_name = "/map/icmp-relayed";
1984
1985   /* IP6 virtual reassembly */
1986   mm->ip6_reass_hash_table = 0;
1987   mm->ip6_reass_pool = 0;
1988   clib_spinlock_init (&mm->ip6_reass_lock);
1989   mm->ip6_reass_conf_ht_ratio = MAP_IP6_REASS_HT_RATIO_DEFAULT;
1990   mm->ip6_reass_conf_lifetime_ms = MAP_IP6_REASS_LIFETIME_DEFAULT;
1991   mm->ip6_reass_conf_pool_size = MAP_IP6_REASS_POOL_SIZE_DEFAULT;
1992   mm->ip6_reass_conf_buffers = MAP_IP6_REASS_BUFFERS_DEFAULT;
1993   mm->ip6_reass_ht_log2len =
1994     map_get_ht_log2len (mm->ip6_reass_conf_ht_ratio,
1995                         mm->ip6_reass_conf_pool_size);
1996   mm->ip6_reass_fifo_last = MAP_REASS_INDEX_NONE;
1997   map_ip6_reass_reinit (NULL, NULL);
1998
1999 #ifdef MAP_SKIP_IP6_LOOKUP
2000   fib_node_register_type (FIB_NODE_TYPE_MAP_E, &map_vft);
2001 #endif
2002
2003   /* LPM lookup tables */
2004   mm->ip4_prefix_tbl = lpm_table_init (LPM_TYPE_KEY32);
2005   mm->ip6_prefix_tbl = lpm_table_init (LPM_TYPE_KEY128);
2006   mm->ip6_src_prefix_tbl = lpm_table_init (LPM_TYPE_KEY128);
2007
2008   mm->bm_trans_enabled_by_sw_if = 0;
2009   mm->bm_encap_enabled_by_sw_if = 0;
2010
2011   error = map_plugin_api_hookup (vm);
2012
2013   return error;
2014 }
2015
2016 VLIB_INIT_FUNCTION (map_init);
2017
2018 /*
2019  * fd.io coding-style-patch-verification: ON
2020  *
2021  * Local Variables:
2022  * eval: (c-set-style "gnu")
2023  * End:
2024  */