复制代码 复制代码

虚拟化之-virtio学习

virtio学习

基于kernel 6.8-rc5和virtio规范1.1、1.2。

1. virtio queue

  • 通用初始化流程:

1.1 split queue

1.1.1 结构

从Desc角度看,可以把Desc理解成一个链表,添加到avail和回收就是裁剪一段子链表和把子链表接回去的过程。

struct vring_desc {
	__virtio64 addr;
	__virtio32 len;
	__virtio16 flags;
	__virtio16 next;
};

struct vring_avail {
	__virtio16 flags;
	__virtio16 idx;
	__virtio16 ring[];
};

struct vring_used {
	__virtio16 flags;
	__virtio16 idx;
	vring_used_elem_t ring[];
};
/* u32 is used here for ids for padding reasons. */
struct vring_used_elem {
	/* Index of start of used descriptor chain. */
	__virtio32 id;
	/* Total length of the descriptor chain which was used (written to) */
	__virtio32 len;
};

typedef struct vring_used_elem __attribute__((aligned(VRING_USED_ALIGN_SIZE)))
	vring_used_elem_t;

1.2 packed queue

1.2.1 结构

​ 相比较于split模式,packed模式所占用的硬件空间显然更小,只要一条descring的空间和8个byte的空间。


driver_eventdevice_event是用来做中断合并的。驱动通过设置driver_event,与设备协商什么时候需要发出通知;设备通过配置device_event,通知驱动什么时候需要发出avail event。具体的含义见spec1.2:

/* Enable events */
#define RING_EVENT_FLAGS_ENABLE 0x0
/* Disable events */
#define RING_EVENT_FLAGS_DISABLE 0x1
/*
* Enable events for a specific descriptor
* (as specified by Descriptor Ring Change Event Offset/Wrap Counter).
* Only valid if VIRTIO_F_EVENT_IDX has been negotiated.
*/
#define RING_EVENT_FLAGS_DESC 0x2
/* The value 0x3 is reserved */


​ 在驱动程序中,除了要映射上面提到的packed queue的基本结构(与硬件中一一对应),还有驱动自己申请的一些空间,用来记录virtqueue工作过程中的一些状态,这些结构容易和基本结构造成混淆,因此下面先拿出来介绍。分别是

  • state array(用来记录添加到ring中的desc的状态字段,间接表的位置和last desc id)

    struct vring_desc_state_packed *state;
    state = kmalloc_array(queue_size, sizeof(struct vring_desc_state_packed), GFP_KERNEL);
    

  • extra array(用来记录map的缓冲区(正常情况下不用)和ID)

    struct vring_desc_extra *extra;
    int i;
    extra = kmalloc_array(queue_size, sizeof(struct vring_desc_extra),GFP_KERNEL);
    memset(extra, 0, queue_size * sizeof(struct vring_desc_extra));
    for (i = 0; i < queue_size - 1; i++)
    		extra[i].next = i + 1;
    

1.2.2 数据流程

