ipsec: Use .api declared error counters
[vpp.git] / src / vnet / ipsec / esp_decrypt.c
1 /*
2  * esp_decrypt.c : IPSec ESP decrypt node
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 #include <vnet/vnet.h>
18 #include <vnet/api_errno.h>
19 #include <vnet/ip/ip.h>
20 #include <vnet/l2/l2_input.h>
21
22 #include <vnet/ipsec/ipsec.h>
23 #include <vnet/ipsec/esp.h>
24 #include <vnet/ipsec/ipsec_io.h>
25 #include <vnet/ipsec/ipsec_tun.h>
26 #include <vnet/ipsec/ipsec.api_enum.h>
27
28 #include <vnet/gre/packet.h>
29
30 #define foreach_esp_decrypt_next                                              \
31   _ (DROP, "error-drop")                                                      \
32   _ (IP4_INPUT, "ip4-input-no-checksum")                                      \
33   _ (IP6_INPUT, "ip6-input")                                                  \
34   _ (L2_INPUT, "l2-input")                                                    \
35   _ (MPLS_INPUT, "mpls-input")                                                \
36   _ (HANDOFF, "handoff")
37
38 #define _(v, s) ESP_DECRYPT_NEXT_##v,
39 typedef enum
40 {
41   foreach_esp_decrypt_next
42 #undef _
43     ESP_DECRYPT_N_NEXT,
44 } esp_decrypt_next_t;
45
46 #define foreach_esp_decrypt_post_next                                         \
47   _ (DROP, "error-drop")                                                      \
48   _ (IP4_INPUT, "ip4-input-no-checksum")                                      \
49   _ (IP6_INPUT, "ip6-input")                                                  \
50   _ (MPLS_INPUT, "mpls-input")                                                \
51   _ (L2_INPUT, "l2-input")
52
53 #define _(v, s) ESP_DECRYPT_POST_NEXT_##v,
54 typedef enum
55 {
56   foreach_esp_decrypt_post_next
57 #undef _
58     ESP_DECRYPT_POST_N_NEXT,
59 } esp_decrypt_post_next_t;
60
61 typedef struct
62 {
63   u32 seq;
64   u32 sa_seq;
65   u32 sa_seq_hi;
66   u32 pkt_seq_hi;
67   ipsec_crypto_alg_t crypto_alg;
68   ipsec_integ_alg_t integ_alg;
69 } esp_decrypt_trace_t;
70
71 typedef vl_counter_esp_decrypt_enum_t esp_decrypt_error_t;
72
73 /* The number of byres in the hisequence number */
74 #define N_HI_ESN_BYTES 4
75
76 /* packet trace format function */
77 static u8 *
78 format_esp_decrypt_trace (u8 * s, va_list * args)
79 {
80   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
81   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
82   esp_decrypt_trace_t *t = va_arg (*args, esp_decrypt_trace_t *);
83
84   s = format (s,
85               "esp: crypto %U integrity %U pkt-seq %d sa-seq %u sa-seq-hi %u "
86               "pkt-seq-hi %u",
87               format_ipsec_crypto_alg, t->crypto_alg, format_ipsec_integ_alg,
88               t->integ_alg, t->seq, t->sa_seq, t->sa_seq_hi, t->pkt_seq_hi);
89   return s;
90 }
91
92 #define ESP_ENCRYPT_PD_F_FD_TRANSPORT (1 << 2)
93
94 static_always_inline void
95 esp_process_ops (vlib_main_t * vm, vlib_node_runtime_t * node,
96                  vnet_crypto_op_t * ops, vlib_buffer_t * b[], u16 * nexts,
97                  int e)
98 {
99   vnet_crypto_op_t *op = ops;
100   u32 n_fail, n_ops = vec_len (ops);
101
102   if (n_ops == 0)
103     return;
104
105   n_fail = n_ops - vnet_crypto_process_ops (vm, op, n_ops);
106
107   while (n_fail)
108     {
109       ASSERT (op - ops < n_ops);
110       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
111         {
112           u32 err, bi = op->user_data;
113           if (op->status == VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC)
114             err = e;
115           else
116             err = ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR;
117           b[bi]->error = node->errors[err];
118           nexts[bi] = ESP_DECRYPT_NEXT_DROP;
119           n_fail--;
120         }
121       op++;
122     }
123 }
124
125 static_always_inline void
126 esp_process_chained_ops (vlib_main_t * vm, vlib_node_runtime_t * node,
127                          vnet_crypto_op_t * ops, vlib_buffer_t * b[],
128                          u16 * nexts, vnet_crypto_op_chunk_t * chunks, int e)
129 {
130
131   vnet_crypto_op_t *op = ops;
132   u32 n_fail, n_ops = vec_len (ops);
133
134   if (PREDICT_TRUE (n_ops == 0))
135     return;
136
137   n_fail = n_ops - vnet_crypto_process_chained_ops (vm, op, chunks, n_ops);
138
139   while (n_fail)
140     {
141       ASSERT (op - ops < n_ops);
142       if (op->status != VNET_CRYPTO_OP_STATUS_COMPLETED)
143         {
144           u32 err, bi = op->user_data;
145           if (op->status == VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC)
146             err = e;
147           else
148             err = ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR;
149           b[bi]->error = node->errors[err];
150           nexts[bi] = ESP_DECRYPT_NEXT_DROP;
151           n_fail--;
152         }
153       op++;
154     }
155 }
156
157 always_inline void
158 esp_remove_tail (vlib_main_t * vm, vlib_buffer_t * b, vlib_buffer_t * last,
159                  u16 tail)
160 {
161   vlib_buffer_t *before_last = b;
162
163   if (last->current_length > tail)
164     {
165       last->current_length -= tail;
166       return;
167     }
168   ASSERT (b->flags & VLIB_BUFFER_NEXT_PRESENT);
169
170   while (b->flags & VLIB_BUFFER_NEXT_PRESENT)
171     {
172       before_last = b;
173       b = vlib_get_buffer (vm, b->next_buffer);
174     }
175   before_last->current_length -= tail - last->current_length;
176   vlib_buffer_free_one (vm, before_last->next_buffer);
177   before_last->flags &= ~VLIB_BUFFER_NEXT_PRESENT;
178 }
179
180 /* ICV is splitted in last two buffers so move it to the last buffer and
181    return pointer to it */
182 static_always_inline u8 *
183 esp_move_icv (vlib_main_t * vm, vlib_buffer_t * first,
184               esp_decrypt_packet_data_t * pd,
185               esp_decrypt_packet_data2_t * pd2, u16 icv_sz, u16 * dif)
186 {
187   vlib_buffer_t *before_last, *bp;
188   u16 last_sz = pd2->lb->current_length;
189   u16 first_sz = icv_sz - last_sz;
190
191   bp = before_last = first;
192   while (bp->flags & VLIB_BUFFER_NEXT_PRESENT)
193     {
194       before_last = bp;
195       bp = vlib_get_buffer (vm, bp->next_buffer);
196     }
197
198   u8 *lb_curr = vlib_buffer_get_current (pd2->lb);
199   memmove (lb_curr + first_sz, lb_curr, last_sz);
200   clib_memcpy_fast (lb_curr, vlib_buffer_get_tail (before_last) - first_sz,
201                     first_sz);
202   before_last->current_length -= first_sz;
203   if (before_last == first)
204     pd->current_length -= first_sz;
205   clib_memset (vlib_buffer_get_tail (before_last), 0, first_sz);
206   if (dif)
207     dif[0] = first_sz;
208   pd2->lb = before_last;
209   pd2->icv_removed = 1;
210   pd2->free_buffer_index = before_last->next_buffer;
211   before_last->flags &= ~VLIB_BUFFER_NEXT_PRESENT;
212   return lb_curr;
213 }
214
215 static_always_inline u16
216 esp_insert_esn (vlib_main_t *vm, ipsec_sa_t *sa, esp_decrypt_packet_data_t *pd,
217                 esp_decrypt_packet_data2_t *pd2, u32 *data_len, u8 **digest,
218                 u16 *len, vlib_buffer_t *b, u8 *payload)
219 {
220   if (!ipsec_sa_is_set_USE_ESN (sa))
221     return 0;
222   /* shift ICV by 4 bytes to insert ESN */
223   u32 seq_hi = clib_host_to_net_u32 (pd->seq_hi);
224   u8 tmp[ESP_MAX_ICV_SIZE];
225
226   if (pd2->icv_removed)
227     {
228       u16 space_left = vlib_buffer_space_left_at_end (vm, pd2->lb);
229       if (space_left >= N_HI_ESN_BYTES)
230         {
231           clib_memcpy_fast (vlib_buffer_get_tail (pd2->lb), &seq_hi,
232                             N_HI_ESN_BYTES);
233           *data_len += N_HI_ESN_BYTES;
234         }
235       else
236         return N_HI_ESN_BYTES;
237
238       len[0] = b->current_length;
239     }
240   else
241     {
242       clib_memcpy_fast (tmp, payload + len[0], ESP_MAX_ICV_SIZE);
243       clib_memcpy_fast (payload + len[0], &seq_hi, N_HI_ESN_BYTES);
244       clib_memcpy_fast (payload + len[0] + N_HI_ESN_BYTES, tmp,
245                         ESP_MAX_ICV_SIZE);
246       *data_len += N_HI_ESN_BYTES;
247       *digest += N_HI_ESN_BYTES;
248     }
249   return N_HI_ESN_BYTES;
250 }
251
252 static_always_inline u8 *
253 esp_move_icv_esn (vlib_main_t * vm, vlib_buffer_t * first,
254                   esp_decrypt_packet_data_t * pd,
255                   esp_decrypt_packet_data2_t * pd2, u16 icv_sz,
256                   ipsec_sa_t * sa, u8 * extra_esn, u32 * len)
257 {
258   u16 dif = 0;
259   u8 *digest = esp_move_icv (vm, first, pd, pd2, icv_sz, &dif);
260   if (dif)
261     *len -= dif;
262
263   if (ipsec_sa_is_set_USE_ESN (sa))
264     {
265       u32 seq_hi = clib_host_to_net_u32 (pd->seq_hi);
266       u16 space_left = vlib_buffer_space_left_at_end (vm, pd2->lb);
267
268       if (space_left >= N_HI_ESN_BYTES)
269         {
270           clib_memcpy_fast (vlib_buffer_get_tail (pd2->lb), &seq_hi,
271                             N_HI_ESN_BYTES);
272           *len += N_HI_ESN_BYTES;
273         }
274       else
275         {
276           /* no space for ESN at the tail, use the next buffer
277            * (with ICV data) */
278           ASSERT (pd2->icv_removed);
279           vlib_buffer_t *tmp = vlib_get_buffer (vm, pd2->free_buffer_index);
280           clib_memcpy_fast (vlib_buffer_get_current (tmp) - N_HI_ESN_BYTES,
281                             &seq_hi, N_HI_ESN_BYTES);
282           extra_esn[0] = 1;
283         }
284     }
285   return digest;
286 }
287
288 static_always_inline int
289 esp_decrypt_chain_integ (vlib_main_t *vm, ipsec_per_thread_data_t *ptd,
290                          const esp_decrypt_packet_data_t *pd,
291                          esp_decrypt_packet_data2_t *pd2, ipsec_sa_t *sa0,
292                          vlib_buffer_t *b, u8 icv_sz, u8 *start_src,
293                          u32 start_len, u8 **digest, u16 *n_ch,
294                          u32 *integ_total_len)
295 {
296   vnet_crypto_op_chunk_t *ch;
297   vlib_buffer_t *cb = vlib_get_buffer (vm, b->next_buffer);
298   u16 n_chunks = 1;
299   u32 total_len;
300   vec_add2 (ptd->chunks, ch, 1);
301   total_len = ch->len = start_len;
302   ch->src = start_src;
303
304   while (1)
305     {
306       vec_add2 (ptd->chunks, ch, 1);
307       n_chunks += 1;
308       ch->src = vlib_buffer_get_current (cb);
309       if (pd2->lb == cb)
310         {
311           if (pd2->icv_removed)
312             ch->len = cb->current_length;
313           else
314             ch->len = cb->current_length - icv_sz;
315           if (ipsec_sa_is_set_USE_ESN (sa0))
316             {
317               u32 seq_hi = clib_host_to_net_u32 (pd->seq_hi);
318               u8 tmp[ESP_MAX_ICV_SIZE];
319               u8 *esn;
320               vlib_buffer_t *tmp_b;
321               u16 space_left = vlib_buffer_space_left_at_end (vm, pd2->lb);
322               if (space_left < N_HI_ESN_BYTES)
323                 {
324                   if (pd2->icv_removed)
325                     {
326                       /* use pre-data area from the last bufer
327                          that was removed from the chain */
328                       tmp_b = vlib_get_buffer (vm, pd2->free_buffer_index);
329                       esn = tmp_b->data - N_HI_ESN_BYTES;
330                     }
331                   else
332                     {
333                       /* no space, need to allocate new buffer */
334                       u32 tmp_bi = 0;
335                       if (vlib_buffer_alloc (vm, &tmp_bi, 1) != 1)
336                         return -1;
337                       tmp_b = vlib_get_buffer (vm, tmp_bi);
338                       esn = tmp_b->data;
339                       pd2->free_buffer_index = tmp_bi;
340                     }
341                   clib_memcpy_fast (esn, &seq_hi, N_HI_ESN_BYTES);
342
343                   vec_add2 (ptd->chunks, ch, 1);
344                   n_chunks += 1;
345                   ch->src = esn;
346                   ch->len = N_HI_ESN_BYTES;
347                 }
348               else
349                 {
350                   if (pd2->icv_removed)
351                     {
352                       clib_memcpy_fast (vlib_buffer_get_tail (pd2->lb),
353                                         &seq_hi, N_HI_ESN_BYTES);
354                     }
355                   else
356                     {
357                       clib_memcpy_fast (tmp, *digest, ESP_MAX_ICV_SIZE);
358                       clib_memcpy_fast (*digest, &seq_hi, N_HI_ESN_BYTES);
359                       clib_memcpy_fast (*digest + N_HI_ESN_BYTES, tmp,
360                                         ESP_MAX_ICV_SIZE);
361                       *digest += N_HI_ESN_BYTES;
362                     }
363                   ch->len += N_HI_ESN_BYTES;
364                 }
365             }
366           total_len += ch->len;
367           break;
368         }
369       else
370         total_len += ch->len = cb->current_length;
371
372       if (!(cb->flags & VLIB_BUFFER_NEXT_PRESENT))
373         break;
374
375       cb = vlib_get_buffer (vm, cb->next_buffer);
376     }
377
378   if (n_ch)
379     *n_ch = n_chunks;
380   if (integ_total_len)
381     *integ_total_len = total_len;
382
383   return 0;
384 }
385
386 static_always_inline u32
387 esp_decrypt_chain_crypto (vlib_main_t * vm, ipsec_per_thread_data_t * ptd,
388                           esp_decrypt_packet_data_t * pd,
389                           esp_decrypt_packet_data2_t * pd2,
390                           ipsec_sa_t * sa0, vlib_buffer_t * b, u8 icv_sz,
391                           u8 * start, u32 start_len, u8 ** tag, u16 * n_ch)
392 {
393   vnet_crypto_op_chunk_t *ch;
394   vlib_buffer_t *cb = b;
395   u16 n_chunks = 1;
396   u32 total_len;
397   vec_add2 (ptd->chunks, ch, 1);
398   total_len = ch->len = start_len;
399   ch->src = ch->dst = start;
400   cb = vlib_get_buffer (vm, cb->next_buffer);
401   n_chunks = 1;
402
403   while (1)
404     {
405       vec_add2 (ptd->chunks, ch, 1);
406       n_chunks += 1;
407       ch->src = ch->dst = vlib_buffer_get_current (cb);
408       if (pd2->lb == cb)
409         {
410           if (ipsec_sa_is_set_IS_AEAD (sa0))
411             {
412               if (pd2->lb->current_length < icv_sz)
413                 {
414                   u16 dif = 0;
415                   *tag = esp_move_icv (vm, b, pd, pd2, icv_sz, &dif);
416
417                   /* this chunk does not contain crypto data */
418                   n_chunks -= 1;
419                   /* and fix previous chunk's length as it might have
420                      been changed */
421                   ASSERT (n_chunks > 0);
422                   if (pd2->lb == b)
423                     {
424                       total_len -= dif;
425                       ch[-1].len -= dif;
426                     }
427                   else
428                     {
429                       total_len = total_len + pd2->lb->current_length -
430                         ch[-1].len;
431                       ch[-1].len = pd2->lb->current_length;
432                     }
433                   break;
434                 }
435               else
436                 *tag = vlib_buffer_get_tail (pd2->lb) - icv_sz;
437             }
438
439           if (pd2->icv_removed)
440             total_len += ch->len = cb->current_length;
441           else
442             total_len += ch->len = cb->current_length - icv_sz;
443         }
444       else
445         total_len += ch->len = cb->current_length;
446
447       if (!(cb->flags & VLIB_BUFFER_NEXT_PRESENT))
448         break;
449
450       cb = vlib_get_buffer (vm, cb->next_buffer);
451     }
452
453   if (n_ch)
454     *n_ch = n_chunks;
455
456   return total_len;
457 }
458
459 static_always_inline void
460 esp_decrypt_prepare_sync_op (vlib_main_t * vm, vlib_node_runtime_t * node,
461                              ipsec_per_thread_data_t * ptd,
462                              vnet_crypto_op_t *** crypto_ops,
463                              vnet_crypto_op_t *** integ_ops,
464                              vnet_crypto_op_t * op,
465                              ipsec_sa_t * sa0, u8 * payload,
466                              u16 len, u8 icv_sz, u8 iv_sz,
467                              esp_decrypt_packet_data_t * pd,
468                              esp_decrypt_packet_data2_t * pd2,
469                              vlib_buffer_t * b, u16 * next, u32 index)
470 {
471   const u8 esp_sz = sizeof (esp_header_t);
472
473   if (PREDICT_TRUE (sa0->integ_op_id != VNET_CRYPTO_OP_NONE))
474     {
475       vnet_crypto_op_init (op, sa0->integ_op_id);
476       op->key_index = sa0->integ_key_index;
477       op->src = payload;
478       op->flags = VNET_CRYPTO_OP_FLAG_HMAC_CHECK;
479       op->user_data = index;
480       op->digest = payload + len;
481       op->digest_len = icv_sz;
482       op->len = len;
483
484       if (pd->is_chain)
485         {
486           /* buffer is chained */
487           op->len = pd->current_length;
488
489           /* special case when ICV is splitted and needs to be reassembled
490            * first -> move it to the last buffer. Also take into account
491            * that ESN needs to be added after encrypted data and may or
492            * may not fit in the tail.*/
493           if (pd2->lb->current_length < icv_sz)
494             {
495               u8 extra_esn = 0;
496               op->digest =
497                 esp_move_icv_esn (vm, b, pd, pd2, icv_sz, sa0,
498                                   &extra_esn, &op->len);
499
500               if (extra_esn)
501                 {
502                   /* esn is in the last buffer, that was unlinked from
503                    * the chain */
504                   op->len = b->current_length;
505                 }
506               else
507                 {
508                   if (pd2->lb == b)
509                     {
510                       /* we now have a single buffer of crypto data, adjust
511                        * the length (second buffer contains only ICV) */
512                       *integ_ops = &ptd->integ_ops;
513                       *crypto_ops = &ptd->crypto_ops;
514                       len = b->current_length;
515                       goto out;
516                     }
517                 }
518             }
519           else
520             op->digest = vlib_buffer_get_tail (pd2->lb) - icv_sz;
521
522           op->flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
523           op->chunk_index = vec_len (ptd->chunks);
524           if (esp_decrypt_chain_integ (vm, ptd, pd, pd2, sa0, b, icv_sz,
525                                        payload, pd->current_length,
526                                        &op->digest, &op->n_chunks, 0) < 0)
527             {
528               b->error = node->errors[ESP_DECRYPT_ERROR_NO_BUFFERS];
529               next[0] = ESP_DECRYPT_NEXT_DROP;
530               return;
531             }
532         }
533       else
534         esp_insert_esn (vm, sa0, pd, pd2, &op->len, &op->digest, &len, b,
535                         payload);
536     out:
537       vec_add_aligned (*(integ_ops[0]), op, 1, CLIB_CACHE_LINE_BYTES);
538     }
539
540   payload += esp_sz;
541   len -= esp_sz;
542
543   if (sa0->crypto_dec_op_id != VNET_CRYPTO_OP_NONE)
544     {
545       vnet_crypto_op_init (op, sa0->crypto_dec_op_id);
546       op->key_index = sa0->crypto_key_index;
547       op->iv = payload;
548
549       if (ipsec_sa_is_set_IS_CTR (sa0))
550         {
551           /* construct nonce in a scratch space in front of the IP header */
552           esp_ctr_nonce_t *nonce =
553             (esp_ctr_nonce_t *) (payload - esp_sz - pd->hdr_sz -
554                                  sizeof (*nonce));
555           if (ipsec_sa_is_set_IS_AEAD (sa0))
556             {
557               /* constuct aad in a scratch space in front of the nonce */
558               esp_header_t *esp0 = (esp_header_t *) (payload - esp_sz);
559               op->aad = (u8 *) nonce - sizeof (esp_aead_t);
560               op->aad_len = esp_aad_fill (op->aad, esp0, sa0, pd->seq_hi);
561               op->tag = payload + len;
562               op->tag_len = 16;
563             }
564           else
565             {
566               nonce->ctr = clib_host_to_net_u32 (1);
567             }
568           nonce->salt = sa0->salt;
569           ASSERT (sizeof (u64) == iv_sz);
570           nonce->iv = *(u64 *) op->iv;
571           op->iv = (u8 *) nonce;
572         }
573       op->src = op->dst = payload += iv_sz;
574       op->len = len - iv_sz;
575       op->user_data = index;
576
577       if (pd->is_chain && (pd2->lb != b))
578         {
579           /* buffer is chained */
580           op->flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
581           op->chunk_index = vec_len (ptd->chunks);
582           esp_decrypt_chain_crypto (vm, ptd, pd, pd2, sa0, b, icv_sz,
583                                     payload, len - pd->iv_sz + pd->icv_sz,
584                                     &op->tag, &op->n_chunks);
585         }
586
587       vec_add_aligned (*(crypto_ops[0]), op, 1, CLIB_CACHE_LINE_BYTES);
588     }
589 }
590
591 static_always_inline esp_decrypt_error_t
592 esp_decrypt_prepare_async_frame (vlib_main_t *vm, vlib_node_runtime_t *node,
593                                  ipsec_per_thread_data_t *ptd,
594                                  vnet_crypto_async_frame_t *f, ipsec_sa_t *sa0,
595                                  u8 *payload, u16 len, u8 icv_sz, u8 iv_sz,
596                                  esp_decrypt_packet_data_t *pd,
597                                  esp_decrypt_packet_data2_t *pd2, u32 bi,
598                                  vlib_buffer_t *b, u16 *next, u16 async_next)
599 {
600   const u8 esp_sz = sizeof (esp_header_t);
601   esp_decrypt_packet_data_t *async_pd = &(esp_post_data (b))->decrypt_data;
602   esp_decrypt_packet_data2_t *async_pd2 = esp_post_data2 (b);
603   u8 *tag = payload + len, *iv = payload + esp_sz, *aad = 0;
604   u32 key_index;
605   u32 crypto_len, integ_len = 0;
606   i16 crypto_start_offset, integ_start_offset = 0;
607   u8 flags = 0;
608
609   if (!ipsec_sa_is_set_IS_AEAD (sa0))
610     {
611       /* linked algs */
612       key_index = sa0->linked_key_index;
613       integ_start_offset = payload - b->data;
614       integ_len = len;
615       if (PREDICT_TRUE (sa0->integ_op_id != VNET_CRYPTO_OP_NONE))
616         flags |= VNET_CRYPTO_OP_FLAG_HMAC_CHECK;
617
618       if (pd->is_chain)
619         {
620           /* buffer is chained */
621           integ_len = pd->current_length;
622
623           /* special case when ICV is splitted and needs to be reassembled
624            * first -> move it to the last buffer. Also take into account
625            * that ESN needs to be added after encrypted data and may or
626            * may not fit in the tail.*/
627           if (pd2->lb->current_length < icv_sz)
628             {
629               u8 extra_esn = 0;
630               tag = esp_move_icv_esn (vm, b, pd, pd2, icv_sz, sa0,
631                                       &extra_esn, &integ_len);
632
633               if (extra_esn)
634                 {
635                   /* esn is in the last buffer, that was unlinked from
636                    * the chain */
637                   integ_len = b->current_length;
638                 }
639               else
640                 {
641                   if (pd2->lb == b)
642                     {
643                       /* we now have a single buffer of crypto data, adjust
644                        * the length (second buffer contains only ICV) */
645                       len = b->current_length;
646                       goto out;
647                     }
648                 }
649             }
650           else
651             tag = vlib_buffer_get_tail (pd2->lb) - icv_sz;
652
653           flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
654           if (esp_decrypt_chain_integ (vm, ptd, pd, pd2, sa0, b, icv_sz,
655                                        payload, pd->current_length, &tag, 0,
656                                        &integ_len) < 0)
657             {
658               /* allocate buffer failed, will not add to frame and drop */
659               return (ESP_DECRYPT_ERROR_NO_BUFFERS);
660             }
661         }
662       else
663         esp_insert_esn (vm, sa0, pd, pd2, &integ_len, &tag, &len, b, payload);
664     }
665   else
666     key_index = sa0->crypto_key_index;
667
668 out:
669   /* crypto */
670   payload += esp_sz;
671   len -= esp_sz;
672   iv = payload;
673
674   if (ipsec_sa_is_set_IS_CTR (sa0))
675     {
676       /* construct nonce in a scratch space in front of the IP header */
677       esp_ctr_nonce_t *nonce =
678         (esp_ctr_nonce_t *) (payload - esp_sz - pd->hdr_sz - sizeof (*nonce));
679       if (ipsec_sa_is_set_IS_AEAD (sa0))
680         {
681           /* constuct aad in a scratch space in front of the nonce */
682           esp_header_t *esp0 = (esp_header_t *) (payload - esp_sz);
683           aad = (u8 *) nonce - sizeof (esp_aead_t);
684           esp_aad_fill (aad, esp0, sa0, pd->seq_hi);
685           tag = payload + len;
686         }
687       else
688         {
689           nonce->ctr = clib_host_to_net_u32 (1);
690         }
691       nonce->salt = sa0->salt;
692       ASSERT (sizeof (u64) == iv_sz);
693       nonce->iv = *(u64 *) iv;
694       iv = (u8 *) nonce;
695     }
696
697   crypto_start_offset = (payload += iv_sz) - b->data;
698   crypto_len = len - iv_sz;
699
700   if (pd->is_chain && (pd2->lb != b))
701     {
702       /* buffer is chained */
703       flags |= VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS;
704
705       crypto_len = esp_decrypt_chain_crypto (vm, ptd, pd, pd2, sa0, b, icv_sz,
706                                              payload,
707                                              len - pd->iv_sz + pd->icv_sz,
708                                              &tag, 0);
709     }
710
711   *async_pd = *pd;
712   *async_pd2 = *pd2;
713
714   /* for AEAD integ_len - crypto_len will be negative, it is ok since it
715    * is ignored by the engine. */
716   vnet_crypto_async_add_to_frame (
717     vm, f, key_index, crypto_len, integ_len - crypto_len, crypto_start_offset,
718     integ_start_offset, bi, async_next, iv, tag, aad, flags);
719
720   return (ESP_DECRYPT_ERROR_RX_PKTS);
721 }
722
723 static_always_inline void
724 esp_decrypt_post_crypto (vlib_main_t *vm, const vlib_node_runtime_t *node,
725                          const u16 *next_by_next_header,
726                          const esp_decrypt_packet_data_t *pd,
727                          const esp_decrypt_packet_data2_t *pd2,
728                          vlib_buffer_t *b, u16 *next, int is_ip6, int is_tun,
729                          int is_async)
730 {
731   ipsec_sa_t *sa0 = ipsec_sa_get (pd->sa_index);
732   vlib_buffer_t *lb = b;
733   const u8 esp_sz = sizeof (esp_header_t);
734   const u8 tun_flags = IPSEC_SA_FLAG_IS_TUNNEL | IPSEC_SA_FLAG_IS_TUNNEL_V6;
735   u8 pad_length = 0, next_header = 0;
736   u16 icv_sz;
737
738   /*
739    * redo the anti-reply check
740    * in this frame say we have sequence numbers, s, s+1, s+1, s+1
741    * and s and s+1 are in the window. When we did the anti-replay
742    * check above we did so against the state of the window (W),
743    * after packet s-1. So each of the packets in the sequence will be
744    * accepted.
745    * This time s will be cheked against Ws-1, s+1 chceked against Ws
746    * (i.e. the window state is updated/advnaced)
747    * so this time the successive s+! packet will be dropped.
748    * This is a consequence of batching the decrypts. If the
749    * check-dcrypt-advance process was done for each packet it would
750    * be fine. But we batch the decrypts because it's much more efficient
751    * to do so in SW and if we offload to HW and the process is async.
752    *
753    * You're probably thinking, but this means an attacker can send the
754    * above sequence and cause VPP to perform decrpyts that will fail,
755    * and that's true. But if the attacker can determine s (a valid
756    * sequence number in the window) which is non-trivial, it can generate
757    * a sequence s, s+1, s+2, s+3, ... s+n and nothing will prevent any
758    * implementation, sequential or batching, from decrypting these.
759    */
760   if (ipsec_sa_anti_replay_and_sn_advance (sa0, pd->seq, pd->seq_hi, true,
761                                            NULL))
762     {
763       b->error = node->errors[ESP_DECRYPT_ERROR_REPLAY];
764       next[0] = ESP_DECRYPT_NEXT_DROP;
765       return;
766     }
767
768   u64 n_lost =
769     ipsec_sa_anti_replay_advance (sa0, vm->thread_index, pd->seq, pd->seq_hi);
770
771   vlib_prefetch_simple_counter (&ipsec_sa_lost_counters, vm->thread_index,
772                                 pd->sa_index);
773
774   if (pd->is_chain)
775     {
776       lb = pd2->lb;
777       icv_sz = pd2->icv_removed ? 0 : pd->icv_sz;
778       if (pd2->free_buffer_index)
779         {
780           vlib_buffer_free_one (vm, pd2->free_buffer_index);
781           lb->next_buffer = 0;
782         }
783       if (lb->current_length < sizeof (esp_footer_t) + icv_sz)
784         {
785           /* esp footer is either splitted in two buffers or in the before
786            * last buffer */
787
788           vlib_buffer_t *before_last = b, *bp = b;
789           while (bp->flags & VLIB_BUFFER_NEXT_PRESENT)
790             {
791               before_last = bp;
792               bp = vlib_get_buffer (vm, bp->next_buffer);
793             }
794           u8 *bt = vlib_buffer_get_tail (before_last);
795
796           if (lb->current_length == icv_sz)
797             {
798               esp_footer_t *f = (esp_footer_t *) (bt - sizeof (*f));
799               pad_length = f->pad_length;
800               next_header = f->next_header;
801             }
802           else
803             {
804               pad_length = (bt - 1)[0];
805               next_header = ((u8 *) vlib_buffer_get_current (lb))[0];
806             }
807         }
808       else
809         {
810           esp_footer_t *f =
811             (esp_footer_t *) (lb->data + lb->current_data +
812                               lb->current_length - sizeof (esp_footer_t) -
813                               icv_sz);
814           pad_length = f->pad_length;
815           next_header = f->next_header;
816         }
817     }
818   else
819     {
820       icv_sz = pd->icv_sz;
821       esp_footer_t *f =
822         (esp_footer_t *) (lb->data + lb->current_data + lb->current_length -
823                           sizeof (esp_footer_t) - icv_sz);
824       pad_length = f->pad_length;
825       next_header = f->next_header;
826     }
827
828   u16 adv = pd->iv_sz + esp_sz;
829   u16 tail = sizeof (esp_footer_t) + pad_length + icv_sz;
830   u16 tail_orig = sizeof (esp_footer_t) + pad_length + pd->icv_sz;
831   b->flags &= ~VLIB_BUFFER_TOTAL_LENGTH_VALID;
832
833   if ((pd->flags & tun_flags) == 0 && !is_tun)  /* transport mode */
834     {
835       u8 udp_sz = (is_ip6 == 0 && pd->flags & IPSEC_SA_FLAG_UDP_ENCAP) ?
836         sizeof (udp_header_t) : 0;
837       u16 ip_hdr_sz = pd->hdr_sz - udp_sz;
838       u8 *old_ip = b->data + pd->current_data - ip_hdr_sz - udp_sz;
839       u8 *ip = old_ip + adv + udp_sz;
840
841       if (is_ip6 && ip_hdr_sz > 64)
842         memmove (ip, old_ip, ip_hdr_sz);
843       else
844         clib_memcpy_le64 (ip, old_ip, ip_hdr_sz);
845
846       b->current_data = pd->current_data + adv - ip_hdr_sz;
847       b->current_length += ip_hdr_sz - adv;
848       esp_remove_tail (vm, b, lb, tail);
849
850       if (is_ip6)
851         {
852           ip6_header_t *ip6 = (ip6_header_t *) ip;
853           u16 len = clib_net_to_host_u16 (ip6->payload_length);
854           len -= adv + tail_orig;
855           ip6->payload_length = clib_host_to_net_u16 (len);
856           ip6->protocol = next_header;
857           next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
858         }
859       else
860         {
861           ip4_header_t *ip4 = (ip4_header_t *) ip;
862           ip_csum_t sum = ip4->checksum;
863           u16 len = clib_net_to_host_u16 (ip4->length);
864           len = clib_host_to_net_u16 (len - adv - tail_orig - udp_sz);
865           sum = ip_csum_update (sum, ip4->protocol, next_header,
866                                 ip4_header_t, protocol);
867           sum = ip_csum_update (sum, ip4->length, len, ip4_header_t, length);
868           ip4->checksum = ip_csum_fold (sum);
869           ip4->protocol = next_header;
870           ip4->length = len;
871           next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
872         }
873     }
874   else
875     {
876       if (PREDICT_TRUE (next_header == IP_PROTOCOL_IP_IN_IP))
877         {
878           next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
879           b->current_data = pd->current_data + adv;
880           b->current_length = pd->current_length - adv;
881           esp_remove_tail (vm, b, lb, tail);
882         }
883       else if (next_header == IP_PROTOCOL_IPV6)
884         {
885           next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
886           b->current_data = pd->current_data + adv;
887           b->current_length = pd->current_length - adv;
888           esp_remove_tail (vm, b, lb, tail);
889         }
890       else if (next_header == IP_PROTOCOL_MPLS_IN_IP)
891         {
892           next[0] = ESP_DECRYPT_NEXT_MPLS_INPUT;
893           b->current_data = pd->current_data + adv;
894           b->current_length = pd->current_length - adv;
895           esp_remove_tail (vm, b, lb, tail);
896         }
897       else if (is_tun && next_header == IP_PROTOCOL_GRE)
898         {
899           gre_header_t *gre;
900
901           b->current_data = pd->current_data + adv;
902           b->current_length = pd->current_length - adv - tail;
903
904           gre = vlib_buffer_get_current (b);
905
906           vlib_buffer_advance (b, sizeof (*gre));
907
908           switch (clib_net_to_host_u16 (gre->protocol))
909             {
910             case GRE_PROTOCOL_teb:
911               vnet_update_l2_len (b);
912               next[0] = ESP_DECRYPT_NEXT_L2_INPUT;
913               break;
914             case GRE_PROTOCOL_ip4:
915               next[0] = ESP_DECRYPT_NEXT_IP4_INPUT;
916               break;
917             case GRE_PROTOCOL_ip6:
918               next[0] = ESP_DECRYPT_NEXT_IP6_INPUT;
919               break;
920             default:
921               b->error = node->errors[ESP_DECRYPT_ERROR_UNSUP_PAYLOAD];
922               next[0] = ESP_DECRYPT_NEXT_DROP;
923               break;
924             }
925         }
926       else if ((next[0] = vec_elt (next_by_next_header, next_header)) !=
927                (u16) ~0)
928         {
929           b->current_data = pd->current_data + adv;
930           b->current_length = pd->current_length - adv;
931           esp_remove_tail (vm, b, lb, tail);
932         }
933       else
934         {
935           next[0] = ESP_DECRYPT_NEXT_DROP;
936           b->error = node->errors[ESP_DECRYPT_ERROR_UNSUP_PAYLOAD];
937           return;
938         }
939
940       if (is_tun)
941         {
942           if (ipsec_sa_is_set_IS_PROTECT (sa0))
943             {
944               /*
945                * There are two encap possibilities
946                * 1) the tunnel and ths SA are prodiving encap, i.e. it's
947                *   MAC | SA-IP | TUN-IP | ESP | PAYLOAD
948                * implying the SA is in tunnel mode (on a tunnel interface)
949                * 2) only the tunnel provides encap
950                *   MAC | TUN-IP | ESP | PAYLOAD
951                * implying the SA is in transport mode.
952                *
953                * For 2) we need only strip the tunnel encap and we're good.
954                *  since the tunnel and crypto ecnap (int the tun=protect
955                * object) are the same and we verified above that these match
956                * for 1) we need to strip the SA-IP outer headers, to
957                * reveal the tunnel IP and then check that this matches
958                * the configured tunnel.
959                */
960               const ipsec_tun_protect_t *itp;
961
962               itp =
963                 ipsec_tun_protect_get (vnet_buffer (b)->ipsec.protect_index);
964
965               if (PREDICT_TRUE (next_header == IP_PROTOCOL_IP_IN_IP))
966                 {
967                   const ip4_header_t *ip4;
968
969                   ip4 = vlib_buffer_get_current (b);
970
971                   if (!ip46_address_is_equal_v4 (&itp->itp_tun.src,
972                                                  &ip4->dst_address) ||
973                       !ip46_address_is_equal_v4 (&itp->itp_tun.dst,
974                                                  &ip4->src_address))
975                     {
976                       next[0] = ESP_DECRYPT_NEXT_DROP;
977                       b->error = node->errors[ESP_DECRYPT_ERROR_TUN_NO_PROTO];
978                     }
979                 }
980               else if (next_header == IP_PROTOCOL_IPV6)
981                 {
982                   const ip6_header_t *ip6;
983
984                   ip6 = vlib_buffer_get_current (b);
985
986                   if (!ip46_address_is_equal_v6 (&itp->itp_tun.src,
987                                                  &ip6->dst_address) ||
988                       !ip46_address_is_equal_v6 (&itp->itp_tun.dst,
989                                                  &ip6->src_address))
990                     {
991                       next[0] = ESP_DECRYPT_NEXT_DROP;
992                       b->error = node->errors[ESP_DECRYPT_ERROR_TUN_NO_PROTO];
993                     }
994                 }
995             }
996         }
997     }
998
999   if (PREDICT_FALSE (n_lost))
1000     vlib_increment_simple_counter (&ipsec_sa_lost_counters, vm->thread_index,
1001                                    pd->sa_index, n_lost);
1002 }
1003
1004 always_inline uword
1005 esp_decrypt_inline (vlib_main_t *vm, vlib_node_runtime_t *node,
1006                     vlib_frame_t *from_frame, int is_ip6, int is_tun,
1007                     u16 async_next_node)
1008 {
1009   ipsec_main_t *im = &ipsec_main;
1010   const u16 *next_by_next_header = im->next_header_registrations;
1011   u32 thread_index = vm->thread_index;
1012   u16 len;
1013   ipsec_per_thread_data_t *ptd = vec_elt_at_index (im->ptd, thread_index);
1014   u32 *from = vlib_frame_vector_args (from_frame);
1015   u32 n_left = from_frame->n_vectors;
1016   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
1017   vlib_buffer_t *sync_bufs[VLIB_FRAME_SIZE];
1018   u16 sync_nexts[VLIB_FRAME_SIZE], *sync_next = sync_nexts, n_sync = 0;
1019   u16 async_nexts[VLIB_FRAME_SIZE], *async_next = async_nexts;
1020   u16 noop_nexts[VLIB_FRAME_SIZE], *noop_next = noop_nexts, n_noop = 0;
1021   u32 sync_bi[VLIB_FRAME_SIZE];
1022   u32 noop_bi[VLIB_FRAME_SIZE];
1023   esp_decrypt_packet_data_t pkt_data[VLIB_FRAME_SIZE], *pd = pkt_data;
1024   esp_decrypt_packet_data2_t pkt_data2[VLIB_FRAME_SIZE], *pd2 = pkt_data2;
1025   esp_decrypt_packet_data_t cpd = { };
1026   u32 current_sa_index = ~0, current_sa_bytes = 0, current_sa_pkts = 0;
1027   const u8 esp_sz = sizeof (esp_header_t);
1028   ipsec_sa_t *sa0 = 0;
1029   vnet_crypto_op_t _op, *op = &_op;
1030   vnet_crypto_op_t **crypto_ops;
1031   vnet_crypto_op_t **integ_ops;
1032   int is_async = im->async_mode;
1033   vnet_crypto_async_op_id_t async_op = ~0;
1034   vnet_crypto_async_frame_t *async_frames[VNET_CRYPTO_ASYNC_OP_N_IDS];
1035   esp_decrypt_error_t err;
1036
1037   vlib_get_buffers (vm, from, b, n_left);
1038   if (!is_async)
1039     {
1040       vec_reset_length (ptd->crypto_ops);
1041       vec_reset_length (ptd->integ_ops);
1042       vec_reset_length (ptd->chained_crypto_ops);
1043       vec_reset_length (ptd->chained_integ_ops);
1044     }
1045   vec_reset_length (ptd->async_frames);
1046   vec_reset_length (ptd->chunks);
1047   clib_memset (sync_nexts, -1, sizeof (sync_nexts));
1048   clib_memset (async_frames, 0, sizeof (async_frames));
1049
1050   while (n_left > 0)
1051     {
1052       u8 *payload;
1053
1054       err = ESP_DECRYPT_ERROR_RX_PKTS;
1055       if (n_left > 2)
1056         {
1057           u8 *p;
1058           vlib_prefetch_buffer_header (b[2], LOAD);
1059           p = vlib_buffer_get_current (b[1]);
1060           clib_prefetch_load (p);
1061           p -= CLIB_CACHE_LINE_BYTES;
1062           clib_prefetch_load (p);
1063         }
1064
1065       u32 n_bufs = vlib_buffer_chain_linearize (vm, b[0]);
1066       if (n_bufs == 0)
1067         {
1068           err = ESP_DECRYPT_ERROR_NO_BUFFERS;
1069           esp_set_next_index (b[0], node, err, n_noop, noop_nexts,
1070                               ESP_DECRYPT_NEXT_DROP);
1071           goto next;
1072         }
1073
1074       if (vnet_buffer (b[0])->ipsec.sad_index != current_sa_index)
1075         {
1076           if (current_sa_pkts)
1077             vlib_increment_combined_counter (&ipsec_sa_counters, thread_index,
1078                                              current_sa_index,
1079                                              current_sa_pkts,
1080                                              current_sa_bytes);
1081           current_sa_bytes = current_sa_pkts = 0;
1082
1083           current_sa_index = vnet_buffer (b[0])->ipsec.sad_index;
1084           sa0 = ipsec_sa_get (current_sa_index);
1085
1086           /* fetch the second cacheline ASAP */
1087           clib_prefetch_load (sa0->cacheline1);
1088           cpd.icv_sz = sa0->integ_icv_size;
1089           cpd.iv_sz = sa0->crypto_iv_size;
1090           cpd.flags = sa0->flags;
1091           cpd.sa_index = current_sa_index;
1092           is_async = im->async_mode | ipsec_sa_is_set_IS_ASYNC (sa0);
1093         }
1094
1095       if (PREDICT_FALSE (~0 == sa0->thread_index))
1096         {
1097           /* this is the first packet to use this SA, claim the SA
1098            * for this thread. this could happen simultaneously on
1099            * another thread */
1100           clib_atomic_cmp_and_swap (&sa0->thread_index, ~0,
1101                                     ipsec_sa_assign_thread (thread_index));
1102         }
1103
1104       if (PREDICT_FALSE (thread_index != sa0->thread_index))
1105         {
1106           vnet_buffer (b[0])->ipsec.thread_index = sa0->thread_index;
1107           err = ESP_DECRYPT_ERROR_HANDOFF;
1108           esp_set_next_index (b[0], node, err, n_noop, noop_nexts,
1109                               ESP_DECRYPT_NEXT_HANDOFF);
1110           goto next;
1111         }
1112
1113       /* store packet data for next round for easier prefetch */
1114       pd->sa_data = cpd.sa_data;
1115       pd->current_data = b[0]->current_data;
1116       pd->hdr_sz = pd->current_data - vnet_buffer (b[0])->l3_hdr_offset;
1117       payload = b[0]->data + pd->current_data;
1118       pd->seq = clib_host_to_net_u32 (((esp_header_t *) payload)->seq);
1119       pd->is_chain = 0;
1120       pd2->lb = b[0];
1121       pd2->free_buffer_index = 0;
1122       pd2->icv_removed = 0;
1123
1124       if (n_bufs > 1)
1125         {
1126           pd->is_chain = 1;
1127           /* find last buffer in the chain */
1128           while (pd2->lb->flags & VLIB_BUFFER_NEXT_PRESENT)
1129             pd2->lb = vlib_get_buffer (vm, pd2->lb->next_buffer);
1130
1131           crypto_ops = &ptd->chained_crypto_ops;
1132           integ_ops = &ptd->chained_integ_ops;
1133         }
1134       else
1135         {
1136           crypto_ops = &ptd->crypto_ops;
1137           integ_ops = &ptd->integ_ops;
1138         }
1139
1140       pd->current_length = b[0]->current_length;
1141
1142       /* anti-reply check */
1143       if (ipsec_sa_anti_replay_and_sn_advance (sa0, pd->seq, ~0, false,
1144                                                &pd->seq_hi))
1145         {
1146           err = ESP_DECRYPT_ERROR_REPLAY;
1147           esp_set_next_index (b[0], node, err, n_noop, noop_nexts,
1148                               ESP_DECRYPT_NEXT_DROP);
1149           goto next;
1150         }
1151
1152       if (pd->current_length < cpd.icv_sz + esp_sz + cpd.iv_sz)
1153         {
1154           err = ESP_DECRYPT_ERROR_RUNT;
1155           esp_set_next_index (b[0], node, err, n_noop, noop_nexts,
1156                               ESP_DECRYPT_NEXT_DROP);
1157           goto next;
1158         }
1159
1160       len = pd->current_length - cpd.icv_sz;
1161       current_sa_pkts += 1;
1162       current_sa_bytes += vlib_buffer_length_in_chain (vm, b[0]);
1163
1164       if (is_async)
1165         {
1166           async_op = sa0->crypto_async_dec_op_id;
1167
1168           /* get a frame for this op if we don't yet have one or it's full
1169            */
1170           if (NULL == async_frames[async_op] ||
1171               vnet_crypto_async_frame_is_full (async_frames[async_op]))
1172             {
1173               async_frames[async_op] =
1174                 vnet_crypto_async_get_frame (vm, async_op);
1175               /* Save the frame to the list we'll submit at the end */
1176               vec_add1 (ptd->async_frames, async_frames[async_op]);
1177             }
1178
1179           err = esp_decrypt_prepare_async_frame (
1180             vm, node, ptd, async_frames[async_op], sa0, payload, len,
1181             cpd.icv_sz, cpd.iv_sz, pd, pd2, from[b - bufs], b[0], async_next,
1182             async_next_node);
1183           if (ESP_DECRYPT_ERROR_RX_PKTS != err)
1184             {
1185               esp_set_next_index (b[0], node, err, n_noop, noop_nexts,
1186                                   ESP_DECRYPT_NEXT_DROP);
1187             }
1188         }
1189       else
1190         esp_decrypt_prepare_sync_op (
1191           vm, node, ptd, &crypto_ops, &integ_ops, op, sa0, payload, len,
1192           cpd.icv_sz, cpd.iv_sz, pd, pd2, b[0], sync_next, b - bufs);
1193       /* next */
1194     next:
1195       if (ESP_DECRYPT_ERROR_RX_PKTS != err)
1196         {
1197           noop_bi[n_noop] = from[b - bufs];
1198           n_noop++;
1199           noop_next++;
1200         }
1201       else if (!is_async)
1202         {
1203           sync_bi[n_sync] = from[b - bufs];
1204           sync_bufs[n_sync] = b[0];
1205           n_sync++;
1206           sync_next++;
1207           pd += 1;
1208           pd2 += 1;
1209         }
1210       else
1211         async_next++;
1212
1213       n_left -= 1;
1214       b += 1;
1215     }
1216
1217   if (PREDICT_TRUE (~0 != current_sa_index))
1218     vlib_increment_combined_counter (&ipsec_sa_counters, thread_index,
1219                                      current_sa_index, current_sa_pkts,
1220                                      current_sa_bytes);
1221
1222   /* submit or free all of the open frames */
1223   vnet_crypto_async_frame_t **async_frame;
1224
1225   vec_foreach (async_frame, ptd->async_frames)
1226     {
1227       /* free frame and move on if no ops were successfully added */
1228       if (PREDICT_FALSE (!(*async_frame)->n_elts))
1229         {
1230           vnet_crypto_async_free_frame (vm, *async_frame);
1231           continue;
1232         }
1233       if (vnet_crypto_async_submit_open_frame (vm, *async_frame) < 0)
1234         {
1235           n_noop += esp_async_recycle_failed_submit (
1236             vm, *async_frame, node, ESP_DECRYPT_ERROR_CRYPTO_ENGINE_ERROR,
1237             n_noop, noop_bi, noop_nexts, ESP_DECRYPT_NEXT_DROP);
1238           vnet_crypto_async_reset_frame (*async_frame);
1239           vnet_crypto_async_free_frame (vm, *async_frame);
1240         }
1241     }
1242
1243   if (n_sync)
1244     {
1245       esp_process_ops (vm, node, ptd->integ_ops, sync_bufs, sync_nexts,
1246                        ESP_DECRYPT_ERROR_INTEG_ERROR);
1247       esp_process_chained_ops (vm, node, ptd->chained_integ_ops, sync_bufs,
1248                                sync_nexts, ptd->chunks,
1249                                ESP_DECRYPT_ERROR_INTEG_ERROR);
1250
1251       esp_process_ops (vm, node, ptd->crypto_ops, sync_bufs, sync_nexts,
1252                        ESP_DECRYPT_ERROR_DECRYPTION_FAILED);
1253       esp_process_chained_ops (vm, node, ptd->chained_crypto_ops, sync_bufs,
1254                                sync_nexts, ptd->chunks,
1255                                ESP_DECRYPT_ERROR_DECRYPTION_FAILED);
1256     }
1257
1258   /* Post decryption ronud - adjust packet data start and length and next
1259      node */
1260
1261   n_left = n_sync;
1262   sync_next = sync_nexts;
1263   pd = pkt_data;
1264   pd2 = pkt_data2;
1265   b = sync_bufs;
1266
1267   while (n_left)
1268     {
1269       if (n_left >= 2)
1270         {
1271           void *data = b[1]->data + pd[1].current_data;
1272
1273           /* buffer metadata */
1274           vlib_prefetch_buffer_header (b[1], LOAD);
1275
1276           /* esp_footer_t */
1277           CLIB_PREFETCH (data + pd[1].current_length - pd[1].icv_sz - 2,
1278                          CLIB_CACHE_LINE_BYTES, LOAD);
1279
1280           /* packet headers */
1281           CLIB_PREFETCH (data - CLIB_CACHE_LINE_BYTES,
1282                          CLIB_CACHE_LINE_BYTES * 2, LOAD);
1283         }
1284
1285       /* save the sa_index as GRE_teb post_crypto changes L2 opaque */
1286       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
1287         current_sa_index = vnet_buffer (b[0])->ipsec.sad_index;
1288
1289       if (sync_next[0] >= ESP_DECRYPT_N_NEXT)
1290         esp_decrypt_post_crypto (vm, node, next_by_next_header, pd, pd2, b[0],
1291                                  sync_next, is_ip6, is_tun, 0);
1292
1293       /* trace: */
1294       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
1295         {
1296           esp_decrypt_trace_t *tr;
1297           tr = vlib_add_trace (vm, node, b[0], sizeof (*tr));
1298           sa0 = ipsec_sa_get (current_sa_index);
1299           tr->crypto_alg = sa0->crypto_alg;
1300           tr->integ_alg = sa0->integ_alg;
1301           tr->seq = pd->seq;
1302           tr->sa_seq = sa0->seq;
1303           tr->sa_seq_hi = sa0->seq_hi;
1304           tr->pkt_seq_hi = pd->seq_hi;
1305         }
1306
1307       /* next */
1308       n_left -= 1;
1309       sync_next += 1;
1310       pd += 1;
1311       pd2 += 1;
1312       b += 1;
1313     }
1314
1315   vlib_node_increment_counter (vm, node->node_index, ESP_DECRYPT_ERROR_RX_PKTS,
1316                                from_frame->n_vectors);
1317
1318   if (n_sync)
1319     vlib_buffer_enqueue_to_next (vm, node, sync_bi, sync_nexts, n_sync);
1320
1321   if (n_noop)
1322     vlib_buffer_enqueue_to_next (vm, node, noop_bi, noop_nexts, n_noop);
1323
1324   return (from_frame->n_vectors);
1325 }
1326
1327 always_inline uword
1328 esp_decrypt_post_inline (vlib_main_t * vm,
1329                          vlib_node_runtime_t * node,
1330                          vlib_frame_t * from_frame, int is_ip6, int is_tun)
1331 {
1332   const ipsec_main_t *im = &ipsec_main;
1333   const u16 *next_by_next_header = im->next_header_registrations;
1334   u32 *from = vlib_frame_vector_args (from_frame);
1335   u32 n_left = from_frame->n_vectors;
1336   vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b = bufs;
1337   u16 nexts[VLIB_FRAME_SIZE], *next = nexts;
1338   vlib_get_buffers (vm, from, b, n_left);
1339
1340   while (n_left > 0)
1341     {
1342       esp_decrypt_packet_data_t *pd = &(esp_post_data (b[0]))->decrypt_data;
1343
1344       if (n_left > 2)
1345         {
1346           vlib_prefetch_buffer_header (b[2], LOAD);
1347           vlib_prefetch_buffer_header (b[1], LOAD);
1348         }
1349
1350       if (!pd->is_chain)
1351         esp_decrypt_post_crypto (vm, node, next_by_next_header, pd, 0, b[0],
1352                                  next, is_ip6, is_tun, 1);
1353       else
1354         {
1355           esp_decrypt_packet_data2_t *pd2 = esp_post_data2 (b[0]);
1356           esp_decrypt_post_crypto (vm, node, next_by_next_header, pd, pd2,
1357                                    b[0], next, is_ip6, is_tun, 1);
1358         }
1359
1360       /*trace: */
1361       if (PREDICT_FALSE (b[0]->flags & VLIB_BUFFER_IS_TRACED))
1362         {
1363           ipsec_sa_t *sa0 = ipsec_sa_get (pd->sa_index);
1364           esp_decrypt_trace_t *tr;
1365           esp_decrypt_packet_data_t *async_pd =
1366             &(esp_post_data (b[0]))->decrypt_data;
1367           tr = vlib_add_trace (vm, node, b[0], sizeof (*tr));
1368           sa0 = ipsec_sa_get (async_pd->sa_index);
1369
1370           tr->crypto_alg = sa0->crypto_alg;
1371           tr->integ_alg = sa0->integ_alg;
1372           tr->seq = pd->seq;
1373           tr->sa_seq = sa0->seq;
1374           tr->sa_seq_hi = sa0->seq_hi;
1375         }
1376
1377       n_left--;
1378       next++;
1379       b++;
1380     }
1381
1382   n_left = from_frame->n_vectors;
1383   vlib_node_increment_counter (vm, node->node_index,
1384                                ESP_DECRYPT_ERROR_RX_POST_PKTS, n_left);
1385
1386   vlib_buffer_enqueue_to_next (vm, node, from, nexts, n_left);
1387
1388   return n_left;
1389 }
1390
1391 VLIB_NODE_FN (esp4_decrypt_node) (vlib_main_t * vm,
1392                                   vlib_node_runtime_t * node,
1393                                   vlib_frame_t * from_frame)
1394 {
1395   return esp_decrypt_inline (vm, node, from_frame, 0, 0,
1396                              esp_decrypt_async_next.esp4_post_next);
1397 }
1398
1399 VLIB_NODE_FN (esp4_decrypt_post_node) (vlib_main_t * vm,
1400                                        vlib_node_runtime_t * node,
1401                                        vlib_frame_t * from_frame)
1402 {
1403   return esp_decrypt_post_inline (vm, node, from_frame, 0, 0);
1404 }
1405
1406 VLIB_NODE_FN (esp4_decrypt_tun_node) (vlib_main_t * vm,
1407                                       vlib_node_runtime_t * node,
1408                                       vlib_frame_t * from_frame)
1409 {
1410   return esp_decrypt_inline (vm, node, from_frame, 0, 1,
1411                              esp_decrypt_async_next.esp4_tun_post_next);
1412 }
1413
1414 VLIB_NODE_FN (esp4_decrypt_tun_post_node) (vlib_main_t * vm,
1415                                            vlib_node_runtime_t * node,
1416                                            vlib_frame_t * from_frame)
1417 {
1418   return esp_decrypt_post_inline (vm, node, from_frame, 0, 1);
1419 }
1420
1421 VLIB_NODE_FN (esp6_decrypt_node) (vlib_main_t * vm,
1422                                   vlib_node_runtime_t * node,
1423                                   vlib_frame_t * from_frame)
1424 {
1425   return esp_decrypt_inline (vm, node, from_frame, 1, 0,
1426                              esp_decrypt_async_next.esp6_post_next);
1427 }
1428
1429 VLIB_NODE_FN (esp6_decrypt_post_node) (vlib_main_t * vm,
1430                                        vlib_node_runtime_t * node,
1431                                        vlib_frame_t * from_frame)
1432 {
1433   return esp_decrypt_post_inline (vm, node, from_frame, 1, 0);
1434 }
1435
1436 VLIB_NODE_FN (esp6_decrypt_tun_node) (vlib_main_t * vm,
1437                                       vlib_node_runtime_t * node,
1438                                       vlib_frame_t * from_frame)
1439 {
1440   return esp_decrypt_inline (vm, node, from_frame, 1, 1,
1441                              esp_decrypt_async_next.esp6_tun_post_next);
1442 }
1443
1444 VLIB_NODE_FN (esp6_decrypt_tun_post_node) (vlib_main_t * vm,
1445                                            vlib_node_runtime_t * node,
1446                                            vlib_frame_t * from_frame)
1447 {
1448   return esp_decrypt_post_inline (vm, node, from_frame, 1, 1);
1449 }
1450
1451 /* *INDENT-OFF* */
1452 VLIB_REGISTER_NODE (esp4_decrypt_node) = {
1453   .name = "esp4-decrypt",
1454   .vector_size = sizeof (u32),
1455   .format_trace = format_esp_decrypt_trace,
1456   .type = VLIB_NODE_TYPE_INTERNAL,
1457
1458   .n_errors = ESP_DECRYPT_N_ERROR,
1459   .error_counters = esp_decrypt_error_counters,
1460
1461   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1462   .next_nodes = {
1463     [ESP_DECRYPT_NEXT_DROP] = "ip4-drop",
1464     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1465     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1466     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-drop",
1467     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1468     [ESP_DECRYPT_NEXT_HANDOFF] = "esp4-decrypt-handoff",
1469   },
1470 };
1471
1472 VLIB_REGISTER_NODE (esp4_decrypt_post_node) = {
1473   .name = "esp4-decrypt-post",
1474   .vector_size = sizeof (u32),
1475   .format_trace = format_esp_decrypt_trace,
1476   .type = VLIB_NODE_TYPE_INTERNAL,
1477
1478   .n_errors = ESP_DECRYPT_N_ERROR,
1479   .error_counters = esp_decrypt_error_counters,
1480
1481   .sibling_of = "esp4-decrypt",
1482 };
1483
1484 VLIB_REGISTER_NODE (esp6_decrypt_node) = {
1485   .name = "esp6-decrypt",
1486   .vector_size = sizeof (u32),
1487   .format_trace = format_esp_decrypt_trace,
1488   .type = VLIB_NODE_TYPE_INTERNAL,
1489
1490   .n_errors = ESP_DECRYPT_N_ERROR,
1491   .error_counters = esp_decrypt_error_counters,
1492
1493   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1494   .next_nodes = {
1495     [ESP_DECRYPT_NEXT_DROP] = "ip6-drop",
1496     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1497     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1498     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-drop",
1499     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1500     [ESP_DECRYPT_NEXT_HANDOFF]=  "esp6-decrypt-handoff",
1501   },
1502 };
1503
1504 VLIB_REGISTER_NODE (esp6_decrypt_post_node) = {
1505   .name = "esp6-decrypt-post",
1506   .vector_size = sizeof (u32),
1507   .format_trace = format_esp_decrypt_trace,
1508   .type = VLIB_NODE_TYPE_INTERNAL,
1509
1510   .n_errors = ESP_DECRYPT_N_ERROR,
1511   .error_counters = esp_decrypt_error_counters,
1512
1513   .sibling_of = "esp6-decrypt",
1514 };
1515
1516 VLIB_REGISTER_NODE (esp4_decrypt_tun_node) = {
1517   .name = "esp4-decrypt-tun",
1518   .vector_size = sizeof (u32),
1519   .format_trace = format_esp_decrypt_trace,
1520   .type = VLIB_NODE_TYPE_INTERNAL,
1521   .n_errors = ESP_DECRYPT_N_ERROR,
1522   .error_counters = esp_decrypt_error_counters,
1523   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1524   .next_nodes = {
1525     [ESP_DECRYPT_NEXT_DROP] = "ip4-drop",
1526     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1527     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1528     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-input",
1529     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1530     [ESP_DECRYPT_NEXT_HANDOFF] = "esp4-decrypt-tun-handoff",
1531   },
1532 };
1533
1534 VLIB_REGISTER_NODE (esp4_decrypt_tun_post_node) = {
1535   .name = "esp4-decrypt-tun-post",
1536   .vector_size = sizeof (u32),
1537   .format_trace = format_esp_decrypt_trace,
1538   .type = VLIB_NODE_TYPE_INTERNAL,
1539
1540   .n_errors = ESP_DECRYPT_N_ERROR,
1541   .error_counters = esp_decrypt_error_counters,
1542
1543   .sibling_of = "esp4-decrypt-tun",
1544 };
1545
1546 VLIB_REGISTER_NODE (esp6_decrypt_tun_node) = {
1547   .name = "esp6-decrypt-tun",
1548   .vector_size = sizeof (u32),
1549   .format_trace = format_esp_decrypt_trace,
1550   .type = VLIB_NODE_TYPE_INTERNAL,
1551   .n_errors = ESP_DECRYPT_N_ERROR,
1552   .error_counters = esp_decrypt_error_counters,
1553   .n_next_nodes = ESP_DECRYPT_N_NEXT,
1554   .next_nodes = {
1555     [ESP_DECRYPT_NEXT_DROP] = "ip6-drop",
1556     [ESP_DECRYPT_NEXT_IP4_INPUT] = "ip4-input-no-checksum",
1557     [ESP_DECRYPT_NEXT_IP6_INPUT] = "ip6-input",
1558     [ESP_DECRYPT_NEXT_MPLS_INPUT] = "mpls-input",
1559     [ESP_DECRYPT_NEXT_L2_INPUT] = "l2-input",
1560     [ESP_DECRYPT_NEXT_HANDOFF]=  "esp6-decrypt-tun-handoff",
1561   },
1562 };
1563
1564 VLIB_REGISTER_NODE (esp6_decrypt_tun_post_node) = {
1565   .name = "esp6-decrypt-tun-post",
1566   .vector_size = sizeof (u32),
1567   .format_trace = format_esp_decrypt_trace,
1568   .type = VLIB_NODE_TYPE_INTERNAL,
1569
1570   .n_errors = ESP_DECRYPT_N_ERROR,
1571   .error_counters = esp_decrypt_error_counters,
1572
1573   .sibling_of = "esp6-decrypt-tun",
1574 };
1575 /* *INDENT-ON* */
1576
1577 #ifndef CLIB_MARCH_VARIANT
1578
1579 static clib_error_t *
1580 esp_decrypt_init (vlib_main_t *vm)
1581 {
1582   ipsec_main_t *im = &ipsec_main;
1583
1584   im->esp4_dec_fq_index =
1585     vlib_frame_queue_main_init (esp4_decrypt_node.index, 0);
1586   im->esp6_dec_fq_index =
1587     vlib_frame_queue_main_init (esp6_decrypt_node.index, 0);
1588   im->esp4_dec_tun_fq_index =
1589     vlib_frame_queue_main_init (esp4_decrypt_tun_node.index, 0);
1590   im->esp6_dec_tun_fq_index =
1591     vlib_frame_queue_main_init (esp6_decrypt_tun_node.index, 0);
1592
1593   return 0;
1594 }
1595
1596 VLIB_INIT_FUNCTION (esp_decrypt_init);
1597
1598 #endif
1599
1600 /*
1601  * fd.io coding-style-patch-verification: ON
1602  *
1603  * Local Variables:
1604  * eval: (c-set-style "gnu")
1605  * End:
1606  */