1 /*
2 * Copyright (c) 2021 Nanjing Xiaoxiongpai Intelligent Technology Co., Ltd.
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 */
15
16 #include "osal.h"
17 #include "osal_io.h"
18 #include "dmac_core.h"
19 #include "los_vm_iomap.h"
20 #include "los_random.h"
21
22 #include "stm32mp1xx_hal.h"
23 #include "stm32mp1xx_hal_rng.h"
24
25 RNG_HandleTypeDef RngHandle;
26
RngInitDev(void)27 static void RngInitDev(void)
28 {
29 RngHandle.Instance = (RNG_TypeDef *)OsalIoRemap(RNG1_BASE, 0x400);
30 /* Initialize the RNG peripheral */
31 if (HAL_RNG_Init(&RngHandle) != HAL_OK) {
32 /* Initialization Error */
33 HDF_LOGE("%s: rng init fail!", __func__);
34 }
35 }
36
RngDeInitDev(void)37 static void RngDeInitDev(void)
38 {
39 /* Initialize the RNG peripheral */
40 if (HAL_RNG_DeInit(&RngHandle) != HAL_OK) {
41 /* Initialization Error */
42 HDF_LOGE("%s: rng deinit fail!", __func__);
43 }
44 }
45
46 /*
47 * random_hw code
48 */
49
RngSupport(void)50 static int RngSupport(void)
51 {
52 return 1;
53 }
54
RngOpen(void)55 static void RngOpen(void)
56 {
57 }
58
RngClose(void)59 static void RngClose(void)
60 {
61 }
62
RngRead(char * buffer,size_t bytes)63 static int RngRead(char *buffer, size_t bytes)
64 {
65 if (HAL_RNG_GenerateRandomNumber(&RngHandle, (uint32_t *)buffer) != HAL_OK) {
66 /* Random number generation error */
67 HDF_LOGE("%s: Random number generation fail!", __func__);
68 }
69 return bytes;
70 }
71
Mp1xxRngInit(void)72 void Mp1xxRngInit(void)
73 {
74 RngInitDev();
75 int ret;
76 RandomOperations r = {
77 .support = RngSupport,
78 .init = RngOpen,
79 .deinit = RngClose,
80 .read = RngRead,
81 };
82 RandomOperationsInit(&r);
83 if ((ret = DevUrandomRegister()) != 0) {
84 HDF_LOGE("[%s]register /dev/urandom failed: %#x", __func__, ret);
85 RngDeInitDev();
86 }
87 }
88
89
90 /*
91 * When kernel decoupled with specific devices,
92 * these code can be removed.
93 */
HiRandomHwInit(void)94 void HiRandomHwInit(void)
95 {
96 RngInitDev();
97 }
HiRandomHwDeinit(void)98 void HiRandomHwDeinit(void)
99 {
100 }
HiRandomHwGetInteger(unsigned * result)101 int HiRandomHwGetInteger(unsigned *result)
102 {
103 return RngRead((char*)result, sizeof(unsigned));
104 }
HiRandomHwGetNumber(char * buffer,size_t buflen)105 int HiRandomHwGetNumber(char *buffer, size_t buflen)
106 {
107 return RngRead(buffer, buflen);
108 }
109