1.2.2.1 驱动生产job
  • 使用indiret desc(优先

    static int virtqueue_add_indirect_packed(struct vring_virtqueue *vq,
    					 struct scatterlist *sgs[],
    					 unsigned int total_sg,
    					 unsigned int out_sgs,
    					 unsigned int in_sgs,
    					 void *data,
    					 gfp_t gfp);
    

    第一步:申请一条indir desc ring

    第二步:使用scattergatterlist表中的每一项,填充indir desc ring,id字段不用填。

    第三步:修改desc ring中的next_avail_idx这个slot,使之指向indir desc ringID字段填充为free_head,FLAG字段加上VRING_DESC_F_INDIRECT

    第四步:驱动更新自己维护的字段,包括avail_wrap_counteravail_used_flagsnext_avail_idxfree_head,最后记录这个desc到state array

    以下图为例,假设queue_size为6,在初始化后,我们在0x8000000处申请了一个长度为5的二级表,并添加到virtqueue里面。

  • 使用chained desc

    chained desc的流程跟indirect类似,只是state array记录的有较大区别。

    这里ID全部设为为Head的ID的意义有点不明确,从extra array的角度理解,实际的ID和next ID都存放在这个数组里面,这里改了难道只是为了辅助设备判断这是一个chain的吗?也可能是为了乱序使用而预留的?

1.2.2.2 设备消费job

​ 以chained desc为例,介绍设备消费Job。设备内部需要维护一个used_idx变量,以便记录上次消费到什么位置。此外,设备内还有一个used_wrap_counter位。这两个字段组合成一个16bit的值。

​ 设备从used_idx开始poll,发现flags变成了W|A,然后往下遍历,发现一直到第5个slot都是W|A,然后开始处理,并且最后覆写第一个slot的FLAG字段,len字段,此时ring的结构如下图所示。

​ 然后设备通过中断或者其他通知机制,通知驱动处理。

1.2.2.3 驱动回收job

​ 驱动收到通知后,开始回收job。

​ 第一步:读取设备的used_idx。发现前15个bit为0,最后一个bit为1。此时驱动就知道设备这次使用的desc的slot为0,且没经过翻转边界。接着就去读取desc[0]的各个字段,发现ID是0。然后去查询state array[ID],先把data字段取出来,作为任务的完成状态字段。

​ 第二步:调用detach_buf_packed(vq, id, ctx);处理缓冲区。首先读取state array[ID],发现这次任务涵盖5个desc,最后一个desc的ID为4。则先做一个类似链表接回去的操作,把extra array的信息先更新了,最后把free_head又设置为ID=0的位置。

​ 第三步:驱动判断消费的数量是否发生越界,从而是否需要更新used_wrap_counterused_idx,最后写回到设备,让设备直到下次从哪里开始poll。此时ring的结构如下所示。

1.2.2.4 发生越界的情况

​ 我们在上一节的情况下继续讨论。加入现在又要添加一条长度为2的chain。那么ring的结构如下所示。此时由于发生了越界,因此驱动更新driver_wrap_counter,并且从头开始重复利用desc。因此slot为0位置的A标志被置为0,U标志被置为1。

​ 设备从used_idx=5的位置开始poll,发现这个slot上是可用的(因为此时设备内部的device_wrap_counter=0,因此识别A=1),然后翻转device_wrap_counter=0,此时又发现slot=0的位置,A=0又符合,因此发现这个也是可用的,接下来发现slot=1的位置不符合,因此就处理两个desc(最后只更新slot为5的那个)。处理完了之后ring的结构如下所示:

​ 驱动回收job的过程类似,只是多了越界时的处理,然后把used_idx设置到1,使得设备下次从1开始poll,驱动包括翻转used_wrap_counter,这样device设置U标志的时候就设置为0,设备写入的标志位就变W|!A|!U。

2. virtio device

2.1 cypto device

  • 对硬件的要求:最后一条virtqueue为control queue

  • Feature bits:

    config空间中的device features的bit0~4
    0:VIRTIO_CRYPTO_F_REVISION_1				/*版本是否1.0以上*/
    1:VIRTIO_CRYPTO_F_CIPHER_STATELESS_MODE		/*无状态模式,仅在1.0以上支持*/
    2:VIRTIO_CRYPTO_F_HASH_STATELESS_MODE
    3:VIRTIO_CRYPTO_F_MAC_STATELESS_MODE
    4:VIRTIO_CRYPTO_F_AEAD_STATELESS_MODE
    
  • 设备配置字段

​ virtio-crypto设备的配置字段如下所示,驱动通过读取配置字段,了解设备信息,从而决定向上提供哪些算法接口。具体配置字段里面每个BIT代表什么参见virtio spec1.2。

struct virtio_crypto_config {
    le32 status;			//设备状态,目前只有1个bit有效,指示驱动设备已经准备好
    le32 max_dataqueues;	//dataqueue的最大数量
    le32 crypto_services;   //指示设备提供哪些加密服务,6.8代码中有5种
    /* Detailed algorithms mask */
    le32 cipher_algo_l;		//指示设备支持哪些cipher加密算法
    le32 cipher_algo_h;
    le32 hash_algo;			//指示设备支持哪些HASH算法
    le32 mac_algo_l;		//指示设备支持哪些MAC算法
    le32 mac_algo_h;
    le32 aead_algo;			//指示设备支持哪些AEAD算法
    /* Maximum length of cipher key in bytes */
    le32 max_cipher_key_len;
    /* Maximum length of authenticated key in bytes */
    le32 max_auth_key_len;
    le32 akcipher_algo;			//指示设备支持哪些akcipher算法
    /* Maximum size of each crypto request's content in bytes */
    le64 max_size;
};

2.1.1设备操作

​ virtio-crypto设备需要提供两种交互模式:session和stateless模式,具体需要看virtqueue的feature字段协商结果。通常情况下应该使用session模式,stateless模式要VIRTIO_CRYPTO_F_REVISION_1=1才支持。

2.1.2 control virtqueue

​ 规范要求,crypto设备的最后一条Ring为control ring,用来交互CMD指令。

​ 驱动通过填充struct virtio_crypto_ctrl_request中的各个字段,向设备发起一个控制请求,为具体的加密算法协商一些基础参数。其中协商的具体参数在struct virtio_crypto_op_ctrl_req的第二个字段中,这个字段的长度为56个Byte,具体参数跟选择的算法有关,而算法类型在header中已经指明。

具体算法的req参数如下:

  • virtio_crypto_sym_create_session_req

    对称算法分为两种模式,一种是单独对称,一种是衔接一个HASH算法。

    单独对称加密算法的参数:

    struct virtio_crypto_cipher_session_para{
    	__le32 algo;/*目前支持14种,具体见代码里宏定义*/
    	__le32 keylen;
    	__le32 op; /*1代表加密,2代表解密*/
    	__le32 padding;
    }
    

    衔接一个HASH算法的参数:

    struct virtio_crypto_alg_chain_session_para{
    	__le32 alg_chain_order;/*1代表先HASH再加密,2代表先加密再HASH*/
        __le32 hash_mode;/*1:Plain hash 2:Authenticated hash (mac) 3:Nested hash*/
        struct virtio_crypto_cipher_session_para cipher_param;
        union {
    		struct virtio_crypto_hash_session_para{
                __le32 algo;/*目前支持12种*/
                __le32 hash_result_len;
                __u8 padding[8];
            }hash_param;
    		struct virtio_crypto_mac_session_para{
                __le32 algo;/*目前支持16种*/
                __le32 hash_result_len;
                __le32 auth_key_len;
                __le32 padding;
            }mac_param;
    		__u8 padding[16];
    	} u;
    	__le32 aad_len;/*附加的认证数据的长度(additional authenticated data,AAD)*/
    	__le32 padding;
    }
    
  • virtio_crypto_hash_create_session_req

    见上hash_param。

  • virtio_crypto_mac_create_session_req

    见上mac_param。

  • virtio_crypto_aead_create_session_req

    struct virtio_crypto_aead_session_para {
    	__le32 algo;/*0:NO 1:GCM 2:CCM 3:CHACHA20_POLY1305*/
        __le32 key_len;
        __le32 hash_result_len;
        __le32 add_len;
        __le32 op;/*1:加密 2:解密*/
        __le32 padding;
    }
    
  • virtio_crypto_akcipher_create_session_req

    struct virtio_crypto_akcipher_session_para{
        __le32 algo;/*0:No 1:RSA 2:DSA 3:ECDSA*/
        __le32 keytype;/*1:public 2:private*/
       	union{
            struct virtio_crypto_rsa_session_para{
                __le32 padding_algo;/*0:RAW PADDING 1:PKCS1 PADDING*/
                __le32 hash_algo;/*10种,具体看代码*/
            }rsa;
            struct virtio_crypto_ecdsa_session_para{
                __le32 curve_id;/*6种,具体看代码*/
                __le32 padding;
            }ecdsa;
        }u;
    }
    

2.1.3 data virtqueue

​ 相比于contro virtqueue,data virtqueue要简单很多。下面介绍具体算法的data req参数。

  • virtio_crypto_sym_data_req

    这部分同样分为两个类型,分别是单独的对称加密和与hash结合的。

    struct virtio_crypto_sym_data_req {
    	union {
    		struct virtio_crypto_cipher_data_req{
                __le32 iv_len;
                __le32 src_data_len;
                __le32 dst_data_len;
                __le32 padding;
            };
    		struct virtio_crypto_alg_chain_data_req{
                __le32 iv_len;
                __le32 src_data_len;
                __le32 dst_data_len;
                /* Starting point for cipher processing in source data */
                __le32 cipher_start_src_offset;
                /* Length of the source data that the cipher will be computed on */
                __le32 len_to_cipher;
                /* Starting point for hash processing in source data */
                __le32 hash_start_src_offset;
                /* Length of the source data that the hash will be computed on */
                __le32 len_to_hash;
                /* Length of the additional auth data */
                __le32 aad_len;
                /* Length of the hash result */
                __le32 hash_result_len;
                __le32 reserved;
            };
    		__u8 padding[40];
    	} u;
    	/* See above VIRTIO_CRYPTO_SYM_OP_* */
    	__le32 op_type;
    	__le32 padding;
    };
    
  • virtio_crypto_hash_data_req

    struct virtio_crypto_hash_para {
    	/* length of source data */
    	__le32 src_data_len;
    	/* hash result length */
    	__le32 hash_result_len;
    };
    
  • virtio_crypto_mac_data_req

    同上

  • virtio_crypto_aead_data_req

    struct virtio_crypto_aead_para {
    	/*
    	 * Byte Length of valid IV data pointed to by the below iv_addr
    	 * parameter.
    	 *
    	 * For GCM mode, this is either 12 (for 96-bit IVs) or 16, in which
    	 *   case iv_addr points to J0.
    	 * For CCM mode, this is the length of the nonce, which can be in the
    	 *   range 7 to 13 inclusive.
    	 */
    	__le32 iv_len;
    	/* length of additional auth data */
    	__le32 aad_len;
    	/* length of source data */
    	__le32 src_data_len;
    	/* length of dst data */
    	__le32 dst_data_len;
    };
    
  • virtio_crypto_akcipher_para

    struct virtio_crypto_akcipher_para {
    	__le32 src_data_len;
    	__le32 dst_data_len;
    };
    

2.1.4 virtio_crypto驱动

​ 对于硬件来说,主要就是Sec引擎要能先识别CMD指令(control ring的请求),然后解析并设置加密参数。

​ 对于data queue来说没什么特殊的,就是Src地址和Dst地址而已。

​ 接下来复杂的是驱动如何跟内核的crpytp子系统进行交互,本节将举例说明。

  • probe流程

    virtcrypto_probe
        1.virtio_cread_le读取设备配置空间各个字段
        2.软件设置配置字段到软件句柄
        3.virtcrypto_init_vqs
        	-->virtcrypto_alloc_queues
        	-->virtcrypto_find_vqs
        		-->virtio_find_vqs /* 调用virtio的标准钩子函数,初始化virtqueue */
        		-->crypto_engine_alloc_init_and_set
     			/*为每条data queue初始化crypto引擎,从而可以通过crpyto框架管理queue*/
        		-->tasklet_init/*注册任务完成的回调*/
        	-->virtcrypto_set_affinity/*设置cpu亲和性*/
        4.virtcrypto_start_crypto_engines
        5.virtio_device_ready
        6.virtcrypto_update_status
        	-->virtcrypto_dev_start
        		-->virtio_crypto_skcipher_algs_register 
        			-->crypto_engine_register_skcipher /*遍历算法,依次注册到crypto子系统*/
        		-->virtio_crypto_akcipher_algs_register
        7.注册配置更改的回调vcrypto_config_changed_work
    
  • 提供的算法接口示例

    static struct virtio_crypto_algo virtio_crypto_algs[] = { {
    	.algonum = VIRTIO_CRYPTO_CIPHER_AES_CBC,
    	.service = VIRTIO_CRYPTO_SERVICE_CIPHER,
    	.algo.base = {
    		.base.cra_name		= "cbc(aes)",
    		.base.cra_driver_name	= "virtio_crypto_aes_cbc",
    		.base.cra_priority	= 150,
    		.base.cra_flags		= CRYPTO_ALG_ASYNC |
    					  CRYPTO_ALG_ALLOCATES_MEMORY,
    		.base.cra_blocksize	= AES_BLOCK_SIZE,
    		.base.cra_ctxsize	= sizeof(struct virtio_crypto_skcipher_ctx),
    		.base.cra_module	= THIS_MODULE,
    		.init			= virtio_crypto_skcipher_init,
    		.exit			= virtio_crypto_skcipher_exit,
    		.setkey			= virtio_crypto_skcipher_setkey,
    		.decrypt		= virtio_crypto_skcipher_decrypt,
    		.encrypt		= virtio_crypto_skcipher_encrypt,
    		.min_keysize		= AES_MIN_KEY_SIZE,
    		.max_keysize		= AES_MAX_KEY_SIZE,
    		.ivsize			= AES_BLOCK_SIZE,
    	},
    	.algo.op = {
    		.do_one_request = virtio_crypto_skcipher_crypt_req,
    	},
    } };
    

    下面逐步分析三个实际操作的API

    static int virtio_crypto_skcipher_setkey(struct crypto_skcipher *tfm,
    					 const uint8_t *key,
    					 unsigned int keylen)
    {
        ....
            ret = virtio_crypto_alg_skcipher_init_sessions(ctx, key, keylen);
        ....
    }
    static int virtio_crypto_alg_skcipher_init_sessions(
    		struct virtio_crypto_skcipher_ctx *ctx,
    		const uint8_t *key, unsigned int keylen)
    {
    	....	
    	/* Create encryption session */
    	ret = virtio_crypto_alg_skcipher_init_session(ctx,
    			alg, key, keylen, 1);
    
    	/* Create decryption session */
    	ret = virtio_crypto_alg_skcipher_init_session(ctx,
    			alg, key, keylen, 0);
    	....
    	return 0;
    }
    static int virtio_crypto_alg_skcipher_init_session(
    		struct virtio_crypto_skcipher_ctx *ctx,
    		uint32_t alg, const uint8_t *key,
    		unsigned int keylen,
    		int encrypt)
    {
    	struct scatterlist outhdr, key_sg, inhdr, *sgs[3];
    	struct virtio_crypto *vcrypto = ctx->vcrypto;
    	int op = encrypt ? VIRTIO_CRYPTO_OP_ENCRYPT : VIRTIO_CRYPTO_OP_DECRYPT;
    	int err;
    	unsigned int num_out = 0, num_in = 0;
    	struct virtio_crypto_op_ctrl_req *ctrl;
    	struct virtio_crypto_session_input *input;
    	struct virtio_crypto_sym_create_session_req *sym_create_session;
    	//ctrl_request结构体包含了上面三个结构体和一个completion
        struct virtio_crypto_ctrl_request *vc_ctrl_req;
    
        ........
    
    	/*第一步: 填充 ctrl header字段 */
    	ctrl = &vc_ctrl_req->ctrl;
    	ctrl->header.opcode = cpu_to_le32(VIRTIO_CRYPTO_CIPHER_CREATE_SESSION);
    	ctrl->header.algo = cpu_to_le32(alg);
    	/* Set the default dataqueue id to 0 */
    	ctrl->header.queue_id = 0;
    	/*第二步:填充virtio_crypto_session_input字段,主要用来记录会话状态*/
    	input = &vc_ctrl_req->input;
    	input->status = cpu_to_le32(VIRTIO_CRYPTO_ERR);
    	/*第三步:填充cipher session的字段 */
    	sym_create_session = &ctrl->u.sym_create_session;
    	sym_create_session->op_type = cpu_to_le32(VIRTIO_CRYPTO_SYM_OP_CIPHER);
    	sym_create_session->u.cipher.para.algo = ctrl->header.algo;
    	sym_create_session->u.cipher.para.keylen = cpu_to_le32(keylen);
    	sym_create_session->u.cipher.para.op = cpu_to_le32(op);
    	/*初始化一个sg,把ctrl request先放进去*/
    	sg_init_one(&outhdr, ctrl, sizeof(*ctrl));
    	sgs[num_out++] = &outhdr;
    
    	/*在把key放到sglist里*/
    	sg_init_one(&key_sg, cipher_key, keylen);
    	sgs[num_out++] = &key_sg;
    
    	/* 最后把任务状态的req放进去 */
    	sg_init_one(&inhdr, input, sizeof(*input));
    	sgs[num_out + num_in++] = &inhdr;
    	/*然后提交到vcrypto设备*/
        /*step1 调用virtqueue_add_sgs-->virtqueue_add,提交到control virtqueue*/
        /*step2 调用virtqueue_kick,通知设备*/
        /*step3 wait for compeletion */
    	err = virtio_crypto_ctrl_vq_request(vcrypto, sgs, num_out, num_in, vc_ctrl_req);
    	if (err < 0)
    		goto out;
    	
    	if (le32_to_cpu(input->status) != VIRTIO_CRYPTO_OK) {
    		pr_err("virtio_crypto: Create session failed status: %u\n",
    			le32_to_cpu(input->status));
    		err = -EINVAL;
    		goto out;
    	}
    
    	if (encrypt)
    		ctx->enc_sess_info.session_id = le64_to_cpu(input->session_id);
    	else
    		ctx->dec_sess_info.session_id = le64_to_cpu(input->session_id);
    
    	err = 0;
    out:
    	kfree(vc_ctrl_req);
    	kfree_sensitive(cipher_key);
    	return err;
    }
    
    static int virtio_crypto_skcipher_encrypt(struct skcipher_request *req)
    {
    	struct crypto_skcipher *atfm = crypto_skcipher_reqtfm(req);
    	struct virtio_crypto_skcipher_ctx *ctx = crypto_skcipher_ctx(atfm);
    	struct virtio_crypto_sym_request *vc_sym_req =
    				skcipher_request_ctx(req);
    	struct virtio_crypto_request *vc_req = &vc_sym_req->base;
    	struct virtio_crypto *vcrypto = ctx->vcrypto;
    	/* Use the first data virtqueue as default */
    	struct data_queue *data_vq = &vcrypto->data_vq[0];
    
    	if (!req->cryptlen)
    		return 0;
    	if (req->cryptlen % AES_BLOCK_SIZE)
    		return -EINVAL;
    	/*填充virtio_crypto_sym_request结构体*/
    	vc_req->dataq = data_vq;
    	vc_req->alg_cb = virtio_crypto_dataq_sym_callback;
    	vc_sym_req->skcipher_ctx = ctx;
    	vc_sym_req->skcipher_req = req;
    	vc_sym_req->encrypt = true;
        /*用crypto框架的api发出请求*/
        /*在初始化的时候通过crypto_engine_alloc_init_and_set为每条dataqueue添加了engine*/
    	return crypto_transfer_skcipher_request_to_engine(data_vq->engine, req);
    }
    

    把加密的请求提交给crypto_engine之后,之前注册加密算法的时候配置了alg.op.do_one_request=virtio_crypto_skcipher_crypt_req,因此crypto子系统会去调用这个注册的处理请求的函数,做实际的处理。

    int virtio_crypto_skcipher_crypt_req(
    	struct crypto_engine *engine, void *vreq)
    {
    	struct skcipher_request *req = container_of(vreq, struct skcipher_request, base);
    	struct virtio_crypto_sym_request *vc_sym_req =
    				skcipher_request_ctx(req);
    	struct virtio_crypto_request *vc_req = &vc_sym_req->base;
    	struct data_queue *data_vq = vc_req->dataq;
    	int ret;
    	/*实际的处理函数,具体解析见下*/
    	ret = __virtio_crypto_skcipher_do_req(vc_sym_req, req, data_vq);
    	if (ret < 0)
    		return ret;
    	virtqueue_kick(data_vq->vq);
    
    	return 0;
    }
    static int
    __virtio_crypto_skcipher_do_req(struct virtio_crypto_sym_request *vc_sym_req,
    		struct skcipher_request *req,
    		struct data_queue *data_vq)
    {
    	....
        ....
        ...
    	src_nents = sg_nents_for_len(req->src, req->cryptlen);
    	if (src_nents < 0) {
    		pr_err("Invalid number of src SG.\n");
    		return src_nents;
    	}
    
    	dst_nents = sg_nents(req->dst);
    
    	pr_debug("virtio_crypto: Number of sgs (src_nents: %d, dst_nents: %d)\n",
    			src_nents, dst_nents);
    	/*总sg数量里还要包括一个两个头和一个初始化向量*/
    	/* Why 3?  outhdr + iv + inhdr */
    	sg_total = src_nents + dst_nents + 3;
    	sgs = kcalloc_node(sg_total, sizeof(*sgs), GFP_KERNEL,
    				dev_to_node(&vcrypto->vdev->dev));
    	if (!sgs)
    		return -ENOMEM;
    
    	req_data = kzalloc_node(sizeof(*req_data), GFP_KERNEL,
    				dev_to_node(&vcrypto->vdev->dev));
    	if (!req_data) {
    		kfree(sgs);
    		return -ENOMEM;
    	}
    
    	vc_req->req_data = req_data;
    	vc_sym_req->type = VIRTIO_CRYPTO_SYM_OP_CIPHER;
    	/* Head of operation */
    	if (vc_sym_req->encrypt) {
    		req_data->header.session_id =
    			cpu_to_le64(ctx->enc_sess_info.session_id);
    		req_data->header.opcode =
    			cpu_to_le32(VIRTIO_CRYPTO_CIPHER_ENCRYPT);
    	} else {
    		req_data->header.session_id =
    			cpu_to_le64(ctx->dec_sess_info.session_id);
    		req_data->header.opcode =
    			cpu_to_le32(VIRTIO_CRYPTO_CIPHER_DECRYPT);
    	}
    	req_data->u.sym_req.op_type = cpu_to_le32(VIRTIO_CRYPTO_SYM_OP_CIPHER);
    	req_data->u.sym_req.u.cipher.para.iv_len = cpu_to_le32(ivsize);
    	req_data->u.sym_req.u.cipher.para.src_data_len =
    			cpu_to_le32(req->cryptlen);
    
    	dst_len = virtio_crypto_alg_sg_nents_length(req->dst);
    	if (unlikely(dst_len > U32_MAX)) {
    		pr_err("virtio_crypto: The dst_len is beyond U32_MAX\n");
    		err = -EINVAL;
    		goto free;
    	}
    
    	dst_len = min_t(unsigned int, req->cryptlen, dst_len);
    	pr_debug("virtio_crypto: src_len: %u, dst_len: %llu\n",
    			req->cryptlen, dst_len);
    
    	if (unlikely(req->cryptlen + dst_len + ivsize +
    		sizeof(vc_req->status) > vcrypto->max_size)) {
    		pr_err("virtio_crypto: The length is too big\n");
    		err = -EINVAL;
    		goto free;
    	}
    
    	req_data->u.sym_req.u.cipher.para.dst_data_len =
    			cpu_to_le32((uint32_t)dst_len);
    
    	/* Outhdr */
    	sg_init_one(&outhdr, req_data, sizeof(*req_data));
    	sgs[num_out++] = &outhdr;
    
    	/* IV */
    
    	/*
    	 * Avoid to do DMA from the stack, switch to using
    	 * dynamically-allocated for the IV
    	 */
        /*初始化向量默认为0*/
    	iv = kzalloc_node(ivsize, GFP_ATOMIC,
    				dev_to_node(&vcrypto->vdev->dev));
    	if (!iv) {
    		err = -ENOMEM;
    		goto free;
    	}
    	memcpy(iv, req->iv, ivsize);
    	if (!vc_sym_req->encrypt)
    		scatterwalk_map_and_copy(req->iv, req->src,
    					 req->cryptlen - AES_BLOCK_SIZE,
    					 AES_BLOCK_SIZE, 0);
    
    	sg_init_one(&iv_sg, iv, ivsize);
    	sgs[num_out++] = &iv_sg;
    	vc_sym_req->iv = iv;
    	
    	/* Source data */
    	for (sg = req->src; src_nents; sg = sg_next(sg), src_nents--)
    		sgs[num_out++] = sg;
    
    	/* Destination data */
    	for (sg = req->dst; sg; sg = sg_next(sg))
    		sgs[num_out + num_in++] = sg;
    
    	/* Status */
    	sg_init_one(&status_sg, &vc_req->status, sizeof(vc_req->status));
    	sgs[num_out + num_in++] = &status_sg;
    
    	vc_req->sgs = sgs;
    
    	spin_lock_irqsave(&data_vq->lock, flags);
        /*调用virtqueue_add_sgs添加到virtqueue*/
    	err = virtqueue_add_sgs(data_vq->vq, sgs, num_out,
    				num_in, vc_req, GFP_ATOMIC);
        /*通知dataqueue*/
    	virtqueue_kick(data_vq->vq);
    	spin_unlock_irqrestore(&data_vq->lock, flags);
    	if (unlikely(err < 0))
    		goto free_iv;
    
    	return 0;
    
    free_iv:
    	kfree_sensitive(iv);
    free:
    	kfree_sensitive(req_data);
    	kfree(sgs);
    	return err;
    }
    
    

    当任务通过virtioqueue框架完成后,virtio-crypto驱动负责回收会话:

    static void virtio_crypto_dataq_sym_callback
    		(struct virtio_crypto_request *vc_req, int len)
    {
    	struct virtio_crypto_sym_request *vc_sym_req =
    		container_of(vc_req, struct virtio_crypto_sym_request, base);
    	struct skcipher_request *ablk_req;
    	int error;
    
        /*根据设备写入的status字段做处理*/
    	/* Finish the encrypt or decrypt process */
    	if (vc_sym_req->type == VIRTIO_CRYPTO_SYM_OP_CIPHER) {
    		switch (vc_req->status) {
    		case VIRTIO_CRYPTO_OK:
    			error = 0;
    			break;
    		case VIRTIO_CRYPTO_INVSESS:
    		case VIRTIO_CRYPTO_ERR:
    			error = -EINVAL;
    			break;
    		case VIRTIO_CRYPTO_BADMSG:
    			error = -EBADMSG;
    			break;
    		default:
    			error = -EIO;
    			break;
    		}
    		ablk_req = vc_sym_req->skcipher_req;
    		virtio_crypto_skcipher_finalize_req(vc_sym_req,
    							ablk_req, error);
    	}
    }
    /*释放request资源*/
    static void virtio_crypto_skcipher_finalize_req(
    	struct virtio_crypto_sym_request *vc_sym_req,
    	struct skcipher_request *req,
    	int err)
    {
    	if (vc_sym_req->encrypt)
     /*The scatterwalk_map_and_copy function 在两个散列表之间拷贝,就是把加密后的结果iv拷贝到dst里面.*/
    		scatterwalk_map_and_copy(req->iv, req->dst,
    					 req->cryptlen - AES_BLOCK_SIZE,
    					 AES_BLOCK_SIZE, 0);
    	kfree_sensitive(vc_sym_req->iv);
    	virtcrypto_clear_request(&vc_sym_req->base);
        /*最后让crypto子系统接管*/
    	crypto_finalize_skcipher_request(vc_sym_req->base.dataq->engine,
    					   req, err);
    }
    
posted @ 2024-03-27 10:03  量子诗人  阅读(348)  评论(0编辑  收藏  举报
Live2D