1 /**
2 * Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 * Description: trng kernel API function implementation.
15 *
16 * Create: 2023-05-26
17 */
18
19 #include "kapi_trng.h"
20 #include "kapi_inner.h"
21
22 #include "drv_trng.h"
23 #include "crypto_drv_common.h"
24
25 #define TRNG_COMPAT_ERRNO(err_code) KAPI_COMPAT_ERRNO(ERROR_MODULE_TRNG, err_code)
26
27 crypto_mutex g_trng_mutex;
28
29 #define kapi_trng_mutex_lock() do { \
30 crypto_mutex_lock(&g_trng_mutex); \
31 } while (0)
32
33 #define kapi_trng_mutex_unlock() do { \
34 crypto_mutex_unlock(&g_trng_mutex); \
35 } while (0)
36
kapi_cipher_trng_env_init(td_void)37 td_s32 kapi_cipher_trng_env_init(td_void)
38 {
39 td_s32 ret = TD_SUCCESS;
40
41 ret = drv_cipher_trng_init();
42 if (ret != TD_SUCCESS) {
43 crypto_log_err("drv_cipher_trng_init failed, ret is 0x%x\n", ret);
44 return ret;
45 }
46
47 ret = crypto_mutex_init(&g_trng_mutex);
48 if (ret != TD_SUCCESS) {
49 crypto_log_err("crypto_mutex_init failed\n");
50 goto error_trng_deinit;
51 }
52
53 error_trng_deinit:
54 return ret;
55 }
56
kapi_cipher_trng_env_deinit(td_void)57 td_s32 kapi_cipher_trng_env_deinit(td_void)
58 {
59 crypto_mutex_destroy(&g_trng_mutex);
60 drv_cipher_trng_deinit();
61 return TD_SUCCESS;
62 }
63
inner_kapi_trng_lock(td_void)64 td_void inner_kapi_trng_lock(td_void)
65 {
66 kapi_trng_mutex_lock();
67 }
68
inner_kapi_trng_unlock(td_void)69 td_void inner_kapi_trng_unlock(td_void)
70 {
71 kapi_trng_mutex_unlock();
72 }
73
kapi_cipher_trng_get_random(td_u32 * randnum)74 td_s32 kapi_cipher_trng_get_random(td_u32 *randnum)
75 {
76 td_s32 ret = TD_FAILURE;
77 crypto_chk_return(randnum == TD_NULL, TRNG_COMPAT_ERRNO(ERROR_PARAM_IS_NULL), "randnum is NULL\n");
78 ret = crypto_get_multi_random(CRYPTO_WORD_WIDTH, (td_u8 *)randnum);
79 return ret;
80 }
81
kapi_cipher_trng_get_multi_random(td_u32 size,td_u8 * randnum)82 td_s32 kapi_cipher_trng_get_multi_random(td_u32 size, td_u8 *randnum)
83 {
84 td_s32 ret = TD_FAILURE;
85 crypto_chk_return(randnum == TD_NULL, TRNG_COMPAT_ERRNO(ERROR_PARAM_IS_NULL), "randnum is NULL\n");
86 ret = crypto_get_multi_random(size, randnum);
87 return ret;
88 }
89 CRYPTO_EXPORT_SYMBOL(kapi_cipher_trng_get_random);