xref: /spdk/module/bdev/crypto/vbdev_crypto.c (revision 6b6dfea6c704a049e553024aa7e44ae916948e20)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUcryptoION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "vbdev_crypto.h"
35 
36 #include "spdk/env.h"
37 #include "spdk/conf.h"
38 #include "spdk/endian.h"
39 #include "spdk/io_channel.h"
40 #include "spdk/bdev_module.h"
41 #include "spdk_internal/log.h"
42 
43 #include <rte_config.h>
44 #include <rte_version.h>
45 #include <rte_bus_vdev.h>
46 #include <rte_crypto.h>
47 #include <rte_cryptodev.h>
48 #include <rte_cryptodev_pmd.h>
49 
50 /* To add support for new device types, follow the examples of the following...
51  * Note that the string names are defined by the DPDK PMD in question so be
52  * sure to use the exact names.
53  */
54 #define MAX_NUM_DRV_TYPES 2
55 #define AESNI_MB "crypto_aesni_mb"
56 #define QAT "crypto_qat"
57 const char *g_driver_names[MAX_NUM_DRV_TYPES] = { AESNI_MB, QAT };
58 
59 /* Global list of available crypto devices. */
60 struct vbdev_dev {
61 	struct rte_cryptodev_info	cdev_info;	/* includes device friendly name */
62 	uint8_t				cdev_id;	/* identifier for the device */
63 	TAILQ_ENTRY(vbdev_dev)		link;
64 };
65 static TAILQ_HEAD(, vbdev_dev) g_vbdev_devs = TAILQ_HEAD_INITIALIZER(g_vbdev_devs);
66 
67 /* Global list and lock for unique device/queue pair combos */
68 struct device_qp {
69 	struct vbdev_dev		*device;	/* ptr to crypto device */
70 	uint8_t				qp;		/* queue pair for this node */
71 	bool				in_use;		/* whether this node is in use or not */
72 	TAILQ_ENTRY(device_qp)		link;
73 };
74 static TAILQ_HEAD(, device_qp) g_device_qp = TAILQ_HEAD_INITIALIZER(g_device_qp);
75 static pthread_mutex_t g_device_qp_lock = PTHREAD_MUTEX_INITIALIZER;
76 
77 
78 /* In order to limit the number of resources we need to do one crypto
79  * operation per LBA (we use LBA as IV), we tell the bdev layer that
80  * our max IO size is something reasonable. Units here are in bytes.
81  */
82 #define CRYPTO_MAX_IO		(64 * 1024)
83 
84 /* This controls how many ops will be dequeued from the crypto driver in one run
85  * of the poller. It is mainly a performance knob as it effectively determines how
86  * much work the poller has to do.  However even that can vary between crypto drivers
87  * as the AESNI_MB driver for example does all the crypto work on dequeue whereas the
88  * QAT drvier just dequeues what has been completed already.
89  */
90 #define MAX_DEQUEUE_BURST_SIZE	64
91 
92 /* When enqueueing, we need to supply the crypto driver with an array of pointers to
93  * operation structs. As each of these can be max 512B, we can adjust the CRYPTO_MAX_IO
94  * value in conjunction with the the other defines to make sure we're not using crazy amounts
95  * of memory. All of these numbers can and probably should be adjusted based on the
96  * workload. By default we'll use the worst case (smallest) block size for the
97  * minimum number of array entries. As an example, a CRYPTO_MAX_IO size of 64K with 512B
98  * blocks would give us an enqueue array size of 128.
99  */
100 #define MAX_ENQUEUE_ARRAY_SIZE (CRYPTO_MAX_IO / 512)
101 
102 /* The number of MBUFS we need must be a power of two and to support other small IOs
103  * in addition to the limits mentioned above, we go to the next power of two. It is
104  * big number because it is one mempool for source and desitnation mbufs. It may
105  * need to be bigger to support multiple crypto drivers at once.
106  */
107 #define NUM_MBUFS		32768
108 #define POOL_CACHE_SIZE		256
109 #define NUM_SESSIONS		1024
110 #define SESS_MEMPOOL_CACHE_SIZE 256
111 
112 /* This is the max number of IOs we can supply to any crypto device QP at one time.
113  * It can vary between drivers.
114  */
115 #define CRYPTO_QP_DESCRIPTORS	2048
116 
117 /* Specific to AES_CBC. */
118 #define AES_CBC_IV_LENGTH	16
119 #define AES_CBC_KEY_LENGTH	16
120 
121 /* Common for suported devices. */
122 #define IV_OFFSET            (sizeof(struct rte_crypto_op) + \
123 				sizeof(struct rte_crypto_sym_op))
124 
125 static void _complete_internal_io(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
126 static void _complete_internal_read(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
127 static void _complete_internal_write(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg);
128 static void vbdev_crypto_examine(struct spdk_bdev *bdev);
129 static int vbdev_crypto_claim(struct spdk_bdev *bdev);
130 static void vbdev_crypto_submit_request(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io);
131 
132 /* list of crypto_bdev names and their base bdevs via configuration file.
133  * Used so we can parse the conf once at init and use this list in examine().
134  */
135 struct bdev_names {
136 	char			*vbdev_name;	/* name of the vbdev to create */
137 	char			*bdev_name;	/* base bdev name */
138 
139 	/* Note, for dev/test we allow use of key in the config file, for production
140 	 * use, you must use an RPC to specify the key for security reasons.
141 	 */
142 	uint8_t			*key;		/* key per bdev */
143 	char			*drv_name;	/* name of the crypto device driver */
144 	TAILQ_ENTRY(bdev_names)	link;
145 };
146 static TAILQ_HEAD(, bdev_names) g_bdev_names = TAILQ_HEAD_INITIALIZER(g_bdev_names);
147 
148 /* List of virtual bdevs and associated info for each. We keep the device friendly name here even
149  * though its also in the device struct because we use it early on.
150  */
151 struct vbdev_crypto {
152 	struct spdk_bdev		*base_bdev;		/* the thing we're attaching to */
153 	struct spdk_bdev_desc		*base_desc;		/* its descriptor we get from open */
154 	struct spdk_bdev		crypto_bdev;		/* the crypto virtual bdev */
155 	uint8_t				*key;			/* key per bdev */
156 	char				*drv_name;		/* name of the crypto device driver */
157 	struct rte_cryptodev_sym_session *session_encrypt;	/* encryption session for this bdev */
158 	struct rte_cryptodev_sym_session *session_decrypt;	/* decryption session for this bdev */
159 	struct rte_crypto_sym_xform	cipher_xform;		/* crypto control struct for this bdev */
160 	TAILQ_ENTRY(vbdev_crypto)	link;
161 };
162 static TAILQ_HEAD(, vbdev_crypto) g_vbdev_crypto = TAILQ_HEAD_INITIALIZER(g_vbdev_crypto);
163 
164 /* Shared mempools between all devices on this system */
165 static struct rte_mempool *g_session_mp = NULL;
166 static struct rte_mempool *g_session_mp_priv = NULL;
167 static struct spdk_mempool *g_mbuf_mp = NULL;		/* mbuf mempool */
168 static struct rte_mempool *g_crypto_op_mp = NULL;	/* crypto operations, must be rte* mempool */
169 
170 /* The crypto vbdev channel struct. It is allocated and freed on my behalf by the io channel code.
171  * We store things in here that are needed on per thread basis like the base_channel for this thread,
172  * and the poller for this thread.
173  */
174 struct crypto_io_channel {
175 	struct spdk_io_channel		*base_ch;		/* IO channel of base device */
176 	struct spdk_poller		*poller;		/* completion poller */
177 	struct device_qp		*device_qp;		/* unique device/qp combination for this channel */
178 	TAILQ_HEAD(, spdk_bdev_io)	pending_cry_ios;	/* outstanding operations to the crypto device */
179 	struct spdk_io_channel_iter	*iter;			/* used with for_each_channel in reset */
180 };
181 
182 /* This is the crypto per IO context that the bdev layer allocates for us opaquely and attaches to
183  * each IO for us.
184  */
185 struct crypto_bdev_io {
186 	int cryop_cnt_remaining;			/* counter used when completing crypto ops */
187 	struct crypto_io_channel *crypto_ch;		/* need to store for crypto completion handling */
188 	struct vbdev_crypto *crypto_bdev;		/* the crypto node struct associated with this IO */
189 	struct spdk_bdev_io *orig_io;			/* the original IO */
190 	struct spdk_bdev_io *read_io;			/* the read IO we issued */
191 
192 	/* Used for the single contigous buffer that serves as the crypto destination target for writes */
193 	uint64_t cry_num_blocks;			/* num of blocks for the contiguous buffer */
194 	uint64_t cry_offset_blocks;			/* block offset on media */
195 	struct iovec cry_iov;				/* iov representing contig write buffer */
196 
197 	/* for bdev_io_wait */
198 	struct spdk_bdev_io_wait_entry bdev_io_wait;
199 	struct spdk_io_channel *ch;
200 };
201 
202 /* Called by vbdev_crypto_init_crypto_drivers() to init each discovered crypto device */
203 static int
204 create_vbdev_dev(uint8_t index, uint16_t num_lcores)
205 {
206 	struct vbdev_dev *device;
207 	uint8_t j, cdev_id, cdrv_id;
208 	struct device_qp *dev_qp;
209 	struct device_qp *tmp_qp;
210 	int rc;
211 
212 	device = calloc(1, sizeof(struct vbdev_dev));
213 	if (!device) {
214 		return -ENOMEM;
215 	}
216 
217 	/* Get details about this device. */
218 	rte_cryptodev_info_get(index, &device->cdev_info);
219 	cdrv_id = device->cdev_info.driver_id;
220 	cdev_id = device->cdev_id = index;
221 
222 	/* Before going any further, make sure we have enough resources for this
223 	 * device type to function.  We need a unique queue pair per core accross each
224 	 * device type to remain lockless....
225 	 */
226 	if ((rte_cryptodev_device_count_by_driver(cdrv_id) *
227 	     device->cdev_info.max_nb_queue_pairs) < num_lcores) {
228 		SPDK_ERRLOG("Insufficient unique queue pairs available for %s\n",
229 			    device->cdev_info.driver_name);
230 		SPDK_ERRLOG("Either add more crypto devices or decrease core count\n");
231 		rc = -EINVAL;
232 		goto err;
233 	}
234 
235 	/* Setup queue pairs. */
236 	struct rte_cryptodev_config conf = {
237 		.nb_queue_pairs = device->cdev_info.max_nb_queue_pairs,
238 		.socket_id = SPDK_ENV_SOCKET_ID_ANY
239 	};
240 
241 	rc = rte_cryptodev_configure(cdev_id, &conf);
242 	if (rc < 0) {
243 		SPDK_ERRLOG("Failed to configure cryptodev %u\n", cdev_id);
244 		rc = -EINVAL;
245 		goto err;
246 	}
247 
248 	struct rte_cryptodev_qp_conf qp_conf = {
249 		.nb_descriptors = CRYPTO_QP_DESCRIPTORS,
250 #if RTE_VERSION >= RTE_VERSION_NUM(19, 02, 0, 0)
251 		.mp_session = g_session_mp,
252 		.mp_session_private = g_session_mp_priv,
253 #endif
254 	};
255 
256 	/* Pre-setup all pottential qpairs now and assign them in the channel
257 	 * callback. If we were to create them there, we'd have to stop the
258 	 * entire device affecting all other threads that might be using it
259 	 * even on other queue pairs.
260 	 */
261 	for (j = 0; j < device->cdev_info.max_nb_queue_pairs; j++) {
262 #if RTE_VERSION >= RTE_VERSION_NUM(19, 02, 0, 0)
263 		rc = rte_cryptodev_queue_pair_setup(cdev_id, j, &qp_conf, SOCKET_ID_ANY);
264 #else
265 		rc = rte_cryptodev_queue_pair_setup(cdev_id, j, &qp_conf, SOCKET_ID_ANY,
266 						    g_session_mp);
267 #endif
268 
269 		if (rc < 0) {
270 			SPDK_ERRLOG("Failed to setup queue pair %u on "
271 				    "cryptodev %u\n", j, cdev_id);
272 			rc = -EINVAL;
273 			goto err;
274 		}
275 	}
276 
277 	rc = rte_cryptodev_start(cdev_id);
278 	if (rc < 0) {
279 		SPDK_ERRLOG("Failed to start device %u: error %d\n",
280 			    cdev_id, rc);
281 		rc = -EINVAL;
282 		goto err;
283 	}
284 
285 	/* Build up list of device/qp combinations */
286 	for (j = 0; j < device->cdev_info.max_nb_queue_pairs; j++) {
287 		dev_qp = calloc(1, sizeof(struct device_qp));
288 		if (!dev_qp) {
289 			rc = -ENOMEM;
290 			goto err;
291 		}
292 		dev_qp->device = device;
293 		dev_qp->qp = j;
294 		dev_qp->in_use = false;
295 		TAILQ_INSERT_TAIL(&g_device_qp, dev_qp, link);
296 	}
297 
298 	/* Add to our list of available crypto devices. */
299 	TAILQ_INSERT_TAIL(&g_vbdev_devs, device, link);
300 
301 	return 0;
302 err:
303 	TAILQ_FOREACH_SAFE(dev_qp, &g_device_qp, link, tmp_qp) {
304 		TAILQ_REMOVE(&g_device_qp, dev_qp, link);
305 		free(dev_qp);
306 	}
307 	free(device);
308 
309 	return rc;
310 
311 }
312 
313 /* This is called from the module's init function. We setup all crypto devices early on as we are unable
314  * to easily dynamically configure queue pairs after the drivers are up and running.  So, here, we
315  * configure the max capabilities of each device and assign threads to queue pairs as channels are
316  * requested.
317  */
318 static int
319 vbdev_crypto_init_crypto_drivers(void)
320 {
321 	uint8_t cdev_count;
322 	uint8_t cdev_id, i;
323 	int rc = 0;
324 	struct vbdev_dev *device;
325 	struct vbdev_dev *tmp_dev;
326 	unsigned int max_sess_size = 0, sess_size;
327 	uint16_t num_lcores = rte_lcore_count();
328 	uint32_t cache_size;
329 
330 	/* Only the first call, via RPC or module init should init the crypto drivers. */
331 	if (g_session_mp != NULL) {
332 		return 0;
333 	}
334 
335 	/* We always init AESNI_MB */
336 	rc = rte_vdev_init(AESNI_MB, NULL);
337 	if (rc) {
338 		SPDK_ERRLOG("error creating virtual PMD %s\n", AESNI_MB);
339 		return -EINVAL;
340 	}
341 
342 	/* If we have no crypto devices, there's no reason to continue. */
343 	cdev_count = rte_cryptodev_count();
344 	if (cdev_count == 0) {
345 		return 0;
346 	}
347 
348 	/*
349 	 * Create global mempools, shared by all devices regardless of type.
350 	 */
351 
352 	/* First determine max session size, most pools are shared by all the devices,
353 	 * so we need to find the global max sessions size.
354 	 */
355 	for (cdev_id = 0; cdev_id < cdev_count; cdev_id++) {
356 		sess_size = rte_cryptodev_sym_get_private_session_size(cdev_id);
357 		if (sess_size > max_sess_size) {
358 			max_sess_size = sess_size;
359 		}
360 	}
361 
362 	cache_size = spdk_min(RTE_MEMPOOL_CACHE_MAX_SIZE, NUM_SESSIONS / 2 / num_lcores);
363 #if RTE_VERSION >= RTE_VERSION_NUM(19, 02, 0, 0)
364 	g_session_mp_priv = rte_mempool_create("session_mp_priv", NUM_SESSIONS, max_sess_size, cache_size,
365 					       0, NULL, NULL, NULL, NULL, SOCKET_ID_ANY, 0);
366 	if (g_session_mp_priv == NULL) {
367 		SPDK_ERRLOG("Cannot create private session pool max size 0x%x\n", max_sess_size);
368 		return -ENOMEM;
369 	}
370 
371 	g_session_mp = rte_cryptodev_sym_session_pool_create(
372 			       "session_mp",
373 			       NUM_SESSIONS, 0, cache_size, 0,
374 			       SOCKET_ID_ANY);
375 #else
376 	g_session_mp = rte_mempool_create("session_mp", NUM_SESSIONS, max_sess_size, cache_size,
377 					  0, NULL, NULL, NULL, NULL, SOCKET_ID_ANY, 0);
378 #endif
379 	if (g_session_mp == NULL) {
380 		SPDK_ERRLOG("Cannot create session pool max size 0x%x\n", max_sess_size);
381 		goto error_create_session_mp;
382 		return -ENOMEM;
383 	}
384 
385 	g_mbuf_mp = spdk_mempool_create("mbuf_mp", NUM_MBUFS, sizeof(struct rte_mbuf),
386 					SPDK_MEMPOOL_DEFAULT_CACHE_SIZE,
387 					SPDK_ENV_SOCKET_ID_ANY);
388 	if (g_mbuf_mp == NULL) {
389 		SPDK_ERRLOG("Cannot create mbuf pool\n");
390 		rc = -ENOMEM;
391 		goto error_create_mbuf;
392 	}
393 
394 	g_crypto_op_mp = rte_crypto_op_pool_create("op_mp",
395 			 RTE_CRYPTO_OP_TYPE_SYMMETRIC,
396 			 NUM_MBUFS,
397 			 POOL_CACHE_SIZE,
398 			 AES_CBC_IV_LENGTH,
399 			 rte_socket_id());
400 	if (g_crypto_op_mp == NULL) {
401 		SPDK_ERRLOG("Cannot create op pool\n");
402 		rc = -ENOMEM;
403 		goto error_create_op;
404 	}
405 
406 	/* Init all devices */
407 	for (i = 0; i < cdev_count; i++) {
408 		rc = create_vbdev_dev(i, num_lcores);
409 		if (rc) {
410 			goto err;
411 		}
412 	}
413 	return 0;
414 
415 	/* Error cleanup paths. */
416 err:
417 	TAILQ_FOREACH_SAFE(device, &g_vbdev_devs, link, tmp_dev) {
418 		TAILQ_REMOVE(&g_vbdev_devs, device, link);
419 		free(device);
420 	}
421 	rte_mempool_free(g_crypto_op_mp);
422 	g_crypto_op_mp = NULL;
423 error_create_op:
424 	spdk_mempool_free(g_mbuf_mp);
425 	g_mbuf_mp = NULL;
426 error_create_mbuf:
427 	rte_mempool_free(g_session_mp);
428 	g_session_mp = NULL;
429 error_create_session_mp:
430 	if (g_session_mp_priv != NULL) {
431 		rte_mempool_free(g_session_mp_priv);
432 		g_session_mp_priv = NULL;
433 	}
434 	return rc;
435 }
436 
437 /* Following an encrypt or decrypt we need to then either write the encrypted data or finish
438  * the read on decrypted data. Do that here.
439  */
440 static void
441 _crypto_operation_complete(struct spdk_bdev_io *bdev_io)
442 {
443 	struct vbdev_crypto *crypto_bdev = SPDK_CONTAINEROF(bdev_io->bdev, struct vbdev_crypto,
444 					   crypto_bdev);
445 	struct crypto_bdev_io *io_ctx = (struct crypto_bdev_io *)bdev_io->driver_ctx;
446 	struct crypto_io_channel *crypto_ch = io_ctx->crypto_ch;
447 	struct spdk_bdev_io *free_me = io_ctx->read_io;
448 	int rc = 0;
449 
450 	TAILQ_REMOVE(&crypto_ch->pending_cry_ios, bdev_io, module_link);
451 
452 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_READ) {
453 
454 		/* Complete the original IO and then free the one that we created
455 		 * as a result of issuing an IO via submit_reqeust.
456 		 */
457 		if (bdev_io->internal.status != SPDK_BDEV_IO_STATUS_FAILED) {
458 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_SUCCESS);
459 		} else {
460 			SPDK_ERRLOG("Issue with decryption on bdev_io %p\n", bdev_io);
461 			rc = -EINVAL;
462 		}
463 		spdk_bdev_free_io(free_me);
464 
465 	} else if (bdev_io->type == SPDK_BDEV_IO_TYPE_WRITE) {
466 
467 		if (bdev_io->internal.status != SPDK_BDEV_IO_STATUS_FAILED) {
468 			/* Write the encrypted data. */
469 			rc = spdk_bdev_writev_blocks(crypto_bdev->base_desc, crypto_ch->base_ch,
470 						     &io_ctx->cry_iov, 1, io_ctx->cry_offset_blocks,
471 						     io_ctx->cry_num_blocks, _complete_internal_write,
472 						     bdev_io);
473 		} else {
474 			SPDK_ERRLOG("Issue with encryption on bdev_io %p\n", bdev_io);
475 			rc = -EINVAL;
476 		}
477 
478 	} else {
479 		SPDK_ERRLOG("Unknown bdev type %u on crypto operation completion\n",
480 			    bdev_io->type);
481 		rc = -EINVAL;
482 	}
483 
484 	if (rc) {
485 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
486 	}
487 }
488 
489 /* This is the poller for the crypto device. It uses a single API to dequeue whatever is ready at
490  * the device. Then we need to decide if what we've got so far (including previous poller
491  * runs) totals up to one or more complete bdev_ios and if so continue with the bdev_io
492  * accordingly. This means either completing a read or issuing a new write.
493  */
494 static int
495 crypto_dev_poller(void *args)
496 {
497 	struct crypto_io_channel *crypto_ch = args;
498 	uint8_t cdev_id = crypto_ch->device_qp->device->cdev_id;
499 	int i, num_dequeued_ops;
500 	struct spdk_bdev_io *bdev_io = NULL;
501 	struct crypto_bdev_io *io_ctx = NULL;
502 	struct rte_crypto_op *dequeued_ops[MAX_DEQUEUE_BURST_SIZE];
503 	struct rte_crypto_op *mbufs_to_free[2 * MAX_DEQUEUE_BURST_SIZE];
504 	int num_mbufs = 0;
505 
506 	/* Each run of the poller will get just what the device has available
507 	 * at the moment we call it, we don't check again after draining the
508 	 * first batch.
509 	 */
510 	num_dequeued_ops = rte_cryptodev_dequeue_burst(cdev_id, crypto_ch->device_qp->qp,
511 			   dequeued_ops, MAX_DEQUEUE_BURST_SIZE);
512 
513 	/* Check if operation was processed successfully */
514 	for (i = 0; i < num_dequeued_ops; i++) {
515 
516 		/* We don't know the order or association of the crypto ops wrt any
517 		 * partiular bdev_io so need to look at each and determine if it's
518 		 * the last one for it's bdev_io or not.
519 		 */
520 		bdev_io = (struct spdk_bdev_io *)dequeued_ops[i]->sym->m_src->userdata;
521 		assert(bdev_io != NULL);
522 
523 		if (dequeued_ops[i]->status != RTE_CRYPTO_OP_STATUS_SUCCESS) {
524 			SPDK_ERRLOG("error with op %d status %u\n", i,
525 				    dequeued_ops[i]->status);
526 			/* Update the bdev status to error, we'll still process the
527 			 * rest of the crypto ops for this bdev_io though so they
528 			 * aren't left hanging.
529 			 */
530 			bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
531 		}
532 
533 		io_ctx = (struct crypto_bdev_io *)bdev_io->driver_ctx;
534 		assert(io_ctx->cryop_cnt_remaining > 0);
535 
536 		/* Return the associated src and dst mbufs by collecting them into
537 		 * an array that we can use the bulk API to free after the loop.
538 		 */
539 		dequeued_ops[i]->sym->m_src->userdata = NULL;
540 		mbufs_to_free[num_mbufs++] = (void *)dequeued_ops[i]->sym->m_src;
541 		if (dequeued_ops[i]->sym->m_dst) {
542 			mbufs_to_free[num_mbufs++] = (void *)dequeued_ops[i]->sym->m_dst;
543 		}
544 
545 		/* done encrypting, complete the bdev_io */
546 		if (--io_ctx->cryop_cnt_remaining == 0) {
547 
548 			/* If we're completing this with an outstanding reset we need
549 			 * to fail it.
550 			 */
551 			if (crypto_ch->iter) {
552 				bdev_io->internal.status = SPDK_BDEV_IO_STATUS_FAILED;
553 			}
554 
555 			/* Complete the IO */
556 			_crypto_operation_complete(bdev_io);
557 		}
558 	}
559 
560 	/* Now bulk free both mbufs and crypto operations. */
561 	if (num_dequeued_ops > 0) {
562 		rte_mempool_put_bulk(g_crypto_op_mp,
563 				     (void **)dequeued_ops,
564 				     num_dequeued_ops);
565 		assert(num_mbufs > 0);
566 		spdk_mempool_put_bulk(g_mbuf_mp,
567 				      (void **)mbufs_to_free,
568 				      num_mbufs);
569 	}
570 
571 	/* If the channel iter is not NULL, we need to continue to poll
572 	 * until the pending list is empty, then we can move on to the
573 	 * next channel.
574 	 */
575 	if (crypto_ch->iter && TAILQ_EMPTY(&crypto_ch->pending_cry_ios)) {
576 		SPDK_NOTICELOG("Channel %p has been quiesced.\n", crypto_ch);
577 		spdk_for_each_channel_continue(crypto_ch->iter, 0);
578 		crypto_ch->iter = NULL;
579 	}
580 
581 	return num_dequeued_ops;
582 }
583 
584 /* We're either encrypting on the way down or decrypting on the way back. */
585 static int
586 _crypto_operation(struct spdk_bdev_io *bdev_io, enum rte_crypto_cipher_operation crypto_op)
587 {
588 	uint16_t num_enqueued_ops = 0;
589 	uint32_t cryop_cnt = bdev_io->u.bdev.num_blocks;
590 	struct crypto_bdev_io *io_ctx = (struct crypto_bdev_io *)bdev_io->driver_ctx;
591 	struct crypto_io_channel *crypto_ch = io_ctx->crypto_ch;
592 	uint8_t cdev_id = crypto_ch->device_qp->device->cdev_id;
593 	uint32_t crypto_len = io_ctx->crypto_bdev->crypto_bdev.blocklen;
594 	uint64_t total_length = bdev_io->u.bdev.num_blocks * crypto_len;
595 	int rc;
596 	uint32_t enqueued = 0;
597 	uint32_t iov_index = 0;
598 	uint32_t allocated = 0;
599 	uint8_t *current_iov = NULL;
600 	uint64_t total_remaining = 0;
601 	uint64_t updated_length, current_iov_remaining = 0;
602 	int completed = 0;
603 	int crypto_index = 0;
604 	uint32_t en_offset = 0;
605 	struct rte_crypto_op *crypto_ops[MAX_ENQUEUE_ARRAY_SIZE];
606 	struct rte_mbuf *src_mbufs[MAX_ENQUEUE_ARRAY_SIZE];
607 	struct rte_mbuf *dst_mbufs[MAX_ENQUEUE_ARRAY_SIZE];
608 	int burst;
609 
610 	assert((bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen) <= CRYPTO_MAX_IO);
611 
612 	/* Get the number of source mbufs that we need. These will always be 1:1 because we
613 	 * don't support chaining. The reason we don't is because of our decision to use
614 	 * LBA as IV, there can be no case where we'd need >1 mbuf per crypto op or the
615 	 * op would be > 1 LBA.
616 	 */
617 	rc = spdk_mempool_get_bulk(g_mbuf_mp, (void **)&src_mbufs[0], cryop_cnt);
618 	if (rc) {
619 		SPDK_ERRLOG("ERROR trying to get src_mbufs!\n");
620 		return -ENOMEM;
621 	}
622 
623 	/* Get the same amount but these buffers to describe the encrypted data location (dst). */
624 	if (crypto_op == RTE_CRYPTO_CIPHER_OP_ENCRYPT) {
625 		rc = spdk_mempool_get_bulk(g_mbuf_mp, (void **)&dst_mbufs[0], cryop_cnt);
626 		if (rc) {
627 			SPDK_ERRLOG("ERROR trying to get dst_mbufs!\n");
628 			rc = -ENOMEM;
629 			goto error_get_dst;
630 		}
631 	}
632 
633 #ifdef __clang_analyzer__
634 	/* silence scan-build false positive */
635 	SPDK_CLANG_ANALYZER_PREINIT_PTR_ARRAY(crypto_ops, MAX_ENQUEUE_ARRAY_SIZE, 0x1000);
636 #endif
637 	/* Allocate crypto operations. */
638 	allocated = rte_crypto_op_bulk_alloc(g_crypto_op_mp,
639 					     RTE_CRYPTO_OP_TYPE_SYMMETRIC,
640 					     crypto_ops, cryop_cnt);
641 	if (allocated < cryop_cnt) {
642 		SPDK_ERRLOG("ERROR trying to get crypto ops!\n");
643 		rc = -ENOMEM;
644 		goto error_get_ops;
645 	}
646 
647 	/* For encryption, we need to prepare a single contiguous buffer as the encryption
648 	 * destination, we'll then pass that along for the write after encryption is done.
649 	 * This is done to avoiding encrypting the provided write buffer which may be
650 	 * undesirable in some use cases.
651 	 */
652 	if (crypto_op == RTE_CRYPTO_CIPHER_OP_ENCRYPT) {
653 		io_ctx->cry_iov.iov_len = total_length;
654 		/* For now just allocate in the I/O path, not optimal but the current bdev API
655 		 * for getting a buffer from the pool won't work if the bdev_io passed in
656 		 * has a buffer, which ours always will.  So, until we modify that API
657 		 * or better yet the current ZCOPY work lands, this is the best we can do.
658 		 */
659 		io_ctx->cry_iov.iov_base = spdk_malloc(total_length,
660 						       spdk_bdev_get_buf_align(bdev_io->bdev), NULL,
661 						       SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
662 		if (!io_ctx->cry_iov.iov_base) {
663 			SPDK_ERRLOG("ERROR trying to allocate write buffer for encryption!\n");
664 			rc = -ENOMEM;
665 			goto error_get_write_buffer;
666 		}
667 		io_ctx->cry_offset_blocks = bdev_io->u.bdev.offset_blocks;
668 		io_ctx->cry_num_blocks = bdev_io->u.bdev.num_blocks;
669 	}
670 
671 	/* This value is used in the completion callback to determine when the bdev_io is
672 	 * complete.
673 	 */
674 	io_ctx->cryop_cnt_remaining = cryop_cnt;
675 
676 	/* As we don't support chaining because of a decision to use LBA as IV, construction
677 	 * of crypto operations is straightforward. We build both the op, the mbuf and the
678 	 * dst_mbuf in our local arrays by looping through the length of the bdev IO and
679 	 * picking off LBA sized blocks of memory from the IOVs as we walk through them. Each
680 	 * LBA sized chunck of memory will correspond 1:1 to a crypto operation and a single
681 	 * mbuf per crypto operation.
682 	 */
683 	total_remaining = total_length;
684 	current_iov = bdev_io->u.bdev.iovs[iov_index].iov_base;
685 	current_iov_remaining = bdev_io->u.bdev.iovs[iov_index].iov_len;
686 	do {
687 		uint8_t *iv_ptr;
688 		uint64_t op_block_offset;
689 
690 		/* Set the mbuf elements address and length. Null out the next pointer. */
691 		src_mbufs[crypto_index]->buf_addr = current_iov;
692 		src_mbufs[crypto_index]->data_len = updated_length = crypto_len;
693 		src_mbufs[crypto_index]->buf_iova = spdk_vtophys((void *)current_iov, &updated_length);
694 		assert(updated_length == crypto_len);
695 		src_mbufs[crypto_index]->next = NULL;
696 		/* Store context in every mbuf as we don't know anything about completion order */
697 		src_mbufs[crypto_index]->userdata = bdev_io;
698 
699 		/* Set the IV - we use the LBA of the crypto_op */
700 		iv_ptr = rte_crypto_op_ctod_offset(crypto_ops[crypto_index], uint8_t *,
701 						   IV_OFFSET);
702 		memset(iv_ptr, 0, AES_CBC_IV_LENGTH);
703 		op_block_offset = bdev_io->u.bdev.offset_blocks + crypto_index;
704 		rte_memcpy(iv_ptr, &op_block_offset, sizeof(uint64_t));
705 
706 		/* Set the data to encrypt/decrypt length */
707 		crypto_ops[crypto_index]->sym->cipher.data.length = crypto_len;
708 		crypto_ops[crypto_index]->sym->cipher.data.offset = 0;
709 
710 		/* link the mbuf to the crypto op. */
711 		crypto_ops[crypto_index]->sym->m_src = src_mbufs[crypto_index];
712 		if (crypto_op == RTE_CRYPTO_CIPHER_OP_ENCRYPT) {
713 			crypto_ops[crypto_index]->sym->m_dst = src_mbufs[crypto_index];
714 		} else {
715 			crypto_ops[crypto_index]->sym->m_dst = NULL;
716 		}
717 
718 		/* For encrypt, point the destination to a buffer we allocate and redirect the bdev_io
719 		 * that will be used to process the write on completion to the same buffer. Setting
720 		 * up the en_buffer is a little simpler as we know the destination buffer is single IOV.
721 		 */
722 		if (crypto_op == RTE_CRYPTO_CIPHER_OP_ENCRYPT) {
723 
724 			/* Set the relevant destination en_mbuf elements. */
725 			dst_mbufs[crypto_index]->buf_addr = io_ctx->cry_iov.iov_base + en_offset;
726 			dst_mbufs[crypto_index]->data_len = updated_length = crypto_len;
727 			dst_mbufs[crypto_index]->buf_iova = spdk_vtophys(dst_mbufs[crypto_index]->buf_addr,
728 							    &updated_length);
729 			assert(updated_length == crypto_len);
730 			crypto_ops[crypto_index]->sym->m_dst = dst_mbufs[crypto_index];
731 			en_offset += crypto_len;
732 			dst_mbufs[crypto_index]->next = NULL;
733 
734 			/* Attach the crypto session to the operation */
735 			rc = rte_crypto_op_attach_sym_session(crypto_ops[crypto_index],
736 							      io_ctx->crypto_bdev->session_encrypt);
737 			if (rc) {
738 				rc = -EINVAL;
739 				goto error_attach_session;
740 			}
741 
742 		} else {
743 			/* Attach the crypto session to the operation */
744 			rc = rte_crypto_op_attach_sym_session(crypto_ops[crypto_index],
745 							      io_ctx->crypto_bdev->session_decrypt);
746 			if (rc) {
747 				rc = -EINVAL;
748 				goto error_attach_session;
749 			}
750 
751 
752 		}
753 
754 		/* Subtract our running totals for the op in progress and the overall bdev io */
755 		total_remaining -= crypto_len;
756 		current_iov_remaining -= crypto_len;
757 
758 		/* move our current IOV pointer accordingly. */
759 		current_iov += crypto_len;
760 
761 		/* move on to the next crypto operation */
762 		crypto_index++;
763 
764 		/* If we're done with this IOV, move to the next one. */
765 		if (current_iov_remaining == 0 && total_remaining > 0) {
766 			iov_index++;
767 			current_iov = bdev_io->u.bdev.iovs[iov_index].iov_base;
768 			current_iov_remaining = bdev_io->u.bdev.iovs[iov_index].iov_len;
769 		}
770 	} while (total_remaining > 0);
771 
772 	/* Enqueue everything we've got but limit by the max number of descriptors we
773 	 * configured the crypto device for.
774 	 */
775 	do {
776 		burst = spdk_min((cryop_cnt - enqueued), CRYPTO_QP_DESCRIPTORS);
777 		num_enqueued_ops = rte_cryptodev_enqueue_burst(cdev_id, crypto_ch->device_qp->qp,
778 				   &crypto_ops[enqueued],
779 				   burst);
780 		enqueued += num_enqueued_ops;
781 
782 		/* Dequeue all inline if the device is full. We don't defer anything simply
783 		 * because of the complexity involved as we're building 1 or more crypto
784 		 * ops per IO. Dequeue will free up space for more enqueue.
785 		 */
786 		if (enqueued < cryop_cnt) {
787 
788 			/* Dequeue everything, this may include ops that were already
789 			 * in the device before this submission....
790 			 */
791 			do {
792 				completed = crypto_dev_poller(crypto_ch);
793 			} while (completed > 0);
794 		}
795 	} while (enqueued < cryop_cnt);
796 
797 	/* Add this bdev_io to our outstanding list. */
798 	TAILQ_INSERT_TAIL(&crypto_ch->pending_cry_ios, bdev_io, module_link);
799 
800 	return rc;
801 
802 	/* Error cleanup paths. */
803 error_attach_session:
804 error_get_write_buffer:
805 	rte_mempool_put_bulk(g_crypto_op_mp, (void **)crypto_ops, cryop_cnt);
806 	allocated = 0;
807 error_get_ops:
808 	if (crypto_op == RTE_CRYPTO_CIPHER_OP_ENCRYPT) {
809 		spdk_mempool_put_bulk(g_mbuf_mp, (void **)&dst_mbufs[0],
810 				      cryop_cnt);
811 	}
812 	if (allocated > 0) {
813 		rte_mempool_put_bulk(g_crypto_op_mp, (void **)crypto_ops,
814 				     allocated);
815 	}
816 error_get_dst:
817 	spdk_mempool_put_bulk(g_mbuf_mp, (void **)&src_mbufs[0],
818 			      cryop_cnt);
819 	return rc;
820 }
821 
822 /* This function is called after all channels have been quiesced following
823  * a bdev reset.
824  */
825 static void
826 _ch_quiesce_done(struct spdk_io_channel_iter *i, int status)
827 {
828 	struct crypto_bdev_io *io_ctx = spdk_io_channel_iter_get_ctx(i);
829 
830 	assert(TAILQ_EMPTY(&io_ctx->crypto_ch->pending_cry_ios));
831 	assert(io_ctx->orig_io != NULL);
832 
833 	spdk_bdev_io_complete(io_ctx->orig_io, SPDK_BDEV_IO_STATUS_SUCCESS);
834 }
835 
836 /* This function is called per channel to quiesce IOs before completing a
837  * bdev reset that we received.
838  */
839 static void
840 _ch_quiesce(struct spdk_io_channel_iter *i)
841 {
842 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
843 	struct crypto_io_channel *crypto_ch = spdk_io_channel_get_ctx(ch);
844 
845 	crypto_ch->iter = i;
846 	/* When the poller runs, it will see the non-NULL iter and handle
847 	 * the quiesce.
848 	 */
849 }
850 
851 /* Completion callback for IO that were issued from this bdev other than read/write.
852  * They have their own for readability.
853  */
854 static void
855 _complete_internal_io(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
856 {
857 	struct spdk_bdev_io *orig_io = cb_arg;
858 	int status = success ? SPDK_BDEV_IO_STATUS_SUCCESS : SPDK_BDEV_IO_STATUS_FAILED;
859 
860 	if (bdev_io->type == SPDK_BDEV_IO_TYPE_RESET) {
861 		struct crypto_bdev_io *orig_ctx = (struct crypto_bdev_io *)orig_io->driver_ctx;
862 
863 		assert(orig_io == orig_ctx->orig_io);
864 
865 		spdk_bdev_free_io(bdev_io);
866 
867 		spdk_for_each_channel(orig_ctx->crypto_bdev,
868 				      _ch_quiesce,
869 				      orig_ctx,
870 				      _ch_quiesce_done);
871 		return;
872 	}
873 
874 	spdk_bdev_io_complete(orig_io, status);
875 	spdk_bdev_free_io(bdev_io);
876 }
877 
878 /* Completion callback for writes that were issued from this bdev. */
879 static void
880 _complete_internal_write(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
881 {
882 	struct spdk_bdev_io *orig_io = cb_arg;
883 	int status = success ? SPDK_BDEV_IO_STATUS_SUCCESS : SPDK_BDEV_IO_STATUS_FAILED;
884 	struct crypto_bdev_io *orig_ctx = (struct crypto_bdev_io *)orig_io->driver_ctx;
885 
886 	spdk_free(orig_ctx->cry_iov.iov_base);
887 	spdk_bdev_io_complete(orig_io, status);
888 	spdk_bdev_free_io(bdev_io);
889 }
890 
891 /* Completion callback for reads that were issued from this bdev. */
892 static void
893 _complete_internal_read(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
894 {
895 	struct spdk_bdev_io *orig_io = cb_arg;
896 	struct crypto_bdev_io *orig_ctx = (struct crypto_bdev_io *)orig_io->driver_ctx;
897 
898 	if (success) {
899 
900 		/* Save off this bdev_io so it can be freed after decryption. */
901 		orig_ctx->read_io = bdev_io;
902 
903 		if (!_crypto_operation(orig_io, RTE_CRYPTO_CIPHER_OP_DECRYPT)) {
904 			return;
905 		} else {
906 			SPDK_ERRLOG("ERROR decrypting\n");
907 		}
908 	} else {
909 		SPDK_ERRLOG("ERROR on read prior to decrypting\n");
910 	}
911 
912 	spdk_bdev_io_complete(orig_io, SPDK_BDEV_IO_STATUS_FAILED);
913 	spdk_bdev_free_io(bdev_io);
914 }
915 
916 static void
917 vbdev_crypto_resubmit_io(void *arg)
918 {
919 	struct spdk_bdev_io *bdev_io = (struct spdk_bdev_io *)arg;
920 	struct crypto_bdev_io *io_ctx = (struct crypto_bdev_io *)bdev_io->driver_ctx;
921 
922 	vbdev_crypto_submit_request(io_ctx->ch, bdev_io);
923 }
924 
925 static void
926 vbdev_crypto_queue_io(struct spdk_bdev_io *bdev_io)
927 {
928 	struct crypto_bdev_io *io_ctx = (struct crypto_bdev_io *)bdev_io->driver_ctx;
929 	int rc;
930 
931 	io_ctx->bdev_io_wait.bdev = bdev_io->bdev;
932 	io_ctx->bdev_io_wait.cb_fn = vbdev_crypto_resubmit_io;
933 	io_ctx->bdev_io_wait.cb_arg = bdev_io;
934 
935 	rc = spdk_bdev_queue_io_wait(bdev_io->bdev, io_ctx->ch, &io_ctx->bdev_io_wait);
936 	if (rc != 0) {
937 		SPDK_ERRLOG("Queue io failed in vbdev_crypto_queue_io, rc=%d.\n", rc);
938 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
939 	}
940 }
941 
942 /* Callback for getting a buf from the bdev pool in the event that the caller passed
943  * in NULL, we need to own the buffer so it doesn't get freed by another vbdev module
944  * beneath us before we're done with it.
945  */
946 static void
947 crypto_read_get_buf_cb(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io,
948 		       bool success)
949 {
950 	struct vbdev_crypto *crypto_bdev = SPDK_CONTAINEROF(bdev_io->bdev, struct vbdev_crypto,
951 					   crypto_bdev);
952 	struct crypto_io_channel *crypto_ch = spdk_io_channel_get_ctx(ch);
953 	struct crypto_bdev_io *io_ctx = (struct crypto_bdev_io *)bdev_io->driver_ctx;
954 	int rc;
955 
956 	if (!success) {
957 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
958 		return;
959 	}
960 
961 	rc = spdk_bdev_readv_blocks(crypto_bdev->base_desc, crypto_ch->base_ch, bdev_io->u.bdev.iovs,
962 				    bdev_io->u.bdev.iovcnt, bdev_io->u.bdev.offset_blocks,
963 				    bdev_io->u.bdev.num_blocks, _complete_internal_read,
964 				    bdev_io);
965 	if (rc != 0) {
966 		if (rc == -ENOMEM) {
967 			SPDK_DEBUGLOG(SPDK_LOG_CRYPTO, "No memory, queue the IO.\n");
968 			io_ctx->ch = ch;
969 			vbdev_crypto_queue_io(bdev_io);
970 		} else {
971 			SPDK_ERRLOG("ERROR on bdev_io submission!\n");
972 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
973 		}
974 	}
975 }
976 
977 /* Called when someone submits IO to this crypto vbdev. For IO's not relevant to crypto,
978  * we're simply passing it on here via SPDK IO calls which in turn allocate another bdev IO
979  * and call our cpl callback provided below along with the original bdev_io so that we can
980  * complete it once this IO completes. For crypto operations, we'll either encrypt it first
981  * (writes) then call back into bdev to submit it or we'll submit a read and then catch it
982  * on the way back for decryption.
983  */
984 static void
985 vbdev_crypto_submit_request(struct spdk_io_channel *ch, struct spdk_bdev_io *bdev_io)
986 {
987 	struct vbdev_crypto *crypto_bdev = SPDK_CONTAINEROF(bdev_io->bdev, struct vbdev_crypto,
988 					   crypto_bdev);
989 	struct crypto_io_channel *crypto_ch = spdk_io_channel_get_ctx(ch);
990 	struct crypto_bdev_io *io_ctx = (struct crypto_bdev_io *)bdev_io->driver_ctx;
991 	int rc = 0;
992 
993 	memset(io_ctx, 0, sizeof(struct crypto_bdev_io));
994 	io_ctx->crypto_bdev = crypto_bdev;
995 	io_ctx->crypto_ch = crypto_ch;
996 	io_ctx->orig_io = bdev_io;
997 
998 	switch (bdev_io->type) {
999 	case SPDK_BDEV_IO_TYPE_READ:
1000 		spdk_bdev_io_get_buf(bdev_io, crypto_read_get_buf_cb,
1001 				     bdev_io->u.bdev.num_blocks * bdev_io->bdev->blocklen);
1002 		break;
1003 	case SPDK_BDEV_IO_TYPE_WRITE:
1004 		rc = _crypto_operation(bdev_io, RTE_CRYPTO_CIPHER_OP_ENCRYPT);
1005 		break;
1006 	case SPDK_BDEV_IO_TYPE_UNMAP:
1007 		rc = spdk_bdev_unmap_blocks(crypto_bdev->base_desc, crypto_ch->base_ch,
1008 					    bdev_io->u.bdev.offset_blocks,
1009 					    bdev_io->u.bdev.num_blocks,
1010 					    _complete_internal_io, bdev_io);
1011 		break;
1012 	case SPDK_BDEV_IO_TYPE_FLUSH:
1013 		rc = spdk_bdev_flush_blocks(crypto_bdev->base_desc, crypto_ch->base_ch,
1014 					    bdev_io->u.bdev.offset_blocks,
1015 					    bdev_io->u.bdev.num_blocks,
1016 					    _complete_internal_io, bdev_io);
1017 		break;
1018 	case SPDK_BDEV_IO_TYPE_RESET:
1019 		rc = spdk_bdev_reset(crypto_bdev->base_desc, crypto_ch->base_ch,
1020 				     _complete_internal_io, bdev_io);
1021 		break;
1022 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
1023 	default:
1024 		SPDK_ERRLOG("crypto: unknown I/O type %d\n", bdev_io->type);
1025 		spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1026 		return;
1027 	}
1028 
1029 	if (rc != 0) {
1030 		if (rc == -ENOMEM) {
1031 			SPDK_DEBUGLOG(SPDK_LOG_CRYPTO, "No memory, queue the IO.\n");
1032 			io_ctx->ch = ch;
1033 			vbdev_crypto_queue_io(bdev_io);
1034 		} else {
1035 			SPDK_ERRLOG("ERROR on bdev_io submission!\n");
1036 			spdk_bdev_io_complete(bdev_io, SPDK_BDEV_IO_STATUS_FAILED);
1037 		}
1038 	}
1039 }
1040 
1041 /* We'll just call the base bdev and let it answer except for WZ command which
1042  * we always say we don't support so that the bdev layer will actually send us
1043  * real writes that we can encrypt.
1044  */
1045 static bool
1046 vbdev_crypto_io_type_supported(void *ctx, enum spdk_bdev_io_type io_type)
1047 {
1048 	struct vbdev_crypto *crypto_bdev = (struct vbdev_crypto *)ctx;
1049 
1050 	switch (io_type) {
1051 	case SPDK_BDEV_IO_TYPE_WRITE:
1052 	case SPDK_BDEV_IO_TYPE_UNMAP:
1053 	case SPDK_BDEV_IO_TYPE_RESET:
1054 	case SPDK_BDEV_IO_TYPE_READ:
1055 	case SPDK_BDEV_IO_TYPE_FLUSH:
1056 		return spdk_bdev_io_type_supported(crypto_bdev->base_bdev, io_type);
1057 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
1058 	/* Force the bdev layer to issue actual writes of zeroes so we can
1059 	 * encrypt them as regular writes.
1060 	 */
1061 	default:
1062 		return false;
1063 	}
1064 }
1065 
1066 /* Callback for unregistering the IO device. */
1067 static void
1068 _device_unregister_cb(void *io_device)
1069 {
1070 	struct vbdev_crypto *crypto_bdev = io_device;
1071 
1072 	/* Done with this crypto_bdev. */
1073 	rte_cryptodev_sym_session_free(crypto_bdev->session_decrypt);
1074 	rte_cryptodev_sym_session_free(crypto_bdev->session_encrypt);
1075 	free(crypto_bdev->drv_name);
1076 	free(crypto_bdev->key);
1077 	free(crypto_bdev->crypto_bdev.name);
1078 	free(crypto_bdev);
1079 }
1080 
1081 /* Called after we've unregistered following a hot remove callback.
1082  * Our finish entry point will be called next.
1083  */
1084 static int
1085 vbdev_crypto_destruct(void *ctx)
1086 {
1087 	struct vbdev_crypto *crypto_bdev = (struct vbdev_crypto *)ctx;
1088 
1089 	/* Remove this device from the internal list */
1090 	TAILQ_REMOVE(&g_vbdev_crypto, crypto_bdev, link);
1091 
1092 	/* Unclaim the underlying bdev. */
1093 	spdk_bdev_module_release_bdev(crypto_bdev->base_bdev);
1094 
1095 	/* Close the underlying bdev. */
1096 	spdk_bdev_close(crypto_bdev->base_desc);
1097 
1098 	/* Unregister the io_device. */
1099 	spdk_io_device_unregister(crypto_bdev, _device_unregister_cb);
1100 
1101 	return 0;
1102 }
1103 
1104 /* We supplied this as an entry point for upper layers who want to communicate to this
1105  * bdev.  This is how they get a channel. We are passed the same context we provided when
1106  * we created our crypto vbdev in examine() which, for this bdev, is the address of one of
1107  * our context nodes. From here we'll ask the SPDK channel code to fill out our channel
1108  * struct and we'll keep it in our crypto node.
1109  */
1110 static struct spdk_io_channel *
1111 vbdev_crypto_get_io_channel(void *ctx)
1112 {
1113 	struct vbdev_crypto *crypto_bdev = (struct vbdev_crypto *)ctx;
1114 
1115 	/* The IO channel code will allocate a channel for us which consists of
1116 	 * the SPDK cahnnel structure plus the size of our crypto_io_channel struct
1117 	 * that we passed in when we registered our IO device. It will then call
1118 	 * our channel create callback to populate any elements that we need to
1119 	 * update.
1120 	 */
1121 	return spdk_get_io_channel(crypto_bdev);
1122 }
1123 
1124 /* This is the output for bdev_get_bdevs() for this vbdev */
1125 static int
1126 vbdev_crypto_dump_info_json(void *ctx, struct spdk_json_write_ctx *w)
1127 {
1128 	struct vbdev_crypto *crypto_bdev = (struct vbdev_crypto *)ctx;
1129 
1130 	spdk_json_write_name(w, "crypto");
1131 	spdk_json_write_object_begin(w);
1132 	spdk_json_write_named_string(w, "base_bdev_name", spdk_bdev_get_name(crypto_bdev->base_bdev));
1133 	spdk_json_write_named_string(w, "name", spdk_bdev_get_name(&crypto_bdev->crypto_bdev));
1134 	spdk_json_write_named_string(w, "crypto_pmd", crypto_bdev->drv_name);
1135 	spdk_json_write_named_string(w, "key", crypto_bdev->key);
1136 	spdk_json_write_object_end(w);
1137 	return 0;
1138 }
1139 
1140 static int
1141 vbdev_crypto_config_json(struct spdk_json_write_ctx *w)
1142 {
1143 	struct vbdev_crypto *crypto_bdev;
1144 
1145 	TAILQ_FOREACH(crypto_bdev, &g_vbdev_crypto, link) {
1146 		spdk_json_write_object_begin(w);
1147 		spdk_json_write_named_string(w, "method", "bdev_crypto_create");
1148 		spdk_json_write_named_object_begin(w, "params");
1149 		spdk_json_write_named_string(w, "base_bdev_name", spdk_bdev_get_name(crypto_bdev->base_bdev));
1150 		spdk_json_write_named_string(w, "name", spdk_bdev_get_name(&crypto_bdev->crypto_bdev));
1151 		spdk_json_write_named_string(w, "crypto_pmd", crypto_bdev->drv_name);
1152 		spdk_json_write_named_string(w, "key", crypto_bdev->key);
1153 		spdk_json_write_object_end(w);
1154 		spdk_json_write_object_end(w);
1155 	}
1156 	return 0;
1157 }
1158 
1159 /* We provide this callback for the SPDK channel code to create a channel using
1160  * the channel struct we provided in our module get_io_channel() entry point. Here
1161  * we get and save off an underlying base channel of the device below us so that
1162  * we can communicate with the base bdev on a per channel basis. We also register the
1163  * poller used to complete crypto operations from the device.
1164  */
1165 static int
1166 crypto_bdev_ch_create_cb(void *io_device, void *ctx_buf)
1167 {
1168 	struct crypto_io_channel *crypto_ch = ctx_buf;
1169 	struct vbdev_crypto *crypto_bdev = io_device;
1170 	struct device_qp *device_qp;
1171 
1172 	crypto_ch->base_ch = spdk_bdev_get_io_channel(crypto_bdev->base_desc);
1173 	crypto_ch->poller = spdk_poller_register(crypto_dev_poller, crypto_ch, 0);
1174 	crypto_ch->device_qp = NULL;
1175 
1176 	pthread_mutex_lock(&g_device_qp_lock);
1177 	TAILQ_FOREACH(device_qp, &g_device_qp, link) {
1178 		if ((strcmp(device_qp->device->cdev_info.driver_name, crypto_bdev->drv_name) == 0) &&
1179 		    (device_qp->in_use == false)) {
1180 			crypto_ch->device_qp = device_qp;
1181 			device_qp->in_use = true;
1182 			break;
1183 		}
1184 	}
1185 	pthread_mutex_unlock(&g_device_qp_lock);
1186 	assert(crypto_ch->device_qp);
1187 
1188 	/* We use this queue to track outstanding IO in our lyaer. */
1189 	TAILQ_INIT(&crypto_ch->pending_cry_ios);
1190 
1191 	return 0;
1192 }
1193 
1194 /* We provide this callback for the SPDK channel code to destroy a channel
1195  * created with our create callback. We just need to undo anything we did
1196  * when we created.
1197  */
1198 static void
1199 crypto_bdev_ch_destroy_cb(void *io_device, void *ctx_buf)
1200 {
1201 	struct crypto_io_channel *crypto_ch = ctx_buf;
1202 
1203 	pthread_mutex_lock(&g_device_qp_lock);
1204 	crypto_ch->device_qp->in_use = false;
1205 	pthread_mutex_unlock(&g_device_qp_lock);
1206 
1207 	spdk_poller_unregister(&crypto_ch->poller);
1208 	spdk_put_io_channel(crypto_ch->base_ch);
1209 }
1210 
1211 /* Create the association from the bdev and vbdev name and insert
1212  * on the global list. */
1213 static int
1214 vbdev_crypto_insert_name(const char *bdev_name, const char *vbdev_name,
1215 			 const char *crypto_pmd, const char *key)
1216 {
1217 	struct bdev_names *name;
1218 	int rc, j;
1219 	bool found = false;
1220 
1221 	TAILQ_FOREACH(name, &g_bdev_names, link) {
1222 		if (strcmp(vbdev_name, name->vbdev_name) == 0) {
1223 			SPDK_ERRLOG("crypto bdev %s already exists\n", vbdev_name);
1224 			return -EEXIST;
1225 		}
1226 	}
1227 
1228 	name = calloc(1, sizeof(struct bdev_names));
1229 	if (!name) {
1230 		SPDK_ERRLOG("could not allocate bdev_names\n");
1231 		return -ENOMEM;
1232 	}
1233 
1234 	name->bdev_name = strdup(bdev_name);
1235 	if (!name->bdev_name) {
1236 		SPDK_ERRLOG("could not allocate name->bdev_name\n");
1237 		rc = -ENOMEM;
1238 		goto error_alloc_bname;
1239 	}
1240 
1241 	name->vbdev_name = strdup(vbdev_name);
1242 	if (!name->vbdev_name) {
1243 		SPDK_ERRLOG("could not allocate name->vbdev_name\n");
1244 		rc = -ENOMEM;
1245 		goto error_alloc_vname;
1246 	}
1247 
1248 	name->drv_name = strdup(crypto_pmd);
1249 	if (!name->drv_name) {
1250 		SPDK_ERRLOG("could not allocate name->drv_name\n");
1251 		rc = -ENOMEM;
1252 		goto error_alloc_dname;
1253 	}
1254 	for (j = 0; j < MAX_NUM_DRV_TYPES ; j++) {
1255 		if (strcmp(crypto_pmd, g_driver_names[j]) == 0) {
1256 			found = true;
1257 			break;
1258 		}
1259 	}
1260 	if (!found) {
1261 		SPDK_ERRLOG("invalid crypto PMD type %s\n", crypto_pmd);
1262 		rc = -EINVAL;
1263 		goto error_invalid_pmd;
1264 	}
1265 
1266 	name->key = strdup(key);
1267 	if (!name->key) {
1268 		SPDK_ERRLOG("could not allocate name->key\n");
1269 		rc = -ENOMEM;
1270 		goto error_alloc_key;
1271 	}
1272 	if (strlen(name->key) != AES_CBC_KEY_LENGTH) {
1273 		SPDK_ERRLOG("invalid AES_CCB key length\n");
1274 		rc = -EINVAL;
1275 		goto error_invalid_key;
1276 	}
1277 
1278 	TAILQ_INSERT_TAIL(&g_bdev_names, name, link);
1279 
1280 	return 0;
1281 
1282 	/* Error cleanup paths. */
1283 error_invalid_key:
1284 error_alloc_key:
1285 error_invalid_pmd:
1286 	free(name->drv_name);
1287 error_alloc_dname:
1288 	free(name->vbdev_name);
1289 error_alloc_vname:
1290 	free(name->bdev_name);
1291 error_alloc_bname:
1292 	free(name);
1293 	return rc;
1294 }
1295 
1296 /* RPC entry point for crypto creation. */
1297 int
1298 create_crypto_disk(const char *bdev_name, const char *vbdev_name,
1299 		   const char *crypto_pmd, const char *key)
1300 {
1301 	struct spdk_bdev *bdev = NULL;
1302 	int rc = 0;
1303 
1304 	bdev = spdk_bdev_get_by_name(bdev_name);
1305 
1306 	rc = vbdev_crypto_insert_name(bdev_name, vbdev_name, crypto_pmd, key);
1307 	if (rc) {
1308 		return rc;
1309 	}
1310 
1311 	if (!bdev) {
1312 		SPDK_NOTICELOG("vbdev creation deferred pending base bdev arrival\n");
1313 		return 0;
1314 	}
1315 
1316 	rc = vbdev_crypto_claim(bdev);
1317 	if (rc) {
1318 		return rc;
1319 	}
1320 
1321 	return rc;
1322 }
1323 
1324 /* Called at driver init time, parses config file to preapre for examine calls,
1325  * also fully initializes the crypto drivers.
1326  */
1327 static int
1328 vbdev_crypto_init(void)
1329 {
1330 	struct spdk_conf_section *sp = NULL;
1331 	const char *conf_bdev_name = NULL;
1332 	const char *conf_vbdev_name = NULL;
1333 	const char *crypto_pmd = NULL;
1334 	int i;
1335 	int rc = 0;
1336 	const char *key = NULL;
1337 
1338 	/* Fully configure both SW and HW drivers. */
1339 	rc = vbdev_crypto_init_crypto_drivers();
1340 	if (rc) {
1341 		SPDK_ERRLOG("Error setting up crypto devices\n");
1342 		return rc;
1343 	}
1344 
1345 	sp = spdk_conf_find_section(NULL, "crypto");
1346 	if (sp == NULL) {
1347 		return 0;
1348 	}
1349 
1350 	for (i = 0; ; i++) {
1351 
1352 		if (!spdk_conf_section_get_nval(sp, "CRY", i)) {
1353 			break;
1354 		}
1355 
1356 		conf_bdev_name = spdk_conf_section_get_nmval(sp, "CRY", i, 0);
1357 		if (!conf_bdev_name) {
1358 			SPDK_ERRLOG("crypto configuration missing bdev name\n");
1359 			return -EINVAL;
1360 		}
1361 
1362 		conf_vbdev_name = spdk_conf_section_get_nmval(sp, "CRY", i, 1);
1363 		if (!conf_vbdev_name) {
1364 			SPDK_ERRLOG("crypto configuration missing crypto_bdev name\n");
1365 			return -EINVAL;
1366 		}
1367 
1368 		key = spdk_conf_section_get_nmval(sp, "CRY", i, 2);
1369 		if (!key) {
1370 			SPDK_ERRLOG("crypto configuration missing crypto_bdev key\n");
1371 			return -EINVAL;
1372 		}
1373 		SPDK_NOTICELOG("WARNING: You are storing your key in a plain text file!!\n");
1374 
1375 		crypto_pmd = spdk_conf_section_get_nmval(sp, "CRY", i, 3);
1376 		if (!crypto_pmd) {
1377 			SPDK_ERRLOG("crypto configuration missing driver type\n");
1378 			return -EINVAL;
1379 		}
1380 
1381 		rc = vbdev_crypto_insert_name(conf_bdev_name, conf_vbdev_name,
1382 					      crypto_pmd, key);
1383 		if (rc != 0) {
1384 			return rc;
1385 		}
1386 	}
1387 
1388 	return rc;
1389 }
1390 
1391 /* Called when the entire module is being torn down. */
1392 static void
1393 vbdev_crypto_finish(void)
1394 {
1395 	struct bdev_names *name;
1396 	struct vbdev_dev *device;
1397 	struct device_qp *dev_qp;
1398 	unsigned i;
1399 	int rc;
1400 
1401 	while ((name = TAILQ_FIRST(&g_bdev_names))) {
1402 		TAILQ_REMOVE(&g_bdev_names, name, link);
1403 		free(name->drv_name);
1404 		free(name->key);
1405 		free(name->bdev_name);
1406 		free(name->vbdev_name);
1407 		free(name);
1408 	}
1409 
1410 	while ((device = TAILQ_FIRST(&g_vbdev_devs))) {
1411 		struct rte_cryptodev *rte_dev;
1412 
1413 		TAILQ_REMOVE(&g_vbdev_devs, device, link);
1414 		rte_cryptodev_stop(device->cdev_id);
1415 
1416 		assert(device->cdev_id < RTE_CRYPTO_MAX_DEVS);
1417 		rte_dev = &rte_cryptodevs[device->cdev_id];
1418 
1419 		if (rte_dev->dev_ops->queue_pair_release != NULL) {
1420 			for (i = 0; i < device->cdev_info.max_nb_queue_pairs; i++) {
1421 				rte_dev->dev_ops->queue_pair_release(rte_dev, i);
1422 			}
1423 		}
1424 		free(device);
1425 	}
1426 	rc = rte_vdev_uninit(AESNI_MB);
1427 	if (rc) {
1428 		SPDK_ERRLOG("%d from rte_vdev_uninit\n", rc);
1429 	}
1430 
1431 	while ((dev_qp = TAILQ_FIRST(&g_device_qp))) {
1432 		TAILQ_REMOVE(&g_device_qp, dev_qp, link);
1433 		free(dev_qp);
1434 	}
1435 
1436 	rte_mempool_free(g_crypto_op_mp);
1437 	spdk_mempool_free(g_mbuf_mp);
1438 	rte_mempool_free(g_session_mp);
1439 	if (g_session_mp_priv != NULL) {
1440 		rte_mempool_free(g_session_mp_priv);
1441 	}
1442 }
1443 
1444 /* During init we'll be asked how much memory we'd like passed to us
1445  * in bev_io structures as context. Here's where we specify how
1446  * much context we want per IO.
1447  */
1448 static int
1449 vbdev_crypto_get_ctx_size(void)
1450 {
1451 	return sizeof(struct crypto_bdev_io);
1452 }
1453 
1454 /* Called when SPDK wants to save the current config of this vbdev module to
1455  * a file.
1456  */
1457 static void
1458 vbdev_crypto_get_spdk_running_config(FILE *fp)
1459 {
1460 	struct bdev_names *names = NULL;
1461 	fprintf(fp, "\n[crypto]\n");
1462 	TAILQ_FOREACH(names, &g_bdev_names, link) {
1463 		fprintf(fp, "  crypto %s %s ", names->bdev_name, names->vbdev_name);
1464 		fprintf(fp, "\n");
1465 	}
1466 
1467 	fprintf(fp, "\n");
1468 }
1469 
1470 /* Called when the underlying base bdev goes away. */
1471 static void
1472 vbdev_crypto_examine_hotremove_cb(void *ctx)
1473 {
1474 	struct vbdev_crypto *crypto_bdev, *tmp;
1475 	struct spdk_bdev *bdev_find = ctx;
1476 
1477 	TAILQ_FOREACH_SAFE(crypto_bdev, &g_vbdev_crypto, link, tmp) {
1478 		if (bdev_find == crypto_bdev->base_bdev) {
1479 			spdk_bdev_unregister(&crypto_bdev->crypto_bdev, NULL, NULL);
1480 		}
1481 	}
1482 }
1483 
1484 static void
1485 vbdev_crypto_write_config_json(struct spdk_bdev *bdev, struct spdk_json_write_ctx *w)
1486 {
1487 	/* No config per bdev needed */
1488 }
1489 
1490 /* When we register our bdev this is how we specify our entry points. */
1491 static const struct spdk_bdev_fn_table vbdev_crypto_fn_table = {
1492 	.destruct		= vbdev_crypto_destruct,
1493 	.submit_request		= vbdev_crypto_submit_request,
1494 	.io_type_supported	= vbdev_crypto_io_type_supported,
1495 	.get_io_channel		= vbdev_crypto_get_io_channel,
1496 	.dump_info_json		= vbdev_crypto_dump_info_json,
1497 	.write_config_json	= vbdev_crypto_write_config_json
1498 };
1499 
1500 static struct spdk_bdev_module crypto_if = {
1501 	.name = "crypto",
1502 	.module_init = vbdev_crypto_init,
1503 	.config_text = vbdev_crypto_get_spdk_running_config,
1504 	.get_ctx_size = vbdev_crypto_get_ctx_size,
1505 	.examine_config = vbdev_crypto_examine,
1506 	.module_fini = vbdev_crypto_finish,
1507 	.config_json = vbdev_crypto_config_json
1508 };
1509 
1510 SPDK_BDEV_MODULE_REGISTER(crypto, &crypto_if)
1511 
1512 static int
1513 vbdev_crypto_claim(struct spdk_bdev *bdev)
1514 {
1515 	struct bdev_names *name;
1516 	struct vbdev_crypto *vbdev;
1517 	struct vbdev_dev *device;
1518 	bool found = false;
1519 	int rc = 0;
1520 
1521 	/* Check our list of names from config versus this bdev and if
1522 	 * there's a match, create the crypto_bdev & bdev accordingly.
1523 	 */
1524 	TAILQ_FOREACH(name, &g_bdev_names, link) {
1525 		if (strcmp(name->bdev_name, bdev->name) != 0) {
1526 			continue;
1527 		}
1528 		SPDK_DEBUGLOG(SPDK_LOG_CRYPTO, "Match on %s\n", bdev->name);
1529 
1530 		vbdev = calloc(1, sizeof(struct vbdev_crypto));
1531 		if (!vbdev) {
1532 			SPDK_ERRLOG("could not allocate crypto_bdev\n");
1533 			rc = -ENOMEM;
1534 			goto error_vbdev_alloc;
1535 		}
1536 
1537 		/* The base bdev that we're attaching to. */
1538 		vbdev->base_bdev = bdev;
1539 		vbdev->crypto_bdev.name = strdup(name->vbdev_name);
1540 		if (!vbdev->crypto_bdev.name) {
1541 			SPDK_ERRLOG("could not allocate crypto_bdev name\n");
1542 			rc = -ENOMEM;
1543 			goto error_bdev_name;
1544 		}
1545 
1546 		vbdev->key = strdup(name->key);
1547 		if (!vbdev->key) {
1548 			SPDK_ERRLOG("could not allocate crypto_bdev key\n");
1549 			rc = -ENOMEM;
1550 			goto error_alloc_key;
1551 		}
1552 
1553 		vbdev->drv_name = strdup(name->drv_name);
1554 		if (!vbdev->drv_name) {
1555 			SPDK_ERRLOG("could not allocate crypto_bdev drv_name\n");
1556 			rc = -ENOMEM;
1557 			goto error_drv_name;
1558 		}
1559 
1560 		vbdev->crypto_bdev.product_name = "crypto";
1561 		vbdev->crypto_bdev.write_cache = bdev->write_cache;
1562 		if (strcmp(vbdev->drv_name, QAT) == 0) {
1563 			vbdev->crypto_bdev.required_alignment =
1564 				spdk_max(spdk_u32log2(bdev->blocklen), bdev->required_alignment);
1565 			SPDK_NOTICELOG("QAT in use: Required alignment set to %u\n",
1566 				       vbdev->crypto_bdev.required_alignment);
1567 		} else {
1568 			vbdev->crypto_bdev.required_alignment = bdev->required_alignment;
1569 		}
1570 		/* Note: CRYPTO_MAX_IO is in units of bytes, optimal_io_boundary is
1571 		 * in units of blocks.
1572 		 */
1573 		if (bdev->optimal_io_boundary > 0) {
1574 			vbdev->crypto_bdev.optimal_io_boundary =
1575 				spdk_min((CRYPTO_MAX_IO / bdev->blocklen), bdev->optimal_io_boundary);
1576 		} else {
1577 			vbdev->crypto_bdev.optimal_io_boundary = (CRYPTO_MAX_IO / bdev->blocklen);
1578 		}
1579 		vbdev->crypto_bdev.split_on_optimal_io_boundary = true;
1580 		vbdev->crypto_bdev.blocklen = bdev->blocklen;
1581 		vbdev->crypto_bdev.blockcnt = bdev->blockcnt;
1582 
1583 		/* This is the context that is passed to us when the bdev
1584 		 * layer calls in so we'll save our crypto_bdev node here.
1585 		 */
1586 		vbdev->crypto_bdev.ctxt = vbdev;
1587 		vbdev->crypto_bdev.fn_table = &vbdev_crypto_fn_table;
1588 		vbdev->crypto_bdev.module = &crypto_if;
1589 		TAILQ_INSERT_TAIL(&g_vbdev_crypto, vbdev, link);
1590 
1591 		spdk_io_device_register(vbdev, crypto_bdev_ch_create_cb, crypto_bdev_ch_destroy_cb,
1592 					sizeof(struct crypto_io_channel), vbdev->crypto_bdev.name);
1593 
1594 		rc = spdk_bdev_open(bdev, true, vbdev_crypto_examine_hotremove_cb,
1595 				    bdev, &vbdev->base_desc);
1596 		if (rc) {
1597 			SPDK_ERRLOG("could not open bdev %s\n", spdk_bdev_get_name(bdev));
1598 			goto error_open;
1599 		}
1600 
1601 		rc = spdk_bdev_module_claim_bdev(bdev, vbdev->base_desc, vbdev->crypto_bdev.module);
1602 		if (rc) {
1603 			SPDK_ERRLOG("could not claim bdev %s\n", spdk_bdev_get_name(bdev));
1604 			goto error_claim;
1605 		}
1606 
1607 		/* To init the session we have to get the cryptoDev device ID for this vbdev */
1608 		TAILQ_FOREACH(device, &g_vbdev_devs, link) {
1609 			if (strcmp(device->cdev_info.driver_name, vbdev->drv_name) == 0) {
1610 				found = true;
1611 				break;
1612 			}
1613 		}
1614 		if (found == false) {
1615 			SPDK_ERRLOG("ERROR can't match crypto device driver to crypto vbdev!\n");
1616 			rc = -EINVAL;
1617 			goto error_cant_find_devid;
1618 		}
1619 
1620 		/* Get sessions. */
1621 		vbdev->session_encrypt = rte_cryptodev_sym_session_create(g_session_mp);
1622 		if (NULL == vbdev->session_encrypt) {
1623 			SPDK_ERRLOG("ERROR trying to create crypto session!\n");
1624 			rc = -EINVAL;
1625 			goto error_session_en_create;
1626 		}
1627 
1628 		vbdev->session_decrypt = rte_cryptodev_sym_session_create(g_session_mp);
1629 		if (NULL == vbdev->session_decrypt) {
1630 			SPDK_ERRLOG("ERROR trying to create crypto session!\n");
1631 			rc = -EINVAL;
1632 			goto error_session_de_create;
1633 		}
1634 
1635 		/* Init our per vbdev xform with the desired cipher options. */
1636 		vbdev->cipher_xform.type = RTE_CRYPTO_SYM_XFORM_CIPHER;
1637 		vbdev->cipher_xform.cipher.key.data = vbdev->key;
1638 		vbdev->cipher_xform.cipher.iv.offset = IV_OFFSET;
1639 		vbdev->cipher_xform.cipher.algo = RTE_CRYPTO_CIPHER_AES_CBC;
1640 		vbdev->cipher_xform.cipher.key.length = AES_CBC_KEY_LENGTH;
1641 		vbdev->cipher_xform.cipher.iv.length = AES_CBC_IV_LENGTH;
1642 
1643 		vbdev->cipher_xform.cipher.op = RTE_CRYPTO_CIPHER_OP_ENCRYPT;
1644 		rc = rte_cryptodev_sym_session_init(device->cdev_id, vbdev->session_encrypt,
1645 						    &vbdev->cipher_xform,
1646 						    g_session_mp_priv ? g_session_mp_priv : g_session_mp);
1647 		if (rc < 0) {
1648 			SPDK_ERRLOG("ERROR trying to init encrypt session!\n");
1649 			rc = -EINVAL;
1650 			goto error_session_init;
1651 		}
1652 
1653 		vbdev->cipher_xform.cipher.op = RTE_CRYPTO_CIPHER_OP_DECRYPT;
1654 		rc = rte_cryptodev_sym_session_init(device->cdev_id, vbdev->session_decrypt,
1655 						    &vbdev->cipher_xform,
1656 						    g_session_mp_priv ? g_session_mp_priv : g_session_mp);
1657 		if (rc < 0) {
1658 			SPDK_ERRLOG("ERROR trying to init decrypt session!\n");
1659 			rc = -EINVAL;
1660 			goto error_session_init;
1661 		}
1662 
1663 		rc = spdk_bdev_register(&vbdev->crypto_bdev);
1664 		if (rc < 0) {
1665 			SPDK_ERRLOG("ERROR trying to register bdev\n");
1666 			rc = -EINVAL;
1667 			goto error_bdev_register;
1668 		}
1669 		SPDK_DEBUGLOG(SPDK_LOG_CRYPTO, "registered io_device and virtual bdev for: %s\n",
1670 			      name->vbdev_name);
1671 		break;
1672 	}
1673 
1674 	return rc;
1675 
1676 	/* Error cleanup paths. */
1677 error_bdev_register:
1678 error_session_init:
1679 	rte_cryptodev_sym_session_free(vbdev->session_decrypt);
1680 error_session_de_create:
1681 	rte_cryptodev_sym_session_free(vbdev->session_encrypt);
1682 error_session_en_create:
1683 error_cant_find_devid:
1684 error_claim:
1685 	spdk_bdev_close(vbdev->base_desc);
1686 error_open:
1687 	TAILQ_REMOVE(&g_vbdev_crypto, vbdev, link);
1688 	spdk_io_device_unregister(vbdev, NULL);
1689 	free(vbdev->drv_name);
1690 error_drv_name:
1691 	free(vbdev->key);
1692 error_alloc_key:
1693 	free(vbdev->crypto_bdev.name);
1694 error_bdev_name:
1695 	free(vbdev);
1696 error_vbdev_alloc:
1697 	return rc;
1698 }
1699 
1700 /* RPC entry for deleting a crypto vbdev. */
1701 void
1702 delete_crypto_disk(struct spdk_bdev *bdev, spdk_delete_crypto_complete cb_fn,
1703 		   void *cb_arg)
1704 {
1705 	struct bdev_names *name;
1706 
1707 	if (!bdev || bdev->module != &crypto_if) {
1708 		cb_fn(cb_arg, -ENODEV);
1709 		return;
1710 	}
1711 
1712 	/* Remove the association (vbdev, bdev) from g_bdev_names. This is required so that the
1713 	 * vbdev does not get re-created if the same bdev is constructed at some other time,
1714 	 * unless the underlying bdev was hot-removed.
1715 	 */
1716 	TAILQ_FOREACH(name, &g_bdev_names, link) {
1717 		if (strcmp(name->vbdev_name, bdev->name) == 0) {
1718 			TAILQ_REMOVE(&g_bdev_names, name, link);
1719 			free(name->bdev_name);
1720 			free(name->vbdev_name);
1721 			free(name->drv_name);
1722 			free(name->key);
1723 			free(name);
1724 			break;
1725 		}
1726 	}
1727 
1728 	/* Additional cleanup happens in the destruct callback. */
1729 	spdk_bdev_unregister(bdev, cb_fn, cb_arg);
1730 }
1731 
1732 /* Because we specified this function in our crypto bdev function table when we
1733  * registered our crypto bdev, we'll get this call anytime a new bdev shows up.
1734  * Here we need to decide if we care about it and if so what to do. We
1735  * parsed the config file at init so we check the new bdev against the list
1736  * we built up at that time and if the user configured us to attach to this
1737  * bdev, here's where we do it.
1738  */
1739 static void
1740 vbdev_crypto_examine(struct spdk_bdev *bdev)
1741 {
1742 	vbdev_crypto_claim(bdev);
1743 	spdk_bdev_module_examine_done(&crypto_if);
1744 }
1745 
1746 SPDK_LOG_REGISTER_COMPONENT("vbdev_crypto", SPDK_LOG_CRYPTO)
1747