0a33d25bd61fa7d88dfe6554aa920c8567047d2d
[vpp.git] / src / plugins / dpdk / cryptodev / cryptodev_dp_api.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2020 Intel and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17
18 #include <vlib/vlib.h>
19 #include <vnet/plugin/plugin.h>
20 #include <vnet/crypto/crypto.h>
21 #include <vnet/vnet.h>
22 #include <vpp/app/version.h>
23
24 #include <dpdk/buffer.h>
25 #include <dpdk/device/dpdk.h>
26 #include <dpdk/device/dpdk_priv.h>
27 #undef always_inline
28 #include <rte_bus_vdev.h>
29 #include <rte_cryptodev.h>
30 #include <rte_crypto_sym.h>
31 #include <rte_crypto.h>
32 #include <rte_cryptodev_pmd.h>
33 #include <rte_config.h>
34
35 #if CLIB_DEBUG > 0
36 #define always_inline static inline
37 #else
38 #define always_inline static inline __attribute__ ((__always_inline__))
39 #endif
40
41 #define CRYPTODEV_NB_CRYPTO_OPS 1024
42 #define CRYPTODEV_MAX_INFLIGHT  (CRYPTODEV_NB_CRYPTO_OPS - 1)
43 #define CRYPTODEV_AAD_MASK      (CRYPTODEV_NB_CRYPTO_OPS - 1)
44 #define CRYPTODEV_DEQ_CACHE_SZ  32
45 #define CRYPTODEV_NB_SESSION    10240
46 #define CRYPTODEV_MAX_AAD_SIZE  16
47 #define CRYPTODEV_MAX_N_SGL     8 /**< maximum number of segments */
48
49 /* VNET_CRYPTO_ALGO, TYPE, DPDK_CRYPTO_ALGO, IV_LEN, TAG_LEN, AAD_LEN */
50 #define foreach_vnet_aead_crypto_conversion \
51   _(AES_128_GCM, AEAD, AES_GCM, 12, 16, 8)  \
52   _(AES_128_GCM, AEAD, AES_GCM, 12, 16, 12) \
53   _(AES_192_GCM, AEAD, AES_GCM, 12, 16, 8)  \
54   _(AES_192_GCM, AEAD, AES_GCM, 12, 16, 12) \
55   _(AES_256_GCM, AEAD, AES_GCM, 12, 16, 8)  \
56   _(AES_256_GCM, AEAD, AES_GCM, 12, 16, 12)
57
58 /**
59  * crypto (alg, cryptodev_alg), hash (alg, digest-size)
60  **/
61 #define foreach_cryptodev_link_async_alg        \
62   _ (AES_128_CBC, AES_CBC, SHA1, 12)            \
63   _ (AES_192_CBC, AES_CBC, SHA1, 12)            \
64   _ (AES_256_CBC, AES_CBC, SHA1, 12)            \
65   _ (AES_128_CBC, AES_CBC, SHA224, 14)          \
66   _ (AES_192_CBC, AES_CBC, SHA224, 14)          \
67   _ (AES_256_CBC, AES_CBC, SHA224, 14)          \
68   _ (AES_128_CBC, AES_CBC, SHA256, 16)          \
69   _ (AES_192_CBC, AES_CBC, SHA256, 16)          \
70   _ (AES_256_CBC, AES_CBC, SHA256, 16)          \
71   _ (AES_128_CBC, AES_CBC, SHA384, 24)          \
72   _ (AES_192_CBC, AES_CBC, SHA384, 24)          \
73   _ (AES_256_CBC, AES_CBC, SHA384, 24)          \
74   _ (AES_128_CBC, AES_CBC, SHA512, 32)          \
75   _ (AES_192_CBC, AES_CBC, SHA512, 32)          \
76   _ (AES_256_CBC, AES_CBC, SHA512, 32)
77
78 typedef enum
79 {
80   CRYPTODEV_OP_TYPE_ENCRYPT = 0,
81   CRYPTODEV_OP_TYPE_DECRYPT,
82   CRYPTODEV_N_OP_TYPES,
83 } cryptodev_op_type_t;
84
85 typedef struct
86 {
87   union rte_cryptodev_session_ctx keys[CRYPTODEV_N_OP_TYPES];
88 } cryptodev_key_t;
89
90 typedef struct
91 {
92   u32 dev_id;
93   u32 q_id;
94   struct rte_crypto_raw_dp_ctx *raw_dp_ctx_buffer;
95   char *desc;
96 } cryptodev_inst_t;
97
98 typedef struct
99 {
100   struct rte_mempool *sess_pool;
101   struct rte_mempool *sess_priv_pool;
102 } cryptodev_numa_data_t;
103
104 typedef struct
105 {
106   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
107   vlib_buffer_t *b[VNET_CRYPTO_FRAME_SIZE];
108   struct rte_crypto_raw_dp_ctx *ctx;
109   struct rte_crypto_vec vec[CRYPTODEV_MAX_N_SGL];
110   struct rte_ring *cached_frame;
111   u16 aad_index;
112   u8 *aad_buf;
113   u64 aad_phy_addr;
114   u16 cryptodev_id;
115   u16 cryptodev_q;
116   u16 inflight;
117 } cryptodev_engine_thread_t;
118
119 typedef struct
120 {
121   cryptodev_numa_data_t *per_numa_data;
122   cryptodev_key_t *keys;
123   cryptodev_engine_thread_t *per_thread_data;
124   enum rte_iova_mode iova_mode;
125   cryptodev_inst_t *cryptodev_inst;
126   clib_bitmap_t *active_cdev_inst_mask;
127   clib_spinlock_t tlock;
128 } cryptodev_main_t;
129
130 cryptodev_main_t cryptodev_main;
131
132 static int
133 prepare_aead_xform (struct rte_crypto_sym_xform *xform,
134                     cryptodev_op_type_t op_type,
135                     const vnet_crypto_key_t * key, u32 aad_len)
136 {
137   struct rte_crypto_aead_xform *aead_xform = &xform->aead;
138   memset (xform, 0, sizeof (*xform));
139   xform->type = RTE_CRYPTO_SYM_XFORM_AEAD;
140   xform->next = 0;
141
142   if (key->alg != VNET_CRYPTO_ALG_AES_128_GCM &&
143       key->alg != VNET_CRYPTO_ALG_AES_192_GCM &&
144       key->alg != VNET_CRYPTO_ALG_AES_256_GCM)
145     return -1;
146
147   aead_xform->algo = RTE_CRYPTO_AEAD_AES_GCM;
148   aead_xform->op = (op_type == CRYPTODEV_OP_TYPE_ENCRYPT) ?
149     RTE_CRYPTO_AEAD_OP_ENCRYPT : RTE_CRYPTO_AEAD_OP_DECRYPT;
150   aead_xform->aad_length = aad_len;
151   aead_xform->digest_length = 16;
152   aead_xform->iv.offset = 0;
153   aead_xform->iv.length = 12;
154   aead_xform->key.data = key->data;
155   aead_xform->key.length = vec_len (key->data);
156
157   return 0;
158 }
159
160 static int
161 prepare_linked_xform (struct rte_crypto_sym_xform *xforms,
162                       cryptodev_op_type_t op_type,
163                       const vnet_crypto_key_t * key)
164 {
165   struct rte_crypto_sym_xform *xform_cipher, *xform_auth;
166   vnet_crypto_key_t *key_cipher, *key_auth;
167   enum rte_crypto_cipher_algorithm cipher_algo = ~0;
168   enum rte_crypto_auth_algorithm auth_algo = ~0;
169   u32 digest_len = ~0;
170
171   key_cipher = vnet_crypto_get_key (key->index_crypto);
172   key_auth = vnet_crypto_get_key (key->index_integ);
173   if (!key_cipher || !key_auth)
174     return -1;
175
176   if (op_type == CRYPTODEV_OP_TYPE_ENCRYPT)
177     {
178       xform_cipher = xforms;
179       xform_auth = xforms + 1;
180       xform_cipher->cipher.op = RTE_CRYPTO_CIPHER_OP_ENCRYPT;
181       xform_auth->auth.op = RTE_CRYPTO_AUTH_OP_GENERATE;
182     }
183   else
184     {
185       xform_cipher = xforms + 1;
186       xform_auth = xforms;
187       xform_cipher->cipher.op = RTE_CRYPTO_CIPHER_OP_DECRYPT;
188       xform_auth->auth.op = RTE_CRYPTO_AUTH_OP_VERIFY;
189     }
190
191   xform_cipher->type = RTE_CRYPTO_SYM_XFORM_CIPHER;
192   xform_auth->type = RTE_CRYPTO_SYM_XFORM_AUTH;
193   xforms->next = xforms + 1;
194
195   switch (key->async_alg)
196     {
197 #define _(a, b, c, d) \
198   case VNET_CRYPTO_ALG_##a##_##c##_TAG##d:\
199     cipher_algo = RTE_CRYPTO_CIPHER_##b; \
200     auth_algo = RTE_CRYPTO_AUTH_##c##_HMAC; \
201     digest_len = d; \
202     break;
203
204       foreach_cryptodev_link_async_alg
205 #undef _
206     default:
207       return -1;
208     }
209
210   xform_cipher->cipher.algo = cipher_algo;
211   xform_cipher->cipher.key.data = key_cipher->data;
212   xform_cipher->cipher.key.length = vec_len (key_cipher->data);
213   xform_cipher->cipher.iv.length = 16;
214   xform_cipher->cipher.iv.offset = 0;
215
216   xform_auth->auth.algo = auth_algo;
217   xform_auth->auth.digest_length = digest_len;
218   xform_auth->auth.key.data = key_auth->data;
219   xform_auth->auth.key.length = vec_len (key_auth->data);
220
221   return 0;
222 }
223
224 static int
225 cryptodev_session_create (vnet_crypto_key_t * const key,
226                           struct rte_mempool *sess_priv_pool,
227                           cryptodev_key_t * session_pair, u32 aad_len)
228 {
229   struct rte_crypto_sym_xform xforms_enc[2] = { {0} };
230   struct rte_crypto_sym_xform xforms_dec[2] = { {0} };
231   cryptodev_main_t *cmt = &cryptodev_main;
232   cryptodev_inst_t *dev_inst;
233   struct rte_cryptodev *cdev;
234   int ret;
235   uint8_t dev_id = 0;
236
237   if (key->type == VNET_CRYPTO_KEY_TYPE_LINK)
238     ret = prepare_linked_xform (xforms_enc, CRYPTODEV_OP_TYPE_ENCRYPT, key);
239   else
240     ret = prepare_aead_xform (xforms_enc, CRYPTODEV_OP_TYPE_ENCRYPT, key,
241                               aad_len);
242   if (ret)
243     return 0;
244
245   if (key->type == VNET_CRYPTO_KEY_TYPE_LINK)
246     prepare_linked_xform (xforms_dec, CRYPTODEV_OP_TYPE_DECRYPT, key);
247   else
248     prepare_aead_xform (xforms_dec, CRYPTODEV_OP_TYPE_DECRYPT, key, aad_len);
249
250   vec_foreach (dev_inst, cmt->cryptodev_inst)
251   {
252     dev_id = dev_inst->dev_id;
253     cdev = rte_cryptodev_pmd_get_dev (dev_id);
254
255     /* if the session is already configured for the driver type, avoid
256        configuring it again to increase the session data's refcnt */
257     if (session_pair->keys[0].crypto_sess->sess_data[cdev->driver_id].data &&
258         session_pair->keys[1].crypto_sess->sess_data[cdev->driver_id].data)
259       continue;
260
261     ret = rte_cryptodev_sym_session_init (dev_id,
262                                           session_pair->keys[0].crypto_sess,
263                                           xforms_enc, sess_priv_pool);
264     ret = rte_cryptodev_sym_session_init (dev_id,
265                                           session_pair->keys[1].crypto_sess,
266                                           xforms_dec, sess_priv_pool);
267     if (ret < 0)
268       return ret;
269   }
270   session_pair->keys[0].crypto_sess->opaque_data = aad_len;
271   session_pair->keys[1].crypto_sess->opaque_data = aad_len;
272
273   return 0;
274 }
275
276 static void
277 cryptodev_session_del (struct rte_cryptodev_sym_session *sess)
278 {
279   u32 n_devs, i;
280
281   if (sess == NULL)
282     return;
283
284   n_devs = rte_cryptodev_count ();
285
286   for (i = 0; i < n_devs; i++)
287     rte_cryptodev_sym_session_clear (i, sess);
288
289   rte_cryptodev_sym_session_free (sess);
290 }
291
292 static int
293 cryptodev_check_supported_vnet_alg (vnet_crypto_key_t * key)
294 {
295   vnet_crypto_alg_t alg;
296   if (key->type == VNET_CRYPTO_KEY_TYPE_LINK)
297     return 0;
298
299   alg = key->alg;
300
301 #define _(a, b, c, d, e, f)     \
302   if (alg == VNET_CRYPTO_ALG_##a) \
303     return 0;
304
305   foreach_vnet_aead_crypto_conversion
306 #undef _
307     return -1;
308 }
309
310 static_always_inline void
311 cryptodev_sess_handler (vlib_main_t * vm, vnet_crypto_key_op_t kop,
312                         vnet_crypto_key_index_t idx, u32 aad_len)
313 {
314   cryptodev_main_t *cmt = &cryptodev_main;
315   cryptodev_numa_data_t *numa_data;
316   vnet_crypto_key_t *key = vnet_crypto_get_key (idx);
317   struct rte_mempool *sess_pool, *sess_priv_pool;
318   cryptodev_key_t *ckey = 0;
319   int ret = 0;
320
321   if (kop == VNET_CRYPTO_KEY_OP_DEL)
322     {
323       if (idx >= vec_len (cmt->keys))
324         return;
325
326       ckey = pool_elt_at_index (cmt->keys, idx);
327       cryptodev_session_del (ckey->keys[0].crypto_sess);
328       cryptodev_session_del (ckey->keys[1].crypto_sess);
329       ckey->keys[0].crypto_sess = 0;
330       ckey->keys[1].crypto_sess = 0;
331       pool_put (cmt->keys, ckey);
332       return;
333     }
334   else if (kop == VNET_CRYPTO_KEY_OP_MODIFY)
335     {
336       if (idx >= vec_len (cmt->keys))
337         return;
338
339       ckey = pool_elt_at_index (cmt->keys, idx);
340
341       cryptodev_session_del (ckey->keys[0].crypto_sess);
342       cryptodev_session_del (ckey->keys[1].crypto_sess);
343       ckey->keys[0].crypto_sess = 0;
344       ckey->keys[1].crypto_sess = 0;
345     }
346   else                          /* create key */
347     pool_get_zero (cmt->keys, ckey);
348
349   /* do not create session for unsupported alg */
350   if (cryptodev_check_supported_vnet_alg (key))
351     return;
352
353   numa_data = vec_elt_at_index (cmt->per_numa_data, vm->numa_node);
354   sess_pool = numa_data->sess_pool;
355   sess_priv_pool = numa_data->sess_priv_pool;
356
357   ckey->keys[0].crypto_sess = rte_cryptodev_sym_session_create (sess_pool);
358   if (!ckey->keys[0].crypto_sess)
359     {
360       ret = -1;
361       goto clear_key;
362     }
363
364   ckey->keys[1].crypto_sess = rte_cryptodev_sym_session_create (sess_pool);
365   if (!ckey->keys[1].crypto_sess)
366     {
367       ret = -1;
368       goto clear_key;
369     }
370
371   ret = cryptodev_session_create (key, sess_priv_pool, ckey, aad_len);
372
373 clear_key:
374   if (ret != 0)
375     {
376       cryptodev_session_del (ckey->keys[0].crypto_sess);
377       cryptodev_session_del (ckey->keys[1].crypto_sess);
378       memset (ckey, 0, sizeof (*ckey));
379       pool_put (cmt->keys, ckey);
380     }
381 }
382
383 /*static*/ void
384 cryptodev_key_handler (vlib_main_t * vm, vnet_crypto_key_op_t kop,
385                        vnet_crypto_key_index_t idx)
386 {
387   cryptodev_sess_handler (vm, kop, idx, 8);
388 }
389
390 static_always_inline void
391 cryptodev_mark_frame_err_status (vnet_crypto_async_frame_t * f,
392                                  vnet_crypto_op_status_t s)
393 {
394   u32 n_elts = f->n_elts, i;
395
396   for (i = 0; i < n_elts; i++)
397     f->elts[i].status = s;
398   f->state = VNET_CRYPTO_FRAME_STATE_NOT_PROCESSED;
399 }
400
401 static_always_inline int
402 cryptodev_frame_build_sgl (vlib_main_t * vm, enum rte_iova_mode iova_mode,
403                            struct rte_crypto_vec *data_vec,
404                            u16 * n_seg, vlib_buffer_t * b, u32 size)
405 {
406   struct rte_crypto_vec *vec = data_vec + 1;
407   if (vlib_buffer_chain_linearize (vm, b) > CRYPTODEV_MAX_N_SGL)
408     return -1;
409
410   while ((b->flags & VLIB_BUFFER_NEXT_PRESENT) && size)
411     {
412       u32 len;
413       b = vlib_get_buffer (vm, b->next_buffer);
414       len = clib_min (b->current_length, size);
415       vec->base = (void *) vlib_buffer_get_current (b);
416       if (iova_mode == RTE_IOVA_VA)
417         vec->iova = pointer_to_uword (vec->base);
418       else
419         vec->iova = vlib_buffer_get_current_pa (vm, b);
420       vec->len = len;
421       size -= len;
422       vec++;
423       *n_seg += 1;
424     }
425
426   if (size)
427     return -1;
428
429   return 0;
430 }
431
432 static_always_inline u64
433 compute_ofs_linked_alg (vnet_crypto_async_frame_elt_t * fe, i16 * min_ofs,
434                         u32 * max_end)
435 {
436   union rte_crypto_sym_ofs ofs;
437   u32 crypto_end = fe->crypto_start_offset + fe->crypto_total_length;
438   u32 integ_end = fe->integ_start_offset + fe->crypto_total_length +
439     fe->integ_length_adj;
440
441   *min_ofs = clib_min (fe->crypto_start_offset, fe->integ_start_offset);
442   *max_end = clib_max (crypto_end, integ_end);
443
444   ofs.ofs.cipher.head = fe->crypto_start_offset - *min_ofs;
445   ofs.ofs.cipher.tail = *max_end - crypto_end;
446   ofs.ofs.auth.head = fe->integ_start_offset - *min_ofs;
447   ofs.ofs.auth.tail = *max_end - integ_end;
448
449   return ofs.raw;
450 }
451
452 /* Reset cryptodev dp context to previous queue pair state */
453 static_always_inline void
454 cryptodev_reset_ctx (u16 cdev_id, u16 qid, struct rte_crypto_raw_dp_ctx *ctx)
455 {
456   union rte_cryptodev_session_ctx session_ctx = {.crypto_sess = NULL };
457
458   rte_cryptodev_configure_raw_dp_ctx (cdev_id, qid, ctx, ~0, session_ctx, 0);
459 }
460
461 static_always_inline int
462 cryptodev_frame_linked_algs_enqueue (vlib_main_t * vm,
463                                      vnet_crypto_async_frame_t * frame,
464                                      cryptodev_op_type_t op_type)
465 {
466   cryptodev_main_t *cmt = &cryptodev_main;
467   cryptodev_engine_thread_t *cet = cmt->per_thread_data + vm->thread_index;
468   vnet_crypto_async_frame_elt_t *fe;
469   struct rte_crypto_vec *vec;
470   struct rte_crypto_va_iova_ptr iv_vec, digest_vec;
471   vlib_buffer_t **b;
472   u32 n_elts;
473   cryptodev_key_t *key;
474   u32 last_key_index = ~0;
475   i16 min_ofs;
476   u32 max_end;
477   int status;
478
479   n_elts = frame->n_elts;
480
481   if (PREDICT_FALSE (CRYPTODEV_MAX_INFLIGHT - cet->inflight < n_elts))
482     {
483       cryptodev_mark_frame_err_status (frame,
484                                        VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
485       return -1;
486     }
487
488   vlib_get_buffers (vm, frame->buffer_indices, cet->b, frame->n_elts);
489
490   vec = cet->vec;
491   b = cet->b;
492   fe = frame->elts;
493
494   while (n_elts)
495     {
496       union rte_crypto_sym_ofs cofs;
497       u16 n_seg = 1;
498
499       if (n_elts > 2)
500         {
501           CLIB_PREFETCH (&fe[1], CLIB_CACHE_LINE_BYTES, LOAD);
502           CLIB_PREFETCH (&fe[2], CLIB_CACHE_LINE_BYTES, LOAD);
503           vlib_prefetch_buffer_header (b[1], LOAD);
504           vlib_prefetch_buffer_header (b[2], LOAD);
505         }
506
507       if (PREDICT_FALSE (last_key_index != fe->key_index))
508         {
509           key = pool_elt_at_index (cmt->keys, fe->key_index);
510           last_key_index = fe->key_index;
511
512           if (PREDICT_FALSE
513               (rte_cryptodev_configure_raw_dp_ctx
514                (cet->cryptodev_id, cet->cryptodev_q, cet->ctx,
515                 RTE_CRYPTO_OP_WITH_SESSION, key->keys[op_type], 1) < 0))
516             {
517               cryptodev_mark_frame_err_status (frame,
518                                                VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
519               cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q,
520                                    cet->ctx);
521               return -1;
522             }
523         }
524
525       cofs.raw = compute_ofs_linked_alg (fe, &min_ofs, &max_end);
526
527       vec->len = max_end - min_ofs;
528       if (cmt->iova_mode == RTE_IOVA_VA)
529         {
530           vec[0].base = (void *) (b[0]->data + min_ofs);
531           vec[0].iova = pointer_to_uword (b[0]->data) + min_ofs;
532           iv_vec.va = (void *) fe->iv;
533           iv_vec.iova = pointer_to_uword (fe->iv);
534           digest_vec.va = (void *) fe->tag;
535           digest_vec.iova = pointer_to_uword (fe->tag);
536         }
537       else
538         {
539           vec[0].base = (void *) (b[0]->data + min_ofs);
540           vec[0].iova = vlib_buffer_get_pa (vm, b[0]) + min_ofs;
541           iv_vec.va = (void *) fe->iv;
542           iv_vec.iova = vlib_physmem_get_pa (vm, fe->iv);
543           digest_vec.va = (void *) fe->tag;
544           digest_vec.iova = vlib_physmem_get_pa (vm, fe->digest);
545         }
546
547       if (PREDICT_FALSE (fe->flags & VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS))
548         {
549           vec[0].len = b[0]->current_data + b[0]->current_length - min_ofs;
550           if (cryptodev_frame_build_sgl
551               (vm, cmt->iova_mode, vec, &n_seg, b[0],
552                max_end - min_ofs - vec->len) < 0)
553             {
554               cryptodev_mark_frame_err_status (frame,
555                                                VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
556               cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q,
557                                    cet->ctx);
558               return -1;
559             }
560         }
561
562       status = rte_cryptodev_raw_enqueue (cet->ctx, vec, n_seg, cofs, &iv_vec,
563                                           &digest_vec, 0, (void *) frame);
564       if (status < 0)
565         {
566           cryptodev_mark_frame_err_status (frame,
567                                            VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
568           cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q, cet->ctx);
569           return -1;
570         }
571
572       b++;
573       fe++;
574       n_elts--;
575     }
576
577   status = rte_cryptodev_raw_enqueue_done (cet->ctx, frame->n_elts);
578   if (PREDICT_FALSE (status < 0))
579     {
580       cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q, cet->ctx);
581       return -1;
582     }
583
584   cet->inflight += frame->n_elts;
585   return 0;
586 }
587
588 static_always_inline int
589 cryptodev_frame_gcm_enqueue (vlib_main_t * vm,
590                              vnet_crypto_async_frame_t * frame,
591                              cryptodev_op_type_t op_type, u8 aad_len)
592 {
593   cryptodev_main_t *cmt = &cryptodev_main;
594   cryptodev_engine_thread_t *cet = cmt->per_thread_data + vm->thread_index;
595   vnet_crypto_async_frame_elt_t *fe;
596   vlib_buffer_t **b;
597   u32 n_elts;
598   cryptodev_key_t *key;
599   u32 last_key_index = ~0;
600   union rte_crypto_sym_ofs cofs;
601   struct rte_crypto_vec *vec;
602   struct rte_crypto_va_iova_ptr iv_vec, digest_vec, aad_vec;
603   u8 sess_aad_len = 0;
604   int status;
605
606
607   n_elts = frame->n_elts;
608
609   if (PREDICT_FALSE (CRYPTODEV_MAX_INFLIGHT - cet->inflight < n_elts))
610     {
611       cryptodev_mark_frame_err_status (frame,
612                                        VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
613       return -1;
614     }
615
616   vlib_get_buffers (vm, frame->buffer_indices, cet->b, frame->n_elts);
617
618   vec = cet->vec;
619   fe = frame->elts;
620   b = cet->b;
621   cofs.raw = 0;
622
623   while (n_elts)
624     {
625       u32 aad_offset = ((cet->aad_index++) & CRYPTODEV_AAD_MASK) << 4;
626       u16 n_seg = 1;
627
628       if (n_elts > 1)
629         {
630           CLIB_PREFETCH (&fe[1], CLIB_CACHE_LINE_BYTES, LOAD);
631           vlib_prefetch_buffer_header (b[1], LOAD);
632         }
633
634       if (last_key_index != fe->key_index)
635         {
636           key = pool_elt_at_index (cmt->keys, fe->key_index);
637           sess_aad_len = (u8) key->keys[op_type].crypto_sess->opaque_data;
638           if (PREDICT_FALSE (sess_aad_len != aad_len))
639             {
640               cryptodev_sess_handler (vm, VNET_CRYPTO_KEY_OP_MODIFY,
641                                       fe->key_index, aad_len);
642             }
643           last_key_index = fe->key_index;
644
645           if (PREDICT_FALSE
646               (rte_cryptodev_configure_raw_dp_ctx
647                (cet->cryptodev_id, cet->cryptodev_q, cet->ctx,
648                 RTE_CRYPTO_OP_WITH_SESSION, key->keys[op_type], 1) < 0))
649             {
650               cryptodev_mark_frame_err_status (frame,
651                                                VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
652               cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q,
653                                    cet->ctx);
654               return -1;
655             }
656         }
657
658       if (cmt->iova_mode == RTE_IOVA_VA)
659         {
660           vec[0].base = (void *) (b[0]->data + fe->crypto_start_offset);
661           vec[0].iova = pointer_to_uword (vec[0].base);
662           vec[0].len = fe->crypto_total_length;
663           iv_vec.va = (void *) fe->iv;
664           iv_vec.iova = pointer_to_uword (fe->iv);
665           digest_vec.va = (void *) fe->tag;
666           digest_vec.iova = pointer_to_uword (fe->tag);
667           aad_vec.va = (void *) (cet->aad_buf + aad_offset);
668           aad_vec.iova = cet->aad_phy_addr + aad_offset;
669         }
670       else
671         {
672           vec[0].base = (void *) (b[0]->data + fe->crypto_start_offset);
673           vec[0].iova =
674             vlib_buffer_get_pa (vm, b[0]) + fe->crypto_start_offset;
675           vec[0].len = fe->crypto_total_length;
676           iv_vec.va = (void *) fe->iv;
677           iv_vec.iova = vlib_physmem_get_pa (vm, fe->iv);
678           aad_vec.va = (void *) (cet->aad_buf + aad_offset);
679           aad_vec.iova = cet->aad_phy_addr + aad_offset;
680           digest_vec.va = (void *) fe->tag;
681           digest_vec.iova = vlib_physmem_get_pa (vm, fe->tag);
682         }
683
684       if (aad_len == 8)
685         *(u64 *) (cet->aad_buf + aad_offset) = *(u64 *) fe->aad;
686       else
687         {
688           /* aad_len == 12 */
689           *(u64 *) (cet->aad_buf + aad_offset) = *(u64 *) fe->aad;
690           *(u32 *) (cet->aad_buf + aad_offset + 8) = *(u32 *) (fe->aad + 8);
691         }
692
693       if (PREDICT_FALSE (fe->flags & VNET_CRYPTO_OP_FLAG_CHAINED_BUFFERS))
694         {
695           vec[0].len = b[0]->current_data +
696             b[0]->current_length - fe->crypto_start_offset;
697           if (cryptodev_frame_build_sgl
698               (vm, cmt->iova_mode, vec, &n_seg, b[0],
699                fe->crypto_total_length - vec[0].len) < 0)
700             {
701               cryptodev_mark_frame_err_status (frame,
702                                                VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
703               cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q,
704                                    cet->ctx);
705               return -1;
706             }
707         }
708
709       status =
710         rte_cryptodev_raw_enqueue (cet->ctx, vec, n_seg, cofs,
711                                    &iv_vec, &digest_vec, &aad_vec,
712                                    (void *) frame);
713       if (PREDICT_FALSE (status < 0))
714         {
715           cryptodev_mark_frame_err_status (frame,
716                                            VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR);
717           cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q, cet->ctx);
718           return -1;
719         }
720       fe++;
721       b++;
722       n_elts--;
723     }
724
725   status = rte_cryptodev_raw_enqueue_done (cet->ctx, frame->n_elts);
726   if (PREDICT_FALSE (status < 0))
727     {
728       cryptodev_reset_ctx (cet->cryptodev_id, cet->cryptodev_q, cet->ctx);
729       return -1;
730     }
731
732   cet->inflight += frame->n_elts;
733
734   return 0;
735 }
736
737 static u32
738 cryptodev_get_frame_n_elts (void *frame)
739 {
740   vnet_crypto_async_frame_t *f = (vnet_crypto_async_frame_t *) frame;
741   return f->n_elts;
742 }
743
744 static void
745 cryptodev_post_dequeue (void *frame, u32 index, u8 is_op_success)
746 {
747   vnet_crypto_async_frame_t *f = (vnet_crypto_async_frame_t *) frame;
748
749   f->elts[index].status = is_op_success ? VNET_CRYPTO_OP_STATUS_COMPLETED :
750     VNET_CRYPTO_OP_STATUS_FAIL_BAD_HMAC;
751 }
752
753 #define GET_RING_OBJ(r, pos, f) do { \
754         vnet_crypto_async_frame_t **ring = (void *)&r[1];     \
755         f = ring[(r->cons.head + pos) & r->mask]; \
756 } while (0)
757
758 static_always_inline vnet_crypto_async_frame_t *
759 cryptodev_frame_dequeue (vlib_main_t * vm, u32 * nb_elts_processed,
760                          u32 * enqueue_thread_idx)
761 {
762   cryptodev_main_t *cmt = &cryptodev_main;
763   cryptodev_engine_thread_t *cet = cmt->per_thread_data + vm->thread_index;
764   vnet_crypto_async_frame_t *frame, *frame_ret = 0;
765   u32 n_deq, n_success;
766   u32 n_cached_frame = rte_ring_count (cet->cached_frame), n_room_left;
767   u8 no_job_to_deq = 0;
768   u16 inflight = cet->inflight;
769   int dequeue_status;
770
771   n_room_left = CRYPTODEV_DEQ_CACHE_SZ - n_cached_frame - 1;
772
773   if (n_cached_frame)
774     {
775       u32 i;
776       for (i = 0; i < n_cached_frame; i++)
777         {
778           vnet_crypto_async_frame_t *f;
779           void *f_ret;
780           enum rte_crypto_op_status op_status;
781           u8 n_left, err, j;
782
783           GET_RING_OBJ (cet->cached_frame, i, f);
784
785           if (i < n_cached_frame - 2)
786             {
787               vnet_crypto_async_frame_t *f1, *f2;
788               GET_RING_OBJ (cet->cached_frame, i + 1, f1);
789               GET_RING_OBJ (cet->cached_frame, i + 2, f2);
790               CLIB_PREFETCH (f1, CLIB_CACHE_LINE_BYTES, LOAD);
791               CLIB_PREFETCH (f2, CLIB_CACHE_LINE_BYTES, LOAD);
792             }
793
794           n_left = f->state & 0x7f;
795           err = f->state & 0x80;
796
797           for (j = f->n_elts - n_left; j < f->n_elts && inflight; j++)
798             {
799               int ret;
800               f_ret = rte_cryptodev_raw_dequeue (cet->ctx, &ret, &op_status);
801
802               if (!f_ret)
803                 break;
804
805               switch (op_status)
806                 {
807                 case RTE_CRYPTO_OP_STATUS_SUCCESS:
808                   f->elts[j].status = VNET_CRYPTO_OP_STATUS_COMPLETED;
809                   break;
810                 default:
811                   f->elts[j].status = VNET_CRYPTO_OP_STATUS_FAIL_ENGINE_ERR;
812                   err |= 1 << 7;
813                 }
814
815               inflight--;
816             }
817
818           if (j == f->n_elts)
819             {
820               if (i == 0)
821                 {
822                   frame_ret = f;
823                   f->state = err ? VNET_CRYPTO_FRAME_STATE_ELT_ERROR :
824                     VNET_CRYPTO_FRAME_STATE_SUCCESS;
825                 }
826               else
827                 {
828                   f->state = f->n_elts - j;
829                   f->state |= err;
830                 }
831               if (inflight)
832                 continue;
833             }
834
835           /* to here f is not completed dequeued and no more job can be
836            * dequeued
837            */
838           f->state = f->n_elts - j;
839           f->state |= err;
840           no_job_to_deq = 1;
841           break;
842         }
843
844       if (frame_ret)
845         {
846           rte_ring_sc_dequeue (cet->cached_frame, (void **) &frame_ret);
847           n_room_left++;
848         }
849     }
850
851   /* no point to dequeue further */
852   if (!inflight || no_job_to_deq || !n_room_left)
853     goto end_deq;
854
855   n_deq = rte_cryptodev_raw_dequeue_burst (cet->ctx,
856                                            cryptodev_get_frame_n_elts,
857                                            cryptodev_post_dequeue,
858                                            (void **) &frame, 0, &n_success,
859                                            &dequeue_status);
860   if (!n_deq)
861     goto end_deq;
862
863   inflight -= n_deq;
864   no_job_to_deq = n_deq < frame->n_elts;
865   /* we have to cache the frame */
866   if (frame_ret || n_cached_frame || no_job_to_deq)
867     {
868       frame->state = frame->n_elts - n_deq;
869       frame->state |= ((n_success < n_deq) << 7);
870       rte_ring_sp_enqueue (cet->cached_frame, (void *) frame);
871       n_room_left--;
872     }
873   else
874     {
875       frame->state = n_success == frame->n_elts ?
876         VNET_CRYPTO_FRAME_STATE_SUCCESS : VNET_CRYPTO_FRAME_STATE_ELT_ERROR;
877       frame_ret = frame;
878     }
879
880   /* see if we can dequeue more */
881   while (inflight && n_room_left && !no_job_to_deq)
882     {
883       n_deq = rte_cryptodev_raw_dequeue_burst (cet->ctx,
884                                                cryptodev_get_frame_n_elts,
885                                                cryptodev_post_dequeue,
886                                                (void **) &frame, 0,
887                                                &n_success, &dequeue_status);
888       if (!n_deq)
889         break;
890       inflight -= n_deq;
891       no_job_to_deq = n_deq < frame->n_elts;
892       frame->state = frame->n_elts - n_deq;
893       frame->state |= ((n_success < n_deq) << 7);
894       rte_ring_sp_enqueue (cet->cached_frame, (void *) frame);
895       n_room_left--;
896     }
897
898 end_deq:
899   if (inflight < cet->inflight)
900     {
901       int res =
902         rte_cryptodev_raw_dequeue_done (cet->ctx, cet->inflight - inflight);
903       ASSERT (res == 0);
904       cet->inflight = inflight;
905     }
906
907   if (frame_ret)
908     {
909       *nb_elts_processed = frame_ret->n_elts;
910       *enqueue_thread_idx = frame_ret->enqueue_thread_index;
911     }
912
913   return frame_ret;
914 }
915
916 /* *INDENT-OFF* */
917 static_always_inline int
918 cryptodev_enqueue_gcm_aad_8_enc (vlib_main_t * vm,
919                                  vnet_crypto_async_frame_t * frame)
920 {
921   return cryptodev_frame_gcm_enqueue (vm, frame,
922                                       CRYPTODEV_OP_TYPE_ENCRYPT, 8);
923 }
924 static_always_inline int
925 cryptodev_enqueue_gcm_aad_12_enc (vlib_main_t * vm,
926                                  vnet_crypto_async_frame_t * frame)
927 {
928   return cryptodev_frame_gcm_enqueue (vm, frame,
929                                       CRYPTODEV_OP_TYPE_ENCRYPT, 12);
930 }
931
932 static_always_inline int
933 cryptodev_enqueue_gcm_aad_8_dec (vlib_main_t * vm,
934                                  vnet_crypto_async_frame_t * frame)
935 {
936   return cryptodev_frame_gcm_enqueue (vm, frame,
937                                       CRYPTODEV_OP_TYPE_DECRYPT, 8);
938 }
939 static_always_inline int
940 cryptodev_enqueue_gcm_aad_12_dec (vlib_main_t * vm,
941                                  vnet_crypto_async_frame_t * frame)
942 {
943   return cryptodev_frame_gcm_enqueue (vm, frame,
944                                       CRYPTODEV_OP_TYPE_DECRYPT, 12);
945 }
946
947 static_always_inline int
948 cryptodev_enqueue_linked_alg_enc (vlib_main_t * vm,
949                                   vnet_crypto_async_frame_t * frame)
950 {
951   return cryptodev_frame_linked_algs_enqueue (vm, frame,
952                                               CRYPTODEV_OP_TYPE_ENCRYPT);
953 }
954
955 static_always_inline int
956 cryptodev_enqueue_linked_alg_dec (vlib_main_t * vm,
957                                   vnet_crypto_async_frame_t * frame)
958 {
959   return cryptodev_frame_linked_algs_enqueue (vm, frame,
960                                               CRYPTODEV_OP_TYPE_DECRYPT);
961 }
962
963 typedef enum
964 {
965   CRYPTODEV_RESOURCE_ASSIGN_AUTO = 0,
966   CRYPTODEV_RESOURCE_ASSIGN_UPDATE,
967 } cryptodev_resource_assign_op_t;
968
969 /**
970  *  assign a cryptodev resource to a worker.
971  *  @param cet: the worker thread data
972  *  @param cryptodev_inst_index: if op is "ASSIGN_AUTO" this param is ignored.
973  *  @param op: the assignment method.
974  *  @return: 0 if successfully, negative number otherwise.
975  **/
976 static_always_inline int
977 cryptodev_assign_resource (cryptodev_engine_thread_t * cet,
978                            u32 cryptodev_inst_index,
979                            cryptodev_resource_assign_op_t op)
980 {
981   cryptodev_main_t *cmt = &cryptodev_main;
982   cryptodev_inst_t *cinst = 0;
983   uword idx;
984
985   /* assign resource is only allowed when no inflight op is in the queue */
986   if (cet->inflight)
987     return -EBUSY;
988
989   switch (op)
990     {
991     case CRYPTODEV_RESOURCE_ASSIGN_AUTO:
992       if (clib_bitmap_count_set_bits (cmt->active_cdev_inst_mask) >=
993           vec_len (cmt->cryptodev_inst))
994         return -1;
995
996       clib_spinlock_lock (&cmt->tlock);
997       idx = clib_bitmap_first_clear (cmt->active_cdev_inst_mask);
998       clib_bitmap_set (cmt->active_cdev_inst_mask, idx, 1);
999       cinst = vec_elt_at_index (cmt->cryptodev_inst, idx);
1000       cet->cryptodev_id = cinst->dev_id;
1001       cet->cryptodev_q = cinst->q_id;
1002       cet->ctx = cinst->raw_dp_ctx_buffer;
1003       clib_spinlock_unlock (&cmt->tlock);
1004       break;
1005     case CRYPTODEV_RESOURCE_ASSIGN_UPDATE:
1006       /* assigning a used cryptodev resource is not allowed */
1007       if (clib_bitmap_get (cmt->active_cdev_inst_mask, cryptodev_inst_index)
1008           == 1)
1009         return -EBUSY;
1010       vec_foreach_index (idx, cmt->cryptodev_inst)
1011       {
1012         cinst = cmt->cryptodev_inst + idx;
1013         if (cinst->dev_id == cet->cryptodev_id &&
1014             cinst->q_id == cet->cryptodev_q)
1015           break;
1016       }
1017       /* invalid existing worker resource assignment */
1018       if (idx == vec_len (cmt->cryptodev_inst))
1019         return -EINVAL;
1020       clib_spinlock_lock (&cmt->tlock);
1021       clib_bitmap_set_no_check (cmt->active_cdev_inst_mask, idx, 0);
1022       clib_bitmap_set_no_check (cmt->active_cdev_inst_mask,
1023                                 cryptodev_inst_index, 1);
1024       cinst = cmt->cryptodev_inst + cryptodev_inst_index;
1025       cet->cryptodev_id = cinst->dev_id;
1026       cet->cryptodev_q = cinst->q_id;
1027       cet->ctx = cinst->raw_dp_ctx_buffer;
1028       clib_spinlock_unlock (&cmt->tlock);
1029       break;
1030     default:
1031       return -EINVAL;
1032     }
1033   return 0;
1034 }
1035
1036 static u8 *
1037 format_cryptodev_inst (u8 * s, va_list * args)
1038 {
1039   cryptodev_main_t *cmt = &cryptodev_main;
1040   u32 inst = va_arg (*args, u32);
1041   cryptodev_inst_t *cit = cmt->cryptodev_inst + inst;
1042   u32 thread_index = 0;
1043   struct rte_cryptodev_info info;
1044
1045   rte_cryptodev_info_get (cit->dev_id, &info);
1046   s = format (s, "%-25s%-10u", info.device->name, cit->q_id);
1047
1048   vec_foreach_index (thread_index, cmt->per_thread_data)
1049   {
1050     cryptodev_engine_thread_t *cet = cmt->per_thread_data + thread_index;
1051     if (vlib_num_workers () > 0 && thread_index == 0)
1052       continue;
1053
1054     if (cet->cryptodev_id == cit->dev_id && cet->cryptodev_q == cit->q_id)
1055       {
1056         s = format (s, "%u (%v)\n", thread_index,
1057                     vlib_worker_threads[thread_index].name);
1058         break;
1059       }
1060   }
1061
1062   if (thread_index == vec_len (cmt->per_thread_data))
1063     s = format (s, "%s\n", "free");
1064
1065   return s;
1066 }
1067
1068 static clib_error_t *
1069 cryptodev_show_assignment_fn (vlib_main_t * vm, unformat_input_t * input,
1070                               vlib_cli_command_t * cmd)
1071 {
1072   cryptodev_main_t *cmt = &cryptodev_main;
1073   u32 inst;
1074
1075   vlib_cli_output (vm, "%-5s%-25s%-10s%s\n", "No.", "Name", "Queue-id",
1076                    "Assigned-to");
1077   if (vec_len (cmt->cryptodev_inst) == 0)
1078     {
1079       vlib_cli_output (vm, "(nil)\n");
1080       return 0;
1081     }
1082
1083   vec_foreach_index (inst, cmt->cryptodev_inst)
1084     vlib_cli_output (vm, "%-5u%U", inst, format_cryptodev_inst, inst);
1085
1086   return 0;
1087 }
1088
1089 VLIB_CLI_COMMAND (show_cryptodev_assignment, static) = {
1090     .path = "show cryptodev assignment",
1091     .short_help = "show cryptodev assignment",
1092     .function = cryptodev_show_assignment_fn,
1093 };
1094
1095 static clib_error_t *
1096 cryptodev_set_assignment_fn (vlib_main_t * vm, unformat_input_t * input,
1097                              vlib_cli_command_t * cmd)
1098 {
1099   cryptodev_main_t *cmt = &cryptodev_main;
1100   cryptodev_engine_thread_t *cet;
1101   unformat_input_t _line_input, *line_input = &_line_input;
1102   u32 thread_index, inst_index;
1103   u32 thread_present = 0, inst_present = 0;
1104   clib_error_t *error = 0;
1105   int ret;
1106
1107   /* Get a line of input. */
1108   if (!unformat_user (input, unformat_line_input, line_input))
1109     return 0;
1110
1111   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1112     {
1113       if (unformat (line_input, "thread %u", &thread_index))
1114         thread_present = 1;
1115       else if (unformat (line_input, "resource %u", &inst_index))
1116         inst_present = 1;
1117       else
1118         {
1119           error = clib_error_return (0, "unknown input `%U'",
1120                                      format_unformat_error, line_input);
1121           return error;
1122         }
1123     }
1124
1125   if (!thread_present || !inst_present)
1126     {
1127       error = clib_error_return (0, "mandatory argument(s) missing");
1128       return error;
1129     }
1130
1131   if (thread_index == 0 && vlib_num_workers () > 0)
1132     {
1133       error =
1134         clib_error_return (0, "assign crypto resource for master thread");
1135       return error;
1136     }
1137
1138   if (thread_index > vec_len (cmt->per_thread_data) ||
1139       inst_index > vec_len (cmt->cryptodev_inst))
1140     {
1141       error = clib_error_return (0, "wrong thread id or resource id");
1142       return error;
1143     }
1144
1145   cet = cmt->per_thread_data + thread_index;
1146   ret = cryptodev_assign_resource (cet, inst_index,
1147                                    CRYPTODEV_RESOURCE_ASSIGN_UPDATE);
1148   if (ret)
1149     {
1150       error = clib_error_return (0, "cryptodev_assign_resource returned %i",
1151                                  ret);
1152       return error;
1153     }
1154
1155   return 0;
1156 }
1157
1158 VLIB_CLI_COMMAND (set_cryptodev_assignment, static) = {
1159     .path = "set cryptodev assignment",
1160     .short_help = "set cryptodev assignment thread <thread_index> "
1161         "resource <inst_index>",
1162     .function = cryptodev_set_assignment_fn,
1163 };
1164
1165 static int
1166 check_cryptodev_alg_support (u32 dev_id)
1167 {
1168   const struct rte_cryptodev_symmetric_capability *cap;
1169   struct rte_cryptodev_sym_capability_idx cap_idx;
1170
1171 #define _(a, b, c, d, e, f) \
1172   cap_idx.type = RTE_CRYPTO_SYM_XFORM_##b; \
1173   cap_idx.algo.aead = RTE_CRYPTO_##b##_##c; \
1174   cap = rte_cryptodev_sym_capability_get (dev_id, &cap_idx); \
1175   if (!cap) \
1176     return -RTE_CRYPTO_##b##_##c; \
1177   else \
1178     { \
1179       if (cap->aead.digest_size.min > e || cap->aead.digest_size.max < e) \
1180         return -RTE_CRYPTO_##b##_##c; \
1181       if (cap->aead.aad_size.min > f || cap->aead.aad_size.max < f) \
1182         return -RTE_CRYPTO_##b##_##c; \
1183       if (cap->aead.iv_size.min > d || cap->aead.iv_size.max < d) \
1184         return -RTE_CRYPTO_##b##_##c; \
1185     }
1186
1187   foreach_vnet_aead_crypto_conversion
1188 #undef _
1189
1190 #define _(a, b, c, d) \
1191   cap_idx.type = RTE_CRYPTO_SYM_XFORM_CIPHER; \
1192   cap_idx.algo.cipher = RTE_CRYPTO_CIPHER_##b; \
1193   cap = rte_cryptodev_sym_capability_get (dev_id, &cap_idx); \
1194   if (!cap) \
1195     return -RTE_CRYPTO_CIPHER_##b; \
1196   cap_idx.type = RTE_CRYPTO_SYM_XFORM_AUTH; \
1197   cap_idx.algo.auth = RTE_CRYPTO_AUTH_##c##_HMAC; \
1198   cap = rte_cryptodev_sym_capability_get (dev_id, &cap_idx); \
1199   if (!cap) \
1200     return -RTE_CRYPTO_AUTH_##c;
1201
1202   foreach_cryptodev_link_async_alg
1203 #undef _
1204     return 0;
1205 }
1206
1207 static u32
1208 cryptodev_count_queue (u32 numa)
1209 {
1210   struct rte_cryptodev_info info;
1211   u32 n_cryptodev = rte_cryptodev_count ();
1212   u32 i, q_count = 0;
1213
1214   for (i = 0; i < n_cryptodev; i++)
1215     {
1216       rte_cryptodev_info_get (i, &info);
1217       if (rte_cryptodev_socket_id (i) != numa)
1218         {
1219           clib_warning ("DPDK crypto resource %s is in different numa node "
1220               "as %u, ignored", info.device->name, numa);
1221           continue;
1222         }
1223       q_count += info.max_nb_queue_pairs;
1224     }
1225
1226   return q_count;
1227 }
1228
1229 static int
1230 cryptodev_configure (vlib_main_t *vm, u32 cryptodev_id)
1231 {
1232   struct rte_cryptodev_info info;
1233   struct rte_cryptodev *cdev;
1234   cryptodev_main_t *cmt = &cryptodev_main;
1235   cryptodev_numa_data_t *numa_data = vec_elt_at_index (cmt->per_numa_data,
1236                                                        vm->numa_node);
1237   u32 dp_size = 0;
1238   u32 i;
1239   int ret;
1240
1241   cdev = rte_cryptodev_pmd_get_dev (cryptodev_id);
1242   rte_cryptodev_info_get (cryptodev_id, &info);
1243
1244   if (!(info.feature_flags & RTE_CRYPTODEV_FF_SYM_RAW_DP))
1245     return -1;
1246
1247   ret = check_cryptodev_alg_support (cryptodev_id);
1248   if (ret != 0)
1249     return ret;
1250
1251
1252
1253   /** If the device is already started, we reuse it, otherwise configure
1254    *  both the device and queue pair.
1255    **/
1256   if (!cdev->data->dev_started)
1257     {
1258       struct rte_cryptodev_config cfg;
1259
1260       cfg.socket_id = vm->numa_node;
1261       cfg.nb_queue_pairs = info.max_nb_queue_pairs;
1262
1263       rte_cryptodev_configure (cryptodev_id, &cfg);
1264
1265       for (i = 0; i < info.max_nb_queue_pairs; i++)
1266         {
1267           struct rte_cryptodev_qp_conf qp_cfg;
1268
1269           qp_cfg.mp_session = numa_data->sess_pool;
1270           qp_cfg.mp_session_private = numa_data->sess_priv_pool;
1271           qp_cfg.nb_descriptors = CRYPTODEV_NB_CRYPTO_OPS;
1272
1273           ret = rte_cryptodev_queue_pair_setup (cryptodev_id, i, &qp_cfg,
1274                                                 vm->numa_node);
1275           if (ret)
1276             break;
1277         }
1278       if (i != info.max_nb_queue_pairs)
1279         return -1;
1280
1281       /* start the device */
1282       rte_cryptodev_start (i);
1283     }
1284
1285   ret = rte_cryptodev_get_raw_dp_ctx_size (cryptodev_id);
1286   if (ret < 0)
1287     return -1;
1288   dp_size = ret;
1289
1290   for (i = 0; i < info.max_nb_queue_pairs; i++)
1291     {
1292       cryptodev_inst_t *cdev_inst;
1293       vec_add2(cmt->cryptodev_inst, cdev_inst, 1);
1294       cdev_inst->desc = vec_new (char, strlen (info.device->name) + 10);
1295       cdev_inst->dev_id = cryptodev_id;
1296       cdev_inst->q_id = i;
1297       vec_validate_aligned (cdev_inst->raw_dp_ctx_buffer, dp_size, 8);
1298       cryptodev_reset_ctx (cdev_inst->dev_id, cdev_inst->q_id,
1299                            cdev_inst->raw_dp_ctx_buffer);
1300
1301       snprintf (cdev_inst->desc, strlen (info.device->name) + 9,
1302                 "%s_q%u", info.device->name, i);
1303     }
1304
1305   return 0;
1306 }
1307
1308 static int
1309 cryptodev_cmp (void *v1, void *v2)
1310 {
1311   cryptodev_inst_t *a1 = v1;
1312   cryptodev_inst_t *a2 = v2;
1313
1314   if (a1->q_id > a2->q_id)
1315     return 1;
1316   if (a1->q_id < a2->q_id)
1317     return -1;
1318   return 0;
1319 }
1320
1321 static int
1322 cryptodev_probe (vlib_main_t *vm, u32 n_workers)
1323 {
1324   cryptodev_main_t *cmt = &cryptodev_main;
1325   u32 n_queues = cryptodev_count_queue (vm->numa_node);
1326   u32 i;
1327   int ret;
1328
1329   if (n_queues < n_workers)
1330     return -1;
1331
1332   for (i = 0; i < rte_cryptodev_count (); i++)
1333     {
1334       ret = cryptodev_configure (vm, i);
1335       if (ret)
1336         continue;
1337     }
1338
1339   vec_sort_with_function(cmt->cryptodev_inst, cryptodev_cmp);
1340
1341   /* if there is not enough device stop cryptodev */
1342   if (vec_len (cmt->cryptodev_inst) < n_workers)
1343     return -1;
1344
1345   return 0;
1346 }
1347
1348 static int
1349 cryptodev_get_session_sz (vlib_main_t *vm, u32 n_workers)
1350 {
1351   u32 sess_data_sz = 0, i;
1352
1353   if (rte_cryptodev_count () == 0)
1354     return -1;
1355
1356   for (i = 0; i < rte_cryptodev_count (); i++)
1357     {
1358       u32 dev_sess_sz = rte_cryptodev_sym_get_private_session_size (i);
1359
1360       sess_data_sz = dev_sess_sz > sess_data_sz ? dev_sess_sz : sess_data_sz;
1361     }
1362
1363   return sess_data_sz;
1364 }
1365
1366 static void
1367 dpdk_disable_cryptodev_engine (vlib_main_t * vm)
1368 {
1369   cryptodev_main_t *cmt = &cryptodev_main;
1370   cryptodev_numa_data_t *numa_data;
1371   cryptodev_engine_thread_t *ptd;
1372
1373   vec_validate (cmt->per_numa_data, vm->numa_node);
1374   numa_data = vec_elt_at_index (cmt->per_numa_data, vm->numa_node);
1375
1376   if (numa_data->sess_pool)
1377     rte_mempool_free (numa_data->sess_pool);
1378   if (numa_data->sess_priv_pool)
1379     rte_mempool_free (numa_data->sess_priv_pool);
1380
1381   vec_foreach (ptd, cmt->per_thread_data)
1382     {
1383       if (ptd->aad_buf)
1384         rte_free (ptd->aad_buf);
1385       if (ptd->cached_frame)
1386         rte_ring_free (ptd->cached_frame);
1387     }
1388 }
1389
1390 clib_error_t *
1391 dpdk_cryptodev_init (vlib_main_t * vm)
1392 {
1393   cryptodev_main_t *cmt = &cryptodev_main;
1394   vlib_thread_main_t *tm = vlib_get_thread_main ();
1395   cryptodev_engine_thread_t *ptd;
1396   cryptodev_numa_data_t *numa_data;
1397   struct rte_mempool *mp;
1398   u32 skip_master = vlib_num_workers () > 0;
1399   u32 n_workers = tm->n_vlib_mains - skip_master;
1400   u32 numa = vm->numa_node;
1401   i32 sess_sz;
1402   u32 eidx;
1403   u32 i;
1404   u8 *name = 0;
1405   clib_error_t *error;
1406
1407   cmt->iova_mode = rte_eal_iova_mode ();
1408
1409   sess_sz = cryptodev_get_session_sz(vm, n_workers);
1410   if (sess_sz < 0)
1411     {
1412       error = clib_error_return (0, "Not enough cryptodevs");
1413       return error;
1414     }
1415
1416   vec_validate (cmt->per_numa_data, vm->numa_node);
1417   numa_data = vec_elt_at_index (cmt->per_numa_data, numa);
1418
1419   /* create session pool for the numa node */
1420   name = format (0, "vcryptodev_sess_pool_%u%c", numa, 0);
1421   mp = rte_cryptodev_sym_session_pool_create ((char *) name,
1422                                               CRYPTODEV_NB_SESSION,
1423                                               0, 0, 0, numa);
1424   if (!mp)
1425     {
1426       error = clib_error_return (0, "Not enough memory for mp %s", name);
1427       goto err_handling;
1428     }
1429   vec_free (name);
1430
1431   numa_data->sess_pool = mp;
1432
1433   /* create session private pool for the numa node */
1434   name = format (0, "cryptodev_sess_pool_%u%c", numa, 0);
1435   mp = rte_mempool_create ((char *) name, CRYPTODEV_NB_SESSION, sess_sz, 0,
1436                            0, NULL, NULL, NULL, NULL, numa, 0);
1437   if (!mp)
1438     {
1439       error = clib_error_return (0, "Not enough memory for mp %s", name);
1440       vec_free (name);
1441       goto err_handling;
1442     }
1443
1444   vec_free (name);
1445
1446   numa_data->sess_priv_pool = mp;
1447
1448   /* probe all cryptodev devices and get queue info */
1449   if (cryptodev_probe (vm, n_workers) < 0)
1450     {
1451       error = clib_error_return (0, "Failed to configure cryptodev");
1452       goto err_handling;
1453     }
1454
1455   clib_bitmap_vec_validate (cmt->active_cdev_inst_mask, tm->n_vlib_mains);
1456   clib_spinlock_init (&cmt->tlock);
1457
1458   vec_validate_aligned(cmt->per_thread_data, tm->n_vlib_mains - 1,
1459                        CLIB_CACHE_LINE_BYTES);
1460   for (i = skip_master; i < tm->n_vlib_mains; i++)
1461     {
1462       ptd = cmt->per_thread_data + i;
1463       cryptodev_assign_resource (ptd, 0, CRYPTODEV_RESOURCE_ASSIGN_AUTO);
1464       ptd->aad_buf = rte_zmalloc_socket (0, CRYPTODEV_NB_CRYPTO_OPS *
1465                                          CRYPTODEV_MAX_AAD_SIZE,
1466                                          CLIB_CACHE_LINE_BYTES,
1467                                          numa);
1468       if (ptd->aad_buf == 0)
1469         {
1470           error = clib_error_return (0, "Failed to alloc aad buf");
1471           goto err_handling;
1472         }
1473
1474       ptd->aad_phy_addr = rte_malloc_virt2iova (ptd->aad_buf);
1475
1476       name = format (0, "cache_frame_ring_%u%u", numa, i);
1477       ptd->cached_frame = rte_ring_create ((char *)name,
1478                                            CRYPTODEV_DEQ_CACHE_SZ, numa,
1479                                            RING_F_SC_DEQ | RING_F_SP_ENQ);
1480
1481       if (ptd->cached_frame == 0)
1482         {
1483           error = clib_error_return (0, "Failed to frame ring");
1484           goto err_handling;
1485         }
1486       vec_free (name);
1487     }
1488
1489   /* register handler */
1490   eidx = vnet_crypto_register_engine (vm, "dpdk_cryptodev", 79,
1491                                       "DPDK Cryptodev Engine");
1492
1493 #define _(a, b, c, d, e, f) \
1494   vnet_crypto_register_async_handler \
1495     (vm, eidx, VNET_CRYPTO_OP_##a##_TAG##e##_AAD##f##_ENC, \
1496         cryptodev_enqueue_gcm_aad_##f##_enc,\
1497         cryptodev_frame_dequeue); \
1498   vnet_crypto_register_async_handler \
1499     (vm, eidx, VNET_CRYPTO_OP_##a##_TAG##e##_AAD##f##_DEC, \
1500         cryptodev_enqueue_gcm_aad_##f##_dec, \
1501         cryptodev_frame_dequeue);
1502
1503   foreach_vnet_aead_crypto_conversion
1504 #undef _
1505
1506 #define _(a, b, c, d) \
1507   vnet_crypto_register_async_handler \
1508     (vm, eidx, VNET_CRYPTO_OP_##a##_##c##_TAG##d##_ENC, \
1509         cryptodev_enqueue_linked_alg_enc, \
1510         cryptodev_frame_dequeue); \
1511   vnet_crypto_register_async_handler \
1512     (vm, eidx, VNET_CRYPTO_OP_##a##_##c##_TAG##d##_DEC, \
1513         cryptodev_enqueue_linked_alg_dec, \
1514         cryptodev_frame_dequeue);
1515
1516     foreach_cryptodev_link_async_alg
1517 #undef _
1518
1519   vnet_crypto_register_key_handler (vm, eidx, cryptodev_key_handler);
1520
1521   return 0;
1522
1523 err_handling:
1524   dpdk_disable_cryptodev_engine (vm);
1525
1526   return error;
1527 }
1528 /* *INDENT-On* */
1529
1530 /*
1531  * fd.io coding-style-patch-verification: ON
1532  *
1533  * Local Variables:
1534  * eval: (c-set-style "gnu")
1535  * End:
1536  */