1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (c) 2024 Rockchip Electronics Co., Ltd
4 */
5
6 #include <common.h>
7 #include <malloc.h>
8 #include <rockchip/crypto_mpa.h>
9
rk_mpa_alloc(struct mpa_num ** mpa,void * data,u32 word_size)10 int rk_mpa_alloc(struct mpa_num **mpa, void *data, u32 word_size)
11 {
12 u32 alignment = sizeof(u32);
13 u32 byte_size = word_size * sizeof(u32);
14 struct mpa_num *tmp_mpa = NULL;
15
16 if (!mpa || word_size == 0)
17 return -EINVAL;
18
19 *mpa = NULL;
20
21 tmp_mpa = malloc(sizeof(*tmp_mpa));
22 if (!tmp_mpa)
23 return -ENOMEM;
24
25 memset(tmp_mpa, 0x00, sizeof(*tmp_mpa));
26
27 if (!data || (unsigned long)data % alignment) {
28 tmp_mpa->d = memalign(alignment, byte_size);
29 if (!tmp_mpa->d) {
30 free(tmp_mpa);
31 return -ENOMEM;
32 }
33
34 if (data)
35 memcpy(tmp_mpa->d, data, byte_size);
36 else
37 memset(tmp_mpa->d, 0x00, byte_size);
38
39 tmp_mpa->alloc = MPA_USE_ALLOC;
40 } else {
41 tmp_mpa->d = data;
42 }
43
44 tmp_mpa->size = word_size;
45
46 *mpa = tmp_mpa;
47
48 return 0;
49 }
50
rk_mpa_free(struct mpa_num ** mpa)51 void rk_mpa_free(struct mpa_num **mpa)
52 {
53 struct mpa_num *tmp_mpa = NULL;
54
55 if (mpa && (*mpa)) {
56 tmp_mpa = *mpa;
57 if (tmp_mpa->alloc == MPA_USE_ALLOC)
58 free(tmp_mpa->d);
59
60 free(tmp_mpa);
61 }
62 }
63
64 /*get bignum data length*/
rk_check_size(u32 * data,u32 max_word_size)65 int rk_check_size(u32 *data, u32 max_word_size)
66 {
67 for (int i = (max_word_size - 1); i >= 0; i--) {
68 if (data[i] == 0)
69 continue;
70 else
71 return (i + 1);
72 }
73 return 0;
74 }
75