1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
2 // Copyright (c) 2019 Mellanox Technologies.
3 
4 #include "mlx5_core.h"
5 #include "lib/mlx5.h"
6 
mlx5_create_encryption_key(struct mlx5_core_dev * mdev,void * key,u32 sz_bytes,u32 key_type,u32 * p_key_id)7 int mlx5_create_encryption_key(struct mlx5_core_dev *mdev,
8 			       void *key, u32 sz_bytes,
9 			       u32 key_type, u32 *p_key_id)
10 {
11 	u32 in[MLX5_ST_SZ_DW(create_encryption_key_in)] = {};
12 	u32 out[MLX5_ST_SZ_DW(general_obj_out_cmd_hdr)];
13 	u32 sz_bits = sz_bytes * BITS_PER_BYTE;
14 	u8  general_obj_key_size;
15 	u64 general_obj_types;
16 	void *obj, *key_p;
17 	int err;
18 
19 	obj = MLX5_ADDR_OF(create_encryption_key_in, in, encryption_key_object);
20 	key_p = MLX5_ADDR_OF(encryption_key_obj, obj, key);
21 
22 	general_obj_types = MLX5_CAP_GEN_64(mdev, general_obj_types);
23 	if (!(general_obj_types &
24 	      MLX5_HCA_CAP_GENERAL_OBJECT_TYPES_ENCRYPTION_KEY))
25 		return -EINVAL;
26 
27 	switch (sz_bits) {
28 	case 128:
29 		general_obj_key_size =
30 			MLX5_GENERAL_OBJECT_TYPE_ENCRYPTION_KEY_KEY_SIZE_128;
31 		key_p += sz_bytes;
32 		break;
33 	case 256:
34 		general_obj_key_size =
35 			MLX5_GENERAL_OBJECT_TYPE_ENCRYPTION_KEY_KEY_SIZE_256;
36 		break;
37 	default:
38 		return -EINVAL;
39 	}
40 
41 	memcpy(key_p, key, sz_bytes);
42 
43 	MLX5_SET(encryption_key_obj, obj, key_size, general_obj_key_size);
44 	MLX5_SET(encryption_key_obj, obj, key_type, key_type);
45 	MLX5_SET(general_obj_in_cmd_hdr, in, opcode,
46 		 MLX5_CMD_OP_CREATE_GENERAL_OBJECT);
47 	MLX5_SET(general_obj_in_cmd_hdr, in, obj_type,
48 		 MLX5_GENERAL_OBJECT_TYPES_ENCRYPTION_KEY);
49 	MLX5_SET(encryption_key_obj, obj, pd, mdev->mlx5e_res.hw_objs.pdn);
50 
51 	err = mlx5_cmd_exec(mdev, in, sizeof(in), out, sizeof(out));
52 	if (!err)
53 		*p_key_id = MLX5_GET(general_obj_out_cmd_hdr, out, obj_id);
54 
55 	/* avoid leaking key on the stack */
56 	memzero_explicit(in, sizeof(in));
57 
58 	return err;
59 }
60 
mlx5_destroy_encryption_key(struct mlx5_core_dev * mdev,u32 key_id)61 void mlx5_destroy_encryption_key(struct mlx5_core_dev *mdev, u32 key_id)
62 {
63 	u32 in[MLX5_ST_SZ_DW(general_obj_in_cmd_hdr)] = {};
64 	u32 out[MLX5_ST_SZ_DW(general_obj_out_cmd_hdr)];
65 
66 	MLX5_SET(general_obj_in_cmd_hdr, in, opcode,
67 		 MLX5_CMD_OP_DESTROY_GENERAL_OBJECT);
68 	MLX5_SET(general_obj_in_cmd_hdr, in, obj_type,
69 		 MLX5_GENERAL_OBJECT_TYPES_ENCRYPTION_KEY);
70 	MLX5_SET(general_obj_in_cmd_hdr, in, obj_id, key_id);
71 
72 	mlx5_cmd_exec(mdev, in, sizeof(in), out, sizeof(out));
73 }
74